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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! Registry-driven typed decoding — the engine's `Value` layer.
//!
//! `ron::Value` cannot represent enum variants (a bare `Weekly` degrades to
//! `Unit`), so the engine decodes records with *seeded* deserialization
//! instead: the registry's `FieldType` drives which serde entry point each
//! field goes through, and `deserialize_enum` + `deserialize_identifier`
//! recover variant names — payload variants included. What the schema crate
//! gets from Rust's derive, the engine gets from the registry.

use std::collections::BTreeMap;
use std::fmt;

use crate::link::Link;
use crate::registry::{Field, FieldType, Kind};
use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::de::{self, DeserializeSeed, Deserializer, EnumAccess, VariantAccess, Visitor};

/// A decoded field value, shaped by the registry.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// An explicit `None`.
    Null,
    /// `Str` and `Markdown` fields both land here; the registry knows which.
    Str(String),
    Date(NaiveDate),
    Bool(bool),
    Int(i64),
    /// EXACT decimal — travels as a string on the wire ("1250000.00").
    Decimal(Decimal),
    /// An external web link: `(title: "…", url: "https://…")`.
    Hyperlink {
        title: String,
        url: String,
    },
    Link(Link),
    Enum {
        variant: String,
        fields: BTreeMap<String, Value>,
    },
    List(Vec<Value>),
    Struct(BTreeMap<String, Value>),
}

impl Value {
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::Str(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_link(&self) -> Option<&Link> {
        match self {
            Value::Link(l) => Some(l),
            _ => None,
        }
    }

    pub fn variant(&self) -> Option<&str> {
        match self {
            Value::Enum { variant, .. } => Some(variant),
            _ => None,
        }
    }
}

/// Decode one record's RON text against its kind. Unknown fields are skipped
/// (the validator judges correctness; this is a reader). A field that fails
/// its declared shape is an error — the caller records the file as unreadable.
pub fn decode(kind: &Kind, text: &str) -> Result<BTreeMap<String, Value>, String> {
    let mut d = ron::Deserializer::from_str(text).map_err(|e| e.to_string())?;
    RecordSeed {
        fields: &kind.fields,
    }
    .deserialize(&mut d)
    .map_err(|e| e.to_string())
}

struct RecordSeed<'r> {
    fields: &'r [Field],
}

impl<'de> DeserializeSeed<'de> for RecordSeed<'_> {
    type Value = BTreeMap<String, Value>;

    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
        // RON paren-records only answer deserialize_any (they are structs to
        // ron, maps to us) — any + visit_map is the reliable entry.
        d.deserialize_any(FieldsVisitor {
            fields: self.fields,
        })
    }
}

struct FieldsVisitor<'r> {
    fields: &'r [Field],
}

impl<'de> Visitor<'de> for FieldsVisitor<'_> {
    type Value = BTreeMap<String, Value>;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a record")
    }

    fn visit_map<M: de::MapAccess<'de>>(self, mut m: M) -> Result<Self::Value, M::Error> {
        let mut out = BTreeMap::new();
        while let Some(key) = m.next_key::<String>()? {
            match self.fields.iter().find(|f| f.name == key) {
                Some(field) => {
                    let v = m.next_value_seed(TypeSeed { ty: &field.ty })?;
                    out.insert(key, v);
                }
                None => {
                    let _: ron::Value = m.next_value()?; // unknown — skip
                }
            }
        }
        Ok(out)
    }
}

struct TypeSeed<'r> {
    ty: &'r FieldType,
}

