kanban-service 0.7.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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
use crate::backend::KanbanBackend;
use kanban_core::AppConfig;
use kanban_domain::commands::{
    AddBlocks, AddRelates, AddSpawns, BoardCommand, CardCommand, ColumnCommand, Command,
    CommandContext, DependencyCommand, RemoveBlocks, RemoveRelates, RemoveSpawns, SprintCommand,
};
use kanban_domain::{
    ArchivedCard, Board, BoardUpdate, Card, CardListFilter, CardStatus, CardSummary, CardUpdate,
    Column, ColumnUpdate, DataStore, DependencyGraph, FieldUpdate, GraphOperations,
    KanbanOperations, RelatesKind, Severity, 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,
}

/// 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).
///
/// # Undo / Redo model
///
/// Every undoable command captures an **inverse** at execute time. The
/// `(forward, inverse)` pair lives on the per-session [`UndoStack`].
/// Undo executes the inverse against current state through the normal
/// command-execute path — no snapshot apply, no replay. Redo re-executes
/// the forward batch.
///
/// `execute` also appends the forward batch to the `CommandStore` audit
/// log (`backend.append_commands`). The audit log is informational — it
/// records what happened; it does not drive undo. Audit-log UI is KAN-36.
pub struct KanbanContext {
    backend: Arc<dyn KanbanBackend>,
    app_config: AppConfig,
    /// Per-session inverse-command undo state.
    undo_stack: crate::undo_stack::UndoStack,
    dirty: bool,
    conflict_pending: bool,
}

impl KanbanContext {
    /// Zero-I/O constructor. Wraps `backend` without reading any data.
    /// Use [`open`][Self::open] instead when a lazy backend's load
    /// errors should surface at construction time.
    pub fn open_deferred(backend: Arc<dyn KanbanBackend>, config: AppConfig) -> Self {
        Self {
            backend,
            app_config: config,
            undo_stack: crate::undo_stack::UndoStack::new(),
            dirty: false,
            conflict_pending: false,
        }
    }

