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("leanctx_archetype".into(), f.archetype.as_type_str().into());
203    extra.insert("leanctx_category".into(), f.category.clone().into());
204    extra.insert("leanctx_confidence".into(), clean_f32(f.confidence));
205    extra.insert(
206        "leanctx_confirmation_count".into(),
207        f.confirmation_count.into(),
208    );
209    extra.insert(
210        "leanctx_created_at".into(),
211        f.created_at.to_rfc3339().into(),
212    );
213    extra.insert("leanctx_key".into(), f.key.clone().into());
214    extra.insert(
215        "leanctx_last_confirmed".into(),
216        f.last_confirmed.to_rfc3339().into(),
217    );
218    extra.insert("leanctx_revision_count".into(), f.revision_count.into());
219    extra.insert(
220        "leanctx_sensitivity".into(),
221        serde_json::to_value(f.sensitivity).unwrap_or_else(|_| "public".into()),
222    );
223    extra.insert(
224        "leanctx_source_session".into(),
225        f.source_session.clone().into(),
226    );
227    if let Some(vf) = f.valid_from {
228        extra.insert("leanctx_valid_from".into(), vf.to_rfc3339().into());
229    }
230    if let Some(vu) = f.valid_until {
231        extra.insert("leanctx_valid_until".into(), vu.to_rfc3339().into());
232    }
233    if let Some(s) = &f.supersedes {
234        extra.insert("leanctx_supersedes".into(), s.clone().into());
235    }
236    pairs.extend(extra);
237    pairs
238}
239
240fn render_pattern(p: &ProjectPattern) -> String {
241    let mut pairs: Vec<(String, Value)> = Vec::new();
242    pairs.push(("type".into(), Value::from("pattern")));
243    pairs.push(("title".into(), Value::from(p.pattern_type.clone())));
244    let desc = first_line(&p.description);
245    if !desc.is_empty() {
246        pairs.push(("description".into(), Value::from(desc)));
247    }
248    let mut extra: BTreeMap<String, Value> = BTreeMap::new();
249    extra.insert(
250        "leanctx_created_at".into(),
251        p.created_at.to_rfc3339().into(),
252    );
253    extra.insert("leanctx_examples".into(), Value::from(p.examples.clone()));
254    extra.insert("leanctx_kind".into(), "pattern".into());
255    extra.insert(
256        "leanctx_source_session".into(),
257        p.source_session.clone().into(),
258    );
259    pairs.extend(extra);
260
261    let mut out = emit_frontmatter(&pairs);
262    out.push('\n');
263    out.push_str(p.description.trim_end());
264    out.push('\n');
265    if !p.examples.is_empty() {
266        out.push_str("\n## Examples\n\n");
267        for ex in &p.examples {
268            out.push_str("- ");
269            out.push_str(ex.trim());
270            out.push('\n');
271        }
272    }
273    out
274}
275
276fn render_index(facts: &[&KnowledgeFact], patterns: &[ProjectPattern]) -> String {
277    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
278    for f in facts {
279        *counts.entry(f.category.clone()).or_insert(0) += 1;
280    }
281    let mut out = String::from(
282        "# Knowledge Index\n\nOpen Knowledge Format (OKF) bundle exported by lean-ctx.\n\n## Concepts by category\n\n",
283    );
284    if counts.is_empty() {
285        out.push_str("_none_\n");
286    } else {
287        for (cat, n) in &counts {
288            out.push_str(&format!("- {} ({})\n", dir_slug(cat), n));
289        }
290    }
291    out.push_str(&format!("\n## Patterns ({})\n", patterns.len()));
292    out
293}
294
295fn render_log(snapshot: &KnowledgeSnapshot) -> String {
296    let mut insights = snapshot.insights.clone();
297    insights.sort_by(|a, b| {
298        a.timestamp
299            .cmp(&b.timestamp)
300            .then_with(|| a.summary.cmp(&b.summary))
301    });
302    let mut out = String::from("# Change Log\n\n");
303    for i in &insights {
304        out.push_str(&format!("## {}\n\n", i.timestamp.to_rfc3339()));
305        out.push_str(i.summary.trim());
306        out.push('\n');
307        if !i.from_sessions.is_empty() {
308            out.push_str(&format!("\n_sessions: {}_\n", i.from_sessions.join(", ")));
309        }
310        out.push('\n');
311    }
312    out
313}
314
315// ---------------------------------------------------------------------------
316// Import
317// ---------------------------------------------------------------------------
318
319/// Parses an OKF directory into facts, patterns, and relations. Lenient by
320/// design: files without a `type` (or without frontmatter) are skipped rather
321/// than failing the whole import; use [`lint_okf_bundle`] to surface those.
322pub fn from_okf_dir(dir: &Path) -> Result<OkfImport, String> {
323    if !dir.is_dir() {
324        return Err(format!("not a directory: {}", dir.display()));
325    }
326    let mut imp = OkfImport::default();
327    for path in concept_files(dir) {
328        let Ok(content) = std::fs::read_to_string(&path) else {
329            continue;
330        };
331        let Some((fm_str, body)) = split_frontmatter(&content) else {
332            continue;
333        };
334        let fm = parse_frontmatter_map(&fm_str);
335        if !fm.contains_key("type") {
336            continue;
337        }
338
339        if fm.get("leanctx_kind").and_then(Value::as_str) == Some("pattern") {
340            if let Some(p) = build_pattern(&fm, &body) {
341                imp.patterns.push(p);
342            }
343            continue;
344        }
345
346        let category = concept_category(&fm);
347        let key = concept_key(&fm);
348        let from = KnowledgeNodeRef::new(&category, &key);
349        imp.facts.push(build_fact(&fm, &body, category, key));
350        imp.edges.extend(parse_relations(&body, &from));
351    }
352    Ok(imp)
353}
354
355/// Non-fatal conformance checks. Returns warnings only — OKF's own tooling
356/// treats these as advisory, and a partially-malformed bundle should still
357/// import what it can.
358pub fn lint_okf_bundle(dir: &Path) -> Vec<String> {
359    let mut warnings = Vec::new();
360    if !dir.is_dir() {
361        warnings.push(format!("not a directory: {}", dir.display()));
362        return warnings;
363    }
364    for path in concept_files(dir) {
365        let rel = path
366            .strip_prefix(dir)
367            .unwrap_or(&path)
368            .to_string_lossy()
369            .to_string();
370        let Ok(content) = std::fs::read_to_string(&path) else {
371            warnings.push(format!("{rel}: unreadable"));
372            continue;
373        };
374        let Some((fm_str, body)) = split_frontmatter(&content) else {
375            warnings.push(format!("{rel}: missing YAML frontmatter"));
376            continue;
377        };
378        let fm = parse_frontmatter_map(&fm_str);
379        if !fm.contains_key("type") {
380            warnings.push(format!("{rel}: missing required `type` field"));
381        }
382        if split_body_content(&body).is_empty() {
383            warnings.push(format!("{rel}: empty concept body"));
384        }
385    }
386    warnings
387}
388
389fn build_fact(fm: &Map<String, Value>, body: &str, category: String, key: String) -> KnowledgeFact {
390    let type_str = get_str(fm, "type").unwrap_or_else(|| "fact".to_string());
391    let content = split_body_content(body);
392    let value = if content.is_empty() {
393        get_str(fm, "description").unwrap_or_default()
394    } else {
395        content
396    };
397    let archetype = get_str(fm, "leanctx_archetype").map_or_else(
398        || KnowledgeArchetype::from_type_str(&type_str),
399        |s| KnowledgeArchetype::from_type_str(&s),
400    );
401    let confidence = fm
402        .get("leanctx_confidence")
403        .and_then(Value::as_f64)
404        .map_or(0.8, |v| v as f32);
405    let source_session =
406        get_str(fm, "leanctx_source_session").unwrap_or_else(|| "okf-import".to_string());
407    let created_at = get_dt(fm, "leanctx_created_at").unwrap_or_else(Utc::now);
408    let last_confirmed = get_dt(fm, "leanctx_last_confirmed")
409        .or_else(|| get_dt(fm, "timestamp"))
410        .unwrap_or(created_at);
411    let valid_from = get_dt(fm, "leanctx_valid_from").or(Some(created_at));
412    let valid_until = get_dt(fm, "leanctx_valid_until");
413    let confirmation_count = fm
414        .get("leanctx_confirmation_count")
415        .and_then(Value::as_u64)
416        .unwrap_or(1) as u32;
417    let revision_count = fm
418        .get("leanctx_revision_count")
419        .and_then(Value::as_u64)
420        .unwrap_or(0) as u32;
421    let sensitivity = get_str(fm, "leanctx_sensitivity")
422        .and_then(|s| serde_json::from_value(Value::String(s)).ok())
423        .unwrap_or_else(|| sensitivity::classify_content(&value));
424
425    KnowledgeFact {
426        category,
427        key,
428        value,
429        source_session,
430        confidence,
431        created_at,
432        last_confirmed,
433        retrieval_count: 0,
434        last_retrieved: None,
435        valid_from,
436        valid_until,
437        supersedes: get_str(fm, "leanctx_supersedes"),
438        confirmation_count,
439        feedback_up: 0,
440        feedback_down: 0,
441        last_feedback: None,
442        privacy: FactPrivacy::default(),
443        sensitivity,
444        imported_from: Some("okf".to_string()),
445        archetype,
446        fidelity: None,
447        revision_count,
448    }
449}
450
451fn build_pattern(fm: &Map<String, Value>, body: &str) -> Option<ProjectPattern> {
452    let pattern_type = get_str(fm, "title")?;
453    let content = split_body_content(body);
454    let description = if content.is_empty() {
455        get_str(fm, "description").unwrap_or_default()
456    } else {
457        content
458    };
459    let examples = fm
460        .get("leanctx_examples")
461        .and_then(Value::as_array)
462        .map(|arr| {
463            arr.iter()
464                .filter_map(|v| v.as_str().map(String::from))
465                .collect()
466        })
467        .unwrap_or_default();
468    Some(ProjectPattern {
469        pattern_type,
470        description,
471        examples,
472        source_session: get_str(fm, "leanctx_source_session")
473            .unwrap_or_else(|| "okf-import".to_string()),
474        created_at: get_dt(fm, "leanctx_created_at").unwrap_or_else(Utc::now),
475    })
476}
477
478fn parse_relations(body: &str, from: &KnowledgeNodeRef) -> Vec<OkfEdge> {
479    let mut edges = Vec::new();
480    let mut in_relations = false;
481    for line in body.lines() {
482        let t = line.trim();
483        if t.eq_ignore_ascii_case("## relations") {
484            in_relations = true;
485            continue;
486        }
487        if in_relations && t.starts_with("## ") {
488            break;
489        }
490        if !in_relations {
491            continue;
492        }
493        let Some(rest) = t.strip_prefix("- ") else {
494            continue;
495        };
496        let Some((kind_str, link_part)) = rest.split_once(':') else {
497            continue;
498        };
499        let Some(kind) = KnowledgeEdgeKind::parse(kind_str.trim()) else {
500            continue;
501        };
502        // Extract the `[label]` target id from `[label](path)`.
503        let label = link_part.trim().trim_start_matches('[');
504        let Some(end) = label.find(']') else {
505            continue;
506        };
507        if let Some(to) = parse_node_ref(&label[..end]) {
508            edges.push(OkfEdge {
509                from: from.clone(),
510                to,
511                kind,
512            });
513        }
514    }
515    edges
516}
517
518// ---------------------------------------------------------------------------
519// Frontmatter helpers
520// ---------------------------------------------------------------------------
521
522/// Emits YAML frontmatter deterministically. Scalars are rendered via
523/// `serde_json` (JSON is a YAML 1.2 subset, so quoted strings / numbers / bools
524/// are valid YAML and unambiguous); arrays use block style for readability.
525fn emit_frontmatter(pairs: &[(String, Value)]) -> String {
526    let mut s = String::from("---\n");
527    for (k, v) in pairs {
528        match v {
529            Value::Array(items) if !items.is_empty() => {
530                s.push_str(k);
531                s.push_str(":\n");
532                for it in items {
533                    s.push_str("  - ");
534                    s.push_str(&serde_json::to_string(it).unwrap_or_else(|_| "null".into()));
535                    s.push('\n');
536                }
537            }
538            Value::Array(_) => {
539                s.push_str(k);
540                s.push_str(": []\n");
541            }
542            _ => {
543                s.push_str(k);
544                s.push_str(": ");
545                s.push_str(&serde_json::to_string(v).unwrap_or_else(|_| "null".into()));
546                s.push('\n');
547            }
548        }
549    }
550    s.push_str("---\n");
551    s
552}
553
554fn parse_frontmatter_map(fm: &str) -> Map<String, Value> {
555    yaml_serde::from_str::<Value>(fm)
556        .ok()
557        .and_then(|v| v.as_object().cloned())
558        .unwrap_or_default()
559}
560
561/// Splits a Markdown document into `(frontmatter, body)` if it opens with a
562/// `---` fenced YAML block. Returns `None` when there is no frontmatter.
563fn split_frontmatter(content: &str) -> Option<(String, String)> {
564    let content = content.strip_prefix('\u{feff}').unwrap_or(content);
565    let after = content.strip_prefix("---")?;
566    let after = after
567        .strip_prefix("\r\n")
568        .or_else(|| after.strip_prefix('\n'))?;
569
570    let mut fm = String::new();
571    let mut body = String::new();
572    let mut closed = false;
573    let mut in_body = false;
574    for line in after.lines() {
575        if in_body {
576            body.push_str(line);
577            body.push('\n');
578        } else if line.trim_end() == "---" {
579            in_body = true;
580            closed = true;
581        } else {
582            fm.push_str(line);
583            fm.push('\n');
584        }
585    }
586    closed.then_some((fm, body))
587}
588
589/// The concept body with any `## Relations` (and later sections) stripped —
590/// i.e. the actual knowledge content.
591fn split_body_content(body: &str) -> String {
592    let mut out = String::new();
593    for line in body.lines() {
594        let t = line.trim();
595        if t.eq_ignore_ascii_case("## relations") {
596            break;
597        }
598        out.push_str(line);
599        out.push('\n');
600    }
601    out.trim().to_string()
602}
603
604fn concept_category(fm: &Map<String, Value>) -> String {
605    get_str(fm, "leanctx_category")
606        .or_else(|| get_str_array_first(fm, "tags"))
607        .unwrap_or_else(|| "imported".to_string())
608}
609
610fn concept_key(fm: &Map<String, Value>) -> String {
611    get_str(fm, "leanctx_key")
612        .or_else(|| get_str(fm, "title"))
613        .unwrap_or_else(|| "concept".to_string())
614}
615
616fn get_str(fm: &Map<String, Value>, key: &str) -> Option<String> {
617    fm.get(key).and_then(Value::as_str).map(str::to_string)
618}
619
620fn get_str_array_first(fm: &Map<String, Value>, key: &str) -> Option<String> {
621    fm.get(key)?
622        .as_array()?
623        .iter()
624        .find_map(|v| v.as_str().map(String::from))
625}
626
627fn get_dt(fm: &Map<String, Value>, key: &str) -> Option<DateTime<Utc>> {
628    let s = fm.get(key).and_then(Value::as_str)?;
629    DateTime::parse_from_rfc3339(s)
630        .ok()
631        .map(|dt| dt.with_timezone(&Utc))
632}
633
634// ---------------------------------------------------------------------------
635// Slugs & paths
636// ---------------------------------------------------------------------------
637
638fn first_line(s: &str) -> String {
639    s.lines()
640        .find(|l| !l.trim().is_empty())
641        .unwrap_or("")
642        .trim()
643        .to_string()
644}
645
646/// Deterministic, filesystem-safe slug: lowercase alphanumerics, single dashes
647/// for separators, trimmed, capped.
648fn slug_like(s: &str) -> String {
649    let mut out = String::new();
650    for ch in s.chars() {
651        if out.len() >= 60 {
652            break;
653        }
654        if ch.is_ascii_alphanumeric() {
655            out.push(ch.to_ascii_lowercase());
656        } else if !out.ends_with('-') && !out.is_empty() {
657            out.push('-');
658        }
659    }
660    out.trim_matches('-').to_string()
661}
662
663fn dir_slug(category: &str) -> String {
664    let s = slug_like(category);
665    if s.is_empty() { "misc".to_string() } else { s }
666}
667
668/// A slug unique within `dir`. On collision (two keys slugging alike) a short
669/// BLAKE3 digest of the full key is appended — stable regardless of iteration
670/// order, so the bundle stays deterministic.
671fn unique_slug(dir: &str, key: &str, used: &mut HashSet<(String, String)>) -> String {
672    let base = {
673        let s = slug_like(key);
674        if s.is_empty() { "fact".to_string() } else { s }
675    };
676    if used.insert((dir.to_string(), base.clone())) {
677        return base;
678    }
679    let suffix = &blake3::hash(key.as_bytes()).to_hex()[..8];
680    let cand = format!("{base}-{suffix}");
681    used.insert((dir.to_string(), cand.clone()));
682    cand
683}
684
685fn relative_link(from_dir: &str, to: &ConceptLoc) -> String {
686    if from_dir == to.dir {
687        format!("{}.md", to.file)
688    } else {
689        format!("../{}/{}.md", to.dir, to.file)
690    }
691}
692
693/// All concept `*.md` files in the bundle, sorted, excluding reserved
694/// `index.md` / `log.md`.
695fn concept_files(dir: &Path) -> Vec<std::path::PathBuf> {
696    let mut files: Vec<std::path::PathBuf> = WalkDir::new(dir)
697        .sort_by_file_name()
698        .into_iter()
699        .filter_map(Result::ok)
700        .filter(|e| e.file_type().is_file())
701        .map(walkdir::DirEntry::into_path)
702        .filter(|p| p.extension().is_some_and(|e| e == "md"))
703        .filter(|p| {
704            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
705            name != INDEX_FILE && name != LOG_FILE
706        })
707        .collect();
708    files.sort();
709    files
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715    use crate::core::knowledge_relations::KnowledgeRelationGraph;
716
717    fn fact(
718        category: &str,
719        key: &str,
720        value: &str,
721        archetype: KnowledgeArchetype,
722    ) -> KnowledgeFact {
723        let now = Utc::now();
724        KnowledgeFact {
725            category: category.into(),
726            key: key.into(),
727            value: value.into(),
728            source_session: "s1".into(),
729            confidence: 0.9,
730            created_at: now,
731            last_confirmed: now,
732            retrieval_count: 0,
733            last_retrieved: None,
734            valid_from: Some(now),
735            valid_until: None,
736            supersedes: None,
737            confirmation_count: 1,
738            feedback_up: 0,
739            feedback_down: 0,
740            last_feedback: None,
741            privacy: FactPrivacy::default(),
742            sensitivity: crate::core::sensitivity::SensitivityLevel::default(),
743            imported_from: None,
744            archetype,
745            fidelity: None,
746            revision_count: 1,
747        }
748    }
749
750    fn sample_snapshot() -> KnowledgeSnapshot {
751        let facts = vec![
752            fact(
753                "architecture",
754                "auth",
755                "Auth uses JWT RS256 tokens verified against Redis sessions.",
756                KnowledgeArchetype::Architecture,
757            ),
758            fact(
759                "architecture",
760                "db",
761                "PostgreSQL 16 with pgvector for the primary datastore.",
762                KnowledgeArchetype::Architecture,
763            ),
764        ];
765        let mut graph = KnowledgeRelationGraph::new("hash");
766        graph.upsert_edge(
767            KnowledgeNodeRef::new("architecture", "auth"),
768            KnowledgeNodeRef::new("architecture", "db"),
769            KnowledgeEdgeKind::DependsOn,
770            "s1",
771        );
772        KnowledgeSnapshot {
773            project_root: "/tmp/proj".into(),
774            project_hash: "hash".into(),
775            facts,
776            patterns: Vec::new(),
777            insights: Vec::new(),
778            relations: graph.edges,
779        }
780    }
781
782    fn key_set(facts: &[KnowledgeFact]) -> HashSet<(String, String, String, String)> {
783        facts
784            .iter()
785            .map(|f| {
786                (
787                    f.category.clone(),
788                    f.key.clone(),
789                    f.value.clone(),
790                    f.archetype.as_type_str().to_string(),
791                )
792            })
793            .collect()
794    }
795
796    #[test]
797    fn round_trip_preserves_facts_and_relations() {
798        let snap = sample_snapshot();
799        let bundle = to_okf_bundle(&snap);
800        let dir = tempfile::tempdir().unwrap();
801        write_okf_bundle(dir.path(), &bundle).unwrap();
802
803        let imported = from_okf_dir(dir.path()).unwrap();
804        assert_eq!(
805            key_set(&imported.facts),
806            key_set(&snap.facts),
807            "current facts (category/key/value/archetype) survive the round-trip"
808        );
809
810        assert_eq!(imported.edges.len(), 1, "the depends_on relation survives");
811        let e = &imported.edges[0];
812        assert_eq!(e.from, KnowledgeNodeRef::new("architecture", "auth"));
813        assert_eq!(e.to, KnowledgeNodeRef::new("architecture", "db"));
814        assert_eq!(e.kind, KnowledgeEdgeKind::DependsOn);
815    }
816
817    #[test]
818    fn export_is_byte_deterministic() {
819        let snap = sample_snapshot();
820        assert_eq!(
821            to_okf_bundle(&snap),
822            to_okf_bundle(&snap),
823            "two exports of the same snapshot are byte-identical (#498)"
824        );
825    }
826
827    #[test]
828    fn okf_concepts_match_current_facts() {
829        // The shared-core guarantee: the OKF rendering derives exactly the
830        // snapshot's current facts — one concept file per current fact.
831        let snap = sample_snapshot();
832        let bundle = to_okf_bundle(&snap);
833        let concept_count = bundle
834            .keys()
835            .filter(|k| *k != INDEX_FILE && *k != LOG_FILE && !k.starts_with(PATTERNS_DIR))
836            .count();
837        assert_eq!(concept_count, snap.current_facts().len());
838    }
839
840    #[test]
841    fn foreign_bundle_needs_only_type() {
842        let dir = tempfile::tempdir().unwrap();
843        std::fs::write(
844            dir.path().join("note.md"),
845            "---\ntype: architecture\n---\n\nWe run everything on Kubernetes.\n",
846        )
847        .unwrap();
848
849        let imp = from_okf_dir(dir.path()).unwrap();
850        assert_eq!(
851            imp.facts.len(),
852            1,
853            "a type-only concept imports as one fact"
854        );
855        let f = &imp.facts[0];
856        assert_eq!(f.archetype, KnowledgeArchetype::Architecture);
857        assert_eq!(f.value, "We run everything on Kubernetes.");
858        assert_eq!(
859            f.key, "concept",
860            "no title/leanctx_key falls back to a default"
861        );
862    }
863
864    #[test]
865    fn unknown_frontmatter_keys_survive_a_parse_emit_cycle() {
866        // OKF lets producers add arbitrary keys and requires consumers to keep
867        // them. Our frontmatter emitter/parser round-trips an unknown key.
868        let src = "custom_producer_key: \"keep me\"\ntype: \"fact\"\n";
869        let map = parse_frontmatter_map(src);
870        let pairs: Vec<(String, Value)> = map.into_iter().collect();
871        let emitted = emit_frontmatter(&pairs);
872        let reparsed = parse_frontmatter_map(
873            emitted
874                .trim_start_matches("---\n")
875                .trim_end_matches("---\n"),
876        );
877        assert_eq!(
878            reparsed.get("custom_producer_key").and_then(Value::as_str),
879            Some("keep me")
880        );
881    }
882
883    #[test]
884    fn lint_reports_warnings_never_panics() {
885        let dir = tempfile::tempdir().unwrap();
886        std::fs::write(dir.path().join("bad.md"), "no frontmatter here\n").unwrap();
887        std::fs::write(dir.path().join("ok.md"), "---\ntype: fact\n---\n\nbody\n").unwrap();
888        let warnings = lint_okf_bundle(dir.path());
889        assert!(
890            warnings.iter().any(|w| w.contains("bad.md")),
891            "the malformed file is flagged: {warnings:?}"
892        );
893        // The good file still imports despite the bad one.
894        assert_eq!(from_okf_dir(dir.path()).unwrap().facts.len(), 1);
895    }
896
897    #[test]
898    fn patterns_round_trip_with_examples() {
899        let mut snap = sample_snapshot();
900        snap.patterns.push(ProjectPattern {
901            pattern_type: "naming".into(),
902            description: "snake_case for functions".into(),
903            examples: vec!["get_user()".into()],
904            source_session: "s1".into(),
905            created_at: Utc::now(),
906        });
907        let bundle = to_okf_bundle(&snap);
908        let dir = tempfile::tempdir().unwrap();
909        write_okf_bundle(dir.path(), &bundle).unwrap();
910
911        let imp = from_okf_dir(dir.path()).unwrap();
912        assert_eq!(imp.patterns.len(), 1);
913        assert_eq!(imp.patterns[0].pattern_type, "naming");
914        assert_eq!(imp.patterns[0].examples, vec!["get_user()".to_string()]);
915    }
916}