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
// 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.

//! Revision-gated diagram mutations and change deltas (optimistic concurrency).
//!
//! Agents and the TUI edit through typed ops (`SeqOp`, `FlowOp`) applied with a `base_rev`
//! OCC check against `diagram.rev()`. Successful batches bump the revision and return a
//! coarse `Delta` of added/removed/updated `ObjectRef`s for UI refresh and MCP `diagram_diff`.
//! Batches are all-or-nothing on a cloned AST; sequence structure must remain Mermaid-export
//! valid (contiguous section membership; nested messages also on ancestor sections).

use std::collections::HashSet;
use std::fmt;

use crate::format::mermaid::flowchart::MermaidIdentError;
use crate::model::seq_ast::{
    SequenceBlock, SequenceBlockKind, SequenceSection, SequenceSectionKind,
};
use crate::model::{
    CategoryPath, Diagram, DiagramAst, DiagramId, DiagramKind, FlowEdge, FlowNode, FlowchartAst,
};
use crate::model::{ObjectId, ObjectRef, SequenceAst, SequenceMessage, SequenceMessageKind};
use crate::model::{SequenceParticipant, SymbolAnchor, SymbolAnchorError, XRefId};

/// Maximum nested block depth, matching the sequence Mermaid parser.
pub const MAX_SEQ_BLOCK_NEST_DEPTH: usize = 8;

/// Kind-tagged diagram mutation (sequence, flowchart, or unsupported xref batch).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op {
    Seq(SeqOp),
    Flow(FlowOp),
    XRef(XRefOp),
}

/// Sequence-diagram mutation: participants, messages, blocks, sections, membership.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SeqOp {
    AddParticipant {
        participant_id: ObjectId,
        mermaid_name: String,
    },
    UpdateParticipant {
        participant_id: ObjectId,
        patch: SeqParticipantPatch,
    },
    SetParticipantNote {
        participant_id: ObjectId,
        note: Option<String>,
    },
    SetParticipantSymbol {
        participant_id: ObjectId,
        symbol: Option<SymbolAnchor>,
    },
    RemoveParticipant {
        participant_id: ObjectId,
    },
    AddMessage {
        message_id: ObjectId,
        from_participant_id: ObjectId,
        to_participant_id: ObjectId,
        kind: SequenceMessageKind,
        arrow: Option<String>,
        text: String,
        order_key: i64,
        /// When set, attach the new message to this section after creation.
        section_id: Option<ObjectId>,
    },
    UpdateMessage {
        message_id: ObjectId,
        patch: SeqMessagePatch,
    },
    RemoveMessage {
        message_id: ObjectId,
    },
    /// Attach, move, or detach a message's block-section membership.
    ///
    /// `section_id: None` detaches the message from every section.
    SetMessageSection {
        message_id: ObjectId,
        section_id: Option<ObjectId>,
    },
    AddBlock {
        block_id: ObjectId,
        kind: SequenceBlockKind,
        header: Option<String>,
        parent_block_id: Option<ObjectId>,
        main_section_id: ObjectId,
    },
    UpdateBlock {
        block_id: ObjectId,
        patch: SeqBlockPatch,
    },
    RemoveBlock {
        block_id: ObjectId,
    },
    AddSection {
        section_id: ObjectId,
        block_id: ObjectId,
        kind: SequenceSectionKind,
        header: Option<String>,
    },
    UpdateSection {
        section_id: ObjectId,
        patch: SeqSectionPatch,
    },
    RemoveSection {
        section_id: ObjectId,
    },
}

/// Partial update for a sequence block header (`Some(None)` clears).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SeqBlockPatch {
    pub header: Option<Option<String>>,
}

/// Partial update for a sequence section header (`Some(None)` clears).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SeqSectionPatch {
    pub header: Option<Option<String>>,
}

/// Partial update for a sequence participant.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SeqParticipantPatch {
    pub mermaid_name: Option<String>,
}

