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