wsb 0.134.3832

Workspace - A tool suite for file operations, version management, and development workflow automation
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
// Schema-Based CRUD Operations - Complete Implementation
// Following Directive D081: Complete replacement with zero backward compatibility

use anyhow::Result;
use sqlx::{Row, SqlitePool};

use crate::entities::schema_models::{
    Directive, DirectiveCategory, Feature, FeatureState, Priority, Project, Session, Task,
    TaskStatus,
};

fn parse_db_timestamp(value: &str) -> Result<chrono::DateTime<chrono::Utc>> {
    if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(value) {
        return Ok(parsed.with_timezone(&chrono::Utc));
    }
    let parsed = chrono::NaiveDateTime::parse_from_str(value, "%Y-%m-%d %H:%M:%S")?;
    Ok(parsed.and_utc())
}

/// Project CRUD operations
pub mod projects {
    use super::*;

    /// Create new project with validation
    pub async fn create(pool: &SqlitePool, name: String, description: String) -> Result<Project> {
        let next_id = get_next_project_id(pool).await?;
        let project = Project::new(next_id.clone(), name, description)
            .map_err(|e| anyhow::anyhow!("Failed to create project: {}", e))?;

        sqlx::query(r#"
            INSERT INTO projects (id, name, description, status, current_phase, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        "#)
        .bind(&project.id)
        .bind(&project.name)
        .bind(&project.description)
        .bind(&project.status)
        .bind(&project.current_phase)
        .bind(&project.created_at.to_rfc3339())
        .bind(&project.updated_at.to_rfc3339())
        .execute(pool)
        .await?;

        Ok(project)
    }

    /// Get project by ID
    pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Option<Project>> {
        let row = sqlx::query(
            r#"
            SELECT id, name, description, status, current_phase, created_at, updated_at 
            FROM projects WHERE id = ?
        "#,
        )
        .bind(id)
        .fetch_optional(pool)
        .await?;

        if let Some(row) = row {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let project = Project::from_db_row(
                row.get("id"),
                row.get("name"),
                row.get("description"),
                row.get("status"),
                row.get("current_phase"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse project from DB: {}", e))?;
            Ok(Some(project))
        } else {
            Ok(None)
        }
    }

    /// List active projects
    pub async fn list_active(pool: &SqlitePool) -> Result<Vec<Project>> {
        let rows = sqlx::query(
            r#"
            SELECT id, name, description, status, current_phase, created_at, updated_at 
            FROM projects WHERE status = 'active' ORDER BY created_at DESC
        "#,
        )
        .fetch_all(pool)
        .await?;

        let mut projects = Vec::new();
        for row in rows {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let project = Project::from_db_row(
                row.get("id"),
                row.get("name"),
                row.get("description"),
                row.get("status"),
                row.get("current_phase"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse project from DB: {}", e))?;
            projects.push(project);
        }
        Ok(projects)
    }

    /// Update project
    pub async fn update(
        pool: &SqlitePool,
        id: &str,
        name: Option<String>,
        description: Option<String>,
        current_phase: Option<String>,
    ) -> Result<()> {
        let mut project = get_by_id(pool, id)
            .await?
            .ok_or_else(|| anyhow::anyhow!("Project not found: {}", id))?;

        project
            .update(name, description, current_phase)
            .map_err(|e| anyhow::anyhow!("Failed to update project: {}", e))?;

        sqlx::query(
            r#"
            UPDATE projects 
            SET name = ?, description = ?, current_phase = ?, updated_at = ?
            WHERE id = ?
        "#,
        )
        .bind(&project.name)
        .bind(&project.description)
        .bind(&project.current_phase)
        .bind(&project.updated_at.to_rfc3339())
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Delete project (CASCADE will handle dependent entities)
    pub async fn delete(pool: &SqlitePool, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM projects WHERE id = ?")
            .bind(id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get next sequential project ID
    async fn get_next_project_id(pool: &SqlitePool) -> Result<String> {
        let max_id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM projects ORDER BY CAST(SUBSTR(id, 2) AS INTEGER) DESC LIMIT 1",
        )
        .fetch_optional(pool)
        .await?;

        match max_id {
            Some(id) => {
                let num_str = &id[1..];
                let num: u32 = num_str.parse().unwrap_or(0);
                Ok(format!("P{:03}", num + 1))
            }
            None => Ok("P001".to_string()),
        }
    }
}

/// Feature CRUD operations
pub mod features {
    use super::*;

    /// Create new feature with validation
    pub async fn create(
        pool: &SqlitePool,
        project_id: String,
        name: String,
        description: String,
        category: Option<String>,
    ) -> Result<Feature> {
        let next_id = get_next_feature_id(pool).await?;
        let feature = Feature::new(
            next_id.clone(),
            project_id.clone(),
            next_id.clone(),
            name,
            description,
            category,
        )
        .map_err(|e| anyhow::anyhow!("Failed to create feature: {}", e))?;

        sqlx::query(r#"
            INSERT INTO features (id, project_id, code, name, description, category, state, test_status, priority, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#)
        .bind(&feature.id)
        .bind(&feature.project_id)
        .bind(&feature.code)
        .bind(&feature.name)
        .bind(&feature.description)
        .bind(&feature.category)
        .bind(&feature.state)
        .bind(&feature.test_status)
        .bind(&feature.priority)
        .bind(&feature.created_at.to_rfc3339())
        .bind(&feature.updated_at.to_rfc3339())
        .execute(pool)
        .await?;

        Ok(feature)
    }

    /// Get feature by ID
    pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Option<Feature>> {
        let row = sqlx::query(r#"
            SELECT id, project_id, code, name, description, category, state, test_status, priority, notes, created_at, updated_at 
            FROM features WHERE id = ?
        "#)
        .bind(id)
        .fetch_optional(pool)
        .await?;

        if let Some(row) = row {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let feature = Feature::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("code"),
                row.get("name"),
                row.get("description"),
                row.get("category"),
                row.get("state"),
                row.get("test_status"),
                row.get("priority"),
                row.get("notes"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse feature from DB: {}", e))?;
            Ok(Some(feature))
        } else {
            Ok(None)
        }
    }

    /// List features by project
    pub async fn list_by_project(pool: &SqlitePool, project_id: &str) -> Result<Vec<Feature>> {
        let rows = sqlx::query(r#"
            SELECT id, project_id, code, name, description, category, state, test_status, priority, notes, created_at, updated_at 
            FROM features WHERE project_id = ? ORDER BY created_at DESC
        "#)
        .bind(project_id)
        .fetch_all(pool)
        .await?;

        let mut features = Vec::new();
        for row in rows {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let feature = Feature::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("code"),
                row.get("name"),
                row.get("description"),
                row.get("category"),
                row.get("state"),
                row.get("test_status"),
                row.get("priority"),
                row.get("notes"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse feature from DB: {}", e))?;
            features.push(feature);
        }
        Ok(features)
    }

    /// Update feature state
    pub async fn update_state(pool: &SqlitePool, id: &str, new_state: FeatureState) -> Result<()> {
        // Simplified implementation - just update the state directly
        sqlx::query(
            r#"
            UPDATE features 
            SET state = ?, updated_at = ?
            WHERE id = ?
        "#,
        )
        .bind(new_state.as_str())
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Delete feature (CASCADE: manually delete related tasks since feature_ids is JSON)
    pub async fn delete(pool: &SqlitePool, id: &str) -> Result<()> {
        // First, delete tasks that reference this feature_id
        // Since feature_ids is stored as JSON/text, we need to check for the feature_id
        sqlx::query("DELETE FROM tasks WHERE feature_ids = ? OR feature_ids LIKE ?")
            .bind(id) // Exact match for simple string case
            .bind(format!("%{}%", id)) // Pattern match for JSON array case
            .execute(pool)
            .await?;

        // Now delete the feature itself
        sqlx::query("DELETE FROM features WHERE id = ?")
            .bind(id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get next sequential feature ID
    async fn get_next_feature_id(pool: &SqlitePool) -> Result<String> {
        let max_id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM features ORDER BY CAST(SUBSTR(id, 2) AS INTEGER) DESC LIMIT 1",
        )
        .fetch_optional(pool)
        .await?;

        match max_id {
            Some(id) => {
                let num_str = &id[1..];
                let num: u32 = num_str.parse().unwrap_or(0);
                Ok(format!("F{:05}", num + 1))
            }
            None => Ok("F00001".to_string()),
        }
    }
}

/// Task CRUD operations
pub mod tasks {
    use super::*;

    /// Create new task with validation
    pub async fn create(
        pool: &SqlitePool,
        project_id: String,
        feature_id: String,
        task_description: String,
        category: String,
    ) -> Result<Task> {
        let next_id = get_next_task_id(pool).await?;
        let task = Task::new(
            next_id.clone(),
            project_id,
            feature_id,
            task_description,
            category,
        )
        .map_err(|e| anyhow::anyhow!("Failed to create task: {}", e))?;

        // Tasks table uses feature_ids (JSON array) and different field names
        let feature_ids_json = format!("{}", task.feature_id); // Store single feature_id as simple string for now

        sqlx::query(r#"
            INSERT INTO tasks (id, project_id, code, title, description, category, status, priority, feature_ids, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#)
        .bind(&task.id)
        .bind(&task.project_id)
        .bind(&task.id) // Using task ID as code
        .bind(&task.task) // title
        .bind(&task.task) // description (reusing task content)
        .bind(&task.category)
        .bind(&task.status)
        .bind(&task.priority)
        .bind(&feature_ids_json) // Store feature_id in feature_ids field
        .bind(&task.created_at.to_rfc3339())
        .bind(&task.updated_at.to_rfc3339())
        .execute(pool)
        .await?;

        Ok(task)
    }

    /// Get task by ID
    pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Option<Task>> {
        let row = sqlx::query(r#"
            SELECT id, project_id, feature_ids, title, category, status, priority, assigned_to, depends_on, notes, created_at, updated_at 
            FROM tasks WHERE id = ?
        "#)
        .bind(id)
        .fetch_optional(pool)
        .await?;

        if let Some(row) = row {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            // Extract first feature_id from feature_ids field
            let feature_ids_str: String = row.get("feature_ids");
            let feature_id = if feature_ids_str.starts_with('[') {
                // Handle JSON array case later
                feature_ids_str.trim_matches(['[', ']', '"']).to_string()
            } else {
                feature_ids_str // Simple string case
            };

            let task = Task::from_db_row(
                row.get("id"),
                row.get("project_id"),
                feature_id,
                row.get("title"), // task description is in title field
                row.get("priority"),
                row.get("status"),
                row.get("category"),
                row.get("depends_on"),
                row.get("assigned_to"),
                row.get("notes"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse task from DB: {}", e))?;
            Ok(Some(task))
        } else {
            Ok(None)
        }
    }

    /// List tasks by project with optional status filter
    pub async fn list_by_project(
        pool: &SqlitePool,
        project_id: &str,
        status: Option<TaskStatus>,
    ) -> Result<Vec<Task>> {
        let query = if status.is_some() {
            "SELECT id, project_id, feature_ids, title, category, status, priority, assigned_to, depends_on, notes, created_at, updated_at FROM tasks WHERE project_id = ? AND status = ? ORDER BY created_at DESC"
        } else {
            "SELECT id, project_id, feature_ids, title, category, status, priority, assigned_to, depends_on, notes, created_at, updated_at FROM tasks WHERE project_id = ? ORDER BY created_at DESC"
        };

        let rows = if let Some(status_filter) = status {
            sqlx::query(query)
                .bind(project_id)
                .bind(status_filter.as_str())
                .fetch_all(pool)
                .await?
        } else {
            sqlx::query(query).bind(project_id).fetch_all(pool).await?
        };

        let mut tasks = Vec::new();
        for row in rows {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            // Extract first feature_id from feature_ids field
            let feature_ids_str: String = row.get("feature_ids");
            let feature_id = if feature_ids_str.starts_with('[') {
                // Handle JSON array case later
                feature_ids_str.trim_matches(['[', ']', '"']).to_string()
            } else {
                feature_ids_str // Simple string case
            };

            let task = Task::from_db_row(
                row.get("id"),
                row.get("project_id"),
                feature_id,
                row.get("title"), // task description is in title field
                row.get("priority"),
                row.get("status"),
                row.get("category"),
                row.get("depends_on"),
                row.get("assigned_to"),
                row.get("notes"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse task from DB: {}", e))?;
            tasks.push(task);
        }

        Ok(tasks)
    }

    /// Update task status
    pub async fn update_status(pool: &SqlitePool, id: &str, new_status: TaskStatus) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE tasks 
            SET status = ?, updated_at = ?
            WHERE id = ?
        "#,
        )
        .bind(new_status.as_str())
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Update complete task object
    pub async fn update(pool: &SqlitePool, task: &Task) -> Result<()> {
        let feature_ids_json = format!("{}", task.feature_id);

        sqlx::query(r#"
            UPDATE tasks 
            SET title = ?, description = ?, category = ?, status = ?, priority = ?, feature_ids = ?, assigned_to = ?, depends_on = ?, notes = ?, updated_at = ?
            WHERE id = ?
        "#)
        .bind(&task.task) // title
        .bind(&task.task) // description (using task content for both)
        .bind(&task.category)
        .bind(&task.status)
        .bind(&task.priority)
        .bind(&feature_ids_json)
        .bind(&task.assigned)
        .bind(&task.dependencies)
        .bind(&task.notes)
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(&task.id)
        .execute(pool)
        .await?;
        Ok(())
    }

    /// Complete task
    pub async fn complete(
        pool: &SqlitePool,
        id: &str,
        _completion_notes: Option<String>,
    ) -> Result<()> {
        sqlx::query(
            r#"
            UPDATE tasks 
            SET status = ?, updated_at = ?
            WHERE id = ?
        "#,
        )
        .bind("completed")
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Delete task
    pub async fn delete(pool: &SqlitePool, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM tasks WHERE id = ?")
            .bind(id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get next sequential task ID
    async fn get_next_task_id(pool: &SqlitePool) -> Result<String> {
        let max_id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM tasks ORDER BY CAST(SUBSTR(id, 2) AS INTEGER) DESC LIMIT 1",
        )
        .fetch_optional(pool)
        .await?;

        match max_id {
            Some(id) => {
                let num_str = &id[1..];
                let num: u32 = num_str.parse().unwrap_or(0);
                Ok(format!("T{:06}", num + 1))
            }
            None => Ok("T000001".to_string()),
        }
    }
}

/// Session CRUD operations
pub mod sessions {
    use super::*;

    /// Create new session with validation
    pub async fn create(
        pool: &SqlitePool,
        project_id: String,
        session_name: String,
        focus_area: Option<String>,
    ) -> Result<Session> {
        let next_id = get_next_session_id(pool).await?;
        let focus = focus_area.unwrap_or_else(|| "General development".to_string());
        let session = Session::new(next_id.clone(), project_id, session_name, focus)
            .map_err(|e| anyhow::anyhow!("Failed to create session: {}", e))?;

        // Sessions table uses 'state' instead of 'status'
        sqlx::query(r#"
            INSERT INTO sessions (id, project_id, title, date, start_time, state, focus, major_achievement, completed_tasks, key_achievements, files_modified, issues_resolved, started_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#)
        .bind(&session.id)
        .bind(&session.project_id)
        .bind(&session.title)
        .bind(&session.date)
        .bind(&session.start_time)
        .bind(&session.status) // Will map to 'state' column
        .bind(&session.focus)
        .bind(&session.major_achievement)
        .bind(&session.completed_tasks)
        .bind(&session.key_achievements)
        .bind(&session.files_modified)
        .bind(&session.issues_resolved)
        .bind(&session.created_at.to_rfc3339()) // Maps to started_at
        .bind(&session.updated_at.to_rfc3339())
        .execute(pool)
        .await?;

        Ok(session)
    }

    /// List sessions by project
    pub async fn list_by_project(pool: &SqlitePool, project_id: &str) -> Result<Vec<Session>> {
        let rows = sqlx::query(r#"
            SELECT id, project_id, title, date, start_time, end_time, state, focus, major_achievement, completed_tasks, key_achievements, files_modified, issues_resolved, started_at, updated_at
            FROM sessions WHERE project_id = ? ORDER BY started_at DESC
        "#)
        .bind(project_id)
        .fetch_all(pool)
        .await?;

        let mut sessions = Vec::new();
        for row in rows {
            let started_at = parse_db_timestamp(&row.get::<String, _>("started_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let session = Session::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("title"),
                row.get("date"),
                row.get("start_time"),
                row.get("end_time"),
                row.get("state"),
                row.get("focus"),
                row.get("major_achievement"),
                row.get("completed_tasks"),
                row.get("key_achievements"),
                row.get("files_modified"),
                row.get("issues_resolved"),
                started_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse session from DB: {}", e))?;
            sessions.push(session);
        }

        Ok(sessions)
    }

    /// Get session by ID
    pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Option<Session>> {
        let row = sqlx::query(r#"
            SELECT id, project_id, title, date, start_time, end_time, state, focus, major_achievement, completed_tasks, key_achievements, files_modified, issues_resolved, started_at, updated_at
            FROM sessions WHERE id = ?
        "#)
        .bind(id)
        .fetch_optional(pool)
        .await?;

        if let Some(row) = row {
            let started_at = parse_db_timestamp(&row.get::<String, _>("started_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let session = Session::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("title"),
                row.get("date"),
                row.get("start_time"),
                row.get("end_time"),
                row.get("state"), // Map state to status
                row.get("focus"),
                row.get("major_achievement"),
                row.get("completed_tasks"),
                row.get("key_achievements"),
                row.get("files_modified"),
                row.get("issues_resolved"),
                started_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse session from DB: {}", e))?;
            Ok(Some(session))
        } else {
            Ok(None)
        }
    }

    /// Complete session
    pub async fn complete(pool: &SqlitePool, id: &str, _summary: String) -> Result<()> {
        // TODO: Implement session completion when schema is finalized
        sqlx::query(
            r#"
            UPDATE sessions 
            SET state = ?
            WHERE id = ?
        "#,
        )
        .bind("completed")
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Delete session (SET NULL will update dependent tasks and audit trails)
    pub async fn delete(pool: &SqlitePool, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM sessions WHERE id = ?")
            .bind(id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get next sequential session ID
    async fn get_next_session_id(pool: &SqlitePool) -> Result<String> {
        let max_id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM sessions ORDER BY CAST(SUBSTR(id, 2) AS INTEGER) DESC LIMIT 1",
        )
        .fetch_optional(pool)
        .await?;

        match max_id {
            Some(id) => {
                let num_str = &id[1..];
                let num: u32 = num_str.parse().unwrap_or(0);
                Ok(format!("S{:06}", num + 1))
            }
            None => Ok("S000001".to_string()),
        }
    }
}

/// Directive CRUD operations
pub mod directives {
    use super::*;

    /// Create new directive with validation
    pub async fn create(
        pool: &SqlitePool,
        project_id: String,
        title: String,
        rule: String,
        category: DirectiveCategory,
        priority: Priority,
    ) -> Result<Directive> {
        let next_id = get_next_directive_id(pool).await?;
        let directive = Directive::new(next_id.clone(), project_id, title, rule)
            .map_err(|e| anyhow::anyhow!("Failed to create directive: {}", e))?;

        sqlx::query(r#"
            INSERT INTO directives (id, project_id, code, title, rule, category, priority, status, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        "#)
        .bind(&directive.id)
        .bind(&directive.project_id)
        .bind(&directive.id) // Use directive ID as code
        .bind(&directive.title)
        .bind(&directive.rule)
        .bind(category.as_str())
        .bind(priority.as_str())
        .bind("active") // Default status
        .bind(&directive.created_at.to_rfc3339())
        .bind(&directive.updated_at.to_rfc3339())
        .execute(pool)
        .await?;

        // Fetch the created directive from database to get all fields properly set
        get_by_id(pool, &directive.id)
            .await?
            .ok_or_else(|| anyhow::anyhow!("Failed to retrieve created directive"))
    }

    /// Get directive by ID
    pub async fn get_by_id(pool: &SqlitePool, id: &str) -> Result<Option<Directive>> {
        let row = sqlx::query(r#"
            SELECT id, project_id, title, rule, priority, status, context, rationale, category, created_at, updated_at 
            FROM directives WHERE id = ?
        "#)
        .bind(id)
        .fetch_optional(pool)
        .await?;

        if let Some(row) = row {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let directive = Directive::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("title"),
                row.get("rule"),
                row.get("priority"),
                row.get("status"),
                row.get("context"),
                row.get("rationale"),
                row.get("category"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse directive from DB: {}", e))?;
            Ok(Some(directive))
        } else {
            Ok(None)
        }
    }

    /// List active directives by project
    pub async fn list_active_by_project(
        pool: &SqlitePool,
        project_id: &str,
    ) -> Result<Vec<Directive>> {
        let rows = sqlx::query(r#"
            SELECT id, project_id, title, rule, priority, status, context, rationale, category, created_at, updated_at 
            FROM directives WHERE project_id = ? AND status = 'active' ORDER BY priority DESC, created_at DESC
        "#)
        .bind(project_id)
        .fetch_all(pool)
        .await?;

        let mut directives = Vec::new();
        for row in rows {
            let created_at = parse_db_timestamp(&row.get::<String, _>("created_at"))?;
            let updated_at = parse_db_timestamp(&row.get::<String, _>("updated_at"))?;

            let directive = Directive::from_db_row(
                row.get("id"),
                row.get("project_id"),
                row.get("title"),
                row.get("rule"),
                row.get("priority"),
                row.get("status"),
                row.get("context"),
                row.get("rationale"),
                row.get("category"),
                created_at,
                updated_at,
            )
            .map_err(|e| anyhow::anyhow!("Failed to parse directive from DB: {}", e))?;
            directives.push(directive);
        }
        Ok(directives)
    }

    /// Deactivate directive
    pub async fn deactivate(pool: &SqlitePool, id: &str) -> Result<()> {
        // Simplified implementation - just update status to inactive
        sqlx::query(
            r#"
            UPDATE directives 
            SET status = ?, updated_at = ?
            WHERE id = ?
        "#,
        )
        .bind("inactive")
        .bind(chrono::Utc::now().to_rfc3339())
        .bind(id)
        .execute(pool)
        .await?;

        Ok(())
    }

    /// Delete directive
    pub async fn delete(pool: &SqlitePool, id: &str) -> Result<()> {
        sqlx::query("DELETE FROM directives WHERE id = ?")
            .bind(id)
            .execute(pool)
            .await?;
        Ok(())
    }

    /// Get next sequential directive ID
    async fn get_next_directive_id(pool: &SqlitePool) -> Result<String> {
        let max_id: Option<String> = sqlx::query_scalar(
            "SELECT id FROM directives ORDER BY CAST(SUBSTR(id, 2) AS INTEGER) DESC LIMIT 1",
        )
        .fetch_optional(pool)
        .await?;

        match max_id {
            Some(id) => {
                let num_str = &id[1..];
                let num: u32 = num_str.parse().unwrap_or(0);
                Ok(format!("D{:03}", num + 1))
            }
            None => Ok("D001".to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::parse_db_timestamp;

    #[test]
    fn parse_db_timestamp_accepts_sqlite_and_rfc3339_formats() {
        let sqlite = parse_db_timestamp("2026-03-28 22:15:04").unwrap();
        let rfc3339 = parse_db_timestamp("2026-03-28T22:15:04Z").unwrap();

        assert_eq!(sqlite.timestamp(), rfc3339.timestamp());
    }
}