nereid 0.9.0

Source-available noncommercial terminal diagram TUI and MCP server for Mermaid-backed sessions
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
// SPDX-FileCopyrightText: 2026 Bruno Meilick
// SPDX-License-Identifier: LicenseRef-Nereid-FreeUse-NoCopy-NoDerivatives
//
// All rights reserved.
//
// This file is part of Nereid and is proprietary software.
// Unauthorized copying, modification, or distribution is prohibited.

//! Sequence-diagram AST: participants, ordered messages, and nested alt/opt/loop/par blocks.
//!
//! Message membership in sections must stay export-valid (contiguous order_key ranges). Nested
//! structure requires messages on ancestor sections as well as the leaf section.

use std::cmp::Ordering;
use std::collections::BTreeMap;

use super::ids::ObjectId;
use super::symbol::SymbolAnchor;

/// Mutable sequence-diagram content: participants, ordered messages, notes, and blocks.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SequenceAst {
    participants: BTreeMap<ObjectId, SequenceParticipant>,
    messages: Vec<SequenceMessage>,
    notes: Vec<SequenceNote>,
    blocks: Vec<SequenceBlock>,
}

impl SequenceAst {
    /// Lifelines keyed by stable participant ids.
    pub fn participants(&self) -> &BTreeMap<ObjectId, SequenceParticipant> {
        &self.participants
    }

    /// Mutable participant map.
    pub fn participants_mut(&mut self) -> &mut BTreeMap<ObjectId, SequenceParticipant> {
        &mut self.participants
    }

    /// Messages in storage order (not necessarily `order_key` order).
    pub fn messages(&self) -> &[SequenceMessage] {
        &self.messages
    }

    /// Mutable message list.
    pub fn messages_mut(&mut self) -> &mut Vec<SequenceMessage> {
        &mut self.messages
    }

    /// Message references in deterministic `(order_key, message_id)` order (export / render).
    pub fn messages_in_order(&self) -> Vec<&SequenceMessage> {
        let mut messages = self.messages.iter().collect::<Vec<_>>();
        messages.sort_by(|a, b| SequenceMessage::cmp_in_order(a, b));
        messages
    }

    /// Top-level notes (sidecar / UI; not Mermaid export).
    pub fn notes(&self) -> &[SequenceNote] {
        &self.notes
    }

    /// Mutable note list.
    pub fn notes_mut(&mut self) -> &mut Vec<SequenceNote> {
        &mut self.notes
    }

    /// Root alt/opt/loop/par blocks (nested children hang off each block).
    pub fn blocks(&self) -> &[SequenceBlock] {
        &self.blocks
    }

    /// Mutable root block list.
    pub fn blocks_mut(&mut self) -> &mut Vec<SequenceBlock> {
        &mut self.blocks
    }

    /// Depth-first lookup of a block by id (including nested).
    pub fn find_block(&self, block_id: &ObjectId) -> Option<&SequenceBlock> {
        fn find<'a>(blocks: &'a [SequenceBlock], block_id: &ObjectId) -> Option<&'a SequenceBlock> {
            for block in blocks {
                if block.block_id() == block_id {
                    return Some(block);
                }
                if let Some(found) = find(block.blocks(), block_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&self.blocks, block_id)
    }

    /// Mutable depth-first block lookup.
    pub fn find_block_mut(&mut self, block_id: &ObjectId) -> Option<&mut SequenceBlock> {
        fn find<'a>(
            blocks: &'a mut [SequenceBlock],
            block_id: &ObjectId,
        ) -> Option<&'a mut SequenceBlock> {
            if let Some(index) = blocks.iter().position(|block| block.block_id() == block_id) {
                return Some(&mut blocks[index]);
            }
            for block in blocks.iter_mut() {
                if let Some(found) = find(block.blocks_mut(), block_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&mut self.blocks, block_id)
    }

    /// Depth-first section lookup across the block tree.
    pub fn find_section(&self, section_id: &ObjectId) -> Option<&SequenceSection> {
        fn find<'a>(
            blocks: &'a [SequenceBlock],
            section_id: &ObjectId,
        ) -> Option<&'a SequenceSection> {
            for block in blocks {
                for section in block.sections() {
                    if section.section_id() == section_id {
                        return Some(section);
                    }
                }
                if let Some(found) = find(block.blocks(), section_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&self.blocks, section_id)
    }

