khive-pack-knowledge 0.18.0

Knowledge verb pack — lore corpus (atoms/domains), TF-IDF retrieval, concept registration
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
//! Shared SQL helpers and row-to-type converters for knowledge handlers.

use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use uuid::Uuid;

use khive_runtime::{micros_to_iso, KhiveRuntime, NamespaceToken, RuntimeError};
use khive_storage::types::{SqlStatement, SqlValue};

use super::schema::{Atom, Domain};

// ─── TF-IDF weight defaults ───────────────────────────────────────────────────

pub(super) const D_W_EXACT_NAME: f32 = 5.0;
pub(super) const D_W_NAME: f32 = 3.0;
pub(super) const D_W_TAGS: f32 = 1.25;
pub(super) const D_W_CONTENT: f32 = 1.5;
pub(super) const D_EXPAND_DISCOUNT: f32 = 0.35;
pub(super) const D_COVERAGE_ALPHA: f32 = 0.5;
pub(super) const D_W_BIGRAM: f32 = 2.0;

/// Final-blend weight given to the lexical/RRF-fused score in `suggest`'s
/// domain ranking (issue #90). `suggest` picks *topics*, not keywords: a
/// domain title that happens to contain a rare, polysemous query token
/// (e.g. "decoding" meaning channel-coding vs. LLM token generation) earns
/// an outsized TF-IDF name bonus (`D_W_EXACT_NAME`/`D_W_NAME`) purely from
/// bag-of-words token overlap, which the FTS leg cannot sense-disambiguate.
/// Embeddings carry distributional sense information FTS does not, so the
/// final blend must let the freshly-computed cosine leg dominate rather
/// than the lexical leg — the inverse of `knowledge.search`'s keyword-match
/// use case, which keeps the general-purpose default weighting.
pub(super) const D_SUGGEST_RERANK_ALPHA: f32 = 0.3;

pub(super) const CANDIDATE_POOL: usize = 2000;
pub(super) const MIN_TERM_LEN: usize = 3;
/// Default embed/write batch when the caller does not pass `batch_size`. This is
/// the number of records embedded per `embed_document_batch` call (and written
/// per batch) — NOT a separate DB-pagination unit. The reindex `--batch-size`
/// flag overrides it; pagination uses the same value.
pub(crate) const DEFAULT_EMBED_BATCH: usize = 128;

pub(super) static STOP_WORDS: &[&str] = &[
    "and", "are", "also", "but", "can", "did", "does", "for", "from", "had", "has", "have", "its",
    "just", "may", "not", "our", "out", "than", "that", "the", "then", "this", "was", "were",
    "will", "with",
];

pub(super) fn is_stop(w: &str) -> bool {
    STOP_WORDS.contains(&w)
}

// ─── content hash and validation ─────────────────────────────────────────────

/// Minimum section content length in Unicode scalar values.
pub(super) const MIN_SECTION_CONTENT_LEN: usize = 80;

/// Minimum atom content length in words.
pub(super) const MIN_ATOM_CONTENT_WORDS: usize = 20;

/// SQL predicate on `knowledge_sections.section_type` that leaves out rows typed with a
/// retired section type (ADR-048, 2026-10-04 amendment). Stored rows keep their retired
/// type unchanged, under any spelling the earlier alias table resolved to it, so every
/// query that reads sections for serving appends this predicate. It normalizes the stored
/// value the way `SectionType::normalize_name` does (Unicode whitespace trimmed, each
/// character listed by code point, `-` and space mapped to `_`, ASCII lowercased) and
/// compares the result with every retired spelling. Unit tests pin it to
/// `SectionType::RETIRED_SPELLINGS`, to the characters `str::trim` removes, and to
/// `SectionType::normalize_name` on the same inputs.
pub(super) const SERVABLE_SECTION: &str = "lower(replace(replace(trim(section_type, \
     char(9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, \
     8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288)), '-', '_'), ' ', '_')) \
     NOT IN ('references', 'reference', 'bibliography', 'related', 'see_also', \
     'further_reading', 'citations', 'links', 'other', 'misc', 'miscellaneous', 'notes', \
     'appendix')";

/// Compute sha256(content)[:16] as a hex string for dedup keying.
pub(super) fn content_hash(content: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(content.as_bytes());
    let hash = hasher.finalize();
    format!("{hash:x}")[..16].to_string()
}

