kyyn-core 0.1.13

Core vocabulary for kyyn: registry, links, query AST, plugin and validation contracts for typed, git-backed knowledge bases.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Registry-driven generic validation — everything a schema DECLARES, the
//! engine can CHECK without the schema crate hand-writing it:
//!
//! - routing + parse: storage patterns say where records live; typed decode
//!   (dates, decimals, enums, links) says whether one reads back (Error).
//! - placeholder consistency: a field named like a storage placeholder must
//!   match its path segment — `id` vs filename, `person` vs directory (Error).
//! - link policy: `Link { allowed }` fields reject other kinds (Error);
//!   KB-native links that do not resolve warn; declared external systems
//!   pass; unrecognized heads warn. Enum-payload links included.
//! - `refers_to`: a plain-string slug must name a known record (Warning).
//! - inline `[[…]]` links in every Markdown field resolve or warn.
//!
//! A schema crate calls [`against_registry`] and appends only its own
//! cross-record invariants — the registry IS the declarative source; this
//! module is its interpreter. Severity doctrine: malformed shape and policy
//! breaches block an accept (Error); unresolvable references warn.

use std::collections::{HashMap, HashSet};

use crate::link::Link;
use crate::registry::{Field, FieldType, Kind, Registry};
use crate::storage::{match_storage, route};
use crate::value::{Value, decode};
use crate::violation::{Severity, Violation};

/// Validate every entry a registry can judge. `entries` are (repo-relative
/// path, RON text) pairs; paths outside `facts/` are ignored.
pub fn against_registry(
    registry: &Registry,
    entries: &[(String, String)],
    systems: &[&str],
) -> Vec<Violation> {
    let mut out = Vec::new();
    let id_kinds: Vec<&str> = registry
        .kinds
        .iter()
        .filter(|k| k.storage.contains('{'))
        .map(|k| k.name.as_str())
        .collect();
    let singleton_kinds: Vec<&str> = registry
        .kinds
        .iter()
        .filter(|k| !k.storage.contains('{'))
        .map(|k| k.name.as_str())
        .collect();

    // Pass 1: route and decode. A facts/ path no pattern claims is an Error;
    // so is a record that fails its kind's typed decode (malformed dates and
    // decimals fail HERE — shape is parse, not a later step).
    struct Parsed<'r> {
        path: String,
        kind: &'r Kind,
        id: Option<String>,
        value: std::collections::BTreeMap<String, Value>,
    }
    let mut parsed: Vec<Parsed> = Vec::new();
    for (path, text) in entries {
        if !path.starts_with("facts/") {
            continue;
        }
        match route(registry, path) {
            None => out.push(Violation {
                path: path.clone(),
                severity: Severity::Error,
                message: format!(
                    "not a recognised KB path for this schema (expected one of: {})",
                    registry
                        .kinds
                        .iter()
                        .map(|k| k.storage.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
            }),
            Some((kind, id)) => match decode(kind, text) {
                Err(e) => out.push(Violation {
                    path: path.clone(),
                    severity: Severity::Error,
                    message: format!("does not parse as a {}: {e}", kind.name),
                }),
                Ok(value) => parsed.push(Parsed {
                    path: path.clone(),
                    kind,
                    id,
                    value,
                }),
            },
        }
    }

    // The id universes links resolve against — route-derived, so they are
    // exactly the ids other records can address.
    let mut universe = Universe {
        ids: id_kinds
            .iter()
            .map(|k| (k.to_string(), HashSet::new()))
            .collect(),
        singletons_present: HashSet::new(),
    };
    for p in &parsed {
        match &p.id {
            Some(id) => {
                universe
                    .ids
                    .get_mut(p.kind.name.as_str())
                    .expect("seeded")
                    .insert(id.clone());
            }
            None => {
                universe.singletons_present.insert(p.kind.name.clone());
            }
        }
    }

    // Pass 2: per-record invariants, walked from the declared field types.
    for p in &parsed {
        let mut check = Checker {
            path: &p.path,
            universe: &universe,
            systems,
            id_kinds: &id_kinds,
            singleton_kinds: &singleton_kinds,
            out: &mut out,
        };
        // Placeholder consistency: each `{name}` binds a path segment; a
        // record field of the same name must agree with it.
        if let Some(id) = &p.id
            && let Some(bindings) = match_storage(&p.kind.storage, &p.path)
        {
            let names = placeholder_names(&p.kind.storage);
            let n = names.len();
            for (i, (name, segment)) in names
                .iter()
                .zip(&bindings)
                .collect::<Vec<_>>()
                .into_iter()
                .enumerate()
            {
                let Some(v) = p.value.get(name.as_str()) else {
                    continue;
                };
                let rendered = match v {
                    Value::Str(s) => s.clone(),
                    Value::Date(d) => d.to_string(),
                    _ => continue,
                };
                if &rendered != segment {
                    let position = if i + 1 == n { "filename" } else { "directory" };
                    check.error(format!(
                        "{name} '{rendered}' does not match {position} '{segment}'"
                    ));
                }
            }
            let _ = id;
        }
        for field in &p.kind.fields {
            if let Some(v) = p.value.get(&field.name) {
                check.walk(&field.name, &field.ty, v, field.refers_to.as_deref());
            }
        }
    }
    out
}

/// The names of a storage pattern's placeholders, in path order.
fn placeholder_names(pattern: &str) -> Vec<String> {
    pattern
        .split('/')
        .filter_map(|seg| {
            let open = seg.find('{')?;
            let close = seg.find('}')?;
            (open < close).then(|| seg[open + 1..close].to_string())
        })
        .collect()
}

/// The id universes KB links resolve against.
struct Universe {
    ids: HashMap<String, HashSet<String>>,
    singletons_present: HashSet<String>,
}

impl Universe {
    /// If `link` is KB-native and does not resolve, say why (a Warning).
    /// External links (a declared system) are not locally resolvable.
    fn unresolved(&self, link: &Link, systems: &[&str]) -> Option<String> {
        let p = link.parts(systems);
        if p.is_external() {
            return None;
        }
        if let Some(set) = self.ids.get(p.kind) {
            return match p.id {
                Some(id) if set.contains(id) => None,
                Some(_) => Some(format!(
                    "link '{link}' does not resolve to a known {}",
                    p.kind
                )),
                None => Some(format!(
                    "link '{link}' names kind '{}' without an id",
                    p.kind
                )),
            };
        }
        Some(format!("unrecognized link '{link}'"))
    }

    fn unresolved_singleton(&self, link: &Link, kind: &str, id: Option<&str>) -> Option<String> {
        match id {
            None if self.singletons_present.contains(kind) => None,
            None => Some(format!(
                "link '{link}' does not resolve: no {kind} record present"
            )),
            Some(_) => Some(format!("singleton kind '{kind}' takes no id")),
        }
    }
}

/// Per-file check helper carrying the path, universe and declared systems.
struct Checker<'a> {
    path: &'a str,
    universe: &'a Universe,
    systems: &'a [&'a str],
    id_kinds: &'a [&'a str],
    singleton_kinds: &'a [&'a str],
    out: &'a mut Vec<Violation>,
}

