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    let entity_embeddings = crate::embedder::embed_passages_parallel_local(
618        &paths.models,
619        &entity_texts,
620        llm_parallelism,
621        crate::embedder::entity_embed_batch_size(),
622    )?;
623
624    Ok(StagedFile {
625        body: raw_body,
626        body_hash,
627        snippet,
628        name: name.to_string(),
629        description,
630        embedding,
631        chunk_embeddings: chunk_embeddings_opt,
632        chunks_info,
633        entities: extracted_entities,
634        relationships: extracted_relationships,
635        entity_embeddings,
636        urls: extracted_urls,
637    })
638}
639
640/// Phase B: persists one `StagedFile` to the database on the main thread.
641fn persist_staged(
642    conn: &mut Connection,
643    namespace: &str,
644    memory_type: &str,
645    staged: StagedFile,
646) -> Result<FileSuccess, AppError> {
647    {
648        let active_count: u32 = conn.query_row(
649            "SELECT COUNT(DISTINCT namespace) FROM memories WHERE deleted_at IS NULL",
650            [],
651            |r| r.get::<_, i64>(0).map(|v| v as u32),
652        )?;
653        let ns_exists: bool = conn.query_row(
654            "SELECT EXISTS(SELECT 1 FROM memories WHERE namespace = ?1 AND deleted_at IS NULL)",
655            rusqlite::params![namespace],
656            |r| r.get::<_, i64>(0).map(|v| v > 0),
657        )?;
658        if !ns_exists && active_count >= crate::constants::MAX_NAMESPACES_ACTIVE {
659            return Err(AppError::NamespaceError(format!(
660                "active namespace limit of {} exceeded while creating '{namespace}'",
661                crate::constants::MAX_NAMESPACES_ACTIVE
662            )));
663        }
664    }
665
666    let existing_memory = memories::find_by_name(conn, namespace, &staged.name)?;
667    if existing_memory.is_some() {
668        return Err(AppError::Duplicate(errors_msg::duplicate_memory(
669            &staged.name,
670            namespace,
671        )));
672    }
673    let duplicate_hash_id = memories::find_by_hash(conn, namespace, &staged.body_hash)?;
674
675    let new_memory = NewMemory {
676        namespace: namespace.to_string(),
677        name: staged.name.clone(),
678        memory_type: memory_type.to_string(),
679        description: staged.description.clone(),
680        body: staged.body,
681        body_hash: staged.body_hash,
682        session_id: None,
683        source: "agent".to_string(),
684        metadata: serde_json::json!({}),
685    };
686
687    if let Some(hash_id) = duplicate_hash_id {
688        tracing::debug!(
689            target: "ingest",
690            duplicate_memory_id = hash_id,
691            "identical body already exists; persisting a new memory anyway"
692        );
693    }
694
695    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
696
697    let memory_id = memories::insert(&tx, &new_memory)?;
698    versions::insert_version(
699        &tx,
700        memory_id,
701        1,
702        &staged.name,
703        memory_type,
704        &staged.description,
705        &new_memory.body,
706        &serde_json::to_string(&new_memory.metadata)?,
707        None,
708        "create",
709    )?;
710    memories::upsert_vec(
711        &tx,
712        memory_id,
713        namespace,
714        memory_type,
715        &staged.embedding,
716        &staged.name,
717        &staged.snippet,
718    )?;
719
720    if staged.chunks_info.len() > 1 {
721        storage_chunks::insert_chunk_slices(&tx, memory_id, &new_memory.body, &staged.chunks_info)?;
722        let chunk_embeddings = staged.chunk_embeddings.ok_or_else(|| {
723            AppError::Internal(anyhow::anyhow!(
724                "missing chunk embeddings cache on multi-chunk ingest path"
725            ))
726        })?;
727        for (i, emb) in chunk_embeddings.iter().enumerate() {
728            storage_chunks::upsert_chunk_vec(&tx, i as i64, memory_id, i as i32, emb)?;
729        }
730    }
731
732    if !staged.entities.is_empty() || !staged.relationships.is_empty() {
733        for (idx, entity) in staged.entities.iter().enumerate() {
734            let entity_id = entities::upsert_entity(&tx, namespace, entity)?;
735            let entity_embedding = &staged.entity_embeddings[idx];
736            entities::upsert_entity_vec(
737                &tx,
738                entity_id,
739                namespace,
740                entity.entity_type,
741                entity_embedding,
742                &entity.name,
743            )?;
744            entities::link_memory_entity(&tx, memory_id, entity_id)?;
745            entities::increment_degree(&tx, entity_id)?;
746        }
747        let entity_types: std::collections::HashMap<&str, EntityType> = staged
748            .entities
749            .iter()
750            .map(|entity| (entity.name.as_str(), entity.entity_type))
751            .collect();
752        for rel in &staged.relationships {
753            let source_entity = NewEntity {
754                name: rel.source.clone(),
755                entity_type: entity_types
756                    .get(rel.source.as_str())
757                    .copied()
758                    .unwrap_or(EntityType::Concept),
759                description: None,
760            };
761            let target_entity = NewEntity {
762                name: rel.target.clone(),
763                entity_type: entity_types
764                    .get(rel.target.as_str())
765                    .copied()
766                    .unwrap_or(EntityType::Concept),
767                description: None,
768            };
769            let source_id = entities::upsert_entity(&tx, namespace, &source_entity)?;
770            let target_id = entities::upsert_entity(&tx, namespace, &target_entity)?;
771            let rel_id = entities::upsert_relationship(&tx, namespace, source_id, target_id, rel)?;
772            entities::link_memory_relationship(&tx, memory_id, rel_id)?;
773        }
774    }
775
776    tx.commit()?;
777
778    if !staged.urls.is_empty() {
779        let url_entries: Vec<storage_urls::MemoryUrl> = staged
780            .urls
781            .into_iter()
782            .map(|u| storage_urls::MemoryUrl {
783                url: u.url,
784                offset: Some(u.start as i64),
785            })
786            .collect();
787        let _ = storage_urls::insert_urls(conn, memory_id, &url_entries);
788    }
789
790    Ok(FileSuccess {
791        memory_id,
792        action: "created".to_string(),
793        body_length: new_memory.body.len(),
794    })
795}
796
797// ---------------------------------------------------------------------------
798// G20: mode-conditional flag validation
799// ---------------------------------------------------------------------------
800
801/// True when a scalar value matches its declared default. Local
802/// re-declaration (also defined in ) to keep this module
803/// self-contained for the G20 fix.
804fn is_at_default<T: PartialEq>(value: T, default: T) -> bool {
805    value == default
806}
807
808/// G20: validate that flags for one LLM provider were not passed when
809/// the operator selected a different provider (or no provider). Flags
810/// silently discarded by the wrong mode are surfaced as
811///  BEFORE any DB work, so the operator gets
812/// an actionable error instead of a surprise at runtime.
813///
814/// Mode-specific matrices:
815/// - `mode=none` and `mode=gliner` reject: claude_binary, claude_model,
816///   claude_timeout!=300, max_cost_usd, resume, retry_failed, keep_queue,
817///   codex_binary, codex_model, codex_timeout!=300, gliner_variant (if
818///   --enable-ner is false)
819/// - `mode=claude-code` rejects: codex_binary, codex_model, codex_timeout!=300
820/// - `mode=codex` rejects: claude_binary, claude_model, claude_timeout!=300,
821///   max_cost_usd, resume, retry_failed, keep_queue
822fn validate_mode_conditional_flags_ingest(args: &IngestArgs) -> Result<(), AppError> {
823    const DEFAULT_TIMEOUT: u64 = 300;
824    const DEFAULT_RATE_LIMIT_WAIT: u64 = 60;
825
826    let mut conflicts: Vec<String> = Vec::new();
827
828    let is_local_mode = args.mode == IngestMode::None || args.mode == IngestMode::Gliner;
829
830    if is_local_mode {
831        if args.claude_binary.is_some() {
832            conflicts.push("--claude-binary is ignored when --mode is none or gliner".to_string());
833        }
834        if args.claude_model.is_some() {
835            conflicts.push("--claude-model is ignored when --mode is none or gliner".to_string());
836        }
837        if !is_at_default(args.claude_timeout, DEFAULT_TIMEOUT) {
838            conflicts.push(format!(
839                "--claude-timeout={} is ignored when --mode is none or gliner (remove the flag to use the default 300s)",
840                args.claude_timeout
841            ));
842        }
843        if args.codex_binary.is_some() {
844            conflicts.push("--codex-binary is ignored when --mode is none or gliner".to_string());
845        }
846        if args.codex_model.is_some() {
847            conflicts.push("--codex-model is ignored when --mode is none or gliner".to_string());
848        }
849        if !is_at_default(args.codex_timeout, DEFAULT_TIMEOUT) {
850            conflicts.push(format!(
851                "--codex-timeout={} is ignored when --mode is none or gliner (remove the flag to use the default 300s)",
852                args.codex_timeout
853            ));
854        }
855        if args.max_cost_usd.is_some() {
856            conflicts.push("--max-cost-usd is ignored when --mode is none or gliner (cost is only tracked for LLM-backed modes)".to_string());
857        }
858        if args.resume {
859            conflicts.push("--resume is ignored when --mode is none or gliner (the queue DB is only used by LLM-backed modes)".to_string());
860        }
861        if args.retry_failed {
862            conflicts.push("--retry-failed is ignored when --mode is none or gliner".to_string());
863        }
864        if args.keep_queue {
865            conflicts.push("--keep-queue is ignored when --mode is none or gliner".to_string());
866        }
867        if !is_at_default(args.rate_limit_wait, DEFAULT_RATE_LIMIT_WAIT) {
868            conflicts.push(format!(
869                "--rate-limit-wait={} is ignored when --mode is none or gliner",
870                args.rate_limit_wait
871            ));
872        }
873    }
874
875    match args.mode {
876        IngestMode::ClaudeCode => {
877            if args.codex_binary.is_some() {
878                conflicts.push("--codex-binary is ignored when --mode=claude-code".to_string());
879            }
880            if args.codex_model.is_some() {
881                conflicts.push("--codex-model is ignored when --mode=claude-code".to_string());
882            }
883            if !is_at_default(args.codex_timeout, DEFAULT_TIMEOUT) {
884                conflicts.push(format!(
885                    "--codex-timeout={} is ignored when --mode=claude-code (remove the flag to use the default 300s)",
886                    args.codex_timeout
887                ));
888            }
889        }
890        IngestMode::Codex => {
891            if args.claude_binary.is_some() {
892                conflicts.push("--claude-binary is ignored when --mode=codex".to_string());
893            }
894            if args.claude_model.is_some() {
895                conflicts.push("--claude-model is ignored when --mode=codex".to_string());
896            }
897            if !is_at_default(args.claude_timeout, DEFAULT_TIMEOUT) {
898                conflicts.push(format!(
899                    "--claude-timeout={} is ignored when --mode=codex (remove the flag to use the default 300s)",
900                    args.claude_timeout
901                ));
902            }
903            if args.max_cost_usd.is_some() {
904                conflicts.push(
905                    "--max-cost-usd is ignored when --mode=codex (OAuth-first; cost is metered by your subscription)"
906                        .to_string(),
907                );
908            }
909            if args.resume {
910                conflicts.push("--resume is only valid for --mode=claude-code".to_string());
911            }
912            if args.retry_failed {
913                conflicts.push("--retry-failed is only valid for --mode=claude-code".to_string());
914            }
915            if args.keep_queue {
916                conflicts.push("--keep-queue is only valid for --mode=claude-code".to_string());
917            }
918        }
919        IngestMode::None | IngestMode::Gliner => {}
920    }
921
922    if !conflicts.is_empty() {
923        return Err(AppError::Validation(format!(
924            "G20: mode-conditional flag conflicts detected for --mode={:?}:\n  - {}",
925            args.mode,
926            conflicts.join("\n  - ")
927        )));
928    }
929
930    Ok(())
931}
932
933// ---------------------------------------------------------------------------
934
935#[tracing::instrument(skip_all, level = "debug", name = "ingest")]
936pub fn run(args: IngestArgs) -> Result<(), AppError> {
937    // G20: mode-conditional flag validation BEFORE any DB access.
938    // Surfaces flags that the wrong mode would silently discard.
939    validate_mode_conditional_flags_ingest(&args)?;
940    tracing::debug!(target: "ingest", dir = %args.dir.display(), mode = ?args.mode, "starting ingest");
941    if args.mode == IngestMode::ClaudeCode {
942        return super::ingest_claude::run_claude_ingest(&args);
943    }
944    if args.mode == IngestMode::Codex {
945        return super::ingest_codex::run_codex_ingest(&args);
946    }
947
948    let started = std::time::Instant::now();
949
950    if !args.dir.exists() {
951        return Err(AppError::Validation(format!(
952            "directory not found: {}",
953            args.dir.display()
954        )));
955    }
956    if !args.dir.is_dir() {
957        return Err(AppError::Validation(format!(
958            "path is not a directory: {}",
959            args.dir.display()
960        )));
961    }
962
963    let mut files: Vec<PathBuf> = Vec::with_capacity(128);
964    collect_files(&args.dir, &args.pattern, args.recursive, &mut files)?;
965    files.sort_unstable();
966
967    if files.len() > args.max_files {
968        return Err(AppError::Validation(format!(
969            "found {} files matching pattern, exceeds --max-files cap of {} (raise the cap or narrow the pattern)",
970            files.len(),
971            args.max_files
972        )));
973    }
974
975    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
976    let memory_type_str = args.r#type.as_str().to_string();
977
978    let paths = AppPaths::resolve(args.db.as_deref())?;
979    let mut conn_or_err = match init_storage(&paths) {
980        Ok(c) => Ok(c),
981        Err(e) => Err(format!("{e}")),
982    };
983
984    let mut succeeded: usize = 0;
985    let mut failed: usize = 0;
986    let mut skipped: usize = 0;
987    let total = files.len();
988
989    // Pre-resolve all names before parallelisation so Phase A workers see a
990    // consistent, immutable name assignment (v1.0.31 A10 contract preserved).
991    let mut taken_names: BTreeSet<String> = BTreeSet::new();
992
993    // SlotMeta: per-slot output metadata retained on the main thread for NDJSON.
994    // ProcessItem: the data moved into the producer thread for Phase A computation.
995    // We split these so `slots_meta` (non-Send BTreeSet-dependent) stays on main
996    // thread while `process_items` (Send: only PathBuf + String) crosses the thread
997    // boundary into the rayon producer.
998    enum SlotMeta {
999        Skip {
1000            file_str: String,
1001            derived_base: String,
1002            name_truncated: bool,
1003            original_name: Option<String>,
1004            original_filename: Option<String>,
1005            reason: String,
1006        },
1007        Process {
1008            file_str: String,
1009            derived_name: String,
1010            name_truncated: bool,
1011            original_name: Option<String>,
1012            original_filename: Option<String>,
1013        },
1014    }
1015
1016    struct ProcessItem {
1017        idx: usize,
1018        path: PathBuf,
1019        file_str: String,
1020        derived_name: String,
1021    }
1022
1023    let files_cap = files.len();
1024    let mut slots_meta: Vec<SlotMeta> = Vec::new();
1025    slots_meta.try_reserve(files_cap).map_err(|_| {
1026        AppError::LimitExceeded(format!(
1027            "allocation of {files_cap} slot metadata entries would exceed available memory"
1028        ))
1029    })?;
1030    let mut process_items: Vec<ProcessItem> = Vec::new();
1031    process_items.try_reserve(files_cap).map_err(|_| {
1032        AppError::LimitExceeded(format!(
1033            "allocation of {files_cap} process items would exceed available memory"
1034        ))
1035    })?;
1036    let mut truncations: Vec<(String, String)> = Vec::new();
1037    truncations.try_reserve(files_cap).map_err(|_| {
1038        AppError::LimitExceeded(format!(
1039            "allocation of {files_cap} truncation entries would exceed available memory"
1040        ))
1041    })?;
1042
1043    let max_name_length = args.max_name_length;
1044    for path in &files {
1045        let file_str = path.to_string_lossy().into_owned();
1046        let (derived_base, name_truncated, original_name) =
1047            derive_kebab_name(path, max_name_length);
1048        let original_basename = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1049
1050        if name_truncated {
1051            if let Some(ref orig) = original_name {
1052                truncations.push((orig.clone(), derived_base.clone()));
1053            }
1054        }
1055
1056        if derived_base.is_empty() {
1057            // original_filename: always include when it differs from the empty derived name
1058            let orig_filename = if !original_basename.is_empty() {
1059                Some(original_basename.to_string())
1060            } else {
1061                None
1062            };
1063            slots_meta.push(SlotMeta::Skip {
1064                file_str,
1065                derived_base: String::new(),
1066                name_truncated: false,
1067                original_name: None,
1068                original_filename: orig_filename,
1069                reason: "could not derive a non-empty kebab-case name from filename".to_string(),
1070            });
1071            continue;
1072        }
1073
1074        match unique_name(&derived_base, &taken_names) {
1075            Ok(derived_name) => {
1076                taken_names.insert(derived_name.clone());
1077                let idx = slots_meta.len();
1078                // original_filename: present only when the raw basename differs from the derived name
1079                let orig_filename = if original_basename != derived_name {
1080                    Some(original_basename.to_string())
1081                } else {
1082                    None
1083                };
1084                process_items.push(ProcessItem {
1085                    idx,
1086                    path: path.clone(),
1087                    file_str: file_str.clone(),
1088                    derived_name: derived_name.clone(),
1089                });
1090                slots_meta.push(SlotMeta::Process {
1091                    file_str,
1092                    derived_name,
1093                    name_truncated,
1094                    original_name,
1095                    original_filename: orig_filename,
1096                });
1097            }
1098            Err(e) => {
1099                let orig_filename = if original_basename != derived_base {
1100                    Some(original_basename.to_string())
1101                } else {
1102                    None
1103                };
1104                slots_meta.push(SlotMeta::Skip {
1105                    file_str,
1106                    derived_base,
1107                    name_truncated,
1108                    original_name,
1109                    original_filename: orig_filename,
1110                    reason: e.to_string(),
1111                });
1112            }
1113        }
1114    }
1115
1116    if !truncations.is_empty() {
1117        tracing::info!(
1118            target: "ingest",
1119            count = truncations.len(),
1120            max_name_length = max_name_length,
1121            max_len = DERIVED_NAME_MAX_LEN,
1122            "derived names truncated; pass -vv (debug) for per-file detail"
1123        );
1124    }
1125
1126    // --dry-run: emit preview events and exit before loading ONNX or touching DB.
1127    if args.dry_run {
1128        for meta in &slots_meta {
1129            match meta {
1130                SlotMeta::Skip {
1131                    file_str,
1132                    derived_base,
1133                    name_truncated,
1134                    original_name,
1135                    original_filename,
1136                    reason,
1137                } => {
1138                    output::emit_json_compact(&IngestFileEvent {
1139                        file: file_str,
1140                        name: derived_base,
1141                        status: "skip",
1142                        truncated: *name_truncated,
1143                        original_name: original_name.clone(),
1144                        original_filename: original_filename.as_deref(),
1145                        error: Some(reason.clone()),
1146                        memory_id: None,
1147                        action: None,
1148                        body_length: 0,
1149                    })?;
1150                }
1151                SlotMeta::Process {
1152                    file_str,
1153                    derived_name,
1154                    name_truncated,
1155                    original_name,
1156                    original_filename,
1157                } => {
1158                    output::emit_json_compact(&IngestFileEvent {
1159                        file: file_str,
1160                        name: derived_name,
1161                        status: "preview",
1162                        truncated: *name_truncated,
1163                        original_name: original_name.clone(),
1164                        original_filename: original_filename.as_deref(),
1165                        error: None,
1166                        memory_id: None,
1167                        action: None,
1168                        body_length: 0,
1169                    })?;
1170                }
1171            }
1172        }
1173        output::emit_json_compact(&IngestSummary {
1174            summary: true,
1175            dir: args.dir.to_string_lossy().into_owned(),
1176            pattern: args.pattern.clone(),
1177            recursive: args.recursive,
1178            files_total: total,
1179            files_succeeded: 0,
1180            files_failed: 0,
1181            files_skipped: 0,
1182            elapsed_ms: started.elapsed().as_millis() as u64,
1183        })?;
1184        return Ok(());
1185    }
1186
1187    // Reject contradictory flag combination: explicit parallelism > 1 with --low-memory.
1188    if args.low_memory {
1189        if let Some(n) = args.ingest_parallelism {
1190            if n > 1 {
1191                return Err(AppError::Validation(
1192                    "--ingest-parallelism N>1 conflicts with --low-memory; use one or the other"
1193                        .to_string(),
1194                ));
1195            }
1196        }
1197    }
1198
1199    // Determine rayon thread pool size, honoring --low-memory and the
1200    // SQLITE_GRAPHRAG_LOW_MEMORY env var (both force parallelism = 1).
1201    let parallelism = resolve_parallelism(args.low_memory, args.ingest_parallelism);
1202
1203    let pool = rayon::ThreadPoolBuilder::new()
1204        .num_threads(parallelism)
1205        .build()
1206        .map_err(|e| AppError::Internal(anyhow::anyhow!("rayon pool: {e}")))?;
1207
1208    if args.enable_ner && args.skip_extraction {
1209        return Err(AppError::Validation(
1210            "--enable-ner and --skip-extraction are mutually exclusive; remove one".to_string(),
1211        ));
1212    }
1213    if args.skip_extraction && !args.enable_ner {
1214        // v1.0.74: revert to v1.0.45 hidden no-op behavior. The v1.0.67
1215        // commit (9ddb17b) promoted this to a hard validation error, which
1216        // broke the "kept as a hidden no-op for backwards compatibility"
1217        // promise documented in CHANGELOG v1.0.45 and started failing
1218        // 5+ CI jobs whose E2E tests use this flag to skip the
1219        // GLiNER-ONNX model download in CI environments.
1220        tracing::warn!(
1221            "--skip-extraction is deprecated since v1.0.45 and has no effect (NER is disabled by default); remove this flag to silence the warning"
1222        );
1223    }
1224    let enable_ner = args.enable_ner;
1225    let max_rss_mb = args.max_rss_mb;
1226    let llm_parallelism = args.llm_parallelism as usize;
1227    // v1.0.79: `--mode gliner` and `--gliner-variant` are no-ops kept for
1228    // compatibility (the GLiNER pipeline was removed); warn explicitly so
1229    // callers do not silently expect NER-quality extraction.
1230    if args.mode == IngestMode::Gliner {
1231        tracing::warn!(
1232            "--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"
1233        );
1234    }
1235    if args.gliner_variant != "fp32" {
1236        tracing::warn!(
1237            "--gliner-variant is deprecated and has no effect since v1.0.79 (the GLiNER pipeline was removed)"
1238        );
1239    }
1240    let gliner_variant: crate::extraction::GlinerVariant = match args.gliner_variant.as_str() {
1241        "int8" => crate::extraction::GlinerVariant::Int8,
1242        _ => crate::extraction::GlinerVariant::Fp32,
1243    };
1244
1245    let total_to_process = process_items.len();
1246    tracing::info!(
1247        target: "ingest",
1248        phase = "pipeline_start",
1249        files = total_to_process,
1250        ingest_parallelism = parallelism,
1251        "incremental pipeline starting: Phase A (rayon) → channel → Phase B (main thread)",
1252    );
1253
1254    // Bounded channel: producer never gets more than parallelism*2 items ahead of
1255    // the consumer, preventing memory blowup when Phase A is faster than Phase B.
1256    // Each message carries the slot index so Phase B can look up SlotMeta in order.
1257    let channel_bound = (parallelism * 2).max(1);
1258    let (tx, rx) = mpsc::sync_channel::<(usize, Result<StagedFile, AppError>)>(channel_bound);
1259
1260    // Phase A: launched in a dedicated OS thread so the main thread can consume
1261    // the channel concurrently. pool.install() blocks the calling thread until
1262    // all rayon workers finish — if called on the main thread it would
1263    // reintroduce the 2-phase blocking behaviour we are eliminating.
1264    let paths_owned = paths.clone();
1265    let producer_handle = std::thread::spawn(move || {
1266        pool.install(|| {
1267            process_items.into_par_iter().for_each(|item| {
1268                if crate::shutdown_requested() {
1269                    return;
1270                }
1271                let t0 = std::time::Instant::now();
1272                let result = stage_file(
1273                    item.idx,
1274                    &item.path,
1275                    &item.derived_name,
1276                    &paths_owned,
1277                    enable_ner,
1278                    gliner_variant,
1279                    max_rss_mb,
1280                    llm_parallelism,
1281                );
1282                let elapsed_ms = t0.elapsed().as_millis() as u64;
1283
1284                // Emit NDJSON progress event to stderr so the user sees work
1285                // happening during long NER runs (e.g. 50 files × 27s each).
1286                let (n_entities, n_relationships) = match &result {
1287                    Ok(sf) => (sf.entities.len(), sf.relationships.len()),
1288                    Err(_) => (0, 0),
1289                };
1290                let progress = StageProgressEvent {
1291                    schema_version: 1,
1292                    event: "file_extracted",
1293                    path: &item.file_str,
1294                    ms: elapsed_ms,
1295                    entities: n_entities,
1296                    relationships: n_relationships,
1297                };
1298                if let Ok(line) = serde_json::to_string(&progress) {
1299                    tracing::info!(target: "ingest_progress", "{}", line);
1300                }
1301
1302                // Blocking send applies backpressure: if Phase B is slower,
1303                // Phase A workers wait here instead of accumulating staged files
1304                // in memory. If the receiver is dropped (fail_fast abort), ignore.
1305                let _ = tx.send((item.idx, result));
1306            });
1307            // Explicit drop of tx signals Phase B (rx iteration) to stop.
1308            drop(tx);
1309        });
1310    });
1311
1312    // Phase B: main thread persists files as results arrive from the channel.
1313    // Results arrive in completion order (par_iter is unordered). We persist
1314    // each file immediately on arrival — this is the key fix for B1: with the
1315    // old 2-phase design the first DB write happened only after ALL files had
1316    // finished Phase A. Now the first commit happens as soon as the first file
1317    // completes Phase A, regardless of how many files remain.
1318    //
1319    // NDJSON output order follows completion order (not file-system sort order).
1320    // Skip slots are emitted at the end, after all Process results are consumed.
1321    // This trade-off is intentional: deterministic NDJSON ordering is a lesser
1322    // requirement than ensuring data is persisted before the user's timeout fires.
1323    let fail_fast = args.fail_fast;
1324
1325    // Emit pending Skip events first so agents see them early.
1326    for meta in &slots_meta {
1327        if let SlotMeta::Skip {
1328            file_str,
1329            derived_base,
1330            name_truncated,
1331            original_name,
1332            original_filename,
1333            reason,
1334        } = meta
1335        {
1336            output::emit_json_compact(&IngestFileEvent {
1337                file: file_str,
1338                name: derived_base,
1339                status: "skipped",
1340                truncated: *name_truncated,
1341                original_name: original_name.clone(),
1342                original_filename: original_filename.as_deref(),
1343                error: Some(reason.clone()),
1344                memory_id: None,
1345                action: None,
1346                body_length: 0,
1347            })?;
1348            skipped += 1;
1349        }
1350    }
1351
1352    // Build a quick index from slot index → SlotMeta reference for O(1) lookups
1353    // as channel messages arrive in completion order.
1354    let meta_index: std::collections::HashMap<usize, &SlotMeta> = slots_meta
1355        .iter()
1356        .enumerate()
1357        .filter(|(_, m)| matches!(m, SlotMeta::Process { .. }))
1358        .collect();
1359
1360    tracing::info!(
1361        target: "ingest",
1362        phase = "persist_start",
1363        files = total_to_process,
1364        "phase B starting: persisting files incrementally as Phase A completes each one",
1365    );
1366
1367    // Drain channel and persist each file immediately — no accumulation into a
1368    // HashMap. The bounded channel ensures Phase A cannot run too far ahead of
1369    // Phase B without applying backpressure.
1370    for (idx, stage_result) in rx {
1371        if crate::shutdown_requested() {
1372            tracing::info!(target: "ingest", "shutdown requested, stopping persistence loop");
1373            break;
1374        }
1375        let meta = meta_index.get(&idx).ok_or_else(|| {
1376            AppError::Internal(anyhow::anyhow!(
1377                "channel idx {idx} has no corresponding Process slot"
1378            ))
1379        })?;
1380        let (file_str, derived_name, name_truncated, original_name, original_filename) = match meta
1381        {
1382            SlotMeta::Process {
1383                file_str,
1384                derived_name,
1385                name_truncated,
1386                original_name,
1387                original_filename,
1388            } => (
1389                file_str,
1390                derived_name,
1391                name_truncated,
1392                original_name,
1393                original_filename,
1394            ),
1395            SlotMeta::Skip { .. } => unreachable!("channel only carries Process results"),
1396        };
1397
1398        // If storage init failed, every file fails with the same error.
1399        let conn = match conn_or_err.as_mut() {
1400            Ok(c) => c,
1401            Err(err_msg) => {
1402                let err_clone = err_msg.clone();
1403                output::emit_json_compact(&IngestFileEvent {
1404                    file: file_str,
1405                    name: derived_name,
1406                    status: "failed",
1407                    truncated: *name_truncated,
1408                    original_name: original_name.clone(),
1409                    original_filename: original_filename.as_deref(),
1410                    error: Some(err_clone.clone()),
1411                    memory_id: None,
1412                    action: None,
1413                    body_length: 0,
1414                })?;
1415                failed += 1;
1416                if fail_fast {
1417                    output::emit_json_compact(&IngestSummary {
1418                        summary: true,
1419                        dir: args.dir.display().to_string(),
1420                        pattern: args.pattern.clone(),
1421                        recursive: args.recursive,
1422                        files_total: total,
1423                        files_succeeded: succeeded,
1424                        files_failed: failed,
1425                        files_skipped: skipped,
1426                        elapsed_ms: started.elapsed().as_millis() as u64,
1427                    })?;
1428                    return Err(AppError::Validation(format!(
1429                        "ingest aborted on first failure: {err_clone}"
1430                    )));
1431                }
1432                continue;
1433            }
1434        };
1435
1436        let outcome =
1437            stage_result.and_then(|sf| persist_staged(conn, &namespace, &memory_type_str, sf));
1438
1439        match outcome {
1440            Ok(FileSuccess {
1441                memory_id,
1442                action,
1443                body_length,
1444            }) => {
1445                output::emit_json_compact(&IngestFileEvent {
1446                    file: file_str,
1447                    name: derived_name,
1448                    status: "indexed",
1449                    truncated: *name_truncated,
1450                    original_name: original_name.clone(),
1451                    original_filename: original_filename.as_deref(),
1452                    error: None,
1453                    memory_id: Some(memory_id),
1454                    action: Some(action),
1455                    body_length,
1456                })?;
1457                succeeded += 1;
1458            }
1459            Err(ref e) if matches!(e, AppError::Duplicate(_)) => {
1460                output::emit_json_compact(&IngestFileEvent {
1461                    file: file_str,
1462                    name: derived_name,
1463                    status: "skipped",
1464                    truncated: *name_truncated,
1465                    original_name: original_name.clone(),
1466                    original_filename: original_filename.as_deref(),
1467                    error: Some(format!("{e}")),
1468                    memory_id: None,
1469                    action: Some("duplicate".to_string()),
1470                    body_length: 0,
1471                })?;
1472                skipped += 1;
1473            }
1474            Err(e) => {
1475                let err_msg = format!("{e}");
1476                output::emit_json_compact(&IngestFileEvent {
1477                    file: file_str,
1478                    name: derived_name,
1479                    status: "failed",
1480                    truncated: *name_truncated,
1481                    original_name: original_name.clone(),
1482                    original_filename: original_filename.as_deref(),
1483                    error: Some(err_msg.clone()),
1484                    memory_id: None,
1485                    action: None,
1486                    body_length: 0,
1487                })?;
1488                failed += 1;
1489                if fail_fast {
1490                    output::emit_json_compact(&IngestSummary {
1491                        summary: true,
1492                        dir: args.dir.display().to_string(),
1493                        pattern: args.pattern.clone(),
1494                        recursive: args.recursive,
1495                        files_total: total,
1496                        files_succeeded: succeeded,
1497                        files_failed: failed,
1498                        files_skipped: skipped,
1499                        elapsed_ms: started.elapsed().as_millis() as u64,
1500                    })?;
1501                    return Err(AppError::Validation(format!(
1502                        "ingest aborted on first failure: {err_msg}"
1503                    )));
1504                }
1505            }
1506        }
1507    }
1508
1509    // Wait for the producer thread to finish cleanly.
1510    producer_handle
1511        .join()
1512        .map_err(|_| AppError::Internal(anyhow::anyhow!("ingest producer thread panicked")))?;
1513
1514    if let Ok(ref conn) = conn_or_err {
1515        if succeeded > 0 {
1516            let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1517        }
1518    }
1519
1520    output::emit_json_compact(&IngestSummary {
1521        summary: true,
1522        dir: args.dir.display().to_string(),
1523        pattern: args.pattern.clone(),
1524        recursive: args.recursive,
1525        files_total: total,
1526        files_succeeded: succeeded,
1527        files_failed: failed,
1528        files_skipped: skipped,
1529        elapsed_ms: started.elapsed().as_millis() as u64,
1530    })?;
1531
1532    Ok(())
1533}
1534
1535/// Auto-initialises the database (matches the contract of every other CRUD
1536/// handler) and returns a fresh read/write connection ready for the ingest
1537/// loop. Errors here are recoverable per-file: the caller surfaces them as
1538/// failure events so `--fail-fast` and the continue-on-error path keep
1539/// working when, for example, the user points `--db` at an unwritable path.
1540fn init_storage(paths: &AppPaths) -> Result<Connection, AppError> {
1541    ensure_db_ready(paths)?;
1542    let conn = open_rw(&paths.db)?;
1543    Ok(conn)
1544}
1545
1546pub(crate) fn collect_files(
1547    dir: &Path,
1548    pattern: &str,
1549    recursive: bool,
1550    out: &mut Vec<PathBuf>,
1551) -> Result<(), AppError> {
1552    let entries = std::fs::read_dir(dir).map_err(AppError::Io)?;
1553    for entry in entries {
1554        let entry = entry.map_err(AppError::Io)?;
1555        let path = entry.path();
1556        let file_type = entry.file_type().map_err(AppError::Io)?;
1557        if file_type.is_file() {
1558            let name = entry.file_name();
1559            let name_str = name.to_string_lossy();
1560            if matches_pattern(&name_str, pattern) {
1561                out.push(path);
1562            }
1563        } else if file_type.is_dir() && recursive {
1564            collect_files(&path, pattern, recursive, out)?;
1565        }
1566    }
1567    Ok(())
1568}
1569
1570fn matches_pattern(name: &str, pattern: &str) -> bool {
1571    if let Some(suffix) = pattern.strip_prefix('*') {
1572        name.ends_with(suffix)
1573    } else if let Some(prefix) = pattern.strip_suffix('*') {
1574        name.starts_with(prefix)
1575    } else {
1576        name == pattern
1577    }
1578}
1579
1580/// Returns `(final_name, truncated, original_name)`.
1581/// `truncated` is true when the derived name exceeded `max_len`.
1582/// `original_name` holds the pre-truncation name only when `truncated=true`.
1583///
1584/// Non-ASCII characters are first decomposed via NFD and then stripped of
1585/// combining marks so accented letters fold to their base ASCII letter
1586/// (e.g. `acai` from accented input, `naive` from diaeresis). Characters with no ASCII
1587/// fallback (emoji, CJK ideographs, symbols) are dropped silently. This
1588/// preserves meaningful word content rather than collapsing the basename
1589/// to a few stray ASCII letters as the previous filter did.
1590pub(crate) fn derive_kebab_name(path: &Path, max_len: usize) -> (String, bool, Option<String>) {
1591    let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
1592    let lowered: String = stem
1593        .nfd()
1594        .filter(|c| !unicode_normalization::char::is_combining_mark(*c))
1595        .map(|c| {
1596            if c == '_' || c.is_whitespace() {
1597                '-'
1598            } else {
1599                c
1600            }
1601        })
1602        .map(|c| c.to_ascii_lowercase())
1603        .filter(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == '-')
1604        .collect();
1605    let collapsed = collapse_dashes(&lowered);
1606    let trimmed_raw = collapsed.trim_matches('-').to_string();
1607    // Prefix names that start with a digit to keep them valid kebab-case identifiers.
1608    let trimmed = if trimmed_raw.starts_with(|c: char| c.is_ascii_digit()) {
1609        format!("doc-{trimmed_raw}")
1610    } else {
1611        trimmed_raw
1612    };
1613    if trimmed.len() > max_len {
1614        let truncated = trimmed[..max_len].trim_matches('-').to_string();
1615        tracing::debug!(
1616            target: "ingest",
1617            original = %trimmed,
1618            truncated_to = %truncated,
1619            max_len = max_len,
1620            "derived memory name truncated to fit length cap; collisions will be resolved with numeric suffixes"
1621        );
1622        (truncated, true, Some(trimmed))
1623    } else {
1624        (trimmed, false, None)
1625    }
1626}
1627
1628/// v1.0.31 A10: returns the first non-colliding kebab name by appending a
1629/// numeric suffix (`-1`, `-2`, …) when needed.
1630///
1631/// `taken` is the set of names already consumed in the current ingest run.
1632/// The caller is expected to insert the returned name into `taken` so the
1633/// next call observes the consumption. Cross-run collisions are intentionally
1634/// surfaced by the per-file persistence path as duplicates so re-ingestion
1635/// of identical corpora stays idempotent.
1636///
1637/// Returns `Err(AppError::Validation)` after `MAX_NAME_COLLISION_SUFFIX`
1638/// candidates collide, signalling a pathological corpus that should be
1639/// renamed manually.
1640fn unique_name(base: &str, taken: &BTreeSet<String>) -> Result<String, AppError> {
1641    if !taken.contains(base) {
1642        return Ok(base.to_string());
1643    }
1644    for suffix in 1..=MAX_NAME_COLLISION_SUFFIX {
1645        let candidate = format!("{base}-{suffix}");
1646        if !taken.contains(&candidate) {
1647            tracing::warn!(
1648                target: "ingest",
1649                base = %base,
1650                resolved = %candidate,
1651                suffix,
1652                "memory name collision resolved with numeric suffix"
1653            );
1654            return Ok(candidate);
1655        }
1656    }
1657    Err(AppError::Validation(format!(
1658        "too many name collisions for base '{base}' (>{MAX_NAME_COLLISION_SUFFIX}); rename source files to disambiguate"
1659    )))
1660}
1661
1662fn collapse_dashes(s: &str) -> String {
1663    let mut out = String::with_capacity(s.len());
1664    let mut prev_dash = false;
1665    for c in s.chars() {
1666        if c == '-' {
1667            if !prev_dash {
1668                out.push('-');
1669            }
1670            prev_dash = true;
1671        } else {
1672            out.push(c);
1673            prev_dash = false;
1674        }
1675    }
1676    out
1677}
1678
1679#[cfg(test)]
1680mod tests {
1681    use super::*;
1682    use std::path::PathBuf;
1683
1684    #[test]
1685    fn matches_pattern_suffix() {
1686        assert!(matches_pattern("foo.md", "*.md"));
1687        assert!(!matches_pattern("foo.txt", "*.md"));
1688        assert!(matches_pattern("foo.md", "*"));
1689    }
1690
1691    #[test]
1692    fn matches_pattern_prefix() {
1693        assert!(matches_pattern("README.md", "README*"));
1694        assert!(!matches_pattern("CHANGELOG.md", "README*"));
1695    }
1696
1697    #[test]
1698    fn matches_pattern_exact() {
1699        assert!(matches_pattern("README.md", "README.md"));
1700        assert!(!matches_pattern("readme.md", "README.md"));
1701    }
1702
1703    #[test]
1704    fn derive_kebab_underscore_to_dash() {
1705        let p = PathBuf::from("/tmp/claude_code_headless.md");
1706        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1707        assert_eq!(name, "claude-code-headless");
1708        assert!(!truncated);
1709        assert!(original.is_none());
1710    }
1711
1712    #[test]
1713    fn derive_kebab_uppercase_lowered() {
1714        let p = PathBuf::from("/tmp/README.md");
1715        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1716        assert_eq!(name, "readme");
1717        assert!(!truncated);
1718        assert!(original.is_none());
1719    }
1720
1721    #[test]
1722    fn derive_kebab_strips_non_kebab_chars() {
1723        let p = PathBuf::from("/tmp/some@weird#name!.md");
1724        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1725        assert_eq!(name, "someweirdname");
1726        assert!(!truncated);
1727        assert!(original.is_none());
1728    }
1729
1730    // Bug M-A3: NFD-based unicode normalization preserves base letters of
1731    // accented characters instead of dropping them entirely.
1732    #[test]
1733    fn derive_kebab_folds_accented_letters_to_ascii() {
1734        let p = PathBuf::from("/tmp/açaí.md");
1735        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1736        assert_eq!(name, "acai", "got '{name}'");
1737    }
1738
1739    #[test]
1740    fn derive_kebab_handles_naive_with_diaeresis() {
1741        let p = PathBuf::from("/tmp/naïve-test.md");
1742        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1743        assert_eq!(name, "naive-test", "got '{name}'");
1744    }
1745
1746    #[test]
1747    fn derive_kebab_drops_emoji_keeps_word() {
1748        let p = PathBuf::from("/tmp/🚀-rocket.md");
1749        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1750        assert_eq!(name, "rocket", "got '{name}'");
1751    }
1752
1753    #[test]
1754    fn derive_kebab_mixed_unicode_emoji_keeps_letters() {
1755        let p = PathBuf::from("/tmp/açaí🦜.md");
1756        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1757        assert_eq!(name, "acai", "got '{name}'");
1758    }
1759
1760    #[test]
1761    fn derive_kebab_pure_emoji_yields_empty() {
1762        let p = PathBuf::from("/tmp/🦜🚀🌟.md");
1763        let (name, _, _) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1764        assert!(name.is_empty(), "got '{name}'");
1765    }
1766
1767    #[test]
1768    fn derive_kebab_collapses_consecutive_dashes() {
1769        let p = PathBuf::from("/tmp/a__b___c.md");
1770        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1771        assert_eq!(name, "a-b-c");
1772        assert!(!truncated);
1773        assert!(original.is_none());
1774    }
1775
1776    #[test]
1777    fn derive_kebab_truncates_to_60_chars() {
1778        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(80)));
1779        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1780        assert!(name.len() <= 60, "got len {}", name.len());
1781        assert!(truncated);
1782        assert!(original.is_some());
1783        assert!(original.unwrap().len() > 60);
1784    }
1785
1786    #[test]
1787    fn collect_files_finds_md_files() {
1788        let tmp = tempfile::tempdir().expect("tempdir");
1789        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1790        std::fs::write(tmp.path().join("b.md"), "y").unwrap();
1791        std::fs::write(tmp.path().join("c.txt"), "z").unwrap();
1792        let mut out = Vec::new();
1793        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1794        assert_eq!(out.len(), 2, "should find 2 .md files, got {out:?}");
1795    }
1796
1797    #[test]
1798    fn collect_files_recursive_descends_subdirs() {
1799        let tmp = tempfile::tempdir().expect("tempdir");
1800        let sub = tmp.path().join("sub");
1801        std::fs::create_dir(&sub).unwrap();
1802        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1803        std::fs::write(sub.join("b.md"), "y").unwrap();
1804        let mut out = Vec::new();
1805        collect_files(tmp.path(), "*.md", true, &mut out).expect("collect");
1806        assert_eq!(out.len(), 2);
1807    }
1808
1809    #[test]
1810    fn collect_files_non_recursive_skips_subdirs() {
1811        let tmp = tempfile::tempdir().expect("tempdir");
1812        let sub = tmp.path().join("sub");
1813        std::fs::create_dir(&sub).unwrap();
1814        std::fs::write(tmp.path().join("a.md"), "x").unwrap();
1815        std::fs::write(sub.join("b.md"), "y").unwrap();
1816        let mut out = Vec::new();
1817        collect_files(tmp.path(), "*.md", false, &mut out).expect("collect");
1818        assert_eq!(out.len(), 1);
1819    }
1820
1821    // ── v1.0.31 A10: name truncation warns and collisions are auto-resolved ──
1822
1823    #[test]
1824    fn derive_kebab_long_basename_truncated_within_cap() {
1825        let p = PathBuf::from(format!("/tmp/{}.md", "a".repeat(120)));
1826        let (name, truncated, original) = derive_kebab_name(&p, DERIVED_NAME_MAX_LEN);
1827        assert!(
1828            name.len() <= DERIVED_NAME_MAX_LEN,
1829            "truncated name must respect cap; got {} chars",
1830            name.len()
1831        );
1832        assert!(!name.is_empty());
1833        assert!(truncated);
1834        assert!(original.is_some());
1835    }
1836
1837    #[test]
1838    fn unique_name_returns_base_when_free() {
1839        let taken: BTreeSet<String> = BTreeSet::new();
1840        let resolved = unique_name("note", &taken).expect("must resolve");
1841        assert_eq!(resolved, "note");
1842    }
1843
1844    #[test]
1845    fn unique_name_appends_first_free_suffix_on_collision() {
1846        let mut taken: BTreeSet<String> = BTreeSet::new();
1847        taken.insert("note".to_string());
1848        taken.insert("note-1".to_string());
1849        let resolved = unique_name("note", &taken).expect("must resolve");
1850        assert_eq!(resolved, "note-2");
1851    }
1852
1853    #[test]
1854    fn unique_name_errors_after_collision_cap() {
1855        let mut taken: BTreeSet<String> = BTreeSet::new();
1856        taken.insert("note".to_string());
1857        for i in 1..=MAX_NAME_COLLISION_SUFFIX {
1858            taken.insert(format!("note-{i}"));
1859        }
1860        let err = unique_name("note", &taken).expect_err("must surface error");
1861        assert!(matches!(err, AppError::Validation(_)));
1862    }
1863
1864    // ── v1.0.32 Onda 4B: in-process pipeline validation ──
1865
1866    #[test]
1867    fn validate_relation_format_accepts_valid_relations() {
1868        use crate::parsers::{is_canonical_relation, validate_relation_format};
1869        assert!(validate_relation_format("applies_to").is_ok());
1870        assert!(validate_relation_format("depends_on").is_ok());
1871        assert!(validate_relation_format("implements").is_ok());
1872        assert!(validate_relation_format("").is_err());
1873        assert!(is_canonical_relation("applies_to"));
1874        assert!(!is_canonical_relation("implements"));
1875    }
1876
1877    // ── v1.0.40 H-A1: --low-memory flag and SQLITE_GRAPHRAG_LOW_MEMORY env var ──
1878
1879    use serial_test::serial;
1880
1881    /// Helper: scrubs the env var around a closure to keep tests deterministic.
1882    fn with_env_var<F: FnOnce()>(value: Option<&str>, f: F) {
1883        let key = "SQLITE_GRAPHRAG_LOW_MEMORY";
1884        let prev = std::env::var(key).ok();
1885        match value {
1886            Some(v) => std::env::set_var(key, v),
1887            None => std::env::remove_var(key),
1888        }
1889        f();
1890        match prev {
1891            Some(p) => std::env::set_var(key, p),
1892            None => std::env::remove_var(key),
1893        }
1894    }
1895
1896    #[test]
1897    #[serial]
1898    fn env_low_memory_enabled_unset_returns_false() {
1899        with_env_var(None, || assert!(!env_low_memory_enabled()));
1900    }
1901
1902    #[test]
1903    #[serial]
1904    fn env_low_memory_enabled_empty_returns_false() {
1905        with_env_var(Some(""), || assert!(!env_low_memory_enabled()));
1906    }
1907
1908    #[test]
1909    #[serial]
1910    fn env_low_memory_enabled_truthy_values_return_true() {
1911        for v in ["1", "true", "TRUE", "yes", "YES", "on", "On"] {
1912            with_env_var(Some(v), || {
1913                assert!(env_low_memory_enabled(), "value {v:?} should be truthy")
1914            });
1915        }
1916    }
1917
1918    #[test]
1919    #[serial]
1920    fn env_low_memory_enabled_falsy_values_return_false() {
1921        for v in ["0", "false", "FALSE", "no", "off"] {
1922            with_env_var(Some(v), || {
1923                assert!(!env_low_memory_enabled(), "value {v:?} should be falsy")
1924            });
1925        }
1926    }
1927
1928    #[test]
1929    #[serial]
1930    fn env_low_memory_enabled_unrecognized_value_returns_false() {
1931        with_env_var(Some("maybe"), || assert!(!env_low_memory_enabled()));
1932    }
1933
1934    #[test]
1935    #[serial]
1936    fn resolve_parallelism_flag_forces_one_overriding_explicit_value() {
1937        with_env_var(None, || {
1938            assert_eq!(resolve_parallelism(true, Some(4)), 1);
1939            assert_eq!(resolve_parallelism(true, Some(8)), 1);
1940            assert_eq!(resolve_parallelism(true, None), 1);
1941        });
1942    }
1943
1944    #[test]
1945    #[serial]
1946    fn resolve_parallelism_env_forces_one_when_flag_off() {
1947        with_env_var(Some("1"), || {
1948            assert_eq!(resolve_parallelism(false, Some(4)), 1);
1949            assert_eq!(resolve_parallelism(false, None), 1);
1950        });
1951    }
1952
1953    #[test]
1954    #[serial]
1955    fn resolve_parallelism_falsy_env_does_not_override() {
1956        with_env_var(Some("0"), || {
1957            assert_eq!(resolve_parallelism(false, Some(4)), 4);
1958        });
1959    }
1960
1961    #[test]
1962    #[serial]
1963    fn resolve_parallelism_explicit_value_when_low_memory_off() {
1964        with_env_var(None, || {
1965            assert_eq!(resolve_parallelism(false, Some(3)), 3);
1966            assert_eq!(resolve_parallelism(false, Some(1)), 1);
1967        });
1968    }
1969
1970    #[test]
1971    #[serial]
1972    fn resolve_parallelism_default_when_unset() {
1973        with_env_var(None, || {
1974            let p = resolve_parallelism(false, None);
1975            assert!((1..=4).contains(&p), "default must be in [1, 4]; got {p}");
1976        });
1977    }
1978
1979    #[test]
1980    fn ingest_args_parses_low_memory_flag_via_clap() {
1981        use clap::Parser;
1982        // Parse a synthetic Cli that contains the `ingest` subcommand. We rely
1983        // on the public `Cli` definition so the flag is wired end-to-end.
1984        let cli = crate::cli::Cli::try_parse_from([
1985            "sqlite-graphrag",
1986            "ingest",
1987            "/tmp/dummy",
1988            "--type",
1989            "document",
1990            "--low-memory",
1991        ])
1992        .expect("parse must succeed");
1993        match cli.command {
1994            crate::cli::Commands::Ingest(args) => {
1995                assert!(args.low_memory, "--low-memory must set field to true");
1996            }
1997            _ => panic!("expected Ingest subcommand"),
1998        }
1999    }
2000
2001    #[test]
2002    fn ingest_args_low_memory_defaults_false() {
2003        use clap::Parser;
2004        let cli = crate::cli::Cli::try_parse_from([
2005            "sqlite-graphrag",
2006            "ingest",
2007            "/tmp/dummy",
2008            "--type",
2009            "document",
2010        ])
2011        .expect("parse must succeed");
2012        match cli.command {
2013            crate::cli::Commands::Ingest(args) => {
2014                assert!(!args.low_memory, "default must be false");
2015            }
2016            _ => panic!("expected Ingest subcommand"),
2017        }
2018    }
2019}