kanban-service 0.4.0

Shared service layer implementing KanbanOperations over a pluggable PersistenceStore
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
use crate::backend::KanbanBackend;
use kanban_core::AppConfig;
use kanban_domain::commands::{
    BoardCommand, CardCommand, ColumnCommand, Command, CommandContext, SprintCommand,
};
use kanban_domain::{
    ArchivedCard, Board, BoardUpdate, Card, CardListFilter, CardSummary, CardUpdate, Column,
    ColumnUpdate, DataStore, DependencyGraph, FieldUpdate, KanbanOperations, Snapshot, Sprint,
    SprintUpdate,
};
use kanban_domain::{KanbanError, KanbanResult};
use kanban_persistence::PersistenceError;
use serde::Serialize;
use std::sync::Arc;
use uuid::Uuid;

#[derive(Debug, Clone, Serialize)]
pub struct BatchOperationResult {
    pub succeeded: Vec<Uuid>,
    pub failed: Vec<BatchOperationFailure>,
}

#[derive(Debug, Clone, Serialize)]
pub struct BatchOperationFailure {
    pub id: Uuid,
    pub error: String,
}

pub const MAX_UNDO_DEPTH: usize = 200;

/// Service layer: wraps a pluggable [`KanbanBackend`] with undo/redo history
/// and a unified async `save()` / `reload()` interface.
///
/// Construction is always zero-I/O — data is fetched lazily on the first
/// read, either directly (SQLite, reads are always live) or via a one-time
/// cache-fill on first access (JSON).
pub struct KanbanContext {
    backend: Arc<dyn KanbanBackend>,
    app_config: AppConfig,
    /// `None` until [`initialize_undo_state`][Self::initialize_undo_state] is called.
    baseline_snapshot: Option<Snapshot>,
    undo_cursor: usize,
    command_count: usize,
    dirty: bool,
    conflict_pending: bool,
}

impl KanbanContext {
    /// Zero-I/O constructor. Wraps `backend` without reading any data.
    /// Call [`initialize_undo_state`][Self::initialize_undo_state] before the
    /// first [`execute`][Self::execute], [`undo`][Self::undo], or
    /// [`redo`][Self::redo], or use [`open`][Self::open]
    /// which calls it automatically.
    pub fn open_deferred(backend: Arc<dyn KanbanBackend>, config: AppConfig) -> Self {
        Self {
            backend,
            app_config: config,
            baseline_snapshot: None,
            undo_cursor: 0,
            command_count: 0,
            dirty: false,
            conflict_pending: false,
        }
    }

    /// Wraps `backend` and eagerly initializes the undo cursor so that
    /// `can_undo()` / `can_redo()` return correct values before the first
    /// mutation. Use this instead of [`open_deferred`][Self::open_deferred]
    /// wherever the caller needs undo state to be populated immediately
    /// (CLI, MCP, TUI startup).
    pub async fn open(backend: Arc<dyn KanbanBackend>, config: AppConfig) -> KanbanResult<Self> {
        let mut ctx = Self::open_deferred(backend, config);
        ctx.initialize_undo_state()?;
        Ok(ctx)
    }

    // ── Accessors ─────────────────────────────────────────────────────────────

    pub fn app_config(&self) -> &AppConfig {
        &self.app_config
    }

    pub fn data_store(&self) -> &dyn DataStore {
        self.backend.as_data_store()
    }

    pub fn backend(&self) -> Arc<dyn KanbanBackend> {
        Arc::clone(&self.backend)
    }

    /// Replace the active backend, discarding all undo/redo history.
    ///
    /// **Destructive**: resets `baseline_snapshot`, `undo_cursor`, `command_count`,
    /// and `dirty`. The caller is responsible for re-initialising undo state via
    /// [`initialize_undo_state`][Self::initialize_undo_state] if needed.
    pub fn replace_backend(&mut self, backend: Arc<dyn KanbanBackend>) {
        tracing::info!("Replacing backend; undo/redo history discarded");
        self.backend = backend;
        self.baseline_snapshot = None;
        self.undo_cursor = 0;
        self.command_count = 0;
        self.dirty = false;
    }

    pub fn boards(&self) -> KanbanResult<Vec<Board>> {
        self.backend.list_boards()
    }

    pub fn columns(&self) -> KanbanResult<Vec<Column>> {
        self.backend.list_all_columns()
    }

    pub fn cards(&self) -> KanbanResult<Vec<Card>> {
        self.backend.list_all_cards()
    }

    pub fn sprints(&self) -> KanbanResult<Vec<Sprint>> {
        self.backend.list_all_sprints()
    }