    /// Mutable depth-first section lookup.
    pub fn find_section_mut(&mut self, section_id: &ObjectId) -> Option<&mut SequenceSection> {
        fn find<'a>(
            blocks: &'a mut [SequenceBlock],
            section_id: &ObjectId,
        ) -> Option<&'a mut SequenceSection> {
            for block in blocks.iter_mut() {
                if let Some(index) =
                    block.sections().iter().position(|section| section.section_id() == section_id)
                {
                    return Some(&mut block.sections_mut()[index]);
                }
                if let Some(found) = find(block.blocks_mut(), section_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&mut self.blocks, section_id)
    }

    /// Returns the block that owns `section_id`, if any.
    pub fn find_block_for_section(&self, section_id: &ObjectId) -> Option<&SequenceBlock> {
        fn find<'a>(
            blocks: &'a [SequenceBlock],
            section_id: &ObjectId,
        ) -> Option<&'a SequenceBlock> {
            for block in blocks {
                if block.sections().iter().any(|section| section.section_id() == section_id) {
                    return Some(block);
                }
                if let Some(found) = find(block.blocks(), section_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&self.blocks, section_id)
    }

    /// Mutable owner block for `section_id`.
    pub fn find_block_for_section_mut(
        &mut self,
        section_id: &ObjectId,
    ) -> Option<&mut SequenceBlock> {
        fn find<'a>(
            blocks: &'a mut [SequenceBlock],
            section_id: &ObjectId,
        ) -> Option<&'a mut SequenceBlock> {
            if let Some(index) = blocks.iter().position(|block| {
                block.sections().iter().any(|section| section.section_id() == section_id)
            }) {
                return Some(&mut blocks[index]);
            }
            for block in blocks.iter_mut() {
                if let Some(found) = find(block.blocks_mut(), section_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&mut self.blocks, section_id)
    }

    /// True if any block in the tree uses `block_id`.
    pub fn contains_block_id(&self, block_id: &ObjectId) -> bool {
        self.find_block(block_id).is_some()
    }

    /// True if any section in the tree uses `section_id`.
    pub fn contains_section_id(&self, section_id: &ObjectId) -> bool {
        self.find_section(section_id).is_some()
    }

    /// Nesting depth of `block_id` (root blocks are depth 1). Returns `None` if missing.
    pub fn block_depth(&self, block_id: &ObjectId) -> Option<usize> {
        fn depth_of(blocks: &[SequenceBlock], block_id: &ObjectId, depth: usize) -> Option<usize> {
            for block in blocks {
                if block.block_id() == block_id {
                    return Some(depth);
                }
                if let Some(found) = depth_of(block.blocks(), block_id, depth + 1) {
                    return Some(found);
                }
            }
            None
        }

        depth_of(&self.blocks, block_id, 1)
    }

    /// Parent block id for a nested block, if any.
    pub fn parent_block_id(&self, block_id: &ObjectId) -> Option<ObjectId> {
        fn find(blocks: &[SequenceBlock], block_id: &ObjectId) -> Option<ObjectId> {
            for block in blocks {
                if block.blocks().iter().any(|child| child.block_id() == block_id) {
                    return Some(block.block_id().clone());
                }
                if let Some(found) = find(block.blocks(), block_id) {
                    return Some(found);
                }
            }
            None
        }

        find(&self.blocks, block_id)
    }

    /// Chain of block ids from root to `block_id` inclusive. Empty if missing.
    pub fn block_ancestor_chain(&self, block_id: &ObjectId) -> Vec<ObjectId> {
        fn find(blocks: &[SequenceBlock], block_id: &ObjectId, path: &mut Vec<ObjectId>) -> bool {
            for block in blocks {
                path.push(block.block_id().clone());
                if block.block_id() == block_id {
                    return true;
                }
                if find(block.blocks(), block_id, path) {
                    return true;
                }
                path.pop();
            }
            false
        }

        let mut path = Vec::new();
        if find(&self.blocks, block_id, &mut path) {
            path
        } else {
            Vec::new()
        }
    }