/// Validate that section content meets the 80-character minimum.
pub(super) fn validate_section_content(content: &str) -> Result<(), RuntimeError> {
    let character_count = content.chars().count();
    if character_count < MIN_SECTION_CONTENT_LEN {
        return Err(RuntimeError::InvalidInput(format!(
            "section content must be at least {} characters (got {})",
            MIN_SECTION_CONTENT_LEN, character_count
        )));
    }
    Ok(())
}

/// Validate that atom content meets the 20-word minimum.
pub(super) fn validate_atom_content(content: &str) -> Result<(), RuntimeError> {
    let word_count = content.split_whitespace().count();
    if word_count < MIN_ATOM_CONTENT_WORDS {
        return Err(RuntimeError::InvalidInput(format!(
            "atom content must be at least {} words (got {})",
            MIN_ATOM_CONTENT_WORDS, word_count
        )));
    }
    Ok(())
}

// ─── error helpers ───────────────────────────────────────────────────────────

pub(super) fn sql_err(ctx: &str, e: impl std::fmt::Display) -> RuntimeError {
    RuntimeError::internal_with_context(ctx, e)
}

pub(super) use khive_runtime::deser_params as deser;

// ─── token estimation ────────────────────────────────────────────────────────

/// Same token unit `compose`'s `max_tokens` budgeting uses.
pub(super) const CHARS_PER_TOKEN: usize = 4;

pub(super) fn compose_item_char_cost(title: &str, content: &str) -> usize {
    title.len().saturating_add(content.len()).saturating_add(40)
}

pub(super) fn estimate_compose_item_tokens(title: &str, content: &str) -> usize {
    compose_item_char_cost(title, content)
        .div_ceil(CHARS_PER_TOKEN)
        .max(1)
}

// ─── SQL helpers ─────────────────────────────────────────────────────────────

pub(super) use khive_storage::now_micros as now_us;

pub(super) fn new_id() -> String {
    Uuid::new_v4().to_string()
}

pub(super) fn tags_to_json(tags: Option<&Vec<String>>) -> String {
    match tags {
        Some(t) => serde_json::to_string(t).unwrap_or_else(|_| "[]".into()),
        None => "[]".to_string(),
    }
}

/// Classify valid stored tag arrays by exact element, retaining the historical
/// guard for malformed or non-array legacy tag text.
pub(super) fn has_domain_mirror_tag(tags: &str) -> bool {
    khive_types::tag_contains(tags, "type:domain")
}

pub(super) fn row_str(row: &khive_storage::types::SqlRow, col: &str) -> Option<String> {
    row.text_or_none(col).map(str::to_owned)
}

pub(super) fn row_i64(row: &khive_storage::types::SqlRow, col: &str) -> Option<i64> {
    row.i64_or_none(col)
}

pub(super) fn row_bool(row: &khive_storage::types::SqlRow, col: &str) -> bool {
    row.i64_or_none(col) == Some(1)
}

pub(crate) fn atom_from_row(row: &khive_storage::types::SqlRow) -> Option<Atom> {
    let id: Uuid = row_str(row, "id")?.parse().ok()?;
    Some(Atom {
        id,
        namespace: row_str(row, "namespace")?,
        slug: row_str(row, "slug")?,
        name: row_str(row, "name")?,
        content: row_str(row, "content").unwrap_or_default(),
        tags: row_str(row, "tags").unwrap_or_else(|| "[]".into()),
        properties: row_str(row, "properties"),
        status: row_str(row, "status"),
        source_uri: row_str(row, "source_uri"),
        source_type: row_str(row, "source_type"),
        finalized: row_bool(row, "finalized"),
        created_at: row_i64(row, "created_at").unwrap_or(0),
        updated_at: row_i64(row, "updated_at").unwrap_or(0),
        deleted_at: row_i64(row, "deleted_at"),
    })
}