    pub fn archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
        self.backend.list_archived_cards()
    }

    pub fn graph(&self) -> KanbanResult<DependencyGraph> {
        self.backend.get_graph()
    }

    pub fn snapshot(&self) -> KanbanResult<Snapshot> {
        self.backend.snapshot()
    }

    pub fn apply_snapshot(&self, snapshot: Snapshot) -> KanbanResult<()> {
        self.backend.apply_snapshot(snapshot)
    }

    // ── Undo / Redo ───────────────────────────────────────────────────────────

    /// Loads the pre-existing command count and baseline snapshot from the backend.
    /// Must be called once after [`open_deferred`][Self::open_deferred] before any call to
    /// [`execute`], [`undo`], or [`redo`].  [`open`][Self::open]
    /// calls this automatically.  Idempotent if called more than once.
    pub fn initialize_undo_state(&mut self) -> KanbanResult<()> {
        if self.baseline_snapshot.is_none() {
            let count = self.backend.command_count()? as usize;
            let baseline = if count > 0 {
                match self.backend.load_snapshot_at(0)? {
                    Some(snap) => snap,
                    // Old file: commands present but no stored baseline.
                    // Use current data as the undo floor so undo cannot
                    // wipe existing data.
                    None => self.backend.snapshot()?,
                }
            } else {
                self.backend.snapshot()?
            };
            self.baseline_snapshot = Some(baseline);
            self.command_count = count;
            self.undo_cursor = count;
        }
        Ok(())
    }

    fn notify_undo_state(&self) -> KanbanResult<()> {
        self.backend
            .on_undo_state_changed(self.undo_cursor as u64, self.baseline_snapshot.clone())
    }

    /// Execute a batch of commands as a single undo unit.
    pub fn execute(&mut self, commands: Vec<Command>) -> KanbanResult<()> {
        if self.baseline_snapshot.is_none() {
            return Err(KanbanError::Internal(
                "undo state not initialized — call initialize_undo_state() or open()".into(),
            ));
        }

        if self.undo_cursor < self.command_count {
            self.backend
                .truncate_commands_after(self.undo_cursor as u64)?;
        }

        let before = if self.backend.supports_indexed_snapshots() {
            None
        } else {
            Some(self.backend.snapshot()?)
        };
        let result = {
            let store: &dyn DataStore = self.backend.as_data_store();
            let ctx = CommandContext { store };
            commands.iter().try_for_each(|cmd| cmd.execute(&ctx))
        };
        if let Err(e) = result {
            let rollback_snap = if let Some(snap) = before {
                snap
            } else if self.undo_cursor > 0 {
                self.backend
                    .load_snapshot_at(self.undo_cursor as u64)?
                    .unwrap_or_else(|| {
                        debug_assert!(
                            self.baseline_snapshot.is_some(),
                            "baseline must be Some after guard"
                        );
                        self.baseline_snapshot.clone().unwrap_or_default()
                    })
            } else {
                debug_assert!(
                    self.baseline_snapshot.is_some(),
                    "baseline must be Some after guard"
                );
                self.baseline_snapshot.clone().unwrap_or_default()
            };
            if let Err(rollback_err) = self.backend.apply_snapshot(rollback_snap) {
                return Err(KanbanError::Internal(format!(
                    "Command failed ({e}) and rollback also failed ({rollback_err}). State may be inconsistent."
                )));
            }
            return Err(e);
        }

        self.backend.append_commands(&commands)?;
        self.undo_cursor += 1;
        self.command_count = self.undo_cursor;

        if self.backend.supports_indexed_snapshots() {
            let snap = self.backend.snapshot()?;
            self.backend
                .store_snapshot_at(self.undo_cursor as u64, &snap)?;
        }

        if self.undo_cursor > MAX_UNDO_DEPTH {
            let excess = self.undo_cursor - MAX_UNDO_DEPTH;
            if let Some(new_baseline) = self.backend.load_snapshot_at(excess as u64)? {
                self.baseline_snapshot = Some(new_baseline);
            }
            self.backend.shift_commands(excess as u64)?;
            self.undo_cursor = MAX_UNDO_DEPTH;
            self.command_count = MAX_UNDO_DEPTH;
        }

        self.dirty = true;
        self.notify_undo_state()?;
        Ok(())
    }

    /// Undo the most recent batch.
    pub fn undo(&mut self) -> KanbanResult<bool> {
        if self.baseline_snapshot.is_none() {
            return Ok(false); // nothing to undo in an uninitialized context
        }
        if self.undo_cursor == 0 {
            return Ok(false);
        }
        self.undo_cursor -= 1;

        if self.backend.supports_indexed_snapshots() {
            let snap = if self.undo_cursor == 0 {
                debug_assert!(
                    self.baseline_snapshot.is_some(),
                    "baseline must be Some after guard"
                );
                self.baseline_snapshot.clone().unwrap_or_default()
            } else {
                self.backend
                    .load_snapshot_at(self.undo_cursor as u64)?
                    .unwrap_or_else(|| {
                        debug_assert!(
                            self.baseline_snapshot.is_some(),
                            "baseline must be Some after guard"
                        );
                        self.baseline_snapshot.clone().unwrap_or_default()
                    })
            };
            self.backend.apply_snapshot(snap)?;
        } else {
            debug_assert!(
                self.baseline_snapshot.is_some(),
                "baseline must be Some after guard"
            );
            self.backend
                .apply_snapshot(self.baseline_snapshot.clone().unwrap_or_default())?;
            let batches = self.backend.load_commands(0, self.undo_cursor as u64)?;
            let store: &dyn DataStore = self.backend.as_data_store();
            let ctx = CommandContext { store };
            for batch in &batches {
                for cmd in batch {
                    cmd.execute(&ctx)?;
                }
            }
        }

        self.dirty = true;
        self.notify_undo_state()?;
        Ok(true)
    }

    /// Redo the next undone batch.
    pub fn redo(&mut self) -> KanbanResult<bool> {
        if self.baseline_snapshot.is_none() {
            return Ok(false); // nothing to redo in an uninitialized context
        }
        if self.undo_cursor >= self.command_count {
            return Ok(false);
        }

        let mut applied = false;
        if self.backend.supports_indexed_snapshots() {
            let target = self.undo_cursor as u64 + 1;
            if let Some(snap) = self.backend.load_snapshot_at(target)? {
                self.backend.apply_snapshot(snap)?;
                applied = true;
            }
        }

        if !applied {
            let batches = self
                .backend
                .load_commands(self.undo_cursor as u64, self.undo_cursor as u64 + 1)?;
            let store: &dyn DataStore = self.backend.as_data_store();
            let ctx = CommandContext { store };
            for batch in &batches {
                for cmd in batch {
                    cmd.execute(&ctx)?;
                }
            }
        }

        self.undo_cursor += 1;
        self.dirty = true;
        self.notify_undo_state()?;
        Ok(true)
    }

    pub fn can_undo(&self) -> bool {
        self.baseline_snapshot.is_some() && self.undo_cursor > 0
    }

    pub fn can_redo(&self) -> bool {
        self.baseline_snapshot.is_some() && self.undo_cursor < self.command_count
    }

    pub fn clear_history(&mut self) -> KanbanResult<()> {
        self.baseline_snapshot = Some(self.backend.snapshot()?);
        self.backend.truncate_commands_after(0)?;
        self.undo_cursor = 0;
        self.command_count = 0;
        self.notify_undo_state()?;
        Ok(())
    }

    pub fn undo_depth(&self) -> usize {
        self.undo_cursor
    }

    pub fn redo_depth(&self) -> usize {
        self.command_count.saturating_sub(self.undo_cursor)
    }

    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    pub fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    pub fn mark_clean(&mut self) {
        self.dirty = false;
    }

    pub fn has_conflict(&self) -> bool {
        self.conflict_pending
    }

    pub fn set_conflict(&mut self) {
        self.conflict_pending = true;
    }

    pub fn clear_conflict(&mut self) {
        self.conflict_pending = false;
    }

    pub fn set_conflict_pending(&mut self, v: bool) {
        self.conflict_pending = v;
    }

    // ── Persistence ───────────────────────────────────────────────────────────

    /// Reload state from durable storage, discarding any uncommitted data cache.
    /// After reloading, the context is immediately ready for mutations — the
    /// baseline snapshot is refreshed from the freshly-loaded data and the
    /// command log is truncated, so no separate call to
    /// [`initialize_undo_state`][Self::initialize_undo_state] is required.
    pub async fn reload(&mut self) -> KanbanResult<()> {
        self.backend.reload().await?;
        self.baseline_snapshot = None;
        self.undo_cursor = 0;
        self.command_count = 0;
        self.dirty = false;
        // Read the fresh snapshot as the new baseline and discard the command
        // log so undo cannot reach across the reload boundary.
        let baseline = self.backend.snapshot()?;
        self.backend.truncate_commands_after(0)?;
        self.baseline_snapshot = Some(baseline);
        self.notify_undo_state()?;
        Ok(())
    }

    /// Persist any dirty state to durable storage.
    /// For SQLite this is a WAL checkpoint; for JSON this flushes the cache.
    pub async fn save(&self) -> KanbanResult<()> {
        self.backend.flush().await
    }

    // ── Batch ops ─────────────────────────────────────────────────────────────

    pub fn archive_cards_detailed(&mut self, ids: Vec<Uuid>) -> BatchOperationResult {
        use kanban_domain::commands::ArchiveCards;
        let all_cards = match self.backend.list_all_cards() {
            Ok(c) => c,
            Err(e) => {
                return BatchOperationResult {
                    succeeded: vec![],
                    failed: ids
                        .into_iter()
                        .map(|id| BatchOperationFailure {
                            id,
                            error: e.to_string(),
                        })
                        .collect(),
                };
            }
        };
        let card_ids: std::collections::HashSet<Uuid> = all_cards.iter().map(|c| c.id).collect();
        let mut to_archive = Vec::new();
        let mut failed = Vec::new();
        for id in ids {
            if card_ids.contains(&id) {
                to_archive.push(id);
            } else {
                failed.push(BatchOperationFailure {
                    id,
                    error: KanbanError::not_found("card", id).to_string(),
                });
            }
        }
        if to_archive.is_empty() {
            return BatchOperationResult {
                succeeded: vec![],
                failed,
            };
        }
        let succeeded = to_archive.clone();
        match self.execute(vec![Command::Card(CardCommand::Archive(ArchiveCards {
            ids: to_archive,
        }))]) {
            Ok(()) => BatchOperationResult { succeeded, failed },
            Err(e) => {
                let err = e.to_string();
                let mut all_failed = failed;
                all_failed.extend(succeeded.into_iter().map(|id| BatchOperationFailure {
                    id,
                    error: err.clone(),
                }));
                BatchOperationResult {
                    succeeded: vec![],
                    failed: all_failed,
                }
            }
        }
    }

    pub fn move_cards_detailed(&mut self, ids: Vec<Uuid>, column_id: Uuid) -> BatchOperationResult {
        use kanban_domain::commands::MoveCards;
        let all_cards = match self.backend.list_all_cards() {
            Ok(c) => c,
            Err(e) => {
                return BatchOperationResult {
                    succeeded: vec![],
                    failed: ids
                        .into_iter()
                        .map(|id| BatchOperationFailure {
                            id,
                            error: e.to_string(),
                        })
                        .collect(),
                };
            }
        };
        let card_ids: std::collections::HashSet<Uuid> = all_cards.iter().map(|c| c.id).collect();
        let mut to_move = Vec::new();
        let mut failed = Vec::new();
        for id in ids {
            if card_ids.contains(&id) {
                to_move.push(id);
            } else {
                failed.push(BatchOperationFailure {
                    id,
                    error: KanbanError::not_found("card", id).to_string(),
                });
            }
        }
        if to_move.is_empty() {
            return BatchOperationResult {
                succeeded: vec![],
                failed,
            };
        }
        let succeeded = to_move.clone();
        match self.execute(vec![Command::Card(CardCommand::MoveMultiple(MoveCards {
            ids: to_move,
            column_id,
        }))]) {
            Ok(()) => BatchOperationResult { succeeded, failed },
            Err(e) => {
                let err = e.to_string();
                let mut all_failed = failed;
                all_failed.extend(succeeded.into_iter().map(|id| BatchOperationFailure {
                    id,
                    error: err.clone(),
                }));
                BatchOperationResult {
                    succeeded: vec![],
                    failed: all_failed,
                }
            }
        }
    }

    pub fn assign_cards_to_sprint_detailed(
        &mut self,
        ids: Vec<Uuid>,
        sprint_id: Uuid,
    ) -> BatchOperationResult {
        use kanban_domain::commands::AssignCardsToSprint;
        let all_sprints = match self.backend.list_all_sprints() {
            Ok(s) => s,
            Err(e) => {
                return BatchOperationResult {
                    succeeded: vec![],
                    failed: ids
                        .into_iter()
                        .map(|id| BatchOperationFailure {
                            id,
                            error: e.to_string(),
                        })
                        .collect(),
                };
            }
        };
        if !all_sprints.iter().any(|s| s.id == sprint_id) {
            return BatchOperationResult {
                succeeded: vec![],
                failed: ids
                    .into_iter()
                    .map(|id| BatchOperationFailure {
                        id,
                        error: KanbanError::not_found("sprint", sprint_id).to_string(),
                    })
                    .collect(),
            };
        }
        let all_cards = match self.backend.list_all_cards() {
            Ok(c) => c,
            Err(e) => {
                return BatchOperationResult {
                    succeeded: vec![],
                    failed: ids
                        .into_iter()
                        .map(|id| BatchOperationFailure {
                            id,
                            error: e.to_string(),
                        })
                        .collect(),
                };
            }
        };
        let card_ids: std::collections::HashSet<Uuid> = all_cards.iter().map(|c| c.id).collect();
        let mut to_assign = Vec::new();
        let mut failed = Vec::new();
        for id in ids {
            if card_ids.contains(&id) {
                to_assign.push(id);
            } else {
                failed.push(BatchOperationFailure {
                    id,
                    error: KanbanError::not_found("card", id).to_string(),
                });
            }
        }
        if to_assign.is_empty() {
            return BatchOperationResult {
                succeeded: vec![],
                failed,
            };
        }
        let succeeded = to_assign.clone();
        match self.execute(vec![Command::Card(CardCommand::AssignToSprint(
            AssignCardsToSprint {
                ids: to_assign,
                sprint_id,
            },
        ))]) {
            Ok(()) => BatchOperationResult { succeeded, failed },
            Err(e) => {
                let err = e.to_string();
                let mut all_failed = failed;
                all_failed.extend(succeeded.into_iter().map(|id| BatchOperationFailure {
                    id,
                    error: err.clone(),
                }));
                BatchOperationResult {
                    succeeded: vec![],
                    failed: all_failed,
                }
            }
        }
    }
}

