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