holix-rs 1.4.0

Local-first context-folding index runtime with SQLite WAL/FTS5 persistence, Orion HNSW semantic routing, BlobSource hydration, and AST/CSV/XLSX/EML slicers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Deterministic lexical TextTiling and extractive entity-anchored labeling for unstructured prose.

use std::collections::{BTreeMap, BTreeSet, HashMap};

use holix_core_verified::coords::{Coordinate, Modality};
use holix_core_verified::tokens::TokenKind;

use crate::ingest::{estimate_text_tokens, make_projection_label, IngestError};
use crate::store::{AssetRecord, FoldedProjection, IndexStore};

pub const DEFAULT_MIN_FOLD_BYTES: usize = 512;
pub const DEFAULT_MAX_FOLD_BYTES: usize = 4096;

const STOPWORDS: &[&str] = &[
    "the", "and", "for", "are", "but", "not", "you", "all", "can", "had", "her", "was", "one",
    "our", "out", "day", "get", "has", "him", "his", "how", "man", "new", "now", "old", "see",
    "two", "way", "who", "boy", "did", "its", "let", "put", "say", "she", "too", "use", "that",
    "with", "have", "this", "will", "your", "from", "they", "know", "want", "been", "good",
    "much", "some", "time", "very", "when", "come", "here", "just", "like", "long", "make",
    "many", "over", "such", "take", "than", "them", "well", "were", "what", "into", "more",
    "only", "then", "also", "back", "even", "most", "said", "each", "which", "their", "there",
    "these", "about", "could", "other", "would", "after", "first", "never", "shall", "should",
    "where", "while", "being", "under", "between", "through", "because", "before", "during",
];

/// A cohesion-bounded prose fold produced by lexical TextTiling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProseFold {
    pub start_byte: usize,
    pub end_byte: usize,
    pub keyphrases: Vec<String>,
    pub salient_lead: String,
    pub entities: Vec<String>,
    pub label: String,
}

#[derive(Debug, Clone)]
struct ParagraphSpan<'a> {
    start_byte: usize,
    end_byte: usize,
    sentences: Vec<&'a str>,
}

fn is_stopword(word: &str) -> bool {
    STOPWORDS.contains(&word)
}

fn tokenize_terms(text: &str) -> Vec<String> {
    text.split(|c: char| !c.is_alphanumeric() && c != '_' && c != '-')
        .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_ascii_lowercase())
        .filter(|w| w.len() >= 3 && !is_stopword(w) && !w.chars().all(|c| c.is_ascii_digit()))
        .collect()
}

fn split_sentences(para: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0usize;
    let bytes = para.as_bytes();
    for (idx, &b) in bytes.iter().enumerate() {
        if matches!(b, b'.' | b'!' | b'?' | b'\n') {
            let next = idx + 1;
            let seg = para[start..next].trim();
            if !seg.is_empty() {
                out.push(seg);
            }
            start = next;
        }
    }
    if start < para.len() {
        let tail = para[start..].trim();
        if !tail.is_empty() {
            out.push(tail);
        }
    }
    if out.is_empty() && !para.trim().is_empty() {
        out.push(para.trim());
    }
    out
}

fn segment_paragraphs(text: &str) -> Vec<ParagraphSpan<'_>> {
    let mut paras = Vec::new();
    let mut offset = 0usize;
    let mut cur_start: Option<usize> = None;
    let mut cur_end = 0usize;

    for raw_line in text.split_inclusive('\n') {
        let line_len = raw_line.len();
        let trimmed = raw_line.trim();
        if trimmed.is_empty() {
            if let Some(s) = cur_start.take() {
                let slice = &text[s..cur_end];
                paras.push(ParagraphSpan {
                    start_byte: s,
                    end_byte: cur_end,
                    sentences: split_sentences(slice),
                });
            }
        } else {
            if cur_start.is_none() {
                cur_start = Some(offset);
            }
            cur_end = offset + line_len;
        }
        offset += line_len;
    }
    if let Some(s) = cur_start {
        let slice = &text[s..cur_end];
        paras.push(ParagraphSpan {
            start_byte: s,
            end_byte: cur_end,
            sentences: split_sentences(slice),
        });
    }
    paras
}