// ── KanbanOperations impl ─────────────────────────────────────────────────────

impl KanbanOperations for KanbanContext {
    fn create_board(&mut self, name: String, card_prefix: Option<String>) -> KanbanResult<Board> {
        use kanban_domain::commands::CreateBoard;
        let id = Uuid::new_v4();
        let position = self.backend.list_boards()?.len() as i32;
        let cmd = Command::Board(BoardCommand::Create(CreateBoard {
            id,
            name,
            card_prefix,
            position,
        }));
        self.execute(vec![cmd])?;
        self.get_board(id)?.ok_or_else(|| {
            KanbanError::Internal("Board creation succeeded but board not found".into())
        })
    }

    fn list_boards(&self) -> KanbanResult<Vec<Board>> {
        self.backend.list_boards()
    }

    fn get_board(&self, id: Uuid) -> KanbanResult<Option<Board>> {
        self.backend.get_board(id)
    }

    fn update_board(&mut self, id: Uuid, updates: BoardUpdate) -> KanbanResult<Board> {
        use kanban_domain::commands::UpdateBoard;
        let cmd = Command::Board(BoardCommand::Update(UpdateBoard {
            board_id: id,
            updates,
        }));
        self.execute(vec![cmd])?;
        self.get_board(id)?
            .ok_or_else(|| KanbanError::not_found("board", id))
    }