    /// All section ids that currently list `message_id`.
    pub fn sections_containing_message(&self, message_id: &ObjectId) -> Vec<ObjectId> {
        fn walk(blocks: &[SequenceBlock], message_id: &ObjectId, out: &mut Vec<ObjectId>) {
            for block in blocks {
                for section in block.sections() {
                    if section.message_ids().contains(message_id) {
                        out.push(section.section_id().clone());
                    }
                }
                walk(block.blocks(), message_id, out);
            }
        }

        let mut out = Vec::new();
        walk(&self.blocks, message_id, &mut out);
        out
    }

    /// Collect every message id referenced by `block` and its nested descendants.
    pub fn collect_block_message_ids(&self, block_id: &ObjectId) -> Vec<ObjectId> {
        let Some(block) = self.find_block(block_id) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        fn walk(block: &SequenceBlock, out: &mut Vec<ObjectId>) {
            for section in block.sections() {
                for message_id in section.message_ids() {
                    if !out.contains(message_id) {
                        out.push(message_id.clone());
                    }
                }
            }
            for child in block.blocks() {
                walk(child, out);
            }
        }
        walk(block, &mut out);
        out
    }

    /// Removes the block (and nested children) from the tree. Messages are not removed.
    ///
    /// Returns the removed block when found.
    pub fn remove_block(&mut self, block_id: &ObjectId) -> Option<SequenceBlock> {
        fn remove_from(
            blocks: &mut Vec<SequenceBlock>,
            block_id: &ObjectId,
        ) -> Option<SequenceBlock> {
            if let Some(index) = blocks.iter().position(|block| block.block_id() == block_id) {
                return Some(blocks.remove(index));
            }
            for block in blocks.iter_mut() {
                if let Some(removed) = remove_from(block.blocks_mut(), block_id) {
                    return Some(removed);
                }
            }
            None
        }

        remove_from(&mut self.blocks, block_id)
    }

    /// Removes `message_id` from every section in the tree. Returns how many memberships were cleared.
    pub fn detach_message_from_all_sections(&mut self, message_id: &ObjectId) -> usize {
        fn detach(blocks: &mut [SequenceBlock], message_id: &ObjectId) -> usize {
            let mut removed = 0usize;
            for block in blocks {
                for section in block.sections_mut() {
                    let before = section.message_ids().len();
                    section.message_ids_mut().retain(|id| id != message_id);
                    removed =
                        removed.saturating_add(before.saturating_sub(section.message_ids().len()));
                }
                removed = removed.saturating_add(detach(block.blocks_mut(), message_id));
            }
            removed
        }

        detach(&mut self.blocks, message_id)
    }

    /// Collects every block id in pre-order (parents before nested children).
    pub fn collect_block_ids(&self) -> Vec<ObjectId> {
        fn walk(blocks: &[SequenceBlock], out: &mut Vec<ObjectId>) {
            for block in blocks {
                out.push(block.block_id().clone());
                walk(block.blocks(), out);
            }
        }

        let mut out = Vec::new();
        walk(&self.blocks, &mut out);
        out
    }

    /// Collects every section id in pre-order (block sections, then nested blocks).
    pub fn collect_section_ids(&self) -> Vec<ObjectId> {
        fn walk(blocks: &[SequenceBlock], out: &mut Vec<ObjectId>) {
            for block in blocks {
                for section in block.sections() {
                    out.push(section.section_id().clone());
                }
                walk(block.blocks(), out);
            }
        }

        let mut out = Vec::new();
        walk(&self.blocks, &mut out);
        out
    }
}

/// Sequence lifeline with Mermaid name, optional role alias, note, and symbol anchor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceParticipant {
    mermaid_name: String,
    role: Option<String>,
    note: Option<String>,
    symbol: Option<SymbolAnchor>,
}

impl SequenceParticipant {
    /// Lifeline with Mermaid participant name only.
    pub fn new(mermaid_name: impl Into<String>) -> Self {
        Self { mermaid_name: mermaid_name.into(), role: None, note: None, symbol: None }
    }

    /// Set the Mermaid-facing participant name (export identity).
    pub fn set_mermaid_name(&mut self, mermaid_name: impl Into<String>) {
        self.mermaid_name = mermaid_name.into();
    }

    /// Set optional role keyword used in export (`actor Alice`, …).
    pub fn set_role<T: Into<String>>(&mut self, role: Option<T>) {
        self.role = role.map(Into::into);
    }

