Skip to main content

kanban_service/
store_manager.rs

1use crate::config;
2use crate::AppConfig;
3use kanban_domain::{DataStore, KanbanError};
4use kanban_persistence::{
5    snapshot_from_json_bytes, PersistenceStore, StoreRegistry, StoreSnapshot,
6};
7use std::collections::HashSet;
8use std::sync::Arc;
9
10/// Owns the `StoreRegistry` and `KanbanBackendRegistry` and exposes the
11/// high-level operations that used to live as free functions in
12/// `kanban_service`. Callers (the CLI, TUI, MCP) construct a `StoreManager`
13/// with whichever factories they want available, then thread it through
14/// request handlers — inverting the old model where `kanban-service`
15/// hard-coded `default_registry()`.
16pub struct StoreManager {
17    registry: Arc<StoreRegistry>,
18    backends: Arc<kanban_backend::KanbanBackendRegistry>,
19}
20
21impl StoreManager {
22    /// Wraps `registry` and `backends` in an `Arc` each. Cloning a
23    /// `StoreManager` is cheap — all clones share the same underlying
24    /// registries.
25    pub fn new(registry: StoreRegistry, backends: kanban_backend::KanbanBackendRegistry) -> Self {
26        Self {
27            registry: Arc::new(registry),
28            backends: Arc::new(backends),
29        }
30    }
31
32    /// Returns a reference to the underlying `StoreRegistry`.
33    /// Useful for introspection and testing.
34    pub fn registry(&self) -> &StoreRegistry {
35        &self.registry
36    }
37
38    /// Returns `true` if at least one backend factory is registered.
39    pub fn has_backends(&self) -> bool {
40        !self.backends.is_empty()
41    }
42
43    /// Returns the names of all registered factories in registration order.
44    pub fn backend_names(&self) -> Vec<&str> {
45        self.registry.backend_names()
46    }
47
48    /// Returns `true` if `locator` points to a SQLite database — either
49    /// because `detect_backend` recognised it as `"sqlite"`, or because the
50    /// file extension matches one of the conventional SQLite extensions.
51    pub fn is_sqlite(&self, locator: &str) -> bool {
52        match self.detect_backend(locator).as_deref() {
53            Some("sqlite") => true,
54            None => {
55                locator.ends_with(".sqlite")
56                    || locator.ends_with(".sqlite3")
57                    || locator.ends_with(".db")
58            }
59            _ => false,
60        }
61    }
62
63    /// Pattern-matches `locator` against all registered factories and returns
64    /// the name of the first match. For existing SQLite files, detects by
65    /// magic bytes even when no SQLite factory is in the registry.
66    pub fn detect_backend(&self, locator: &str) -> Option<String> {
67        if let Some(name) = self.registry.detect_backend(locator) {
68            return Some(name.to_string());
69        }
70        #[cfg(feature = "sqlite")]
71        {
72            let path = std::path::Path::new(locator);
73            if path.exists() {
74                if let Ok(mut f) = std::fs::File::open(path) {
75                    use std::io::Read;
76                    let mut hdr = [0u8; 16];
77                    let n = f.read(&mut hdr).unwrap_or(0);
78                    if hdr[..n].starts_with(b"SQLite format 3\0") {
79                        return Some("sqlite".to_string());
80                    }
81                }
82            }
83        }
84        None
85    }
86
87    /// Updates `config.storage_backend` to match the backend inferred from
88    /// `locator`. Returns `true` if the config value changed.
89    pub fn sync_backend_with_file(&self, locator: &str, config: &mut AppConfig) -> bool {
90        if let Some(detected) = self.detect_backend(locator) {
91            if detected != config.effective_storage_backend() {
92                config.storage_backend = Some(detected);
93                return true;
94            }
95        }
96        false
97    }
98
99    /// Creates a [`KanbanBackend`] for `locator` by dispatching through the
100    /// injected `KanbanBackendRegistry` — the first registered factory whose
101    /// `matches_locator` accepts `locator` builds it.
102    pub async fn make_backend(
103        &self,
104        locator: &str,
105        config: &AppConfig,
106    ) -> Result<std::sync::Arc<dyn crate::backend::KanbanBackend>, KanbanError> {
107        let factory = self.backends.for_locator(locator).ok_or_else(|| {
108            KanbanError::Internal(format!(
109                "no registered backend handles '{locator}'; registered: {:?}",
110                self.backends.names()
111            ))
112        })?;
113        factory.create(locator, config).await
114    }
115
116    /// Creates a `PersistenceStore` for the named `backend` at `locator`.
117    /// Returns an error if `backend` is not registered in this manager.
118    pub fn make_store(
119        &self,
120        backend: &str,
121        locator: &str,
122    ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
123        Ok(self.registry.create_store(backend, locator)?)
124    }
125
126    /// Creates a store from an explicit file locator, or falls back to the
127    /// storage location in `config` when `file` is `None`. The backend is
128    /// inferred from the locator; if no factory matches, `config`'s backend
129    /// is used as a fallback.
130    pub fn make_store_with_config(
131        &self,
132        file: Option<&str>,
133        config: &AppConfig,
134    ) -> Result<Arc<dyn PersistenceStore + Send + Sync>, KanbanError> {
135        let locator = match file {
136            Some(path) => path.to_string(),
137            None => config::resolve_storage_location(config),
138        };
139        let backend = self
140            .detect_backend(&locator)
141            .unwrap_or_else(|| config.effective_storage_backend().to_string());
142        self.make_store(&backend, &locator)
143    }
144
145    /// Verifies `path` is a readable, valid store for `backend` without
146    /// returning its contents.
147    ///
148    /// For `.sqlite`/`.db` files, opens through `SqliteBackend` and issues a
149    /// cheap real read (`list_boards`) that proves the store is openable and
150    /// queryable, rather than deserialising the whole store: opening already
151    /// runs schema migration and fails loudly on a corrupt or future-version
152    /// file (side effects — see the comment below — are pre-existing and
153    /// intentional), so a full table scan on top of that buys nothing.
154    /// Non-SQLite backends keep a full parse: for JSON the envelope IS the
155    /// file, so "readable" means "the whole file parses"; a partial read
156    /// could miss corruption in an untouched region.
157    pub async fn validate_store_readable(
158        &self,
159        backend: &str,
160        path: &str,
161    ) -> Result<(), KanbanError> {
162        if matches!(backend, "sqlite" | "sqlite3" | "db") {
163            #[cfg(feature = "sqlite")]
164            {
165                if !std::path::Path::new(path).exists() {
166                    return Err(std::io::Error::new(
167                        std::io::ErrorKind::NotFound,
168                        format!("Storage file does not exist: {}", path),
169                    )
170                    .into());
171                }
172                // Opening runs schema migration and writes a `.v{N}.backup`;
173                // pre-existing and intentional — a validate that cannot open
174                // the file is not a validate.
175                let sqlite_backend = kanban_persistence_sqlite::SqliteBackend::open(path).await?;
176                sqlite_backend.list_boards()?;
177                return Ok(());
178            }
179            #[cfg(not(feature = "sqlite"))]
180            return Err(KanbanError::validation("sqlite feature not compiled in"));
181        }
182        let store = self.make_store(backend, path)?;
183        if !store.exists().await {
184            return Err(std::io::Error::new(
185                std::io::ErrorKind::NotFound,
186                format!("Storage file does not exist: {}", path),
187            )
188            .into());
189        }
190        let (snapshot, _metadata) = store.load().await?;
191        snapshot_from_json_bytes(&snapshot.data)?;
192        Ok(())
193    }
194
195    /// Exports a board selection to a new SQLite file.
196    ///
197    /// **Note:** The dependency graph is not part of the `AllBoardsExport` format
198    /// and will not be present in the exported file.
199    pub async fn export_to_sqlite(
200        &self,
201        export: kanban_domain::export::AllBoardsExport,
202        filename: &str,
203        config: &AppConfig,
204    ) -> Result<(), KanbanError> {
205        #[cfg(feature = "sqlite")]
206        {
207            use kanban_domain::export::BoardImporter;
208            use kanban_domain::{DependencyGraph, Snapshot};
209
210            // Mirrors migrate_store. The path this replaced wiped the
211            // destination's tables before inserting, so exporting onto an
212            // existing database silently replaced it; writing per entity would
213            // instead merge the export on top of whatever was there. Refusing
214            // an existing file makes the caller choose rather than either.
215            if std::path::Path::new(filename).exists() {
216                return Err(std::io::Error::new(
217                    std::io::ErrorKind::AlreadyExists,
218                    format!(
219                        "Destination already exists: {filename}. Remove it first or use a different path."
220                    ),
221                )
222                .into());
223            }
224
225            let mut entities = BoardImporter::extract_entities(export);
226            entities.cards = entities
227                .cards
228                .iter()
229                .map(|c| {
230                    kanban_domain::stamp_card_prefix(
231                        c,
232                        &entities.columns,
233                        &entities.boards,
234                        &entities.sprints,
235                    )
236                })
237                .collect();
238            // `AllBoardsExport` carries no counters, so they are reconstructed
239            // from the entities that consumed them. Without this the exported
240            // database hands out numbers its own cards already hold.
241            let prefixes = kanban_domain::counters_implied_by(
242                &entities.cards,
243                &entities.columns,
244                &entities.sprints,
245                &entities.boards,
246                Some(config.effective_default_sprint_prefix()),
247            );
248            let snapshot = Snapshot {
249                archived_boards: entities.archived_boards,
250                boards: entities.boards,
251                columns: entities.columns,
252                cards: entities.cards,
253                archived_cards: entities.archived_cards,
254                sprints: entities.sprints,
255                graph: DependencyGraph::default(),
256                prefixes,
257            };
258            self.write_sqlite_destination(filename, snapshot).await
259        }
260        #[cfg(not(feature = "sqlite"))]
261        {
262            let _ = export;
263            let _ = filename;
264            Err(KanbanError::validation("sqlite feature not compiled in"))
265        }
266    }
267
268    /// Copies a snapshot from one backend/path pair to another, repairing
269    /// any dangling foreign keys in the process. Rolls back (deletes the
270    /// partial destination file) on failure.
271    ///
272    /// SQLite source/destination are handled directly via `SqliteStore`;
273    /// JSON and other registry-backed backends go through the `StoreRegistry`.
274    pub async fn migrate_store(
275        &self,
276        from_backend: &str,
277        from_path: &str,
278        to_backend: &str,
279        to_path: &str,
280    ) -> Result<(), KanbanError> {
281        let from = std::path::Path::new(from_path);
282        let to = std::path::Path::new(to_path);
283        if !from.exists() {
284            return Err(std::io::Error::new(
285                std::io::ErrorKind::NotFound,
286                format!("Source file not found: {}", from.display()),
287            )
288            .into());
289        }
290        if to.exists() {
291            return Err(std::io::Error::new(
292                std::io::ErrorKind::AlreadyExists,
293                format!(
294                    "Destination already exists: {}. Remove it first or use a different path.",
295                    to.display()
296                ),
297            )
298            .into());
299        }
300
301        let leg = MigrationLeg::of(from_backend, to_backend);
302        let source_is_sqlite = matches!(
303            leg,
304            MigrationLeg::SqliteToSqlite | MigrationLeg::SqliteToJson
305        );
306        let dest_is_sqlite = matches!(
307            leg,
308            MigrationLeg::SqliteToSqlite | MigrationLeg::JsonToSqlite
309        );
310
311        // SQLite -> SQLite never touches JSON: atomic reads feed transactional
312        // writes directly. Foreign keys are checked as each row lands, so
313        // write_full_snapshot's ordering carries the correctness here, not the
314        // transaction.
315        if !leg.round_trips_through_json() {
316            #[cfg(feature = "sqlite")]
317            {
318                let snapshot = self.read_sqlite_source(from_path).await?;
319                return self.write_sqlite_destination(to_path, snapshot).await;
320            }
321            #[cfg(not(feature = "sqlite"))]
322            return Err(KanbanError::validation("sqlite feature not compiled in"));
323        }
324
325        // Every other leg has JSON on one end, so a StoreSnapshot exists and FK
326        // repair applies to it.
327        let mut store_snapshot: StoreSnapshot = if source_is_sqlite {
328            #[cfg(feature = "sqlite")]
329            {
330                use kanban_persistence::PersistenceMetadata;
331                let snapshot = self.read_sqlite_source(from_path).await?;
332                StoreSnapshot {
333                    data: kanban_persistence::snapshot_to_json_bytes(&snapshot)?,
334                    metadata: PersistenceMetadata::new(uuid::Uuid::new_v4()),
335                }
336            }
337            #[cfg(not(feature = "sqlite"))]
338            return Err(KanbanError::validation("sqlite feature not compiled in"));
339        } else {
340            let source = self.make_store(from_backend, from_path)?;
341            let (snap, _) = source.load().await?;
342            snap
343        };
344
345        repair_snapshot_fks(&mut store_snapshot)?;
346
347        if dest_is_sqlite {
348            #[cfg(feature = "sqlite")]
349            {
350                let repaired = snapshot_from_json_bytes(&store_snapshot.data)?;
351                return self.write_sqlite_destination(to_path, repaired).await;
352            }
353            #[cfg(not(feature = "sqlite"))]
354            return Err(KanbanError::validation("sqlite feature not compiled in"));
355        }
356
357        let target = self.make_store(to_backend, to_path)?;
358        let outcome = target.save(store_snapshot).await;
359        target.close().await;
360        drop(target);
361        if let Err(e) = outcome {
362            cleanup_destination_files(to_path).await;
363            return Err(e.into());
364        }
365        Ok(())
366    }
367
368    /// Reads a SQLite source into a `Snapshot` through per-entity `DataStore`
369    /// calls.
370    ///
371    /// Opening a source below `SUPPORTED_SCHEMA_VERSION` runs the same in-place
372    /// schema upgrade (and durable `.v{N}.backup`) that any kanban binary runs
373    /// against that file — reading a schema-current workspace requires it.
374    #[cfg(feature = "sqlite")]
375    async fn read_sqlite_source(
376        &self,
377        from_path: &str,
378    ) -> Result<kanban_domain::Snapshot, KanbanError> {
379        use kanban_backend::KanbanBackend;
380
381        let backend = kanban_persistence_sqlite::SqliteBackend::open(from_path).await?;
382        let snapshot = crate::store_adapter::read_full_snapshot(backend.as_data_store());
383        backend.close().await;
384        drop(backend);
385        snapshot
386    }
387
388    /// Writes a whole workspace into a SQLite destination inside one
389    /// transaction, cleaning up on failure.
390    ///
391    /// Cleanup only removes a file this call brought into existence. `migrate_store`
392    /// rejects an existing destination up front, so its behaviour is unchanged;
393    /// `export_to_sqlite` has no such guard, and deleting a database the caller
394    /// already had would turn a failed export into data loss.
395    ///
396    /// `close()` runs before the cleanup because Windows refuses to unlink a
397    /// file that still has live handles.
398    #[cfg(feature = "sqlite")]
399    async fn write_sqlite_destination(
400        &self,
401        to_path: &str,
402        snapshot: kanban_domain::Snapshot,
403    ) -> Result<(), KanbanError> {
404        use kanban_backend::KanbanBackend;
405
406        let created_here = !std::path::Path::new(to_path).exists();
407
408        let backend = kanban_persistence_sqlite::SqliteBackend::open(to_path).await?;
409        let outcome = backend.with_transaction(Box::new(|| {
410            crate::store_adapter::write_full_snapshot(backend.as_data_store(), snapshot)
411        }));
412        backend.close().await;
413        drop(backend);
414        if let Err(e) = outcome {
415            if created_here {
416                cleanup_destination_files(to_path).await;
417            }
418            return Err(e);
419        }
420        Ok(())
421    }
422}
423
424impl Clone for StoreManager {
425    fn clone(&self) -> Self {
426        Self {
427            registry: Arc::clone(&self.registry),
428            backends: Arc::clone(&self.backends),
429        }
430    }
431}
432
433/// Best-effort `remove_file` that retries with linear backoff. SQLite on
434/// Windows can briefly hold a file handle even after `PersistenceStore::close`
435/// returns, because the OS-level handle release is asynchronous and lags the
436/// pool's synchronization. POSIX always succeeds on the first try.
437async fn remove_file_with_windows_retry(path: &std::path::Path) {
438    for delay_ms in [0u64, 50, 100, 200, 400] {
439        if delay_ms > 0 {
440            tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;
441        }
442        if std::fs::remove_file(path).is_ok() {
443            return;
444        }
445        if !path.exists() {
446            return;
447        }
448    }
449    tracing::warn!(
450        path = %path.display(),
451        "failed to remove file after retry backoff; orphan may remain on disk"
452    );
453}
454
455/// Remove the main destination and its SQLite WAL/SHM sidecars (best-effort).
456/// The sidecars are named `<path>-wal` and `<path>-shm` regardless of the
457/// main file's extension, so they're constructed by appending to the raw
458/// path string rather than via `Path::with_extension`.
459fn is_sqlite_backend(name: &str) -> bool {
460    matches!(name, "sqlite" | "sqlite3" | "db")
461}
462
463/// Which of the four source/destination combinations a migration takes.
464/// `SqliteToSqlite` is the one leg that carries no JSON at all.
465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466pub(crate) enum MigrationLeg {
467    SqliteToSqlite,
468    SqliteToJson,
469    JsonToSqlite,
470    JsonToJson,
471}
472
473impl MigrationLeg {
474    pub(crate) fn of(from_backend: &str, to_backend: &str) -> Self {
475        match (
476            is_sqlite_backend(from_backend),
477            is_sqlite_backend(to_backend),
478        ) {
479            (true, true) => Self::SqliteToSqlite,
480            (true, false) => Self::SqliteToJson,
481            (false, true) => Self::JsonToSqlite,
482            (false, false) => Self::JsonToJson,
483        }
484    }
485
486    /// Whether this leg serialises through JSON bytes. Only `SqliteToSqlite`
487    /// does not, and that is therefore the one leg FK repair cannot run on. It
488    /// does not need it: its source is a relational database that already
489    /// enforced those keys on the way in.
490    pub(crate) fn round_trips_through_json(self) -> bool {
491        !matches!(self, Self::SqliteToSqlite)
492    }
493}
494
495async fn cleanup_destination_files(to_path: &str) {
496    remove_file_with_windows_retry(std::path::Path::new(to_path)).await;
497    let wal = format!("{}-wal", to_path);
498    let shm = format!("{}-shm", to_path);
499    remove_file_with_windows_retry(std::path::Path::new(&wal)).await;
500    remove_file_with_windows_retry(std::path::Path::new(&shm)).await;
501}
502
503fn repair_snapshot_fks(snapshot: &mut StoreSnapshot) -> Result<(), KanbanError> {
504    let mut data: serde_json::Value = serde_json::from_slice(&snapshot.data).map_err(|e| {
505        KanbanError::validation(format!("Failed to parse snapshot for FK repair: {e}"))
506    })?;
507
508    let valid_columns: HashSet<String> = data["columns"]
509        .as_array()
510        .map(|arr| {
511            arr.iter()
512                .filter_map(|c| c["id"].as_str().map(String::from))
513                .collect()
514        })
515        .unwrap_or_default();
516
517    let valid_sprints: HashSet<String> = data["sprints"]
518        .as_array()
519        .map(|arr| {
520            arr.iter()
521                .filter_map(|s| s["id"].as_str().map(String::from))
522                .collect()
523        })
524        .unwrap_or_default();
525
526    let fallback_column: Option<String> = data["columns"].as_array().and_then(|arr| {
527        arr.iter()
528            .min_by_key(|c| c["position"].as_i64().unwrap_or(i64::MAX))
529            .and_then(|c| c["id"].as_str())
530            .map(String::from)
531    });
532
533    if let Some(cards) = data["cards"].as_array_mut() {
534        for card in cards.iter_mut() {
535            fix_card_fks(
536                card,
537                &valid_columns,
538                &valid_sprints,
539                fallback_column.as_deref(),
540            );
541        }
542        // Live cards must land in a real column. The SQLite `cards.column_id`
543        // FK used to reject an orphan on save; it was dropped (KAN-832) so an
544        // archived card can keep a dangling historical column, which also
545        // removed that backstop for LIVE cards. `fix_card_fks` moved every
546        // fixable card to the fallback column, so a card still pointing outside
547        // `valid_columns` had no column to reassign to and is unrepairable —
548        // fail explicitly (archived cards are intentionally exempt: their
549        // column reference is historical and may dangle).
550        let orphaned = cards
551            .iter()
552            .filter(|card| {
553                card["column_id"]
554                    .as_str()
555                    .is_some_and(|c| !valid_columns.contains(c))
556            })
557            .count();
558        if orphaned > 0 {
559            return Err(KanbanError::validation(format!(
560                "cannot migrate: {orphaned} live card(s) reference a column that does not \
561                 exist and there is no column to reassign them to"
562            )));
563        }
564    }
565
566    // Archived cards are pure markers ({ entity_id, archived_at, board_id }); the
567    // archived card's live row is repaired by the `cards` loop above. There is no
568    // embedded `card` to fix here since the V10 migration ran before FK repair.
569
570    snapshot.data = serde_json::to_vec(&data).map_err(|e| {
571        KanbanError::validation(format!("Failed to serialize repaired snapshot: {e}"))
572    })?;
573
574    Ok(())
575}
576
577fn fix_card_fks(
578    card: &mut serde_json::Value,
579    valid_columns: &HashSet<String>,
580    valid_sprints: &HashSet<String>,
581    fallback_column: Option<&str>,
582) {
583    if let Some(sprint_id) = card["sprint_id"].as_str() {
584        if !valid_sprints.contains(sprint_id) {
585            card["sprint_id"] = serde_json::Value::Null;
586        }
587    }
588    if let Some(col_id) = card["column_id"].as_str() {
589        if !valid_columns.contains(col_id) {
590            if let Some(fb) = fallback_column {
591                card["column_id"] = serde_json::Value::String(fb.to_string());
592            }
593        }
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600    use kanban_persistence::{PersistenceMetadata, StoreRegistry};
601    use tempfile::tempdir;
602    use uuid::Uuid;
603
604    #[test]
605    fn test_sqlite_to_sqlite_leg_does_not_round_trip_through_json() {
606        // The whole point of the adapter: a SQLite-to-SQLite move reads
607        // atomically straight into transactional writes, with no intermediate
608        // serialisation. Asserted on the routing decision so it cannot regress
609        // into a JSON round trip unnoticed.
610        for (from, to) in [("sqlite", "sqlite"), ("sqlite3", "db"), ("db", "sqlite3")] {
611            let leg = MigrationLeg::of(from, to);
612            assert_eq!(leg, MigrationLeg::SqliteToSqlite, "{from} -> {to}");
613            assert!(
614                !leg.round_trips_through_json(),
615                "{from} -> {to} must not serialise through JSON"
616            );
617        }
618    }
619
620    #[test]
621    fn test_every_leg_with_json_on_one_end_round_trips_through_json() {
622        // FK repair operates on JSON bytes, so it can only run where they exist.
623        for (from, to, expected) in [
624            ("sqlite", "json", MigrationLeg::SqliteToJson),
625            ("json", "sqlite", MigrationLeg::JsonToSqlite),
626            ("json", "json", MigrationLeg::JsonToJson),
627        ] {
628            let leg = MigrationLeg::of(from, to);
629            assert_eq!(leg, expected, "{from} -> {to}");
630            assert!(
631                leg.round_trips_through_json(),
632                "{from} -> {to} carries a StoreSnapshot, so FK repair applies"
633            );
634        }
635    }
636
637    fn make_snapshot_with_json(data: serde_json::Value) -> StoreSnapshot {
638        StoreSnapshot {
639            data: serde_json::to_vec(&data).unwrap(),
640            metadata: PersistenceMetadata::new(Uuid::new_v4()),
641        }
642    }
643
644    /// Drift guard: verifies that an archived card whose live row has a dangling
645    /// column_id gets the live row repaired (moved to fallback column) without
646    /// erroring, and the marker entry is left unchanged with no `card` key.
647    #[test]
648    fn test_repair_snapshot_fks_repairs_live_row_of_archived_card() {
649        let valid_col_id = Uuid::new_v4().to_string();
650        let dangling_col_id = Uuid::new_v4().to_string();
651        let card_id = Uuid::new_v4().to_string();
652        let board_id = Uuid::new_v4().to_string();
653
654        let data = serde_json::json!({
655            "boards": [{"id": board_id}],
656            "columns": [{"id": valid_col_id, "position": 0}],
657            "sprints": [],
658            "cards": [{
659                "id": card_id,
660                "column_id": dangling_col_id,
661                "sprint_id": null
662            }],
663            "archived_cards": [{
664                "entity_id": card_id,
665                "board_id": board_id,
666                "archived_at": "2024-01-01T00:00:00Z"
667            }]
668        });
669
670        let mut snapshot = make_snapshot_with_json(data);
671        repair_snapshot_fks(&mut snapshot)
672            .expect("repair must succeed for archived card with dangling column");
673
674        let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
675
676        assert_eq!(
677            repaired["cards"][0]["column_id"].as_str().unwrap(),
678            valid_col_id,
679            "live card row must be reassigned to fallback column"
680        );
681        let marker = &repaired["archived_cards"][0];
682        assert!(
683            marker.get("card").is_none(),
684            "marker must have no embedded `card` key (pure marker shape)"
685        );
686        assert_eq!(marker["entity_id"].as_str().unwrap(), card_id);
687        assert_eq!(marker["board_id"].as_str().unwrap(), board_id);
688    }
689
690    /// Drift guard: verifies that a marker-only archived_cards entry passes
691    /// through repair_snapshot_fks byte-identical. Pins the marker-shape contract
692    /// so a future reader cannot silently re-add an embed-handling branch.
693    #[test]
694    fn test_repair_snapshot_fks_marker_archived_cards_pass_through_unchanged() {
695        let col_id = Uuid::new_v4().to_string();
696        let card_id = Uuid::new_v4().to_string();
697        let board_id = Uuid::new_v4().to_string();
698
699        let archived_entry = serde_json::json!({
700            "entity_id": card_id,
701            "board_id": board_id,
702            "archived_at": "2024-01-01T00:00:00Z"
703        });
704
705        let data = serde_json::json!({
706            "boards": [],
707            "columns": [{"id": col_id, "position": 0}],
708            "sprints": [],
709            "cards": [{"id": card_id, "column_id": col_id, "sprint_id": null}],
710            "archived_cards": [archived_entry.clone()]
711        });
712
713        let mut snapshot = make_snapshot_with_json(data);
714        repair_snapshot_fks(&mut snapshot).expect("repair must succeed");
715
716        let repaired: serde_json::Value = serde_json::from_slice(&snapshot.data).unwrap();
717        let marker_after = &repaired["archived_cards"][0];
718
719        assert_eq!(
720            marker_after["entity_id"].as_str().unwrap(),
721            card_id,
722            "entity_id must be unchanged"
723        );
724        assert_eq!(
725            marker_after["board_id"].as_str().unwrap(),
726            board_id,
727            "board_id must be unchanged"
728        );
729        assert!(
730            marker_after.get("card").is_none(),
731            "no `card` embed must be present before or after repair"
732        );
733    }
734
735    fn make_sm() -> StoreManager {
736        let mut registry = StoreRegistry::new();
737        #[cfg(feature = "sqlite")]
738        registry.register(Box::new(kanban_persistence_sqlite::SqliteStoreFactory));
739        // kanban-persistence-json is an unconditional dev-dependency of kanban-service (see
740        // KAN-1027-C, which removes its production feature gate entirely) — registering it
741        // unconditionally here, rather than behind `#[cfg(feature = "json")]`, avoids ever
742        // creating a gate that becomes permanently dead once that feature is deleted.
743        registry.register(Box::new(kanban_persistence_json::JsonStoreFactory));
744        let mut backends = kanban_backend::KanbanBackendRegistry::new();
745        #[cfg(feature = "sqlite")]
746        backends.register(Box::new(kanban_persistence_sqlite::SqliteBackendFactory));
747        backends.register(Box::new(kanban_persistence_json::JsonBackendFactory));
748        StoreManager::new(registry, backends)
749    }
750
751    #[tokio::test(flavor = "multi_thread")]
752    async fn test_make_backend_errors_for_unregistered_locator() {
753        let dir = tempdir().unwrap();
754        let path = dir.path().join("test.json");
755        let sm = StoreManager::new(
756            StoreRegistry::new(),
757            kanban_backend::KanbanBackendRegistry::new(),
758        );
759        let cfg = AppConfig::default();
760        let err = sm
761            .make_backend(path.to_str().unwrap(), &cfg)
762            .await
763            .err()
764            .expect("empty registry must not silently pick a backend");
765        let msg = err.to_string();
766        assert!(
767            msg.contains("no registered backend handles"),
768            "expected unregistered-locator error, got: {msg}"
769        );
770    }
771
772    #[tokio::test(flavor = "multi_thread")]
773    async fn test_make_backend_json_path_returns_json_data_store() {
774        let dir = tempdir().unwrap();
775        let path = dir.path().join("test.json");
776        let sm = make_sm();
777        let cfg = AppConfig::default();
778        let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
779        assert!(!backend.needs_flush(), "new JSON backend starts clean");
780        assert!(
781            backend.needs_save_worker(),
782            "JSON backend requires a background flush worker"
783        );
784    }
785
786    #[cfg(feature = "sqlite")]
787    mod sqlite_backend_tests {
788        use super::*;
789
790        #[tokio::test(flavor = "multi_thread")]
791        async fn test_make_backend_sqlite_path_returns_sqlite_store() {
792            let dir = tempdir().unwrap();
793            let path = dir.path().join("test.sqlite");
794            let sm = make_sm();
795            let cfg = AppConfig::default();
796            let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
797            assert!(!backend.needs_flush(), "new SQLite backend starts clean");
798            assert!(
799                !backend.needs_save_worker(),
800                "SQLite backend is write-through and does not need a save worker"
801            );
802        }
803
804        #[tokio::test(flavor = "multi_thread")]
805        async fn test_make_backend_detects_sqlite_by_magic_bytes() {
806            let dir = tempdir().unwrap();
807            let path = dir.path().join("noext");
808
809            // Create a real SQLite file with no extension so the registry can
810            // detect it via magic bytes.
811            kanban_persistence_sqlite::SqliteStore::open(path.to_str().unwrap())
812                .await
813                .unwrap();
814
815            let sm = make_sm();
816            let cfg = AppConfig::default();
817            let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
818            assert!(
819                !backend.needs_save_worker(),
820                "magic-byte SQLite detection should yield a write-through backend"
821            );
822            let boards = backend.list_boards().unwrap();
823            assert!(boards.is_empty());
824        }
825
826        #[tokio::test(flavor = "multi_thread")]
827        async fn test_make_backend_detects_json_by_content() {
828            use kanban_persistence::{PersistenceMetadata, PersistenceStore, StoreSnapshot};
829            let dir = tempdir().unwrap();
830            let path = dir.path().join("noext");
831
832            // Write a valid JSON envelope file with no extension so the registry
833            // detects it as JSON via content sniffing (first byte is '{').
834            {
835                let jfs = kanban_persistence_json::JsonFileStore::new(&path);
836                let snap = kanban_domain::Snapshot::new();
837                let data = kanban_persistence::snapshot_to_json_bytes(&snap).unwrap();
838                let meta = PersistenceMetadata::new(uuid::Uuid::new_v4());
839                jfs.save(StoreSnapshot {
840                    data,
841                    metadata: meta,
842                })
843                .await
844                .unwrap();
845            }
846
847            let sm = make_sm();
848            let cfg = AppConfig::default();
849            let backend = sm.make_backend(path.to_str().unwrap(), &cfg).await.unwrap();
850            assert!(
851                backend.needs_save_worker(),
852                "content-sniffed JSON backend requires a save worker"
853            );
854            let boards = backend.list_boards().unwrap();
855            assert!(boards.is_empty());
856        }
857    }
858}