    fn delete_board(&mut self, id: Uuid) -> KanbanResult<()> {
        use kanban_domain::commands::DeleteBoard;
        let cmd = Command::Board(BoardCommand::Delete(DeleteBoard { board_id: id }));
        self.execute(vec![cmd])
    }

    fn create_column(
        &mut self,
        board_id: Uuid,
        name: String,
        position: Option<i32>,
    ) -> KanbanResult<Column> {
        use kanban_domain::commands::CreateColumn;
        let position = match position {
            Some(p) => p,
            None => self.backend.list_columns_by_board(board_id)?.len() as i32,
        };
        let id = Uuid::new_v4();
        let cmd = Command::Column(ColumnCommand::Create(CreateColumn {
            id,
            board_id,
            name,
            position,
        }));
        self.execute(vec![cmd])?;
        self.get_column(id)?.ok_or_else(|| {
            KanbanError::Internal("Column creation succeeded but column not found".into())
        })
    }

    fn list_columns(&self, board_id: Uuid) -> KanbanResult<Vec<Column>> {
        self.backend.list_columns_by_board(board_id)
    }

    fn get_column(&self, id: Uuid) -> KanbanResult<Option<Column>> {
        self.backend.get_column(id)
    }

    fn update_column(&mut self, id: Uuid, updates: ColumnUpdate) -> KanbanResult<Column> {
        use kanban_domain::commands::UpdateColumn;
        let cmd = Command::Column(ColumnCommand::Update(UpdateColumn {
            column_id: id,
            updates,
        }));
        self.execute(vec![cmd])?;
        self.get_column(id)?
            .ok_or_else(|| KanbanError::not_found("column", id))
    }

