kanban-domain 0.7.0

Domain models and business logic for the kanban project management tool
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
use super::{Command, CommandContext};
use crate::data_store::DataStore;
use crate::field_update::FieldUpdate;
use crate::KanbanResult;
use crate::{ArchivedCard, Board, Card, Column, DependencyGraph, KanbanError, Sprint};
use kanban_core::Editable;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum BoardCommand {
    Create(CreateBoard),
    Update(UpdateBoard),
    SetTaskSort(SetBoardTaskSort),
    SetTaskListView(SetBoardTaskListView),
    Delete(DeleteBoard),
    ApplySettings(ApplyBoardSettings),
    Import(ImportEntities),
    /// Internal: replace a board's sprint-name pool wholesale. Used by
    /// `UpdateSprint`'s inverse to restore the pool that name allocation
    /// mutated. Not a user-facing command — accessed only via the
    /// inverse-capture path.
    RestoreSprintPool(RestoreSprintPool),
}

impl BoardCommand {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        match self {
            BoardCommand::Create(c) => c.execute(context),
            BoardCommand::Update(c) => c.execute(context),
            BoardCommand::SetTaskSort(c) => c.execute(context),
            BoardCommand::SetTaskListView(c) => c.execute(context),
            BoardCommand::Delete(c) => c.execute(context),
            BoardCommand::ApplySettings(c) => c.execute(context),
            BoardCommand::Import(c) => c.execute(context),
            BoardCommand::RestoreSprintPool(c) => c.execute(context),
        }
    }

    pub fn description(&self) -> String {
        match self {
            BoardCommand::Create(c) => c.description(),
            BoardCommand::Update(c) => c.description(),
            BoardCommand::SetTaskSort(c) => c.description(),
            BoardCommand::SetTaskListView(c) => c.description(),
            BoardCommand::Delete(c) => c.description(),
            BoardCommand::ApplySettings(c) => c.description(),
            BoardCommand::Import(c) => c.description(),
            BoardCommand::RestoreSprintPool(c) => c.description(),
        }
    }

    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        match self {
            BoardCommand::Create(c) => c.capture_inverse(store),
            BoardCommand::Update(c) => c.capture_inverse(store),
            BoardCommand::SetTaskSort(c) => c.capture_inverse(store),
            BoardCommand::SetTaskListView(c) => c.capture_inverse(store),
            BoardCommand::ApplySettings(c) => c.capture_inverse(store),
            BoardCommand::Delete(c) => c.capture_inverse(store),
            BoardCommand::Import(c) => c.capture_inverse(store),
            BoardCommand::RestoreSprintPool(c) => c.capture_inverse(store),
        }
    }
}

/// Internal — replace a board's sprint-name pool and used-count
/// wholesale. Emitted by `UpdateSprint::capture_inverse` to restore
/// pool state that the forward command's name allocation mutated.
///
/// Not exposed to user-facing CLI/MCP commands. `capture_inverse`
/// rejects top-level execute (the command is synthetic-only).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RestoreSprintPool {
    pub board_id: Uuid,
    pub sprint_names: Vec<String>,
    pub sprint_name_used_count: usize,
}

impl RestoreSprintPool {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = context.get_board(self.board_id)?;
        board.sprint_names = self.sprint_names.clone();
        board.sprint_name_used_count = self.sprint_name_used_count;
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Restore sprint-name pool for board {}", self.board_id)
    }

    pub fn capture_inverse(&self, _store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        Err(KanbanError::Internal(format!(
            "RestoreSprintPool is a synthetic command — it must only appear inside an inverse batch (UpdateSprint undo), never as a top-level forward command. Board id: {}",
            self.board_id
        )))
    }
}

/// Create a new board
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateBoard {
    pub id: Uuid,
    pub name: String,
    pub card_prefix: Option<String>,
    #[serde(default)]
    pub position: i32,
}

impl CreateBoard {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = Board::new(self.name.clone(), self.card_prefix.clone());
        board.id = self.id;
        board.position = self.position;
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Create board: '{}'", self.name)
    }

    /// Inverse: delete the newly-created board. The `id` is already in the
    /// command, so no pre-state read from the store is required — `_store`
    /// is unused.
    pub fn capture_inverse(&self, _store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        Ok(vec![Command::Board(BoardCommand::Delete(DeleteBoard {
            board_id: self.id,
        }))])
    }
}