/// Partial update for a sequence message.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SeqMessagePatch {
    pub from_participant_id: Option<ObjectId>,
    pub to_participant_id: Option<ObjectId>,
    pub kind: Option<SequenceMessageKind>,
    pub arrow: Option<String>,
    pub text: Option<String>,
    pub order_key: Option<i64>,
}

/// Flowchart mutation: nodes, edges, notes, and Frigg symbol anchors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlowOp {
    AddNode {
        node_id: ObjectId,
        label: String,
        shape: Option<String>,
    },
    UpdateNode {
        node_id: ObjectId,
        patch: FlowNodePatch,
    },
    SetNodeMermaidId {
        node_id: ObjectId,
        mermaid_id: Option<String>,
    },
    SetNodeNote {
        node_id: ObjectId,
        note: Option<String>,
    },
    SetNodeSymbol {
        node_id: ObjectId,
        symbol: Option<SymbolAnchor>,
    },
    RemoveNode {
        node_id: ObjectId,
    },
    AddEdge {
        edge_id: ObjectId,
        from_node_id: ObjectId,
        to_node_id: ObjectId,
        label: Option<String>,
        connector: Option<String>,
        style: Option<String>,
    },
    UpdateEdge {
        edge_id: ObjectId,
        patch: FlowEdgePatch,
    },
    RemoveEdge {
        edge_id: ObjectId,
    },
}

/// Partial update for a flow node.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FlowNodePatch {
    pub label: Option<String>,
    pub shape: Option<String>,
}

/// Partial update for a flow edge.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FlowEdgePatch {
    pub from_node_id: Option<ObjectId>,
    pub to_node_id: Option<ObjectId>,
    pub label: Option<String>,
    pub connector: Option<String>,
    pub style: Option<String>,
}

/// Session-level xref mutation (not applied via `apply_ops` today; MCP uses dedicated tools).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum XRefOp {
    Add { xref_id: XRefId, from: ObjectRef, to: ObjectRef, kind: String, label: Option<String> },
    Remove { xref_id: XRefId },
}

/// Outcome of a successful `apply_ops` batch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApplyResult {
    pub new_rev: u64,
    pub applied: usize,
    pub delta: Delta,
}

/// Coarse object-level change set from an op batch (added / removed / updated `ObjectRef`s).
///
/// Net effect after collapsing intermediate states within the same batch (e.g. add-then-remove
/// cancels out; update of an already-added ref stays in `added` only).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Delta {
    pub added: Vec<ObjectRef>,
    pub removed: Vec<ObjectRef>,
    pub updated: Vec<ObjectRef>,
}

/// Collapses per-op `ObjectRef` events into a net [`Delta`] for one batch.
#[derive(Debug, Default)]
struct DeltaBuilder {
    added: HashSet<ObjectRef>,
    removed: HashSet<ObjectRef>,
    updated: HashSet<ObjectRef>,
}

impl DeltaBuilder {
    fn record_added(&mut self, object_ref: ObjectRef) {
        self.removed.remove(&object_ref);
        self.updated.remove(&object_ref);
        self.added.insert(object_ref);
    }

    fn record_removed(&mut self, object_ref: ObjectRef) {
        self.added.remove(&object_ref);
        self.updated.remove(&object_ref);
        self.removed.insert(object_ref);
    }

    fn record_updated(&mut self, object_ref: ObjectRef) {
        // Already added or removed in this batch: keep the stronger lifecycle event.
        if self.added.contains(&object_ref) || self.removed.contains(&object_ref) {
            return;
        }
        self.updated.insert(object_ref);
    }

    fn finish(self) -> Delta {
        let mut added = self.added.into_iter().collect::<Vec<_>>();
        let mut removed = self.removed.into_iter().collect::<Vec<_>>();
        let mut updated = self.updated.into_iter().collect::<Vec<_>>();

        sort_object_refs(&mut added);
        sort_object_refs(&mut removed);
        sort_object_refs(&mut updated);

        Delta { added, removed, updated }
    }
}

