memvid_cli/commands/
data.rs

1//! Data operation command handlers (put, update, delete, api-fetch).
2//!
3//! Focused on ingesting files/bytes into `.mv2` memories, updating/deleting frames,
4//! and fetching remote content. Keeps ingestion flags and capacity checks consistent
5//! with the core engine while presenting concise CLI output.
6
7use std::collections::{BTreeMap, HashMap};
8use std::env;
9use std::fs;
10use std::io::{self, Cursor, Write};
11use std::num::NonZeroU64;
12use std::path::{Path, PathBuf};
13use std::sync::OnceLock;
14use std::time::Duration;
15
16use anyhow::{anyhow, Context, Result};
17use blake3::hash;
18use clap::{ArgAction, Args};
19use color_thief::{get_palette, Color, ColorFormat};
20use exif::{Reader as ExifReader, Tag, Value as ExifValue};
21use glob::glob;
22use image::ImageReader;
23use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
24use infer;
25#[cfg(feature = "clip")]
26use memvid_core::clip::render_pdf_pages_for_clip;
27#[cfg(feature = "clip")]
28use memvid_core::get_image_info;
29use memvid_core::table::{extract_tables, store_table, TableExtractionOptions};
30use memvid_core::{
31    normalize_text, AudioSegmentMetadata, DocAudioMetadata, DocExifMetadata, DocGpsMetadata,
32    DocMetadata, DocumentFormat, MediaManifest, Memvid, MemvidError, PutOptions,
33    ReaderHint, ReaderRegistry, Stats, Tier, TimelineQueryBuilder,
34};
35#[cfg(feature = "clip")]
36use memvid_core::FrameRole;
37#[cfg(feature = "parallel_segments")]
38use memvid_core::{BuildOpts, ParallelInput, ParallelPayload};
39use pdf_extract::OutputError as PdfExtractError;
40use serde_json::json;
41use tracing::{info, warn};
42use tree_magic_mini::from_u8 as magic_from_u8;
43use uuid::Uuid;
44
45const MAX_SEARCH_TEXT_LEN: usize = 32_768;
46/// Maximum characters for embedding text to avoid exceeding OpenAI's 8192 token limit.
47/// Using ~4 chars/token estimate, 30K chars ≈ 7.5K tokens (safe margin).
48const MAX_EMBEDDING_TEXT_LEN: usize = 20_000;
49const COLOR_PALETTE_SIZE: u8 = 5;
50const COLOR_PALETTE_QUALITY: u8 = 8;
51const MAGIC_SNIFF_BYTES: usize = 16;
52/// Maximum number of images to extract from a PDF for CLIP visual search.
53/// Set high to capture all images; processing stops when no more images found.
54#[cfg(feature = "clip")]
55const CLIP_PDF_MAX_IMAGES: usize = 100;
56#[cfg(feature = "clip")]
57const CLIP_PDF_TARGET_PX: u32 = 768;
58
59/// Truncate text for embedding to fit within OpenAI token limits.
60/// Returns a truncated string that fits within MAX_EMBEDDING_TEXT_LEN.
61fn truncate_for_embedding(text: &str) -> String {
62    if text.len() <= MAX_EMBEDDING_TEXT_LEN {
63        text.to_string()
64    } else {
65        // Find a char boundary to avoid splitting UTF-8
66        let truncated = &text[..MAX_EMBEDDING_TEXT_LEN];
67        // Try to find the last complete character
68        let end = truncated
69            .char_indices()
70            .rev()
71            .next()
72            .map(|(i, c)| i + c.len_utf8())
73            .unwrap_or(MAX_EMBEDDING_TEXT_LEN);
74        text[..end].to_string()
75    }
76}
77
78/// Get the default local model path for contextual retrieval (phi-3.5-mini).
79/// Uses MEMVID_MODELS_DIR or defaults to ~/.memvid/models/llm/phi-3-mini-q4/Phi-3.5-mini-instruct-Q4_K_M.gguf
80#[cfg(feature = "llama-cpp")]
81fn get_local_contextual_model_path() -> Result<PathBuf> {
82    let models_dir = if let Ok(custom) = env::var("MEMVID_MODELS_DIR") {
83        // Handle ~ expansion manually
84        let expanded = if custom.starts_with("~/") {
85            if let Ok(home) = env::var("HOME") {
86                PathBuf::from(home).join(&custom[2..])
87            } else {
88                PathBuf::from(&custom)
89            }
90        } else {
91            PathBuf::from(&custom)
92        };
93        expanded
94    } else {
95        // Default to ~/.memvid/models
96        let home = env::var("HOME").map_err(|_| anyhow!("HOME environment variable not set"))?;
97        PathBuf::from(home).join(".memvid").join("models")
98    };
99
100    let model_path = models_dir
101        .join("llm")
102        .join("phi-3-mini-q4")
103        .join("Phi-3.5-mini-instruct-Q4_K_M.gguf");
104
105    if model_path.exists() {
106        Ok(model_path)
107    } else {
108        Err(anyhow!(
109            "Local model not found at {}. Run 'memvid models install phi-3.5-mini' first.",
110            model_path.display()
111        ))
112    }
113}
114
115use pathdiff::diff_paths;
116
117use crate::api_fetch::{run_api_fetch, ApiFetchCommand, ApiFetchMode};
118use crate::commands::{extension_from_mime, frame_to_json, print_frame_summary};
119use crate::config::{load_embedding_runtime_for_mv2, CliConfig, EmbeddingRuntime};
120use crate::contextual::{apply_contextual_prefixes, ContextualEngine};
121use crate::error::{CapacityExceededMessage, DuplicateUriError};
122use crate::utils::{
123    apply_lock_cli, ensure_cli_mutation_allowed, format_bytes, frame_status_str, read_payload,
124    select_frame,
125};
126#[cfg(feature = "temporal_enrich")]
127use memvid_core::enrich_chunks as temporal_enrich_chunks;
128
129/// Helper function to parse boolean flags from environment variables
130fn parse_bool_flag(value: &str) -> Option<bool> {
131    match value.trim().to_ascii_lowercase().as_str() {
132        "1" | "true" | "yes" | "on" => Some(true),
133        "0" | "false" | "no" | "off" => Some(false),
134        _ => None,
135    }
136}
137
138/// Helper function to check for parallel segments environment override
139#[cfg(feature = "parallel_segments")]
140fn parallel_env_override() -> Option<bool> {
141    std::env::var("MEMVID_PARALLEL_SEGMENTS")
142        .ok()
143        .and_then(|value| parse_bool_flag(&value))
144}
145
146/// Check if CLIP model files are installed
147#[cfg(feature = "clip")]
148fn is_clip_model_installed() -> bool {
149    let models_dir = if let Ok(custom) = env::var("MEMVID_MODELS_DIR") {
150        PathBuf::from(custom)
151    } else if let Ok(home) = env::var("HOME") {
152        PathBuf::from(home).join(".memvid/models")
153    } else {
154        PathBuf::from(".memvid/models")
155    };
156
157    let model_name =
158        env::var("MEMVID_CLIP_MODEL").unwrap_or_else(|_| "mobileclip-s2".to_string());
159
160    let vision_model = models_dir.join(format!("{}_vision.onnx", model_name));
161    let text_model = models_dir.join(format!("{}_text.onnx", model_name));
162
163    vision_model.exists() && text_model.exists()
164}
165
166/// Minimum confidence threshold for NER entities (0.0-1.0)
167/// Note: Lower threshold captures more entities but also more noise
168#[cfg(feature = "logic_mesh")]
169const NER_MIN_CONFIDENCE: f32 = 0.50;
170
171/// Minimum length for entity names (characters)
172#[cfg(feature = "logic_mesh")]
173const NER_MIN_ENTITY_LEN: usize = 2;
174
175/// Maximum gap (in characters) between adjacent entities to merge
176/// Allows merging "S" + "&" + "P Global" when they're close together
177#[cfg(feature = "logic_mesh")]
178const MAX_MERGE_GAP: usize = 3;
179
180/// Merge adjacent NER entities that appear to be tokenization artifacts.
181///
182/// The BERT tokenizer splits names at special characters like `&`, producing
183/// separate entities like "S", "&", "P Global" instead of "S&P Global".
184/// This function merges adjacent entities of the same type when they're
185/// contiguous or nearly contiguous in the original text.
186#[cfg(feature = "logic_mesh")]
187fn merge_adjacent_entities(
188    entities: Vec<memvid_core::ExtractedEntity>,
189    original_text: &str,
190) -> Vec<memvid_core::ExtractedEntity> {
191    use memvid_core::ExtractedEntity;
192
193    if entities.is_empty() {
194        return entities;
195    }
196
197    // Sort by byte position
198    let mut sorted: Vec<ExtractedEntity> = entities;
199    sorted.sort_by_key(|e| e.byte_start);
200
201    let mut merged: Vec<ExtractedEntity> = Vec::new();
202
203    for entity in sorted {
204        if let Some(last) = merged.last_mut() {
205            // Check if this entity is adjacent to the previous one and same type
206            let gap = entity.byte_start.saturating_sub(last.byte_end);
207            let same_type = last.entity_type == entity.entity_type;
208
209            // Check what's in the gap (if any)
210            let gap_is_mergeable = if gap == 0 {
211                true
212            } else if gap <= MAX_MERGE_GAP && entity.byte_start <= original_text.len() && last.byte_end <= original_text.len() {
213                // Gap content should be whitespace (but not newlines), punctuation, or connectors
214                let gap_text = &original_text[last.byte_end..entity.byte_start];
215                // Don't merge across newlines - that indicates separate entities
216                if gap_text.contains('\n') || gap_text.contains('\r') {
217                    false
218                } else {
219                    gap_text.chars().all(|c| c == ' ' || c == '\t' || c == '&' || c == '-' || c == '\'' || c == '.')
220                }
221            } else {
222                false
223            };
224
225            if same_type && gap_is_mergeable {
226                // Merge: extend the previous entity to include this one
227                let merged_text = if entity.byte_end <= original_text.len() {
228                    original_text[last.byte_start..entity.byte_end].to_string()
229                } else {
230                    format!("{}{}", last.text, entity.text)
231                };
232
233                tracing::debug!(
234                    "Merged entities: '{}' + '{}' -> '{}' (gap: {} chars)",
235                    last.text, entity.text, merged_text, gap
236                );
237
238                last.text = merged_text;
239                last.byte_end = entity.byte_end;
240                // Average the confidence
241                last.confidence = (last.confidence + entity.confidence) / 2.0;
242                continue;
243            }
244        }
245
246        merged.push(entity);
247    }
248
249    merged
250}
251
252/// Filter and clean extracted NER entities to remove noise.
253/// Returns true if the entity should be kept.
254#[cfg(feature = "logic_mesh")]
255fn is_valid_entity(text: &str, confidence: f32) -> bool {
256    // Filter by confidence
257    if confidence < NER_MIN_CONFIDENCE {
258        return false;
259    }
260
261    let trimmed = text.trim();
262
263    // Filter by minimum length
264    if trimmed.len() < NER_MIN_ENTITY_LEN {
265        return false;
266    }
267
268    // Filter out entities that are just whitespace or punctuation
269    if trimmed.chars().all(|c| c.is_whitespace() || c.is_ascii_punctuation()) {
270        return false;
271    }
272
273    // Filter out entities containing newlines (malformed extractions)
274    if trimmed.contains('\n') || trimmed.contains('\r') {
275        return false;
276    }
277
278    // Filter out entities that look like partial words (start/end with ##)
279    if trimmed.starts_with("##") || trimmed.ends_with("##") {
280        return false;
281    }
282
283    // Filter out entities ending with period (likely sentence fragments)
284    if trimmed.ends_with('.') {
285        return false;
286    }
287
288    let lower = trimmed.to_lowercase();
289
290    // Filter out common single-letter false positives
291    if trimmed.len() == 1 {
292        return false;
293    }
294
295    // Filter out 2-letter tokens that are common noise
296    if trimmed.len() == 2 {
297        // Allow legitimate 2-letter entities like "EU", "UN", "UK", "US"
298        if matches!(lower.as_str(), "eu" | "un" | "uk" | "us" | "ai" | "it") {
299            return true;
300        }
301        // Filter other 2-letter tokens
302        return false;
303    }
304
305    // Filter out common noise words
306    if matches!(lower.as_str(), "the" | "api" | "url" | "pdf" | "inc" | "ltd" | "llc") {
307        return false;
308    }
309
310    // Filter out partial tokenization artifacts
311    // e.g., "S&P Global" becomes "P Global", "IHS Markit" becomes "HS Markit"
312    let words: Vec<&str> = trimmed.split_whitespace().collect();
313    if words.len() >= 2 {
314        let first_word = words[0];
315        // If first word is 1-2 chars and looks like a fragment, filter it
316        if first_word.len() <= 2 && first_word.chars().all(|c| c.is_uppercase()) {
317            // But allow "US Bank", "UK Office", etc.
318            if !matches!(first_word.to_lowercase().as_str(), "us" | "uk" | "eu" | "un") {
319                return false;
320            }
321        }
322    }
323
324    // Filter entities that start with lowercase (likely partial words)
325    if let Some(first_char) = trimmed.chars().next() {
326        if first_char.is_lowercase() {
327            return false;
328        }
329    }
330
331    true
332}
333
334/// Parse key=value pairs for tags
335pub fn parse_key_val(s: &str) -> Result<(String, String)> {
336    let (key, value) = s
337        .split_once('=')
338        .ok_or_else(|| anyhow!("expected KEY=VALUE, got `{s}`"))?;
339    Ok((key.to_string(), value.to_string()))
340}
341
342/// Lock-related CLI arguments (shared across commands)
343#[derive(Args, Clone, Copy, Debug)]
344pub struct LockCliArgs {
345    /// Maximum time to wait for an active writer before failing (ms)
346    #[arg(long = "lock-timeout", value_name = "MS", default_value_t = 250)]
347    pub lock_timeout: u64,
348    /// Attempt a stale takeover if the recorded writer heartbeat has expired
349    #[arg(long = "force", action = ArgAction::SetTrue)]
350    pub force: bool,
351}
352
353/// Arguments for the `put` subcommand
354#[derive(Args)]
355pub struct PutArgs {
356    /// Path to the memory file to append to
357    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
358    pub file: PathBuf,
359    /// Emit JSON instead of human-readable output
360    #[arg(long)]
361    pub json: bool,
362    /// Read payload bytes from a file instead of stdin
363    #[arg(long, value_name = "PATH")]
364    pub input: Option<String>,
365    /// Override the derived URI for the document
366    #[arg(long, value_name = "URI")]
367    pub uri: Option<String>,
368    /// Override the derived title for the document
369    #[arg(long, value_name = "TITLE")]
370    pub title: Option<String>,
371    /// Optional POSIX timestamp to store on the frame
372    #[arg(long)]
373    pub timestamp: Option<i64>,
374    /// Track name for the frame
375    #[arg(long)]
376    pub track: Option<String>,
377    /// Kind metadata for the frame
378    #[arg(long)]
379    pub kind: Option<String>,
380    /// Store the payload as a binary video without transcoding
381    #[arg(long, action = ArgAction::SetTrue)]
382    pub video: bool,
383    /// Attempt to attach a transcript (Dev/Enterprise tiers only)
384    #[arg(long, action = ArgAction::SetTrue)]
385    pub transcript: bool,
386    /// Tags to attach in key=value form
387    #[arg(long = "tag", value_parser = parse_key_val, value_name = "KEY=VALUE")]
388    pub tags: Vec<(String, String)>,
389    /// Free-form labels to attach to the frame
390    #[arg(long = "label", value_name = "LABEL")]
391    pub labels: Vec<String>,
392    /// Additional metadata payloads expressed as JSON
393    #[arg(long = "metadata", value_name = "JSON")]
394    pub metadata: Vec<String>,
395    /// Disable automatic tag generation from extracted text
396    #[arg(long = "no-auto-tag", action = ArgAction::SetTrue)]
397    pub no_auto_tag: bool,
398    /// Disable automatic date extraction from content
399    #[arg(long = "no-extract-dates", action = ArgAction::SetTrue)]
400    pub no_extract_dates: bool,
401    /// Force audio analysis and tagging when ingesting binary data
402    #[arg(long, action = ArgAction::SetTrue)]
403    pub audio: bool,
404    /// Override the default segment duration (in seconds) when generating audio snippets
405    #[arg(long = "audio-segment-seconds", value_name = "SECS")]
406    pub audio_segment_seconds: Option<u32>,
407    /// Compute semantic embeddings using the installed model
408    /// Increases storage overhead from ~5KB to ~270KB per document
409    #[arg(long, aliases = ["embeddings"], action = ArgAction::SetTrue, conflicts_with = "no_embedding")]
410    pub embedding: bool,
411    /// Explicitly disable embeddings (default, but kept for clarity)
412    #[arg(long = "no-embedding", action = ArgAction::SetTrue)]
413    pub no_embedding: bool,
414    /// Path to a JSON file containing a pre-computed embedding vector (e.g., from OpenAI)
415    /// The JSON file should contain a flat array of floats like [0.1, 0.2, ...]
416    #[arg(long = "embedding-vec", value_name = "JSON_PATH")]
417    pub embedding_vec: Option<PathBuf>,
418    /// Enable Product Quantization compression for vectors (16x compression)
419    /// Reduces vector storage from ~270KB to ~20KB per document with ~95% accuracy
420    /// Only applies when --embedding is enabled
421    #[arg(long, action = ArgAction::SetTrue)]
422    pub vector_compression: bool,
423    /// Enable contextual retrieval: prepend LLM-generated context to each chunk before embedding
424    /// This improves retrieval accuracy for preference/personalization queries
425    /// Requires OPENAI_API_KEY or a local model (phi-3.5-mini)
426    #[arg(long, action = ArgAction::SetTrue)]
427    pub contextual: bool,
428    /// Model to use for contextual retrieval (default: gpt-4o-mini, or "local" for phi-3.5-mini)
429    #[arg(long = "contextual-model", value_name = "MODEL")]
430    pub contextual_model: Option<String>,
431    /// Automatically extract tables from PDF documents
432    /// Uses aggressive mode with fallbacks for best results
433    #[arg(long, action = ArgAction::SetTrue)]
434    pub tables: bool,
435    /// Disable automatic table extraction (when --tables is the default)
436    #[arg(long = "no-tables", action = ArgAction::SetTrue)]
437    pub no_tables: bool,
438    /// Enable CLIP visual embeddings for images and PDF pages
439    /// Allows text-to-image search using natural language queries
440    /// Auto-enabled when CLIP model is installed; use --no-clip to disable
441    #[cfg(feature = "clip")]
442    #[arg(long, action = ArgAction::SetTrue)]
443    pub clip: bool,
444
445    /// Disable CLIP visual embeddings even when model is available
446    #[cfg(feature = "clip")]
447    #[arg(long, action = ArgAction::SetTrue)]
448    pub no_clip: bool,
449
450    /// Replace any existing frame with the same URI instead of inserting a duplicate
451    #[arg(long, conflicts_with = "allow_duplicate")]
452    pub update_existing: bool,
453    /// Allow inserting a new frame even if a frame with the same URI already exists
454    #[arg(long)]
455    pub allow_duplicate: bool,
456
457    /// Enable temporal enrichment: resolve relative time phrases ("last year") to absolute dates
458    /// Prepends resolved temporal context to chunks for improved temporal question accuracy
459    /// Requires the temporal_enrich feature in memvid-core
460    #[arg(long, action = ArgAction::SetTrue)]
461    pub temporal_enrich: bool,
462
463    /// Build Logic-Mesh entity graph during ingestion (opt-in)
464    /// Extracts entities (people, organizations, locations, etc.) and their relationships
465    /// Enables graph traversal with `memvid follow`
466    /// Requires NER model: `memvid models install --ner distilbert-ner`
467    #[arg(long, action = ArgAction::SetTrue)]
468    pub logic_mesh: bool,
469
470    /// Use the experimental parallel segment builder (requires --features parallel_segments)
471    #[cfg(feature = "parallel_segments")]
472    #[arg(long, action = ArgAction::SetTrue)]
473    pub parallel_segments: bool,
474    /// Force the legacy ingestion path even when the parallel feature is available
475    #[cfg(feature = "parallel_segments")]
476    #[arg(long, action = ArgAction::SetTrue)]
477    pub no_parallel_segments: bool,
478    /// Target tokens per segment when using the parallel builder
479    #[cfg(feature = "parallel_segments")]
480    #[arg(long = "parallel-seg-tokens", value_name = "TOKENS")]
481    pub parallel_segment_tokens: Option<usize>,
482    /// Target pages per segment when using the parallel builder
483    #[cfg(feature = "parallel_segments")]
484    #[arg(long = "parallel-seg-pages", value_name = "PAGES")]
485    pub parallel_segment_pages: Option<usize>,
486    /// Worker threads used by the parallel builder
487    #[cfg(feature = "parallel_segments")]
488    #[arg(long = "parallel-threads", value_name = "N")]
489    pub parallel_threads: Option<usize>,
490    /// Worker queue depth used by the parallel builder
491    #[cfg(feature = "parallel_segments")]
492    #[arg(long = "parallel-queue-depth", value_name = "N")]
493    pub parallel_queue_depth: Option<usize>,
494
495    #[command(flatten)]
496    pub lock: LockCliArgs,
497}
498
499#[cfg(feature = "parallel_segments")]
500impl PutArgs {
501    pub fn wants_parallel(&self) -> bool {
502        if self.parallel_segments {
503            return true;
504        }
505        if self.no_parallel_segments {
506            return false;
507        }
508        if let Some(env_flag) = parallel_env_override() {
509            return env_flag;
510        }
511        false
512    }
513
514    pub fn sanitized_parallel_opts(&self) -> memvid_core::BuildOpts {
515        let mut opts = memvid_core::BuildOpts::default();
516        if let Some(tokens) = self.parallel_segment_tokens {
517            opts.segment_tokens = tokens;
518        }
519        if let Some(pages) = self.parallel_segment_pages {
520            opts.segment_pages = pages;
521        }
522        if let Some(threads) = self.parallel_threads {
523            opts.threads = threads;
524        }
525        if let Some(depth) = self.parallel_queue_depth {
526            opts.queue_depth = depth;
527        }
528        opts.sanitize();
529        opts
530    }
531}
532
533#[cfg(not(feature = "parallel_segments"))]
534impl PutArgs {
535    pub fn wants_parallel(&self) -> bool {
536        false
537    }
538}
539
540/// Arguments for the `api-fetch` subcommand
541#[derive(Args)]
542pub struct ApiFetchArgs {
543    /// Path to the memory file to ingest into
544    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
545    pub file: PathBuf,
546    /// Path to the fetch configuration JSON file
547    #[arg(value_name = "CONFIG", value_parser = clap::value_parser!(PathBuf))]
548    pub config: PathBuf,
549    /// Perform a dry run without writing to the memory
550    #[arg(long, action = ArgAction::SetTrue)]
551    pub dry_run: bool,
552    /// Override the configured ingest mode
553    #[arg(long, value_name = "MODE")]
554    pub mode: Option<ApiFetchMode>,
555    /// Override the base URI used when constructing frame URIs
556    #[arg(long, value_name = "URI")]
557    pub uri: Option<String>,
558    /// Emit JSON instead of human-readable output
559    #[arg(long, action = ArgAction::SetTrue)]
560    pub json: bool,
561
562    #[command(flatten)]
563    pub lock: LockCliArgs,
564}
565
566/// Arguments for the `update` subcommand
567#[derive(Args)]
568pub struct UpdateArgs {
569    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
570    pub file: PathBuf,
571    #[arg(long = "frame-id", value_name = "ID", conflicts_with = "uri")]
572    pub frame_id: Option<u64>,
573    #[arg(long, value_name = "URI", conflicts_with = "frame_id")]
574    pub uri: Option<String>,
575    #[arg(long = "input", value_name = "PATH", value_parser = clap::value_parser!(PathBuf))]
576    pub input: Option<PathBuf>,
577    #[arg(long = "set-uri", value_name = "URI")]
578    pub set_uri: Option<String>,
579    #[arg(long, value_name = "TITLE")]
580    pub title: Option<String>,
581    #[arg(long, value_name = "TIMESTAMP")]
582    pub timestamp: Option<i64>,
583    #[arg(long, value_name = "TRACK")]
584    pub track: Option<String>,
585    #[arg(long, value_name = "KIND")]
586    pub kind: Option<String>,
587    #[arg(long = "tag", value_name = "KEY=VALUE", value_parser = parse_key_val)]
588    pub tags: Vec<(String, String)>,
589    #[arg(long = "label", value_name = "LABEL")]
590    pub labels: Vec<String>,
591    #[arg(long = "metadata", value_name = "JSON")]
592    pub metadata: Vec<String>,
593    #[arg(long, aliases = ["embeddings"], action = ArgAction::SetTrue)]
594    pub embeddings: bool,
595    #[arg(long)]
596    pub json: bool,
597
598    #[command(flatten)]
599    pub lock: LockCliArgs,
600}
601
602/// Arguments for the `delete` subcommand
603#[derive(Args)]
604pub struct DeleteArgs {
605    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
606    pub file: PathBuf,
607    #[arg(long = "frame-id", value_name = "ID", conflicts_with = "uri")]
608    pub frame_id: Option<u64>,
609    #[arg(long, value_name = "URI", conflicts_with = "frame_id")]
610    pub uri: Option<String>,
611    #[arg(long, action = ArgAction::SetTrue)]
612    pub yes: bool,
613    #[arg(long)]
614    pub json: bool,
615
616    #[command(flatten)]
617    pub lock: LockCliArgs,
618}
619
620/// Handler for `memvid api-fetch`
621pub fn handle_api_fetch(config: &CliConfig, args: ApiFetchArgs) -> Result<()> {
622    let command = ApiFetchCommand {
623        file: args.file,
624        config_path: args.config,
625        dry_run: args.dry_run,
626        mode_override: args.mode,
627        uri_override: args.uri,
628        output_json: args.json,
629        lock_timeout_ms: args.lock.lock_timeout,
630        force_lock: args.lock.force,
631    };
632    run_api_fetch(config, command)
633}
634
635/// Handler for `memvid delete`
636pub fn handle_delete(_config: &CliConfig, args: DeleteArgs) -> Result<()> {
637    let mut mem = Memvid::open(&args.file)?;
638    ensure_cli_mutation_allowed(&mem)?;
639    apply_lock_cli(&mut mem, &args.lock);
640    let frame = select_frame(&mut mem, args.frame_id, args.uri.as_deref())?;
641
642    if !args.yes {
643        if let Some(uri) = &frame.uri {
644            println!("About to delete frame {} ({uri})", frame.id);
645        } else {
646            println!("About to delete frame {}", frame.id);
647        }
648        print!("Confirm? [y/N]: ");
649        io::stdout().flush()?;
650        let mut input = String::new();
651        io::stdin().read_line(&mut input)?;
652        let confirmed = matches!(input.trim().to_ascii_lowercase().as_str(), "y" | "yes");
653        if !confirmed {
654            println!("Aborted");
655            return Ok(());
656        }
657    }
658
659    let seq = mem.delete_frame(frame.id)?;
660    mem.commit()?;
661    let deleted = mem.frame_by_id(frame.id)?;
662
663    if args.json {
664        let json = json!({
665            "frame_id": frame.id,
666            "sequence": seq,
667            "status": frame_status_str(deleted.status),
668        });
669        println!("{}", serde_json::to_string_pretty(&json)?);
670    } else {
671        println!("Deleted frame {} (seq {})", frame.id, seq);
672    }
673
674    Ok(())
675}
676pub fn handle_put(config: &CliConfig, args: PutArgs) -> Result<()> {
677    let mut mem = Memvid::open(&args.file)?;
678    ensure_cli_mutation_allowed(&mem)?;
679    apply_lock_cli(&mut mem, &args.lock);
680    let mut stats = mem.stats()?;
681    if stats.frame_count == 0 && !stats.has_lex_index {
682        mem.enable_lex()?;
683        stats = mem.stats()?;
684    }
685
686    // Set vector compression mode if requested
687    if args.vector_compression {
688        mem.set_vector_compression(memvid_core::VectorCompression::Pq96);
689    }
690
691    let mut capacity_guard = CapacityGuard::from_stats(&stats);
692    let use_parallel = args.wants_parallel();
693    #[cfg(feature = "parallel_segments")]
694    let mut parallel_opts = if use_parallel {
695        Some(args.sanitized_parallel_opts())
696    } else {
697        None
698    };
699    #[cfg(feature = "parallel_segments")]
700    let mut pending_parallel_inputs: Vec<ParallelInput> = Vec::new();
701    #[cfg(feature = "parallel_segments")]
702    let mut pending_parallel_indices: Vec<usize> = Vec::new();
703    let input_set = resolve_inputs(args.input.as_deref())?;
704
705    if args.video {
706        if let Some(kind) = &args.kind {
707            if !kind.eq_ignore_ascii_case("video") {
708                anyhow::bail!("--video conflicts with explicit --kind={kind}");
709            }
710        }
711        if matches!(input_set, InputSet::Stdin) {
712            anyhow::bail!("--video requires --input <file>");
713        }
714    }
715
716    #[allow(dead_code)]
717    enum EmbeddingMode {
718        None,
719        Auto,
720        Explicit,
721    }
722
723    // PHASE 1: Make embeddings opt-in, not opt-out
724    // Removed auto-embedding mode to reduce storage bloat (270 KB/doc → 5 KB/doc without vectors)
725    // Auto-detect embedding model from existing MV2 dimension to ensure compatibility
726    let mv2_dimension = mem.vec_index_dimension();
727    let (embedding_mode, embedding_runtime) = if args.embedding {
728        (
729            EmbeddingMode::Explicit,
730            Some(load_embedding_runtime_for_mv2(config, None, mv2_dimension)?),
731        )
732    } else {
733        (EmbeddingMode::None, None)
734    };
735    let embedding_enabled = embedding_runtime.is_some();
736    let runtime_ref = embedding_runtime.as_ref();
737
738    // Enable CLIP index if:
739    // 1. --clip flag is set explicitly, OR
740    // 2. Input contains image files and model is available, OR
741    // 3. Model is installed (auto-detect) and --no-clip is not set
742    #[cfg(feature = "clip")]
743    let clip_enabled = {
744        if args.no_clip {
745            false
746        } else if args.clip {
747            true // Explicitly requested
748        } else {
749            // Auto-detect: check if model is installed
750            let model_available = is_clip_model_installed();
751            if model_available {
752                // Model is installed, check if input has images or PDFs
753                match &input_set {
754                    InputSet::Files(paths) => paths.iter().any(|p| {
755                        is_image_file(p) || p.extension().map_or(false, |ext| ext.eq_ignore_ascii_case("pdf"))
756                    }),
757                    InputSet::Stdin => false,
758                }
759            } else {
760                false
761            }
762        }
763    };
764    #[cfg(feature = "clip")]
765    let clip_model = if clip_enabled {
766        mem.enable_clip()?;
767        if !args.json {
768            let mode = if args.clip {
769                "explicit"
770            } else {
771                "auto-detected"
772            };
773            eprintln!("ℹ️  CLIP visual embeddings enabled ({mode})");
774            eprintln!("   Model: MobileCLIP-S2 (512 dimensions)");
775            eprintln!("   Use 'memvid find --mode clip' to search with natural language");
776            eprintln!("   Use --no-clip to disable auto-detection");
777            eprintln!();
778        }
779        // Initialize CLIP model for generating image embeddings
780        match memvid_core::ClipModel::default_model() {
781            Ok(model) => Some(model),
782            Err(e) => {
783                warn!("Failed to load CLIP model: {e}. CLIP embeddings will be skipped.");
784                None
785            }
786        }
787    } else {
788        None
789    };
790
791    // Warn user about vector storage overhead (PHASE 2)
792    if embedding_enabled && !args.json {
793        let capacity = stats.capacity_bytes;
794        if args.vector_compression {
795            // PHASE 3: PQ compression reduces storage 16x
796            let max_docs = capacity / 20_000; // ~20 KB/doc with PQ compression
797            eprintln!("ℹ️  Vector embeddings enabled with Product Quantization compression");
798            eprintln!("   Storage: ~20 KB per document (16x compressed)");
799            eprintln!("   Accuracy: ~95% recall@10 maintained");
800            eprintln!(
801                "   Capacity: ~{} documents max for {:.1} GB",
802                max_docs,
803                capacity as f64 / 1e9
804            );
805            eprintln!();
806        } else {
807            let max_docs = capacity / 270_000; // Conservative estimate: 270 KB/doc
808            eprintln!("⚠️  WARNING: Vector embeddings enabled (uncompressed)");
809            eprintln!("   Storage: ~270 KB per document");
810            eprintln!(
811                "   Capacity: ~{} documents max for {:.1} GB",
812                max_docs,
813                capacity as f64 / 1e9
814            );
815            eprintln!("   Use --vector-compression for 16x storage savings (~20 KB/doc)");
816            eprintln!("   Use --no-embedding for lexical search only (~5 KB/doc)");
817            eprintln!();
818        }
819    }
820
821    let embed_progress = if embedding_enabled {
822        let total = match &input_set {
823            InputSet::Files(paths) => Some(paths.len() as u64),
824            InputSet::Stdin => None,
825        };
826        Some(create_task_progress_bar(total, "embed", false))
827    } else {
828        None
829    };
830    let mut embedded_docs = 0usize;
831
832    if let InputSet::Files(paths) = &input_set {
833        if paths.len() > 1 {
834            if args.uri.is_some() || args.title.is_some() {
835                anyhow::bail!(
836                    "--uri/--title apply to a single file; omit them when using a directory or glob"
837                );
838            }
839        }
840    }
841
842    let mut reports = Vec::new();
843    let mut processed = 0usize;
844    let mut skipped = 0usize;
845    let mut bytes_added = 0u64;
846    let mut summary_warnings: Vec<String> = Vec::new();
847    #[cfg(feature = "clip")]
848    let mut clip_embeddings_added = false;
849
850    let mut capacity_reached = false;
851    match input_set {
852        InputSet::Stdin => {
853            processed += 1;
854            match read_payload(None) {
855                Ok(payload) => {
856                    let mut analyze_spinner = if args.json {
857                        None
858                    } else {
859                        Some(create_spinner("Analyzing stdin payload..."))
860                    };
861                    match ingest_payload(
862                        &mut mem,
863                        &args,
864                        payload,
865                        None,
866                        capacity_guard.as_mut(),
867                        embedding_enabled,
868                        runtime_ref,
869                        use_parallel,
870                    ) {
871                        Ok(outcome) => {
872                            if let Some(pb) = analyze_spinner.take() {
873                                pb.finish_and_clear();
874                            }
875                            bytes_added += outcome.report.stored_bytes as u64;
876                            if args.json {
877                                summary_warnings
878                                    .extend(outcome.report.extraction.warnings.iter().cloned());
879                            }
880                            reports.push(outcome.report);
881                            let report_index = reports.len() - 1;
882                            if !args.json && !use_parallel {
883                                if let Some(report) = reports.get(report_index) {
884                                    print_report(report);
885                                }
886                            }
887                            if args.transcript {
888                                let notice = transcript_notice_message(&mut mem)?;
889                                if args.json {
890                                    summary_warnings.push(notice);
891                                } else {
892                                    println!("{notice}");
893                                }
894                            }
895                            if outcome.embedded {
896                                if let Some(pb) = embed_progress.as_ref() {
897                                    pb.inc(1);
898                                }
899                                embedded_docs += 1;
900                            }
901                            if use_parallel {
902                                #[cfg(feature = "parallel_segments")]
903                                if let Some(input) = outcome.parallel_input {
904                                    pending_parallel_indices.push(report_index);
905                                    pending_parallel_inputs.push(input);
906                                }
907                            } else if let Some(guard) = capacity_guard.as_mut() {
908                                mem.commit()?;
909                                let stats = mem.stats()?;
910                                guard.update_after_commit(&stats);
911                                guard.check_and_warn_capacity(); // PHASE 2: Capacity warnings
912                            }
913                        }
914                        Err(err) => {
915                            if let Some(pb) = analyze_spinner.take() {
916                                pb.finish_and_clear();
917                            }
918                            if err.downcast_ref::<DuplicateUriError>().is_some() {
919                                return Err(err);
920                            }
921                            warn!("skipped stdin payload: {err}");
922                            skipped += 1;
923                            if err.downcast_ref::<CapacityExceededMessage>().is_some() {
924                                capacity_reached = true;
925                            }
926                        }
927                    }
928                }
929                Err(err) => {
930                    warn!("failed to read stdin: {err}");
931                    skipped += 1;
932                }
933            }
934        }
935        InputSet::Files(ref paths) => {
936            let mut transcript_notice_printed = false;
937            for path in paths {
938                processed += 1;
939                match read_payload(Some(&path)) {
940                    Ok(payload) => {
941                        let label = path.display().to_string();
942                        let mut analyze_spinner = if args.json {
943                            None
944                        } else {
945                            Some(create_spinner(&format!("Analyzing {label}...")))
946                        };
947                        match ingest_payload(
948                            &mut mem,
949                            &args,
950                            payload,
951                            Some(&path),
952                            capacity_guard.as_mut(),
953                            embedding_enabled,
954                            runtime_ref,
955                            use_parallel,
956                        ) {
957                            Ok(outcome) => {
958                                if let Some(pb) = analyze_spinner.take() {
959                                    pb.finish_and_clear();
960                                }
961                                bytes_added += outcome.report.stored_bytes as u64;
962
963                                // Generate CLIP embedding for image files
964                                #[cfg(feature = "clip")]
965                                if let Some(ref model) = clip_model {
966                                    let mime = outcome.report.mime.as_deref();
967                                    let clip_frame_id = outcome.report.frame_id;
968
969                                    if is_image_file(&path) {
970                                        match model.encode_image_file(&path) {
971                                            Ok(embedding) => {
972                                                if let Err(e) = mem.add_clip_embedding_with_page(
973                                                    clip_frame_id,
974                                                    None,
975                                                    embedding,
976                                                ) {
977                                                    warn!(
978                                                        "Failed to add CLIP embedding for {}: {e}",
979                                                        path.display()
980                                                    );
981                                                } else {
982                                                    info!(
983                                                        "Added CLIP embedding for frame {}",
984                                                        clip_frame_id
985                                                    );
986                                                    clip_embeddings_added = true;
987                                                }
988                                            }
989                                            Err(e) => {
990                                                warn!(
991                                                    "Failed to encode CLIP embedding for {}: {e}",
992                                                    path.display()
993                                                );
994                                            }
995                                        }
996                                    } else if matches!(mime, Some(m) if m == "application/pdf") {
997                                        // Commit before adding child frames to ensure WAL has space
998                                        if let Err(e) = mem.commit() {
999                                            warn!("Failed to commit before CLIP extraction: {e}");
1000                                        }
1001
1002                                        match render_pdf_pages_for_clip(
1003                                            &path,
1004                                            CLIP_PDF_MAX_IMAGES,
1005                                            CLIP_PDF_TARGET_PX,
1006                                        ) {
1007                                            Ok(rendered_pages) => {
1008                                                use rayon::prelude::*;
1009
1010                                                // Pre-encode all images to PNG in parallel for better performance
1011                                                // Filter out junk images (solid colors, black, too small)
1012                                                let path_for_closure = path.clone();
1013
1014                                                // Temporarily suppress panic output during image encoding
1015                                                // (some PDFs have malformed images that cause panics in the image crate)
1016                                                let prev_hook = std::panic::take_hook();
1017                                                std::panic::set_hook(Box::new(|_| {
1018                                                    // Silently ignore panics - we handle them with catch_unwind
1019                                                }));
1020
1021                                                let encoded_images: Vec<_> = rendered_pages
1022                                                    .into_par_iter()
1023                                                    .filter_map(|(page_num, image)| {
1024                                                        // Check if image is worth embedding (not junk)
1025                                                        let image_info = get_image_info(&image);
1026                                                        if !image_info.should_embed() {
1027                                                            info!(
1028                                                                "Skipping junk image for {} page {} (variance={:.4}, {}x{})",
1029                                                                path_for_closure.display(),
1030                                                                page_num,
1031                                                                image_info.color_variance,
1032                                                                image_info.width,
1033                                                                image_info.height
1034                                                            );
1035                                                            return None;
1036                                                        }
1037
1038                                                        // Convert to RGB8 first to ensure consistent buffer size
1039                                                        // (some PDFs have images with alpha or other formats that cause panics)
1040                                                        // Use catch_unwind to handle any panics from corrupted image data
1041                                                        let encode_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1042                                                            let rgb_image = image.to_rgb8();
1043                                                            let mut png_bytes = Vec::new();
1044                                                            image::DynamicImage::ImageRgb8(rgb_image).write_to(
1045                                                                &mut Cursor::new(&mut png_bytes),
1046                                                                image::ImageFormat::Png,
1047                                                            ).map(|()| png_bytes)
1048                                                        }));
1049
1050                                                        match encode_result {
1051                                                            Ok(Ok(png_bytes)) => Some((page_num, image, png_bytes)),
1052                                                            Ok(Err(e)) => {
1053                                                                info!(
1054                                                                    "Skipping image for {} page {}: {e}",
1055                                                                    path_for_closure.display(),
1056                                                                    page_num
1057                                                                );
1058                                                                None
1059                                                            }
1060                                                            Err(_) => {
1061                                                                // Panic occurred - corrupted image data, silently skip
1062                                                                info!(
1063                                                                    "Skipping malformed image for {} page {}",
1064                                                                    path_for_closure.display(),
1065                                                                    page_num
1066                                                                );
1067                                                                None
1068                                                            }
1069                                                        }
1070                                                    })
1071                                                    .collect();
1072
1073                                                // Restore the original panic hook
1074                                                std::panic::set_hook(prev_hook);
1075
1076                                                // Process encoded images sequentially (storage + CLIP encoding)
1077                                                // Commit after each image to prevent WAL overflow (PNG images can be large)
1078                                                let mut child_frame_offset = 1u64;
1079                                                let parent_uri = outcome.report.uri.clone();
1080                                                let parent_title = outcome.report.title.clone().unwrap_or_else(|| "Image".to_string());
1081                                                let total_images = encoded_images.len();
1082
1083                                                // Show progress bar for CLIP extraction
1084                                                let clip_pb = if !args.json && total_images > 0 {
1085                                                    let pb = ProgressBar::new(total_images as u64);
1086                                                    pb.set_style(
1087                                                        ProgressStyle::with_template(
1088                                                            "  CLIP {bar:40.cyan/blue} {pos}/{len} images ({eta})"
1089                                                        )
1090                                                        .unwrap_or_else(|_| ProgressStyle::default_bar())
1091                                                        .progress_chars("█▓░"),
1092                                                    );
1093                                                    Some(pb)
1094                                                } else {
1095                                                    None
1096                                                };
1097
1098                                                for (page_num, image, png_bytes) in encoded_images {
1099                                                    let child_uri = format!("{}/image/{}", parent_uri, child_frame_offset);
1100                                                    let child_title = format!(
1101                                                        "{} - Image {} (page {})",
1102                                                        parent_title,
1103                                                        child_frame_offset,
1104                                                        page_num
1105                                                    );
1106
1107                                                    let child_options = PutOptions::builder()
1108                                                        .uri(&child_uri)
1109                                                        .title(&child_title)
1110                                                        .parent_id(clip_frame_id)
1111                                                        .role(FrameRole::ExtractedImage)
1112                                                        .auto_tag(false)
1113                                                        .extract_dates(false)
1114                                                        .build();
1115
1116                                                    match mem.put_bytes_with_options(&png_bytes, child_options) {
1117                                                        Ok(_child_seq) => {
1118                                                            let child_frame_id = clip_frame_id + child_frame_offset;
1119                                                            child_frame_offset += 1;
1120
1121                                                            match model.encode_image(&image) {
1122                                                                Ok(embedding) => {
1123                                                                    if let Err(e) = mem
1124                                                                        .add_clip_embedding_with_page(
1125                                                                            child_frame_id,
1126                                                                            Some(page_num),
1127                                                                            embedding,
1128                                                                        )
1129                                                                    {
1130                                                                        warn!(
1131                                                                            "Failed to add CLIP embedding for {} page {}: {e}",
1132                                                                            path.display(),
1133                                                                            page_num
1134                                                                        );
1135                                                                    } else {
1136                                                                        info!(
1137                                                                            "Added CLIP image frame {} for {} page {}",
1138                                                                            child_frame_id,
1139                                                                            clip_frame_id,
1140                                                                            page_num
1141                                                                        );
1142                                                                        clip_embeddings_added = true;
1143                                                                    }
1144                                                                }
1145                                                                Err(e) => warn!(
1146                                                                    "Failed to encode CLIP embedding for {} page {}: {e}",
1147                                                                    path.display(),
1148                                                                    page_num
1149                                                                ),
1150                                                            }
1151
1152                                                            // Commit after each image to checkpoint WAL
1153                                                            if let Err(e) = mem.commit() {
1154                                                                warn!("Failed to commit after image {}: {e}", child_frame_offset);
1155                                                            }
1156                                                        }
1157                                                        Err(e) => warn!(
1158                                                            "Failed to store image frame for {} page {}: {e}",
1159                                                            path.display(),
1160                                                            page_num
1161                                                        ),
1162                                                    }
1163
1164                                                    if let Some(ref pb) = clip_pb {
1165                                                        pb.inc(1);
1166                                                    }
1167                                                }
1168
1169                                                if let Some(pb) = clip_pb {
1170                                                    pb.finish_and_clear();
1171                                                }
1172                                            }
1173                                            Err(err) => warn!(
1174                                                "Failed to render PDF pages for CLIP {}: {err}",
1175                                                path.display()
1176                                            ),
1177                                        }
1178                                    }
1179                                }
1180
1181                                if args.json {
1182                                    summary_warnings
1183                                        .extend(outcome.report.extraction.warnings.iter().cloned());
1184                                }
1185                                reports.push(outcome.report);
1186                                let report_index = reports.len() - 1;
1187                                if !args.json && !use_parallel {
1188                                    if let Some(report) = reports.get(report_index) {
1189                                        print_report(report);
1190                                    }
1191                                }
1192                                if args.transcript && !transcript_notice_printed {
1193                                    let notice = transcript_notice_message(&mut mem)?;
1194                                    if args.json {
1195                                        summary_warnings.push(notice);
1196                                    } else {
1197                                        println!("{notice}");
1198                                    }
1199                                    transcript_notice_printed = true;
1200                                }
1201                                if outcome.embedded {
1202                                    if let Some(pb) = embed_progress.as_ref() {
1203                                        pb.inc(1);
1204                                    }
1205                                    embedded_docs += 1;
1206                                }
1207                                if use_parallel {
1208                                    #[cfg(feature = "parallel_segments")]
1209                                    if let Some(input) = outcome.parallel_input {
1210                                        pending_parallel_indices.push(report_index);
1211                                        pending_parallel_inputs.push(input);
1212                                    }
1213                                } else if let Some(guard) = capacity_guard.as_mut() {
1214                                    mem.commit()?;
1215                                    let stats = mem.stats()?;
1216                                    guard.update_after_commit(&stats);
1217                                    guard.check_and_warn_capacity(); // PHASE 2: Capacity warnings
1218                                }
1219                            }
1220                            Err(err) => {
1221                                if let Some(pb) = analyze_spinner.take() {
1222                                    pb.finish_and_clear();
1223                                }
1224                                if err.downcast_ref::<DuplicateUriError>().is_some() {
1225                                    return Err(err);
1226                                }
1227                                warn!("skipped {}: {err}", path.display());
1228                                skipped += 1;
1229                                if err.downcast_ref::<CapacityExceededMessage>().is_some() {
1230                                    capacity_reached = true;
1231                                }
1232                            }
1233                        }
1234                    }
1235                    Err(err) => {
1236                        warn!("failed to read {}: {err}", path.display());
1237                        skipped += 1;
1238                    }
1239                }
1240                if capacity_reached {
1241                    break;
1242                }
1243            }
1244        }
1245    }
1246
1247    if capacity_reached {
1248        warn!("capacity limit reached; remaining inputs were not processed");
1249    }
1250
1251    if let Some(pb) = embed_progress.as_ref() {
1252        pb.finish_with_message("embed");
1253    }
1254
1255    if let Some(runtime) = embedding_runtime.as_ref() {
1256        if embedded_docs > 0 {
1257            match embedding_mode {
1258                EmbeddingMode::Explicit => println!(
1259                    "\u{2713} vectors={}  dim={}  hnsw(M=16, efC=200)",
1260                    embedded_docs,
1261                    runtime.dimension()
1262                ),
1263                EmbeddingMode::Auto => println!(
1264                    "\u{2713} vectors={}  dim={}  hnsw(M=16, efC=200)  (auto)",
1265                    embedded_docs,
1266                    runtime.dimension()
1267                ),
1268                EmbeddingMode::None => {}
1269            }
1270        } else {
1271            match embedding_mode {
1272                EmbeddingMode::Explicit => {
1273                    println!("No embeddings were generated (no textual content available)");
1274                }
1275                EmbeddingMode::Auto => {
1276                    println!(
1277                        "Semantic runtime available, but no textual content produced embeddings"
1278                    );
1279                }
1280                EmbeddingMode::None => {}
1281            }
1282        }
1283    }
1284
1285    if reports.is_empty() {
1286        if args.json {
1287            if capacity_reached {
1288                summary_warnings.push("capacity_limit_reached".to_string());
1289            }
1290            let summary_json = json!({
1291                "processed": processed,
1292                "ingested": 0,
1293                "skipped": skipped,
1294                "bytes_added": bytes_added,
1295                "bytes_added_human": format_bytes(bytes_added),
1296                "embedded_documents": embedded_docs,
1297                "capacity_reached": capacity_reached,
1298                "warnings": summary_warnings,
1299                "reports": Vec::<serde_json::Value>::new(),
1300            });
1301            println!("{}", serde_json::to_string_pretty(&summary_json)?);
1302        } else {
1303            println!(
1304                "Summary: processed {}, ingested 0, skipped {}, bytes added 0 B",
1305                processed, skipped
1306            );
1307        }
1308        return Ok(());
1309    }
1310
1311    #[cfg(feature = "parallel_segments")]
1312    let mut parallel_flush_spinner = if use_parallel && !args.json {
1313        Some(create_spinner("Flushing parallel segments..."))
1314    } else {
1315        None
1316    };
1317
1318    if use_parallel {
1319        #[cfg(feature = "parallel_segments")]
1320        {
1321            let mut opts = parallel_opts.take().unwrap_or_else(|| {
1322                let mut opts = BuildOpts::default();
1323                opts.sanitize();
1324                opts
1325            });
1326            // Set vector compression mode from mem state
1327            opts.vec_compression = mem.vector_compression().clone();
1328            let seqs = if pending_parallel_inputs.is_empty() {
1329                mem.commit_parallel(opts)?;
1330                Vec::new()
1331            } else {
1332                mem.put_parallel_inputs(&pending_parallel_inputs, opts)?
1333            };
1334            if let Some(pb) = parallel_flush_spinner.take() {
1335                pb.finish_with_message("Flushed parallel segments");
1336            }
1337            for (idx, seq) in pending_parallel_indices.into_iter().zip(seqs.into_iter()) {
1338                if let Some(report) = reports.get_mut(idx) {
1339                    report.seq = seq;
1340                }
1341            }
1342        }
1343        #[cfg(not(feature = "parallel_segments"))]
1344        {
1345            mem.commit()?;
1346        }
1347    } else {
1348        mem.commit()?;
1349    }
1350
1351    // Persist CLIP embeddings added after the primary commit (avoids rebuild ordering issues).
1352    #[cfg(feature = "clip")]
1353    if clip_embeddings_added {
1354        mem.commit()?;
1355    }
1356
1357    if !args.json && use_parallel {
1358        for report in &reports {
1359            print_report(report);
1360        }
1361    }
1362
1363    // Table extraction for PDF files
1364    let mut tables_extracted = 0usize;
1365    let mut table_summaries: Vec<serde_json::Value> = Vec::new();
1366    if args.tables && !args.no_tables {
1367        if let InputSet::Files(ref paths) = input_set {
1368            let pdf_paths: Vec<_> = paths
1369                .iter()
1370                .filter(|p| {
1371                    p.extension()
1372                        .and_then(|e| e.to_str())
1373                        .map(|e| e.eq_ignore_ascii_case("pdf"))
1374                        .unwrap_or(false)
1375                })
1376                .collect();
1377
1378            if !pdf_paths.is_empty() {
1379                let table_spinner = if args.json {
1380                    None
1381                } else {
1382                    Some(create_spinner(&format!(
1383                        "Extracting tables from {} PDF(s)...",
1384                        pdf_paths.len()
1385                    )))
1386                };
1387
1388                // Use aggressive mode with auto fallback for best results
1389                let table_options = TableExtractionOptions::builder()
1390                    .mode(memvid_core::table::ExtractionMode::Aggressive)
1391                    .min_rows(2)
1392                    .min_cols(2)
1393                    .min_quality(memvid_core::table::TableQuality::Low)
1394                    .merge_multi_page(true)
1395                    .build();
1396
1397                for pdf_path in pdf_paths {
1398                    if let Ok(pdf_bytes) = std::fs::read(pdf_path) {
1399                        let filename = pdf_path
1400                            .file_name()
1401                            .and_then(|s| s.to_str())
1402                            .unwrap_or("unknown.pdf");
1403
1404                        if let Ok(result) = extract_tables(&pdf_bytes, filename, &table_options) {
1405                            for table in &result.tables {
1406                                if let Ok((meta_id, _row_ids)) = store_table(&mut mem, table, true)
1407                                {
1408                                    tables_extracted += 1;
1409                                    table_summaries.push(json!({
1410                                        "table_id": table.table_id,
1411                                        "source_file": table.source_file,
1412                                        "meta_frame_id": meta_id,
1413                                        "rows": table.n_rows,
1414                                        "cols": table.n_cols,
1415                                        "quality": format!("{:?}", table.quality),
1416                                        "pages": format!("{}-{}", table.page_start, table.page_end),
1417                                    }));
1418                                }
1419                            }
1420                        }
1421                    }
1422                }
1423
1424                if let Some(pb) = table_spinner {
1425                    if tables_extracted > 0 {
1426                        pb.finish_with_message(format!("Extracted {} table(s)", tables_extracted));
1427                    } else {
1428                        pb.finish_with_message("No tables found");
1429                    }
1430                }
1431
1432                // Commit table frames
1433                if tables_extracted > 0 {
1434                    mem.commit()?;
1435                }
1436            }
1437        }
1438    }
1439
1440    // Logic-Mesh: Extract entities and build relationship graph
1441    // Opt-in only: requires --logic-mesh flag
1442    #[cfg(feature = "logic_mesh")]
1443    let mut logic_mesh_entities = 0usize;
1444    #[cfg(feature = "logic_mesh")]
1445    {
1446        use memvid_core::{ner_model_path, ner_tokenizer_path, NerModel, LogicMesh, MeshNode};
1447
1448        let models_dir = config.models_dir.clone();
1449        let model_path = ner_model_path(&models_dir);
1450        let tokenizer_path = ner_tokenizer_path(&models_dir);
1451
1452        // Opt-in: only enable Logic-Mesh when explicitly requested with --logic-mesh
1453        let ner_available = model_path.exists() && tokenizer_path.exists();
1454        let should_run_ner = args.logic_mesh;
1455
1456        if should_run_ner && !ner_available {
1457            // User explicitly requested --logic-mesh but model not installed
1458            if args.json {
1459                summary_warnings.push(
1460                    "logic_mesh_skipped: NER model not installed. Run 'memvid models install --ner distilbert-ner'".to_string()
1461                );
1462            } else {
1463                eprintln!("⚠️  Logic-Mesh skipped: NER model not installed.");
1464                eprintln!("   Run: memvid models install --ner distilbert-ner");
1465            }
1466        } else if should_run_ner {
1467            let ner_spinner = if args.json {
1468                None
1469            } else {
1470                Some(create_spinner("Building Logic-Mesh entity graph..."))
1471            };
1472
1473            match NerModel::load(&model_path, &tokenizer_path, None) {
1474                Ok(mut ner_model) => {
1475                    let mut mesh = LogicMesh::new();
1476                    let mut filtered_count = 0usize;
1477
1478                    // Process each ingested frame for entity extraction using cached search_text
1479                    for report in &reports {
1480                        let frame_id = report.frame_id;
1481                        // Use the cached search_text from ingestion
1482                        if let Some(ref content) = report.search_text {
1483                            if !content.is_empty() {
1484                                match ner_model.extract(content) {
1485                                    Ok(raw_entities) => {
1486                                        // Merge adjacent entities that were split by tokenization
1487                                        // e.g., "S" + "&" + "P Global" -> "S&P Global"
1488                                        let merged_entities = merge_adjacent_entities(raw_entities, content);
1489
1490                                        for entity in &merged_entities {
1491                                            // Apply post-processing filter to remove noisy entities
1492                                            if !is_valid_entity(&entity.text, entity.confidence) {
1493                                                tracing::debug!(
1494                                                    "Filtered entity: '{}' (confidence: {:.0}%)",
1495                                                    entity.text, entity.confidence * 100.0
1496                                                );
1497                                                filtered_count += 1;
1498                                                continue;
1499                                            }
1500
1501                                            // Convert NER entity type to EntityKind
1502                                            let kind = entity.to_entity_kind();
1503                                            // Create mesh node with proper structure
1504                                            let node = MeshNode::new(
1505                                                entity.text.to_lowercase(),
1506                                                entity.text.trim().to_string(),
1507                                                kind,
1508                                                entity.confidence,
1509                                                frame_id,
1510                                                entity.byte_start as u32,
1511                                                (entity.byte_end - entity.byte_start).min(u16::MAX as usize) as u16,
1512                                            );
1513                                            mesh.merge_node(node);
1514                                            logic_mesh_entities += 1;
1515                                        }
1516                                    }
1517                                    Err(e) => {
1518                                        warn!("NER extraction failed for frame {frame_id}: {e}");
1519                                    }
1520                                }
1521                            }
1522                        }
1523                    }
1524
1525                    if logic_mesh_entities > 0 {
1526                        mesh.finalize();
1527                        let node_count = mesh.stats().node_count;
1528                        // Persist mesh to MV2 file
1529                        mem.set_logic_mesh(mesh);
1530                        mem.commit()?;
1531                        info!(
1532                            "Logic-Mesh persisted with {} entities ({} unique nodes, {} filtered)",
1533                            logic_mesh_entities,
1534                            node_count,
1535                            filtered_count
1536                        );
1537                    }
1538
1539                    if let Some(pb) = ner_spinner {
1540                        pb.finish_with_message(format!(
1541                            "Logic-Mesh: {} entities ({} unique)",
1542                            logic_mesh_entities,
1543                            mem.mesh_node_count()
1544                        ));
1545                    }
1546                }
1547                Err(e) => {
1548                    if let Some(pb) = ner_spinner {
1549                        pb.finish_with_message(format!("Logic-Mesh failed: {e}"));
1550                    }
1551                    if args.json {
1552                        summary_warnings.push(format!("logic_mesh_failed: {e}"));
1553                    }
1554                }
1555            }
1556        }
1557    }
1558
1559    let stats = mem.stats()?;
1560    if args.json {
1561        if capacity_reached {
1562            summary_warnings.push("capacity_limit_reached".to_string());
1563        }
1564        let reports_json: Vec<serde_json::Value> = reports.iter().map(put_report_to_json).collect();
1565        let total_duration_ms: Option<u64> = {
1566            let sum: u64 = reports
1567                .iter()
1568                .filter_map(|r| r.extraction.duration_ms)
1569                .sum();
1570            if sum > 0 {
1571                Some(sum)
1572            } else {
1573                None
1574            }
1575        };
1576        let total_pages: Option<u32> = {
1577            let sum: u32 = reports
1578                .iter()
1579                .filter_map(|r| r.extraction.pages_processed)
1580                .sum();
1581            if sum > 0 {
1582                Some(sum)
1583            } else {
1584                None
1585            }
1586        };
1587        let embedding_mode_str = match embedding_mode {
1588            EmbeddingMode::None => "none",
1589            EmbeddingMode::Auto => "auto",
1590            EmbeddingMode::Explicit => "explicit",
1591        };
1592        let summary_json = json!({
1593            "processed": processed,
1594            "ingested": reports.len(),
1595            "skipped": skipped,
1596            "bytes_added": bytes_added,
1597            "bytes_added_human": format_bytes(bytes_added),
1598            "embedded_documents": embedded_docs,
1599            "embedding": {
1600                "enabled": embedding_enabled,
1601                "mode": embedding_mode_str,
1602                "runtime_dimension": runtime_ref.map(|rt| rt.dimension()),
1603            },
1604            "tables": {
1605                "enabled": args.tables && !args.no_tables,
1606                "extracted": tables_extracted,
1607                "tables": table_summaries,
1608            },
1609            "capacity_reached": capacity_reached,
1610            "warnings": summary_warnings,
1611            "extraction": {
1612                "total_duration_ms": total_duration_ms,
1613                "total_pages_processed": total_pages,
1614            },
1615            "memory": {
1616                "path": args.file.display().to_string(),
1617                "frame_count": stats.frame_count,
1618                "size_bytes": stats.size_bytes,
1619                "tier": format!("{:?}", stats.tier),
1620            },
1621            "reports": reports_json,
1622        });
1623        println!("{}", serde_json::to_string_pretty(&summary_json)?);
1624    } else {
1625        println!(
1626            "Committed {} frame(s); total frames {}",
1627            reports.len(),
1628            stats.frame_count
1629        );
1630        println!(
1631            "Summary: processed {}, ingested {}, skipped {}, bytes added {}",
1632            processed,
1633            reports.len(),
1634            skipped,
1635            format_bytes(bytes_added)
1636        );
1637        if tables_extracted > 0 {
1638            println!("Tables: {} extracted from PDF(s)", tables_extracted);
1639        }
1640    }
1641    Ok(())
1642}
1643
1644pub fn handle_update(config: &CliConfig, args: UpdateArgs) -> Result<()> {
1645    let mut mem = Memvid::open(&args.file)?;
1646    ensure_cli_mutation_allowed(&mem)?;
1647    apply_lock_cli(&mut mem, &args.lock);
1648    let existing = select_frame(&mut mem, args.frame_id, args.uri.as_deref())?;
1649    let frame_id = existing.id;
1650
1651    let payload_bytes = match args.input.as_ref() {
1652        Some(path) => Some(read_payload(Some(path))?),
1653        None => None,
1654    };
1655    let payload_slice = payload_bytes.as_deref();
1656    let payload_utf8 = payload_slice.and_then(|bytes| std::str::from_utf8(bytes).ok());
1657    let source_path = args.input.as_deref();
1658
1659    let mut options = PutOptions::default();
1660    options.enable_embedding = false;
1661    options.auto_tag = payload_slice.is_some();
1662    options.extract_dates = payload_slice.is_some();
1663    options.timestamp = Some(existing.timestamp);
1664    options.track = existing.track.clone();
1665    options.kind = existing.kind.clone();
1666    options.uri = existing.uri.clone();
1667    options.title = existing.title.clone();
1668    options.metadata = existing.metadata.clone();
1669    options.search_text = existing.search_text.clone();
1670    options.tags = existing.tags.clone();
1671    options.labels = existing.labels.clone();
1672    options.extra_metadata = existing.extra_metadata.clone();
1673
1674    if let Some(new_uri) = &args.set_uri {
1675        options.uri = Some(derive_uri(Some(new_uri), None));
1676    }
1677
1678    if options.uri.is_none() && payload_slice.is_some() {
1679        options.uri = Some(derive_uri(None, source_path));
1680    }
1681
1682    if let Some(title) = &args.title {
1683        options.title = Some(title.clone());
1684    }
1685    if let Some(ts) = args.timestamp {
1686        options.timestamp = Some(ts);
1687    }
1688    if let Some(track) = &args.track {
1689        options.track = Some(track.clone());
1690    }
1691    if let Some(kind) = &args.kind {
1692        options.kind = Some(kind.clone());
1693    }
1694
1695    if !args.labels.is_empty() {
1696        options.labels = args.labels.clone();
1697    }
1698
1699    if !args.tags.is_empty() {
1700        options.tags.clear();
1701        for (key, value) in &args.tags {
1702            if !key.is_empty() {
1703                options.tags.push(key.clone());
1704            }
1705            if !value.is_empty() && value != key {
1706                options.tags.push(value.clone());
1707            }
1708            options.extra_metadata.insert(key.clone(), value.clone());
1709        }
1710    }
1711
1712    apply_metadata_overrides(&mut options, &args.metadata);
1713
1714    let mut search_source = options.search_text.clone();
1715
1716    if let Some(payload) = payload_slice {
1717        let inferred_title = derive_title(args.title.clone(), source_path, payload_utf8);
1718        if let Some(title) = inferred_title {
1719            options.title = Some(title);
1720        }
1721
1722        if options.uri.is_none() {
1723            options.uri = Some(derive_uri(None, source_path));
1724        }
1725
1726        let analysis = analyze_file(
1727            source_path,
1728            payload,
1729            payload_utf8,
1730            options.title.as_deref(),
1731            AudioAnalyzeOptions::default(),
1732            false,
1733        );
1734        if let Some(meta) = analysis.metadata {
1735            options.metadata = Some(meta);
1736        }
1737        if let Some(text) = analysis.search_text {
1738            search_source = Some(text.clone());
1739            options.search_text = Some(text);
1740        }
1741    } else {
1742        options.auto_tag = false;
1743        options.extract_dates = false;
1744    }
1745
1746    let stats = mem.stats()?;
1747    options.enable_embedding = stats.has_vec_index;
1748
1749    // Auto-detect embedding model from existing MV2 dimension
1750    let mv2_dimension = mem.vec_index_dimension();
1751    let mut embedding: Option<Vec<f32>> = None;
1752    if args.embeddings {
1753        let runtime = load_embedding_runtime_for_mv2(config, None, mv2_dimension)?;
1754        if let Some(text) = search_source.as_ref() {
1755            if !text.trim().is_empty() {
1756                embedding = Some(runtime.embed(text)?);
1757            }
1758        }
1759        if embedding.is_none() {
1760            if let Some(text) = payload_utf8 {
1761                if !text.trim().is_empty() {
1762                    embedding = Some(runtime.embed(text)?);
1763                }
1764            }
1765        }
1766        if embedding.is_none() {
1767            warn!("no textual content available; embeddings not recomputed");
1768        }
1769    }
1770
1771    let mut effective_embedding = embedding;
1772    if effective_embedding.is_none() && stats.has_vec_index {
1773        effective_embedding = mem.frame_embedding(frame_id)?;
1774    }
1775
1776    let final_uri = options.uri.clone();
1777    let replaced_payload = payload_slice.is_some();
1778    let seq = mem.update_frame(frame_id, payload_bytes, options, effective_embedding)?;
1779    mem.commit()?;
1780
1781    let updated_frame =
1782        if let Some(uri) = final_uri.and_then(|u| if u.is_empty() { None } else { Some(u) }) {
1783            mem.frame_by_uri(&uri)?
1784        } else {
1785            let mut query = TimelineQueryBuilder::default();
1786            if let Some(limit) = NonZeroU64::new(1) {
1787                query = query.limit(limit).reverse(true);
1788            }
1789            let latest = mem.timeline(query.build())?;
1790            if let Some(entry) = latest.first() {
1791                mem.frame_by_id(entry.frame_id)?
1792            } else {
1793                mem.frame_by_id(frame_id)?
1794            }
1795        };
1796
1797    if args.json {
1798        let json = json!({
1799            "sequence": seq,
1800            "previous_frame_id": frame_id,
1801            "frame": frame_to_json(&updated_frame),
1802            "replaced_payload": replaced_payload,
1803        });
1804        println!("{}", serde_json::to_string_pretty(&json)?);
1805    } else {
1806        println!(
1807            "Updated frame {} → new frame {} (seq {})",
1808            frame_id, updated_frame.id, seq
1809        );
1810        println!(
1811            "Payload: {}",
1812            if replaced_payload {
1813                "replaced"
1814            } else {
1815                "reused"
1816            }
1817        );
1818        print_frame_summary(&mut mem, &updated_frame)?;
1819    }
1820
1821    Ok(())
1822}
1823
1824fn derive_uri(provided: Option<&str>, source: Option<&Path>) -> String {
1825    if let Some(uri) = provided {
1826        let sanitized = sanitize_uri(uri, true);
1827        return format!("mv2://{}", sanitized);
1828    }
1829
1830    if let Some(path) = source {
1831        let raw = path.to_string_lossy();
1832        let sanitized = sanitize_uri(&raw, false);
1833        return format!("mv2://{}", sanitized);
1834    }
1835
1836    format!("mv2://frames/{}", Uuid::new_v4())
1837}
1838
1839pub fn derive_video_uri(payload: &[u8], source: Option<&Path>, mime: &str) -> String {
1840    let digest = hash(payload).to_hex();
1841    let short = &digest[..32];
1842    let ext_from_path = source
1843        .and_then(|path| path.extension())
1844        .and_then(|ext| ext.to_str())
1845        .map(|ext| ext.trim_start_matches('.').to_ascii_lowercase())
1846        .filter(|ext| !ext.is_empty());
1847    let ext = ext_from_path
1848        .or_else(|| extension_from_mime(mime).map(|ext| ext.to_string()))
1849        .unwrap_or_else(|| "bin".to_string());
1850    format!("mv2://video/{short}.{ext}")
1851}
1852
1853fn derive_title(
1854    provided: Option<String>,
1855    source: Option<&Path>,
1856    payload_utf8: Option<&str>,
1857) -> Option<String> {
1858    if let Some(title) = provided {
1859        let trimmed = title.trim();
1860        if trimmed.is_empty() {
1861            None
1862        } else {
1863            Some(trimmed.to_string())
1864        }
1865    } else {
1866        if let Some(text) = payload_utf8 {
1867            if let Some(markdown_title) = extract_markdown_title(text) {
1868                return Some(markdown_title);
1869            }
1870        }
1871        source
1872            .and_then(|path| path.file_stem())
1873            .and_then(|stem| stem.to_str())
1874            .map(to_title_case)
1875    }
1876}
1877
1878fn extract_markdown_title(text: &str) -> Option<String> {
1879    for line in text.lines() {
1880        let trimmed = line.trim();
1881        if trimmed.starts_with('#') {
1882            let title = trimmed.trim_start_matches('#').trim();
1883            if !title.is_empty() {
1884                return Some(title.to_string());
1885            }
1886        }
1887    }
1888    None
1889}
1890
1891fn to_title_case(input: &str) -> String {
1892    if input.is_empty() {
1893        return String::new();
1894    }
1895    let mut chars = input.chars();
1896    let Some(first) = chars.next() else {
1897        return String::new();
1898    };
1899    let prefix = first.to_uppercase().collect::<String>();
1900    prefix + chars.as_str()
1901}
1902
1903fn should_skip_input(path: &Path) -> bool {
1904    matches!(
1905        path.file_name().and_then(|name| name.to_str()),
1906        Some(".DS_Store")
1907    )
1908}
1909
1910fn should_skip_dir(path: &Path) -> bool {
1911    matches!(
1912        path.file_name().and_then(|name| name.to_str()),
1913        Some(name) if name.starts_with('.')
1914    )
1915}
1916
1917enum InputSet {
1918    Stdin,
1919    Files(Vec<PathBuf>),
1920}
1921
1922/// Check if a file is an image based on extension
1923#[cfg(feature = "clip")]
1924fn is_image_file(path: &std::path::Path) -> bool {
1925    let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
1926        return false;
1927    };
1928    matches!(
1929        ext.to_ascii_lowercase().as_str(),
1930        "jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "tiff" | "tif" | "ico"
1931    )
1932}
1933
1934fn resolve_inputs(input: Option<&str>) -> Result<InputSet> {
1935    let Some(raw) = input else {
1936        return Ok(InputSet::Stdin);
1937    };
1938
1939    if raw.contains('*') || raw.contains('?') || raw.contains('[') {
1940        let mut files = Vec::new();
1941        let mut matched_any = false;
1942        for entry in glob(raw)? {
1943            let path = entry?;
1944            if path.is_file() {
1945                matched_any = true;
1946                if should_skip_input(&path) {
1947                    continue;
1948                }
1949                files.push(path);
1950            }
1951        }
1952        files.sort();
1953        if files.is_empty() {
1954            if matched_any {
1955                anyhow::bail!(
1956                    "pattern '{raw}' only matched files that are ignored by default (e.g. .DS_Store)"
1957                );
1958            }
1959            anyhow::bail!("pattern '{raw}' did not match any files");
1960        }
1961        return Ok(InputSet::Files(files));
1962    }
1963
1964    let path = PathBuf::from(raw);
1965    if path.is_dir() {
1966        let (mut files, skipped_any) = collect_directory_files(&path)?;
1967        files.sort();
1968        if files.is_empty() {
1969            if skipped_any {
1970                anyhow::bail!(
1971                    "directory '{}' contains only ignored files (e.g. .DS_Store/.git)",
1972                    path.display()
1973                );
1974            }
1975            anyhow::bail!(
1976                "directory '{}' contains no ingestible files",
1977                path.display()
1978            );
1979        }
1980        Ok(InputSet::Files(files))
1981    } else {
1982        Ok(InputSet::Files(vec![path]))
1983    }
1984}
1985
1986fn collect_directory_files(root: &Path) -> Result<(Vec<PathBuf>, bool)> {
1987    let mut files = Vec::new();
1988    let mut skipped_any = false;
1989    let mut stack = vec![root.to_path_buf()];
1990    while let Some(dir) = stack.pop() {
1991        for entry in fs::read_dir(&dir)? {
1992            let entry = entry?;
1993            let path = entry.path();
1994            let file_type = entry.file_type()?;
1995            if file_type.is_dir() {
1996                if should_skip_dir(&path) {
1997                    skipped_any = true;
1998                    continue;
1999                }
2000                stack.push(path);
2001            } else if file_type.is_file() {
2002                if should_skip_input(&path) {
2003                    skipped_any = true;
2004                    continue;
2005                }
2006                files.push(path);
2007            }
2008        }
2009    }
2010    Ok((files, skipped_any))
2011}
2012
2013struct IngestOutcome {
2014    report: PutReport,
2015    embedded: bool,
2016    #[cfg(feature = "parallel_segments")]
2017    parallel_input: Option<ParallelInput>,
2018}
2019
2020struct PutReport {
2021    seq: u64,
2022    #[allow(dead_code)] // Used in feature-gated code (clip, logic_mesh)
2023    frame_id: u64,
2024    uri: String,
2025    title: Option<String>,
2026    original_bytes: usize,
2027    stored_bytes: usize,
2028    compressed: bool,
2029    source: Option<PathBuf>,
2030    mime: Option<String>,
2031    metadata: Option<DocMetadata>,
2032    extraction: ExtractionSummary,
2033    /// Text content for entity extraction (only populated when --logic-mesh is enabled)
2034    #[cfg(feature = "logic_mesh")]
2035    search_text: Option<String>,
2036}
2037
2038struct CapacityGuard {
2039    #[allow(dead_code)]
2040    tier: Tier,
2041    capacity: u64,
2042    current_size: u64,
2043}
2044
2045impl CapacityGuard {
2046    const MIN_OVERHEAD: u64 = 128 * 1024;
2047    const RELATIVE_OVERHEAD: f64 = 0.05;
2048
2049    fn from_stats(stats: &Stats) -> Option<Self> {
2050        if stats.capacity_bytes == 0 {
2051            return None;
2052        }
2053        Some(Self {
2054            tier: stats.tier,
2055            capacity: stats.capacity_bytes,
2056            current_size: stats.size_bytes,
2057        })
2058    }
2059
2060    fn ensure_capacity(&self, additional: u64) -> Result<()> {
2061        let projected = self
2062            .current_size
2063            .saturating_add(additional)
2064            .saturating_add(Self::estimate_overhead(additional));
2065        if projected > self.capacity {
2066            return Err(map_put_error(
2067                MemvidError::CapacityExceeded {
2068                    current: self.current_size,
2069                    limit: self.capacity,
2070                    required: projected,
2071                },
2072                Some(self.capacity),
2073            ));
2074        }
2075        Ok(())
2076    }
2077
2078    fn update_after_commit(&mut self, stats: &Stats) {
2079        self.current_size = stats.size_bytes;
2080    }
2081
2082    fn capacity_hint(&self) -> Option<u64> {
2083        Some(self.capacity)
2084    }
2085
2086    // PHASE 2: Check capacity and warn at thresholds (50%, 75%, 90%)
2087    fn check_and_warn_capacity(&self) {
2088        if self.capacity == 0 {
2089            return;
2090        }
2091
2092        let usage_pct = (self.current_size as f64 / self.capacity as f64) * 100.0;
2093
2094        // Warn at key thresholds
2095        if usage_pct >= 90.0 && usage_pct < 91.0 {
2096            eprintln!(
2097                "⚠️  CRITICAL: 90% capacity used ({} / {})",
2098                format_bytes(self.current_size),
2099                format_bytes(self.capacity)
2100            );
2101            eprintln!("   Actions:");
2102            eprintln!("   1. Recreate with larger --size");
2103            eprintln!("   2. Delete old frames with: memvid delete <file> --uri <pattern>");
2104            eprintln!("   3. If using vectors, consider --no-embedding for new docs");
2105        } else if usage_pct >= 75.0 && usage_pct < 76.0 {
2106            eprintln!(
2107                "⚠️  WARNING: 75% capacity used ({} / {})",
2108                format_bytes(self.current_size),
2109                format_bytes(self.capacity)
2110            );
2111            eprintln!("   Consider planning for capacity expansion soon");
2112        } else if usage_pct >= 50.0 && usage_pct < 51.0 {
2113            eprintln!(
2114                "ℹ️  INFO: 50% capacity used ({} / {})",
2115                format_bytes(self.current_size),
2116                format_bytes(self.capacity)
2117            );
2118        }
2119    }
2120
2121    fn estimate_overhead(additional: u64) -> u64 {
2122        let fractional = ((additional as f64) * Self::RELATIVE_OVERHEAD).ceil() as u64;
2123        fractional.max(Self::MIN_OVERHEAD)
2124    }
2125}
2126
2127#[derive(Debug, Clone)]
2128pub struct FileAnalysis {
2129    pub mime: String,
2130    pub metadata: Option<DocMetadata>,
2131    pub search_text: Option<String>,
2132    pub extraction: ExtractionSummary,
2133}
2134
2135#[derive(Clone, Copy)]
2136pub struct AudioAnalyzeOptions {
2137    force: bool,
2138    segment_secs: u32,
2139}
2140
2141impl AudioAnalyzeOptions {
2142    const DEFAULT_SEGMENT_SECS: u32 = 30;
2143
2144    fn normalised_segment_secs(self) -> u32 {
2145        self.segment_secs.max(1)
2146    }
2147}
2148
2149impl Default for AudioAnalyzeOptions {
2150    fn default() -> Self {
2151        Self {
2152            force: false,
2153            segment_secs: Self::DEFAULT_SEGMENT_SECS,
2154        }
2155    }
2156}
2157
2158struct AudioAnalysis {
2159    metadata: DocAudioMetadata,
2160    caption: Option<String>,
2161    search_terms: Vec<String>,
2162}
2163
2164struct ImageAnalysis {
2165    width: u32,
2166    height: u32,
2167    palette: Vec<String>,
2168    caption: Option<String>,
2169    exif: Option<DocExifMetadata>,
2170}
2171
2172#[derive(Debug, Clone)]
2173pub struct ExtractionSummary {
2174    reader: Option<String>,
2175    status: ExtractionStatus,
2176    warnings: Vec<String>,
2177    duration_ms: Option<u64>,
2178    pages_processed: Option<u32>,
2179}
2180
2181impl ExtractionSummary {
2182    fn record_warning<S: Into<String>>(&mut self, warning: S) {
2183        self.warnings.push(warning.into());
2184    }
2185}
2186
2187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2188enum ExtractionStatus {
2189    Skipped,
2190    Ok,
2191    FallbackUsed,
2192    Empty,
2193    Failed,
2194}
2195
2196impl ExtractionStatus {
2197    fn label(self) -> &'static str {
2198        match self {
2199            Self::Skipped => "skipped",
2200            Self::Ok => "ok",
2201            Self::FallbackUsed => "fallback_used",
2202            Self::Empty => "empty",
2203            Self::Failed => "failed",
2204        }
2205    }
2206}
2207
2208fn analyze_video(source_path: Option<&Path>, mime: &str, bytes: u64) -> MediaManifest {
2209    let filename = source_path
2210        .and_then(|path| path.file_name())
2211        .and_then(|name| name.to_str())
2212        .map(|value| value.to_string());
2213    MediaManifest {
2214        kind: "video".to_string(),
2215        mime: mime.to_string(),
2216        bytes,
2217        filename,
2218        duration_ms: None,
2219        width: None,
2220        height: None,
2221        codec: None,
2222    }
2223}
2224
2225pub fn analyze_file(
2226    source_path: Option<&Path>,
2227    payload: &[u8],
2228    payload_utf8: Option<&str>,
2229    inferred_title: Option<&str>,
2230    audio_opts: AudioAnalyzeOptions,
2231    force_video: bool,
2232) -> FileAnalysis {
2233    let (mime, treat_as_text_base) = detect_mime(source_path, payload, payload_utf8);
2234    let is_video = force_video || mime.starts_with("video/");
2235    let treat_as_text = if is_video { false } else { treat_as_text_base };
2236
2237    let mut metadata = DocMetadata::default();
2238    metadata.mime = Some(mime.clone());
2239    metadata.bytes = Some(payload.len() as u64);
2240    metadata.hash = Some(hash(payload).to_hex().to_string());
2241
2242    let mut search_text = None;
2243
2244    let mut extraction = ExtractionSummary {
2245        reader: None,
2246        status: ExtractionStatus::Skipped,
2247        warnings: Vec::new(),
2248        duration_ms: None,
2249        pages_processed: None,
2250    };
2251
2252    let reader_registry = default_reader_registry();
2253    let magic = payload.get(..MAGIC_SNIFF_BYTES).and_then(|slice| {
2254        if slice.is_empty() {
2255            None
2256        } else {
2257            Some(slice)
2258        }
2259    });
2260
2261    let apply_extracted_text = |text: &str,
2262                                reader_label: &str,
2263                                status_if_applied: ExtractionStatus,
2264                                extraction: &mut ExtractionSummary,
2265                                metadata: &mut DocMetadata,
2266                                search_text: &mut Option<String>|
2267     -> bool {
2268        if let Some(normalized) = normalize_text(text, MAX_SEARCH_TEXT_LEN) {
2269            let mut value = normalized.text;
2270            if normalized.truncated {
2271                value.push('…');
2272            }
2273            if metadata.caption.is_none() {
2274                if let Some(caption) = caption_from_text(&value) {
2275                    metadata.caption = Some(caption);
2276                }
2277            }
2278            *search_text = Some(value);
2279            extraction.reader = Some(reader_label.to_string());
2280            extraction.status = status_if_applied;
2281            true
2282        } else {
2283            false
2284        }
2285    };
2286
2287    if is_video {
2288        metadata.media = Some(analyze_video(source_path, &mime, payload.len() as u64));
2289    }
2290
2291    if treat_as_text {
2292        if let Some(text) = payload_utf8 {
2293            if !apply_extracted_text(
2294                text,
2295                "bytes",
2296                ExtractionStatus::Ok,
2297                &mut extraction,
2298                &mut metadata,
2299                &mut search_text,
2300            ) {
2301                extraction.status = ExtractionStatus::Empty;
2302                extraction.reader = Some("bytes".to_string());
2303                let msg = "text payload contained no searchable content after normalization";
2304                extraction.record_warning(msg);
2305                warn!("{msg}");
2306            }
2307        } else {
2308            extraction.reader = Some("bytes".to_string());
2309            extraction.status = ExtractionStatus::Failed;
2310            let msg = "payload reported as text but was not valid UTF-8";
2311            extraction.record_warning(msg);
2312            warn!("{msg}");
2313        }
2314    } else if mime == "application/pdf"
2315        || mime == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
2316        || mime == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
2317        || mime == "application/vnd.openxmlformats-officedocument.presentationml.presentation"
2318        || mime == "application/vnd.ms-excel"
2319        || mime == "application/msword"
2320    {
2321        // Use reader registry for PDFs and Office documents (XLSX, DOCX, PPTX, etc.)
2322        let mut applied = false;
2323
2324        let format_hint = infer_document_format(Some(mime.as_str()), magic);
2325        let hint = ReaderHint::new(Some(mime.as_str()), format_hint)
2326            .with_uri(source_path.and_then(|p| p.to_str()))
2327            .with_magic(magic);
2328
2329        if let Some(reader) = reader_registry.find_reader(&hint) {
2330            match reader.extract(payload, &hint) {
2331                Ok(output) => {
2332                    extraction.reader = Some(output.reader_name.clone());
2333                    if let Some(ms) = output.diagnostics.duration_ms {
2334                        extraction.duration_ms = Some(ms);
2335                    }
2336                    if let Some(pages) = output.diagnostics.pages_processed {
2337                        extraction.pages_processed = Some(pages);
2338                    }
2339                    if let Some(mime_type) = output.document.mime_type.clone() {
2340                        metadata.mime = Some(mime_type);
2341                    }
2342
2343                    for warning in output.diagnostics.warnings.iter() {
2344                        extraction.record_warning(warning);
2345                        warn!("{warning}");
2346                    }
2347
2348                    let status = if output.diagnostics.fallback {
2349                        ExtractionStatus::FallbackUsed
2350                    } else {
2351                        ExtractionStatus::Ok
2352                    };
2353
2354                    if let Some(doc_text) = output.document.text.as_ref() {
2355                        applied = apply_extracted_text(
2356                            doc_text,
2357                            output.reader_name.as_str(),
2358                            status,
2359                            &mut extraction,
2360                            &mut metadata,
2361                            &mut search_text,
2362                        );
2363                        if !applied {
2364                            extraction.reader = Some(output.reader_name);
2365                            extraction.status = ExtractionStatus::Empty;
2366                            let msg = "primary reader returned no usable text";
2367                            extraction.record_warning(msg);
2368                            warn!("{msg}");
2369                        }
2370                    } else {
2371                        extraction.reader = Some(output.reader_name);
2372                        extraction.status = ExtractionStatus::Empty;
2373                        let msg = "primary reader returned empty text";
2374                        extraction.record_warning(msg);
2375                        warn!("{msg}");
2376                    }
2377                }
2378                Err(err) => {
2379                    let name = reader.name();
2380                    extraction.reader = Some(name.to_string());
2381                    extraction.status = ExtractionStatus::Failed;
2382                    let msg = format!("primary reader {name} failed: {err}");
2383                    extraction.record_warning(&msg);
2384                    warn!("{msg}");
2385                }
2386            }
2387        } else {
2388            extraction.record_warning("no registered reader matched this PDF payload");
2389            warn!("no registered reader matched this PDF payload");
2390        }
2391
2392        if !applied {
2393            match extract_pdf_text(payload) {
2394                Ok(pdf_text) => {
2395                    if !apply_extracted_text(
2396                        &pdf_text,
2397                        "pdf_extract",
2398                        ExtractionStatus::FallbackUsed,
2399                        &mut extraction,
2400                        &mut metadata,
2401                        &mut search_text,
2402                    ) {
2403                        extraction.reader = Some("pdf_extract".to_string());
2404                        extraction.status = ExtractionStatus::Empty;
2405                        let msg = "PDF text extraction yielded no searchable content";
2406                        extraction.record_warning(msg);
2407                        warn!("{msg}");
2408                    }
2409                }
2410                Err(err) => {
2411                    extraction.reader = Some("pdf_extract".to_string());
2412                    extraction.status = ExtractionStatus::Failed;
2413                    let msg = format!("failed to extract PDF text via fallback: {err}");
2414                    extraction.record_warning(&msg);
2415                    warn!("{msg}");
2416                }
2417            }
2418        }
2419    }
2420
2421    if !is_video && mime.starts_with("image/") {
2422        if let Some(image_meta) = analyze_image(payload) {
2423            let ImageAnalysis {
2424                width,
2425                height,
2426                palette,
2427                caption,
2428                exif,
2429            } = image_meta;
2430            metadata.width = Some(width);
2431            metadata.height = Some(height);
2432            if !palette.is_empty() {
2433                metadata.colors = Some(palette);
2434            }
2435            if metadata.caption.is_none() {
2436                metadata.caption = caption;
2437            }
2438            if let Some(exif) = exif {
2439                metadata.exif = Some(exif);
2440            }
2441        }
2442    }
2443
2444    if !is_video && (audio_opts.force || mime.starts_with("audio/")) {
2445        if let Some(AudioAnalysis {
2446            metadata: audio_metadata,
2447            caption: audio_caption,
2448            mut search_terms,
2449        }) = analyze_audio(payload, source_path, &mime, audio_opts)
2450        {
2451            if metadata.audio.is_none()
2452                || metadata
2453                    .audio
2454                    .as_ref()
2455                    .map_or(true, DocAudioMetadata::is_empty)
2456            {
2457                metadata.audio = Some(audio_metadata);
2458            }
2459            if metadata.caption.is_none() {
2460                metadata.caption = audio_caption;
2461            }
2462            if !search_terms.is_empty() {
2463                match &mut search_text {
2464                    Some(existing) => {
2465                        for term in search_terms.drain(..) {
2466                            if !existing.contains(&term) {
2467                                if !existing.ends_with(' ') {
2468                                    existing.push(' ');
2469                                }
2470                                existing.push_str(&term);
2471                            }
2472                        }
2473                    }
2474                    None => {
2475                        search_text = Some(search_terms.join(" "));
2476                    }
2477                }
2478            }
2479        }
2480    }
2481
2482    if metadata.caption.is_none() {
2483        if let Some(title) = inferred_title {
2484            let trimmed = title.trim();
2485            if !trimmed.is_empty() {
2486                metadata.caption = Some(truncate_to_boundary(trimmed, 240));
2487            }
2488        }
2489    }
2490
2491    FileAnalysis {
2492        mime,
2493        metadata: if metadata.is_empty() {
2494            None
2495        } else {
2496            Some(metadata)
2497        },
2498        search_text,
2499        extraction,
2500    }
2501}
2502
2503fn default_reader_registry() -> &'static ReaderRegistry {
2504    static REGISTRY: OnceLock<ReaderRegistry> = OnceLock::new();
2505    REGISTRY.get_or_init(ReaderRegistry::default)
2506}
2507
2508fn infer_document_format(mime: Option<&str>, magic: Option<&[u8]>) -> Option<DocumentFormat> {
2509    if detect_pdf_magic(magic) {
2510        return Some(DocumentFormat::Pdf);
2511    }
2512
2513    let mime = mime?.trim().to_ascii_lowercase();
2514    match mime.as_str() {
2515        "application/pdf" => Some(DocumentFormat::Pdf),
2516        "text/plain" => Some(DocumentFormat::PlainText),
2517        "text/markdown" => Some(DocumentFormat::Markdown),
2518        "text/html" | "application/xhtml+xml" => Some(DocumentFormat::Html),
2519        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => {
2520            Some(DocumentFormat::Docx)
2521        }
2522        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => {
2523            Some(DocumentFormat::Pptx)
2524        }
2525        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => {
2526            Some(DocumentFormat::Xlsx)
2527        }
2528        other if other.starts_with("text/") => Some(DocumentFormat::PlainText),
2529        _ => None,
2530    }
2531}
2532
2533fn detect_pdf_magic(magic: Option<&[u8]>) -> bool {
2534    let mut slice = match magic {
2535        Some(slice) if !slice.is_empty() => slice,
2536        _ => return false,
2537    };
2538    if slice.starts_with(&[0xEF, 0xBB, 0xBF]) {
2539        slice = &slice[3..];
2540    }
2541    while let Some((first, rest)) = slice.split_first() {
2542        if first.is_ascii_whitespace() {
2543            slice = rest;
2544        } else {
2545            break;
2546        }
2547    }
2548    slice.starts_with(b"%PDF")
2549}
2550
2551fn extract_pdf_text(payload: &[u8]) -> Result<String, PdfExtractError> {
2552    match pdf_extract::extract_text_from_mem(payload) {
2553        Ok(text) if text.trim().is_empty() => match fallback_pdftotext(payload) {
2554            Ok(fallback) => Ok(fallback),
2555            Err(err) => {
2556                warn!("pdf_extract returned empty text and pdftotext fallback failed: {err}");
2557                Ok(text)
2558            }
2559        },
2560        Err(err) => {
2561            warn!("pdf_extract failed: {err}");
2562            match fallback_pdftotext(payload) {
2563                Ok(fallback) => Ok(fallback),
2564                Err(fallback_err) => {
2565                    warn!("pdftotext fallback failed: {fallback_err}");
2566                    Err(err)
2567                }
2568            }
2569        }
2570        other => other,
2571    }
2572}
2573
2574fn fallback_pdftotext(payload: &[u8]) -> Result<String> {
2575    use std::io::Write;
2576    use std::process::{Command, Stdio};
2577
2578    let pdftotext = which::which("pdftotext").context("pdftotext binary not found in PATH")?;
2579
2580    let mut temp_pdf = tempfile::NamedTempFile::new().context("failed to create temp pdf file")?;
2581    temp_pdf
2582        .write_all(payload)
2583        .context("failed to write pdf payload to temp file")?;
2584    temp_pdf.flush().context("failed to flush temp pdf file")?;
2585
2586    let child = Command::new(pdftotext)
2587        .arg("-layout")
2588        .arg(temp_pdf.path())
2589        .arg("-")
2590        .stdout(Stdio::piped())
2591        .spawn()
2592        .context("failed to spawn pdftotext")?;
2593
2594    let output = child
2595        .wait_with_output()
2596        .context("failed to read pdftotext output")?;
2597
2598    if !output.status.success() {
2599        return Err(anyhow!("pdftotext exited with status {}", output.status));
2600    }
2601
2602    let text = String::from_utf8(output.stdout).context("pdftotext produced non-UTF8 output")?;
2603    Ok(text)
2604}
2605
2606fn detect_mime(
2607    source_path: Option<&Path>,
2608    payload: &[u8],
2609    payload_utf8: Option<&str>,
2610) -> (String, bool) {
2611    if let Some(kind) = infer::get(payload) {
2612        let mime = kind.mime_type().to_string();
2613        let treat_as_text = mime.starts_with("text/")
2614            || matches!(
2615                mime.as_str(),
2616                "application/json" | "application/xml" | "application/javascript" | "image/svg+xml"
2617            );
2618        return (mime, treat_as_text);
2619    }
2620
2621    let magic = magic_from_u8(payload);
2622    if !magic.is_empty() && magic != "application/octet-stream" {
2623        let treat_as_text = magic.starts_with("text/")
2624            || matches!(
2625                magic,
2626                "application/json"
2627                    | "application/xml"
2628                    | "application/javascript"
2629                    | "image/svg+xml"
2630                    | "text/plain"
2631            );
2632        return (magic.to_string(), treat_as_text);
2633    }
2634
2635    if let Some(path) = source_path {
2636        if let Some(ext) = path.extension().and_then(|ext| ext.to_str()) {
2637            if let Some((mime, treat_as_text)) = mime_from_extension(ext) {
2638                return (mime.to_string(), treat_as_text);
2639            }
2640        }
2641    }
2642
2643    if payload_utf8.is_some() {
2644        return ("text/plain".to_string(), true);
2645    }
2646
2647    ("application/octet-stream".to_string(), false)
2648}
2649
2650fn mime_from_extension(ext: &str) -> Option<(&'static str, bool)> {
2651    let ext_lower = ext.to_ascii_lowercase();
2652    match ext_lower.as_str() {
2653        "txt" | "text" | "log" | "cfg" | "conf" | "ini" | "properties" | "sql" | "rs" | "py"
2654        | "js" | "ts" | "tsx" | "jsx" | "c" | "h" | "cpp" | "hpp" | "go" | "rb" | "php" | "css"
2655        | "scss" | "sass" | "sh" | "bash" | "zsh" | "ps1" | "swift" | "kt" | "java" | "scala"
2656        | "lua" | "pl" | "pm" | "r" | "erl" | "ex" | "exs" | "dart" => Some(("text/plain", true)),
2657        "md" | "markdown" => Some(("text/markdown", true)),
2658        "rst" => Some(("text/x-rst", true)),
2659        "json" => Some(("application/json", true)),
2660        "csv" => Some(("text/csv", true)),
2661        "tsv" => Some(("text/tab-separated-values", true)),
2662        "yaml" | "yml" => Some(("application/yaml", true)),
2663        "toml" => Some(("application/toml", true)),
2664        "html" | "htm" => Some(("text/html", true)),
2665        "xml" => Some(("application/xml", true)),
2666        "svg" => Some(("image/svg+xml", true)),
2667        "gif" => Some(("image/gif", false)),
2668        "jpg" | "jpeg" => Some(("image/jpeg", false)),
2669        "png" => Some(("image/png", false)),
2670        "bmp" => Some(("image/bmp", false)),
2671        "ico" => Some(("image/x-icon", false)),
2672        "tif" | "tiff" => Some(("image/tiff", false)),
2673        "webp" => Some(("image/webp", false)),
2674        _ => None,
2675    }
2676}
2677
2678fn caption_from_text(text: &str) -> Option<String> {
2679    for line in text.lines() {
2680        let trimmed = line.trim();
2681        if !trimmed.is_empty() {
2682            return Some(truncate_to_boundary(trimmed, 240));
2683        }
2684    }
2685    None
2686}
2687
2688fn truncate_to_boundary(text: &str, max_len: usize) -> String {
2689    if text.len() <= max_len {
2690        return text.to_string();
2691    }
2692    let mut end = max_len;
2693    while end > 0 && !text.is_char_boundary(end) {
2694        end -= 1;
2695    }
2696    if end == 0 {
2697        return String::new();
2698    }
2699    let mut truncated = text[..end].trim_end().to_string();
2700    truncated.push('…');
2701    truncated
2702}
2703
2704fn analyze_image(payload: &[u8]) -> Option<ImageAnalysis> {
2705    let reader = ImageReader::new(Cursor::new(payload))
2706        .with_guessed_format()
2707        .map_err(|err| warn!("failed to guess image format: {err}"))
2708        .ok()?;
2709    let image = reader
2710        .decode()
2711        .map_err(|err| warn!("failed to decode image: {err}"))
2712        .ok()?;
2713    let width = image.width();
2714    let height = image.height();
2715    let rgb = image.to_rgb8();
2716    let palette = match get_palette(
2717        rgb.as_raw(),
2718        ColorFormat::Rgb,
2719        COLOR_PALETTE_SIZE,
2720        COLOR_PALETTE_QUALITY,
2721    ) {
2722        Ok(colors) => colors.into_iter().map(color_to_hex).collect(),
2723        Err(err) => {
2724            warn!("failed to compute colour palette: {err}");
2725            Vec::new()
2726        }
2727    };
2728
2729    let (exif, exif_caption) = extract_exif_metadata(payload);
2730
2731    Some(ImageAnalysis {
2732        width,
2733        height,
2734        palette,
2735        caption: exif_caption,
2736        exif,
2737    })
2738}
2739
2740fn color_to_hex(color: Color) -> String {
2741    format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b)
2742}
2743
2744fn analyze_audio(
2745    payload: &[u8],
2746    source_path: Option<&Path>,
2747    mime: &str,
2748    options: AudioAnalyzeOptions,
2749) -> Option<AudioAnalysis> {
2750    use symphonia::core::codecs::{CodecParameters, DecoderOptions, CODEC_TYPE_NULL};
2751    use symphonia::core::errors::Error as SymphoniaError;
2752    use symphonia::core::formats::FormatOptions;
2753    use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
2754    use symphonia::core::meta::MetadataOptions;
2755    use symphonia::core::probe::Hint;
2756
2757    let cursor = Cursor::new(payload.to_vec());
2758    let mss = MediaSourceStream::new(Box::new(cursor), MediaSourceStreamOptions::default());
2759
2760    let mut hint = Hint::new();
2761    if let Some(path) = source_path {
2762        if let Some(ext) = path.extension().and_then(|ext| ext.to_str()) {
2763            hint.with_extension(ext);
2764        }
2765    }
2766    if let Some(suffix) = mime.split('/').nth(1) {
2767        hint.with_extension(suffix);
2768    }
2769
2770    let probed = symphonia::default::get_probe()
2771        .format(
2772            &hint,
2773            mss,
2774            &FormatOptions::default(),
2775            &MetadataOptions::default(),
2776        )
2777        .map_err(|err| warn!("failed to probe audio stream: {err}"))
2778        .ok()?;
2779
2780    let mut format = probed.format;
2781    let track = format.default_track()?;
2782    let track_id = track.id;
2783    let codec_params: CodecParameters = track.codec_params.clone();
2784    let sample_rate = codec_params.sample_rate;
2785    let channel_count = codec_params.channels.map(|channels| channels.count() as u8);
2786
2787    let mut decoder = symphonia::default::get_codecs()
2788        .make(&codec_params, &DecoderOptions::default())
2789        .map_err(|err| warn!("failed to create audio decoder: {err}"))
2790        .ok()?;
2791
2792    let mut decoded_frames: u64 = 0;
2793    loop {
2794        let packet = match format.next_packet() {
2795            Ok(packet) => packet,
2796            Err(SymphoniaError::IoError(_)) => break,
2797            Err(SymphoniaError::DecodeError(err)) => {
2798                warn!("skipping undecodable audio packet: {err}");
2799                continue;
2800            }
2801            Err(SymphoniaError::ResetRequired) => {
2802                decoder.reset();
2803                continue;
2804            }
2805            Err(other) => {
2806                warn!("stopping audio analysis due to error: {other}");
2807                break;
2808            }
2809        };
2810
2811        if packet.track_id() != track_id {
2812            continue;
2813        }
2814
2815        match decoder.decode(&packet) {
2816            Ok(audio_buf) => {
2817                decoded_frames = decoded_frames.saturating_add(audio_buf.frames() as u64);
2818            }
2819            Err(SymphoniaError::DecodeError(err)) => {
2820                warn!("failed to decode audio packet: {err}");
2821            }
2822            Err(SymphoniaError::IoError(_)) => break,
2823            Err(SymphoniaError::ResetRequired) => {
2824                decoder.reset();
2825            }
2826            Err(other) => {
2827                warn!("decoder error: {other}");
2828                break;
2829            }
2830        }
2831    }
2832
2833    let duration_secs = match sample_rate {
2834        Some(rate) if rate > 0 => decoded_frames as f64 / rate as f64,
2835        _ => 0.0,
2836    };
2837
2838    let bitrate_kbps = if duration_secs > 0.0 {
2839        Some(((payload.len() as f64 * 8.0) / duration_secs / 1_000.0).round() as u32)
2840    } else {
2841        None
2842    };
2843
2844    let tags = extract_lofty_tags(payload);
2845    let caption = tags
2846        .get("title")
2847        .cloned()
2848        .or_else(|| tags.get("tracktitle").cloned());
2849
2850    let mut search_terms = Vec::new();
2851    if let Some(title) = tags.get("title").or_else(|| tags.get("tracktitle")) {
2852        search_terms.push(title.clone());
2853    }
2854    if let Some(artist) = tags.get("artist") {
2855        search_terms.push(artist.clone());
2856    }
2857    if let Some(album) = tags.get("album") {
2858        search_terms.push(album.clone());
2859    }
2860    if let Some(genre) = tags.get("genre") {
2861        search_terms.push(genre.clone());
2862    }
2863
2864    let mut segments = Vec::new();
2865    if duration_secs > 0.0 {
2866        let segment_len = options.normalised_segment_secs() as f64;
2867        if segment_len > 0.0 {
2868            let mut start = 0.0;
2869            let mut idx = 1usize;
2870            while start < duration_secs {
2871                let end = (start + segment_len).min(duration_secs);
2872                segments.push(AudioSegmentMetadata {
2873                    start_seconds: start as f32,
2874                    end_seconds: end as f32,
2875                    label: Some(format!("Segment {}", idx)),
2876                });
2877                if end >= duration_secs {
2878                    break;
2879                }
2880                start = end;
2881                idx += 1;
2882            }
2883        }
2884    }
2885
2886    let mut metadata = DocAudioMetadata::default();
2887    if duration_secs > 0.0 {
2888        metadata.duration_secs = Some(duration_secs as f32);
2889    }
2890    if let Some(rate) = sample_rate {
2891        metadata.sample_rate_hz = Some(rate);
2892    }
2893    if let Some(channels) = channel_count {
2894        metadata.channels = Some(channels);
2895    }
2896    if let Some(bitrate) = bitrate_kbps {
2897        metadata.bitrate_kbps = Some(bitrate);
2898    }
2899    if codec_params.codec != CODEC_TYPE_NULL {
2900        metadata.codec = Some(format!("{:?}", codec_params.codec));
2901    }
2902    if !segments.is_empty() {
2903        metadata.segments = segments;
2904    }
2905    if !tags.is_empty() {
2906        metadata.tags = tags
2907            .iter()
2908            .map(|(k, v)| (k.clone(), v.clone()))
2909            .collect::<BTreeMap<_, _>>();
2910    }
2911
2912    Some(AudioAnalysis {
2913        metadata,
2914        caption,
2915        search_terms,
2916    })
2917}
2918
2919fn extract_lofty_tags(payload: &[u8]) -> HashMap<String, String> {
2920    use lofty::{ItemKey, Probe as LoftyProbe, Tag, TaggedFileExt};
2921
2922    fn collect_tag(tag: &Tag, out: &mut HashMap<String, String>) {
2923        if let Some(value) = tag.get_string(&ItemKey::TrackTitle) {
2924            out.entry("title".into())
2925                .or_insert_with(|| value.to_string());
2926            out.entry("tracktitle".into())
2927                .or_insert_with(|| value.to_string());
2928        }
2929        if let Some(value) = tag.get_string(&ItemKey::TrackArtist) {
2930            out.entry("artist".into())
2931                .or_insert_with(|| value.to_string());
2932        } else if let Some(value) = tag.get_string(&ItemKey::AlbumArtist) {
2933            out.entry("artist".into())
2934                .or_insert_with(|| value.to_string());
2935        }
2936        if let Some(value) = tag.get_string(&ItemKey::AlbumTitle) {
2937            out.entry("album".into())
2938                .or_insert_with(|| value.to_string());
2939        }
2940        if let Some(value) = tag.get_string(&ItemKey::Genre) {
2941            out.entry("genre".into())
2942                .or_insert_with(|| value.to_string());
2943        }
2944        if let Some(value) = tag.get_string(&ItemKey::TrackNumber) {
2945            out.entry("track_number".into())
2946                .or_insert_with(|| value.to_string());
2947        }
2948        if let Some(value) = tag.get_string(&ItemKey::DiscNumber) {
2949            out.entry("disc_number".into())
2950                .or_insert_with(|| value.to_string());
2951        }
2952    }
2953
2954    let mut tags = HashMap::new();
2955    let probe = match LoftyProbe::new(Cursor::new(payload)).guess_file_type() {
2956        Ok(probe) => probe,
2957        Err(err) => {
2958            warn!("failed to guess audio tag file type: {err}");
2959            return tags;
2960        }
2961    };
2962
2963    let tagged_file = match probe.read() {
2964        Ok(file) => file,
2965        Err(err) => {
2966            warn!("failed to read audio tags: {err}");
2967            return tags;
2968        }
2969    };
2970
2971    if let Some(primary) = tagged_file.primary_tag() {
2972        collect_tag(primary, &mut tags);
2973    }
2974    for tag in tagged_file.tags() {
2975        collect_tag(tag, &mut tags);
2976    }
2977
2978    tags
2979}
2980
2981fn extract_exif_metadata(payload: &[u8]) -> (Option<DocExifMetadata>, Option<String>) {
2982    let mut cursor = Cursor::new(payload);
2983    let exif = match ExifReader::new().read_from_container(&mut cursor) {
2984        Ok(exif) => exif,
2985        Err(err) => {
2986            warn!("failed to read EXIF metadata: {err}");
2987            return (None, None);
2988        }
2989    };
2990
2991    let mut doc = DocExifMetadata::default();
2992    let mut has_data = false;
2993
2994    if let Some(make) = exif_string(&exif, Tag::Make) {
2995        doc.make = Some(make);
2996        has_data = true;
2997    }
2998    if let Some(model) = exif_string(&exif, Tag::Model) {
2999        doc.model = Some(model);
3000        has_data = true;
3001    }
3002    if let Some(lens) =
3003        exif_string(&exif, Tag::LensModel).or_else(|| exif_string(&exif, Tag::LensMake))
3004    {
3005        doc.lens = Some(lens);
3006        has_data = true;
3007    }
3008    if let Some(dt) =
3009        exif_string(&exif, Tag::DateTimeOriginal).or_else(|| exif_string(&exif, Tag::DateTime))
3010    {
3011        doc.datetime = Some(dt);
3012        has_data = true;
3013    }
3014
3015    if let Some(gps) = extract_gps_metadata(&exif) {
3016        doc.gps = Some(gps);
3017        has_data = true;
3018    }
3019
3020    let caption = exif_string(&exif, Tag::ImageDescription);
3021
3022    let metadata = if has_data { Some(doc) } else { None };
3023    (metadata, caption)
3024}
3025
3026fn exif_string(exif: &exif::Exif, tag: Tag) -> Option<String> {
3027    exif.fields()
3028        .find(|field| field.tag == tag)
3029        .and_then(|field| field_to_string(field, exif))
3030}
3031
3032fn field_to_string(field: &exif::Field, exif: &exif::Exif) -> Option<String> {
3033    let value = field.display_value().with_unit(exif).to_string();
3034    let trimmed = value.trim_matches('\0').trim();
3035    if trimmed.is_empty() {
3036        None
3037    } else {
3038        Some(trimmed.to_string())
3039    }
3040}
3041
3042fn extract_gps_metadata(exif: &exif::Exif) -> Option<DocGpsMetadata> {
3043    let latitude_field = exif.fields().find(|field| field.tag == Tag::GPSLatitude)?;
3044    let latitude_ref_field = exif
3045        .fields()
3046        .find(|field| field.tag == Tag::GPSLatitudeRef)?;
3047    let longitude_field = exif.fields().find(|field| field.tag == Tag::GPSLongitude)?;
3048    let longitude_ref_field = exif
3049        .fields()
3050        .find(|field| field.tag == Tag::GPSLongitudeRef)?;
3051
3052    let mut latitude = gps_value_to_degrees(&latitude_field.value)?;
3053    let mut longitude = gps_value_to_degrees(&longitude_field.value)?;
3054
3055    if let Some(reference) = value_to_ascii(&latitude_ref_field.value) {
3056        if reference.eq_ignore_ascii_case("S") {
3057            latitude = -latitude;
3058        }
3059    }
3060    if let Some(reference) = value_to_ascii(&longitude_ref_field.value) {
3061        if reference.eq_ignore_ascii_case("W") {
3062            longitude = -longitude;
3063        }
3064    }
3065
3066    Some(DocGpsMetadata {
3067        latitude,
3068        longitude,
3069    })
3070}
3071
3072fn gps_value_to_degrees(value: &ExifValue) -> Option<f64> {
3073    match value {
3074        ExifValue::Rational(values) if !values.is_empty() => {
3075            let deg = rational_to_f64_u(values.get(0)?)?;
3076            let min = values
3077                .get(1)
3078                .and_then(|v| rational_to_f64_u(v))
3079                .unwrap_or(0.0);
3080            let sec = values
3081                .get(2)
3082                .and_then(|v| rational_to_f64_u(v))
3083                .unwrap_or(0.0);
3084            Some(deg + (min / 60.0) + (sec / 3600.0))
3085        }
3086        ExifValue::SRational(values) if !values.is_empty() => {
3087            let deg = rational_to_f64_i(values.get(0)?)?;
3088            let min = values
3089                .get(1)
3090                .and_then(|v| rational_to_f64_i(v))
3091                .unwrap_or(0.0);
3092            let sec = values
3093                .get(2)
3094                .and_then(|v| rational_to_f64_i(v))
3095                .unwrap_or(0.0);
3096            Some(deg + (min / 60.0) + (sec / 3600.0))
3097        }
3098        _ => None,
3099    }
3100}
3101
3102fn rational_to_f64_u(value: &exif::Rational) -> Option<f64> {
3103    if value.denom == 0 {
3104        None
3105    } else {
3106        Some(value.num as f64 / value.denom as f64)
3107    }
3108}
3109
3110fn rational_to_f64_i(value: &exif::SRational) -> Option<f64> {
3111    if value.denom == 0 {
3112        None
3113    } else {
3114        Some(value.num as f64 / value.denom as f64)
3115    }
3116}
3117
3118fn value_to_ascii(value: &ExifValue) -> Option<String> {
3119    if let ExifValue::Ascii(values) = value {
3120        values
3121            .first()
3122            .and_then(|bytes| std::str::from_utf8(bytes).ok())
3123            .map(|s| s.trim_matches('\0').trim().to_string())
3124            .filter(|s| !s.is_empty())
3125    } else {
3126        None
3127    }
3128}
3129
3130fn ingest_payload(
3131    mem: &mut Memvid,
3132    args: &PutArgs,
3133    payload: Vec<u8>,
3134    source_path: Option<&Path>,
3135    capacity_guard: Option<&mut CapacityGuard>,
3136    enable_embedding: bool,
3137    runtime: Option<&EmbeddingRuntime>,
3138    parallel_mode: bool,
3139) -> Result<IngestOutcome> {
3140    let original_bytes = payload.len();
3141    let (stored_bytes, compressed) = canonical_storage_len(&payload)?;
3142
3143    let payload_text = std::str::from_utf8(&payload).ok();
3144    let inferred_title = derive_title(args.title.clone(), source_path, payload_text);
3145
3146    let audio_opts = AudioAnalyzeOptions {
3147        force: args.audio,
3148        segment_secs: args
3149            .audio_segment_seconds
3150            .unwrap_or(AudioAnalyzeOptions::DEFAULT_SEGMENT_SECS),
3151    };
3152
3153    let mut analysis = analyze_file(
3154        source_path,
3155        &payload,
3156        payload_text,
3157        inferred_title.as_deref(),
3158        audio_opts,
3159        args.video,
3160    );
3161
3162    if args.video && !analysis.mime.starts_with("video/") {
3163        anyhow::bail!(
3164            "--video requires a video input; detected MIME type {}",
3165            analysis.mime
3166        );
3167    }
3168
3169    let mut search_text = analysis.search_text.clone();
3170    if let Some(ref mut text) = search_text {
3171        if text.len() > MAX_SEARCH_TEXT_LEN {
3172            let truncated = truncate_to_boundary(text, MAX_SEARCH_TEXT_LEN);
3173            *text = truncated;
3174        }
3175    }
3176    analysis.search_text = search_text.clone();
3177
3178    let uri = if let Some(ref explicit) = args.uri {
3179        derive_uri(Some(explicit), None)
3180    } else if args.video {
3181        derive_video_uri(&payload, source_path, &analysis.mime)
3182    } else {
3183        derive_uri(None, source_path)
3184    };
3185
3186    let mut options_builder = PutOptions::builder()
3187        .enable_embedding(enable_embedding)
3188        .auto_tag(!args.no_auto_tag)
3189        .extract_dates(!args.no_extract_dates);
3190    if let Some(ts) = args.timestamp {
3191        options_builder = options_builder.timestamp(ts);
3192    }
3193    if let Some(track) = &args.track {
3194        options_builder = options_builder.track(track.clone());
3195    }
3196    if args.video {
3197        options_builder = options_builder.kind("video");
3198        options_builder = options_builder.tag("kind", "video");
3199        options_builder = options_builder.push_tag("video");
3200    } else if let Some(kind) = &args.kind {
3201        options_builder = options_builder.kind(kind.clone());
3202    }
3203    options_builder = options_builder.uri(uri.clone());
3204    if let Some(ref title) = inferred_title {
3205        options_builder = options_builder.title(title.clone());
3206    }
3207    for (key, value) in &args.tags {
3208        options_builder = options_builder.tag(key.clone(), value.clone());
3209        if !key.is_empty() {
3210            options_builder = options_builder.push_tag(key.clone());
3211        }
3212        if !value.is_empty() && value != key {
3213            options_builder = options_builder.push_tag(value.clone());
3214        }
3215    }
3216    for label in &args.labels {
3217        options_builder = options_builder.label(label.clone());
3218    }
3219    if let Some(metadata) = analysis.metadata.clone() {
3220        if !metadata.is_empty() {
3221            options_builder = options_builder.metadata(metadata);
3222        }
3223    }
3224    for (idx, entry) in args.metadata.iter().enumerate() {
3225        match serde_json::from_str::<DocMetadata>(entry) {
3226            Ok(meta) => {
3227                options_builder = options_builder.metadata(meta);
3228            }
3229            Err(_) => match serde_json::from_str::<serde_json::Value>(entry) {
3230                Ok(value) => {
3231                    options_builder =
3232                        options_builder.metadata_entry(format!("custom_metadata_{}", idx), value);
3233                }
3234                Err(err) => {
3235                    warn!("failed to parse --metadata JSON: {err}");
3236                }
3237            },
3238        }
3239    }
3240    if let Some(text) = search_text.clone() {
3241        if !text.trim().is_empty() {
3242            options_builder = options_builder.search_text(text);
3243        }
3244    }
3245    let options = options_builder.build();
3246
3247    let existing_frame = if args.update_existing || !args.allow_duplicate {
3248        match mem.frame_by_uri(&uri) {
3249            Ok(frame) => Some(frame),
3250            Err(MemvidError::FrameNotFoundByUri { .. }) => None,
3251            Err(err) => return Err(err.into()),
3252        }
3253    } else {
3254        None
3255    };
3256
3257    // Compute frame_id: for updates it's the existing frame's id,
3258    // for new frames it's the current frame count (which becomes the next id)
3259    let frame_id = if let Some(ref existing) = existing_frame {
3260        existing.id
3261    } else {
3262        mem.stats()?.frame_count
3263    };
3264
3265    let mut embedded = false;
3266    let allow_embedding = enable_embedding && !args.video;
3267    if enable_embedding && !allow_embedding && args.video {
3268        warn!("semantic embeddings are not generated for video payloads");
3269    }
3270    let seq = if let Some(existing) = existing_frame {
3271        if args.update_existing {
3272            let payload_for_update = payload.clone();
3273            if allow_embedding {
3274                let runtime = runtime.ok_or_else(|| anyhow!("semantic runtime unavailable"))?;
3275                let embed_text = search_text
3276                    .clone()
3277                    .or_else(|| payload_text.map(|text| text.to_string()))
3278                    .unwrap_or_default();
3279                if embed_text.trim().is_empty() {
3280                    warn!("no textual content available; embedding skipped");
3281                    mem.update_frame(existing.id, Some(payload_for_update), options.clone(), None)
3282                        .map_err(|err| {
3283                            map_put_error(
3284                                err,
3285                                capacity_guard.as_ref().and_then(|g| g.capacity_hint()),
3286                            )
3287                        })?
3288                } else {
3289                    // Truncate to avoid token limits
3290                    let truncated_text = truncate_for_embedding(&embed_text);
3291                    if truncated_text.len() < embed_text.len() {
3292                        info!(
3293                            "Truncated text from {} to {} chars for embedding",
3294                            embed_text.len(),
3295                            truncated_text.len()
3296                        );
3297                    }
3298                    let embedding = runtime.embed(&truncated_text)?;
3299                    embedded = true;
3300                    mem.update_frame(
3301                        existing.id,
3302                        Some(payload_for_update),
3303                        options.clone(),
3304                        Some(embedding),
3305                    )
3306                    .map_err(|err| {
3307                        map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3308                    })?
3309                }
3310            } else {
3311                mem.update_frame(existing.id, Some(payload_for_update), options.clone(), None)
3312                    .map_err(|err| {
3313                        map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3314                    })?
3315            }
3316        } else {
3317            return Err(DuplicateUriError::new(uri.as_str()).into());
3318        }
3319    } else {
3320        if let Some(guard) = capacity_guard.as_ref() {
3321            guard.ensure_capacity(stored_bytes as u64)?;
3322        }
3323        if parallel_mode {
3324            #[cfg(feature = "parallel_segments")]
3325            {
3326                let mut parent_embedding = None;
3327                let mut chunk_embeddings_vec = None;
3328                if allow_embedding {
3329                    let runtime = runtime.ok_or_else(|| anyhow!("semantic runtime unavailable"))?;
3330                    let embed_text = search_text
3331                        .clone()
3332                        .or_else(|| payload_text.map(|text| text.to_string()))
3333                        .unwrap_or_default();
3334                    if embed_text.trim().is_empty() {
3335                        warn!("no textual content available; embedding skipped");
3336                    } else {
3337                        // Check if document will be chunked - if so, embed each chunk
3338                        info!(
3339                            "parallel mode: checking for chunks on {} bytes payload",
3340                            payload.len()
3341                        );
3342                        if let Some(chunk_texts) = mem.preview_chunks(&payload) {
3343                            // Document will be chunked - embed each chunk for full semantic coverage
3344                            info!("parallel mode: Document will be chunked into {} chunks, generating embeddings for each", chunk_texts.len());
3345
3346                            // Apply temporal enrichment if enabled (before contextual)
3347                            #[cfg(feature = "temporal_enrich")]
3348                            let enriched_chunks = if args.temporal_enrich {
3349                                info!(
3350                                    "Temporal enrichment enabled, processing {} chunks",
3351                                    chunk_texts.len()
3352                                );
3353                                // Use today's date as fallback document date
3354                                let today = chrono::Local::now().date_naive();
3355                                let results = temporal_enrich_chunks(&chunk_texts, Some(today));
3356                                // Results are tuples of (enriched_text, TemporalEnrichment)
3357                                let enriched: Vec<String> =
3358                                    results.iter().map(|(text, _)| text.clone()).collect();
3359                                let resolved_count = results
3360                                    .iter()
3361                                    .filter(|(_, e)| {
3362                                        e.relative_phrases.iter().any(|p| p.resolved.is_some())
3363                                    })
3364                                    .count();
3365                                info!(
3366                                    "Temporal enrichment: resolved {} chunks with temporal context",
3367                                    resolved_count
3368                                );
3369                                enriched
3370                            } else {
3371                                chunk_texts.clone()
3372                            };
3373                            #[cfg(not(feature = "temporal_enrich"))]
3374                            let enriched_chunks = {
3375                                if args.temporal_enrich {
3376                                    warn!(
3377                                        "Temporal enrichment requested but feature not compiled in"
3378                                    );
3379                                }
3380                                chunk_texts.clone()
3381                            };
3382
3383                            // Apply contextual retrieval if enabled
3384                            let embed_chunks = if args.contextual {
3385                                info!("Contextual retrieval enabled, generating context prefixes for {} chunks", enriched_chunks.len());
3386                                let engine = if args.contextual_model.as_deref() == Some("local") {
3387                                    #[cfg(feature = "llama-cpp")]
3388                                    {
3389                                        let model_path = get_local_contextual_model_path()?;
3390                                        ContextualEngine::local(model_path)
3391                                    }
3392                                    #[cfg(not(feature = "llama-cpp"))]
3393                                    {
3394                                        anyhow::bail!("Local contextual model requires the 'llama-cpp' feature. Use --contextual-model openai or omit the flag for OpenAI.");
3395                                    }
3396                                } else if let Some(model) = &args.contextual_model {
3397                                    ContextualEngine::openai_with_model(model)?
3398                                } else {
3399                                    ContextualEngine::openai()?
3400                                };
3401
3402                                match engine.generate_contexts_batch(&embed_text, &enriched_chunks)
3403                                {
3404                                    Ok(contexts) => {
3405                                        info!("Generated {} contextual prefixes", contexts.len());
3406                                        apply_contextual_prefixes(
3407                                            &embed_text,
3408                                            &enriched_chunks,
3409                                            &contexts,
3410                                        )
3411                                    }
3412                                    Err(e) => {
3413                                        warn!("Failed to generate contextual prefixes: {}. Using original chunks.", e);
3414                                        enriched_chunks.clone()
3415                                    }
3416                                }
3417                            } else {
3418                                enriched_chunks
3419                            };
3420
3421                            let mut chunk_embeddings = Vec::with_capacity(embed_chunks.len());
3422                            for chunk_text in &embed_chunks {
3423                                // Truncate chunk to avoid OpenAI token limits (contextual prefixes can make chunks large)
3424                                let truncated_chunk = truncate_for_embedding(chunk_text);
3425                                if truncated_chunk.len() < chunk_text.len() {
3426                                    info!("parallel mode: Truncated chunk from {} to {} chars for embedding", chunk_text.len(), truncated_chunk.len());
3427                                }
3428                                let chunk_emb = runtime.embed(&truncated_chunk)?;
3429                                chunk_embeddings.push(chunk_emb);
3430                            }
3431                            let num_chunks = chunk_embeddings.len();
3432                            chunk_embeddings_vec = Some(chunk_embeddings);
3433                            // Also embed the parent for the parent frame (truncate to avoid token limits)
3434                            let parent_text = truncate_for_embedding(&embed_text);
3435                            if parent_text.len() < embed_text.len() {
3436                                info!("parallel mode: Truncated parent text from {} to {} chars for embedding", embed_text.len(), parent_text.len());
3437                            }
3438                            parent_embedding = Some(runtime.embed(&parent_text)?);
3439                            embedded = true;
3440                            info!(
3441                                "parallel mode: Generated {} chunk embeddings + 1 parent embedding",
3442                                num_chunks
3443                            );
3444                        } else {
3445                            // No chunking - just embed the whole document (truncate to avoid token limits)
3446                            info!("parallel mode: No chunking (payload < 2400 chars or not UTF-8), using single embedding");
3447                            let truncated_text = truncate_for_embedding(&embed_text);
3448                            if truncated_text.len() < embed_text.len() {
3449                                info!("parallel mode: Truncated text from {} to {} chars for embedding", embed_text.len(), truncated_text.len());
3450                            }
3451                            parent_embedding = Some(runtime.embed(&truncated_text)?);
3452                            embedded = true;
3453                        }
3454                    }
3455                }
3456                let payload_variant = if let Some(path) = source_path {
3457                    ParallelPayload::Path(path.to_path_buf())
3458                } else {
3459                    ParallelPayload::Bytes(payload)
3460                };
3461                let input = ParallelInput {
3462                    payload: payload_variant,
3463                    options: options.clone(),
3464                    embedding: parent_embedding,
3465                    chunk_embeddings: chunk_embeddings_vec,
3466                };
3467                return Ok(IngestOutcome {
3468                    report: PutReport {
3469                        seq: 0,
3470                        frame_id: 0, // Will be populated after parallel commit
3471                        uri,
3472                        title: inferred_title,
3473                        original_bytes,
3474                        stored_bytes,
3475                        compressed,
3476                        source: source_path.map(Path::to_path_buf),
3477                        mime: Some(analysis.mime),
3478                        metadata: analysis.metadata,
3479                        extraction: analysis.extraction,
3480                        #[cfg(feature = "logic_mesh")]
3481                        search_text: search_text.clone(),
3482                    },
3483                    embedded,
3484                    parallel_input: Some(input),
3485                });
3486            }
3487            #[cfg(not(feature = "parallel_segments"))]
3488            {
3489                mem.put_bytes_with_options(&payload, options)
3490                    .map_err(|err| {
3491                        map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3492                    })?
3493            }
3494        } else if allow_embedding {
3495            let runtime = runtime.ok_or_else(|| anyhow!("semantic runtime unavailable"))?;
3496            let embed_text = search_text
3497                .clone()
3498                .or_else(|| payload_text.map(|text| text.to_string()))
3499                .unwrap_or_default();
3500            if embed_text.trim().is_empty() {
3501                warn!("no textual content available; embedding skipped");
3502                mem.put_bytes_with_options(&payload, options)
3503                    .map_err(|err| {
3504                        map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3505                    })?
3506            } else {
3507                // Check if document will be chunked - if so, embed each chunk
3508                if let Some(chunk_texts) = mem.preview_chunks(&payload) {
3509                    // Document will be chunked - embed each chunk for full semantic coverage
3510                    info!(
3511                        "Document will be chunked into {} chunks, generating embeddings for each",
3512                        chunk_texts.len()
3513                    );
3514
3515                    // Apply temporal enrichment if enabled (before contextual)
3516                    #[cfg(feature = "temporal_enrich")]
3517                    let enriched_chunks = if args.temporal_enrich {
3518                        info!(
3519                            "Temporal enrichment enabled, processing {} chunks",
3520                            chunk_texts.len()
3521                        );
3522                        // Use today's date as fallback document date
3523                        let today = chrono::Local::now().date_naive();
3524                        let results = temporal_enrich_chunks(&chunk_texts, Some(today));
3525                        // Results are tuples of (enriched_text, TemporalEnrichment)
3526                        let enriched: Vec<String> =
3527                            results.iter().map(|(text, _)| text.clone()).collect();
3528                        let resolved_count = results
3529                            .iter()
3530                            .filter(|(_, e)| {
3531                                e.relative_phrases.iter().any(|p| p.resolved.is_some())
3532                            })
3533                            .count();
3534                        info!(
3535                            "Temporal enrichment: resolved {} chunks with temporal context",
3536                            resolved_count
3537                        );
3538                        enriched
3539                    } else {
3540                        chunk_texts.clone()
3541                    };
3542                    #[cfg(not(feature = "temporal_enrich"))]
3543                    let enriched_chunks = {
3544                        if args.temporal_enrich {
3545                            warn!("Temporal enrichment requested but feature not compiled in");
3546                        }
3547                        chunk_texts.clone()
3548                    };
3549
3550                    // Apply contextual retrieval if enabled
3551                    let embed_chunks = if args.contextual {
3552                        info!("Contextual retrieval enabled, generating context prefixes for {} chunks", enriched_chunks.len());
3553                        let engine = if args.contextual_model.as_deref() == Some("local") {
3554                            #[cfg(feature = "llama-cpp")]
3555                            {
3556                                let model_path = get_local_contextual_model_path()?;
3557                                ContextualEngine::local(model_path)
3558                            }
3559                            #[cfg(not(feature = "llama-cpp"))]
3560                            {
3561                                anyhow::bail!("Local contextual model requires the 'llama-cpp' feature. Use --contextual-model openai or omit the flag for OpenAI.");
3562                            }
3563                        } else if let Some(model) = &args.contextual_model {
3564                            ContextualEngine::openai_with_model(model)?
3565                        } else {
3566                            ContextualEngine::openai()?
3567                        };
3568
3569                        match engine.generate_contexts_batch(&embed_text, &enriched_chunks) {
3570                            Ok(contexts) => {
3571                                info!("Generated {} contextual prefixes", contexts.len());
3572                                apply_contextual_prefixes(&embed_text, &enriched_chunks, &contexts)
3573                            }
3574                            Err(e) => {
3575                                warn!("Failed to generate contextual prefixes: {}. Using original chunks.", e);
3576                                enriched_chunks.clone()
3577                            }
3578                        }
3579                    } else {
3580                        enriched_chunks
3581                    };
3582
3583                    let mut chunk_embeddings = Vec::with_capacity(embed_chunks.len());
3584                    for chunk_text in &embed_chunks {
3585                        // Truncate chunk to avoid OpenAI token limits (contextual prefixes can make chunks large)
3586                        let truncated_chunk = truncate_for_embedding(chunk_text);
3587                        if truncated_chunk.len() < chunk_text.len() {
3588                            info!(
3589                                "Truncated chunk from {} to {} chars for embedding",
3590                                chunk_text.len(),
3591                                truncated_chunk.len()
3592                            );
3593                        }
3594                        let chunk_emb = runtime.embed(&truncated_chunk)?;
3595                        chunk_embeddings.push(chunk_emb);
3596                    }
3597                    // Truncate parent text to avoid token limits
3598                    let parent_text = truncate_for_embedding(&embed_text);
3599                    if parent_text.len() < embed_text.len() {
3600                        info!(
3601                            "Truncated parent text from {} to {} chars for embedding",
3602                            embed_text.len(),
3603                            parent_text.len()
3604                        );
3605                    }
3606                    let parent_embedding = runtime.embed(&parent_text)?;
3607                    embedded = true;
3608                    info!(
3609                        "Calling put_with_chunk_embeddings with {} chunk embeddings",
3610                        chunk_embeddings.len()
3611                    );
3612                    mem.put_with_chunk_embeddings(
3613                        &payload,
3614                        Some(parent_embedding),
3615                        chunk_embeddings,
3616                        options,
3617                    )
3618                    .map_err(|err| {
3619                        map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3620                    })?
3621                } else {
3622                    // No chunking - just embed the whole document (truncate to avoid token limits)
3623                    info!("Document too small for chunking (< 2400 chars after normalization), using single embedding");
3624                    let truncated_text = truncate_for_embedding(&embed_text);
3625                    if truncated_text.len() < embed_text.len() {
3626                        info!(
3627                            "Truncated text from {} to {} chars for embedding",
3628                            embed_text.len(),
3629                            truncated_text.len()
3630                        );
3631                    }
3632                    let embedding = runtime.embed(&truncated_text)?;
3633                    embedded = true;
3634                    mem.put_with_embedding_and_options(&payload, embedding, options)
3635                        .map_err(|err| {
3636                            map_put_error(
3637                                err,
3638                                capacity_guard.as_ref().and_then(|g| g.capacity_hint()),
3639                            )
3640                        })?
3641                }
3642            }
3643        } else {
3644            mem.put_bytes_with_options(&payload, options)
3645                .map_err(|err| {
3646                    map_put_error(err, capacity_guard.as_ref().and_then(|g| g.capacity_hint()))
3647                })?
3648        }
3649    };
3650
3651    Ok(IngestOutcome {
3652        report: PutReport {
3653            seq,
3654            frame_id,
3655            uri,
3656            title: inferred_title,
3657            original_bytes,
3658            stored_bytes,
3659            compressed,
3660            source: source_path.map(Path::to_path_buf),
3661            mime: Some(analysis.mime),
3662            metadata: analysis.metadata,
3663            extraction: analysis.extraction,
3664            #[cfg(feature = "logic_mesh")]
3665            search_text,
3666        },
3667        embedded,
3668        #[cfg(feature = "parallel_segments")]
3669        parallel_input: None,
3670    })
3671}
3672
3673fn canonical_storage_len(payload: &[u8]) -> Result<(usize, bool)> {
3674    if std::str::from_utf8(payload).is_ok() {
3675        let compressed = zstd::encode_all(Cursor::new(payload), 3)?;
3676        Ok((compressed.len(), true))
3677    } else {
3678        Ok((payload.len(), false))
3679    }
3680}
3681
3682fn print_report(report: &PutReport) {
3683    let name = report
3684        .source
3685        .as_ref()
3686        .map(|path| {
3687            let pretty = env::current_dir()
3688                .ok()
3689                .as_ref()
3690                .and_then(|cwd| diff_paths(path, cwd))
3691                .unwrap_or_else(|| path.to_path_buf());
3692            pretty.to_string_lossy().into_owned()
3693        })
3694        .unwrap_or_else(|| "stdin".to_string());
3695
3696    let ratio = if report.original_bytes > 0 {
3697        (report.stored_bytes as f64 / report.original_bytes as f64) * 100.0
3698    } else {
3699        100.0
3700    };
3701
3702    println!("• {name} → {}", report.uri);
3703    println!("  seq: {}", report.seq);
3704    if report.compressed {
3705        println!(
3706            "  size: {} B → {} B ({:.1}% of original, compressed)",
3707            report.original_bytes, report.stored_bytes, ratio
3708        );
3709    } else {
3710        println!("  size: {} B (stored as-is)", report.original_bytes);
3711    }
3712    if let Some(mime) = &report.mime {
3713        println!("  mime: {mime}");
3714    }
3715    if let Some(title) = &report.title {
3716        println!("  title: {title}");
3717    }
3718    let extraction_reader = report.extraction.reader.as_deref().unwrap_or("n/a");
3719    println!(
3720        "  extraction: status={} reader={}",
3721        report.extraction.status.label(),
3722        extraction_reader
3723    );
3724    if let Some(ms) = report.extraction.duration_ms {
3725        println!("  extraction-duration: {} ms", ms);
3726    }
3727    if let Some(pages) = report.extraction.pages_processed {
3728        println!("  extraction-pages: {}", pages);
3729    }
3730    for warning in &report.extraction.warnings {
3731        println!("  warning: {warning}");
3732    }
3733    if let Some(metadata) = &report.metadata {
3734        if let Some(caption) = &metadata.caption {
3735            println!("  caption: {caption}");
3736        }
3737        if let Some(audio) = metadata.audio.as_ref() {
3738            if audio.duration_secs.is_some()
3739                || audio.sample_rate_hz.is_some()
3740                || audio.channels.is_some()
3741            {
3742                let duration = audio
3743                    .duration_secs
3744                    .map(|secs| format!("{secs:.1}s"))
3745                    .unwrap_or_else(|| "unknown".into());
3746                let rate = audio
3747                    .sample_rate_hz
3748                    .map(|hz| format!("{} Hz", hz))
3749                    .unwrap_or_else(|| "? Hz".into());
3750                let channels = audio
3751                    .channels
3752                    .map(|ch| ch.to_string())
3753                    .unwrap_or_else(|| "?".into());
3754                println!("  audio: duration {duration}, {channels} ch, {rate}");
3755            }
3756        }
3757    }
3758
3759    println!();
3760}
3761
3762fn put_report_to_json(report: &PutReport) -> serde_json::Value {
3763    let source = report
3764        .source
3765        .as_ref()
3766        .map(|path| path.to_string_lossy().into_owned());
3767    let extraction = json!({
3768        "status": report.extraction.status.label(),
3769        "reader": report.extraction.reader,
3770        "duration_ms": report.extraction.duration_ms,
3771        "pages_processed": report.extraction.pages_processed,
3772        "warnings": report.extraction.warnings,
3773    });
3774    json!({
3775        "seq": report.seq,
3776        "uri": report.uri,
3777        "title": report.title,
3778        "original_bytes": report.original_bytes,
3779        "original_bytes_human": format_bytes(report.original_bytes as u64),
3780        "stored_bytes": report.stored_bytes,
3781        "stored_bytes_human": format_bytes(report.stored_bytes as u64),
3782        "compressed": report.compressed,
3783        "mime": report.mime,
3784        "source": source,
3785        "metadata": report.metadata,
3786        "extraction": extraction,
3787    })
3788}
3789
3790fn map_put_error(err: MemvidError, _capacity_hint: Option<u64>) -> anyhow::Error {
3791    match err {
3792        MemvidError::CapacityExceeded {
3793            current,
3794            limit,
3795            required,
3796        } => anyhow!(CapacityExceededMessage {
3797            current,
3798            limit,
3799            required,
3800        }),
3801        other => other.into(),
3802    }
3803}
3804
3805fn apply_metadata_overrides(options: &mut PutOptions, entries: &[String]) {
3806    for (idx, entry) in entries.iter().enumerate() {
3807        match serde_json::from_str::<DocMetadata>(entry) {
3808            Ok(meta) => {
3809                options.metadata = Some(meta);
3810            }
3811            Err(_) => match serde_json::from_str::<serde_json::Value>(entry) {
3812                Ok(value) => {
3813                    options
3814                        .extra_metadata
3815                        .insert(format!("custom_metadata_{idx}"), value.to_string());
3816                }
3817                Err(err) => warn!("failed to parse --metadata JSON: {err}"),
3818            },
3819        }
3820    }
3821}
3822
3823fn transcript_notice_message(mem: &mut Memvid) -> Result<String> {
3824    let stats = mem.stats()?;
3825    let message = match stats.tier {
3826        Tier::Free => "Transcript requires Dev/Enterprise tier. Apply a ticket to enable.".to_string(),
3827        Tier::Dev | Tier::Enterprise => "Transcript capture will attach in a future update; no transcript generated in this build.".to_string(),
3828    };
3829    Ok(message)
3830}
3831
3832fn sanitize_uri(raw: &str, keep_path: bool) -> String {
3833    let trimmed = raw.trim().trim_start_matches("mv2://");
3834    let normalized = trimmed.replace('\\', "/");
3835    let mut segments: Vec<String> = Vec::new();
3836    for segment in normalized.split('/') {
3837        if segment.is_empty() || segment == "." {
3838            continue;
3839        }
3840        if segment == ".." {
3841            segments.pop();
3842            continue;
3843        }
3844        segments.push(segment.to_string());
3845    }
3846
3847    if segments.is_empty() {
3848        return normalized
3849            .split('/')
3850            .last()
3851            .filter(|s| !s.is_empty())
3852            .unwrap_or("document")
3853            .to_string();
3854    }
3855
3856    if keep_path {
3857        segments.join("/")
3858    } else {
3859        segments
3860            .last()
3861            .cloned()
3862            .unwrap_or_else(|| "document".to_string())
3863    }
3864}
3865
3866fn create_task_progress_bar(total: Option<u64>, message: &str, quiet: bool) -> ProgressBar {
3867    if quiet {
3868        let pb = ProgressBar::hidden();
3869        pb.set_message(message.to_string());
3870        return pb;
3871    }
3872
3873    match total {
3874        Some(len) => {
3875            let pb = ProgressBar::new(len);
3876            pb.set_draw_target(ProgressDrawTarget::stderr());
3877            let style = ProgressStyle::with_template("{msg:>9} {pos}/{len}")
3878                .unwrap_or_else(|_| ProgressStyle::default_bar());
3879            pb.set_style(style);
3880            pb.set_message(message.to_string());
3881            pb
3882        }
3883        None => {
3884            let pb = ProgressBar::new_spinner();
3885            pb.set_draw_target(ProgressDrawTarget::stderr());
3886            pb.set_message(message.to_string());
3887            pb.enable_steady_tick(Duration::from_millis(120));
3888            pb
3889        }
3890    }
3891}
3892
3893fn create_spinner(message: &str) -> ProgressBar {
3894    let pb = ProgressBar::new_spinner();
3895    pb.set_draw_target(ProgressDrawTarget::stderr());
3896    let style = ProgressStyle::with_template("{spinner} {msg}")
3897        .unwrap_or_else(|_| ProgressStyle::default_spinner())
3898        .tick_strings(&["-", "\\", "|", "/"]);
3899    pb.set_style(style);
3900    pb.set_message(message.to_string());
3901    pb.enable_steady_tick(Duration::from_millis(120));
3902    pb
3903}
3904
3905// ============================================================================
3906// put-many command - batch ingestion with pre-computed embeddings
3907// ============================================================================
3908
3909/// Arguments for the `put-many` subcommand
3910#[cfg(feature = "parallel_segments")]
3911#[derive(Args)]
3912pub struct PutManyArgs {
3913    /// Path to the memory file to append to
3914    #[arg(value_name = "FILE", value_parser = clap::value_parser!(PathBuf))]
3915    pub file: PathBuf,
3916    /// Emit JSON instead of human-readable output
3917    #[arg(long)]
3918    pub json: bool,
3919    /// Path to JSON file containing batch requests (array of objects with title, label, text, uri, tags, labels, metadata, embedding)
3920    /// If not specified, reads from stdin
3921    #[arg(long, value_name = "PATH")]
3922    pub input: Option<PathBuf>,
3923    /// Zstd compression level (1-9, default: 3)
3924    #[arg(long, default_value = "3")]
3925    pub compression_level: i32,
3926    #[command(flatten)]
3927    pub lock: LockCliArgs,
3928}
3929
3930/// JSON input format for put-many requests
3931#[cfg(feature = "parallel_segments")]
3932#[derive(Debug, serde::Deserialize)]
3933pub struct PutManyRequest {
3934    pub title: String,
3935    #[serde(default)]
3936    pub label: String,
3937    pub text: String,
3938    #[serde(default)]
3939    pub uri: Option<String>,
3940    #[serde(default)]
3941    pub tags: Vec<String>,
3942    #[serde(default)]
3943    pub labels: Vec<String>,
3944    #[serde(default)]
3945    pub metadata: serde_json::Value,
3946    /// Pre-computed embedding vector for the parent document (e.g., from OpenAI)
3947    #[serde(default)]
3948    pub embedding: Option<Vec<f32>>,
3949    /// Pre-computed embeddings for each chunk (matched by index)
3950    /// If the document gets chunked, these embeddings are assigned to each chunk frame.
3951    /// The number of chunk embeddings should match the number of chunks that will be created.
3952    #[serde(default)]
3953    pub chunk_embeddings: Option<Vec<Vec<f32>>>,
3954}
3955
3956/// Batch input format (array of requests)
3957#[cfg(feature = "parallel_segments")]
3958#[derive(Debug, serde::Deserialize)]
3959#[serde(transparent)]
3960pub struct PutManyBatch {
3961    pub requests: Vec<PutManyRequest>,
3962}
3963
3964#[cfg(feature = "parallel_segments")]
3965pub fn handle_put_many(_config: &crate::config::CliConfig, args: PutManyArgs) -> Result<()> {
3966    use memvid_core::{BuildOpts, Memvid, ParallelInput, ParallelPayload, PutOptions};
3967
3968    let mut mem = Memvid::open(&args.file)?;
3969    crate::utils::ensure_cli_mutation_allowed(&mem)?;
3970    crate::utils::apply_lock_cli(&mut mem, &args.lock);
3971
3972    // Ensure indexes are enabled
3973    let stats = mem.stats()?;
3974    if !stats.has_lex_index {
3975        mem.enable_lex()?;
3976    }
3977    if !stats.has_vec_index {
3978        mem.enable_vec()?;
3979    }
3980
3981    // Read batch input
3982    let batch_json: String = if let Some(input_path) = &args.input {
3983        fs::read_to_string(input_path)
3984            .with_context(|| format!("Failed to read input file: {}", input_path.display()))?
3985    } else {
3986        let mut buffer = String::new();
3987        io::stdin()
3988            .read_line(&mut buffer)
3989            .context("Failed to read from stdin")?;
3990        buffer
3991    };
3992
3993    let batch: PutManyBatch =
3994        serde_json::from_str(&batch_json).context("Failed to parse JSON input")?;
3995
3996    if batch.requests.is_empty() {
3997        if args.json {
3998            println!("{{\"frame_ids\": [], \"count\": 0}}");
3999        } else {
4000            println!("No requests to process");
4001        }
4002        return Ok(());
4003    }
4004
4005    let count = batch.requests.len();
4006    if !args.json {
4007        eprintln!("Processing {} documents...", count);
4008    }
4009
4010    // Convert to ParallelInput
4011    let inputs: Vec<ParallelInput> = batch
4012        .requests
4013        .into_iter()
4014        .enumerate()
4015        .map(|(i, req)| {
4016            let uri = req.uri.unwrap_or_else(|| format!("mv2://batch/{}", i));
4017            let mut options = PutOptions::default();
4018            options.title = Some(req.title);
4019            options.uri = Some(uri);
4020            options.tags = req.tags;
4021            options.labels = req.labels;
4022
4023            ParallelInput {
4024                payload: ParallelPayload::Bytes(req.text.into_bytes()),
4025                options,
4026                embedding: req.embedding,
4027                chunk_embeddings: req.chunk_embeddings,
4028            }
4029        })
4030        .collect();
4031
4032    // Build options
4033    let build_opts = BuildOpts {
4034        zstd_level: args.compression_level.clamp(1, 9),
4035        ..BuildOpts::default()
4036    };
4037
4038    // Ingest batch
4039    let frame_ids = mem
4040        .put_parallel_inputs(&inputs, build_opts)
4041        .context("Failed to ingest batch")?;
4042
4043    if args.json {
4044        let output = serde_json::json!({
4045            "frame_ids": frame_ids,
4046            "count": frame_ids.len()
4047        });
4048        println!("{}", serde_json::to_string(&output)?);
4049    } else {
4050        println!("Ingested {} documents", frame_ids.len());
4051        if frame_ids.len() <= 10 {
4052            for fid in &frame_ids {
4053                println!("  frame_id: {}", fid);
4054            }
4055        } else {
4056            println!("  first: {}", frame_ids.first().unwrap_or(&0));
4057            println!("  last:  {}", frame_ids.last().unwrap_or(&0));
4058        }
4059    }
4060
4061    Ok(())
4062}