fn cosine_sim(a: &HashMap<String, usize>, b: &HashMap<String, usize>) -> f64 {
    if a.is_empty() || b.is_empty() {
        return 0.0;
    }
    let mut dot = 0.0f64;
    let mut norm_a = 0.0f64;
    let mut norm_b = 0.0f64;
    for (k, &va) in a {
        let fa = va as f64;
        norm_a += fa * fa;
        if let Some(&vb) = b.get(k) {
            dot += fa * (vb as f64);
        }
    }
    for &vb in b.values() {
        let fb = vb as f64;
        norm_b += fb * fb;
    }
    if norm_a == 0.0 || norm_b == 0.0 {
        0.0
    } else {
        dot / (norm_a.sqrt() * norm_b.sqrt())
    }
}

fn block_tf(sentences: &[&str]) -> HashMap<String, usize> {
    let mut tf = HashMap::new();
    for s in sentences {
        for tok in tokenize_terms(s) {
            *tf.entry(tok).or_insert(0) += 1;
        }
    }
    tf
}

/// Extracts pinned entity anchors (generic `[A-Z]{2,8}-[A-Za-z0-9-]+` IDs, dates, currency amounts, versions).
pub fn extract_pinned_entities(text: &str) -> Vec<String> {
    let mut seen = BTreeSet::new();
    let mut out = Vec::new();
    for space_tok in text.split_whitespace() {
        let sub_tokens: Vec<&str> = if !space_tok.starts_with('$') && (space_tok.contains(',') || space_tok.contains(';')) {
            space_tok.split([',', ';']).collect()
        } else {
            vec![space_tok]
        };
        for raw in sub_tokens {
            let tok = raw.trim_matches(|c: char| {
                matches!(
                    c,
                    ',' | '.' | ';' | ':' | '(' | ')' | '[' | ']' | '"' | '\'' | '<' | '>'
                )
            });
            if tok.is_empty() || tok.len() > 48 {
                continue;
            }
            let is_currency = tok.starts_with('$')
                && tok.len() > 1
                && tok[1..].chars().all(|c| c.is_ascii_digit() || c == ',' || c == '.');
            let is_date = tok.len() == 10
                && tok.as_bytes()[4] == b'-'
                && tok.as_bytes()[7] == b'-'
                && tok.bytes().enumerate().all(|(i, b)| i == 4 || i == 7 || b.is_ascii_digit());
            let is_prefixed_id = tok
                .split_once('-')
                .is_some_and(|(prefix, suffix)| {
                    (2..=8).contains(&prefix.len())
                        && prefix
                            .bytes()
                            .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
                        && prefix.bytes().any(|b| b.is_ascii_uppercase())
                        && !suffix.is_empty()
                        && suffix.chars().any(|c| c.is_ascii_digit())
                        && suffix
                            .chars()
                            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
                });
            let is_version = tok.starts_with('v')
                && tok.len() >= 4
                && tok.contains('.')
                && tok[1..].chars().all(|c| c.is_ascii_digit() || c == '.');

            if (is_currency || is_date || is_prefixed_id || is_version) && seen.insert(tok.to_string()) {
                out.push(tok.to_string());
                if out.len() >= 6 {
                    return out;
                }
            }
        }
    }
    out
}

fn cap_tokens(s: &str, max_tokens: usize) -> String {
    let words: Vec<&str> = s.split_whitespace().collect();
    if words.len() <= max_tokens {
        words.join(" ")
    } else {
        format!("{}...", words[..max_tokens].join(" "))
    }
}