    /// Wraps `backend` and forces a lazy backend's I/O so any
    /// deserialization or read failure surfaces here, before the
    /// caller starts mutating.
    pub async fn open(backend: Arc<dyn KanbanBackend>, config: AppConfig) -> KanbanResult<Self> {
        let ctx = Self::open_deferred(backend, config);
        ctx.backend.command_count()?;
        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)
    }

    /// Metadata for the underlying persistence store: format version, writer
    /// kanban version, writer commit, last save time. Returns `None` for
    /// in-memory backends or before the underlying file has been loaded.
    /// Surfaced by the TUI F12 diagnostics panel.
    pub fn persistence_metadata(&self) -> Option<kanban_persistence::PersistenceMetadata> {
        self.backend.persistence_metadata()
    }

    /// Replace the active backend, discarding all undo/redo history.
    pub fn replace_backend(&mut self, backend: Arc<dyn KanbanBackend>) {
        tracing::info!("Replacing backend; undo/redo history discarded");
        self.backend = backend;
        self.undo_stack.clear();
        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)
    }

    // ── Data migrations ───────────────────────────────────────────────────────

    /// Backfill `sprint_logs` for cards that have a `sprint_id` but empty logs.
    ///
    /// This is a one-time data-migration utility, not a regular operation —
    /// it bypasses the undo stack on purpose. The actual rule for what
    /// constitutes a correctly migrated log lives in
    /// [`kanban_domain::card_lifecycle::migrate_sprint_logs`]; this method
    /// just orchestrates the read → transform → persist-changed loop.
    ///
    /// `sprints` and `boards` are passed by shared reference to the pure
    /// function — they are reference data only, never mutated, so the
    /// persist loop correctly iterates `cards` alone.
    ///
    /// Returns the number of cards that received a backfilled log.
    pub fn migrate_sprint_logs(&mut self) -> KanbanResult<usize> {
        let mut cards = self.backend.list_all_cards()?;
        let sprints = self.backend.list_all_sprints()?;
        let boards = self.backend.list_boards()?;
        let before_logs: Vec<_> = cards.iter().map(|c| c.sprint_logs.clone()).collect();
        let count =
            kanban_domain::card_lifecycle::migrate_sprint_logs(&mut cards, &sprints, &boards);
        if count > 0 {
            // Invalidate the entire undo history — a data migration
            // mutates state outside the command pipeline, so any
            // inverse captured before the migration would now reference
            // stale entity values.
            self.undo_stack.clear();
            tracing::info!("Migrated sprint logs for {} card(s)", count);
            for (card, before) in cards.into_iter().zip(before_logs) {
                if card.sprint_logs != before {
                    self.backend.upsert_card(card)?;
                }
            }
            self.dirty = true;
        }
        Ok(count)
    }

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

    /// Execute a batch as one undo unit. Entity mutations, inverse
    /// capture, and audit-log append run inside one transaction —
    /// either all commit or all roll back.
    ///
    /// Each command's inverse is captured against the state the
    /// previous command left behind. The composed inverse is the
    /// per-command inverses in reverse order, so undoing each `Fk_inv`
    /// runs against the state `Fk` itself saw at capture time.
    pub fn execute(&mut self, commands: Vec<Command>) -> KanbanResult<()> {
        let backend = Arc::clone(&self.backend);
        let cmds = &commands;
        let mut per_cmd_inverses: Vec<Vec<Command>> = Vec::new();
        self.backend.with_transaction(&mut || {
            let store: &dyn DataStore = backend.as_data_store();
            let ctx = CommandContext { store };
            for cmd in cmds.iter() {
                per_cmd_inverses.push(cmd.capture_inverse(store)?);
                cmd.execute(&ctx)?;
            }
            backend.append_commands(cmds)?;
            Ok(())
        })?;
        let inverses: Vec<Command> = per_cmd_inverses.into_iter().rev().flatten().collect();

        self.undo_stack.push(crate::undo_stack::UndoEntry {
            forward: commands,
            inverse: inverses,
        });

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

    /// Undo the most recent batch via inverse-command execution.
    /// The cursor advances only if the inverse commits successfully —
    /// a failed undo leaves the stack ready to retry the same entry.
    pub fn undo(&mut self) -> KanbanResult<bool> {
        let inverse = match self.undo_stack.peek_undo() {
            Some(entry) => entry.inverse.clone(),
            None => return Ok(false),
        };
        let backend = Arc::clone(&self.backend);
        let inv = &inverse;
        self.backend.with_transaction(&mut || {
            let store: &dyn DataStore = backend.as_data_store();
            let ctx = CommandContext { store };
            inv.iter().try_for_each(|cmd| cmd.execute(&ctx))
        })?;
        self.undo_stack.commit_undo();
        self.dirty = true;
        Ok(true)
    }

    /// Redo the next undone batch via forward-command execution.
    /// The cursor advances only if the forward batch commits — a failed
    /// redo leaves the stack ready to retry the same entry.
    pub fn redo(&mut self) -> KanbanResult<bool> {
        let forward = match self.undo_stack.peek_redo() {
            Some(entry) => entry.forward.clone(),
            None => return Ok(false),
        };
        let backend = Arc::clone(&self.backend);
        let fwd = &forward;
        self.backend.with_transaction(&mut || {
            let store: &dyn DataStore = backend.as_data_store();
            let ctx = CommandContext { store };
            fwd.iter().try_for_each(|cmd| cmd.execute(&ctx))
        })?;
        self.undo_stack.commit_redo();
        self.dirty = true;
        Ok(true)
    }

    pub fn can_undo(&self) -> bool {
        self.undo_stack.can_undo()
    }

    pub fn can_redo(&self) -> bool {
        self.undo_stack.can_redo()
    }

    /// Drop the per-session undo/redo history. The audit log is
    /// append-only and is not touched.
    pub fn clear_history(&mut self) -> KanbanResult<()> {
        self.undo_stack.clear();
        Ok(())
    }

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

    pub fn redo_depth(&self) -> usize {
        self.undo_stack.redo_depth()
    }

    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. Drops the per-session `UndoStack` (entity ids from
    /// before the reload may no longer exist). The audit log is left
    /// untouched — it records what happened, and a reload does not
    /// unhappen it.
    pub async fn reload(&mut self) -> KanbanResult<()> {
        self.backend.reload().await?;
        self.undo_stack.clear();
        self.dirty = false;
        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 {
        // Dedup at the input boundary so the per-id classification loop both
        // (a) reports each invalid id once in `failed` and (b) reports each
        // valid id once in `succeeded`, matching the one `MoveCard` per
        // unique id that `compute_move_positions` will emit. Also avoids
        // redundant get_card calls for the same id.
        let ids = kanban_domain::card_lifecycle::dedup_preserving_order(&ids);
        let mut to_move = Vec::new();
        let mut failed = Vec::new();
        for id in ids {
            match self.backend.get_card(id) {
                Ok(Some(_)) => to_move.push(id),
                Ok(None) => failed.push(BatchOperationFailure {
                    id,
                    error: KanbanError::not_found("Card", id).to_string(),
                }),
                Err(e) => failed.push(BatchOperationFailure {
                    id,
                    error: e.to_string(),
                }),
            }
        }
        if to_move.is_empty() {
            return BatchOperationResult {
                succeeded: vec![],
                failed,
            };
        }
        let succeeded = to_move.clone();

        let chained_status_updates =
            match self.chained_status_updates_for_batch_move(&to_move, column_id) {
                Ok(v) => v,
                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(),
                    }));
                    return BatchOperationResult {
                        succeeded: vec![],
                        failed: all_failed,
                    };
                }
            };

        let batch = match self.build_move_cards_batch(&to_move, column_id, chained_status_updates) {
            Ok(b) => b,
            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(),
                }));
                return BatchOperationResult {
                    succeeded: vec![],
                    failed: all_failed,
                };
            }
        };

        match self.execute(batch) {
            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,
                }
            }
        }
    }

    /// KAN-394: given a status that's about to be applied to a card, compute the
    /// target column the card should live in (and the position to use in that
    /// column) to maintain the status ↔ completion column invariant. Returns
    /// None when no chained move is needed.
    ///
    /// The position is computed via a column-scoped `list_cards_by_column`
    /// query — same convention as `KanbanContext::move_card(_, _, None)` — so
    /// we only ever read the target column, never the full cards table.
    fn compute_target_column_for_status(
        &self,
        card_id: Uuid,
        new_status: CardStatus,
    ) -> KanbanResult<Option<(Uuid, i32)>> {
        let Some(card) = self.backend.get_card(card_id)? else {
            return Ok(None);
        };
        let Some(column) = self.backend.get_column(card.column_id)? else {
            return Ok(None);
        };
        let Some(board) = self.backend.get_board(column.board_id)? else {
            return Ok(None);
        };
        let columns = self.backend.list_columns_by_board(board.id)?;
        let Some(target_col) = kanban_domain::card_lifecycle::target_column_for_status(
            &card, new_status, &board, &columns,
        ) else {
            return Ok(None);
        };
        let pos = self.backend.list_cards_by_column(target_col)?.len() as i32;
        Ok(Some((target_col, pos)))
    }

    /// KAN-394: per-card chained status updates for a batch move. For each id
    /// in `ids`, asks the domain whether moving to `new_column_id` requires a
    /// status flip. Returns the cards that need a status update along with
    /// their target status. Cards that aren't found are silently skipped —
    /// individual `MoveCard` commands will surface the not-found error.
    fn chained_status_updates_for_batch_move(
        &self,
        ids: &[Uuid],
        new_column_id: Uuid,
    ) -> KanbanResult<Vec<(Uuid, CardStatus)>> {
        let mut updates = Vec::new();
        for &card_id in ids {
            if let Some(new_status) = self.compute_target_status_for_move(card_id, new_column_id)? {
                updates.push((card_id, new_status));
            }
        }
        Ok(updates)
    }

    /// KAN-428: build the command batch for a multi-card move into one column.
    ///
    /// Validates that every input id is a known card up front so that an
    /// unknown id surfaces as `not_found` rather than being miscounted by
    /// the batch WIP pre-check. When the target column has a WIP limit,
    /// performs a single batch-level pre-check that returns one clean
    /// `WipLimitExceeded` before any per-card command runs. The per-card
    /// `MoveCard::execute` WIP check still runs as belt-and-suspenders, but
    /// since `count_cards_in_column_excluding` is now O(column_size +
    /// exclude.len()), the redundant per-card checks are cheap.
    fn build_move_cards_batch(
        &self,
        ids: &[Uuid],
        column_id: Uuid,
        chained_status_updates: Vec<(Uuid, CardStatus)>,
    ) -> KanbanResult<Vec<Command>> {
        use kanban_domain::commands::{MoveCard, UpdateCard};
        use kanban_domain::DomainError;
        use std::collections::HashSet;

        for &id in ids {
            if self.backend.get_card(id)?.is_none() {
                return Err(KanbanError::not_found("Card", id));
            }
        }

        let existing = self.backend.list_cards_by_column(column_id)?;
        let column = self
            .backend
            .get_column(column_id)?
            .ok_or_else(|| KanbanError::not_found("Column", column_id))?;

        if let Some(limit) = column.wip_limit {
            // `moving_set.len()` is the post-dedup mover count — `compute_move_positions`
            // emits one `MoveCard` per unique id, so the pre-check must use the same
            // count to avoid a false `WipLimitExceeded` when the caller passes
            // duplicates that would actually fit under the limit.
            let moving_set: HashSet<Uuid> = ids.iter().copied().collect();
            let non_moving = existing
                .iter()
                .filter(|c| !moving_set.contains(&c.id))
                .count();
            if non_moving + moving_set.len() > limit as usize {
                return Err(KanbanError::Domain(DomainError::wip_limit_exceeded(
                    column_id,
                    limit as u32,
                )));
            }
        }

        let positions = kanban_domain::card_lifecycle::compute_move_positions(&existing, ids);

        let mut batch: Vec<Command> =
            Vec::with_capacity(positions.len() + chained_status_updates.len());
        for (card_id, new_position) in positions {
            batch.push(Command::Card(CardCommand::Move(MoveCard {
                card_id,
                new_column_id: column_id,
                new_position,
            })));
        }
        for (card_id, new_status) in chained_status_updates {
            batch.push(Command::Card(CardCommand::Update(UpdateCard {
                card_id,
                updates: CardUpdate {
                    status: Some(new_status),
                    ..Default::default()
                },
            })));
        }
        Ok(batch)
    }

    /// KAN-394: given a column the card is about to move to, compute the status
    /// the card should have to maintain the status ↔ completion column invariant.
    /// Returns None when no chained status update is needed.
    fn compute_target_status_for_move(
        &self,
        card_id: Uuid,
        new_column_id: Uuid,
    ) -> KanbanResult<Option<CardStatus>> {
        let Some(card) = self.backend.get_card(card_id)? else {
            return Ok(None);
        };
        let Some(column) = self.backend.get_column(new_column_id)? else {
            return Ok(None);
        };
        let Some(board) = self.backend.get_board(column.board_id)? else {
            return Ok(None);
        };
        let columns = self.backend.list_columns_by_board(board.id)?;
        Ok(
            kanban_domain::card_lifecycle::target_status_for_column_move(
                &card,
                new_column_id,
                &board,
                &columns,
            ),
        )
    }
}