    fn delete_column(&mut self, id: Uuid) -> KanbanResult<()> {
        use kanban_domain::commands::DeleteColumn;
        let cmd = Command::Column(ColumnCommand::Delete(DeleteColumn { column_id: id }));
        self.execute(vec![cmd])
    }

    fn reorder_column(&mut self, id: Uuid, new_position: i32) -> KanbanResult<Column> {
        let updates = ColumnUpdate {
            name: None,
            position: Some(new_position),
            wip_limit: FieldUpdate::NoChange,
        };
        self.update_column(id, updates)
    }

    fn create_card(
        &mut self,
        board_id: Uuid,
        column_id: Uuid,
        title: String,
        options: kanban_domain::CreateCardOptions,
    ) -> KanbanResult<Card> {
        use kanban_domain::commands::CreateCard;
        let position = self.backend.list_cards_by_column(column_id)?.len() as i32;
        let card_number = self
            .backend
            .get_board(board_id)?
            .map(|b| b.card_counter)
            .unwrap_or(1);
        let id = Uuid::new_v4();
        let cmd = Command::Card(CardCommand::Create(CreateCard {
            id,
            card_number,
            board_id,
            column_id,
            title,
            position,
            options,
            timestamp: chrono::Utc::now(),
        }));
        self.execute(vec![cmd])?;
        self.get_card(id)?.ok_or_else(|| {
            KanbanError::Internal("Card creation succeeded but card not found".into())
        })
    }

