zenith-core 0.0.5

Zenith core: KDL parser adapter, semantic AST, canonical formatter, tokens, validation, and diagnostics.
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Integration tests for the canonical writer: nodes.
//!
//! Leaf and decorative nodes — images, ellipses, assets, safe-zones, folds, and
//! unknown properties — parse, serialize, and round-trip.
//!
//! Moved verbatim from the former in-`src` `format/writer/tests.rs`; the body of
//! every test is unchanged — only import paths were rewritten to the public
//! `zenith_core` surface. Span-stripping helpers live in `common`.

mod common;

use common::*;
use zenith_core::format::format_document;

/// **Image clip round-trip**: `clip="rounded"` + `clip-radius=(token)"..."`
/// must parse onto the `ImageNode`, be re-emitted by the formatter, and survive
/// a format → re-parse round-trip.
#[test]
fn test_image_clip_parse_format_round_trip() {
    let src = r##"zenith version=1 {
  project id="proj.iclip" name="IClip"
  assets {
    asset id="asset.pfp" kind="image" src="assets/pfp.png"
  }
  tokens format="zenith-token-v1" {
    token id="size.radius.avatar" type="dimension" value=(px)24
  }
  styles {
  }
  document id="doc.iclip" title="IClip" {
    page id="page.iclip" w=(px)400 h=(px)300 {
      image id="av" asset="asset.pfp" x=(px)0 y=(px)0 w=(px)100 h=(px)100 fit="cover" clip="rounded" clip-radius=(token)"size.radius.avatar"
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");
    let image_node = match &doc.body.pages[0].children[0] {
        Node::Image(i) => i,
        other => panic!("expected Image node, got {other:?}"),
    };
    assert_eq!(image_node.clip.as_deref(), Some("rounded"));
    use zenith_core::PropertyValue;
    assert_eq!(
        image_node.clip_radius,
        Some(PropertyValue::TokenRef("size.radius.avatar".to_owned())),
        "clip-radius must parse as a token ref"
    );

    let formatted = format_document(&doc).expect("format must succeed");
    let formatted_str = String::from_utf8(formatted).expect("formatted must be utf8");
    assert!(
        formatted_str.contains("clip=\"rounded\""),
        "formatter must emit clip=\"rounded\"; got:\n{formatted_str}"
    );
    assert!(
        formatted_str.contains("clip-radius=(token)\"size.radius.avatar\""),
        "formatter must emit clip-radius token; got:\n{formatted_str}"
    );

    let doc2 = adapter
        .parse(formatted_str.as_bytes())
        .expect("re-parse after format");
    let image2 = match &doc2.body.pages[0].children[0] {
        Node::Image(i) => i,
        other => panic!("expected Image node on re-parse, got {other:?}"),
    };
    assert_eq!(image2.clip.as_deref(), Some("rounded"));
    assert_eq!(
        image2.clip_radius,
        Some(PropertyValue::TokenRef("size.radius.avatar".to_owned())),
        "clip-radius must survive a format → re-parse round-trip"
    );
}

/// A `.zen` document with an image node exercising the string and `(pct)`
/// object-position forms.
const WITH_IMAGE: &str = r##"zenith version=1 {
  project id="proj.img" name="Image Test"
  assets {
    asset id="asset.logo" kind="image" src="assets/logo.png"
  }
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.img" title="Image Test" {
    page id="page.one" w=(px)320 h=(px)200 {
      image id="img.logo" asset="asset.logo" x=(px)80 y=(px)60 w=(px)160 h=(px)48 fit="contain" object-position-x="center" object-position-y=(pct)25
    }
  }
}
"##;