impl KanbanContext {
    fn filter_cards(&self, filter: &CardListFilter) -> KanbanResult<Vec<Card>> {
        let cards = self.backend.list_all_cards()?;
        let board = match filter.board_id {
            Some(bid) => self.backend.get_board(bid)?,
            None => None,
        };
        let columns = match filter.board_id {
            Some(bid) => self.backend.list_columns_by_board(bid)?,
            None => Vec::new(),
        };
        let sprints = match (board.as_ref(), filter.search.as_deref()) {
            (Some(b), Some(q)) if !q.is_empty() => self.backend.list_sprints_by_board(b.id)?,
            _ => Vec::new(),
        };
        Ok(kanban_domain::filter_and_sort_cards(
            &cards,
            &columns,
            &sprints,
            board.as_ref(),
            filter,
        ))
    }
}

// ── 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<()> {
        let commands = crate::cascade::delete_board(self.backend.as_data_store(), id)?;
        self.execute(commands)
    }

    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 cards = self.filter_cards(&filter)?;
        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 list_all_cards(&self) -> KanbanResult<Vec<Card>> {
        self.backend.list_all_cards()
    }

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

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

    fn update_card(&mut self, id: Uuid, updates: CardUpdate) -> KanbanResult<Card> {
        self.update_cards(vec![(id, updates)])?;
        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, UpdateCard};
        let position = match position {
            Some(p) => p,
            None => self.backend.list_cards_by_column(column_id)?.len() as i32,
        };
        let mut batch = vec![Command::Card(CardCommand::Move(MoveCard {
            card_id: id,
            new_column_id: column_id,
            new_position: position,
        }))];

        if let Some(new_status) = self.compute_target_status_for_move(id, column_id)? {
            batch.push(Command::Card(CardCommand::Update(UpdateCard {
                card_id: id,
                updates: CardUpdate {
                    status: Some(new_status),
                    ..Default::default()
                },
            })));
        }

        self.execute(batch)?;
        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> {
        self.assign_cards_to_sprint(vec![card_id], sprint_id)?;
        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> {
        let before = self.backend.list_cards_by_column(column_id)?.len();

        let chained_status_updates = self.chained_status_updates_for_batch_move(&ids, column_id)?;
        let batch = self.build_move_cards_batch(&ids, column_id, chained_status_updates)?;

        self.execute(batch)?;
        let after = self.backend.list_cards_by_column(column_id)?.len();
        Ok(after - before)
    }

    fn update_cards(&mut self, updates: Vec<(Uuid, CardUpdate)>) -> KanbanResult<usize> {
        use kanban_domain::commands::{MoveCard, UpdateCard};
        use std::collections::HashMap;

        let count = updates.len();
        let mut batch: Vec<Command> = Vec::with_capacity(count * 2);
        // Track per-column position offsets within this batch so chained moves
        // into the same target column don't all collapse onto the same
        // position. `compute_target_column_for_status` reads `list_cards_by_column`
        // once per call against the pre-batch state.
        let mut position_offsets: HashMap<Uuid, i32> = HashMap::new();

        enum Chained {
            Move(Uuid, i32),
            Status(CardStatus),
        }

        for (card_id, card_updates) in updates {
            let chained = match (card_updates.status, card_updates.column_id) {
                (Some(new_status), None) => self
                    .compute_target_column_for_status(card_id, new_status)?
                    .map(|(col, base_pos)| {
                        let offset = position_offsets.entry(col).or_insert(0);
                        let pos = base_pos + *offset;
                        *offset += 1;
                        Chained::Move(col, pos)
                    }),
                (None, Some(new_col)) => self
                    .compute_target_status_for_move(card_id, new_col)?
                    .map(Chained::Status),
                _ => None,
            };

            batch.push(Command::Card(CardCommand::Update(UpdateCard {
                card_id,
                updates: card_updates,
            })));

            match chained {
                Some(Chained::Move(col, pos)) => {
                    batch.push(Command::Card(CardCommand::Move(MoveCard {
                        card_id,
                        new_column_id: col,
                        new_position: pos,
                    })));
                }
                Some(Chained::Status(status)) => {
                    batch.push(Command::Card(CardCommand::Update(UpdateCard {
                        card_id,
                        updates: CardUpdate {
                            status: Some(status),
                            ..Default::default()
                        },
                    })));
                }
                None => {}
            }
        }

        self.execute(batch)?;
        Ok(count)
    }

    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;
        use std::collections::HashSet;

        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 imported_column_ids: HashSet<Uuid> = imported.columns.iter().map(|c| c.id).collect();
        let existing_column_ids: HashSet<Uuid> = self
            .backend
            .list_all_columns()?
            .into_iter()
            .map(|c| c.id)
            .collect();
        for card in &imported.cards {
            if !imported_column_ids.contains(&card.column_id)
                && !existing_column_ids.contains(&card.column_id)
            {
                return Err(KanbanError::validation(format!(
                    "Card '{}' references column {} which does not exist in the import or the current store",
                    card.title, card.column_id
                )));
            }
        }

        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.undo_stack.clear();
        self.dirty = true;

        Ok(board)
    }
}