impl<'de> DeserializeSeed<'de> for TypeSeed<'_> {
    type Value = Value;

    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
        match self.ty {
            FieldType::Str | FieldType::Markdown => d.deserialize_str(StrVisitor).map(Value::Str),
            FieldType::Date => {
                let s = d.deserialize_str(StrVisitor)?;
                NaiveDate::parse_from_str(&s, "%Y-%m-%d")
                    .map(Value::Date)
                    .map_err(|e| de::Error::custom(format!("date '{s}': {e}")))
            }
            FieldType::Bool => d.deserialize_bool(BoolVisitor).map(Value::Bool),
            FieldType::Int => d.deserialize_i64(IntVisitor).map(Value::Int),
            FieldType::Hyperlink => {
                let fields = [
                    Field {
                        name: "title".into(),
                        doc: String::new(),
                        ty: FieldType::Str,
                        role: None,
                        refers_to: None,
                    },
                    Field {
                        name: "url".into(),
                        doc: String::new(),
                        ty: FieldType::Str,
                        role: None,
                        refers_to: None,
                    },
                ];
                let map = d.deserialize_any(FieldsVisitor { fields: &fields })?;
                let get = |k: &str| match map.get(k) {
                    Some(Value::Str(s)) => Ok(s.clone()),
                    _ => Err(de::Error::custom(format!(
                        "hyperlink needs a string '{k}' — (title: \"\", url: \"https://…\")"
                    ))),
                };
                Ok(Value::Hyperlink {
                    title: get("title")?,
                    url: get("url")?,
                })
            }
            FieldType::Decimal => {
                let s = d.deserialize_str(StrVisitor)?;
                Decimal::from_str_exact(&s)
                    .map(Value::Decimal)
                    .map_err(|e| {
                        de::Error::custom(format!(
                            "decimal '{s}': {e} — exact decimals travel as strings, \
                             e.g. \"1250000.00\", never floats"
                        ))
                    })
            }
            FieldType::Link { .. } => d
                .deserialize_str(StrVisitor)
                .map(|s| Value::Link(Link::new(s))),
            FieldType::Enum(variants) => d.deserialize_enum("", &[], EnumVisitor { variants }),
            FieldType::Option(inner) => d.deserialize_option(OptVisitor { inner }),
            FieldType::List(inner) => d.deserialize_seq(ListVisitor { inner }),
            FieldType::Struct(fields) => d
                .deserialize_any(FieldsVisitor { fields })
                .map(Value::Struct),
        }
    }
}

struct StrVisitor;
impl<'de> Visitor<'de> for StrVisitor {
    type Value = String;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a string")
    }
    fn visit_str<E: de::Error>(self, v: &str) -> Result<String, E> {
        Ok(v.to_string())
    }
    fn visit_string<E: de::Error>(self, v: String) -> Result<String, E> {
        Ok(v)
    }
}

struct IntVisitor;

impl Visitor<'_> for IntVisitor {
    type Value = i64;
    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.write_str("an integer")
    }
    fn visit_i64<E: de::Error>(self, x: i64) -> Result<i64, E> {
        Ok(x)
    }
    fn visit_u64<E: de::Error>(self, x: u64) -> Result<i64, E> {
        i64::try_from(x).map_err(|_| E::custom(format!("integer {x} overflows i64")))
    }
}

struct BoolVisitor;
impl<'de> Visitor<'de> for BoolVisitor {
    type Value = bool;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a bool")
    }
    fn visit_bool<E: de::Error>(self, v: bool) -> Result<bool, E> {
        Ok(v)
    }
}

/// Variant name via `deserialize_identifier` (ron's variant seed speaks
/// identifiers, not strings — found empirically, guarded by tests).
struct NameSeed;
impl<'de> DeserializeSeed<'de> for NameSeed {
    type Value = String;
    fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<String, D::Error> {
        struct S;
        impl<'de> Visitor<'de> for S {
            type Value = String;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "a variant name")
            }
            fn visit_str<E: de::Error>(self, v: &str) -> Result<String, E> {
                Ok(v.to_string())
            }
        }
        d.deserialize_identifier(S)
    }
}

struct EnumVisitor<'r> {
    variants: &'r [crate::registry::Variant],
}

impl<'de> Visitor<'de> for EnumVisitor<'_> {
    type Value = Value;

    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "an enum variant")
    }

    fn visit_enum<A: EnumAccess<'de>>(self, a: A) -> Result<Value, A::Error> {
        let (name, variant) = a.variant_seed(NameSeed)?;
        let Some(spec) = self.variants.iter().find(|v| v.name == name) else {
            return Err(de::Error::custom(format!(
                "unknown variant '{name}' (expected one of: {})",
                self.variants
                    .iter()
                    .map(|v| v.name.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            )));
        };
        let fields = if spec.fields.is_empty() {
            variant.unit_variant()?;
            BTreeMap::new()
        } else {
            variant
                .struct_variant(
                    &[],
                    FieldsVisitor {
                        fields: &spec.fields,
                    },
                )
                .map_err(|e| {
                    de::Error::custom(format!(
                        "variant '{name}' payload: {e} — payload variants carry NAMED \
                         fields on disk (`{name}(field: value)`); positional/newtype \
                         payloads are not supported"
                    ))
                })?
        };
        Ok(Value::Enum {
            variant: name,
            fields,
        })
    }
}