    fn list_cards(&self, filter: CardListFilter) -> KanbanResult<Vec<CardSummary>> {
        let mut cards = self.backend.list_all_cards()?;

        if let Some(board_id) = filter.board_id {
            let board_columns: Vec<Uuid> = self
                .backend
                .list_columns_by_board(board_id)?
                .iter()
                .map(|c| c.id)
                .collect();
            cards.retain(|c| board_columns.contains(&c.column_id));
        }

        if let Some(column_id) = filter.column_id {
            cards.retain(|c| c.column_id == column_id);
        }

        if let Some(sprint_id) = filter.sprint_id {
            cards.retain(|c| c.sprint_id == Some(sprint_id));
        }

        if let Some(status) = filter.status {
            cards.retain(|c| c.status == status);
        }

        Ok(cards.iter().map(CardSummary::from).collect())
    }

    fn get_card(&self, id: Uuid) -> KanbanResult<Option<Card>> {
        self.backend.get_card(id)
    }

    fn find_cards_by_identifier(&self, identifier: &str) -> KanbanResult<Vec<Card>> {
        use kanban_domain::search::find_cards_by_identifier as search;
        let cards = self.backend.list_all_cards()?;
        let columns = self.backend.list_all_columns()?;
        let boards = self.backend.list_boards()?;
        let sprints = self.backend.list_all_sprints()?;
        Ok(search(identifier, &cards, &columns, &boards, &sprints)
            .into_iter()
            .cloned()
            .collect())
    }

    fn update_card(&mut self, id: Uuid, updates: CardUpdate) -> KanbanResult<Card> {
        use kanban_domain::commands::UpdateCard;
        let cmd = Command::Card(CardCommand::Update(UpdateCard {
            card_id: id,
            updates,
        }));
        self.execute(vec![cmd])?;
        self.get_card(id)?
            .ok_or_else(|| KanbanError::not_found("card", id))
    }

    fn move_card(
        &mut self,
        id: Uuid,
        column_id: Uuid,
        position: Option<i32>,
    ) -> KanbanResult<Card> {
        use kanban_domain::commands::MoveCard;
        let position = match position {
            Some(p) => p,
            None => self.backend.list_cards_by_column(column_id)?.len() as i32,
        };
        let cmd = Command::Card(CardCommand::Move(MoveCard {
            card_id: id,
            new_column_id: column_id,
            new_position: position,
        }));
        self.execute(vec![cmd])?;
        self.get_card(id)?
            .ok_or_else(|| KanbanError::not_found("card", id))
    }

    fn archive_card(&mut self, id: Uuid) -> KanbanResult<()> {
        match self.archive_cards(vec![id]) {
            Ok(0) | Err(KanbanError::Domain(kanban_domain::DomainError::Validation(_))) => {
                Err(KanbanError::not_found("card", id))
            }
            Ok(_) => Ok(()),
            Err(e) => Err(e),
        }
    }

    fn restore_card(&mut self, id: Uuid, column_id: Option<Uuid>) -> KanbanResult<Card> {
        use kanban_domain::commands::RestoreCard;
        let archived = self
            .backend
            .get_archived_card(id)?
            .ok_or_else(|| KanbanError::not_found("archived card", id))?;

        let target_column = if let Some(col_id) = column_id {
            if self.backend.get_column(col_id)?.is_none() {
                return Err(KanbanError::not_found("column", col_id));
            }
            col_id
        } else if self
            .backend
            .get_column(archived.original_column_id)?
            .is_some()
        {
            archived.original_column_id
        } else {
            return Err(KanbanError::validation("Original column no longer exists. Specify --column-id to restore to a different column"));
        };

        let position = archived.original_position;
        let cmd = Command::Card(CardCommand::Restore(RestoreCard {
            card_id: id,
            column_id: target_column,
            position,
            timestamp: chrono::Utc::now(),
        }));
        self.execute(vec![cmd])?;
        self.get_card(id)?
            .ok_or_else(|| KanbanError::not_found("card", id))
    }

    fn delete_card(&mut self, id: Uuid) -> KanbanResult<()> {
        use kanban_domain::commands::DeleteCard;
        let cmd = Command::Card(CardCommand::Delete(DeleteCard { card_id: id }));
        self.execute(vec![cmd])
    }

    fn list_archived_cards(&self) -> KanbanResult<Vec<ArchivedCard>> {
        self.backend.list_archived_cards()
    }

    fn assign_card_to_sprint(&mut self, card_id: Uuid, sprint_id: Uuid) -> KanbanResult<Card> {
        use kanban_domain::commands::AssignCardsToSprint;
        let cmd = Command::Card(CardCommand::AssignToSprint(AssignCardsToSprint {
            ids: vec![card_id],
            sprint_id,
        }));
        self.execute(vec![cmd])?;
        self.get_card(card_id)?
            .ok_or_else(|| KanbanError::not_found("card", card_id))
    }

    fn unassign_card_from_sprint(&mut self, card_id: Uuid) -> KanbanResult<Card> {
        use kanban_domain::commands::UnassignCardFromSprint;
        let cmd = Command::Card(CardCommand::UnassignFromSprint(UnassignCardFromSprint {
            card_id,
            timestamp: chrono::Utc::now(),
        }));
        self.execute(vec![cmd])?;
        self.get_card(card_id)?
            .ok_or_else(|| KanbanError::not_found("card", card_id))
    }