/// Update board properties (name, description, prefixes, sort options, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateBoard {
    pub board_id: Uuid,
    pub updates: crate::BoardUpdate,
}

impl UpdateBoard {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = context.get_board(self.board_id)?;
        if !matches!(self.updates.card_prefix, FieldUpdate::NoChange) && board.card_counter > 1 {
            return Err(KanbanError::validation(
                "board card_prefix cannot be changed after cards have been created",
            ));
        }
        board.update(self.updates.clone());
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        "Update board".to_string()
    }

    /// Inverse: read the board's current state and build a BoardUpdate
    /// that reverses every field the forward command touched.
    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let board = match store.get_board(self.board_id)? {
            Some(b) => b,
            None => return Err(KanbanError::not_found("Board", self.board_id)),
        };
        let upd = &self.updates;
        let inverse = crate::BoardUpdate {
            name: upd.name.as_ref().map(|_| board.name.clone()),
            description: match upd.description {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.description {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            sprint_prefix: match upd.sprint_prefix {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.sprint_prefix {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            card_prefix: match upd.card_prefix {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.card_prefix {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            task_sort_field: upd.task_sort_field.map(|_| board.task_sort_field),
            task_sort_order: upd.task_sort_order.map(|_| board.task_sort_order),
            sprint_duration_days: match upd.sprint_duration_days {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.sprint_duration_days {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            task_list_view: upd.task_list_view.map(|_| board.task_list_view),
            active_sprint_id: match upd.active_sprint_id {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.active_sprint_id {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            completion_column_id: match upd.completion_column_id {
                FieldUpdate::NoChange => FieldUpdate::NoChange,
                _ => match board.completion_column_id {
                    Some(v) => FieldUpdate::Set(v),
                    None => FieldUpdate::Clear,
                },
            },
            position: upd.position.map(|_| board.position),
        };
        Ok(vec![Command::Board(BoardCommand::Update(UpdateBoard {
            board_id: self.board_id,
            updates: inverse,
        }))])
    }
}

/// Update board's task sorting preference
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetBoardTaskSort {
    pub board_id: Uuid,
    pub field: crate::SortField,
    pub order: crate::SortOrder,
}

impl SetBoardTaskSort {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = context.get_board(self.board_id)?;
        board.update_task_sort(self.field, self.order);
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Set board task sort to {:?} {:?}", self.field, self.order)
    }

    /// Inverse: another SetBoardTaskSort with the prior values.
    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let board = match store.get_board(self.board_id)? {
            Some(b) => b,
            None => return Err(KanbanError::not_found("Board", self.board_id)),
        };
        Ok(vec![Command::Board(BoardCommand::SetTaskSort(
            SetBoardTaskSort {
                board_id: self.board_id,
                field: board.task_sort_field,
                order: board.task_sort_order,
            },
        ))])
    }
}

/// Update board's task list view
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetBoardTaskListView {
    pub board_id: Uuid,
    pub view: crate::TaskListView,
}

impl SetBoardTaskListView {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = context.get_board(self.board_id)?;
        board.update_task_list_view(self.view);
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Set board task list view to {:?}", self.view)
    }

    /// Inverse: another SetBoardTaskListView with the prior view.
    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let board = match store.get_board(self.board_id)? {
            Some(b) => b,
            None => return Err(KanbanError::not_found("Board", self.board_id)),
        };
        Ok(vec![Command::Board(BoardCommand::SetTaskListView(
            SetBoardTaskListView {
                board_id: self.board_id,
                view: board.task_list_view,
            },
        ))])
    }
}

/// Delete a board and all associated columns, cards, and sprints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteBoard {
    pub board_id: Uuid,
}

impl DeleteBoard {
    /// Delete the board record. **Atomic only** — does not cascade to columns,
    /// cards, sprints, or graph edges. Cascade orchestration is the
    /// responsibility of the service layer (see
    /// `KanbanContext::delete_board`).
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        context.store.delete_board(self.board_id)
    }

    pub fn description(&self) -> String {
        format!("Delete board: {}", self.board_id)
    }

    /// Inverse: re-insert the deleted Board via ImportEntities. The
    /// cascade siblings (DeleteColumnsByBoard, DeleteSprintsByBoard,
    /// DeleteCardsByColumns, DeleteCardEdges) capture their own
    /// entities, so undoing the full cascade restores everything.
    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let board = match store.get_board(self.board_id)? {
            Some(b) => b,
            None => return Err(KanbanError::not_found("Board", self.board_id)),
        };
        Ok(vec![Command::Board(BoardCommand::Import(ImportEntities {
            boards: vec![board],
            ..Default::default()
        }))])
    }
}

/// Apply board settings from a DTO (used by JSON editor).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApplyBoardSettings {
    pub board_id: Uuid,
    pub dto: crate::editable::BoardSettingsDto,
}