impl Checker<'_> {
    fn push(&mut self, severity: Severity, message: String) {
        self.out.push(Violation {
            path: self.path.to_string(),
            severity,
            message,
        });
    }

    fn error(&mut self, message: String) {
        self.push(Severity::Error, message);
    }

    fn warn(&mut self, message: String) {
        self.push(Severity::Warning, message);
    }

    /// Resolution with singleton awareness — the one seam Universe splits on.
    fn resolve(&mut self, prefix: &str, link: &Link) {
        let p = link.parts(self.systems);
        let msg = if self.singleton_kinds.contains(&p.kind) && !p.is_external() {
            self.universe.unresolved_singleton(link, p.kind, p.id)
        } else {
            self.universe.unresolved(link, self.systems)
        };
        if let Some(msg) = msg {
            self.warn(format!("{prefix}{msg}"));
        }
    }

    /// The uniform link policy: a disallowed kind is an Error; an
    /// unresolvable / unrecognized link is a Warning.
    fn link(&mut self, field: &str, link: &Link, allowed: Option<&[String]>) {
        let p = link.parts(self.systems);
        if let Some(kinds) = allowed {
            // Policy matches the namespace (system for external links, kind
            // for native ones). An *unrecognized* head isn't a kind violation
            // — it's an unknown, warned below.
            if p.recognized(self.id_kinds, self.singleton_kinds)
                && !kinds.iter().any(|k| k == p.namespace())
            {
                self.error(format!(
                    "{field} '{link}' has kind '{}' (allowed: {})",
                    p.namespace(),
                    kinds.join(", ")
                ));
                return;
            }
        }
        self.resolve(&format!("{field}: "), link);
    }

    /// Inline `[[…]]` links in prose: an unresolvable KB-kind link is a
    /// Warning. Bracketed text whose head is no known kind is left alone —
    /// prose is prose.
    fn inline(&mut self, text: &str) {
        for l in Link::find_inline(text) {
            let p = l.parts(self.systems);
            if !p.recognized(self.id_kinds, self.singleton_kinds) {
                continue;
            }
            self.resolve("inline ", &l);
        }
    }

    /// Walk a decoded value with its declared type, checking every link,
    /// prose store and refers_to slug — enum payloads and nested structs
    /// included, so a Link is checked wherever the schema can put one.
    fn walk(&mut self, field: &str, ty: &FieldType, v: &Value, refers_to: Option<&str>) {
        match (ty, v) {
            (FieldType::Link { allowed }, Value::Link(l)) => {
                self.link(field, l, allowed.as_deref());
            }
            (FieldType::Markdown, Value::Str(s)) => self.inline(s),
            (FieldType::Str, Value::Str(s)) => {
                if let Some(target) = refers_to
                    && let Some(set) = self.universe.ids.get(target)
                    && !set.contains(s)
                {
                    self.warn(format!("{field} '{s}' is not a known {target}"));
                }
            }
            (FieldType::Option(inner), v) if !matches!(v, Value::Null) => {
                self.walk(field, inner, v, refers_to);
            }
            (FieldType::List(inner), Value::List(vs)) => {
                for v in vs {
                    self.walk(field, inner, v, refers_to);
                }
            }
            (FieldType::Struct(fields), Value::Struct(map)) => {
                self.walk_fields(fields, map);
            }
            (FieldType::Enum(variants), Value::Enum { variant, fields }) => {
                if let Some(decl) = variants.iter().find(|d| &d.name == variant) {
                    self.walk_fields(&decl.fields, fields);
                }
            }
            _ => {}
        }
    }

    fn walk_fields(&mut self, decls: &[Field], values: &std::collections::BTreeMap<String, Value>) {
        for f in decls {
            if let Some(v) = values.get(&f.name) {
                self.walk(&f.name, &f.ty, v, f.refers_to.as_deref());
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::Variant;

    fn field(name: &str, ty: FieldType) -> Field {
        Field {
            name: name.into(),
            doc: String::new(),
            ty,
            role: None,
            refers_to: None,
        }
    }

    fn unit(name: &str) -> Variant {
        Variant {
            name: name.into(),
            doc: String::new(),
            fields: Vec::new(),
            tone: None,
        }
    }

    /// A todo/charter/self-shaped registry, built by hand: validation is
    /// registry-driven, so the fixture is a registry, not a schema crate.
    fn reg() -> Registry {
        Registry {
            schema_hash: String::new(),
            kinds: vec![
                Kind {
                    name: "todo".into(),
                    doc: String::new(),
                    storage: "facts/todos/{id}.ron".into(),
                    fields: vec![
                        field("id", FieldType::Str),
                        field("title", FieldType::Str),
                        field("status", FieldType::Enum(vec![unit("Open"), unit("Done")])),
                        field("due", FieldType::Option(Box::new(FieldType::Date))),
                        field(
                            "blocked_by",
                            FieldType::Option(Box::new(FieldType::Link {
                                allowed: Some(vec!["todo".into()]),
                            })),
                        ),
                        field(
                            "sources",
                            FieldType::List(Box::new(FieldType::Link { allowed: None })),
                        ),
                        field("notes", FieldType::Markdown),
                    ],
                },
                Kind {
                    name: "charter".into(),
                    doc: String::new(),
                    storage: "facts/charter.ron".into(),
                    fields: vec![
                        field("purpose", FieldType::Str),
                        field("objectives", FieldType::List(Box::new(FieldType::Markdown))),
                        field("notes", FieldType::Markdown),
                    ],
                },
                Kind {
                    name: "self".into(),
                    doc: String::new(),
                    storage: "facts/self.ron".into(),
                    fields: vec![
                        field("name", FieldType::Str),
                        field("role", FieldType::Str),
                        field("notes", FieldType::Markdown),
                    ],
                },
            ],
            queries: vec![],
            roles: vec![],
        }
    }

    const SYSTEMS: &[&str] = &["graph", "sharepoint"];

    fn v(entries: &[(&str, &str)]) -> Vec<Violation> {
        let entries: Vec<(String, String)> = entries
            .iter()
            .map(|(p, t)| (p.to_string(), t.to_string()))
            .collect();
        against_registry(&reg(), &entries, SYSTEMS)
    }

    fn errors(v: &[Violation]) -> Vec<&Violation> {
        v.iter().filter(|x| x.severity == Severity::Error).collect()
    }

    fn warnings(v: &[Violation]) -> Vec<&Violation> {
        v.iter()
            .filter(|x| x.severity == Severity::Warning)
            .collect()
    }

    #[test]
    fn happy_path_is_clean() {
        let out = v(&[
            (
                "facts/todos/declare-source.ron",
                r#"(id: "declare-source", title: "Declare", status: Open)"#,
            ),
            (
                "facts/todos/ship-it.ron",
                r#"(id: "ship-it", title: "Ship", status: Open, due: Some("2026-07-31"),
                    blocked_by: Some("todo:declare-source"),
                    sources: ["graph:email:AAMk=="],
                    notes: "see [[charter]] and [[todo:declare-source]]")"#,
            ),
            ("facts/charter.ron", r#"(purpose: "P", objectives: ["o"])"#),
            ("facts/self.ron", r#"(name: "Tom", role: "CTO")"#),
        ]);
        assert!(out.is_empty(), "{out:?}");
    }

    #[test]
    fn routing_parse_and_placeholder_mismatches_are_errors() {
        let out = v(&[
            ("facts/notes/x.ron", "(id: \"x\")"),
            ("facts/todos/readme.txt", "hi"),
            ("facts/todos/broken.ron", "(id: "),
            ("facts/todos/ship-it.ron", r#"(id: "ship", title: "T")"#),
            (
                "facts/todos/bad-date.ron",
                r#"(id: "bad-date", title: "T", due: Some("someday"))"#,
            ),
            ("tools/elsewhere.txt", "ignored"),
        ]);
        let e = errors(&out);
        assert_eq!(e.len(), 5, "{out:?}");
        assert!(
            e.iter()
                .any(|x| x.message.contains("not a recognised KB path")
                    && x.message.contains("facts/todos/{id}.ron"))
        );
        assert!(
            e.iter().any(
                |x| x.path.contains("broken") && x.message.contains("does not parse as a todo")
            )
        );
        assert!(e.iter().any(|x| {
            x.message
                .contains("id 'ship' does not match filename 'ship-it'")
        }));
        assert!(
            e.iter()
                .any(|x| x.path.contains("bad-date") && x.message.contains("does not parse"))
        );
    }

    #[test]
    fn multi_segment_placeholders_check_each_position() {
        let mut registry = reg();
        registry.kinds.push(Kind {
            name: "checkin".into(),
            doc: String::new(),
            storage: "facts/checkins/{person}/{date}.ron".into(),
            fields: vec![
                field("person", FieldType::Str),
                field("date", FieldType::Date),
            ],
        });
        let entries = vec![(
            "facts/checkins/jane-doe/2026-07-03.ron".to_string(),
            r#"(person: "bob-ray", date: "2026-07-04")"#.to_string(),
        )];
        let out = against_registry(&registry, &entries, SYSTEMS);
        let e = errors(&out);
        assert!(e.iter().any(|x| {
            x.message
                .contains("person 'bob-ray' does not match directory 'jane-doe'")
        }));
        assert!(e.iter().any(|x| {
            x.message
                .contains("date '2026-07-04' does not match filename '2026-07-03'")
        }));
    }

    #[test]
    fn link_policy_rejects_disallowed_kinds() {
        let out = v(&[
            (
                "facts/todos/b.ron",
                r#"(id: "b", title: "B", blocked_by: Some("charter"))"#,
            ),
            ("facts/charter.ron", r#"(purpose: "P")"#),
        ]);
        let e = errors(&out);
        assert_eq!(e.len(), 1, "{out:?}");
        assert!(e[0].message.contains("blocked_by") && e[0].message.contains("kind 'charter'"));
    }

    #[test]
    fn dangling_and_unrecognized_links_warn_externals_pass() {
        let out = v(&[(
            "facts/todos/b.ron",
            r#"(id: "b", title: "B", blocked_by: Some("todo:ghost"),
                sources: ["jira:EV-12", "graph:email:fine=="])"#,
        )]);
        assert!(errors(&out).is_empty(), "{out:?}");
        let w = warnings(&out);
        assert_eq!(w.len(), 2, "{w:?}");
        assert!(
            w.iter()
                .any(|x| x.message.contains("does not resolve to a known todo"))
        );
        assert!(
            w.iter()
                .any(|x| x.message.contains("unrecognized link 'jira:EV-12'"))
        );
    }

    #[test]
    fn singletons_resolve_iff_present_and_take_no_id() {
        let todo = (
            "facts/todos/b.ron",
            r#"(id: "b", title: "B", notes: "per [[charter]] and [[charter:2026]]")"#,
        );
        let out = v(&[todo, ("facts/charter.ron", r#"(purpose: "P")"#)]);
        assert!(errors(&out).is_empty());
        let w = warnings(&out);
        assert_eq!(w.len(), 1, "{w:?}");
        assert!(
            w[0].message
                .contains("singleton kind 'charter' takes no id")
        );

        let out = v(&[todo]);
        assert!(
            warnings(&out)
                .iter()
                .any(|x| x.message.contains("no charter record present"))
        );
    }

    #[test]
    fn inline_links_are_scanned_in_every_markdown_store() {
        let out = v(&[
            (
                "facts/todos/b.ron",
                r#"(id: "b", title: "B", notes: "see [[todo:ghost1]]; [[not a link]] is prose")"#,
            ),
            (
                "facts/charter.ron",
                r#"(purpose: "P", objectives: ["see [[todo:ghost2]]"], notes: "see [[todo:ghost3]]")"#,
            ),
            (
                "facts/self.ron",
                r#"(name: "T", role: "R", notes: "see [[todo:ghost4]]")"#,
            ),
        ]);
        assert!(errors(&out).is_empty());
        let inline: Vec<_> = warnings(&out)
            .into_iter()
            .filter(|x| x.message.starts_with("inline"))
            .collect();
        assert_eq!(inline.len(), 4, "{out:?}");
    }

    #[test]
    fn refers_to_slugs_warn_when_unknown() {
        let mut registry = reg();
        let mut person_field = field("person", FieldType::Str);
        person_field.refers_to = Some("todo".into());
        registry.kinds.push(Kind {
            name: "checkin".into(),
            doc: String::new(),
            storage: "facts/checkins/{person}/{date}.ron".into(),
            fields: vec![person_field, field("date", FieldType::Date)],
        });
        let entries = vec![(
            "facts/checkins/ghost/2026-07-01.ron".to_string(),
            r#"(person: "ghost", date: "2026-07-01")"#.to_string(),
        )];
        let out = against_registry(&registry, &entries, SYSTEMS);
        assert!(errors(&out).is_empty(), "{out:?}");
        assert!(
            warnings(&out)
                .iter()
                .any(|x| x.message.contains("person 'ghost' is not a known todo"))
        );
    }

    /// SOL finding 18's generic descendant: a Link inside an enum VARIANT
    /// payload gets the same policy and resolution as a top-level field.
    #[test]
    fn enum_payload_links_are_checked() {
        let mut registry = reg();
        registry.kinds.push(Kind {
            name: "probe".into(),
            doc: String::new(),
            storage: "facts/probes/{id}.ron".into(),
            fields: vec![
                field("id", FieldType::Str),
                Field {
                    name: "client".into(),
                    doc: String::new(),
                    ty: FieldType::Enum(vec![
                        unit("Unknown"),
                        Variant {
                            name: "Known".into(),
                            doc: String::new(),
                            fields: vec![field(
                                "todo",
                                FieldType::Link {
                                    allowed: Some(vec!["todo".into()]),
                                },
                            )],
                            tone: None,
                        },
                    ]),
                    role: None,
                    refers_to: None,
                },
            ],
        });
        let entries = vec![(
            "facts/probes/p1.ron".to_string(),
            r#"(id: "p1", client: Known(todo: "charter"))"#.to_string(),
        )];
        let out = against_registry(&registry, &entries, SYSTEMS);
        assert!(
            errors(&out)
                .iter()
                .any(|x| x.message.contains("todo") && x.message.contains("kind 'charter'")),
            "{out:?}"
        );
    }
}