    fn get_card_branch_name(&self, id: Uuid) -> KanbanResult<String> {
        let card = self
            .get_card(id)?
            .ok_or_else(|| KanbanError::not_found("card", id))?;
        let column = self
            .backend
            .get_column(card.column_id)?
            .ok_or_else(|| KanbanError::not_found("column", card.column_id))?;
        let board = self
            .backend
            .get_board(column.board_id)?
            .ok_or_else(|| KanbanError::not_found("board", column.board_id))?;
        let sprints = self.backend.list_all_sprints()?;
        Ok(card.branch_name(
            &board,
            &sprints,
            self.app_config.effective_default_card_prefix(),
        ))
    }

    fn get_card_git_checkout(&self, id: Uuid) -> KanbanResult<String> {
        let card = self
            .get_card(id)?
            .ok_or_else(|| KanbanError::not_found("card", id))?;
        let column = self
            .backend
            .get_column(card.column_id)?
            .ok_or_else(|| KanbanError::not_found("column", card.column_id))?;
        let board = self
            .backend
            .get_board(column.board_id)?
            .ok_or_else(|| KanbanError::not_found("board", column.board_id))?;
        let sprints = self.backend.list_all_sprints()?;
        Ok(card.git_checkout_command(
            &board,
            &sprints,
            self.app_config.effective_default_card_prefix(),
        ))
    }

    fn archive_cards(&mut self, ids: Vec<Uuid>) -> KanbanResult<usize> {
        use kanban_domain::commands::ArchiveCards;
        let before = self.backend.list_archived_cards()?.len();
        self.execute(vec![Command::Card(CardCommand::Archive(ArchiveCards {
            ids,
        }))])?;
        Ok(self.backend.list_archived_cards()?.len() - before)
    }

    fn move_cards(&mut self, ids: Vec<Uuid>, column_id: Uuid) -> KanbanResult<usize> {
        use kanban_domain::commands::MoveCards;
        let before = self.backend.list_cards_by_column(column_id)?.len();
        self.execute(vec![Command::Card(CardCommand::MoveMultiple(MoveCards {
            ids,
            column_id,
        }))])?;
        let after = self.backend.list_cards_by_column(column_id)?.len();
        Ok(after - before)
    }

    fn assign_cards_to_sprint(&mut self, ids: Vec<Uuid>, sprint_id: Uuid) -> KanbanResult<usize> {
        use kanban_domain::commands::AssignCardsToSprint;
        let before = self.backend.list_cards_by_sprint(sprint_id)?.len();
        self.execute(vec![Command::Card(CardCommand::AssignToSprint(
            AssignCardsToSprint { ids, sprint_id },
        ))])?;
        let after = self.backend.list_cards_by_sprint(sprint_id)?.len();
        Ok(after - before)
    }

    fn carry_over_sprint_cards(
        &mut self,
        from_sprint_id: Uuid,
        to_sprint_id: Uuid,
    ) -> KanbanResult<usize> {
        use kanban_domain::query::sprint::get_sprint_uncompleted_cards;

        let from_sprint = self
            .get_sprint(from_sprint_id)?
            .ok_or_else(|| KanbanError::not_found("sprint", from_sprint_id))?;
        if from_sprint.status != kanban_domain::SprintStatus::Completed
            && from_sprint.status != kanban_domain::SprintStatus::Cancelled
        {
            return Err(KanbanError::validation(format!(
                "Source sprint must be Completed or Cancelled, got {:?}",
                from_sprint.status
            )));
        }
        let to_sprint = self
            .get_sprint(to_sprint_id)?
            .ok_or_else(|| KanbanError::not_found("sprint", to_sprint_id))?;
        if to_sprint.status != kanban_domain::SprintStatus::Planning {
            return Err(KanbanError::validation(format!(
                "Target sprint must be Planning, got {:?}",
                to_sprint.status
            )));
        }

        let all_cards = self.backend.list_all_cards()?;
        let ids: Vec<Uuid> = get_sprint_uncompleted_cards(from_sprint_id, &all_cards)
            .iter()
            .map(|c| c.id)
            .collect();
        self.assign_cards_to_sprint(ids, to_sprint_id)
    }

    fn create_sprint(
        &mut self,
        board_id: Uuid,
        prefix: Option<String>,
        name: Option<String>,
    ) -> KanbanResult<Sprint> {
        use kanban_domain::commands::CreateSprint;

        let default_sprint_prefix = self
            .app_config
            .effective_default_sprint_prefix()
            .to_string();

        let id = Uuid::new_v4();
        let cmd = Command::Sprint(SprintCommand::Create(CreateSprint {
            id,
            board_id,
            name,
            default_sprint_prefix,
            explicit_prefix: prefix,
            auto_consume_name: false,
        }));
        self.execute(vec![cmd])?;
        self.get_sprint(id)?.ok_or_else(|| {
            KanbanError::Internal("Sprint creation succeeded but sprint not found".into())
        })
    }