impl KanbanContext {
    /// Reject edge mutations against unknown card ids before the
    /// command reaches the graph. Without this guard a stale or
    /// fabricated UUID would silently land in the graph as a dangling
    /// edge — the CLI's identifier-resolution layer parses raw UUIDs
    /// without looking them up, so service-level enforcement is the
    /// right boundary.
    fn require_card_exists(&self, id: Uuid) -> KanbanResult<()> {
        match self.backend.get_card(id)? {
            Some(_) => Ok(()),
            None => Err(KanbanError::not_found("Card", id)),
        }
    }
}

impl GraphOperations for KanbanContext {
    fn attach_children(&mut self, parent: Uuid, children: Vec<Uuid>) -> KanbanResult<()> {
        self.require_card_exists(parent)?;
        for child in &children {
            self.require_card_exists(*child)?;
        }
        let commands: Vec<Command> = children
            .into_iter()
            .map(|child| {
                Command::Dependency(DependencyCommand::AddSpawns(AddSpawns {
                    source: parent,
                    target: child,
                    as_archived: false,
                }))
            })
            .collect();
        self.execute(commands)
    }

    fn detach_children(&mut self, parent: Uuid, children: Vec<Uuid>) -> KanbanResult<()> {
        self.require_card_exists(parent)?;
        for child in &children {
            self.require_card_exists(*child)?;
        }
        let commands: Vec<Command> = children
            .into_iter()
            .map(|child| {
                Command::Dependency(DependencyCommand::RemoveSpawns(RemoveSpawns {
                    source: parent,
                    target: child,
                    tolerate_missing: false,
                }))
            })
            .collect();
        self.execute(commands)
    }