/// Image node parses all fields including both object-position forms.
#[test]
fn image_parses_fields() {
    use zenith_core::{Node, ObjectPosition, Unit};
    let adapter = KdlAdapter;
    let doc = adapter.parse(WITH_IMAGE.as_bytes()).expect("parse");
    let node = &doc.body.pages[0].children[0];
    let img = match node {
        Node::Image(i) => i,
        other => panic!("expected Image, got {other:?}"),
    };
    assert_eq!(img.id, "img.logo");
    assert_eq!(img.asset, "asset.logo");
    let geom_value = |pv: Option<&PropertyValue>| match pv {
        Some(PropertyValue::Dimension(d)) => Some(d.value),
        _ => None,
    };
    assert_eq!(geom_value(img.x.as_ref()), Some(80.0));
    assert_eq!(geom_value(img.y.as_ref()), Some(60.0));
    assert_eq!(geom_value(img.w.as_ref()), Some(160.0));
    assert_eq!(geom_value(img.h.as_ref()), Some(48.0));
    assert!(matches!(
        img.x.as_ref(),
        Some(PropertyValue::Dimension(d)) if d.unit == Unit::Px
    ));
    assert_eq!(img.fit.as_deref(), Some("contain"));
    assert_eq!(img.object_position_x, Some(ObjectPosition::Center));
    assert_eq!(img.object_position_y, Some(ObjectPosition::Pct(25.0)));
}

/// Image node round-trips through format → parse with fields intact, and
/// the formatter is idempotent (incl. an object-position `(pct)25`).
#[test]
fn image_format_round_trip_and_idempotency() {
    use zenith_core::{Node, ObjectPosition};
    let adapter = KdlAdapter;
    let doc1 = adapter.parse(WITH_IMAGE.as_bytes()).expect("parse 1");
    let s1 = format_document(&doc1).expect("format 1");

    // The (pct)25 must survive as an annotated number, not a string.
    let text = String::from_utf8(s1.clone()).unwrap();
    assert!(
        text.contains("object-position-y=(pct)25"),
        "object-position (pct) must format as annotated number; got:\n{text}"
    );
    assert!(
        text.contains("object-position-x=\"center\""),
        "object-position anchor must format as string; got:\n{text}"
    );

    let doc2 = adapter.parse(&s1).expect("parse 2");
    let img2 = match &doc2.body.pages[0].children[0] {
        Node::Image(i) => i,
        other => panic!("expected Image, got {other:?}"),
    };
    assert_eq!(img2.asset, "asset.logo");
    assert_eq!(img2.fit.as_deref(), Some("contain"));
    assert_eq!(img2.object_position_x, Some(ObjectPosition::Center));
    assert_eq!(img2.object_position_y, Some(ObjectPosition::Pct(25.0)));

    let s2 = format_document(&doc2).expect("format 2");
    assert_eq!(
        String::from_utf8(s1).unwrap(),
        String::from_utf8(s2).unwrap(),
        "image format must be idempotent"
    );
}

// ── Style block parse + format tests ──────────────────────────────────

