Skip to main content

lean_ctx/core/knowledge/
okf.rs

1//! Open Knowledge Format (OKF) rendering for lean-ctx project knowledge.
2//!
3//! OKF (Google Cloud, June 2026) formalises the "LLM-wiki" pattern: a *directory
4//! of Markdown files*, one concept per file, each with a small YAML frontmatter
5//! block (only `type` is mandatory) and a Markdown body; concepts link to each
6//! other with ordinary Markdown links, and reserved `index.md` / `log.md` files
7//! provide progressive disclosure and history. It is vendor-neutral, human- and
8//! agent-readable, and git-diffable — the portable, no-lock-in counterpart to the
9//! signed `ctxpkg` bundle.
10//!
11//! This module renders a [`KnowledgeSnapshot`] to an OKF bundle and parses a
12//! bundle back into facts + relations. Both directions go through that *shared*
13//! snapshot, so OKF and ctxpkg can never disagree on what the project's
14//! knowledge is.
15//!
16//! ## Determinism (#498)
17//! Every byte of the export is a pure function of the snapshot: frontmatter keys
18//! are emitted in a fixed order (reserved OKF keys first, then sorted
19//! `leanctx_*`), file slugs are stable, relation lines are sorted, and no
20//! `now()` or counter ever reaches the output. Two exports of the same snapshot
21//! are byte-identical, which keeps provider prompt-caching effective.
22//!
23//! ## Lossless round-trip
24//! lean-ctx-specific fields ride along as producer-owned `leanctx_*` keys (OKF
25//! §reserves only a small set and lets producers add their own), so an
26//! export -> import cycle reconstructs the same facts, archetypes, and relations.
27//! Foreign bundles that carry only `type` import as plain facts rather than
28//! failing.
29
30use std::collections::{BTreeMap, HashMap, HashSet};
31use std::path::Path;
32
33use chrono::{DateTime, Utc};
34use serde_json::{Map, Value};
35use walkdir::WalkDir;
36
37use crate::core::knowledge_relations::{KnowledgeEdgeKind, KnowledgeNodeRef, parse_node_ref};
38use crate::core::memory_boundary::FactPrivacy;
39use crate::core::sensitivity;
40
41use super::snapshot::KnowledgeSnapshot;
42use super::types::{KnowledgeArchetype, KnowledgeFact, ProjectPattern};
43
44/// Reserved OKF filenames that are *not* concepts: an overview index and a
45/// chronological change log. Skipped on import.
46const INDEX_FILE: &str = "index.md";
47const LOG_FILE: &str = "log.md";
48/// Directory (one level under the bundle root) that holds project patterns.
49const PATTERNS_DIR: &str = "patterns";
50
51/// A rendered OKF bundle: relative file path -> file contents. A `BTreeMap` so
52/// iteration (and thus writing) is deterministic.
53pub type OkfBundle = BTreeMap<String, String>;
54
55/// A relation parsed from a concept's `## Relations` section.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct OkfEdge {
58    pub from: KnowledgeNodeRef,
59    pub to: KnowledgeNodeRef,
60    pub kind: KnowledgeEdgeKind,
61}
62
63/// The result of parsing an OKF directory back into lean-ctx structures.
64#[derive(Debug, Default)]
65pub struct OkfImport {
66    pub facts: Vec<KnowledgeFact>,
67    pub patterns: Vec<ProjectPattern>,
68    pub edges: Vec<OkfEdge>,
69}
70
71/// Where a concept lives inside the bundle: `<dir>/<file>.md`.
72struct ConceptLoc {
73    dir: String,
74    file: String,
75}
76
77// ---------------------------------------------------------------------------
78// Export
79// ---------------------------------------------------------------------------
80
81/// Renders a snapshot to a deterministic OKF bundle (path -> contents). Only
82/// current facts become concepts; superseded history stays in ctxpkg.
83pub fn to_okf_bundle(snapshot: &KnowledgeSnapshot) -> OkfBundle {
84    let mut facts = snapshot.current_facts();
85    facts.sort_by(|a, b| a.category.cmp(&b.category).then_with(|| a.key.cmp(&b.key)));
86
87    // Pass 1: resolve a stable, unique file location for every fact node so that
88    // relation links (pass 2) can point at real files.
89    let mut used: HashSet<(String, String)> = HashSet::new();
90    let mut paths: HashMap<KnowledgeNodeRef, ConceptLoc> = HashMap::new();
91    for f in &facts {
92        let node = KnowledgeNodeRef::new(&f.category, &f.key);
93        if paths.contains_key(&node) {
94            continue;
95        }
96        let dir = dir_slug(&f.category);
97        let file = unique_slug(&dir, &f.key, &mut used);
98        paths.insert(node, ConceptLoc { dir, file });
99    }
100
101    let mut bundle = OkfBundle::new();
102
103    // Pass 2: render each concept with its outgoing relations.
104    for f in &facts {
105        let node = KnowledgeNodeRef::new(&f.category, &f.key);
106        let Some(loc) = paths.get(&node) else {
107            continue;
108        };
109        let mut rel_lines: Vec<String> = snapshot
110            .relations
111            .iter()
112            .filter(|e| e.from == node && paths.contains_key(&e.to))
113            .map(|e| {
114                let target = &paths[&e.to];
115                let link = relative_link(&loc.dir, target);
116                format!("- {}: [{}]({link})", e.kind.as_str(), e.to.id())
117            })
118            .collect();
119        rel_lines.sort();
120        rel_lines.dedup();
121
122        bundle.insert(
123            format!("{}/{}.md", loc.dir, loc.file),
124            render_concept(f, &rel_lines),
125        );
126    }
127
128    // Patterns: one file each under patterns/.
129    let mut patterns = snapshot.patterns.clone();
130    patterns.sort_by(|a, b| {
131        a.pattern_type
132            .cmp(&b.pattern_type)
133            .then_with(|| a.description.cmp(&b.description))
134    });
135    for p in &patterns {
136        let file = unique_slug(PATTERNS_DIR, &p.pattern_type, &mut used);
137        bundle.insert(format!("{PATTERNS_DIR}/{file}.md"), render_pattern(p));
138    }
139
140    // Reserved files: index always, log only when there is history.
141    bundle.insert(INDEX_FILE.to_string(), render_index(&facts, &patterns));
142    if !snapshot.insights.is_empty() {
143        bundle.insert(LOG_FILE.to_string(), render_log(snapshot));
144    }
145
146    bundle
147}
148
149/// Writes a bundle to `dir`, creating category subdirectories as needed.
150pub fn write_okf_bundle(dir: &Path, bundle: &OkfBundle) -> Result<(), String> {
151    std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
152    for (rel, contents) in bundle {
153        let path = dir.join(rel);
154        if let Some(parent) = path.parent() {
155            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
156        }
157        std::fs::write(&path, contents).map_err(|e| e.to_string())?;
158    }
159    Ok(())
160}
161
162fn render_concept(f: &KnowledgeFact, rel_lines: &[String]) -> String {
163    let mut out = emit_frontmatter(&concept_frontmatter(f));
164    out.push('\n');
165    out.push_str(f.value.trim_end());
166    out.push('\n');
167    if !rel_lines.is_empty() {
168        out.push_str("\n## Relations\n\n");
169        for line in rel_lines {
170            out.push_str(line);
171            out.push('\n');
172        }
173    }
174    out
175}
176
177/// Ordered frontmatter for a fact: reserved OKF keys first (fixed order), then
178/// producer-owned `leanctx_*` keys sorted for determinism and lossless import.
179/// Emits an `f32` as its shortest round-trippable decimal so frontmatter shows
180/// `0.9` rather than the f64-widened `0.8999999761581421`. Keeps git diffs and
181/// prompt-cache bytes stable while parsing back to the same `f32` on import.
182fn clean_f32(x: f32) -> Value {
183    let parsed: f64 = format!("{x}").parse().unwrap_or_else(|_| f64::from(x));
184    serde_json::Number::from_f64(parsed).map_or(Value::Null, Value::Number)
185}
186
187fn concept_frontmatter(f: &KnowledgeFact) -> Vec<(String, Value)> {
188    let mut pairs: Vec<(String, Value)> = Vec::new();
189    pairs.push(("type".into(), Value::from(f.archetype.as_type_str())));
190    pairs.push(("title".into(), Value::from(f.key.clone())));
191    let desc = first_line(&f.value);
192    if !desc.is_empty() {
193        pairs.push(("description".into(), Value::from(desc)));
194    }
195    pairs.push(("tags".into(), Value::from(vec![f.category.clone()])));
196    pairs.push((
197        "timestamp".into(),
198        Value::from(f.last_confirmed.to_rfc3339()),
199    ));
200
201    let mut extra: BTreeMap<String, Value> = BTreeMap::new();
202    extra.insert(
203        "leanctx_origin".into(),
204        serde_json::to_value(&f.origin).unwrap_or(Value::Null),
205    );
206    extra.insert("leanctx_archetype".into(), f.archetype.as_type_str().into());
207    extra.insert("leanctx_category".into(), f.category.clone().into());
208    extra.insert("leanctx_confidence".into(), clean_f32(f.confidence));
209    extra.insert(
210        "leanctx_confirmation_count".into(),
211        f.confirmation_count.into(),
212    );
213    extra.insert(
214        "leanctx_created_at".into(),
215        f.created_at.to_rfc3339().into(),
216    );
217    extra.insert("leanctx_key".into(), f.key.clone().into());
218    extra.insert(
219        "leanctx_last_confirmed".into(),
220        f.last_confirmed.to_rfc3339().into(),
221    );
222    extra.insert("leanctx_revision_count".into(), f.revision_count.into());
223    extra.insert(
224        "leanctx_sensitivity".into(),
225        serde_json::to_value(f.sensitivity).unwrap_or_else(|_| "public".into()),
226    );
227    extra.insert(
228        "leanctx_source_session".into(),
229        f.source_session.clone().into(),
230    );
231    if let Some(vf) = f.valid_from {
232        extra.insert("leanctx_valid_from".into(), vf.to_rfc3339().into());
233    }
234    if let Some(vu) = f.valid_until {
235        extra.insert("leanctx_valid_until".into(), vu.to_rfc3339().into());
236    }
237    if let Some(s) = &f.supersedes {
238        extra.insert("leanctx_supersedes".into(), s.clone().into());
239    }
240    pairs.extend(extra);
241    pairs
242}
243
244fn render_pattern(p: &ProjectPattern) -> String {
245    let mut pairs: Vec<(String, Value)> = Vec::new();
246    pairs.push(("type".into(), Value::from("pattern")));
247    pairs.push(("title".into(), Value::from(p.pattern_type.clone())));
248    let desc = first_line(&p.description);
249    if !desc.is_empty() {
250        pairs.push(("description".into(), Value::from(desc)));
251    }
252    let mut extra: BTreeMap<String, Value> = BTreeMap::new();
253    extra.insert(
254        "leanctx_created_at".into(),
255        p.created_at.to_rfc3339().into(),
256    );
257    extra.insert("leanctx_examples".into(), Value::from(p.examples.clone()));
258    extra.insert("leanctx_kind".into(), "pattern".into());
259    extra.insert(
260        "leanctx_source_session".into(),
261        p.source_session.clone().into(),
262    );
263    pairs.extend(extra);
264
265    let mut out = emit_frontmatter(&pairs);
266    out.push('\n');
267    out.push_str(p.description.trim_end());
268    out.push('\n');
269    if !p.examples.is_empty() {
270        out.push_str("\n## Examples\n\n");
271        for ex in &p.examples {
272            out.push_str("- ");
273            out.push_str(ex.trim());
274            out.push('\n');
275        }
276    }
277    out
278}
279
280fn render_index(facts: &[&KnowledgeFact], patterns: &[ProjectPattern]) -> String {
281    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
282    for f in facts {
283        *counts.entry(f.category.clone()).or_insert(0) += 1;
284    }
285    let mut out = String::from(
286        "# Knowledge Index\n\nOpen Knowledge Format (OKF) bundle exported by lean-ctx.\n\n## Concepts by category\n\n",
287    );
288    if counts.is_empty() {
289        out.push_str("_none_\n");
290    } else {
291        for (cat, n) in &counts {
292            out.push_str(&format!("- {} ({})\n", dir_slug(cat), n));
293        }
294    }
295    out.push_str(&format!("\n## Patterns ({})\n", patterns.len()));
296    out
297}
298
299fn render_log(snapshot: &KnowledgeSnapshot) -> String {
300    let mut insights = snapshot.insights.clone();
301    insights.sort_by(|a, b| {
302        a.timestamp
303            .cmp(&b.timestamp)
304            .then_with(|| a.summary.cmp(&b.summary))
305    });
306    let mut out = String::from("# Change Log\n\n");
307    for i in &insights {
308        out.push_str(&format!("## {}\n\n", i.timestamp.to_rfc3339()));
309        out.push_str(i.summary.trim());
310        out.push('\n');
311        if !i.from_sessions.is_empty() {
312            out.push_str(&format!("\n_sessions: {}_\n", i.from_sessions.join(", ")));
313        }
314        out.push('\n');
315    }
316    out
317}
318
319// ---------------------------------------------------------------------------
320// Import
321// ---------------------------------------------------------------------------
322
323/// Parses an OKF directory into facts, patterns, and relations. Lenient by
324/// design: files without a `type` (or without frontmatter) are skipped rather
325/// than failing the whole import; use [`lint_okf_bundle`] to surface those.
326pub fn from_okf_dir(dir: &Path) -> Result<OkfImport, String> {
327    if !dir.is_dir() {
328        return Err(format!("not a directory: {}", dir.display()));
329    }
330    let mut imp = OkfImport::default();
331    for path in concept_files(dir) {
332        let Ok(content) = std::fs::read_to_string(&path) else {
333            continue;
334        };
335        let Some((fm_str, body)) = split_frontmatter(&content) else {
336            continue;
337        };
338        let fm = parse_frontmatter_map(&fm_str);
339        if !fm.contains_key("type") {
340            continue;
341        }
342
343        if fm.get("leanctx_kind").and_then(Value::as_str) == Some("pattern") {
344            if let Some(p) = build_pattern(&fm, &body) {
345                imp.patterns.push(p);
346            }
347            continue;
348        }
349
350        let category = concept_category(&fm);
351        let key = concept_key(&fm);
352        let from = KnowledgeNodeRef::new(&category, &key);
353        imp.facts.push(build_fact(&fm, &body, category, key));
354        imp.edges.extend(parse_relations(&body, &from));
355    }
356    Ok(imp)
357}
358
359/// Non-fatal conformance checks. Returns warnings only — OKF's own tooling
360/// treats these as advisory, and a partially-malformed bundle should still
361/// import what it can.
362pub fn lint_okf_bundle(dir: &Path) -> Vec<String> {
363    let mut warnings = Vec::new();
364    if !dir.is_dir() {
365        warnings.push(format!("not a directory: {}", dir.display()));
366        return warnings;
367    }
368    for path in concept_files(dir) {
369        let rel = path
370            .strip_prefix(dir)
371            .unwrap_or(&path)
372            .to_string_lossy()
373            .to_string();
374        let Ok(content) = std::fs::read_to_string(&path) else {
375            warnings.push(format!("{rel}: unreadable"));
376            continue;
377        };
378        let Some((fm_str, body)) = split_frontmatter(&content) else {
379            warnings.push(format!("{rel}: missing YAML frontmatter"));
380            continue;
381        };
382        let fm = parse_frontmatter_map(&fm_str);
383        if !fm.contains_key("type") {
384            warnings.push(format!("{rel}: missing required `type` field"));
385        }
386        if split_body_content(&body).is_empty() {
387            warnings.push(format!("{rel}: empty concept body"));
388        }
389    }
390    warnings
391}
392
393fn build_fact(fm: &Map<String, Value>, body: &str, category: String, key: String) -> KnowledgeFact {
394    let type_str = get_str(fm, "type").unwrap_or_else(|| "fact".to_string());
395    let content = split_body_content(body);
396    let value = if content.is_empty() {
397        get_str(fm, "description").unwrap_or_default()
398    } else {
399        content
400    };
401    let archetype = get_str(fm, "leanctx_archetype").map_or_else(
402        || KnowledgeArchetype::from_type_str(&type_str),
403        |s| KnowledgeArchetype::from_type_str(&s),
404    );
405    let confidence = fm
406        .get("leanctx_confidence")
407        .and_then(Value::as_f64)
408        .map_or(0.8, |v| v as f32);
409    let source_session =
410        get_str(fm, "leanctx_source_session").unwrap_or_else(|| "okf-import".to_string());
411    let created_at = get_dt(fm, "leanctx_created_at").unwrap_or_else(Utc::now);
412    let last_confirmed = get_dt(fm, "leanctx_last_confirmed")
413        .or_else(|| get_dt(fm, "timestamp"))
414        .unwrap_or(created_at);
415    let valid_from = get_dt(fm, "leanctx_valid_from").or(Some(created_at));
416    let valid_until = get_dt(fm, "leanctx_valid_until");
417    let confirmation_count = fm
418        .get("leanctx_confirmation_count")
419        .and_then(Value::as_u64)
420        .unwrap_or(1) as u32;
421    let revision_count = fm
422        .get("leanctx_revision_count")
423        .and_then(Value::as_u64)
424        .unwrap_or(0) as u32;
425    let sensitivity = get_str(fm, "leanctx_sensitivity")
426        .and_then(|s| serde_json::from_value(Value::String(s)).ok())
427        .unwrap_or_else(|| sensitivity::classify_content(&value));
428
429    KnowledgeFact {
430        origin: super::source_view::imported_origin(
431            &fm.get("leanctx_origin")
432                .and_then(|value| serde_json::from_value(value.clone()).ok())
433                .unwrap_or_default(),
434        ),
435        category,
436        key,
437        value,
438        source_session,
439        confidence,
440        created_at,
441        last_confirmed,
442        retrieval_count: 0,
443        last_retrieved: None,
444        valid_from,
445        valid_until,
446        supersedes: get_str(fm, "leanctx_supersedes"),
447        confirmation_count,
448        feedback_up: 0,
449        feedback_down: 0,
450        last_feedback: None,
451        privacy: FactPrivacy::default(),
452        sensitivity,
453        imported_from: Some("okf".to_string()),
454        archetype,
455        fidelity: None,
456        revision_count,
457    }
458}
459
460fn build_pattern(fm: &Map<String, Value>, body: &str) -> Option<ProjectPattern> {
461    let pattern_type = get_str(fm, "title")?;
462    let content = split_body_content(body);
463    let description = if content.is_empty() {
464        get_str(fm, "description").unwrap_or_default()
465    } else {
466        content
467    };
468    let examples = fm
469        .get("leanctx_examples")
470        .and_then(Value::as_array)
471        .map(|arr| {
472            arr.iter()
473                .filter_map(|v| v.as_str().map(String::from))
474                .collect()
475        })
476        .unwrap_or_default();
477    Some(ProjectPattern {
478        pattern_type,
479        description,
480        examples,
481        source_session: get_str(fm, "leanctx_source_session")
482            .unwrap_or_else(|| "okf-import".to_string()),
483        created_at: get_dt(fm, "leanctx_created_at").unwrap_or_else(Utc::now),
484    })
485}
486
487fn parse_relations(body: &str, from: &KnowledgeNodeRef) -> Vec<OkfEdge> {
488    let mut edges = Vec::new();
489    let mut in_relations = false;
490    for line in body.lines() {
491        let t = line.trim();
492        if t.eq_ignore_ascii_case("## relations") {
493            in_relations = true;
494            continue;
495        }
496        if in_relations && t.starts_with("## ") {
497            break;
498        }
499        if !in_relations {
500            continue;
501        }
502        let Some(rest) = t.strip_prefix("- ") else {
503            continue;
504        };
505        let Some((kind_str, link_part)) = rest.split_once(':') else {
506            continue;
507        };
508        let Some(kind) = KnowledgeEdgeKind::parse(kind_str.trim()) else {
509            continue;
510        };
511        // Extract the `[label]` target id from `[label](path)`.
512        let label = link_part.trim().trim_start_matches('[');
513        let Some(end) = label.find(']') else {
514            continue;
515        };
516        if let Some(to) = parse_node_ref(&label[..end]) {
517            edges.push(OkfEdge {
518                from: from.clone(),
519                to,
520                kind,
521            });
522        }
523    }
524    edges
525}
526
527// ---------------------------------------------------------------------------
528// Frontmatter helpers
529// ---------------------------------------------------------------------------
530
531/// Emits YAML frontmatter deterministically. Scalars are rendered via
532/// `serde_json` (JSON is a YAML 1.2 subset, so quoted strings / numbers / bools
533/// are valid YAML and unambiguous); arrays use block style for readability.
534fn emit_frontmatter(pairs: &[(String, Value)]) -> String {
535    let mut s = String::from("---\n");
536    for (k, v) in pairs {
537        match v {
538            Value::Array(items) if !items.is_empty() => {
539                s.push_str(k);
540                s.push_str(":\n");
541                for it in items {
542                    s.push_str("  - ");
543                    s.push_str(&serde_json::to_string(it).unwrap_or_else(|_| "null".into()));
544                    s.push('\n');
545                }
546            }
547            Value::Array(_) => {
548                s.push_str(k);
549                s.push_str(": []\n");
550            }
551            _ => {
552                s.push_str(k);
553                s.push_str(": ");
554                s.push_str(&serde_json::to_string(v).unwrap_or_else(|_| "null".into()));
555                s.push('\n');
556            }
557        }
558    }
559    s.push_str("---\n");
560    s
561}
562
563fn parse_frontmatter_map(fm: &str) -> Map<String, Value> {
564    yaml_serde::from_str::<Value>(fm)
565        .ok()
566        .and_then(|v| v.as_object().cloned())
567        .unwrap_or_default()
568}
569
570/// Splits a Markdown document into `(frontmatter, body)` if it opens with a
571/// `---` fenced YAML block. Returns `None` when there is no frontmatter.
572fn split_frontmatter(content: &str) -> Option<(String, String)> {
573    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
574    let after = content.strip_prefix("---")?;
575    let after = after
576        .strip_prefix("\r\n")
577        .or_else(|| after.strip_prefix('\n'))?;
578
579    let mut fm = String::new();
580    let mut body = String::new();
581    let mut closed = false;
582    let mut in_body = false;
583    for line in after.lines() {
584        if in_body {
585            body.push_str(line);
586            body.push('\n');
587        } else if line.trim_end() == "---" {
588            in_body = true;
589            closed = true;
590        } else {
591            fm.push_str(line);
592            fm.push('\n');
593        }
594    }
595    closed.then_some((fm, body))
596}
597
598/// The concept body with any `## Relations` (and later sections) stripped —
599/// i.e. the actual knowledge content.
600fn split_body_content(body: &str) -> String {
601    let mut out = String::new();
602    for line in body.lines() {
603        let t = line.trim();
604        if t.eq_ignore_ascii_case("## relations") {
605            break;
606        }
607        out.push_str(line);
608        out.push('\n');
609    }
610    out.trim().to_string()
611}
612
613fn concept_category(fm: &Map<String, Value>) -> String {
614    get_str(fm, "leanctx_category")
615        .or_else(|| get_str_array_first(fm, "tags"))
616        .unwrap_or_else(|| "imported".to_string())
617}
618
619fn concept_key(fm: &Map<String, Value>) -> String {
620    get_str(fm, "leanctx_key")
621        .or_else(|| get_str(fm, "title"))
622        .unwrap_or_else(|| "concept".to_string())
623}
624
625fn get_str(fm: &Map<String, Value>, key: &str) -> Option<String> {
626    fm.get(key).and_then(Value::as_str).map(str::to_string)
627}
628
629fn get_str_array_first(fm: &Map<String, Value>, key: &str) -> Option<String> {
630    fm.get(key)?
631        .as_array()?
632        .iter()
633        .find_map(|v| v.as_str().map(String::from))
634}
635
636fn get_dt(fm: &Map<String, Value>, key: &str) -> Option<DateTime<Utc>> {
637    let s = fm.get(key).and_then(Value::as_str)?;
638    DateTime::parse_from_rfc3339(s)
639        .ok()
640        .map(|dt| dt.with_timezone(&Utc))
641}
642
643// ---------------------------------------------------------------------------
644// Slugs & paths
645// ---------------------------------------------------------------------------
646
647fn first_line(s: &str) -> String {
648    s.lines()
649        .find(|l| !l.trim().is_empty())
650        .unwrap_or("")
651        .trim()
652        .to_string()
653}
654
655/// Deterministic, filesystem-safe slug: lowercase alphanumerics, single dashes
656/// for separators, trimmed, capped.
657fn slug_like(s: &str) -> String {
658    let mut out = String::new();
659    for ch in s.chars() {
660        if out.len() >= 60 {
661            break;
662        }
663        if ch.is_ascii_alphanumeric() {
664            out.push(ch.to_ascii_lowercase());
665        } else if !out.ends_with('-') && !out.is_empty() {
666            out.push('-');
667        }
668    }
669    out.trim_matches('-').to_string()
670}
671
672fn dir_slug(category: &str) -> String {
673    let s = slug_like(category);
674    if s.is_empty() { "misc".to_string() } else { s }
675}
676
677/// A slug unique within `dir`. On collision (two keys slugging alike) a short
678/// BLAKE3 digest of the full key is appended — stable regardless of iteration
679/// order, so the bundle stays deterministic.
680fn unique_slug(dir: &str, key: &str, used: &mut HashSet<(String, String)>) -> String {
681    let base = {
682        let s = slug_like(key);
683        if s.is_empty() { "fact".to_string() } else { s }
684    };
685    if used.insert((dir.to_string(), base.clone())) {
686        return base;
687    }
688    let suffix = &blake3::hash(key.as_bytes()).to_hex()[..8];
689    let cand = format!("{base}-{suffix}");
690    used.insert((dir.to_string(), cand.clone()));
691    cand
692}
693
694fn relative_link(from_dir: &str, to: &ConceptLoc) -> String {
695    if from_dir == to.dir {
696        format!("{}.md", to.file)
697    } else {
698        format!("../{}/{}.md", to.dir, to.file)
699    }
700}
701
702/// All concept `*.md` files in the bundle, sorted, excluding reserved
703/// `index.md` / `log.md`.
704fn concept_files(dir: &Path) -> Vec<std::path::PathBuf> {
705    let mut files: Vec<std::path::PathBuf> = WalkDir::new(dir)
706        .sort_by_file_name()
707        .into_iter()
708        .filter_map(Result::ok)
709        .filter(|e| e.file_type().is_file())
710        .map(walkdir::DirEntry::into_path)
711        .filter(|p| p.extension().is_some_and(|e| e == "md"))
712        .filter(|p| {
713            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
714            name != INDEX_FILE && name != LOG_FILE
715        })
716        .collect();
717    files.sort();
718    files
719}
720
721#[cfg(test)]
722mod tests {
723    use super::*;
724    use crate::core::knowledge_relations::KnowledgeRelationGraph;
725
726    fn fact(
727        category: &str,
728        key: &str,
729        value: &str,
730        archetype: KnowledgeArchetype,
731    ) -> KnowledgeFact {
732        let now = Utc::now();
733        KnowledgeFact {
734            origin: crate::core::knowledge::FactOrigin::Local,
735            category: category.into(),
736            key: key.into(),
737            value: value.into(),
738            source_session: "s1".into(),
739            confidence: 0.9,
740            created_at: now,
741            last_confirmed: now,
742            retrieval_count: 0,
743            last_retrieved: None,
744            valid_from: Some(now),
745            valid_until: None,
746            supersedes: None,
747            confirmation_count: 1,
748            feedback_up: 0,
749            feedback_down: 0,
750            last_feedback: None,
751            privacy: FactPrivacy::default(),
752            sensitivity: crate::core::sensitivity::SensitivityLevel::default(),
753            imported_from: None,
754            archetype,
755            fidelity: None,
756            revision_count: 1,
757        }
758    }
759
760    fn sample_snapshot() -> KnowledgeSnapshot {
761        let facts = vec![
762            fact(
763                "architecture",
764                "auth",
765                "Auth uses JWT RS256 tokens verified against Redis sessions.",
766                KnowledgeArchetype::Architecture,
767            ),
768            fact(
769                "architecture",
770                "db",
771                "PostgreSQL 16 with pgvector for the primary datastore.",
772                KnowledgeArchetype::Architecture,
773            ),
774        ];
775        let mut graph = KnowledgeRelationGraph::new("hash");
776        graph.upsert_edge(
777            KnowledgeNodeRef::new("architecture", "auth"),
778            KnowledgeNodeRef::new("architecture", "db"),
779            KnowledgeEdgeKind::DependsOn,
780            "s1",
781        );
782        KnowledgeSnapshot {
783            project_root: "/tmp/proj".into(),
784            project_hash: "hash".into(),
785            facts,
786            patterns: Vec::new(),
787            insights: Vec::new(),
788            relations: graph.edges,
789            task_id: None,
790            policy_version: None,
791            knowledge_refs: Vec::new(),
792            snapshot_hash: None,
793        }
794    }
795
796    fn key_set(facts: &[KnowledgeFact]) -> HashSet<(String, String, String, String)> {
797        facts
798            .iter()
799            .map(|f| {
800                (
801                    f.category.clone(),
802                    f.key.clone(),
803                    f.value.clone(),
804                    f.archetype.as_type_str().to_string(),
805                )
806            })
807            .collect()
808    }
809
810    #[test]
811    fn round_trip_preserves_facts_and_relations() {
812        let snap = sample_snapshot();
813        let bundle = to_okf_bundle(&snap);
814        let dir = tempfile::tempdir().unwrap();
815        write_okf_bundle(dir.path(), &bundle).unwrap();
816
817        let imported = from_okf_dir(dir.path()).unwrap();
818        assert_eq!(
819            key_set(&imported.facts),
820            key_set(&snap.facts),
821            "current facts (category/key/value/archetype) survive the round-trip"
822        );
823
824        assert_eq!(imported.edges.len(), 1, "the depends_on relation survives");
825        let e = &imported.edges[0];
826        assert_eq!(e.from, KnowledgeNodeRef::new("architecture", "auth"));
827        assert_eq!(e.to, KnowledgeNodeRef::new("architecture", "db"));
828        assert_eq!(e.kind, KnowledgeEdgeKind::DependsOn);
829    }
830
831    #[test]
832    fn export_is_byte_deterministic() {
833        let snap = sample_snapshot();
834        assert_eq!(
835            to_okf_bundle(&snap),
836            to_okf_bundle(&snap),
837            "two exports of the same snapshot are byte-identical (#498)"
838        );
839    }
840
841    #[test]
842    fn okf_concepts_match_current_facts() {
843        // The shared-core guarantee: the OKF rendering derives exactly the
844        // snapshot's current facts — one concept file per current fact.
845        let snap = sample_snapshot();
846        let bundle = to_okf_bundle(&snap);
847        let concept_count = bundle
848            .keys()
849            .filter(|k| *k != INDEX_FILE && *k != LOG_FILE && !k.starts_with(PATTERNS_DIR))
850            .count();
851        assert_eq!(concept_count, snap.current_facts().len());
852    }
853
854    #[test]
855    fn foreign_bundle_needs_only_type() {
856        let dir = tempfile::tempdir().unwrap();
857        std::fs::write(
858            dir.path().join("note.md"),
859            "---\ntype: architecture\n---\n\nWe run everything on Kubernetes.\n",
860        )
861        .unwrap();
862
863        let imp = from_okf_dir(dir.path()).unwrap();
864        assert_eq!(
865            imp.facts.len(),
866            1,
867            "a type-only concept imports as one fact"
868        );
869        let f = &imp.facts[0];
870        assert_eq!(f.archetype, KnowledgeArchetype::Architecture);
871        assert_eq!(f.value, "We run everything on Kubernetes.");
872        assert_eq!(
873            f.key, "concept",
874            "no title/leanctx_key falls back to a default"
875        );
876    }
877
878    #[test]
879    fn unknown_frontmatter_keys_survive_a_parse_emit_cycle() {
880        // OKF lets producers add arbitrary keys and requires consumers to keep
881        // them. Our frontmatter emitter/parser round-trips an unknown key.
882        let src = "custom_producer_key: \"keep me\"\ntype: \"fact\"\n";
883        let map = parse_frontmatter_map(src);
884        let pairs: Vec<(String, Value)> = map.into_iter().collect();
885        let emitted = emit_frontmatter(&pairs);
886        let reparsed = parse_frontmatter_map(
887            emitted
888                .trim_start_matches("---\n")
889                .trim_end_matches("---\n"),
890        );
891        assert_eq!(
892            reparsed.get("custom_producer_key").and_then(Value::as_str),
893            Some("keep me")
894        );
895    }
896
897    #[test]
898    fn lint_reports_warnings_never_panics() {
899        let dir = tempfile::tempdir().unwrap();
900        std::fs::write(dir.path().join("bad.md"), "no frontmatter here\n").unwrap();
901        std::fs::write(dir.path().join("ok.md"), "---\ntype: fact\n---\n\nbody\n").unwrap();
902        let warnings = lint_okf_bundle(dir.path());
903        assert!(
904            warnings.iter().any(|w| w.contains("bad.md")),
905            "the malformed file is flagged: {warnings:?}"
906        );
907        // The good file still imports despite the bad one.
908        assert_eq!(from_okf_dir(dir.path()).unwrap().facts.len(), 1);
909    }
910
911    #[test]
912    fn patterns_round_trip_with_examples() {
913        let mut snap = sample_snapshot();
914        snap.patterns.push(ProjectPattern {
915            pattern_type: "naming".into(),
916            description: "snake_case for functions".into(),
917            examples: vec!["get_user()".into()],
918            source_session: "s1".into(),
919            created_at: Utc::now(),
920        });
921        let bundle = to_okf_bundle(&snap);
922        let dir = tempfile::tempdir().unwrap();
923        write_okf_bundle(dir.path(), &bundle).unwrap();
924
925        let imp = from_okf_dir(dir.path()).unwrap();
926        assert_eq!(imp.patterns.len(), 1);
927        assert_eq!(imp.patterns[0].pattern_type, "naming");
928        assert_eq!(imp.patterns[0].examples, vec!["get_user()".to_string()]);
929    }
930}