/// Slices unstructured prose via lexical TextTiling into cohesion-bounded folds with extractive labels.
pub fn slice_prose_with_texttiling(
    text: &str,
    min_fold_bytes: usize,
    max_fold_bytes: usize,
) -> Vec<ProseFold> {
    if text.trim().is_empty() {
        return Vec::new();
    }
    let paras = segment_paragraphs(text);
    if paras.is_empty() {
        return Vec::new();
    }

    // Build flat sentence stream and map each paragraph gap to a sentence index.
    let mut all_sentences: Vec<&str> = Vec::new();
    let mut para_end_sent_idx: Vec<usize> = Vec::with_capacity(paras.len());
    for p in &paras {
        all_sentences.extend(p.sentences.iter().copied());
        para_end_sent_idx.push(all_sentences.len());
    }

    // Compute cosine similarity across 3-sentence left/right blocks at each inter-paragraph gap.
    let gap_count = paras.len().saturating_sub(1);
    let mut sims = Vec::with_capacity(gap_count);
    for &split_idx in para_end_sent_idx.iter().take(gap_count) {
        let left_start = split_idx.saturating_sub(3);
        let right_end = (split_idx + 3).min(all_sentences.len());
        let left_tf = block_tf(&all_sentences[left_start..split_idx]);
        let right_tf = block_tf(&all_sentences[split_idx..right_end]);
        sims.push(cosine_sim(&left_tf, &right_tf));
    }

    // Compute depth scores at each gap and pick local maxima (topic valleys).
    let mut depth_scores = vec![0.0f64; gap_count];
    for g in 0..gap_count {
        let mut left_peak = sims[g];
        for i in (0..g).rev() {
            if sims[i] >= left_peak {
                left_peak = sims[i];
            } else {
                break;
            }
        }
        let mut right_peak = sims[g];
        for &sim_i in &sims[(g + 1)..gap_count] {
            if sim_i >= right_peak {
                right_peak = sim_i;
            } else {
                break;
            }
        }
        depth_scores[g] = (left_peak - sims[g]) + (right_peak - sims[g]);
    }

    let mean_depth = if depth_scores.is_empty() {
        0.0
    } else {
        depth_scores.iter().sum::<f64>() / (depth_scores.len() as f64)
    };
    let mut boundary_gaps = BTreeSet::new();
    for g in 0..gap_count {
        let is_local_max = (g == 0 || depth_scores[g] >= depth_scores[g - 1])
            && (g + 1 == gap_count || depth_scores[g] >= depth_scores[g + 1]);
        if is_local_max && depth_scores[g] > mean_depth * 0.85 && depth_scores[g] > 0.05 {
            boundary_gaps.insert(g);
        }
    }

    // Assemble raw byte ranges respecting min_fold_bytes and max_fold_bytes.
    let mut raw_ranges: Vec<(usize, usize)> = Vec::new();
    let mut cur_start = paras[0].start_byte;
    let mut cur_end = paras[0].end_byte;
    for (idx, p) in paras.iter().enumerate().skip(1) {
        let prev_gap = idx - 1;
        let cur_len = cur_end.saturating_sub(cur_start);
        let next_len = p.end_byte.saturating_sub(cur_start);
        let split_for_topic = boundary_gaps.contains(&prev_gap) && cur_len >= min_fold_bytes;
        let split_for_max = next_len > max_fold_bytes && cur_len >= min_fold_bytes.min(cur_len);

        if split_for_topic || split_for_max {
            raw_ranges.push((cur_start, cur_end));
            cur_start = p.start_byte;
        }
        cur_end = p.end_byte;
    }
    raw_ranges.push((cur_start, cur_end));

    // If any single paragraph exceeded max_fold_bytes, split it safely on UTF-8 char boundaries.
    let mut final_ranges: Vec<(usize, usize)> = Vec::new();
    for (s, e) in raw_ranges {
        if e.saturating_sub(s) <= max_fold_bytes {
            final_ranges.push((s, e));
        } else {
            let mut pos = s;
            while pos < e {
                let mut next_end = (pos + max_fold_bytes).min(e);
                while next_end > pos && !text.is_char_boundary(next_end) {
                    next_end -= 1;
                }
                if next_end < e {
                    if let Some(ws) = text[pos..next_end].rfind(char::is_whitespace) {
                        if ws >= min_fold_bytes.min(next_end - pos) {
                            next_end = pos + ws;
                        }
                    }
                }
                if next_end <= pos {
                    next_end = e;
                }
                final_ranges.push((pos, next_end));
                pos = next_end;
                while pos < e && text[pos..e].starts_with(char::is_whitespace) {
                    if let Some(ch) = text[pos..e].chars().next() {
                        pos += ch.len_utf8();
                    } else {
                        break;
                    }
                }
            }
        }
    }

    // Compute document-wide DF for TF-IDF keyphrase scoring across folds.
    let fold_count = final_ranges.len();
    let mut df: HashMap<String, usize> = HashMap::new();
    let mut fold_tfs: Vec<HashMap<String, usize>> = Vec::with_capacity(fold_count);
    for &(s, e) in &final_ranges {
        let mut tf = HashMap::new();
        for tok in tokenize_terms(&text[s..e]) {
            *tf.entry(tok).or_insert(0) += 1;
        }
        for k in tf.keys() {
            *df.entry(k.clone()).or_insert(0) += 1;
        }
        fold_tfs.push(tf);
    }

    let mut folds = Vec::with_capacity(fold_count);
    for (idx, &(s, e)) in final_ranges.iter().enumerate() {
        let slice = &text[s..e];
        let tf = &fold_tfs[idx];
        let mut scored_terms: Vec<(String, f64)> = tf
            .iter()
            .map(|(term, &count)| {
                let doc_freq = *df.get(term).unwrap_or(&1) as f64;
                let idf = ((fold_count as f64 + 1.0) / (doc_freq + 1.0)).ln() + 1.0;
                (term.clone(), (count as f64) * idf)
            })
            .collect();
        scored_terms.sort_by(|a, b| {
            b.1.partial_cmp(&a.1)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.0.cmp(&b.0))
        });
        let keyphrases: Vec<String> = scored_terms.iter().take(5).map(|(t, _)| t.clone()).collect();

        // Pick highest-centrality sentence as salient lead (capped to 24 tokens).
        let term_weights: HashMap<&str, f64> =
            scored_terms.iter().map(|(t, w)| (t.as_str(), *w)).collect();
        let sentences = split_sentences(slice);
        let best_sentence = sentences
            .iter()
            .copied()
            .max_by(|a, b| {
                let score_s = |sent: &str| -> f64 {
                    tokenize_terms(sent)
                        .iter()
                        .filter_map(|t| term_weights.get(t.as_str()))
                        .sum()
                };
                score_s(a)
                    .partial_cmp(&score_s(b))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .unwrap_or(slice);
        let salient_lead = cap_tokens(best_sentence, 24);
        let entities = extract_pinned_entities(slice);

        let kw_str = keyphrases.join(", ");
        let ent_str = if entities.is_empty() {
            String::new()
        } else {
            format!(" | {}", entities.join(" "))
        };
        let raw_label = format!(
            "prose:fold {}/{} | {} | {}{}",
            idx + 1,
            fold_count,
            kw_str,
            salient_lead,
            ent_str
        );
        folds.push(ProseFold {
            start_byte: s,
            end_byte: e,
            keyphrases,
            salient_lead,
            entities,
            label: make_projection_label(&raw_label),
        });
    }
    folds
}

/// Registers an unstructured prose asset and emits Depth 0 outline + Depth 1 TextTiling folds.
pub fn ingest_prose_with_texttiling(
    store: &mut IndexStore,
    asset_id: u64,
    uri: String,
    extractor_id: u32,
    text: &str,
    next_proj_id: &mut u32,
) -> Result<Vec<u32>, IngestError> {
    if text.is_empty() {
        return Err(IngestError::EmptyPayload);
    }
    store.register_asset(AssetRecord {
        asset_id,
        modality: Modality::Text,
        payload_len: text.len() as u64,
        uri,
        mtime_ms: 0,
        locator: None,
        immutable: false,
        tags: BTreeMap::new(),
    })?;

    let folds = slice_prose_with_texttiling(text, DEFAULT_MIN_FOLD_BYTES, DEFAULT_MAX_FOLD_BYTES);
    let mut ids = Vec::with_capacity(folds.len() + 1);

    // Depth 0 document topic cluster outline.
    let mut doc_keywords: Vec<String> = Vec::new();
    let mut doc_entities: Vec<String> = Vec::new();
    let mut seen_kw = BTreeSet::new();
    let mut seen_ent = BTreeSet::new();
    for f in &folds {
        for kw in &f.keyphrases {
            if seen_kw.insert(kw.clone()) && doc_keywords.len() < 8 {
                doc_keywords.push(kw.clone());
            }
        }
        for ent in &f.entities {
            if seen_ent.insert(ent.clone()) && doc_entities.len() < 8 {
                doc_entities.push(ent.clone());
            }
        }
    }
    let outline_label = if doc_entities.is_empty() {
        format!("prose:outline ({} folds) | {}", folds.len(), doc_keywords.join(", "))
    } else {
        format!(
            "prose:outline ({} folds) | {} | {}",
            folds.len(),
            doc_keywords.join(", "),
            doc_entities.join(" ")
        )
    };
    let outline_id = *next_proj_id;
    *next_proj_id += 1;
    store.insert_projection(FoldedProjection {
        id: outline_id,
        asset_id,
        modality: Modality::Text,
        extractor_id,
        coord: Coordinate::TextRange {
            start_char: 0,
            end_char: text.len() as u64,
        },
        layer_tokens: vec![estimate_text_tokens(outline_label.len())],
        kinds: vec![TokenKind::Semantic],
        label: make_projection_label(&outline_label),
    })?;
    ids.push(outline_id);

    // Depth 1 topic folds.
    for f in folds {
        let pid = *next_proj_id;
        *next_proj_id += 1;
        store.insert_projection(FoldedProjection {
            id: pid,
            asset_id,
            modality: Modality::Text,
            extractor_id,
            coord: Coordinate::TextRange {
                start_char: f.start_byte as u64,
                end_char: f.end_byte as u64,
            },
            layer_tokens: vec![estimate_text_tokens(f.end_byte.saturating_sub(f.start_byte))],
            kinds: vec![TokenKind::Semantic],
            label: f.label,
        })?;
        ids.push(pid);
    }

    Ok(ids)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn texttiling_splits_distinct_topics_and_pins_entities() {
        let topic_a = "Distributed consensus protocols rely on Raft leader election and log replication across quorum nodes. \
            Each follower persists term numbers and voted candidates to disk before acknowledging AppendEntries RPCs. \
            When network partitions isolate the leader, split votes resolve via randomized election timeouts. \
            Storage engines pair WAL compaction with snapshot streaming so lagging replicas catch up cleanly.\n\n";
        let topic_b = "Procurement settled contract RFQ-2026-041 for SKU-9042 at $1420 per unit on 2026-11-29. \
            Customs clearance requires signed bills of lading and supplier ISO certificates before port release. \
            Warehouse receiving verifies pallet weights against the purchase order tolerance within forty-eight hours. \
            Finance reconciles net settlement invoices after inspection signoff.\n";
        let doc = format!("{}{}{}{}", topic_a, topic_a, topic_b, topic_b);
        let folds = slice_prose_with_texttiling(&doc, 300, 1200);
        assert!(folds.len() >= 2, "expected TextTiling to split distinct topics, got {}", folds.len());
        assert!(folds.iter().any(|f| f.entities.iter().any(|e| e == "RFQ-2026-041")));
        assert!(folds.iter().any(|f| f.entities.iter().any(|e| e == "SKU-9042")));
        assert!(folds.iter().any(|f| f.entities.iter().any(|e| e == "$1420")));
        for f in &folds {
            assert!(f.end_byte > f.start_byte);
            assert!(f.end_byte <= doc.len());
            assert!(doc.is_char_boundary(f.start_byte) && doc.is_char_boundary(f.end_byte));
        }
    }
}