    fn list_children_of(&self, parent: Uuid) -> KanbanResult<Vec<Uuid>> {
        self.require_card_exists(parent)?;
        Ok(self.backend.get_graph()?.children(parent))
    }

    fn list_parents_of(&self, child: Uuid) -> KanbanResult<Vec<Uuid>> {
        self.require_card_exists(child)?;
        Ok(self.backend.get_graph()?.parents(child))
    }

    fn block(&mut self, blocker: Uuid, blocked: Uuid, severity: Severity) -> KanbanResult<()> {
        self.require_card_exists(blocker)?;
        self.require_card_exists(blocked)?;
        self.execute(vec![Command::Dependency(DependencyCommand::AddBlocks(
            AddBlocks {
                source: blocker,
                target: blocked,
                severity,
                as_archived: false,
            },
        ))])
    }

    fn unblock(&mut self, blocker: Uuid, blocked: Uuid) -> KanbanResult<()> {
        self.require_card_exists(blocker)?;
        self.require_card_exists(blocked)?;
        self.execute(vec![Command::Dependency(DependencyCommand::RemoveBlocks(
            RemoveBlocks {
                source: blocker,
                target: blocked,
                tolerate_missing: false,
            },
        ))])
    }

    fn list_blocked_by(&self, blocker: Uuid) -> KanbanResult<Vec<Uuid>> {
        self.require_card_exists(blocker)?;
        Ok(self.backend.get_graph()?.blocked(blocker))
    }

    fn list_blockers_of(&self, blocked: Uuid) -> KanbanResult<Vec<Uuid>> {
        self.require_card_exists(blocked)?;
        Ok(self.backend.get_graph()?.blockers(blocked))
    }

    fn relate(&mut self, a: Uuid, b: Uuid, kind: RelatesKind) -> KanbanResult<()> {
        self.require_card_exists(a)?;
        self.require_card_exists(b)?;
        self.execute(vec![Command::Dependency(DependencyCommand::AddRelates(
            AddRelates {
                source: a,
                target: b,
                kind,
                as_archived: false,
            },
        ))])
    }

    fn dissociate(&mut self, a: Uuid, b: Uuid) -> KanbanResult<()> {
        self.require_card_exists(a)?;
        self.require_card_exists(b)?;
        self.execute(vec![Command::Dependency(DependencyCommand::RemoveRelates(
            RemoveRelates {
                source: a,
                target: b,
                tolerate_missing: false,
            },
        ))])
    }

    fn list_related_to(&self, card: Uuid) -> KanbanResult<Vec<Uuid>> {
        self.require_card_exists(card)?;
        Ok(self.backend.get_graph()?.related(card))
    }
}