impl ApplyBoardSettings {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        let mut board = context.get_board(self.board_id)?;
        self.dto.clone().apply_to(&mut board);
        context.store.upsert_board(board)?;
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Apply board settings for {}", self.board_id)
    }

    /// Inverse: snapshot the current board into a `BoardSettingsDto` via the
    /// `Editable::from_entity` impl, then re-apply that DTO via another
    /// `ApplyBoardSettings`. The DTO covers exactly the fields this command
    /// writes, so the round-trip is symmetric.
    pub fn capture_inverse(&self, store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let board = match store.get_board(self.board_id)? {
            Some(b) => b,
            None => return Err(KanbanError::not_found("Board", self.board_id)),
        };
        let prior_dto = crate::editable::BoardSettingsDto::from_entity(&board);
        Ok(vec![Command::Board(BoardCommand::ApplySettings(
            ApplyBoardSettings {
                board_id: self.board_id,
                dto: prior_dto,
            },
        ))])
    }
}

/// Import entities (boards, columns, cards, etc.) into the context.
/// Used by TUI import functionality. Appends without replacing existing data.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ImportEntities {
    pub boards: Vec<Board>,
    pub columns: Vec<Column>,
    pub cards: Vec<Card>,
    pub archived_cards: Vec<ArchivedCard>,
    pub sprints: Vec<Sprint>,
    pub graph: Option<DependencyGraph>,
}

impl ImportEntities {
    pub fn execute(&self, context: &CommandContext) -> KanbanResult<()> {
        use std::collections::HashSet;

        let existing_board_ids: HashSet<Uuid> =
            context.store.list_boards()?.iter().map(|b| b.id).collect();
        let existing_column_ids: HashSet<Uuid> = context
            .store
            .list_all_columns()?
            .iter()
            .map(|c| c.id)
            .collect();
        let existing_card_ids: HashSet<Uuid> = context
            .store
            .list_all_cards()?
            .iter()
            .map(|c| c.id)
            .collect();
        let existing_sprint_ids: HashSet<Uuid> = context
            .store
            .list_all_sprints()?
            .iter()
            .map(|s| s.id)
            .collect();
        let existing_archived_ids: HashSet<Uuid> = context
            .store
            .list_archived_cards()?
            .iter()
            .map(|ac| ac.card.id)
            .collect();

        for b in &self.boards {
            if existing_board_ids.contains(&b.id) {
                return Err(crate::KanbanError::validation(format!(
                    "Duplicate board ID: {}",
                    b.id
                )));
            }
        }
        for c in &self.columns {
            if existing_column_ids.contains(&c.id) {
                return Err(crate::KanbanError::validation(format!(
                    "Duplicate column ID: {}",
                    c.id
                )));
            }
        }
        for c in &self.cards {
            if existing_card_ids.contains(&c.id) {
                return Err(crate::KanbanError::validation(format!(
                    "Duplicate card ID: {}",
                    c.id
                )));
            }
        }
        for ac in &self.archived_cards {
            if existing_archived_ids.contains(&ac.card.id) {
                return Err(crate::KanbanError::validation(format!(
                    "Duplicate archived card ID: {}",
                    ac.card.id
                )));
            }
        }
        for s in &self.sprints {
            if existing_sprint_ids.contains(&s.id) {
                return Err(crate::KanbanError::validation(format!(
                    "Duplicate sprint ID: {}",
                    s.id
                )));
            }
        }

        for b in &self.boards {
            context.store.upsert_board(b.clone())?;
        }
        for c in &self.columns {
            context.store.upsert_column(c.clone())?;
        }
        for c in &self.cards {
            context.store.upsert_card(c.clone())?;
        }
        for ac in &self.archived_cards {
            context.store.insert_archived_card(ac.clone())?;
        }
        for s in &self.sprints {
            context.store.upsert_sprint(s.clone())?;
        }
        if let Some(ref graph) = self.graph {
            context.store.set_graph(graph.clone())?;
        }
        Ok(())
    }

    pub fn description(&self) -> String {
        format!("Import {} board(s)", self.boards.len())
    }