pub(crate) fn domain_from_row(row: &khive_storage::types::SqlRow) -> Option<Domain> {
    let id: Uuid = row_str(row, "id")?.parse().ok()?;
    Some(Domain {
        id,
        namespace: row_str(row, "namespace")?,
        slug: row_str(row, "slug")?,
        name: row_str(row, "name")?,
        description: row_str(row, "description"),
        tags: row_str(row, "tags").unwrap_or_else(|| "[]".into()),
        members: row_str(row, "members").unwrap_or_else(|| "[]".into()),
        created_at: row_i64(row, "created_at").unwrap_or(0),
        updated_at: row_i64(row, "updated_at").unwrap_or(0),
        deleted_at: row_i64(row, "deleted_at"),
    })
}

pub(crate) fn atom_to_json(atom: &Atom) -> Value {
    json!({
        "id": atom.id.to_string(),
        "namespace": atom.namespace,
        "slug": atom.slug,
        "name": atom.name,
        "content": atom.content,
        "tags": serde_json::from_str::<Value>(&atom.tags).unwrap_or(Value::Array(vec![])),
        "properties": atom.properties.as_deref().and_then(|s| serde_json::from_str::<Value>(s).ok()),
        "status": atom.status,
        "source_uri": atom.source_uri,
        "source_type": atom.source_type,
        "finalized": atom.finalized,
        "kind": "atom",
        "created_at": micros_to_iso(atom.created_at),
        "updated_at": micros_to_iso(atom.updated_at),
    })
}

pub(crate) fn domain_to_json(domain: &Domain) -> Value {
    json!({
        "id": domain.id.to_string(),
        "namespace": domain.namespace,
        "slug": domain.slug,
        "name": domain.name,
        "description": domain.description,
        "tags": serde_json::from_str::<Value>(&domain.tags).unwrap_or(Value::Array(vec![])),
        "members": serde_json::from_str::<Value>(&domain.members).unwrap_or(Value::Array(vec![])),
        "kind": "domain",
        "created_at": micros_to_iso(domain.created_at),
        "updated_at": micros_to_iso(domain.updated_at),
    })
}

// ─── status helpers ───────────────────────────────────────────────────────────