    fn list_sprints(&self, board_id: Uuid) -> KanbanResult<Vec<Sprint>> {
        self.backend.list_sprints_by_board(board_id)
    }

    fn get_sprint(&self, id: Uuid) -> KanbanResult<Option<Sprint>> {
        self.backend.get_sprint(id)
    }

    fn update_sprint(&mut self, id: Uuid, updates: SprintUpdate) -> KanbanResult<Sprint> {
        use kanban_domain::commands::UpdateSprint;
        let cmd = Command::Sprint(SprintCommand::Update(UpdateSprint {
            sprint_id: id,
            updates,
        }));
        self.execute(vec![cmd])?;
        self.get_sprint(id)?
            .ok_or_else(|| KanbanError::not_found("sprint", id))
    }

    fn activate_sprint(&mut self, id: Uuid, duration_days: Option<i32>) -> KanbanResult<Sprint> {
        use kanban_domain::commands::ActivateSprint;
        let duration = duration_days.unwrap_or(14) as u32;
        let cmd = Command::Sprint(SprintCommand::Activate(ActivateSprint {
            sprint_id: id,
            duration_days: duration,
        }));
        self.execute(vec![cmd])?;
        self.get_sprint(id)?
            .ok_or_else(|| KanbanError::not_found("sprint", id))
    }

    fn complete_sprint(&mut self, id: Uuid) -> KanbanResult<Sprint> {
        use kanban_domain::commands::CompleteSprint;
        let cmd = Command::Sprint(SprintCommand::Complete(CompleteSprint { sprint_id: id }));
        self.execute(vec![cmd])?;
        self.get_sprint(id)?
            .ok_or_else(|| KanbanError::not_found("sprint", id))
    }

    fn cancel_sprint(&mut self, id: Uuid) -> KanbanResult<Sprint> {
        use kanban_domain::commands::CancelSprint;
        let cmd = Command::Sprint(SprintCommand::Cancel(CancelSprint { sprint_id: id }));
        self.execute(vec![cmd])?;
        self.get_sprint(id)?
            .ok_or_else(|| KanbanError::not_found("sprint", id))
    }

    fn delete_sprint(&mut self, id: Uuid) -> KanbanResult<()> {
        use kanban_domain::commands::DeleteSprint;
        let cmd = Command::Sprint(SprintCommand::Delete(DeleteSprint {
            sprint_id: id,
            timestamp: chrono::Utc::now(),
        }));
        self.execute(vec![cmd])
    }

    fn export_board(&self, board_id: Option<Uuid>) -> KanbanResult<String> {
        let snapshot = if let Some(id) = board_id {
            let boards: Vec<_> = self
                .backend
                .list_boards()?
                .into_iter()
                .filter(|b| b.id == id)
                .collect();
            let columns = self.backend.list_columns_by_board(id)?;
            let column_ids: Vec<_> = columns.iter().map(|c| c.id).collect();
            let cards: Vec<_> = self
                .backend
                .list_all_cards()?
                .into_iter()
                .filter(|c| column_ids.contains(&c.column_id))
                .collect();
            let sprints = self.backend.list_sprints_by_board(id)?;
            let graph = self.backend.get_graph()?;
            Snapshot {
                boards,
                columns,
                cards,
                archived_cards: vec![],
                sprints,
                graph,
            }
        } else {
            self.backend.snapshot()?
        };

        serde_json::to_string_pretty(&snapshot)
            .map_err(|e| PersistenceError::Serialization(e.to_string()).into())
    }

    fn import_board(&mut self, data: &str) -> KanbanResult<Board> {
        use kanban_domain::commands::ImportEntities;

        let imported: Snapshot = serde_json::from_str(data)
            .map_err(|e| PersistenceError::Serialization(e.to_string()))?;

        let board = imported
            .boards
            .first()
            .cloned()
            .ok_or_else(|| KanbanError::validation("No board in import data"))?;

        let commands = vec![Command::Board(BoardCommand::Import(ImportEntities {
            boards: imported.boards,
            columns: imported.columns,
            cards: imported.cards,
            archived_cards: imported.archived_cards,
            sprints: imported.sprints,
            graph: Some(imported.graph),
        }))];

        {
            let store: &dyn DataStore = self.backend.as_data_store();
            let ctx = CommandContext { store };
            for cmd in &commands {
                cmd.execute(&ctx)?;
            }
        }

        self.baseline_snapshot = Some(self.backend.snapshot()?);
        self.backend.truncate_commands_after(0)?;
        self.undo_cursor = 0;
        self.command_count = 0;
        self.dirty = true;
        self.notify_undo_state()?;

        Ok(board)
    }
}