    /// Sidecar/UI note; not part of Mermaid export.
    pub fn set_note<T: Into<String>>(&mut self, note: Option<T>) {
        self.note = note.map(Into::into);
    }

    /// Attach or clear a Frigg symbol anchor (sidecar).
    pub fn set_symbol(&mut self, symbol: Option<SymbolAnchor>) {
        self.symbol = symbol;
    }

    /// Mermaid participant name.
    pub fn mermaid_name(&self) -> &str {
        &self.mermaid_name
    }

    /// Optional role keyword for export.
    pub fn role(&self) -> Option<&str> {
        self.role.as_deref()
    }

    /// Sidecar/UI note text.
    pub fn note(&self) -> Option<&str> {
        self.note.as_deref()
    }

    /// Optional Frigg symbol anchor.
    pub fn symbol(&self) -> Option<&SymbolAnchor> {
        self.symbol.as_ref()
    }
}

/// Mermaid fragment kind for alt / opt / loop / par blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SequenceBlockKind {
    Alt,
    Opt,
    Loop,
    Par,
}

/// Nested control-flow region: sections (main/else/and) plus child blocks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceBlock {
    block_id: ObjectId,
    kind: SequenceBlockKind,
    header: Option<String>,
    sections: Vec<SequenceSection>,
    blocks: Vec<SequenceBlock>,
}

impl SequenceBlock {
    /// Deterministic parse-time id: `b:NNNN`.
    pub fn make_block_id(block_index: usize) -> ObjectId {
        ObjectId::new(format!("b:{block_index:04}")).expect("valid block id")
    }

    /// Assemble a block with its sections and nested children.
    pub fn new(
        block_id: ObjectId,
        kind: SequenceBlockKind,
        header: Option<String>,
        sections: Vec<SequenceSection>,
        blocks: Vec<SequenceBlock>,
    ) -> Self {
        Self { block_id, kind, header, sections, blocks }
    }

    /// Stable block id (`seq/block` category).
    pub fn block_id(&self) -> &ObjectId {
        &self.block_id
    }

    /// Alt / opt / loop / par discriminant.
    pub fn kind(&self) -> SequenceBlockKind {
        self.kind
    }

    /// Optional header text on the opening keyword line.
    pub fn header(&self) -> Option<&str> {
        self.header.as_deref()
    }

    /// Set or clear the opening header.
    pub fn set_header<T: Into<String>>(&mut self, header: Option<T>) {
        self.header = header.map(Into::into);
    }

    /// Main / else / and sections for this block.
    pub fn sections(&self) -> &[SequenceSection] {
        &self.sections
    }

    /// Mutable sections list.
    pub fn sections_mut(&mut self) -> &mut Vec<SequenceSection> {
        &mut self.sections
    }

    /// Nested child blocks.
    pub fn blocks(&self) -> &[SequenceBlock] {
        &self.blocks
    }

    /// Mutable nested blocks.
    pub fn blocks_mut(&mut self) -> &mut Vec<SequenceBlock> {
        &mut self.blocks
    }
}

/// Section role inside a [`SequenceBlock`] (main branch, `else`, or `and`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SequenceSectionKind {
    Main,
    Else,
    And,
}

/// One branch of a sequence block, listing member message ids.
///
/// Nested export validity requires a message appear on every ancestor section as well as the leaf.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceSection {
    section_id: ObjectId,
    kind: SequenceSectionKind,
    header: Option<String>,
    message_ids: Vec<ObjectId>,
}

impl SequenceSection {
    /// Deterministic parse-time id: `sec:BBBB:SS`.
    pub fn make_section_id(block_index: usize, section_index: usize) -> ObjectId {
        ObjectId::new(format!("sec:{block_index:04}:{section_index:02}")).expect("valid section id")
    }

    /// Assemble a section with optional header and message membership.
    pub fn new(
        section_id: ObjectId,
        kind: SequenceSectionKind,
        header: Option<String>,
        message_ids: Vec<ObjectId>,
    ) -> Self {
        Self { section_id, kind, header, message_ids }
    }

    /// Stable section id (`seq/section` category).
    pub fn section_id(&self) -> &ObjectId {
        &self.section_id
    }

    /// Main / else / and discriminant.
    pub fn kind(&self) -> SequenceSectionKind {
        self.kind
    }