    /// Inverse: emit one delete command per imported entity. The IDs are
    /// in the forward command, so no pre-state read needed.
    ///
    /// Order matters: delete cards before columns before boards so
    /// foreign-key-style invariants stay satisfied (the in-memory store
    /// doesn't enforce them, but downstream backends may).
    pub fn capture_inverse(&self, _store: &dyn DataStore) -> KanbanResult<Vec<Command>> {
        let mut commands: Vec<Command> = Vec::new();

        // Cards first.
        if !self.cards.is_empty() {
            commands.push(Command::Card(crate::commands::CardCommand::Archive(
                crate::commands::ArchiveCards {
                    ids: self.cards.iter().map(|c| c.id).collect(),
                },
            )));
        }

        // Archived cards: per-card permanent delete.
        for ac in &self.archived_cards {
            commands.push(Command::Card(crate::commands::CardCommand::Delete(
                crate::commands::DeleteCard {
                    card_id: ac.card.id,
                },
            )));
        }

        // Sprints: per-sprint delete.
        for s in &self.sprints {
            commands.push(Command::Sprint(crate::commands::SprintCommand::Delete(
                crate::commands::DeleteSprint {
                    sprint_id: s.id,
                    timestamp: chrono::Utc::now(),
                },
            )));
        }

        // Columns: per-column delete (must be empty by the time we get
        // here — cards above were archived first).
        for c in &self.columns {
            commands.push(Command::Column(crate::commands::ColumnCommand::Delete(
                crate::commands::DeleteColumn { column_id: c.id },
            )));
        }

        // Boards last.
        for b in &self.boards {
            commands.push(Command::Board(BoardCommand::Delete(DeleteBoard {
                board_id: b.id,
            })));
        }

        Ok(commands)
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_helpers::TestContext;
    use super::*;
    use crate::DataStore;

    #[test]
    fn test_update_board_not_found_returns_error() {
        let tc = TestContext::new();
        let context = tc.as_command_context();
        let cmd = UpdateBoard {
            board_id: Uuid::new_v4(),
            updates: crate::BoardUpdate::default(),
        };
        let result = cmd.execute(&context);
        assert!(result.unwrap_err().is_not_found());
    }

    #[test]
    fn test_set_board_task_sort_not_found_returns_error() {
        let tc = TestContext::new();
        let context = tc.as_command_context();
        let cmd = SetBoardTaskSort {
            board_id: Uuid::new_v4(),
            field: crate::SortField::Priority,
            order: crate::SortOrder::Ascending,
        };
        let result = cmd.execute(&context);
        assert!(result.unwrap_err().is_not_found());
    }

    #[test]
    fn test_set_board_task_list_view_not_found_returns_error() {
        let tc = TestContext::new();
        let context = tc.as_command_context();
        let cmd = SetBoardTaskListView {
            board_id: Uuid::new_v4(),
            view: crate::TaskListView::default(),
        };
        let result = cmd.execute(&context);
        assert!(result.unwrap_err().is_not_found());
    }

    #[test]
    fn test_import_entities_with_duplicate_board_id_returns_error() {
        let tc = TestContext::new();
        let b1 = Board::new("B1", None::<String>);
        let dup_id = b1.id;
        tc.store.upsert_board(b1).unwrap();

        let mut dup = Board::new("Dup", None::<String>);
        dup.id = dup_id;

        let cmd = ImportEntities {
            boards: vec![dup],
            columns: vec![],
            cards: vec![],
            archived_cards: vec![],
            sprints: vec![],
            graph: None,
        };
        let context = tc.as_command_context();
        let result = cmd.execute(&context);
        assert!(result.is_err());
        assert!(result.unwrap_err().is_validation());
    }

    #[test]
    fn test_import_entities_with_duplicate_card_id_returns_error() {
        let tc = TestContext::new();
        let mut board = Board::new("B", Some("TST"));
        let col = crate::Column::new(board.id, "Col", 0);
        let card = crate::Card::new(&mut board, col.id, "Card", 0);
        let dup_card_id = card.id;
        tc.store.upsert_board(board.clone()).unwrap();
        tc.store.upsert_column(col).unwrap();
        tc.store.upsert_card(card).unwrap();

        let mut dup_card = crate::Card::new(&mut board, Uuid::new_v4(), "Dup", 0);
        dup_card.id = dup_card_id;

        let cmd = ImportEntities {
            boards: vec![],
            columns: vec![],
            cards: vec![dup_card],
            archived_cards: vec![],
            sprints: vec![],
            graph: None,
        };
        let context = tc.as_command_context();
        let result = cmd.execute(&context);
        assert!(result.is_err());
        assert!(result.unwrap_err().is_validation());
    }

    #[test]
    fn test_import_entities_appends_without_replacing() {
        let tc = TestContext::new();
        let b1 = Board::new("B1", None::<String>);
        tc.store.upsert_board(b1).unwrap();

        let b2 = Board::new("B2", None::<String>);
        let col = crate::Column::new(b2.id, "Todo", 0);
        let mut b2_clone = b2.clone();
        let card = crate::Card::new(&mut b2_clone, col.id, "Card", 0);

        let cmd = ImportEntities {
            boards: vec![b2],
            columns: vec![col],
            cards: vec![card],
            archived_cards: vec![],
            sprints: vec![],
            graph: None,
        };

        let context = tc.as_command_context();
        cmd.execute(&context).unwrap();

        let boards = tc.store.list_boards().unwrap();
        assert_eq!(boards.len(), 2);
        assert!(boards.iter().any(|b| b.name == "B1"));
        assert!(boards.iter().any(|b| b.name == "B2"));
        assert_eq!(tc.store.list_all_columns().unwrap().len(), 1);
        assert_eq!(tc.store.list_all_cards().unwrap().len(), 1);
    }

    #[test]
    fn test_update_board_card_prefix_allowed_before_first_card_succeeds() {
        let tc = TestContext::new();
        let board = Board::new("B", Some("OLD"));
        let board_id = board.id;
        tc.store.upsert_board(board).unwrap();
        let context = tc.as_command_context();

        let cmd = UpdateBoard {
            board_id,
            updates: crate::BoardUpdate {
                card_prefix: FieldUpdate::Set("NEW".to_string()),
                ..Default::default()
            },
        };
        assert!(cmd.execute(&context).is_ok());
        let board = tc.store.get_board(board_id).unwrap().unwrap();
        assert_eq!(board.card_prefix, Some("NEW".to_string()));
    }

    #[test]
    fn test_update_board_card_prefix_locked_after_first_card_returns_validation_error() {
        let tc = TestContext::new();
        let mut board = Board::new("B", Some("OLD"));
        let board_id = board.id;
        let col = Column::new(board_id, "Col", 0);
        let _card = Card::new(&mut board, col.id, "C", 0);
        // card_counter is now 2 (incremented past initial 1)
        tc.store.upsert_board(board).unwrap();
        tc.store.upsert_column(col).unwrap();
        let context = tc.as_command_context();

        let cmd = UpdateBoard {
            board_id,
            updates: crate::BoardUpdate {
                card_prefix: FieldUpdate::Set("NEW".to_string()),
                ..Default::default()
            },
        };
        let err = cmd.execute(&context).unwrap_err();
        assert!(err.is_validation());
    }

    #[test]
    fn test_update_board_clear_card_prefix_locked_after_first_card_returns_validation_error() {
        let tc = TestContext::new();
        let mut board = Board::new("B", Some("OLD"));
        let board_id = board.id;
        let col = Column::new(board_id, "Col", 0);
        let _card = Card::new(&mut board, col.id, "C", 0);
        tc.store.upsert_board(board).unwrap();
        tc.store.upsert_column(col).unwrap();
        let context = tc.as_command_context();

        let cmd = UpdateBoard {
            board_id,
            updates: crate::BoardUpdate {
                card_prefix: FieldUpdate::Clear,
                ..Default::default()
            },
        };
        let err = cmd.execute(&context).unwrap_err();
        assert!(err.is_validation());
    }

    #[test]
    fn test_delete_board_atomic_removes_only_board_record() {
        let tc = TestContext::new();
        let board = Board::new("B", Some("TST"));
        let board_id = board.id;
        let col = Column::new(board_id, "Col", 0);
        tc.store.upsert_board(board).unwrap();
        tc.store.upsert_column(col.clone()).unwrap();

        let context = tc.as_command_context();
        let cmd = DeleteBoard { board_id };
        cmd.execute(&context).unwrap();

        assert!(tc.store.list_boards().unwrap().is_empty());
        assert_eq!(
            tc.store.list_all_columns().unwrap().len(),
            1,
            "atomic DeleteBoard must not cascade to columns; cascade is the service's responsibility"
        );
    }
}