pub(super) fn status_values(value: Option<&Value>) -> Vec<String> {
    match value {
        Some(Value::String(s)) => {
            let s = s.trim();
            if s.is_empty() {
                Vec::new()
            } else {
                vec![s.to_string()]
            }
        }
        Some(Value::Array(items)) => items
            .iter()
            .filter_map(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect(),
        _ => Vec::new(),
    }
}

pub(super) fn status_sql_clause(
    statuses: &[String],
    exclude_statuses: &[&str],
    first_param: usize,
) -> (String, Vec<SqlValue>) {
    if !statuses.is_empty() {
        let placeholders = statuses
            .iter()
            .enumerate()
            .map(|(i, _)| format!("?{}", first_param + i))
            .collect::<Vec<_>>()
            .join(",");
        let clause = if statuses.len() == 1 {
            format!(" AND status = ?{first_param}")
        } else {
            format!(" AND status IN ({placeholders})")
        };
        let params = statuses.iter().cloned().map(SqlValue::Text).collect();
        return (clause, params);
    }

    let non_empty: Vec<&str> = exclude_statuses
        .iter()
        .copied()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();

    if !non_empty.is_empty() {
        let conditions: Vec<String> = non_empty
            .iter()
            .enumerate()
            .map(|(i, _)| format!("status != ?{}", first_param + i))
            .collect();
        let clause = format!(" AND (status IS NULL OR ({}))", conditions.join(" AND "));
        let params: Vec<SqlValue> = non_empty
            .iter()
            .map(|s| SqlValue::Text(s.to_string()))
            .collect();
        return (clause, params);
    }

    (
        " AND (status IS NULL OR status != 'deprecated')".to_string(),
        Vec::new(),
    )
}

pub(super) fn explicitly_requested_status(statuses: &[String], status: &str) -> bool {
    statuses.iter().any(|s| s == status)
}

pub(super) fn status_multiplier(status: Option<&str>) -> f32 {
    // Atom status taxonomy: draft | reviewed | deprecated (closed set per ADR-047).
    // 'verified' is a section-level status only; no public write path sets atom status
    // to 'verified', so it falls through to the 1.0 default here.
    match status.unwrap_or("reviewed") {
        "reviewed" => 1.0,
        "draft" => 0.8,
        "deprecated" => 0.0,
        _ => 1.0,
    }
}

// ─── embed text helper ────────────────────────────────────────────────────────

pub(super) fn atom_embed_text(atom: &Atom) -> String {
    atom_embed_text_fields(&atom.name, &atom.content, &atom.tags)
}

/// Render search fallbacks from the same stored fields as index-time atoms.
pub(super) fn atom_embed_text_fields(name: &str, content: &str, tags: &str) -> String {
    let mut parts: Vec<String> = Vec::with_capacity(3);
    if !name.is_empty() {
        parts.push(name.to_owned());
    }
    if !content.is_empty() {
        parts.push(content.to_owned());
    }
    if let Ok(tags) = serde_json::from_str::<Vec<String>>(tags) {
        let meaningful: Vec<&str> = tags.iter().map(|s| s.as_str()).collect();
        if !meaningful.is_empty() {
            parts.push(format!("Tags: {}", meaningful.join(", ")));
        }
    }
    parts.join("\n\n")
}

// ─── atom id resolver ─────────────────────────────────────────────────────────

pub(super) async fn resolve_atom_id(
    runtime: &KhiveRuntime,
    ns: &str,
    id_or_slug: &str,
) -> Result<String, RuntimeError> {
    let sql = runtime.sql();
    let mut reader = sql
        .reader()
        .await
        .map_err(|e| sql_err("resolve_atom_id reader", e))?;
    let id = id_or_slug.trim().to_string();
    let row = if let Ok(uuid) = id.parse::<Uuid>() {
        // Atom ids are stored as lowercase hyphenated text, so bind the parsed
        // value's canonical form, not the spelling the caller used.
        reader
            .query_row(SqlStatement {
                sql: khive_runtime::sql!("knowledge_atom_resolve_id").into(),
                params: vec![
                    SqlValue::Text(uuid.as_hyphenated().to_string()),
                    SqlValue::Text(ns.to_owned()),
                ],
                label: None,
            })
            .await
            .map_err(|e| sql_err("resolve_atom_id by id", e))?
    } else {
        reader
            .query_row(SqlStatement {
                sql: khive_runtime::sql!("knowledge_atom_resolve_slug").into(),
                params: vec![SqlValue::Text(id.clone()), SqlValue::Text(ns.to_owned())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("resolve_atom_id by slug", e))?
    };
    row.and_then(|r| row_str(&r, "id"))
        .ok_or_else(|| RuntimeError::NotFound(format!("atom not found: {id:?}")))
}

// ─── embedding coverage ───────────────────────────────────────────────────────

pub(super) async fn compute_embedding_coverage(
    runtime: &KhiveRuntime,
    token: &NamespaceToken,
    ns: &str,
    total_atoms: i64,
) -> Result<f64, RuntimeError> {
    if total_atoms <= 0 || runtime.default_embedder_name().is_empty() {
        return Ok(0.0);
    }

    match runtime.vectors(token) {
        Ok(_) => {}
        Err(RuntimeError::Unconfigured(_)) => return Ok(0.0),
        Err(e) => return Err(e),
    }

    let model = runtime.default_embedder_name().to_owned();
    let table_name = format!("vec_{}", super::vamana::sanitize_model_key(&model));
    let sql = runtime.sql();
    let mut reader = sql
        .reader()
        .await
        .map_err(|e| sql_err("stats embedding coverage reader", e))?;

    let atoms_with_vector = reader
        .count(SqlStatement {
            sql: format!(
                "SELECT COUNT(DISTINCT a.id) \
                 FROM knowledge_atoms a \
                 WHERE a.namespace = ?1 \
                   AND a.deleted_at IS NULL \
                   AND NOT khive_tag_contains(a.tags, 'type:domain') \
                   AND a.id IN ( \
                       SELECT v.subject_id FROM {table_name} v \
                       WHERE v.namespace = ?1 \
                         AND v.embedding_model = ?2 \
                         AND v.field = 'knowledge.atom' \
                   )"
            ),
            params: vec![SqlValue::Text(ns.to_owned()), SqlValue::Text(model.clone())],
            label: Some("knowledge_stats_embedding_coverage".into()),
        })
        .await
        .map_err(|e| sql_err("stats embedding coverage", e))?;

    Ok(atoms_with_vector as f64 / total_atoms as f64)
}

#[cfg(test)]
#[path = "util_tests.rs"]
mod tests;