fn sort_object_refs(refs: &mut [ObjectRef]) {
    refs.sort_by(|a, b| {
        a.diagram_id()
            .cmp(b.diagram_id())
            .then_with(|| a.category().cmp(b.category()))
            .then_with(|| a.object_id().cmp(b.object_id()))
    });
}

/// Apply ops under OCC if `base_rev` matches `diagram.rev()`, then bump revision once.
///
/// Empty `ops` is a no-op that keeps the current revision. `Op::XRef` is rejected; session
/// xrefs use dedicated MCP tools. Sequence batches re-validate block structure via export.
///
/// # Errors
///
/// [`ApplyError::Conflict`] on stale `base_rev`; also kind mismatches, missing/duplicate ids,
/// invalid Mermaid identifiers/message text, or export-invalid sequence structure after the batch.
pub fn apply_ops(
    diagram: &mut Diagram,
    base_rev: u64,
    ops: &[Op],
) -> Result<ApplyResult, ApplyError> {
    let current_rev = diagram.rev();
    if base_rev != current_rev {
        return Err(ApplyError::Conflict { base_rev, current_rev });
    }

    if ops.is_empty() {
        return Ok(ApplyResult { new_rev: current_rev, applied: 0, delta: Delta::default() });
    }

    let mut new_ast = diagram.ast().clone();
    let diagram_id = diagram.diagram_id().clone();
    let mut delta = DeltaBuilder::default();

    for op in ops {
        match op {
            Op::Seq(seq_op) => {
                let DiagramAst::Sequence(ast) = &mut new_ast else {
                    return Err(ApplyError::KindMismatch {
                        diagram_kind: diagram.kind(),
                        op_kind: OpKind::Seq,
                    });
                };
                apply_seq_op(&diagram_id, ast, seq_op, &mut delta)?;
            }
            Op::Flow(flow_op) => {
                let DiagramAst::Flowchart(ast) = &mut new_ast else {
                    return Err(ApplyError::KindMismatch {
                        diagram_kind: diagram.kind(),
                        op_kind: OpKind::Flow,
                    });
                };
                apply_flow_op(&diagram_id, ast, flow_op, &mut delta)?;
            }
            Op::XRef(_) => {
                return Err(ApplyError::UnsupportedOp { op_kind: OpKind::XRef });
            }
        }
    }

    if let DiagramAst::Sequence(ast) = &new_ast {
        validate_sequence_block_structure(ast)?;
    }

    diagram.set_ast(new_ast).map_err(|mismatch| {
        let op_kind = match mismatch.found() {
            DiagramKind::Sequence => OpKind::Seq,
            DiagramKind::Flowchart | DiagramKind::Class | DiagramKind::Er | DiagramKind::Gantt => {
                OpKind::Flow
            }
        };
        ApplyError::KindMismatch { diagram_kind: mismatch.expected(), op_kind }
    })?;
    diagram.bump_rev();
    let new_rev = diagram.rev();

    Ok(ApplyResult { new_rev, applied: ops.len(), delta: delta.finish() })
}

/// High-level op family used in kind-mismatch errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpKind {
    Seq,
    Flow,
    XRef,
}

/// Object category for existence / uniqueness errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectKind {
    SeqParticipant,
    SeqMessage,
    SeqBlock,
    SeqSection,
    FlowNode,
    FlowEdge,
}