/// **src-rect round-trip**: an image node with `src-x`/`src-y`/`src-w`/`src-h`
/// must parse → format → re-parse byte-identically (all four src-* fields
/// survive the round-trip).
#[test]
fn test_image_src_rect_round_trip() {
    let src = r##"zenith version=1 {
  project id="proj.srcrt" name="SrcRt"
  assets {
    asset id="asset.photo" kind="image" src="assets/photo.png"
  }
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.srcrt" title="SrcRt" {
    page id="page.srcrt" w=(px)400 h=(px)300 {
      image id="img.srcrt" asset="asset.photo" x=(px)0 y=(px)0 w=(px)200 h=(px)100 src-x=(px)10 src-y=(px)20 src-w=(px)50 src-h=(px)60 fit="stretch"
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");
    let image_node = match &doc.body.pages[0].children[0] {
        Node::Image(i) => i,
        other => panic!("expected Image node, got {other:?}"),
    };

    use zenith_core::{Dimension, Unit};
    assert_eq!(
        image_node.src_x,
        Some(Dimension {
            value: 10.0,
            unit: Unit::Px
        }),
        "src-x must parse to (px)10"
    );
    assert_eq!(
        image_node.src_y,
        Some(Dimension {
            value: 20.0,
            unit: Unit::Px
        }),
        "src-y must parse to (px)20"
    );
    assert_eq!(
        image_node.src_w,
        Some(Dimension {
            value: 50.0,
            unit: Unit::Px
        }),
        "src-w must parse to (px)50"
    );
    assert_eq!(
        image_node.src_h,
        Some(Dimension {
            value: 60.0,
            unit: Unit::Px
        }),
        "src-h must parse to (px)60"
    );

    let formatted = format_document(&doc).expect("format must succeed");
    let formatted_str = String::from_utf8(formatted.clone()).expect("formatted must be utf8");
    assert!(
        formatted_str.contains("src-x=(px)10"),
        "formatter must emit src-x=(px)10; got:\n{formatted_str}"
    );
    assert!(
        formatted_str.contains("src-y=(px)20"),
        "formatter must emit src-y=(px)20; got:\n{formatted_str}"
    );
    assert!(
        formatted_str.contains("src-w=(px)50"),
        "formatter must emit src-w=(px)50; got:\n{formatted_str}"
    );
    assert!(
        formatted_str.contains("src-h=(px)60"),
        "formatter must emit src-h=(px)60; got:\n{formatted_str}"
    );

    let reparsed = adapter.parse(&formatted).expect("re-parse after format");
    assert_eq!(
        strip_spans(doc),
        strip_spans(reparsed),
        "src-rect image must round-trip identically"
    );
}

// ── sections: parse, serialize, and round-trip ────────────────────────

/// **Ellipse stroke + stroke-width round-trip**: an ellipse with both
/// `stroke` and `stroke-width` tokens must survive parse→format→parse with
/// those fields preserved in the canonical position (after `fill`).
#[test]
fn ellipse_stroke_round_trip() {
    let src = r##"zenith version=1 {
  project id="proj.es" name="ES"
  tokens format="zenith-token-v1" {
    token id="color.border" type="color" value="#334155"
    token id="size.border" type="dimension" value=(px)3
  }
  styles {
  }
  document id="doc.es" title="ES" {
    page id="p" w=(px)200 h=(px)200 {
      ellipse id="e" x=(px)10 y=(px)10 w=(px)80 h=(px)80 stroke=(token)"color.border" stroke-width=(token)"size.border"
    }
  }
}
"##;
    use zenith_core::{Node, PropertyValue};
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse");

    // Verify AST fields are set.
    match &doc.body.pages[0].children[0] {
        Node::Ellipse(e) => {
            assert_eq!(
                e.stroke,
                Some(PropertyValue::TokenRef("color.border".to_owned())),
                "stroke must parse to TokenRef(color.border)"
            );
            assert_eq!(
                e.stroke_width,
                Some(PropertyValue::TokenRef("size.border".to_owned())),
                "stroke_width must parse to TokenRef(size.border)"
            );
            assert!(e.fill.is_none(), "fill must be absent");
        }
        other => panic!("expected Ellipse, got {other:?}"),
    }

    // Format and re-parse — the tokens must survive.
    let formatted = format_document(&doc).expect("format");
    let formatted_str = String::from_utf8(formatted.clone()).expect("utf8");
    let doc2 = adapter.parse(&formatted).expect("re-parse");
    match &doc2.body.pages[0].children[0] {
        Node::Ellipse(e) => {
            assert_eq!(
                e.stroke,
                Some(PropertyValue::TokenRef("color.border".to_owned())),
                "stroke must survive format round-trip"
            );
            assert_eq!(
                e.stroke_width,
                Some(PropertyValue::TokenRef("size.border".to_owned())),
                "stroke_width must survive format round-trip"
            );
        }
        other => panic!("expected Ellipse on re-parse, got {other:?}"),
    }

    // Canonical position: stroke comes after fill.
    let ellipse_line = formatted_str
        .lines()
        .find(|l| l.trim_start().starts_with("ellipse"))
        .expect("must find ellipse line");
    assert!(
        ellipse_line.contains("stroke=(token)\"color.border\""),
        "formatted line must contain stroke token; got: {ellipse_line}"
    );
    assert!(
        ellipse_line.contains("stroke-width=(token)\"size.border\""),
        "formatted line must contain stroke-width token; got: {ellipse_line}"
    );
    // stroke must come before stroke-width (canonical order).
    let pos_stroke = ellipse_line.find(" stroke=").expect("must have stroke=");
    let pos_sw = ellipse_line
        .find(" stroke-width=")
        .expect("must have stroke-width=");
    assert!(
        pos_stroke < pos_sw,
        "stroke= must appear before stroke-width= in canonical output"
    );

    // Idempotency: format(format(doc)) == format(doc).
    let s2 = format_document(&doc2).expect("format 2");
    assert_eq!(
        formatted_str,
        String::from_utf8(s2).unwrap(),
        "ellipse stroke formatting must be idempotent"
    );
}