    /// Optional branch header (`else miss`, …).
    pub fn header(&self) -> Option<&str> {
        self.header.as_deref()
    }

    /// Set or clear the branch header.
    pub fn set_header<T: Into<String>>(&mut self, header: Option<T>) {
        self.header = header.map(Into::into);
    }

    /// Message ids claimed by this section (must stay contiguous in `order_key` for export).
    pub fn message_ids(&self) -> &[ObjectId] {
        &self.message_ids
    }

    /// Mutable membership list.
    pub fn message_ids_mut(&mut self) -> &mut Vec<ObjectId> {
        &mut self.message_ids
    }
}

/// Semantic message arrow class after Mermaid arrow normalization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SequenceMessageKind {
    Sync,
    Async,
    Return,
}

/// Directed message between participants with stable id and ordering key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceMessage {
    message_id: ObjectId,
    from_participant_id: ObjectId,
    to_participant_id: ObjectId,
    kind: SequenceMessageKind,
    raw_arrow: Option<String>,
    text: String,
    order_key: i64,
}

impl SequenceMessage {
    /// Create without a raw Mermaid arrow (export falls back to kind defaults).
    pub fn new(
        message_id: ObjectId,
        from_participant_id: ObjectId,
        to_participant_id: ObjectId,
        kind: SequenceMessageKind,
        text: impl Into<String>,
        order_key: i64,
    ) -> Self {
        Self {
            message_id,
            from_participant_id,
            to_participant_id,
            kind,
            raw_arrow: None,
            text: text.into(),
            order_key,
        }
    }

    /// Preserve the original Mermaid arrow token for lossless export.
    pub fn set_raw_arrow<T: Into<String>>(&mut self, raw_arrow: Option<T>) {
        self.raw_arrow = raw_arrow.map(Into::into);
    }

    /// Stable message id (`seq/message` category).
    pub fn message_id(&self) -> &ObjectId {
        &self.message_id
    }

    /// Source participant id.
    pub fn from_participant_id(&self) -> &ObjectId {
        &self.from_participant_id
    }

    /// Target participant id.
    pub fn to_participant_id(&self) -> &ObjectId {
        &self.to_participant_id
    }

    /// Sync / async / return classification.
    pub fn kind(&self) -> SequenceMessageKind {
        self.kind
    }

    /// Original Mermaid arrow when known.
    pub fn raw_arrow(&self) -> Option<&str> {
        self.raw_arrow.as_deref()
    }

    /// Message label text.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Sort key for vertical order; ties break on `message_id`.
    pub fn order_key(&self) -> i64 {
        self.order_key
    }

    /// Total order used by export and render: `(order_key, message_id)`.
    pub fn cmp_in_order(a: &Self, b: &Self) -> Ordering {
        a.order_key.cmp(&b.order_key).then_with(|| a.message_id.cmp(&b.message_id))
    }
}

/// Free-floating note attached to the diagram (sidecar / UI; not Mermaid `Note over`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SequenceNote {
    note_id: ObjectId,
    text: String,
}

impl SequenceNote {
    /// Note with stable id and body text.
    pub fn new(note_id: ObjectId, text: impl Into<String>) -> Self {
        Self { note_id, text: text.into() }
    }

    /// Stable note id.
    pub fn note_id(&self) -> &ObjectId {
        &self.note_id
    }

    /// Note body.
    pub fn text(&self) -> &str {
        &self.text
    }
}

#[cfg(test)]
mod tests {
    use super::{
        SequenceAst, SequenceBlock, SequenceBlockKind, SequenceParticipant, SequenceSection,
        SequenceSectionKind,
    };
    use crate::model::ids::ObjectId;

    #[test]
    fn sequence_participant_can_be_updated_in_place() {
        let mut participant = SequenceParticipant::new("Alice");
        assert_eq!(participant.mermaid_name(), "Alice");
        assert_eq!(participant.role(), None);
        assert_eq!(participant.note(), None);

        participant.set_role(Some("actor"));
        assert_eq!(participant.role(), Some("actor"));

        participant.set_mermaid_name("Alice2");
        assert_eq!(participant.mermaid_name(), "Alice2");
        assert_eq!(participant.role(), Some("actor"));

        participant.set_note(Some("invariant"));
        assert_eq!(participant.note(), Some("invariant"));

        participant.set_role::<&str>(None);
        assert_eq!(participant.role(), None);

        participant.set_note::<&str>(None);
        assert_eq!(participant.note(), None);
    }

