Skip to main content

nenjo_knowledge/
lib.rs

1//! Shared knowledge pack primitives.
2//!
3//! Knowledge packs expose a common metadata/search/read API for
4//! filesystem, or remote document sets.
5
6use std::borrow::Cow;
7use std::collections::BTreeSet;
8use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result};
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12
13pub mod search;
14pub mod tools;
15
16pub use search::{
17    KnowledgeIndexBuildStats, KnowledgeIndexKey, KnowledgeSearchService, KnowledgeSearchStats,
18};
19
20/// Shared read-only metadata contract for any knowledge pack manifest.
21///
22/// This trait intentionally covers only pack identity and document metadata.
23/// Concrete pack manifests, such as project or remote manifests, should expose
24/// their own sync/cache mutation methods on their concrete types.
25pub trait KnowledgePackManifest: Send + Sync {
26    fn pack_id(&self) -> &str;
27    fn version(&self) -> &str;
28    fn schema_version(&self) -> u32;
29    fn root_uri(&self) -> &str;
30    fn content_hash(&self) -> &str;
31    fn docs(&self) -> &[KnowledgeDocManifest];
32
33    fn read_doc_manifest(&self, selector: &str) -> Option<&KnowledgeDocManifest> {
34        self.docs().iter().find(|doc| {
35            doc.id == selector || doc.selector == selector || doc.source_path == selector
36        })
37    }
38}
39
40/// Serializable base manifest used by read-only packs and generic consumers.
41///
42/// Project and remote packs may deserialize into richer concrete types, but
43/// their document entries should still use [`KnowledgeDocManifest`] so agents
44/// and MCP tools see one metadata schema across all pack sources.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct KnowledgePackManifestData {
47    #[serde(alias = "pack_slug")]
48    pub pack_id: String,
49    #[serde(default = "default_knowledge_pack_version")]
50    pub version: String,
51    #[serde(default = "default_knowledge_schema_version")]
52    pub schema_version: u32,
53    #[serde(default)]
54    pub root_uri: String,
55    #[serde(default)]
56    pub content_hash: String,
57    #[serde(default)]
58    pub docs: Vec<KnowledgeDocManifest>,
59}
60
61impl KnowledgePackManifest for KnowledgePackManifestData {
62    fn pack_id(&self) -> &str {
63        &self.pack_id
64    }
65
66    fn version(&self) -> &str {
67        &self.version
68    }
69
70    fn schema_version(&self) -> u32 {
71        self.schema_version
72    }
73
74    fn root_uri(&self) -> &str {
75        &self.root_uri
76    }
77
78    fn content_hash(&self) -> &str {
79        &self.content_hash
80    }
81
82    fn docs(&self) -> &[KnowledgeDocManifest] {
83        &self.docs
84    }
85}
86
87fn default_knowledge_pack_version() -> String {
88    "1".to_string()
89}
90
91fn default_knowledge_schema_version() -> u32 {
92    1
93}
94
95/// Stored metadata for one knowledge document.
96///
97/// Tool responses expose a slimmer projection of this type. `source_path` and
98/// `updated_at` are retained for pack hydration and local sync, not for agent
99/// selection.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct KnowledgeDocManifest {
102    /// Stable document identifier within the pack.
103    pub id: String,
104    /// Agent-visible selector used for lookup and graph traversal.
105    pub selector: String,
106    /// Pack-local file path used to load the document body.
107    pub source_path: String,
108    /// Human-readable title.
109    pub title: String,
110    /// Short summary used for search and selection.
111    pub summary: String,
112    /// Open-ended document category normalized to a slug.
113    pub kind: KnowledgeDocKind,
114    /// Lightweight classification labels.
115    pub tags: Vec<String>,
116    /// Outbound graph edges authored on this document.
117    pub related: Vec<KnowledgeDocEdge>,
118    /// Sync timestamp for local library packs.
119    #[serde(default)]
120    pub updated_at: String,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
124#[serde(rename_all = "snake_case")]
125pub enum KnowledgeDocEdgeType {
126    PartOf,
127    Defines,
128    Governs,
129    Classifies,
130    References,
131    DependsOn,
132    Extends,
133    RelatedTo,
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
137pub struct KnowledgeDocKind(String);
138
139/// Authored outbound edge from one document to another document.
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct KnowledgeDocEdge {
142    #[serde(rename = "type", alias = "edge_type")]
143    pub edge_type: KnowledgeDocEdgeType,
144    /// Target document id or path.
145    pub target: String,
146    /// Optional authoring note. Tool metadata omits this to keep traversal compact.
147    pub description: Option<String>,
148}
149
150#[derive(Debug, Clone, Default, Serialize, Deserialize)]
151pub struct KnowledgeDocFilter {
152    pub tags: Vec<String>,
153    pub kind: Option<KnowledgeDocKind>,
154    pub selector_prefix: Option<String>,
155    pub related_to: Option<String>,
156    pub edge_type: Option<KnowledgeDocEdgeType>,
157}
158
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct KnowledgeDocRead {
161    pub manifest: KnowledgeDocManifest,
162    pub content: String,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize)]
166pub struct KnowledgeDocNeighbor {
167    /// Source document for the neighbor request.
168    pub document: KnowledgeDocManifest,
169    /// Resolved outbound edges from the source document.
170    pub edges: Vec<KnowledgeDocNeighborEdge>,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct KnowledgeDocNeighborEdge {
175    #[serde(rename = "type")]
176    pub edge_type: KnowledgeDocEdgeType,
177    /// Resolved target document metadata.
178    pub target: KnowledgeDocManifest,
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct KnowledgeDocSearchHit {
183    /// Matched document metadata.
184    pub document: KnowledgeDocManifest,
185    /// Simple relevance score derived from metadata matches.
186    pub score: usize,
187    /// Metadata fields that matched the query.
188    pub matched: Vec<String>,
189}
190
191/// Runtime access to a knowledge pack's metadata and lazy document content.
192pub trait KnowledgePack: Send + Sync {
193    fn manifest(&self) -> &dyn KnowledgePackManifest;
194
195    fn doc_content(&self, manifest: &KnowledgeDocManifest) -> Option<Cow<'_, str>>;
196
197    fn list_docs(&self, filter: KnowledgeDocFilter) -> Vec<&KnowledgeDocManifest> {
198        self.manifest()
199            .docs()
200            .iter()
201            .filter(|doc| matches_filter(self, doc, &filter))
202            .collect()
203    }
204
205    fn read_manifest(&self, path: &str) -> Option<&KnowledgeDocManifest> {
206        self.manifest().read_doc_manifest(path)
207    }
208
209    fn read_doc(&self, path: &str) -> Option<KnowledgeDocRead> {
210        let manifest = self.read_manifest(path)?.clone();
211        let content = self.doc_content(&manifest)?.into_owned();
212        Some(KnowledgeDocRead { manifest, content })
213    }
214
215    fn search(&self, query: &str, filter: KnowledgeDocFilter) -> Vec<KnowledgeDocSearchHit> {
216        search_pack(self, query, filter)
217    }
218
219    fn neighbors(
220        &self,
221        path: &str,
222        edge_type: Option<KnowledgeDocEdgeType>,
223    ) -> Option<KnowledgeDocNeighbor> {
224        let source = self.read_manifest(path)?;
225
226        let mut edges = Vec::new();
227
228        for edge in &source.related {
229            if let Some(expected) = edge_type
230                && edge.edge_type != expected
231            {
232                continue;
233            }
234            if let Some(target) = self.read_manifest(&edge.target) {
235                edges.push(KnowledgeDocNeighborEdge {
236                    edge_type: edge.edge_type,
237                    target: target.clone(),
238                });
239            }
240        }
241
242        edges.sort_by(|left, right| {
243            left.target
244                .selector
245                .cmp(&right.target.selector)
246                .then_with(|| left.edge_type.as_str().cmp(right.edge_type.as_str()))
247        });
248        edges.dedup_by(|left, right| {
249            left.edge_type == right.edge_type && left.target.selector == right.target.selector
250        });
251
252        Some(KnowledgeDocNeighbor {
253            document: source.clone(),
254            edges,
255        })
256    }
257}
258
259/// Filesystem-backed package knowledge pack loaded from an installed package
260/// knowledge manifest.
261#[derive(Debug, Clone)]
262pub struct PackageKnowledgePack {
263    content_root: PathBuf,
264    selector: Option<String>,
265    manifest: KnowledgePackManifestData,
266}
267
268impl PackageKnowledgePack {
269    pub fn load(path: &Path, package_version: &str) -> Result<Self> {
270        let content = std::fs::read_to_string(path)
271            .with_context(|| format!("failed to read knowledge manifest {}", path.display()))?;
272        let file: PackageKnowledgeManifestFile =
273            serde_yaml::from_str(&content).context("invalid package knowledge manifest")?;
274        let root_uri = file
275            .manifest
276            .root_uri
277            .or(file.root_uri)
278            .unwrap_or_else(|| format!("pkg://{}/", file.manifest.pack_id));
279        let pack_id = file.manifest.pack_id;
280        let docs = file
281            .manifest
282            .docs
283            .into_iter()
284            .map(|doc| doc.into_manifest(&pack_id))
285            .collect();
286        Ok(Self {
287            content_root: path.parent().unwrap_or_else(|| Path::new("")).to_path_buf(),
288            selector: file.manifest.selector.or(file.selector),
289            manifest: KnowledgePackManifestData {
290                pack_id,
291                version: file
292                    .manifest
293                    .version
294                    .unwrap_or_else(|| package_version.to_string()),
295                schema_version: file.manifest.schema_version.unwrap_or(1),
296                root_uri,
297                content_hash: file.manifest.content_hash.unwrap_or_default(),
298                docs,
299            },
300        })
301    }
302
303    pub fn selector(&self) -> Option<&str> {
304        self.selector.as_deref()
305    }
306}
307
308impl KnowledgePack for PackageKnowledgePack {
309    fn manifest(&self) -> &dyn KnowledgePackManifest {
310        &self.manifest
311    }
312
313    fn doc_content(&self, manifest: &KnowledgeDocManifest) -> Option<Cow<'_, str>> {
314        let content =
315            std::fs::read_to_string(self.content_root.join(&manifest.source_path)).ok()?;
316        Some(Cow::Owned(content))
317    }
318}
319
320/// Filesystem-backed knowledge pack loaded from a local cache directory.
321///
322/// The manifest is loaded eagerly, while document bodies are read lazily from
323/// `source_path` when a tool asks for a document.
324#[derive(Debug, Clone)]
325pub struct FilesystemKnowledgePack {
326    content_root: PathBuf,
327    manifest: KnowledgePackManifestData,
328}
329
330impl FilesystemKnowledgePack {
331    pub const MANIFEST_FILENAME: &'static str = "manifest.json";
332
333    pub fn load(root: &Path) -> Option<Self> {
334        let manifest_path = root.join(Self::MANIFEST_FILENAME);
335        let content = std::fs::read_to_string(&manifest_path).ok()?;
336        let mut manifest: KnowledgePackManifestData = serde_json::from_str(&content).ok()?;
337        if manifest.root_uri.trim().is_empty() {
338            manifest.root_uri = format!("file://{}/", root.display());
339        }
340        Some(Self {
341            content_root: root.to_path_buf(),
342            manifest,
343        })
344    }
345
346    fn doc_path(&self, source_path: &str) -> Option<PathBuf> {
347        let relative = Path::new(source_path);
348        if relative.is_absolute()
349            || relative
350                .components()
351                .any(|component| !matches!(component, std::path::Component::Normal(_)))
352        {
353            return None;
354        }
355        Some(self.content_root.join(relative))
356    }
357}
358
359impl KnowledgePack for FilesystemKnowledgePack {
360    fn manifest(&self) -> &dyn KnowledgePackManifest {
361        &self.manifest
362    }
363
364    fn doc_content(&self, manifest: &KnowledgeDocManifest) -> Option<Cow<'_, str>> {
365        let content = std::fs::read_to_string(self.doc_path(&manifest.source_path)?).ok()?;
366        Some(Cow::Owned(content))
367    }
368}
369
370#[derive(Debug, Deserialize)]
371struct PackageKnowledgeManifestFile {
372    selector: Option<String>,
373    root_uri: Option<String>,
374    manifest: PackageKnowledgeManifestBody,
375}
376
377#[derive(Debug, Deserialize)]
378struct PackageKnowledgeManifestBody {
379    pack_id: String,
380    selector: Option<String>,
381    version: Option<String>,
382    schema_version: Option<u32>,
383    root_uri: Option<String>,
384    content_hash: Option<String>,
385    #[serde(default)]
386    docs: Vec<PackageKnowledgeDoc>,
387}
388
389#[derive(Debug, Deserialize)]
390struct PackageKnowledgeDoc {
391    id: Option<String>,
392    selector: Option<String>,
393    source_path: String,
394    title: String,
395    summary: String,
396    #[serde(default)]
397    kind: KnowledgeDocKind,
398    #[serde(default)]
399    tags: Vec<String>,
400    #[serde(default)]
401    related: Vec<KnowledgeDocEdge>,
402    #[serde(default)]
403    updated_at: String,
404}
405
406impl PackageKnowledgeDoc {
407    fn into_manifest(self, pack_id: &str) -> KnowledgeDocManifest {
408        let id_hint = self.id.as_deref().unwrap_or_default();
409        let selector = self
410            .selector
411            .unwrap_or_else(|| selector_from_source_path(&self.source_path, pack_id, id_hint));
412        let id = self.id.unwrap_or_else(|| format!("{pack_id}.{selector}"));
413        KnowledgeDocManifest {
414            id,
415            selector,
416            source_path: self.source_path,
417            title: self.title,
418            summary: self.summary,
419            kind: self.kind,
420            tags: self.tags,
421            related: self.related,
422            updated_at: self.updated_at,
423        }
424    }
425}
426
427fn selector_from_source_path(source_path: &str, pack_id: &str, id: &str) -> String {
428    let trimmed = source_path.strip_prefix("docs/").unwrap_or(source_path);
429    let trimmed = trimmed.strip_suffix(".md").unwrap_or(trimmed);
430    let selector = trimmed.replace('/', ".");
431    if selector.is_empty() {
432        id.strip_prefix(&format!("{pack_id}."))
433            .unwrap_or(id)
434            .to_string()
435    } else {
436        selector
437    }
438}
439
440impl KnowledgeDocEdgeType {
441    pub fn as_str(self) -> &'static str {
442        match self {
443            KnowledgeDocEdgeType::PartOf => "part_of",
444            KnowledgeDocEdgeType::Defines => "defines",
445            KnowledgeDocEdgeType::Governs => "governs",
446            KnowledgeDocEdgeType::Classifies => "classifies",
447            KnowledgeDocEdgeType::References => "references",
448            KnowledgeDocEdgeType::DependsOn => "depends_on",
449            KnowledgeDocEdgeType::Extends => "extends",
450            KnowledgeDocEdgeType::RelatedTo => "related_to",
451        }
452    }
453}
454
455impl KnowledgeDocKind {
456    pub fn new(value: impl AsRef<str>) -> Self {
457        let value = value.as_ref().trim().to_ascii_lowercase();
458        let mut slug = String::new();
459        let mut last_was_separator = false;
460        for ch in value.chars() {
461            if ch.is_ascii_alphanumeric() {
462                slug.push(ch);
463                last_was_separator = false;
464            } else if !last_was_separator {
465                slug.push('_');
466                last_was_separator = true;
467            }
468        }
469        let slug = slug.trim_matches('_');
470        if slug.is_empty() {
471            Self("reference".to_string())
472        } else {
473            Self(slug.to_string())
474        }
475    }
476
477    pub fn as_str(&self) -> &str {
478        &self.0
479    }
480}
481
482impl Default for KnowledgeDocKind {
483    fn default() -> Self {
484        Self::new("reference")
485    }
486}
487
488impl From<&str> for KnowledgeDocKind {
489    fn from(value: &str) -> Self {
490        Self::new(value)
491    }
492}
493
494impl From<String> for KnowledgeDocKind {
495    fn from(value: String) -> Self {
496        Self::new(value)
497    }
498}
499
500impl Serialize for KnowledgeDocKind {
501    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
502    where
503        S: Serializer,
504    {
505        serializer.serialize_str(self.as_str())
506    }
507}
508
509impl<'de> Deserialize<'de> for KnowledgeDocKind {
510    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
511    where
512        D: Deserializer<'de>,
513    {
514        String::deserialize(deserializer).map(Self::new)
515    }
516}
517
518pub(crate) fn search_pack<P: KnowledgePack + ?Sized>(
519    pack: &P,
520    query: &str,
521    filter: KnowledgeDocFilter,
522) -> Vec<KnowledgeDocSearchHit> {
523    let needle = normalize(query);
524    let mut hits = Vec::new();
525
526    for manifest in pack.list_docs(filter) {
527        let mut score = 0;
528        let mut matched = BTreeSet::new();
529
530        score += score_field(&needle, &manifest.id, 100, "id", &mut matched);
531        score += score_field(&needle, &manifest.selector, 90, "selector", &mut matched);
532        score += score_field(&needle, &manifest.title, 80, "title", &mut matched);
533        score += score_field(&needle, &manifest.summary, 60, "summary", &mut matched);
534
535        for tag in &manifest.tags {
536            score += score_field(&needle, tag, 70, "tag", &mut matched);
537        }
538
539        if score > 0 || needle.is_empty() {
540            hits.push(KnowledgeDocSearchHit {
541                document: manifest.clone(),
542                score,
543                matched: matched.into_iter().collect(),
544            });
545        }
546    }
547
548    hits.sort_by(|a, b| {
549        b.score
550            .cmp(&a.score)
551            .then_with(|| a.document.selector.cmp(&b.document.selector))
552    });
553    hits
554}
555
556pub(crate) fn matches_filter<P: KnowledgePack + ?Sized>(
557    pack: &P,
558    doc: &KnowledgeDocManifest,
559    filter: &KnowledgeDocFilter,
560) -> bool {
561    if let Some(kind) = &filter.kind
562        && doc.kind != *kind
563    {
564        return false;
565    }
566    if let Some(prefix) = &filter.selector_prefix
567        && !doc.selector.starts_with(prefix)
568    {
569        return false;
570    }
571    if !filter.tags.is_empty()
572        && !filter
573            .tags
574            .iter()
575            .all(|tag| doc.tags.iter().any(|doc_tag| doc_tag == tag))
576    {
577        return false;
578    }
579    if let Some(target) = &filter.related_to {
580        let has_edge = doc.related.iter().any(|edge| {
581            let edge_matches_target = edge.target == *target
582                || pack
583                    .read_manifest(&edge.target)
584                    .map(|edge_target| edge_target.id == *target || edge_target.selector == *target)
585                    .unwrap_or(false);
586            edge_matches_target
587                && filter
588                    .edge_type
589                    .as_ref()
590                    .map(|expected| edge.edge_type == *expected)
591                    .unwrap_or(true)
592        });
593        if !has_edge {
594            return false;
595        }
596    }
597    true
598}
599
600fn score_field(
601    needle: &str,
602    haystack: &str,
603    weight: usize,
604    label: &str,
605    matched: &mut BTreeSet<String>,
606) -> usize {
607    if needle.is_empty() {
608        return 1;
609    }
610    let haystack = normalize(haystack);
611    if haystack == needle {
612        matched.insert(label.to_string());
613        weight * 2
614    } else if haystack.contains(needle) {
615        matched.insert(label.to_string());
616        weight
617    } else {
618        0
619    }
620}
621
622fn normalize(value: &str) -> String {
623    value.trim().to_lowercase()
624}
625
626#[cfg(test)]
627mod tests {
628    use super::*;
629    use std::time::{SystemTime, UNIX_EPOCH};
630
631    #[test]
632    fn package_knowledge_manifest_accepts_selector_without_doc_id() {
633        let unique = SystemTime::now()
634            .duration_since(UNIX_EPOCH)
635            .unwrap()
636            .as_nanos();
637        let dir = std::env::temp_dir().join(format!(
638            "nenjo-knowledge-package-manifest-{pid}-{unique}",
639            pid = std::process::id()
640        ));
641        let docs_dir = dir.join("docs/domain");
642        std::fs::create_dir_all(&docs_dir).unwrap();
643        std::fs::write(
644            dir.join("manifest.yaml"),
645            r#"
646schema: nenjo.knowledge.v1
647manifest:
648  pack_id: nenjo.core
649  selector: pkg:nenjo-ai.packages.knowledge.core
650  version: 0.1.0
651  docs:
652    - selector: domain.nenjo
653      source_path: docs/domain/nenjo.md
654      title: Nenjo
655      summary: Platform overview.
656      kind: domain
657      tags: [domain:nenjo]
658      related: []
659"#,
660        )
661        .unwrap();
662        std::fs::write(docs_dir.join("nenjo.md"), "# Nenjo\n\nKnowledge content.").unwrap();
663
664        let pack = PackageKnowledgePack::load(&dir.join("manifest.yaml"), "0.1.0").unwrap();
665        let doc = pack.read_doc("domain.nenjo").unwrap();
666
667        assert_eq!(doc.manifest.selector, "domain.nenjo");
668        assert_eq!(doc.manifest.id, "nenjo.core.domain.nenjo");
669        assert!(doc.content.contains("Knowledge content"));
670        assert_eq!(
671            pack.selector(),
672            Some("pkg:nenjo-ai.packages.knowledge.core")
673        );
674        let knowledge_ref = pack.selector().unwrap().parse().unwrap();
675        let vars = crate::tools::knowledge_pack_prompt_vars(&knowledge_ref, &pack);
676        assert!(vars.contains_key("pkg.nenjo_ai.packages.knowledge.core.domain.nenjo"));
677
678        std::fs::remove_dir_all(dir).unwrap();
679    }
680}