Skip to main content

sqlite_graphrag/commands/
ingest.rs

1//! Handler for the `ingest` CLI subcommand.
2//!
3//! Bulk-ingests every file under a directory that matches a glob pattern.
4//! Each matched file is persisted as a separate memory using the same
5//! validation, chunking, embedding and persistence pipeline as `remember`,
6//! but executed in-process so the ONNX model is loaded only once per
7//! invocation. This is the v1.0.32 Onda 4B (finding A2) refactor that
8//! replaced a fork-spawn-per-file pipeline (every file paid the ~17s ONNX
9//! cold-start cost) with an in-process loop reusing the warm embedder
10//! (daemon when available, in-process `Embedder::new` otherwise).
11//!
12//! Memory names are derived from file basenames (kebab-case, lowercase,
13//! ASCII alphanumerics + hyphens). Output is line-delimited JSON: one
14//! object per processed file (success or error), followed by a final
15//! summary object. Designed for streaming consumption by agents.
16//!
17//! ## Incremental pipeline (v1.0.43)
18//!
19//! Phase A runs on a rayon thread pool (size = `--ingest-parallelism`):
20//! read + chunk + embed + NER per file. Results are sent immediately via a
21//! bounded `mpsc::sync_channel` to Phase B so persistence starts as soon
22//! as the first file completes — no waiting for all files to finish Phase A.
23//!
24//! Phase B runs on the main thread: receives staged files from the channel,
25//! writes to SQLite per-file (WAL absorbs individual commits), and emits
26//! NDJSON progress events to stderr as each file is persisted. `Connection`
27//! is not `Sync` so it never crosses thread boundaries.
28//!
29//! This fixes B1: with the old 2-phase design, a 50-file corpus with 27s/file
30//! NER would spend ~22min in Phase A alone, exceeding the user's 900s timeout
31//! before Phase B (and any DB writes) could begin. With this pipeline, the
32//! first file is committed within seconds of starting.
33
34use crate::chunking;
35use crate::cli::MemoryType;
36use crate::entity_type::EntityType;
37use crate::errors::AppError;
38use crate::i18n::errors_msg;
39use crate::output::{self, JsonOutputFormat};
40use crate::paths::AppPaths;
41use crate::storage::chunks as storage_chunks;
42use crate::storage::connection::{ensure_db_ready, open_rw};
43use crate::storage::entities::{NewEntity, NewRelationship};
44use crate::storage::memories::NewMemory;
45use crate::storage::{entities, memories, urls as storage_urls, versions};
46use rayon::prelude::*;
47use rusqlite::Connection;
48use serde::Serialize;
49use std::collections::BTreeSet;
50use std::path::{Path, PathBuf};
51use std::sync::mpsc;
52use unicode_normalization::UnicodeNormalization;
53
54use crate::constants::DERIVED_NAME_MAX_LEN;
55
56/// Hard cap on the numeric suffix appended for collision resolution. If 1000
57/// candidates collide we surface an error rather than loop forever.
58const MAX_NAME_COLLISION_SUFFIX: usize = 1000;
59
60#[derive(clap::Args)]
61#[command(after_long_help = "EXAMPLES:\n  \
62    # Ingest every Markdown file under ./docs as `document` memories\n  \
63    sqlite-graphrag ingest ./docs --type document\n\n  \
64    # Ingest .txt files recursively under ./notes\n  \
65    sqlite-graphrag ingest ./notes --type note --pattern '*.txt' --recursive\n\n  \
66    # Enable automatic URL extraction (URL-regex only since v1.0.79)\n  \
67    sqlite-graphrag ingest ./big-corpus --type reference --enable-ner\n\n  \
68    # Preview file-to-name mapping without ingesting\n  \
69    sqlite-graphrag ingest ./docs --dry-run\n\n  \
70    # LLM-curated extraction via Claude Code CLI\n  \
71    sqlite-graphrag ingest ./docs --mode claude-code --recursive --json\n\n  \
72    # Resume interrupted claude-code ingest\n  \
73    sqlite-graphrag ingest ./docs --mode claude-code --resume --json\n\n  \
74    # Claude Code with budget cap and custom timeout\n  \
75    sqlite-graphrag ingest ./docs --mode claude-code --max-cost-usd 5.00 --claude-timeout 600 --json\n\n  \
76AUTHENTICATION:\n  \
77    --mode claude-code: Uses existing Claude Code authentication.\n  \
78      OAuth (Pro/Max/Team): works automatically from ~/.claude/.credentials.json\n  \
79      API key: set ANTHROPIC_API_KEY for faster startup (optional)\n\n  \
80    --mode codex: Uses existing Codex CLI authentication.\n  \
81      Device auth: run `codex auth login` first\n  \
82      API key: set OPENAI_API_KEY (optional)\n\n  \
83NOTES:\n  \
84    Each file becomes a separate memory. Names derive from file basenames\n  \
85    (kebab-case, lowercase, ASCII). Output is NDJSON: one JSON object per file,\n  \
86    followed by a final summary line with counts. Per-file errors are reported\n  \
87    inline and processing continues unless --fail-fast is set.")]
88pub struct IngestArgs {
89    /// Directory containing files to ingest.
90    #[arg(
91        value_name = "DIR",
92        help = "Directory to ingest recursively (each matching file becomes a memory)"
93    )]
94    pub dir: PathBuf,
95
96    /// Memory type stored in `memories.type` for every ingested file. Defaults to `document`.
97    #[arg(long, value_enum, default_value_t = MemoryType::Document)]
98    pub r#type: MemoryType,
99
100    /// Glob pattern matched against file basenames (default: `*.md`). Supports
101    /// `*.<ext>`, `<prefix>*`, and exact filename match.
102    #[arg(long, default_value = "*.md")]
103    pub pattern: String,
104
105    /// Recurse into subdirectories.
106    #[arg(long, default_value_t = false)]
107    pub recursive: bool,
108
109    #[arg(
110        long,
111        env = "SQLITE_GRAPHRAG_ENABLE_NER",
112        value_parser = crate::parsers::parse_bool_flexible,
113        action = clap::ArgAction::Set,
114        num_args = 0..=1,
115        default_missing_value = "true",
116        default_value = "false",
117        help = "Enable automatic URL-regex extraction (the GLiNER NER pipeline was removed in v1.0.79)"
118    )]
119    pub enable_ner: bool,
120    #[arg(
121        long,
122        env = "SQLITE_GRAPHRAG_GLINER_VARIANT",
123        default_value = "fp32",
124        help = "DEPRECATED: no effect since v1.0.79 (the GLiNER pipeline was removed); accepted for compatibility only"
125    )]
126    pub gliner_variant: String,
127
128    /// Deprecated: NER is now disabled by default. Kept for backwards compatibility.
129    #[arg(long, default_value_t = false, hide = true)]
130    pub skip_extraction: bool,
131
132    /// Stop on first per-file error instead of continuing with the next file.
133    #[arg(long, default_value_t = false)]
134    pub fail_fast: bool,
135
136    /// Preview file-to-name mapping without loading model or persisting.
137    #[arg(long, default_value_t = false)]
138    pub dry_run: bool,
139
140    /// Maximum number of files to ingest (safety cap to prevent runaway ingestion).
141    #[arg(long, default_value_t = 10_000)]
142    pub max_files: usize,
143
144    /// Namespace for the ingested memories.
145    #[arg(long)]
146    pub namespace: Option<String>,
147
148    /// Database path. Falls back to `SQLITE_GRAPHRAG_DB_PATH`, then `./graphrag.sqlite`.
149    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
150    pub db: Option<String>,
151
152    #[arg(long, value_enum, default_value_t = JsonOutputFormat::Json)]
153    pub format: JsonOutputFormat,
154
155    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
156    pub json: bool,
157
158    /// Number of files to extract+embed in parallel; default = max(1, cpus/2).min(4).
159    #[arg(
160        long,
161        help = "Number of files to extract+embed in parallel; default = max(1, cpus/2).min(4)"
162    )]
163    pub ingest_parallelism: Option<usize>,
164
165    /// Force single-threaded ingest to reduce RSS pressure.
166    ///
167    /// Equivalent to `--ingest-parallelism 1`, takes precedence over any
168    /// explicit value. Recommended for environments with <4 GB available
169    /// RAM or container/cgroup constraints. Trade-off: 3-4x longer wall
170    /// time. Also honored via `SQLITE_GRAPHRAG_LOW_MEMORY=1` env var
171    /// (CLI flag has higher precedence than the env var).
172    #[arg(
173        long,
174        default_value_t = false,
175        help = "Forces single-threaded ingest (--ingest-parallelism 1) to reduce RSS pressure. \
176                Recommended for environments with <4 GB available RAM or container/cgroup \
177                constraints. Trade-off: 3-4x longer wall time. Also honored via \
178                SQLITE_GRAPHRAG_LOW_MEMORY=1 env var."
179    )]
180    pub low_memory: bool,
181
182    /// Maximum process RSS in MiB; abort if exceeded during embedding.
183    #[arg(long, default_value_t = crate::constants::DEFAULT_MAX_RSS_MB,
184          help = "Maximum process RSS in MiB; abort if exceeded during embedding (default: 8192)")]
185    pub max_rss_mb: u64,
186
187    /// G42/S3 (v1.0.79): maximum simultaneous LLM embedding subprocesses
188    /// PER FILE. Multiplies with --ingest-parallelism (files staged
189    /// concurrently), hence the conservative default of 2. The effective
190    /// value is further bounded by CPU count and available RAM.
191    #[arg(long, default_value_t = 2, value_name = "N",
192          value_parser = clap::value_parser!(u64).range(1..=32),
193          help = "Maximum simultaneous LLM embedding subprocesses per file (default: 2, clamp [1,32])")]
194    pub llm_parallelism: u64,
195
196    /// Maximum character length for derived memory names from file basenames.
197    ///
198    /// Overrides the compile-time `DERIVED_NAME_MAX_LEN` constant (default 60).
199    /// Shorter values leave more headroom for collision suffix resolution.
200    #[arg(long, default_value_t = crate::constants::DERIVED_NAME_MAX_LEN,
201          help = "Maximum length for derived memory names (default: 60)")]
202    pub max_name_length: usize,
203
204    /// Extraction mode: `none` (body-only, default), `claude-code`/`codex` (LLM-curated), or `gliner` (DEPRECATED: URL-regex only since v1.0.79).
205    #[arg(long, value_enum, default_value_t = IngestMode::None)]
206    pub mode: IngestMode,
207
208    /// Explicit path to the Claude Code binary (only with --mode claude-code).
209    #[arg(long, env = "SQLITE_GRAPHRAG_CLAUDE_BINARY")]
210    pub claude_binary: Option<std::path::PathBuf>,
211
212    /// Model override for Claude Code extraction (e.g. claude-sonnet-4-6).
213    #[arg(long)]
214    pub claude_model: Option<String>,
215
216    /// Resume a previously interrupted claude-code ingest from the queue DB.
217    #[arg(long, default_value_t = false)]
218    pub resume: bool,
219
220    /// Retry only failed files from a previous claude-code ingest.
221    #[arg(long, default_value_t = false)]
222    pub retry_failed: bool,
223
224    /// Keep the queue DB (.ingest-queue.sqlite) after completion.
225    #[arg(long, default_value_t = false)]
226    pub keep_queue: bool,
227
228    /// Custom path for the claude-code ingest queue database.
229    #[arg(long, default_value = ".ingest-queue.sqlite")]
230    pub queue_db: String,
231
232    /// Initial wait time in seconds when rate-limited (only with --mode claude-code).
233    #[arg(long, default_value_t = 60)]
234    pub rate_limit_wait: u64,
235
236    /// Maximum cumulative cost in USD before aborting (only with --mode claude-code).
237    #[arg(long)]
238    pub max_cost_usd: Option<f64>,
239
240    /// Timeout in seconds for each claude -p invocation (only with --mode claude-code).
241    #[arg(
242        long,
243        default_value_t = 300,
244        help = "Timeout in seconds for each claude -p invocation (default: 300)"
245    )]
246    pub claude_timeout: u64,
247
248    /// Explicit path to the Codex CLI binary (only with --mode codex).
249    #[arg(
250        long,
251        env = "SQLITE_GRAPHRAG_CODEX_BINARY",
252        help = "Explicit path to the Codex CLI binary (only with --mode codex)"
253    )]
254    pub codex_binary: Option<PathBuf>,
255
256    /// Model override for Codex extraction (e.g. o4-mini, gpt-5.1-codex).
257    #[arg(
258        long,
259        help = "Model override for Codex extraction (e.g. o4-mini, gpt-5.1-codex)"
260    )]
261    pub codex_model: Option<String>,
262
263    /// Timeout in seconds for each codex exec invocation.
264    #[arg(
265        long,
266        default_value_t = 300,
267        help = "Timeout in seconds for each codex exec invocation (default: 300)"
268    )]
269    pub codex_timeout: u64,
270
271    /// G30: poll for the job singleton every second for up to N seconds
272    /// when another invocation holds the lock. Default: 0 (fail fast).
273    #[arg(long, value_name = "SECONDS")]
274    pub wait_job_singleton: Option<u64>,
275
276    /// G30: force acquisition of the singleton lock by removing a stale
277    /// lock file from a previously crashed invocation.
278    #[arg(long, default_value_t = false)]
279    pub force_job_singleton: bool,
280}
281
282/// Extraction mode for the ingest pipeline.
283#[derive(Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
284pub enum IngestMode {
285    /// Body-only ingestion without entity/relationship extraction (default).
286    None,
287    /// DEPRECATED: URL-regex extraction only since v1.0.79 (the GLiNER pipeline was removed; requires --enable-ner).
288    Gliner,
289    /// LLM-curated extraction via locally installed Claude Code CLI.
290    ClaudeCode,
291    /// LLM-curated extraction via locally installed OpenAI Codex CLI.
292    Codex,
293}
294
295/// Returns true when the `SQLITE_GRAPHRAG_LOW_MEMORY` env var is set to a
296/// truthy value (`1`, `true`, `yes`, `on`, case-insensitive). Empty or unset
297/// values evaluate to false. Unrecognized non-empty values emit a
298/// `tracing::warn!` and evaluate to false.
299fn env_low_memory_enabled() -> bool {
300    match std::env::var("SQLITE_GRAPHRAG_LOW_MEMORY") {
301        Ok(v) if v.is_empty() => false,
302        Ok(v) => match v.to_lowercase().as_str() {
303            "1" | "true" | "yes" | "on" => true,
304            "0" | "false" | "no" | "off" => false,
305            other => {
306                tracing::warn!(
307                    target: "ingest",
308                    value = %other,
309                    "SQLITE_GRAPHRAG_LOW_MEMORY value not recognized; treating as disabled"
310                );
311                false
312            }
313        },
314        Err(_) => false,
315    }
316}
317
318/// Resolves the effective ingest parallelism honoring `--low-memory` and the
319/// `SQLITE_GRAPHRAG_LOW_MEMORY` env var.
320///
321/// Precedence:
322/// 1. `--low-memory` CLI flag forces parallelism = 1.
323/// 2. `SQLITE_GRAPHRAG_LOW_MEMORY=1` env var forces parallelism = 1.
324/// 3. Explicit `--ingest-parallelism N` (when low-memory is off).
325/// 4. Default heuristic `(cpus/2).clamp(1, 4)`.
326///
327/// When low-memory wins and the user also passed `--ingest-parallelism N>1`,
328/// emits a `tracing::warn!` advertising the override.
329fn resolve_parallelism(low_memory_flag: bool, ingest_parallelism: Option<usize>) -> usize {
330    let env_flag = env_low_memory_enabled();
331    let low_memory = low_memory_flag || env_flag;
332
333    if low_memory {
334        if let Some(n) = ingest_parallelism {
335            if n > 1 {
336                tracing::warn!(
337                    target: "ingest",
338                    requested = n,
339                    "--ingest-parallelism overridden by --low-memory; using 1"
340                );
341            }
342        }
343        if low_memory_flag {
344            tracing::info!(
345                target: "ingest",
346                source = "flag",
347                "low-memory mode enabled: forcing --ingest-parallelism 1"
348            );
349        } else {
350            tracing::info!(
351                target: "ingest",
352                source = "env",
353                "low-memory mode enabled via SQLITE_GRAPHRAG_LOW_MEMORY: forcing --ingest-parallelism 1"
354            );
355        }
356        return 1;
357    }
358
359    ingest_parallelism
360        .unwrap_or_else(|| {
361            std::thread::available_parallelism()
362                .map(|v| v.get() / 2)
363                .unwrap_or(1)
364                .clamp(1, 4)
365        })
366        .max(1)
367}
368
369#[derive(Serialize)]
370struct IngestFileEvent<'a> {
371    file: &'a str,
372    name: &'a str,
373    status: &'a str,
374    /// True when the derived name was truncated to fit `DERIVED_NAME_MAX_LEN`. False otherwise.
375    truncated: bool,
376    /// Original derived name before truncation; only present when `truncated=true`.
377    #[serde(skip_serializing_if = "Option::is_none")]
378    original_name: Option<String>,
379    /// Original file basename (without extension); only present when it differs from `name`.
380    #[serde(skip_serializing_if = "Option::is_none")]
381    original_filename: Option<&'a str>,
382    #[serde(skip_serializing_if = "Option::is_none")]
383    error: Option<String>,
384    #[serde(skip_serializing_if = "Option::is_none")]
385    memory_id: Option<i64>,
386    #[serde(skip_serializing_if = "Option::is_none")]
387    action: Option<String>,
388    /// Byte length of the body ingested; 0 when not yet read (e.g. skip or dry-run events).
389    body_length: usize,
390}
391
392#[derive(Serialize)]
393struct IngestSummary {
394    summary: bool,
395    dir: String,
396    pattern: String,
397    recursive: bool,
398    files_total: usize,
399    files_succeeded: usize,
400    files_failed: usize,
401    files_skipped: usize,
402    elapsed_ms: u64,
403}
404
405/// Outcome of a successful per-file ingest, used to build the NDJSON event.
406struct FileSuccess {
407    memory_id: i64,
408    action: String,
409    body_length: usize,
410}
411
412/// NDJSON progress event emitted to stderr after each file completes Phase A.
413/// Schema version 1; consumers should check `schema_version` before parsing.
414#[derive(Serialize)]
415struct StageProgressEvent<'a> {
416    schema_version: u8,
417    event: &'a str,
418    path: &'a str,
419    ms: u64,
420    entities: usize,
421    relationships: usize,
422}
423
424/// All artefacts pre-computed by Phase A (CPU-bound, runs on rayon thread pool).
425/// Phase B persists these to SQLite on the main thread in submission order.
426struct StagedFile {
427    body: String,
428    body_hash: String,
429    snippet: String,
430    name: String,
431    description: String,
432    embedding: Vec<f32>,
433    chunk_embeddings: Option<Vec<Vec<f32>>>,
434    chunks_info: Vec<crate::chunking::Chunk>,
435    entities: Vec<NewEntity>,
436    relationships: Vec<NewRelationship>,
437    entity_embeddings: Vec<Vec<f32>>,
438    urls: Vec<crate::extraction::ExtractedUrl>,
439}
440
441/// Phase A worker: reads, chunks, embeds and extracts NER for one file.
442/// Never touches the database — safe to run on any rayon thread.
443// G42/S3 added `llm_parallelism` as the 8th parameter; grouping the
444// stage knobs into a struct is a wider refactor than the surgical
445// scope of v1.0.79 allows.
446#[allow(clippy::too_many_arguments)]
447fn stage_file(
448    _idx: usize,
449    path: &Path,
450    name: &str,
451    paths: &AppPaths,
452    enable_ner: bool,
453    gliner_variant: crate::extraction::GlinerVariant,
454    max_rss_mb: u64,
455    llm_parallelism: usize,
456) -> Result<StagedFile, AppError> {
457    use crate::constants::*;
458
459    if name.len() > MAX_MEMORY_NAME_LEN {
460        return Err(AppError::LimitExceeded(
461            crate::i18n::validation::name_length(MAX_MEMORY_NAME_LEN),
462        ));
463    }
464    if name.starts_with("__") {
465        return Err(AppError::Validation(
466            crate::i18n::validation::reserved_name(),
467        ));
468    }
469    {
470        let slug_re = crate::constants::name_slug_regex();
471        if !slug_re.is_match(name) {
472            return Err(AppError::Validation(crate::i18n::validation::name_kebab(
473                name,
474            )));
475        }
476    }
477
478    let file_size = std::fs::metadata(path).map_err(AppError::Io)?.len();
479    if file_size > MAX_MEMORY_BODY_LEN as u64 {
480        return Err(AppError::LimitExceeded(
481            crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
482        ));
483    }
484    let raw_body = std::fs::read_to_string(path).map_err(AppError::Io)?;
485    if raw_body.len() > MAX_MEMORY_BODY_LEN {
486        return Err(AppError::LimitExceeded(
487            crate::i18n::validation::body_exceeds(MAX_MEMORY_BODY_LEN),
488        ));
489    }
490    if raw_body.trim().is_empty() {
491        return Err(AppError::Validation(crate::i18n::validation::empty_body()));
492    }
493
494    let description = format!("ingested from {}", path.display());
495    if description.len() > MAX_MEMORY_DESCRIPTION_LEN {
496        return Err(AppError::Validation(
497            crate::i18n::validation::description_exceeds(MAX_MEMORY_DESCRIPTION_LEN),
498        ));
499    }
500
501    let mut extracted_entities: Vec<NewEntity> = Vec::with_capacity(30);
502    let mut extracted_relationships: Vec<NewRelationship> = Vec::with_capacity(50);
503    let mut extracted_urls: Vec<crate::extraction::ExtractedUrl> = Vec::with_capacity(4);
504    if enable_ner {
505        match crate::extraction::extract_graph_auto(&raw_body, paths, gliner_variant) {
506            Ok(extracted) => {
507                extracted_urls = extracted.urls;
508                // v1.0.76: ExtractionResult.entities is now
509                // Vec<ExtractedEntity>, not Vec<NewEntity>. Convert
510                // via name + type only; start/end offsets are not
511                // carried forward into the storage layer.
512                extracted_entities = extracted
513                    .entities
514                    .into_iter()
515                    .map(|e| NewEntity {
516                        name: e.name,
517                        entity_type: crate::entity_type::EntityType::Concept,
518                        description: None,
519                    })
520                    .collect();
521                // v1.0.76: relationships are no longer in the
522                // ExtractionResult struct; the LLM backend returns
523                // them in its own payload. The default build is
524                // URL-only extraction.
525                extracted_relationships.clear();
526
527                if extracted_entities.len() > max_entities_per_memory() {
528                    extracted_entities.truncate(max_entities_per_memory());
529                }
530                if extracted_relationships.len() > max_relationships_per_memory() {
531                    extracted_relationships.truncate(max_relationships_per_memory());
532                }
533            }
534            Err(e) => {
535                tracing::warn!(
536                    target: "ingest",
537                    file = %path.display(),
538                    "auto-extraction failed (graceful degradation): {e:#}"
539                );
540            }
541        }
542    }
543
544    for rel in &mut extracted_relationships {
545        rel.relation = crate::parsers::normalize_relation(&rel.relation);
546        if let Err(e) = crate::parsers::validate_relation_format(&rel.relation) {
547            return Err(AppError::Validation(format!(
548                "{e} for relationship '{}' -> '{}'",
549                rel.source, rel.target
550            )));
551        }
552        crate::parsers::warn_if_non_canonical(&rel.relation);
553        if !(0.0..=1.0).contains(&rel.strength) {
554            return Err(AppError::Validation(format!(
555                "invalid strength {} for relationship '{}' -> '{}'; expected value in [0.0, 1.0]",
556                rel.strength, rel.source, rel.target
557            )));
558        }
559    }
560
561    let body_hash = blake3::hash(raw_body.as_bytes()).to_hex().to_string();
562    let snippet: String = raw_body.chars().take(200).collect();
563
564    let chunks_info = chunking::split_into_chunks_hierarchical(&raw_body);
565    if chunks_info.len() > REMEMBER_MAX_SAFE_MULTI_CHUNKS {
566        return Err(AppError::LimitExceeded(format!(
567            "document produces {} chunks; current safe operational limit is {} chunks; split the document before using remember",
568            chunks_info.len(),
569            REMEMBER_MAX_SAFE_MULTI_CHUNKS
570        )));
571    }
572
573    let mut chunk_embeddings_opt: Option<Vec<Vec<f32>>> = None;
574    let embedding = if chunks_info.len() == 1 {
575        crate::embedder::embed_passage_local(&paths.models, &raw_body)?
576    } else {
577        // G42/S2+S3 (v1.0.79): batched bounded fan-out replaces the
578        // serial per-chunk subprocess loop.
579        let chunk_texts: Vec<String> = chunks_info
580            .iter()
581            .map(|c| chunking::chunk_text(&raw_body, c).to_string())
582            .collect();
583        if let Some(rss) = crate::memory_guard::current_process_memory_mb() {
584            if rss > max_rss_mb {
585                tracing::error!(
586                    target: "ingest",
587                    rss_mb = rss,
588                    max_rss_mb = max_rss_mb,
589                    file = %path.display(),
590                    "RSS exceeded --max-rss-mb threshold; aborting to prevent system instability"
591                );
592                return Err(AppError::LowMemory {
593                    available_mb: crate::memory_guard::available_memory_mb(),
594                    required_mb: max_rss_mb,
595                });
596            }
597        }
598        let chunk_embeddings = crate::embedder::embed_passages_parallel_local(
599            &paths.models,
600            &chunk_texts,
601            llm_parallelism,
602            crate::embedder::chunk_embed_batch_size(),
603        )?;
604        let aggregated = chunking::aggregate_embeddings(&chunk_embeddings);
605        chunk_embeddings_opt = Some(chunk_embeddings);
606        aggregated
607    };
608
609    // G42/S2+A4 (v1.0.79): entity names use the short-text batch profile.
610    let entity_texts: Vec<String> = extracted_entities
611        .iter()
612        .map(|entity| match &entity.description {
613            Some(desc) => format!("{} {}", entity.name, desc),
614            None => entity.name.clone(),
615        })
616        .collect();
617    // G56 (v1.0.80): ingest reuses canonical entity names across many
618    // memories (e.g. `sqlite-graphrag`, `claude-code`); the in-process
619    // cache collapses the repeated LLM calls into one per unique text.
620    let (entity_embeddings, embed_cache_stats) =
621        crate::embedder::embed_entity_texts_cached(&paths.models, &entity_texts, llm_parallelism)?;
622    if embed_cache_stats.hits > 0 {
623        tracing::debug!(
624            hits = embed_cache_stats.hits,
625            misses = embed_cache_stats.misses,
626            requested = embed_cache_stats.requested,
627            "G56: entity embed cache hit (ingest)"
628        );
629    }
630
631    Ok(StagedFile {
632        body: raw_body,
633        body_hash,
634        snippet,
635        name: name.to_string(),
636        description,
637        embedding,
638        chunk_embeddings: chunk_embeddings_opt,
639        chunks_info,
640        entities: extracted_entities,
641        relationships: extracted_relationships,
642        entity_embeddings,
643        urls: extracted_urls,
644    })
645}
646
647/// Phase B: persists one `StagedFile` to the database on the main thread.
648fn persist_staged(
649    conn: &mut Connection,
650    namespace: &str,
651    memory_type: &str,
652    staged: StagedFile,
653) -> Result<FileSuccess, AppError> {
654    {
655        let active_count: u32 = conn.query_row(
656            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
657            [],
658            |r| r.get::<_, i64>(0).map(|v| v as u32),
659        )?;
660        let ns_exists: bool = conn.query_row(
661            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
662            rusqlite::params![namespace],
663            |r| r.get::<_, i64>(0).map(|v| v > 0),
664        )?;
665        if !ns_exists && active_count >= crate::constants::MAX_NAMESPACES_ACTIVE {
666            return Err(AppError::NamespaceError(format!(
667                "active namespace limit of {} exceeded while creating '{namespace}'",
668                crate::constants::MAX_NAMESPACES_ACTIVE
669            )));
670        }
671    }
672
673    let existing_memory = memories::find_by_name(conn, namespace, &staged.name)?;
674    if existing_memory.is_some() {
675        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
676            &staged.name,
677            namespace,
678        )));
679    }
680    let duplicate_hash_id = memories::find_by_hash(conn, namespace, &staged.body_hash)?;
681
682    let new_memory = NewMemory {
683        namespace: namespace.to_string(),
684        name: staged.name.clone(),
685        memory_type: memory_type.to_string(),
686        description: staged.description.clone(),
687        body: staged.body,
688        body_hash: staged.body_hash,
689        session_id: None,
690        source: "agent".to_string(),
691        metadata: serde_json::json!({}),
692    };
693
694    if let Some(hash_id) = duplicate_hash_id {
695        tracing::debug!(
696            target: "ingest",
697            duplicate_memory_id = hash_id,
698            "identical body already exists; persisting a new memory anyway"
699        );
700    }
701
702    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
703
704    let memory_id = memories::insert(&tx, &new_memory)?;
705    versions::insert_version(
706        &tx,
707        memory_id,
708        1,
709        &staged.name,
710        memory_type,
711        &staged.description,
712        &new_memory.body,
713        &serde_json::to_string(&new_memory.metadata)?,
714        None,
715        "create",
716    )?;
717    memories::upsert_vec(
718        &tx,
719        memory_id,
720        namespace,
721        memory_type,
722        &staged.embedding,
723        &staged.name,
724        &staged.snippet,
725    )?;
726
727    if staged.chunks_info.len() > 1 {
728        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &staged.chunks_info)?;
729        let chunk_embeddings = staged.chunk_embeddings.ok_or_else(|| {
730            AppError::Internal(anyhow::anyhow!(
731                "missing chunk embeddings cache on multi-chunk ingest path"
732            ))
733        })?;
734        for (i, emb) in chunk_embeddings.iter().enumerate() {
735            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
736        }
737    }
738
739    if !staged.entities.is_empty() || !staged.relationships.is_empty() {
740        for (idx, entity) in staged.entities.iter().enumerate() {
741            let entity_id = entities::upsert_entity(&tx, namespace, entity)?;
742            let entity_embedding = &staged.entity_embeddings[idx];
743            entities::upsert_entity_vec(
744                &tx,
745                entity_id,
746                namespace,
747                entity.entity_type,
748                entity_embedding,
749                &entity.name,
750            )?;
751            entities::link_memory_entity(&tx, memory_id, entity_id)?;
752            entities::increment_degree(&tx, entity_id)?;
753        }
754        let entity_types: std::collections::HashMap<&str, EntityType> = staged
755            .entities
756            .iter()
757            .map(|entity| (entity.name.as_str(), entity.entity_type))
758            .collect();
759        for rel in &staged.relationships {
760            let source_entity = NewEntity {
761                name: rel.source.clone(),
762                entity_type: entity_types
763                    .get(rel.source.as_str())
764                    .copied()
765                    .unwrap_or(EntityType::Concept),
766                description: None,
767            };
768            let target_entity = NewEntity {
769                name: rel.target.clone(),
770                entity_type: entity_types
771                    .get(rel.target.as_str())
772                    .copied()
773                    .unwrap_or(EntityType::Concept),
774                description: None,
775            };
776            let source_id = entities::upsert_entity(&tx, namespace, &source_entity)?;
777            let target_id = entities::upsert_entity(&tx, namespace, &target_entity)?;
778            let rel_id = entities::upsert_relationship(&tx, namespace, source_id, target_id, rel)?;
779            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
780        }
781    }
782
783    tx.commit()?;
784
785    if !staged.urls.is_empty() {
786        let url_entries: Vec<storage_urls::MemoryUrl> = staged
787            .urls
788            .into_iter()
789            .map(|u| storage_urls::MemoryUrl {
790                url: u.url,
791                offset: Some(u.start as i64),
792            })
793            .collect();
794        let _ = storage_urls::insert_urls(conn, memory_id, &url_entries);
795    }
796
797    Ok(FileSuccess {
798        memory_id,
799        action: "created".to_string(),
800        body_length: new_memory.body.len(),
801    })
802}
803
804// ---------------------------------------------------------------------------
805// G20: mode-conditional flag validation
806// ---------------------------------------------------------------------------
807
808/// True when a scalar value matches its declared default. Local
809/// re-declaration (also defined in ) to keep this module
810/// self-contained for the G20 fix.
811fn is_at_default<T: PartialEq>(value: T, default: T) -> bool {
812    value == default
813}
814
815/// G20: validate that flags for one LLM provider were not passed when
816/// the operator selected a different provider (or no provider). Flags
817/// silently discarded by the wrong mode are surfaced as
818///  BEFORE any DB work, so the operator gets
819/// an actionable error instead of a surprise at runtime.
820///
821/// Mode-specific matrices:
822/// - `mode=none` and `mode=gliner` reject: claude_binary, claude_model,
823///   claude_timeout!=300, max_cost_usd, resume, retry_failed, keep_queue,
824///   codex_binary, codex_model, codex_timeout!=300, gliner_variant (if
825///   --enable-ner is false)
826/// - `mode=claude-code` rejects: codex_binary, codex_model, codex_timeout!=300
827/// - `mode=codex` rejects: claude_binary, claude_model, claude_timeout!=300,
828///   max_cost_usd, resume, retry_failed, keep_queue
829fn validate_mode_conditional_flags_ingest(args: &IngestArgs) -> Result<(), AppError> {
830    const DEFAULT_TIMEOUT: u64 = 300;
831    const DEFAULT_RATE_LIMIT_WAIT: u64 = 60;
832
833    let mut conflicts: Vec<String> = Vec::new();
834
835    let is_local_mode = args.mode == IngestMode::None || args.mode == IngestMode::Gliner;
836
837    if is_local_mode {
838        if args.claude_binary.is_some() {
839            conflicts.push("--claude-binary is ignored when --mode is none or gliner".to_string());
840        }
841        if args.claude_model.is_some() {
842            conflicts.push("--claude-model is ignored when --mode is none or gliner".to_string());
843        }
844        if !is_at_default(args.claude_timeout, DEFAULT_TIMEOUT) {
845            conflicts.push(format!(
846                "--claude-timeout={} is ignored when --mode is none or gliner (remove the flag to use the default 300s)",
847                args.claude_timeout
848            ));
849        }
850        if args.codex_binary.is_some() {
851            conflicts.push("--codex-binary is ignored when --mode is none or gliner".to_string());
852        }
853        if args.codex_model.is_some() {
854            conflicts.push("--codex-model is ignored when --mode is none or gliner".to_string());
855        }
856        if !is_at_default(args.codex_timeout, DEFAULT_TIMEOUT) {
857            conflicts.push(format!(
858                "--codex-timeout={} is ignored when --mode is none or gliner (remove the flag to use the default 300s)",
859                args.codex_timeout
860            ));
861        }
862        if args.max_cost_usd.is_some() {
863            conflicts.push("--max-cost-usd is ignored when --mode is none or gliner (cost is only tracked for LLM-backed modes)".to_string());
864        }
865        if args.resume {
866            conflicts.push("--resume is ignored when --mode is none or gliner (the queue DB is only used by LLM-backed modes)".to_string());
867        }
868        if args.retry_failed {
869            conflicts.push("--retry-failed is ignored when --mode is none or gliner".to_string());
870        }
871        if args.keep_queue {
872            conflicts.push("--keep-queue is ignored when --mode is none or gliner".to_string());
873        }
874        if !is_at_default(args.rate_limit_wait, DEFAULT_RATE_LIMIT_WAIT) {
875            conflicts.push(format!(
876                "--rate-limit-wait={} is ignored when --mode is none or gliner",
877                args.rate_limit_wait
878            ));
879        }
880    }
881
882    match args.mode {
883        IngestMode::ClaudeCode => {
884            if args.codex_binary.is_some() {
885                conflicts.push("--codex-binary is ignored when --mode=claude-code".to_string());
886            }
887            if args.codex_model.is_some() {
888                conflicts.push("--codex-model is ignored when --mode=claude-code".to_string());
889            }
890            if !is_at_default(args.codex_timeout, DEFAULT_TIMEOUT) {
891                conflicts.push(format!(
892                    "--codex-timeout={} is ignored when --mode=claude-code (remove the flag to use the default 300s)",
893                    args.codex_timeout
894                ));
895            }
896        }
897        IngestMode::Codex => {
898            if args.claude_binary.is_some() {
899                conflicts.push("--claude-binary is ignored when --mode=codex".to_string());
900            }
901            if args.claude_model.is_some() {
902                conflicts.push("--claude-model is ignored when --mode=codex".to_string());
903            }
904            if !is_at_default(args.claude_timeout, DEFAULT_TIMEOUT) {
905                conflicts.push(format!(
906                    "--claude-timeout={} is ignored when --mode=codex (remove the flag to use the default 300s)",
907                    args.claude_timeout
908                ));
909            }
910            if args.max_cost_usd.is_some() {
911                conflicts.push(
912                    "--max-cost-usd is ignored when --mode=codex (OAuth-first; cost is metered by your subscription)"
913                        .to_string(),
914                );
915            }
916            if args.resume {
917                conflicts.push("--resume is only valid for --mode=claude-code".to_string());
918            }
919            if args.retry_failed {
920                conflicts.push("--retry-failed is only valid for --mode=claude-code".to_string());
921            }
922            if args.keep_queue {
923                conflicts.push("--keep-queue is only valid for --mode=claude-code".to_string());
924            }
925        }
926        IngestMode::None | IngestMode::Gliner => {}
927    }
928
929    if !conflicts.is_empty() {
930        return Err(AppError::Validation(format!(
931            "G20: mode-conditional flag conflicts detected for --mode={:?}:\n  - {}",
932            args.mode,
933            conflicts.join("\n  - ")
934        )));
935    }
936
937    Ok(())
938}
939
940// ---------------------------------------------------------------------------
941
942#[tracing::instrument(skip_all, level = "debug", name = "ingest")]
943pub fn run(args: IngestArgs) -> Result<(), AppError> {
944    // G20: mode-conditional flag validation BEFORE any DB access.
945    // Surfaces flags that the wrong mode would silently discard.
946    validate_mode_conditional_flags_ingest(&args)?;
947    tracing::debug!(target: "ingest", dir = %args.dir.display(), mode = ?args.mode, "starting ingest");
948    if args.mode == IngestMode::ClaudeCode {
949        return super::ingest_claude::run_claude_ingest(&args);
950    }
951    if args.mode == IngestMode::Codex {
952        return super::ingest_codex::run_codex_ingest(&args);
953    }
954
955    let started = std::time::Instant::now();
956
957    if !args.dir.exists() {
958        return Err(AppError::Validation(format!(
959            "directory not found: {}",
960            args.dir.display()
961        )));
962    }
963    if !args.dir.is_dir() {
964        return Err(AppError::Validation(format!(
965            "path is not a directory: {}",
966            args.dir.display()
967        )));
968    }
969
970    let mut files: Vec<PathBuf> = Vec::with_capacity(128);
971    collect_files(&args.dir, &args.pattern, args.recursive, &mut files)?;
972    files.sort_unstable();
973
974    if files.len() > args.max_files {
975        return Err(AppError::Validation(format!(
976            "found {} files matching pattern, exceeds --max-files cap of {} (raise the cap or narrow the pattern)",
977            files.len(),
978            args.max_files
979        )));
980    }
981
982    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
983    let memory_type_str = args.r#type.as_str().to_string();
984
985    let paths = AppPaths::resolve(args.db.as_deref())?;
986    let mut conn_or_err = match init_storage(&paths) {
987        Ok(c) => Ok(c),
988        Err(e) => Err(format!("{e}")),
989    };
990
991    let mut succeeded: usize = 0;
992    let mut failed: usize = 0;
993    let mut skipped: usize = 0;
994    let total = files.len();
995
996    // Pre-resolve all names before parallelisation so Phase A workers see a
997    // consistent, immutable name assignment (v1.0.31 A10 contract preserved).
998    let mut taken_names: BTreeSet<String> = BTreeSet::new();
999
1000    // SlotMeta: per-slot output metadata retained on the main thread for NDJSON.
1001    // ProcessItem: the data moved into the producer thread for Phase A computation.
1002    // We split these so `slots_meta` (non-Send BTreeSet-dependent) stays on main
1003    // thread while `process_items` (Send: only PathBuf + String) crosses the thread
1004    // boundary into the rayon producer.
1005    enum SlotMeta {
1006        Skip {
1007            file_str: String,
1008            derived_base: String,
1009            name_truncated: bool,
1010            original_name: Option<String>,
1011            original_filename: Option<String>,
1012            reason: String,
1013        },
1014        Process {
1015            file_str: String,
1016            derived_name: String,
1017            name_truncated: bool,
1018            original_name: Option<String>,
1019            original_filename: Option<String>,
1020        },
1021    }
1022
1023    struct ProcessItem {
1024        idx: usize,
1025        path: PathBuf,
1026        file_str: String,
1027        derived_name: String,
1028    }
1029
1030    let files_cap = files.len();
1031    let mut slots_meta: Vec<SlotMeta> = Vec::new();
1032    slots_meta.try_reserve(files_cap).map_err(|_| {
1033        AppError::LimitExceeded(format!(
1034            "allocation of {files_cap} slot metadata entries would exceed available memory"
1035        ))
1036    })?;
1037    let mut process_items: Vec<ProcessItem> = Vec::new();
1038    process_items.try_reserve(files_cap).map_err(|_| {
1039        AppError::LimitExceeded(format!(
1040            "allocation of {files_cap} process items would exceed available memory"
1041        ))
1042    })?;
1043    let mut truncations: Vec<(String, String)> = Vec::new();
1044    truncations.try_reserve(files_cap).map_err(|_| {
1045        AppError::LimitExceeded(format!(
1046            "allocation of {files_cap} truncation entries would exceed available memory"
1047        ))
1048    })?;
1049
1050    let max_name_length = args.max_name_length;
1051    for path in &files {
1052        let file_str = path.to_string_lossy().into_owned();
1053        let (derived_base, name_truncated, original_name) =
1054            derive_kebab_name(path, max_name_length);
1055        let original_basename = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1056
1057        if name_truncated {
1058            if let Some(ref orig) = original_name {
1059                truncations.push((orig.clone(), derived_base.clone()));
1060            }
1061        }
1062
1063        if derived_base.is_empty() {
1064            // original_filename: always include when it differs from the empty derived name
1065            let orig_filename = if !original_basename.is_empty() {
1066                Some(original_basename.to_string())
1067            } else {
1068                None
1069            };
1070            slots_meta.push(SlotMeta::Skip {
1071                file_str,
1072                derived_base: String::new(),
1073                name_truncated: false,
1074                original_name: None,
1075                original_filename: orig_filename,
1076                reason: "could not derive a non-empty kebab-case name from filename".to_string(),
1077            });
1078            continue;
1079        }
1080
1081        match unique_name(&derived_base, &taken_names) {
1082            Ok(derived_name) => {
1083                taken_names.insert(derived_name.clone());
1084                let idx = slots_meta.len();
1085                // original_filename: present only when the raw basename differs from the derived name
1086                let orig_filename = if original_basename != derived_name {
1087                    Some(original_basename.to_string())
1088                } else {
1089                    None
1090                };
1091                process_items.push(ProcessItem {
1092                    idx,
1093                    path: path.clone(),
1094                    file_str: file_str.clone(),
1095                    derived_name: derived_name.clone(),
1096                });
1097                slots_meta.push(SlotMeta::Process {
1098                    file_str,
1099                    derived_name,
1100                    name_truncated,
1101                    original_name,
1102                    original_filename: orig_filename,
1103                });
1104            }
1105            Err(e) => {
1106                let orig_filename = if original_basename != derived_base {
1107                    Some(original_basename.to_string())
1108                } else {
1109                    None
1110                };
1111                slots_meta.push(SlotMeta::Skip {
1112                    file_str,
1113                    derived_base,
1114                    name_truncated,
1115                    original_name,
1116                    original_filename: orig_filename,
1117                    reason: e.to_string(),
1118                });
1119            }
1120        }
1121    }
1122
1123    if !truncations.is_empty() {
1124        tracing::info!(
1125            target: "ingest",
1126            count = truncations.len(),
1127            max_name_length = max_name_length,
1128            max_len = DERIVED_NAME_MAX_LEN,
1129            "derived names truncated; pass -vv (debug) for per-file detail"
1130        );
1131    }
1132
1133    // --dry-run: emit preview events and exit before loading ONNX or touching DB.
1134    if args.dry_run {
1135        for meta in &slots_meta {
1136            match meta {
1137                SlotMeta::Skip {
1138                    file_str,
1139                    derived_base,
1140                    name_truncated,
1141                    original_name,
1142                    original_filename,
1143                    reason,
1144                } => {
1145                    output::emit_json_compact(&IngestFileEvent {
1146                        file: file_str,
1147                        name: derived_base,
1148                        status: "skip",
1149                        truncated: *name_truncated,
1150                        original_name: original_name.clone(),
1151                        original_filename: original_filename.as_deref(),
1152                        error: Some(reason.clone()),
1153                        memory_id: None,
1154                        action: None,
1155                        body_length: 0,
1156                    })?;
1157                }
1158                SlotMeta::Process {
1159                    file_str,
1160                    derived_name,
1161                    name_truncated,
1162                    original_name,
1163                    original_filename,
1164                } => {
1165                    output::emit_json_compact(&IngestFileEvent {
1166                        file: file_str,
1167                        name: derived_name,
1168                        status: "preview",
1169                        truncated: *name_truncated,
1170                        original_name: original_name.clone(),
1171                        original_filename: original_filename.as_deref(),
1172                        error: None,
1173                        memory_id: None,
1174                        action: None,
1175                        body_length: 0,
1176                    })?;
1177                }
1178            }
1179        }
1180        output::emit_json_compact(&IngestSummary {
1181            summary: true,
1182            dir: args.dir.to_string_lossy().into_owned(),
1183            pattern: args.pattern.clone(),
1184            recursive: args.recursive,
1185            files_total: total,
1186            files_succeeded: 0,
1187            files_failed: 0,
1188            files_skipped: 0,
1189            elapsed_ms: started.elapsed().as_millis() as u64,
1190        })?;
1191        return Ok(());
1192    }
1193
1194    // Reject contradictory flag combination: explicit parallelism > 1 with --low-memory.
1195    if args.low_memory {
1196        if let Some(n) = args.ingest_parallelism {
1197            if n > 1 {
1198                return Err(AppError::Validation(
1199                    "--ingest-parallelism N>1 conflicts with --low-memory; use one or the other"
1200                        .to_string(),
1201                ));
1202            }
1203        }
1204    }
1205
1206    // Determine rayon thread pool size, honoring --low-memory and the
1207    // SQLITE_GRAPHRAG_LOW_MEMORY env var (both force parallelism = 1).
1208    let parallelism = resolve_parallelism(args.low_memory, args.ingest_parallelism);
1209
1210    let pool = rayon::ThreadPoolBuilder::new()
1211        .num_threads(parallelism)
1212        .build()
1213        .map_err(|e| AppError::Internal(anyhow::anyhow!("rayon pool: {e}")))?;
1214
1215    if args.enable_ner && args.skip_extraction {
1216        return Err(AppError::Validation(
1217            "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
1218        ));
1219    }
1220    if args.skip_extraction && !args.enable_ner {
1221        // v1.0.74: revert to v1.0.45 hidden no-op behavior. The v1.0.67
1222        // commit (9ddb17b) promoted this to a hard validation error, which
1223        // broke the "kept as a hidden no-op for backwards compatibility"
1224        // promise documented in CHANGELOG v1.0.45 and started failing
1225        // 5+ CI jobs whose E2E tests use this flag to skip the
1226        // GLiNER-ONNX model download in CI environments.
1227        tracing::warn!(
1228            "--skip-extraction is deprecated since v1.0.45 and has no effect (NER is disabled by default); remove this flag to silence the warning"
1229        );
1230    }
1231    let enable_ner = args.enable_ner;
1232    let max_rss_mb = args.max_rss_mb;
1233    let llm_parallelism = args.llm_parallelism as usize;
1234    // v1.0.79: `--mode gliner` and `--gliner-variant` are no-ops kept for
1235    // compatibility (the GLiNER pipeline was removed); warn explicitly so
1236    // callers do not silently expect NER-quality extraction.
1237    if args.mode == IngestMode::Gliner {
1238        tracing::warn!(
1239            "--mode gliner is deprecated since v1.0.79 (the GLiNER pipeline was removed); it now performs URL-regex extraction only — use --mode claude-code or --mode codex for LLM-curated extraction"
1240        );
1241    }
1242    if args.gliner_variant != "fp32" {
1243        tracing::warn!(
1244            "--gliner-variant is deprecated and has no effect since v1.0.79 (the GLiNER pipeline was removed)"
1245        );
1246    }
1247    let gliner_variant: crate::extraction::GlinerVariant = match args.gliner_variant.as_str() {
1248        "int8" => crate::extraction::GlinerVariant::Int8,
1249        _ => crate::extraction::GlinerVariant::Fp32,
1250    };
1251
1252    let total_to_process = process_items.len();
1253    tracing::info!(
1254        target: "ingest",
1255        phase = "pipeline_start",
1256        files = total_to_process,
1257        ingest_parallelism = parallelism,
1258        "incremental pipeline starting: Phase A (rayon) → channel → Phase B (main thread)",
1259    );
1260
1261    // Bounded channel: producer never gets more than parallelism*2 items ahead of
1262    // the consumer, preventing memory blowup when Phase A is faster than Phase B.
1263    // Each message carries the slot index so Phase B can look up SlotMeta in order.
1264    let channel_bound = (parallelism * 2).max(1);
1265    let (tx, rx) = mpsc::sync_channel::<(usize, Result<StagedFile, AppError>)>(channel_bound);
1266
1267    // Phase A: launched in a dedicated OS thread so the main thread can consume
1268    // the channel concurrently. pool.install() blocks the calling thread until
1269    // all rayon workers finish — if called on the main thread it would
1270    // reintroduce the 2-phase blocking behaviour we are eliminating.
1271    let paths_owned = paths.clone();
1272    let producer_handle = std::thread::spawn(move || {
1273        pool.install(|| {
1274            process_items.into_par_iter().for_each(|item| {
1275                if crate::shutdown_requested() {
1276                    return;
1277                }
1278                let t0 = std::time::Instant::now();
1279                let result = stage_file(
1280                    item.idx,
1281                    &item.path,
1282                    &item.derived_name,
1283                    &paths_owned,
1284                    enable_ner,
1285                    gliner_variant,
1286                    max_rss_mb,
1287                    llm_parallelism,
1288                );
1289                let elapsed_ms = t0.elapsed().as_millis() as u64;
1290
1291                // Emit NDJSON progress event to stderr so the user sees work
1292                // happening during long NER runs (e.g. 50 files × 27s each).
1293                let (n_entities, n_relationships) = match &result {
1294                    Ok(sf) => (sf.entities.len(), sf.relationships.len()),
1295                    Err(_) => (0, 0),
1296                };
1297                let progress = StageProgressEvent {
1298                    schema_version: 1,
1299                    event: "file_extracted",
1300                    path: &item.file_str,
1301                    ms: elapsed_ms,
1302                    entities: n_entities,
1303                    relationships: n_relationships,
1304                };
1305                if let Ok(line) = serde_json::to_string(&progress) {
1306                    tracing::info!(target: "ingest_progress", "{}", line);
1307                }
1308
1309                // Blocking send applies backpressure: if Phase B is slower,
1310                // Phase A workers wait here instead of accumulating staged files
1311                // in memory. If the receiver is dropped (fail_fast abort), ignore.
1312                let _ = tx.send((item.idx, result));
1313            });
1314            // Explicit drop of tx signals Phase B (rx iteration) to stop.
1315            drop(tx);
1316        });
1317    });
1318
1319    // Phase B: main thread persists files as results arrive from the channel.
1320    // Results arrive in completion order (par_iter is unordered). We persist
1321    // each file immediately on arrival — this is the key fix for B1: with the
1322    // old 2-phase design the first DB write happened only after ALL files had
1323    // finished Phase A. Now the first commit happens as soon as the first file
1324    // completes Phase A, regardless of how many files remain.
1325    //
1326    // NDJSON output order follows completion order (not file-system sort order).
1327    // Skip slots are emitted at the end, after all Process results are consumed.
1328    // This trade-off is intentional: deterministic NDJSON ordering is a lesser
1329    // requirement than ensuring data is persisted before the user's timeout fires.
1330    let fail_fast = args.fail_fast;
1331
1332    // Emit pending Skip events first so agents see them early.
1333    for meta in &slots_meta {
1334        if let SlotMeta::Skip {
1335            file_str,
1336            derived_base,
1337            name_truncated,
1338            original_name,
1339            original_filename,
1340            reason,
1341        } = meta
1342        {
1343            output::emit_json_compact(&IngestFileEvent {
1344                file: file_str,
1345                name: derived_base,
1346                status: "skipped",
1347                truncated: *name_truncated,
1348                original_name: original_name.clone(),
1349                original_filename: original_filename.as_deref(),
1350                error: Some(reason.clone()),
1351                memory_id: None,
1352                action: None,
1353                body_length: 0,
1354            })?;
1355            skipped += 1;
1356        }
1357    }
1358
1359    // Build a quick index from slot index → SlotMeta reference for O(1) lookups
1360    // as channel messages arrive in completion order.
1361    let meta_index: std::collections::HashMap<usize, &SlotMeta> = slots_meta
1362        .iter()
1363        .enumerate()
1364        .filter(|(_, m)| matches!(m, SlotMeta::Process { .. }))
1365        .collect();
1366
1367    tracing::info!(
1368        target: "ingest",
1369        phase = "persist_start",
1370        files = total_to_process,
1371        "phase B starting: persisting files incrementally as Phase A completes each one",
1372    );
1373
1374    // Drain channel and persist each file immediately — no accumulation into a
1375    // HashMap. The bounded channel ensures Phase A cannot run too far ahead of
1376    // Phase B without applying backpressure.
1377    for (idx, stage_result) in rx {
1378        if crate::shutdown_requested() {
1379            tracing::info!(target: "ingest", "shutdown requested, stopping persistence loop");
1380            break;
1381        }
1382        let meta = meta_index.get(&idx).ok_or_else(|| {
1383            AppError::Internal(anyhow::anyhow!(
1384                "channel idx {idx} has no corresponding Process slot"
1385            ))
1386        })?;
1387        let (file_str, derived_name, name_truncated, original_name, original_filename) = match meta
1388        {
1389            SlotMeta::Process {
1390                file_str,
1391                derived_name,
1392                name_truncated,
1393                original_name,
1394                original_filename,
1395            } => (
1396                file_str,
1397                derived_name,
1398                name_truncated,
1399                original_name,
1400                original_filename,
1401            ),
1402            SlotMeta::Skip { .. } => unreachable!("channel only carries Process results"),
1403        };
1404
1405        // If storage init failed, every file fails with the same error.
1406        let conn = match conn_or_err.as_mut() {
1407            Ok(c) => c,
1408            Err(err_msg) => {
1409                let err_clone = err_msg.clone();
1410                output::emit_json_compact(&IngestFileEvent {
1411                    file: file_str,
1412                    name: derived_name,
1413                    status: "failed",
1414                    truncated: *name_truncated,
1415                    original_name: original_name.clone(),
1416                    original_filename: original_filename.as_deref(),
1417                    error: Some(err_clone.clone()),
1418                    memory_id: None,
1419                    action: None,
1420                    body_length: 0,
1421                })?;
1422                failed += 1;
1423                if fail_fast {
1424                    output::emit_json_compact(&IngestSummary {
1425                        summary: true,
1426                        dir: args.dir.display().to_string(),
1427                        pattern: args.pattern.clone(),
1428                        recursive: args.recursive,
1429                        files_total: total,
1430                        files_succeeded: succeeded,
1431                        files_failed: failed,
1432                        files_skipped: skipped,
1433                        elapsed_ms: started.elapsed().as_millis() as u64,
1434                    })?;
1435                    return Err(AppError::Validation(format!(
1436                        "ingest aborted on first failure: {err_clone}"
1437                    )));
1438                }
1439                continue;
1440            }
1441        };
1442
1443        let outcome =
1444            stage_result.and_then(|sf| persist_staged(conn, &namespace, &memory_type_str, sf));
1445
1446        match outcome {
1447            Ok(FileSuccess {
1448                memory_id,
1449                action,
1450                body_length,
1451            }) => {
1452                output::emit_json_compact(&IngestFileEvent {
1453                    file: file_str,
1454                    name: derived_name,
1455                    status: "indexed",
1456                    truncated: *name_truncated,
1457                    original_name: original_name.clone(),
1458                    original_filename: original_filename.as_deref(),
1459                    error: None,
1460                    memory_id: Some(memory_id),
1461                    action: Some(action),
1462                    body_length,
1463                })?;
1464                succeeded += 1;
1465            }
1466            Err(ref e) if matches!(e, AppError::Duplicate(_)) => {
1467                output::emit_json_compact(&IngestFileEvent {
1468                    file: file_str,
1469                    name: derived_name,
1470                    status: "skipped",
1471                    truncated: *name_truncated,
1472                    original_name: original_name.clone(),
1473                    original_filename: original_filename.as_deref(),
1474                    error: Some(format!("{e}")),
1475                    memory_id: None,
1476                    action: Some("duplicate".to_string()),
1477                    body_length: 0,
1478                })?;
1479                skipped += 1;
1480            }
1481            Err(e) => {
1482                let err_msg = format!("{e}");
1483                output::emit_json_compact(&IngestFileEvent {
1484                    file: file_str,
1485                    name: derived_name,
1486                    status: "failed",
1487                    truncated: *name_truncated,
1488                    original_name: original_name.clone(),
1489                    original_filename: original_filename.as_deref(),
1490                    error: Some(err_msg.clone()),
1491                    memory_id: None,
1492                    action: None,
1493                    body_length: 0,
1494                })?;
1495                failed += 1;
1496                if fail_fast {
1497                    output::emit_json_compact(&IngestSummary {
1498                        summary: true,
1499                        dir: args.dir.display().to_string(),
1500                        pattern: args.pattern.clone(),
1501                        recursive: args.recursive,
1502                        files_total: total,
1503                        files_succeeded: succeeded,
1504                        files_failed: failed,
1505                        files_skipped: skipped,
1506                        elapsed_ms: started.elapsed().as_millis() as u64,
1507                    })?;
1508                    return Err(AppError::Validation(format!(
1509                        "ingest aborted on first failure: {err_msg}"
1510                    )));
1511                }
1512            }
1513        }
1514    }
1515
1516    // Wait for the producer thread to finish cleanly.
1517    producer_handle
1518        .join()
1519        .map_err(|_| AppError::Internal(anyhow::anyhow!("ingest producer thread panicked")))?;
1520
1521    if let Ok(ref conn) = conn_or_err {
1522        if succeeded > 0 {
1523            let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1524        }
1525    }
1526
1527    output::emit_json_compact(&IngestSummary {
1528        summary: true,
1529        dir: args.dir.display().to_string(),
1530        pattern: args.pattern.clone(),
1531        recursive: args.recursive,
1532        files_total: total,
1533        files_succeeded: succeeded,
1534        files_failed: failed,
1535        files_skipped: skipped,
1536        elapsed_ms: started.elapsed().as_millis() as u64,
1537    })?;
1538
1539    Ok(())
1540}
1541
1542/// Auto-initialises the database (matches the contract of every other CRUD
1543/// handler) and returns a fresh read/write connection ready for the ingest
1544/// loop. Errors here are recoverable per-file: the caller surfaces them as
1545/// failure events so `--fail-fast` and the continue-on-error path keep
1546/// working when, for example, the user points `--db` at an unwritable path.
1547fn init_storage(paths: &AppPaths) -> Result<Connection, AppError> {
1548    ensure_db_ready(paths)?;
1549    let conn = open_rw(&paths.db)?;
1550    Ok(conn)
1551}
1552
1553pub(crate) fn collect_files(
1554    dir: &Path,
1555    pattern: &str,
1556    recursive: bool,
1557    out: &mut Vec<PathBuf>,
1558) -> Result<(), AppError> {
1559    let entries = std::fs::read_dir(dir).map_err(AppError::Io)?;
1560    for entry in entries {
1561        let entry = entry.map_err(AppError::Io)?;
1562        let path = entry.path();
1563        let file_type = entry.file_type().map_err(AppError::Io)?;
1564        if file_type.is_file() {
1565            let name = entry.file_name();
1566            let name_str = name.to_string_lossy();
1567            if matches_pattern(&name_str, pattern) {
1568                out.push(path);
1569            }
1570        } else if file_type.is_dir() && recursive {
1571            collect_files(&path, pattern, recursive, out)?;
1572        }
1573    }
1574    Ok(())
1575}
1576
1577fn matches_pattern(name: &str, pattern: &str) -> bool {
1578    if let Some(suffix) = pattern.strip_prefix('*') {
1579        name.ends_with(suffix)
1580    } else if let Some(prefix) = pattern.strip_suffix('*') {
1581        name.starts_with(prefix)
1582    } else {
1583        name == pattern
1584    }
1585}
1586
1587/// Returns `(final_name, truncated, original_name)`.
1588/// `truncated` is true when the derived name exceeded `max_len`.
1589/// `original_name` holds the pre-truncation name only when `truncated=true`.
1590///
1591/// Non-ASCII characters are first decomposed via NFD and then stripped of
1592/// combining marks so accented letters fold to their base ASCII letter
1593/// (e.g. `acai` from accented input, `naive` from diaeresis). Characters with no ASCII
1594/// fallback (emoji, CJK ideographs, symbols) are dropped silently. This
1595/// preserves meaningful word content rather than collapsing the basename
1596/// to a few stray ASCII letters as the previous filter did.
1597pub(crate) fn derive_kebab_name(path: &Path, max_len: usize) -> (String, bool, Option<String>) {
1598    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1599    let lowered: String = stem
1600        .nfd()
1601        .filter(|c| !unicode_normalization::char::is_combining_mark(*c))
1602        .map(|c| {
1603            if c == '_' || c.is_whitespace() {
1604                '-'
1605            } else {
1606                c
1607            }
1608        })
1609        .map(|c| c.to_ascii_lowercase())
1610        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '-')
1611        .collect();
1612    let collapsed = collapse_dashes(&lowered);
1613    let trimmed_raw = collapsed.trim_matches('-').to_string();
1614    // Prefix names that start with a digit to keep them valid kebab-case identifiers.
1615    let trimmed = if trimmed_raw.starts_with(|c: char| c.is_ascii_digit()) {
1616        format!("doc-{trimmed_raw}")
1617    } else {
1618        trimmed_raw
1619    };
1620    if trimmed.len() > max_len {
1621        let truncated = trimmed[..max_len].trim_matches('-').to_string();
1622        tracing::debug!(
1623            target: "ingest",
1624            original = %trimmed,
1625            truncated_to = %truncated,
1626            max_len = max_len,
1627            "derived memory name truncated to fit length cap; collisions will be resolved with numeric suffixes"
1628        );
1629        (truncated, true, Some(trimmed))
1630    } else {
1631        (trimmed, false, None)
1632    }
1633}
1634
1635/// v1.0.31 A10: returns the first non-colliding kebab name by appending a
1636/// numeric suffix (`-1`, `-2`, …) when needed.
1637///
1638/// `taken` is the set of names already consumed in the current ingest run.
1639/// The caller is expected to insert the returned name into `taken` so the
1640/// next call observes the consumption. Cross-run collisions are intentionally
1641/// surfaced by the per-file persistence path as duplicates so re-ingestion
1642/// of identical corpora stays idempotent.
1643///
1644/// Returns `Err(AppError::Validation)` after `MAX_NAME_COLLISION_SUFFIX`
1645/// candidates collide, signalling a pathological corpus that should be
1646/// renamed manually.
1647fn unique_name(base: &str, taken: &BTreeSet<String>) -> Result<String, AppError> {
1648    if !taken.contains(base) {
1649        return Ok(base.to_string());
1650    }
1651    for suffix in 1..=MAX_NAME_COLLISION_SUFFIX {
1652        let candidate = format!("{base}-{suffix}");
1653        if !taken.contains(&candidate) {
1654            tracing::warn!(
1655                target: "ingest",
1656                base = %base,
1657                resolved = %candidate,
1658                suffix,
1659                "memory name collision resolved with numeric suffix"
1660            );
1661            return Ok(candidate);
1662        }
1663    }
1664    Err(AppError::Validation(format!(
1665        "too many name collisions for base '{base}' (>{MAX_NAME_COLLISION_SUFFIX}); rename source files to disambiguate"
1666    )))
1667}
1668
1669fn collapse_dashes(s: &str) -> String {
1670    let mut out = String::with_capacity(s.len());
1671    let mut prev_dash = false;
1672    for c in s.chars() {
1673        if c == '-' {
1674            if !prev_dash {
1675                out.push('-');
1676            }
1677            prev_dash = true;
1678        } else {
1679            out.push(c);
1680            prev_dash = false;
1681        }
1682    }
1683    out
1684}
1685
1686#[cfg(test)]
1687mod tests {
1688    use super::*;
1689    use std::path::PathBuf;
1690
1691    #[test]
1692    fn matches_pattern_suffix() {
1693        assert!(matches_pattern("foo.md", "*.md"));
1694        assert!(!matches_pattern("foo.txt", "*.md"));
1695        assert!(matches_pattern("foo.md", "*"));
1696    }
1697
1698    #[test]
1699    fn matches_pattern_prefix() {
1700        assert!(matches_pattern("README.md", "README*"));
1701        assert!(!matches_pattern("CHANGELOG.md", "README*"));
1702    }
1703
1704    #[test]
1705    fn matches_pattern_exact() {
1706        assert!(matches_pattern("README.md", "README.md"));
1707        assert!(!matches_pattern("readme.md", "README.md"));
1708    }
1709
1710    #[test]
1711    fn derive_kebab_underscore_to_dash() {
1712        let p = PathBuf::from("/tmp/claude_code_headless.md");
1713        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1714        assert_eq!(name, "claude-code-headless");
1715        assert!(!truncated);
1716        assert!(original.is_none());
1717    }
1718
1719    #[test]
1720    fn derive_kebab_uppercase_lowered() {
1721        let p = PathBuf::from("/tmp/README.md");
1722        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1723        assert_eq!(name, "readme");
1724        assert!(!truncated);
1725        assert!(original.is_none());
1726    }
1727
1728    #[test]
1729    fn derive_kebab_strips_non_kebab_chars() {
1730        let p = PathBuf::from("/tmp/some@weird#name!.md");
1731        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1732        assert_eq!(name, "someweirdname");
1733        assert!(!truncated);
1734        assert!(original.is_none());
1735    }
1736
1737    // Bug M-A3: NFD-based unicode normalization preserves base letters of
1738    // accented characters instead of dropping them entirely.
1739    #[test]
1740    fn derive_kebab_folds_accented_letters_to_ascii() {
1741        let p = PathBuf::from("/tmp/açaí.md");
1742        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1743        assert_eq!(name, "acai", "got '{name}'");
1744    }
1745
1746    #[test]
1747    fn derive_kebab_handles_naive_with_diaeresis() {
1748        let p = PathBuf::from("/tmp/naïve-test.md");
1749        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1750        assert_eq!(name, "naive-test", "got '{name}'");
1751    }
1752
1753    #[test]
1754    fn derive_kebab_drops_emoji_keeps_word() {
1755        let p = PathBuf::from("/tmp/🚀-rocket.md");
1756        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1757        assert_eq!(name, "rocket", "got '{name}'");
1758    }
1759
1760    #[test]
1761    fn derive_kebab_mixed_unicode_emoji_keeps_letters() {
1762        let p = PathBuf::from("/tmp/açaí🦜.md");
1763        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1764        assert_eq!(name, "acai", "got '{name}'");
1765    }
1766
1767    #[test]
1768    fn derive_kebab_pure_emoji_yields_empty() {
1769        let p = PathBuf::from("/tmp/🦜🚀🌟.md");
1770        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1771        assert!(name.is_empty(), "got '{name}'");
1772    }
1773
1774    #[test]
1775    fn derive_kebab_collapses_consecutive_dashes() {
1776        let p = PathBuf::from("/tmp/a__b___c.md");
1777        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1778        assert_eq!(name, "a-b-c");
1779        assert!(!truncated);
1780        assert!(original.is_none());
1781    }
1782
1783    #[test]
1784    fn derive_kebab_truncates_to_60_chars() {
1785        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(80)));
1786        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1787        assert!(name.len() <= 60, "got len {}", name.len());
1788        assert!(truncated);
1789        assert!(original.is_some());
1790        assert!(original.unwrap().len() > 60);
1791    }
1792
1793    #[test]
1794    fn collect_files_finds_md_files() {
1795        let tmp = tempfile::tempdir().expect("tempdir");
1796        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1797        std::fs::write(tmp.path().join("b.md"), "y").unwrap();
1798        std::fs::write(tmp.path().join("c.txt"), "z").unwrap();
1799        let mut out = Vec::new();
1800        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1801        assert_eq!(out.len(), 2, "should find 2 .md files, got {out:?}");
1802    }
1803
1804    #[test]
1805    fn collect_files_recursive_descends_subdirs() {
1806        let tmp = tempfile::tempdir().expect("tempdir");
1807        let sub = tmp.path().join("sub");
1808        std::fs::create_dir(&sub).unwrap();
1809        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1810        std::fs::write(sub.join("b.md"), "y").unwrap();
1811        let mut out = Vec::new();
1812        collect_files(tmp.path(), "*.md", true, &mut out).expect("collect");
1813        assert_eq!(out.len(), 2);
1814    }
1815
1816    #[test]
1817    fn collect_files_non_recursive_skips_subdirs() {
1818        let tmp = tempfile::tempdir().expect("tempdir");
1819        let sub = tmp.path().join("sub");
1820        std::fs::create_dir(&sub).unwrap();
1821        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1822        std::fs::write(sub.join("b.md"), "y").unwrap();
1823        let mut out = Vec::new();
1824        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1825        assert_eq!(out.len(), 1);
1826    }
1827
1828    // ── v1.0.31 A10: name truncation warns and collisions are auto-resolved ──
1829
1830    #[test]
1831    fn derive_kebab_long_basename_truncated_within_cap() {
1832        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(120)));
1833        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1834        assert!(
1835            name.len() <= DERIVED_NAME_MAX_LEN,
1836            "truncated name must respect cap; got {} chars",
1837            name.len()
1838        );
1839        assert!(!name.is_empty());
1840        assert!(truncated);
1841        assert!(original.is_some());
1842    }
1843
1844    #[test]
1845    fn unique_name_returns_base_when_free() {
1846        let taken: BTreeSet<String> = BTreeSet::new();
1847        let resolved = unique_name("note", &taken).expect("must resolve");
1848        assert_eq!(resolved, "note");
1849    }
1850
1851    #[test]
1852    fn unique_name_appends_first_free_suffix_on_collision() {
1853        let mut taken: BTreeSet<String> = BTreeSet::new();
1854        taken.insert("note".to_string());
1855        taken.insert("note-1".to_string());
1856        let resolved = unique_name("note", &taken).expect("must resolve");
1857        assert_eq!(resolved, "note-2");
1858    }
1859
1860    #[test]
1861    fn unique_name_errors_after_collision_cap() {
1862        let mut taken: BTreeSet<String> = BTreeSet::new();
1863        taken.insert("note".to_string());
1864        for i in 1..=MAX_NAME_COLLISION_SUFFIX {
1865            taken.insert(format!("note-{i}"));
1866        }
1867        let err = unique_name("note", &taken).expect_err("must surface error");
1868        assert!(matches!(err, AppError::Validation(_)));
1869    }
1870
1871    // ── v1.0.32 Onda 4B: in-process pipeline validation ──
1872
1873    #[test]
1874    fn validate_relation_format_accepts_valid_relations() {
1875        use crate::parsers::{is_canonical_relation, validate_relation_format};
1876        assert!(validate_relation_format("applies_to").is_ok());
1877        assert!(validate_relation_format("depends_on").is_ok());
1878        assert!(validate_relation_format("implements").is_ok());
1879        assert!(validate_relation_format("").is_err());
1880        assert!(is_canonical_relation("applies_to"));
1881        assert!(!is_canonical_relation("implements"));
1882    }
1883
1884    // ── v1.0.40 H-A1: --low-memory flag and SQLITE_GRAPHRAG_LOW_MEMORY env var ──
1885
1886    use serial_test::serial;
1887
1888    /// Helper: scrubs the env var around a closure to keep tests deterministic.
1889    fn with_env_var<F: FnOnce()>(value: Option<&str>, f: F) {
1890        let key = "SQLITE_GRAPHRAG_LOW_MEMORY";
1891        let prev = std::env::var(key).ok();
1892        match value {
1893            Some(v) => std::env::set_var(key, v),
1894            None => std::env::remove_var(key),
1895        }
1896        f();
1897        match prev {
1898            Some(p) => std::env::set_var(key, p),
1899            None => std::env::remove_var(key),
1900        }
1901    }
1902
1903    #[test]
1904    #[serial]
1905    fn env_low_memory_enabled_unset_returns_false() {
1906        with_env_var(None, || assert!(!env_low_memory_enabled()));
1907    }
1908
1909    #[test]
1910    #[serial]
1911    fn env_low_memory_enabled_empty_returns_false() {
1912        with_env_var(Some(""), || assert!(!env_low_memory_enabled()));
1913    }
1914
1915    #[test]
1916    #[serial]
1917    fn env_low_memory_enabled_truthy_values_return_true() {
1918        for v in ["1", "true", "TRUE", "yes", "YES", "on", "On"] {
1919            with_env_var(Some(v), || {
1920                assert!(env_low_memory_enabled(), "value {v:?} should be truthy")
1921            });
1922        }
1923    }
1924
1925    #[test]
1926    #[serial]
1927    fn env_low_memory_enabled_falsy_values_return_false() {
1928        for v in ["0", "false", "FALSE", "no", "off"] {
1929            with_env_var(Some(v), || {
1930                assert!(!env_low_memory_enabled(), "value {v:?} should be falsy")
1931            });
1932        }
1933    }
1934
1935    #[test]
1936    #[serial]
1937    fn env_low_memory_enabled_unrecognized_value_returns_false() {
1938        with_env_var(Some("maybe"), || assert!(!env_low_memory_enabled()));
1939    }
1940
1941    #[test]
1942    #[serial]
1943    fn resolve_parallelism_flag_forces_one_overriding_explicit_value() {
1944        with_env_var(None, || {
1945            assert_eq!(resolve_parallelism(true, Some(4)), 1);
1946            assert_eq!(resolve_parallelism(true, Some(8)), 1);
1947            assert_eq!(resolve_parallelism(true, None), 1);
1948        });
1949    }
1950
1951    #[test]
1952    #[serial]
1953    fn resolve_parallelism_env_forces_one_when_flag_off() {
1954        with_env_var(Some("1"), || {
1955            assert_eq!(resolve_parallelism(false, Some(4)), 1);
1956            assert_eq!(resolve_parallelism(false, None), 1);
1957        });
1958    }
1959
1960    #[test]
1961    #[serial]
1962    fn resolve_parallelism_falsy_env_does_not_override() {
1963        with_env_var(Some("0"), || {
1964            assert_eq!(resolve_parallelism(false, Some(4)), 4);
1965        });
1966    }
1967
1968    #[test]
1969    #[serial]
1970    fn resolve_parallelism_explicit_value_when_low_memory_off() {
1971        with_env_var(None, || {
1972            assert_eq!(resolve_parallelism(false, Some(3)), 3);
1973            assert_eq!(resolve_parallelism(false, Some(1)), 1);
1974        });
1975    }
1976
1977    #[test]
1978    #[serial]
1979    fn resolve_parallelism_default_when_unset() {
1980        with_env_var(None, || {
1981            let p = resolve_parallelism(false, None);
1982            assert!((1..=4).contains(&p), "default must be in [1, 4]; got {p}");
1983        });
1984    }
1985
1986    #[test]
1987    fn ingest_args_parses_low_memory_flag_via_clap() {
1988        use clap::Parser;
1989        // Parse a synthetic Cli that contains the `ingest` subcommand. We rely
1990        // on the public `Cli` definition so the flag is wired end-to-end.
1991        let cli = crate::cli::Cli::try_parse_from([
1992            "sqlite-graphrag",
1993            "ingest",
1994            "/tmp/dummy",
1995            "--type",
1996            "document",
1997            "--low-memory",
1998        ])
1999        .expect("parse must succeed");
2000        match cli.command {
2001            crate::cli::Commands::Ingest(args) => {
2002                assert!(args.low_memory, "--low-memory must set field to true");
2003            }
2004            _ => panic!("expected Ingest subcommand"),
2005        }
2006    }
2007
2008    #[test]
2009    fn ingest_args_low_memory_defaults_false() {
2010        use clap::Parser;
2011        let cli = crate::cli::Cli::try_parse_from([
2012            "sqlite-graphrag",
2013            "ingest",
2014            "/tmp/dummy",
2015            "--type",
2016            "document",
2017        ])
2018        .expect("parse must succeed");
2019        match cli.command {
2020            crate::cli::Commands::Ingest(args) => {
2021                assert!(!args.low_memory, "default must be false");
2022            }
2023            _ => panic!("expected Ingest subcommand"),
2024        }
2025    }
2026}