    #[test]
    fn sequence_block_and_section_ids_are_allocated_deterministically() {
        assert_eq!(SequenceBlock::make_block_id(1).as_str(), "b:0001");
        assert_eq!(SequenceSection::make_section_id(1, 0).as_str(), "sec:0001:00");
    }

    fn oid(raw: &str) -> ObjectId {
        ObjectId::new(raw.to_owned()).expect("valid object id")
    }

    fn sample_nested_ast() -> SequenceAst {
        let mut ast = SequenceAst::default();
        let nested = SequenceBlock::new(
            oid("b:nested"),
            SequenceBlockKind::Opt,
            Some("warm".to_owned()),
            vec![SequenceSection::new(
                oid("sec:nested:main"),
                SequenceSectionKind::Main,
                None,
                vec![oid("m:2")],
            )],
            Vec::new(),
        );
        let root = SequenceBlock::new(
            oid("b:root"),
            SequenceBlockKind::Alt,
            Some("hit".to_owned()),
            vec![
                SequenceSection::new(
                    oid("sec:root:main"),
                    SequenceSectionKind::Main,
                    None,
                    vec![oid("m:1"), oid("m:2")],
                ),
                SequenceSection::new(
                    oid("sec:root:else"),
                    SequenceSectionKind::Else,
                    Some("miss".to_owned()),
                    vec![oid("m:3")],
                ),
            ],
            vec![nested],
        );
        ast.blocks_mut().push(root);
        ast
    }

    #[test]
    fn find_block_mut_and_find_section_mut_update_nested_tree() {
        let mut ast = sample_nested_ast();

        ast.find_block_mut(&oid("b:nested")).expect("nested block").set_header(Some("warm-cache"));
        assert_eq!(ast.find_block(&oid("b:nested")).expect("nested").header(), Some("warm-cache"));

        ast.find_section_mut(&oid("sec:root:else"))
            .expect("else section")
            .set_header(Some("cache-miss"));
        assert_eq!(
            ast.find_section(&oid("sec:root:else")).expect("else").header(),
            Some("cache-miss")
        );

        assert_eq!(
            ast.find_block_for_section(&oid("sec:root:else")).expect("owner").block_id().as_str(),
            "b:root"
        );
        assert_eq!(ast.block_depth(&oid("b:root")), Some(1));
        assert_eq!(ast.block_depth(&oid("b:nested")), Some(2));
        assert!(ast.contains_block_id(&oid("b:nested")));
        assert!(ast.contains_section_id(&oid("sec:nested:main")));
    }

    #[test]
    fn detach_message_from_all_sections_clears_memberships() {
        let mut ast = sample_nested_ast();
        let removed = ast.detach_message_from_all_sections(&oid("m:2"));
        assert_eq!(removed, 2);
        assert!(!ast
            .find_section(&oid("sec:root:main"))
            .expect("main")
            .message_ids()
            .contains(&oid("m:2")));
        assert!(!ast
            .find_section(&oid("sec:nested:main"))
            .expect("nested main")
            .message_ids()
            .contains(&oid("m:2")));
        assert!(ast
            .find_section(&oid("sec:root:else"))
            .expect("else")
            .message_ids()
            .contains(&oid("m:3")));
    }

    #[test]
    fn remove_block_keeps_sibling_structure_and_messages_lists() {
        let mut ast = sample_nested_ast();
        let removed = ast.remove_block(&oid("b:nested")).expect("removed nested");
        assert_eq!(removed.block_id().as_str(), "b:nested");
        assert!(!ast.contains_block_id(&oid("b:nested")));
        assert!(ast.contains_block_id(&oid("b:root")));
        assert_eq!(
            ast.find_section(&oid("sec:root:main")).expect("main").message_ids(),
            &[oid("m:1"), oid("m:2")]
        );
        assert_eq!(
            ast.collect_block_ids().iter().map(ObjectId::as_str).collect::<Vec<_>>(),
            vec!["b:root"]
        );
        assert_eq!(
            ast.collect_section_ids().iter().map(ObjectId::as_str).collect::<Vec<_>>(),
            vec!["sec:root:main", "sec:root:else"]
        );
    }
}