// ── Image node parse + format tests ───────────────────────────────────

/// A `.zen` document with a `safe-zone` declared as a page child.
const SAFE_ZONE_DOC: &str = r##"zenith version=1 {
  project id="proj.sz" name="Safe Zone Project"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.sz" title="Safe Zone Doc" {
    page id="page.one" w=(px)1500 h=(px)500 {
      safe-zone id="sz.avatar" type="exclusion" x=(px)0 y=(px)358 w=(px)175 h=(px)142 label="X avatar dead zone"
      rect id="logo" x=(px)600 y=(px)40 w=(px)200 h=(px)80 fill="#ffffff"
    }
  }
}
"##;

/// **Parse**: a `safe-zone` page child lands in `page.safe_zones`, NOT in
/// `page.children`.
#[test]
fn test_safe_zone_parses_into_page_not_children() {
    let adapter = KdlAdapter;
    let doc = adapter
        .parse(SAFE_ZONE_DOC.as_bytes())
        .expect("parse must succeed");
    let page = &doc.body.pages[0];

    assert_eq!(page.safe_zones.len(), 1, "exactly one safe-zone parsed");
    let zone = &page.safe_zones[0];
    assert_eq!(zone.id, "sz.avatar");
    assert_eq!(zone.zone_type, zenith_core::SafeZoneType::Exclusion);
    assert_eq!(zone.label.as_deref(), Some("X avatar dead zone"));

    // The renderable rect is the ONLY child; the safe-zone is not a child.
    assert_eq!(page.children.len(), 1, "only the rect is a child node");
    match &page.children[0] {
        Node::Rect(r) => assert_eq!(r.id, "logo"),
        other => panic!("expected Rect, got {other:?}"),
    }
}

/// **Format round-trip**: a safe-zone survives a parse → format → parse pass
/// unchanged (spans excluded).
#[test]
fn test_safe_zone_format_round_trip() {
    let adapter = KdlAdapter;
    let doc_orig = adapter
        .parse(SAFE_ZONE_DOC.as_bytes())
        .expect("original parse");
    let formatted = format_document(&doc_orig).expect("format");

    // The emitted line carries the canonical safe-zone shape.
    let text = String::from_utf8(formatted.clone()).expect("utf8");
    assert!(
        text.contains(
            "safe-zone id=\"sz.avatar\" type=\"exclusion\" \
             x=(px)0 y=(px)358 w=(px)175 h=(px)142 label=\"X avatar dead zone\""
        ),
        "formatted safe-zone line missing/incorrect; output:\n{text}"
    );

    let doc_reparsed = adapter.parse(&formatted).expect("re-parse after format");
    assert_eq!(
        strip_spans(doc_orig),
        strip_spans(doc_reparsed),
        "safe-zone must survive a format round-trip (spans excluded)"
    );
}

/// A safe-zone `label` containing a double-quote and a newline must be escaped on
/// emit so the formatted document re-parses to the identical label.
#[test]
fn test_safe_zone_label_escaping_round_trip() {
    let src = "zenith version=1 {\n  \
         project id=\"proj.szesc\" name=\"SZEsc\"\n  \
         tokens format=\"zenith-token-v1\" {\n  }\n  \
         styles {\n  }\n  \
         document id=\"doc.szesc\" title=\"SZEsc\" {\n    \
           page id=\"page.one\" w=(px)800 h=(px)600 {\n      \
             safe-zone id=\"sz.q\" type=\"exclusion\" x=(px)0 y=(px)0 w=(px)10 h=(px)10 \
                 label=\"a \\\"q\\\" b\\nc\"\n    }\n  }\n}\n";
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");
    let label = doc.body.pages[0].safe_zones[0]
        .label
        .clone()
        .expect("label present");
    assert_eq!(
        label, "a \"q\" b\nc",
        "parsed label has the raw special chars"
    );

    let formatted = format_document(&doc).expect("format must succeed");
    let doc2 = adapter
        .parse(&formatted)
        .expect("re-parse after format must succeed");
    assert_eq!(
        doc2.body.pages[0].safe_zones[0].label.as_deref(),
        Some("a \"q\" b\nc"),
        "safe-zone label with quote/newline must survive parse → format → parse"
    );
}