struct OptVisitor<'r> {
    inner: &'r FieldType,
}

impl<'de> Visitor<'de> for OptVisitor<'_> {
    type Value = Value;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "an option")
    }
    fn visit_none<E: de::Error>(self) -> Result<Value, E> {
        Ok(Value::Null)
    }
    fn visit_unit<E: de::Error>(self) -> Result<Value, E> {
        Ok(Value::Null)
    }
    fn visit_some<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
        TypeSeed { ty: self.inner }.deserialize(d)
    }
}

struct ListVisitor<'r> {
    inner: &'r FieldType,
}

impl<'de> Visitor<'de> for ListVisitor<'_> {
    type Value = Value;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "a list")
    }
    fn visit_seq<S: de::SeqAccess<'de>>(self, mut s: S) -> Result<Value, S::Error> {
        let mut out = Vec::new();
        while let Some(v) = s.next_element_seed(TypeSeed { ty: self.inner })? {
            out.push(v);
        }
        Ok(Value::List(out))
    }
}

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

    use crate::registry::Variant;

    /// A hand-built todo-shaped kind — value decoding is registry-driven,
    /// so the fixture is a registry, not a schema crate.
    fn todo_kind() -> Kind {
        let field = |name: &str, ty: FieldType| Field {
            name: name.into(),
            doc: String::new(),
            ty,
            role: None,
            refers_to: None,
        };
        let unit = |name: &str| Variant {
            name: name.into(),
            doc: String::new(),
            fields: Vec::new(),
            tone: None,
        };
        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"), unit("Dropped")]),
                ),
                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),
            ],
        }
    }

    #[test]
    fn decodes_a_todo_with_enum_names_intact() {
        let text = r#"(
            id: "ship-it",
            title: "Ship the thing",
            status: Open,
            blocked_by: Some("todo:declare-source"),
            sources: ["graph:email:AA=="],
            notes: "Snapshot prose.",
        )"#;
        let v = decode(&todo_kind(), text).unwrap();
        assert_eq!(
            v["status"].variant(),
            Some("Open"),
            "the ron::Value limitation, fixed"
        );
        assert_eq!(
            v["blocked_by"],
            Value::Link(Link::kb("todo", "declare-source"))
        );
        assert_eq!(
            v["sources"],
            Value::List(vec![Value::Link(Link::external("graph", "email", "AA=="))])
        );
        assert!(!v.contains_key("due"), "absent optional stays absent");
    }

    #[test]
    fn decodes_nested_structs_and_null_options() {
        use crate::registry::Field;
        // The starter has no nested-struct field — a synthetic kind pins
        // List(Struct) decoding and explicit None options (the old
        // action.notes shape).
        let field = |name: &str, ty: FieldType| Field {
            name: name.into(),
            doc: String::new(),
            ty,
            role: None,
            refers_to: None,
        };
        let note = vec![
            field("date", FieldType::Date),
            field("text", FieldType::Markdown),
            field(
                "sources",
                FieldType::List(Box::new(FieldType::Link { allowed: None })),
            ),
        ];
        let journal = Kind {
            name: "journal".into(),
            doc: String::new(),
            storage: "facts/journal/{id}.ron".into(),
            fields: vec![
                field("id", FieldType::Str),
                field(
                    "owner",
                    FieldType::Option(Box::new(FieldType::Link { allowed: None })),
                ),
                field(
                    "origin",
                    FieldType::Option(Box::new(FieldType::Link { allowed: None })),
                ),
                field("notes", FieldType::List(Box::new(FieldType::Struct(note)))),
            ],
        };
        let text = r#"(
            id: "ship-it",
            owner: Some("self"),
            origin: None,
            notes: [(date: "2026-07-02", text: "Started.", sources: ["graph:event:AA=="])],
        )"#;
        let v = decode(&journal, text).unwrap();
        assert_eq!(v["origin"], Value::Null);
        assert_eq!(v["owner"], Value::Link(Link::singleton("self")));
        let Value::List(notes) = &v["notes"] else {
            panic!("notes is a list")
        };
        let Value::Struct(entry) = &notes[0] else {
            panic!("entry is a struct")
        };
        assert_eq!(
            entry["date"],
            Value::Date(NaiveDate::from_ymd_opt(2026, 7, 2).unwrap())
        );
        assert_eq!(
            entry["sources"],
            Value::List(vec![Value::Link(Link::external("graph", "event", "AA=="))])
        );
    }

    #[test]
    fn shape_violations_are_errors_not_garbage() {
        assert!(
            decode(&todo_kind(), r#"(id: "x", due: Some("not-a-date"))"#)
                .unwrap_err()
                .contains("date")
        );
        assert!(decode(&todo_kind(), "(id: ").is_err());
    }

    #[test]
    fn payload_variants_decode_with_their_fields() {
        // A synthetic kind exercising what the starter's shapes don't yet:
        // an enum variant carrying fields (the RunKind / health-KB shape).
        let run = Kind {
            name: "run".into(),
            doc: String::new(),
            storage: "runs/{id}.ron".into(),
            fields: vec![Field {
                name: "kind".into(),
                doc: String::new(),
                ty: FieldType::Enum(vec![
                    Variant {
                        name: "Window".into(),
                        doc: String::new(),
                        fields: vec![
                            Field {
                                name: "from".into(),
                                doc: String::new(),
                                ty: FieldType::Date,
                                role: None,
                                refers_to: None,
                            },
                            Field {
                                name: "to".into(),
                                doc: String::new(),
                                ty: FieldType::Date,
                                role: None,
                                refers_to: None,
                            },
                        ],
                        tone: None,
                    },
                    Variant {
                        name: "Snapshot".into(),
                        doc: String::new(),
                        fields: vec![],
                        tone: None,
                    },
                ]),
                role: None,
                refers_to: None,
            }],
        };
        let v = decode(
            &run,
            r#"(kind: Window(from: "2026-07-01", to: "2026-07-08"))"#,
        )
        .unwrap();
        let Value::Enum { variant, fields } = &v["kind"] else {
            panic!()
        };
        assert_eq!(variant, "Window");
        assert_eq!(
            fields["from"],
            Value::Date(NaiveDate::from_ymd_opt(2026, 7, 1).unwrap())
        );

        let v = decode(&run, "(kind: Snapshot)").unwrap();
        assert_eq!(v["kind"].variant(), Some("Snapshot"));
    }

    /// Nesting has no depth limit: list-of-struct containing an enum whose
    /// payload carries a markdown field and a list — decodes with true types
    /// at every level.
    #[test]
    fn deep_nesting_decodes_with_true_types() {
        use crate::registry::Variant;
        let payload_fields = vec![
            Field {
                name: "why".into(),
                doc: String::new(),
                ty: FieldType::Markdown,
                role: None,
                refers_to: None,
            },
            Field {
                name: "tags".into(),
                doc: String::new(),
                ty: FieldType::List(Box::new(FieldType::Str)),
                role: None,
                refers_to: None,
            },
        ];
        let entry = FieldType::Struct(vec![
            Field {
                name: "when".into(),
                doc: String::new(),
                ty: FieldType::Date,
                role: None,
                refers_to: None,
            },
            Field {
                name: "verdict".into(),
                doc: String::new(),
                ty: FieldType::Enum(vec![
                    Variant {
                        name: "Flagged".into(),
                        doc: String::new(),
                        fields: payload_fields,
                        tone: None,
                    },
                    Variant {
                        name: "Clear".into(),
                        doc: String::new(),
                        fields: vec![],
                        tone: None,
                    },
                ]),
                role: None,
                refers_to: None,
            },
        ]);
        let kind = Kind {
            name: "audit".into(),
            doc: String::new(),
            storage: "facts/audit/{id}.ron".into(),
            fields: vec![
                Field {
                    name: "id".into(),
                    doc: String::new(),
                    ty: FieldType::Str,
                    role: None,
                    refers_to: None,
                },
                Field {
                    name: "entries".into(),
                    doc: String::new(),
                    ty: FieldType::List(Box::new(entry)),
                    role: None,
                    refers_to: None,
                },
            ],
        };
        let rec = decode(
            &kind,
            r#"(
            id: "a1",
            entries: [
                (when: "2026-07-11", verdict: Flagged(why: "**bad**", tags: ["x", "y"])),
                (when: "2026-07-10", verdict: Clear),
            ],
        )"#,
        )
        .expect("deep nesting decodes");
        let Some(Value::List(entries)) = rec.get("entries") else {
            panic!("entries")
        };
        let Value::Struct(first) = &entries[0] else {
            panic!("struct entry")
        };
        let Some(Value::Enum { variant, fields }) = first.get("verdict") else {
            panic!("enum")
        };
        assert_eq!(variant, "Flagged");
        assert_eq!(fields.get("why"), Some(&Value::Str("**bad**".into())));
        assert!(matches!(fields.get("tags"), Some(Value::List(t)) if t.len() == 2));
    }

    /// The two payload-variant encodings, probed side by side: NAMED-field
    /// (struct) variants are the supported on-disk form; positional/newtype
    /// payloads are refused — the registry vocabulary cannot even express a
    /// nameless payload (Variant.fields all carry names).
    #[test]
    fn struct_variant_payloads_decode_newtype_payloads_are_refused() {
        use crate::registry::Variant;
        let client_ref = FieldType::Enum(vec![
            Variant {
                name: "Known".into(),
                doc: String::new(),
                fields: vec![Field {
                    name: "org".into(),
                    doc: String::new(),
                    ty: FieldType::Str,
                    role: None,
                    refers_to: None,
                }],
                tone: None,
            },
            Variant {
                name: "Unknown".into(),
                doc: String::new(),
                fields: vec![],
                tone: None,
            },
        ]);
        let kind = Kind {
            name: "probe".into(),
            doc: String::new(),
            storage: "facts/probe/{id}.ron".into(),
            fields: vec![
                Field {
                    name: "id".into(),
                    doc: String::new(),
                    ty: FieldType::Str,
                    role: None,
                    refers_to: None,
                },
                Field {
                    name: "r".into(),
                    doc: String::new(),
                    ty: client_ref,
                    role: None,
                    refers_to: None,
                },
            ],
        };
        // Struct-variant encoding: named payload — decodes.
        let ok =
            decode(&kind, r#"(id: "p", r: Known(org: "org:absa"))"#).expect("named fields decode");
        assert!(matches!(ok.get("r"), Some(Value::Enum { variant, .. }) if variant == "Known"));

        // Newtype encoding: positional payload — refused, with a steer.
        let err =
            decode(&kind, r#"(id: "p", r: Known("org:absa"))"#).expect_err("positional refused");
        assert!(err.contains("NAMED fields"), "steering error, got: {err}");
    }

    #[test]
    fn numeric_and_hyperlink_fields_decode() {
        let kind = Kind {
            name: "project".into(),
            doc: String::new(),
            storage: "facts/projects/{id}.ron".into(),
            fields: vec![
                Field {
                    name: "id".into(),
                    doc: String::new(),
                    ty: FieldType::Str,
                    role: None,
                    refers_to: None,
                },
                Field {
                    name: "headcount".into(),
                    doc: String::new(),
                    ty: FieldType::Int,
                    role: None,
                    refers_to: None,
                },
                Field {
                    name: "value".into(),
                    doc: String::new(),
                    ty: FieldType::Decimal,
                    role: None,
                    refers_to: None,
                },
                Field {
                    name: "tracker".into(),
                    doc: String::new(),
                    ty: FieldType::Hyperlink,
                    role: None,
                    refers_to: None,
                },
            ],
        };
        let ron = r#"(
            id: "absa-adt",
            headcount: 7,
            value: "1250000.00",
            tracker: (title: "PMO Tracker", url: "https://example.com/x.xlsx"),
        )"#;
        let rec = decode(&kind, ron).expect("decodes");
        assert_eq!(rec.get("headcount"), Some(&Value::Int(7)));
        assert_eq!(
            rec.get("value"),
            Some(&Value::Decimal(
                Decimal::from_str_exact("1250000.00").unwrap()
            ))
        );
        assert_eq!(
            rec.get("tracker"),
            Some(&Value::Hyperlink {
                title: "PMO Tracker".into(),
                url: "https://example.com/x.xlsx".into()
            })
        );

        // A float where an exact decimal belongs is an ERROR, not a value.
        let bad = r#"(id: "x", headcount: 1, value: 1250000.00, tracker: (title: "t", url: "https://e"))"#;
        assert!(
            decode(&kind, bad).is_err(),
            "float decimals must be refused"
        );
    }
}