/// Failures from [`apply_ops`]: OCC conflicts, missing ids, structure, identifiers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplyError {
    /// OCC rejection: caller's `base_rev` does not match `diagram.rev()`.
    Conflict {
        base_rev: u64,
        current_rev: u64,
    },
    /// Op family does not match the diagram AST kind (e.g. `SeqOp` on flowchart).
    KindMismatch {
        diagram_kind: DiagramKind,
        op_kind: OpKind,
    },
    /// Op family not applied through this path (currently `XRef`).
    UnsupportedOp {
        op_kind: OpKind,
    },
    AlreadyExists {
        kind: ObjectKind,
        object_id: ObjectId,
    },
    NotFound {
        kind: ObjectKind,
        object_id: ObjectId,
    },
    /// Edge endpoint references a node id absent from the flowchart AST.
    MissingFlowNode {
        node_id: ObjectId,
    },
    InvalidSeqParticipantMermaidName {
        mermaid_name: String,
        reason: MermaidIdentError,
    },
    DuplicateSeqParticipantMermaidName {
        mermaid_name: String,
        participant_id: ObjectId,
    },
    InvalidFlowNodeMermaidId {
        mermaid_id: String,
        reason: MermaidIdentError,
    },
    DuplicateFlowNodeMermaidId {
        mermaid_id: String,
        node_id: ObjectId,
    },
    InvalidSymbolAnchor {
        source: SymbolAnchorError,
    },
    InvalidSeqSectionKind {
        block_id: ObjectId,
        block_kind: SequenceBlockKind,
        section_kind: SequenceSectionKind,
    },
    InvalidSeqSectionNotEmpty {
        section_id: ObjectId,
    },
    InvalidSeqSectionIsMain {
        section_id: ObjectId,
    },
    InvalidSeqBlockNesting {
        block_id: ObjectId,
        reason: String,
    },
    InvalidSeqBlockStructure {
        reason: String,
    },
    /// Empty or whitespace-only sequence message text (parser would reject on reload).
    InvalidSeqMessageText {
        text: String,
    },
}

impl fmt::Display for ApplyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Conflict { base_rev, current_rev } => {
                write!(f, "stale base_rev (base_rev={base_rev}, current_rev={current_rev})")
            }
            Self::KindMismatch { diagram_kind, op_kind } => {
                write!(f, "op kind mismatch (diagram_kind={diagram_kind:?}, op_kind={op_kind:?})")
            }
            Self::UnsupportedOp { op_kind } => write!(f, "unsupported op kind ({op_kind:?})"),
            Self::AlreadyExists { kind, object_id } => {
                write!(f, "object already exists ({kind:?}, id={object_id})")
            }
            Self::NotFound { kind, object_id } => {
                write!(f, "object not found ({kind:?}, id={object_id})")
            }
            Self::MissingFlowNode { node_id } => write!(f, "flow node not found (id={node_id})"),
            Self::InvalidSeqParticipantMermaidName { mermaid_name, reason } => {
                write!(f, "invalid sequence participant Mermaid name '{mermaid_name}': {reason}")
            }
            Self::DuplicateSeqParticipantMermaidName { mermaid_name, participant_id } => {
                write!(
                    f,
                    "sequence participant Mermaid name '{mermaid_name}' is already used by participant {participant_id}"
                )
            }
            Self::InvalidFlowNodeMermaidId { mermaid_id, reason } => {
                write!(f, "invalid flow node Mermaid id '{mermaid_id}': {reason}")
            }
            Self::DuplicateFlowNodeMermaidId { mermaid_id, node_id } => {
                write!(f, "flow node Mermaid id '{mermaid_id}' is already used by node {node_id}")
            }
            Self::InvalidSymbolAnchor { source } => write!(f, "{source}"),
            Self::InvalidSeqSectionKind { block_id, block_kind, section_kind } => write!(
                f,
                "section kind {section_kind:?} is not valid under block {block_id} ({block_kind:?})"
            ),
            Self::InvalidSeqSectionNotEmpty { section_id } => write!(
                f,
                "section {section_id} still has messages; detach them before removing the section"
            ),
            Self::InvalidSeqSectionIsMain { section_id } => {
                write!(f, "cannot remove main section {section_id}")
            }
            Self::InvalidSeqBlockNesting { block_id, reason } => {
                write!(f, "invalid block nesting for {block_id}: {reason}")
            }
            Self::InvalidSeqBlockStructure { reason } => {
                write!(
                    f,
                    "invalid sequence block structure: {reason} (section messages must be contiguous in order_key order; nested messages must also belong to ancestor sections)"
                )
            }
            Self::InvalidSeqMessageText { text } => {
                write!(f, "sequence message text must be non-empty (got {text:?})")
            }
        }
    }
}

impl std::error::Error for ApplyError {}

include!("ops_impl.rs");

#[cfg(test)]
mod tests;