/// A `.zen` document with a `fold` declared as a page child.
const FOLD_DOC: &str = r##"zenith version=1 {
  project id="proj.fold" name="Fold Project"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.fold" title="Fold Doc" {
    page id="page.one" w=(px)2480 h=(px)1000 {
      fold id="fold.1" orientation="vertical" position=(px)1169
      rect id="logo" x=(px)600 y=(px)40 w=(px)200 h=(px)80 fill="#ffffff"
    }
  }
}
"##;

/// **Parse**: a `fold` page child lands in `page.folds`, NOT in
/// `page.children`.
#[test]
fn test_fold_parses_into_page_not_children() {
    let adapter = KdlAdapter;
    let doc = adapter
        .parse(FOLD_DOC.as_bytes())
        .expect("parse must succeed");
    let page = &doc.body.pages[0];

    assert_eq!(page.folds.len(), 1, "exactly one fold parsed");
    let fold = &page.folds[0];
    assert_eq!(fold.id, "fold.1");
    assert_eq!(fold.orientation, "vertical");
    let pos = fold.position.as_ref().expect("position present");
    assert_eq!(pos.value, 1169.0);

    // The renderable rect is the ONLY child; the fold is not a child.
    assert_eq!(page.children.len(), 1, "only the rect is a child node");
    match &page.children[0] {
        Node::Rect(r) => assert_eq!(r.id, "logo"),
        other => panic!("expected Rect, got {other:?}"),
    }
}

/// **Format round-trip**: a fold survives a parse → format → parse pass
/// unchanged (spans excluded).
#[test]
fn test_fold_format_round_trip() {
    let adapter = KdlAdapter;
    let doc_orig = adapter.parse(FOLD_DOC.as_bytes()).expect("original parse");
    let formatted = format_document(&doc_orig).expect("format");

    let text = String::from_utf8(formatted.clone()).expect("utf8");
    assert!(
        text.contains("fold id=\"fold.1\" orientation=\"vertical\" position=(px)1169"),
        "formatted fold line missing/incorrect; output:\n{text}"
    );

    let doc_reparsed = adapter.parse(&formatted).expect("re-parse after format");
    assert_eq!(
        strip_spans(doc_orig),
        strip_spans(doc_reparsed),
        "fold must survive a format round-trip (spans excluded)"
    );
}

/// **Unknown-property multi-type round-trip**: unknown properties of every
/// KDL value type survive parse→format→parse with their type intact, and
/// the output is idempotent (format twice → identical bytes).
#[test]
fn test_unknown_property_all_types_round_trip() {
    // Each property exercises one KdlValue variant.
    // Raw string r##"..."## needed because KDL v2 booleans/null use `#`.
    let src = r##"zenith version=1 {
  project id="proj.rt" name="RT"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.rt" title="RT" {
    page id="p" w=(px)100 h=(px)100 {
      rect id="r" x=(px)0 y=(px)0 w=(px)10 h=(px)10 future-flag=#true future-float=1.5 future-int=42 future-null=#null future-str="hi"
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc1 = adapter.parse(src.as_bytes()).expect("parse 1");

    // Verify all five types landed correctly after the first parse.
    let rect = match &doc1.body.pages[0].children[0] {
        zenith_core::Node::Rect(r) => r,
        other => panic!("expected Rect, got {other:?}"),
    };
    assert_eq!(
        rect.unknown_props["future-flag"].value,
        zenith_core::UnknownValue::Bool(true),
        "boolean must parse as UnknownValue::Bool(true), not a string"
    );
    assert_eq!(
        rect.unknown_props["future-int"].value,
        zenith_core::UnknownValue::Integer(42),
        "integer must parse as UnknownValue::Integer(42)"
    );
    assert_eq!(
        rect.unknown_props["future-float"].value,
        zenith_core::UnknownValue::Float(1.5),
        "float must parse as UnknownValue::Float(1.5)"
    );
    assert_eq!(
        rect.unknown_props["future-str"].value,
        zenith_core::UnknownValue::String("hi".to_owned()),
        "string must parse as UnknownValue::String"
    );
    assert_eq!(
        rect.unknown_props["future-null"].value,
        zenith_core::UnknownValue::Null,
        "null must parse as UnknownValue::Null"
    );

    // Format once → parse → assert same typed values survive (round-trip).
    let formatted1 = format_document(&doc1).expect("format 1");
    let doc2 = adapter.parse(&formatted1).expect("parse 2 after format");
    let rect2 = match &doc2.body.pages[0].children[0] {
        zenith_core::Node::Rect(r) => r,
        other => panic!("expected Rect in re-parsed doc, got {other:?}"),
    };
    assert_eq!(
        rect2.unknown_props["future-flag"].value,
        zenith_core::UnknownValue::Bool(true),
        "boolean must survive format round-trip as UnknownValue::Bool(true)"
    );
    assert_eq!(
        rect2.unknown_props["future-int"].value,
        zenith_core::UnknownValue::Integer(42),
        "integer must survive format round-trip as UnknownValue::Integer(42)"
    );
    assert_eq!(
        rect2.unknown_props["future-float"].value,
        zenith_core::UnknownValue::Float(1.5),
        "float must survive format round-trip"
    );
    assert_eq!(
        rect2.unknown_props["future-str"].value,
        zenith_core::UnknownValue::String("hi".to_owned()),
        "string must survive format round-trip"
    );
    assert_eq!(
        rect2.unknown_props["future-null"].value,
        zenith_core::UnknownValue::Null,
        "null must survive format round-trip"
    );

    // Idempotence: format a second time → identical bytes.
    let formatted2 = format_document(&doc2).expect("format 2");
    assert_eq!(
        formatted1, formatted2,
        "format must be idempotent for documents with unknown properties of all types"
    );
}

/// **Unknown-property type-annotation round-trip**: KDL type annotations on
/// unrecognized properties (e.g. `(px)42`, `(token)"color.brand"`) must be
/// captured on parse, re-emitted in the value position on format, and survive
/// a full parse→format→parse cycle byte-identically. Non-annotated unknown
/// values must remain unchanged.
#[test]
fn test_unknown_property_type_annotation_round_trip() {
    let src = r##"zenith version=1 {
  project id="proj.ann" name="Ann"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.ann" title="Ann" {
    page id="p" w=(px)100 h=(px)100 {
      rect id="r" x=(px)0 y=(px)0 w=(px)10 h=(px)10 mystery=(px)42 magic=(token)"color.brand" plain="hello" flag=#true
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc1 = adapter.parse(src.as_bytes()).expect("parse 1");

    let rect = match &doc1.body.pages[0].children[0] {
        zenith_core::Node::Rect(r) => r,
        other => panic!("expected Rect, got {other:?}"),
    };

    // Annotations captured on parse.
    assert_eq!(
        rect.unknown_props["mystery"].ty.as_deref(),
        Some("px"),
        "`(px)42` must capture ty = Some(\"px\")"
    );
    assert_eq!(
        rect.unknown_props["mystery"].value,
        zenith_core::UnknownValue::Integer(42),
    );
    assert_eq!(
        rect.unknown_props["magic"].ty.as_deref(),
        Some("token"),
        "`(token)\"color.brand\"` must capture ty = Some(\"token\")"
    );
    assert_eq!(
        rect.unknown_props["magic"].value,
        zenith_core::UnknownValue::String("color.brand".to_owned()),
    );
    // Non-annotated unknown props have ty = None.
    assert_eq!(
        rect.unknown_props["plain"].ty, None,
        "non-annotated `plain` must have ty = None"
    );
    assert_eq!(
        rect.unknown_props["flag"].ty, None,
        "non-annotated `flag` must have ty = None"
    );

    // Format → the annotation is emitted in the value position.
    let formatted1 = format_document(&doc1).expect("format 1");
    let text = String::from_utf8_lossy(&formatted1);
    assert!(
        text.contains("mystery=(px)42"),
        "formatted output must contain `mystery=(px)42`, got:\n{text}"
    );
    assert!(
        text.contains(r#"magic=(token)"color.brand""#),
        "formatted output must contain `magic=(token)\"color.brand\"`, got:\n{text}"
    );
    assert!(
        text.contains(r#"plain="hello""#),
        "non-annotated `plain=\"hello\"` must be unchanged, got:\n{text}"
    );
    assert!(
        text.contains("flag=#true"),
        "non-annotated `flag=#true` must be unchanged, got:\n{text}"
    );

    // Re-parse → unknown_props (value + ty) are identical to the first parse.
    let doc2 = adapter.parse(&formatted1).expect("parse 2 after format");
    let rect2 = match &doc2.body.pages[0].children[0] {
        zenith_core::Node::Rect(r) => r,
        other => panic!("expected Rect in re-parsed doc, got {other:?}"),
    };
    assert_eq!(
        rect.unknown_props, rect2.unknown_props,
        "unknown_props (value + ty) must be byte-stable across parse→format→parse"
    );

    // Idempotence: format a second time → identical bytes.
    let formatted2 = format_document(&doc2).expect("format 2");
    assert_eq!(
        formatted1, formatted2,
        "format must be idempotent for annotated unknown properties"
    );
}

/// **Forward-compat preservation**: an unknown property on a rect survives
/// a format round-trip.
#[test]
fn test_unknown_property_preserved() {
    let src = r##"zenith version=1 {
  project id="proj.unk" name="Unk"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.unk" title="Unk" {
    page id="p" w=(px)100 h=(px)100 {
      rect id="r" x=(px)0 y=(px)0 w=(px)10 h=(px)10 future-prop="hello"
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse");
    let out = format_document(&doc).expect("format");
    let text = String::from_utf8(out).unwrap();
    assert!(
        text.contains("future-prop="),
        "unknown property `future-prop` must survive format; got:\n{text}"
    );
}

/// **anchor-sibling round-trip**: a rect with `anchor="top-left"` and
/// `anchor-sibling="some-id"` must parse onto the AST with both fields set,
/// survive `format_document`, and still carry `anchor-sibling="some-id"` after
/// a format → re-parse cycle.
#[test]
fn test_anchor_sibling_round_trip() {
    let src = r##"zenith version=1 {
  project id="proj.as" name="AS"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.as" title="AS" {
    page id="p" w=(px)200 h=(px)200 {
      rect id="r" anchor="top-left" anchor-sibling="some-id" x=(px)0 y=(px)0 w=(px)50 h=(px)50
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");

    // Verify AST fields are set after parse.
    match &doc.body.pages[0].children[0] {
        Node::Rect(r) => {
            assert_eq!(
                r.anchor.as_deref(),
                Some("top-left"),
                "anchor must parse to \"top-left\""
            );
            assert_eq!(
                r.anchor_sibling.as_deref(),
                Some("some-id"),
                "anchor-sibling must parse to \"some-id\""
            );
        }
        other => panic!("expected Rect, got {other:?}"),
    }

    // Format and assert the KDL text contains anchor-sibling.
    let formatted = format_document(&doc).expect("format must succeed");
    let formatted_str = String::from_utf8(formatted).expect("formatted must be utf8");
    assert!(
        formatted_str.contains("anchor-sibling=\"some-id\""),
        "formatter must emit anchor-sibling=\"some-id\"; got:\n{formatted_str}"
    );

    // Re-parse the formatted output and verify anchor-sibling survived.
    let doc2 = adapter
        .parse(formatted_str.as_bytes())
        .expect("re-parse after format must succeed");
    match &doc2.body.pages[0].children[0] {
        Node::Rect(r) => {
            assert_eq!(
                r.anchor_sibling.as_deref(),
                Some("some-id"),
                "anchor-sibling must survive a format → re-parse round-trip"
            );
            assert_eq!(
                r.anchor.as_deref(),
                Some("top-left"),
                "anchor must survive a format → re-parse round-trip"
            );
        }
        other => panic!("expected Rect on re-parse, got {other:?}"),
    }
}

// ── connector owned label ─────────────────────────────────────────────────────

/// A `connector` with a `span "Yes"` label must survive parse → format → parse.
/// After roundtrip the connector node carries the original span text and `text-style`.
#[test]
fn connector_label_roundtrip_preserves_spans_and_text_style() {
    let src = r##"zenith version=1 {
  project id="proj.clrt" name="CLRT"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.clrt" title="CLRT" {
    page id="p.clrt" w=(px)640 h=(px)360 {
      rect id="a" x=(px)40 y=(px)40 w=(px)100 h=(px)80
      rect id="b" x=(px)300 y=(px)60 w=(px)100 h=(px)80
      connector id="c1" from="a" to="b" text-style="s.branch" {
        span "Yes"
      }
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");

    // Verify that after parse the connector carries the span and text_style.
    let connector = match &doc.body.pages[0].children[2] {
        Node::Connector(c) => c,
        other => panic!("expected Connector node, got {other:?}"),
    };
    assert_eq!(connector.spans.len(), 1, "connector must have 1 span");
    assert_eq!(connector.spans[0].text, "Yes", "span text must be \"Yes\"");
    assert_eq!(
        connector.text_style.as_deref(),
        Some("s.branch"),
        "text-style must parse as \"s.branch\""
    );

    // Format then re-parse and verify the span survives.
    let formatted = format_document(&doc).expect("format must succeed");
    let formatted_str = String::from_utf8(formatted).expect("formatted must be utf8");

    // The formatted text must contain `span "Yes"` inside a connector block.
    assert!(
        formatted_str.contains("span \"Yes\""),
        "formatted output must contain span \"Yes\"; got:\n{formatted_str}"
    );
    assert!(
        formatted_str.contains("text-style=\"s.branch\""),
        "formatted output must contain text-style=\"s.branch\"; got:\n{formatted_str}"
    );

    let doc2 = adapter
        .parse(formatted_str.as_bytes())
        .expect("re-parse after format must succeed");
    let connector2 = match &doc2.body.pages[0].children[2] {
        Node::Connector(c) => c,
        other => panic!("expected Connector on re-parse, got {other:?}"),
    };
    assert_eq!(
        connector2.spans.len(),
        1,
        "connector must still have 1 span after roundtrip"
    );
    assert_eq!(
        connector2.spans[0].text, "Yes",
        "span text must survive parse → format → parse"
    );
    assert_eq!(
        connector2.text_style.as_deref(),
        Some("s.branch"),
        "text-style must survive parse → format → parse"
    );
}

/// A connector WITHOUT spans must emit NO `{ }` block — the formatted line must
/// end with a plain `\n` (byte-identical to the pre-label behaviour).
#[test]
fn connector_without_label_emits_no_brace_block() {
    let src = r##"zenith version=1 {
  project id="proj.cnbl" name="CNBL"
  tokens format="zenith-token-v1" {
  }
  styles {
  }
  document id="doc.cnbl" title="CNBL" {
    page id="p.cnbl" w=(px)640 h=(px)360 {
      rect id="a" x=(px)40 y=(px)40 w=(px)100 h=(px)80
      rect id="b" x=(px)300 y=(px)60 w=(px)100 h=(px)80
      connector id="c1" from="a" to="b"
    }
  }
}
"##;
    let adapter = KdlAdapter;
    let doc = adapter.parse(src.as_bytes()).expect("parse must succeed");
    let formatted = format_document(&doc).expect("format must succeed");
    let formatted_str = String::from_utf8(formatted).expect("utf8");

    // The connector line must NOT contain a `{` (no brace block emitted).
    let connector_line = formatted_str
        .lines()
        .find(|l| l.trim_start().starts_with("connector "))
        .expect("formatted output must contain a connector line");
    assert!(
        !connector_line.contains('{'),
        "label-less connector must not emit a brace block; line: {connector_line:?}"
    );
}