lific 2.5.0

Local-first, lightweight issue tracker. Single binary, SQLite-backed, MCP-native.
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
use std::collections::HashMap;

use rusqlite::{params, Connection};

use crate::db::models::*;
use crate::error::LificError;

use super::unescape_text;

/// Per-project workload signals shown only in the MCP project listing.
///
/// This deliberately lives beside project queries rather than on `Project`:
/// REST and web callers keep their existing project payload and ordering.
#[derive(Debug, Clone, Default)]
pub struct ProjectAgentStats {
    pub workable: i64,
    pub active_plans: i64,
    pub last_activity: Option<String>,
}

pub fn list_projects(conn: &Connection) -> Result<Vec<Project>, LificError> {
    let mut stmt = conn.prepare_cached(
        "SELECT id, name, identifier, description, emoji, lead_user_id, sort_order, created_at, updated_at
         FROM projects ORDER BY sort_order, name",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok(Project {
            id: row.get(0)?,
            name: row.get(1)?,
            identifier: row.get(2)?,
            description: row.get(3)?,
            emoji: row.get(4)?,
            lead_user_id: row.get(5)?,
            sort_order: row.get(6)?,
            created_at: row.get(7)?,
            updated_at: row.get(8)?,
        })
    })?;
    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}

/// Fetch workload signals for every project in one SQL statement.
///
/// The workable predicate intentionally mirrors `issues::list_issues` exactly:
/// a blocker is unresolved until its source issue is `done` (a cancelled
/// blocker therefore continues to block, matching the existing list filter).
pub fn project_agent_stats(
    conn: &Connection,
) -> Result<HashMap<i64, ProjectAgentStats>, LificError> {
    let mut stmt = conn.prepare_cached(
        "WITH workable AS (
             SELECT i.project_id, COUNT(*) AS count
             FROM issues i
             WHERE i.status NOT IN ('done', 'cancelled')
               AND NOT EXISTS (
                   SELECT 1 FROM issue_relations ir
                   JOIN issues blocker ON blocker.id = ir.source_id
                   WHERE ir.target_id = i.id
                     AND ir.relation_type = 'blocks'
                     AND blocker.status != 'done'
               )
             GROUP BY i.project_id
         ),
         active_plans AS (
             SELECT project_id, COUNT(*) AS count
             FROM plans
             WHERE status = 'active'
             GROUP BY project_id
         ),
         activity AS (
             SELECT project_id, updated_at FROM issues
             UNION ALL
             SELECT project_id, updated_at FROM pages WHERE project_id IS NOT NULL
             UNION ALL
             SELECT project_id, updated_at FROM plans
         ),
         last_activity AS (
             SELECT project_id, MAX(updated_at) AS updated_at
             FROM activity
             GROUP BY project_id
         )
         SELECT p.id,
                COALESCE(w.count, 0),
                COALESCE(ap.count, 0),
                la.updated_at
         FROM projects p
         LEFT JOIN workable w ON w.project_id = p.id
         LEFT JOIN active_plans ap ON ap.project_id = p.id
         LEFT JOIN last_activity la ON la.project_id = p.id",
    )?;
    let rows = stmt.query_map([], |row| {
        Ok((
            row.get::<_, i64>(0)?,
            ProjectAgentStats {
                workable: row.get(1)?,
                active_plans: row.get(2)?,
                last_activity: row.get(3)?,
            },
        ))
    })?;
    Ok(rows.collect::<Result<HashMap<_, _>, _>>()?)
}

pub fn resolve_project_identifier(conn: &Connection, identifier: &str) -> Result<i64, LificError> {
    conn.prepare_cached("SELECT id FROM projects WHERE identifier = ?1")?
        .query_row(params![identifier], |row| row.get(0))
        .map_err(|e| match e {
            rusqlite::Error::QueryReturnedNoRows => {
                LificError::NotFound(format!("project '{identifier}' not found"))
            }
            _ => e.into(),
        })
}

pub fn get_project(conn: &Connection, id: i64) -> Result<Project, LificError> {
    conn.query_row(
        "SELECT id, name, identifier, description, emoji, lead_user_id, sort_order, created_at, updated_at
         FROM projects WHERE id = ?1",
        params![id],
        |row| {
            Ok(Project {
                id: row.get(0)?,
                name: row.get(1)?,
                identifier: row.get(2)?,
                description: row.get(3)?,
                emoji: row.get(4)?,
                lead_user_id: row.get(5)?,
                sort_order: row.get(6)?,
                created_at: row.get(7)?,
                updated_at: row.get(8)?,
            })
        },
    )
    .map_err(|e| match e {
        rusqlite::Error::QueryReturnedNoRows => {
            LificError::NotFound(format!("project {id} not found"))
        }
        _ => e.into(),
    })
}

/// Validate a project identifier (LIF-134).
///
/// Identifiers are woven into issue (`LIF-42`) and page (`LIF-DOC-1`)
/// identifiers, so the grammar must keep parsing unambiguous:
/// - non-empty, at most 5 characters
/// - uppercase ASCII letters and digits only, starting with a letter
///   (a hyphen would break `resolve_identifier`, which splits at the
///   first `-`; lowercase would make lookups case-sensitive surprises)
/// - not the reserved word `DOC`, which marks page identifiers โ€” a project
///   named DOC would make its issues (`DOC-1`) indistinguishable from
///   workspace pages
fn validate_identifier(identifier: &str) -> Result<(), LificError> {
    if identifier.is_empty() {
        return Err(LificError::BadRequest("identifier must not be empty".into()));
    }
    if identifier.chars().count() > 5 {
        return Err(LificError::BadRequest(
            "identifier must be 5 characters or fewer".into(),
        ));
    }
    let mut chars = identifier.chars();
    let first_ok = chars.next().is_some_and(|c| c.is_ascii_uppercase());
    let rest_ok = chars.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
    if !first_ok || !rest_ok {
        return Err(LificError::BadRequest(
            "identifier must be uppercase letters/digits starting with a letter (e.g. LIF, PRO2)"
                .into(),
        ));
    }
    if identifier == "DOC" {
        return Err(LificError::BadRequest(
            "identifier 'DOC' is reserved for page identifiers".into(),
        ));
    }
    Ok(())
}

pub fn create_project(conn: &Connection, input: &CreateProject) -> Result<Project, LificError> {
    validate_identifier(&input.identifier)?;
    // LIF-233: append new projects below existing ones rather than letting them
    // default to rank 0 (which would jump them to the top once the user has
    // reordered). COALESCE handles the first-ever project (no rows yet).
    conn.execute(
        "INSERT INTO projects (name, identifier, description, emoji, lead_user_id, sort_order)
         VALUES (?1, ?2, ?3, ?4, ?5, (SELECT COALESCE(MAX(sort_order), -1) + 1 FROM projects))",
        params![
            input.name,
            input.identifier,
            unescape_text(&input.description),
            input.emoji,
            input.lead_user_id
        ],
    )?;
    let id = conn.last_insert_rowid();
    // LIF-195: keep project_members in sync with the denormalized lead
    // pointer โ€” a project created with a lead gets a 'lead' membership row.
    if let Some(lead_id) = input.lead_user_id {
        super::members::upsert_member(conn, id, lead_id, Role::Lead)?;
    }
    get_project(conn, id)
}

/// LIF-233: reindex project `sort_order` to match the supplied id order
/// (position 0 = top of the sidebar). Full reindex on every call keeps ranks
/// dense and deterministic, avoiding the float-midpoint exhaustion and
/// all-equal-rank collisions a per-item PATCH scheme would hit.
///
/// Rejects duplicate ids and any id that doesn't exist (BadRequest). Projects
/// not present in `ids` keep their current rank โ€” callers should send the full
/// list to guarantee a total order.
pub fn reorder_projects(conn: &Connection, ids: &[i64]) -> Result<Vec<Project>, LificError> {
    // Reject duplicates: an id appearing twice would silently clobber its own
    // rank and signals a malformed client request.
    let mut seen = std::collections::HashSet::new();
    for id in ids {
        if !seen.insert(*id) {
            return Err(LificError::BadRequest(format!(
                "duplicate project id {id} in reorder list"
            )));
        }
    }
    super::savepoint(conn, "reorder_projects", || {
        for (position, id) in ids.iter().enumerate() {
            let changed = conn.execute(
                "UPDATE projects SET sort_order = ?1 WHERE id = ?2",
                params![position as i64, id],
            )?;
            if changed == 0 {
                return Err(LificError::BadRequest(format!("project {id} not found")));
            }
        }
        Ok(())
    })?;
    list_projects(conn)
}

pub fn update_project(
    conn: &Connection,
    id: i64,
    input: &UpdateProject,
) -> Result<Project, LificError> {
    get_project(conn, id)?;
    super::savepoint(conn, "update_project", || {
        if let Some(ref name) = input.name {
            conn.execute(
                "UPDATE projects SET name = ?1 WHERE id = ?2",
                params![name, id],
            )?;
        }
        if let Some(ref identifier) = input.identifier {
            validate_identifier(identifier)?;
            conn.execute(
                "UPDATE projects SET identifier = ?1 WHERE id = ?2",
                params![identifier, id],
            )?;
        }
        if let Some(ref description) = input.description {
            conn.execute(
                "UPDATE projects SET description = ?1 WHERE id = ?2",
                params![unescape_text(description), id],
            )?;
        }
        // LIF-103: tristate fields. Outer Some means the client sent the key;
        // inner None means they want NULL. rusqlite binds Option<T> to NULL
        // automatically when the inner is None.
        if let Some(emoji) = &input.emoji {
            conn.execute(
                "UPDATE projects SET emoji = ?1 WHERE id = ?2",
                params![emoji.as_ref(), id],
            )?;
        }
        if let Some(lead) = input.lead_user_id {
            // When setting a non-null lead, validate the user exists so we
            // return a 400 with a clear message instead of letting the FK
            // constraint surface as a generic 500.
            if let Some(uid) = lead {
                let exists = match conn.query_row(
                    "SELECT 1 FROM users WHERE id = ?1",
                    params![uid],
                    |_| Ok(true),
                ) {
                    Ok(_) => true,
                    Err(rusqlite::Error::QueryReturnedNoRows) => false,
                    Err(e) => return Err(e.into()),
                };
                if !exists {
                    return Err(LificError::BadRequest(format!(
                        "user {uid} not found"
                    )));
                }
            }
            conn.execute(
                "UPDATE projects SET lead_user_id = ?1 WHERE id = ?2",
                params![lead, id],
            )?;
            // LIF-195: upsert a 'lead' membership for the new lead. The old
            // lead (if any) keeps their existing membership row โ€” this is
            // additive, not a swap.
            if let Some(uid) = lead {
                super::members::upsert_member(conn, id, uid, Role::Lead)?;
            }
        }
        Ok(())
    })?;
    get_project(conn, id)
}

pub fn delete_project(conn: &Connection, id: i64) -> Result<(), LificError> {
    let changed = conn.execute("DELETE FROM projects WHERE id = ?1", params![id])?;
    if changed == 0 {
        return Err(LificError::NotFound(format!("project {id} not found")));
    }
    Ok(())
}

pub fn delete_project_with_audience(
    conn: &Connection,
    id: i64,
) -> Result<(Project, Option<Vec<i64>>), LificError> {
    let project = get_project(conn, id)?;
    let audience = if super::settings::get(conn)?.authz_enforced {
        Some(project_viewer_ids(conn, &project)?)
    } else {
        None
    };
    delete_project(conn, id)?;
    Ok((project, audience))
}

fn project_viewer_ids(conn: &Connection, project: &Project) -> Result<Vec<i64>, LificError> {
    let mut ids: Vec<_> = super::members::list_members(conn, project.id)?
        .into_iter()
        .map(|member| member.user_id)
        .collect();
    if let Some(lead_id) = project.lead_user_id
        && !ids.contains(&lead_id)
    {
        ids.push(lead_id);
    }
    let mut stmt = conn.prepare("SELECT id FROM users WHERE is_admin = 1")?;
    let admins = stmt
        .query_map([], |row| row.get::<_, i64>(0))?
        .collect::<Result<Vec<_>, _>>()?;
    admins.into_iter().for_each(|id| {
        if !ids.contains(&id) {
            ids.push(id);
        }
    });
    Ok(ids)
}

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

    fn test_db() -> db::DbPool {
        db::open_memory().expect("test db")
    }

    #[test]
    fn create_and_get_project() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Test".into(),
                identifier: "TST".into(),
                description: "A test project".into(),
                emoji: Some("๐Ÿงช".into()),
                lead_user_id: None,
            },
        )
        .unwrap();

        assert_eq!(project.name, "Test");
        assert_eq!(project.identifier, "TST");
        assert_eq!(project.description, "A test project");
        assert_eq!(project.emoji, Some("๐Ÿงช".into()));

        let fetched = get_project(&conn, project.id).unwrap();
        assert_eq!(fetched.identifier, "TST");
    }

    #[test]
    fn resolve_project_identifier_works() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        create_project(
            &conn,
            &CreateProject {
                name: "Lific".into(),
                identifier: "LIF".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        let id = resolve_project_identifier(&conn, "LIF").unwrap();
        assert!(id > 0);
    }

    #[test]
    fn resolve_project_not_found() {
        let pool = test_db();
        let conn = pool.read().unwrap();
        let result = resolve_project_identifier(&conn, "NOPE");
        assert!(result.is_err());
    }

    #[test]
    fn duplicate_identifier_rejected() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        create_project(
            &conn,
            &CreateProject {
                name: "First".into(),
                identifier: "DUP".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        let result = create_project(
            &conn,
            &CreateProject {
                name: "Second".into(),
                identifier: "DUP".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        );
        assert!(result.is_err());
    }

    // โ”€โ”€ LIF-134: identifier grammar โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    fn try_create(conn: &Connection, ident: &str) -> Result<Project, LificError> {
        create_project(
            conn,
            &CreateProject {
                name: format!("P {ident}"),
                identifier: ident.into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
    }

    #[test]
    fn identifier_rejects_malformed_values() {
        let pool = test_db();
        let conn = pool.write().unwrap();

        // Empty, lowercase, hyphenated (breaks resolve_identifier), leading
        // digit, reserved page marker, >5 chars (counted in chars, not bytes).
        for bad in ["", "lif", "A-B", "1AB", "DOC", "TOOLNG", "๐Ÿงช๐Ÿงช"] {
            let result = try_create(&conn, bad);
            assert!(
                matches!(result, Err(LificError::BadRequest(_))),
                "identifier {bad:?} must be rejected, got: {result:?}"
            );
        }
    }

    #[test]
    fn identifier_accepts_uppercase_alphanumeric() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        for good in ["A", "LIF", "PRO2", "AB1C5"] {
            assert!(
                try_create(&conn, good).is_ok(),
                "identifier {good:?} must be accepted"
            );
        }
    }

    #[test]
    fn update_rejects_malformed_identifier() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = try_create(&conn, "GOOD").unwrap();

        for bad in ["A-B", "DOC", "bad"] {
            let result = update_project(
                &conn,
                project.id,
                &UpdateProject {
                    name: None,
                    identifier: Some(bad.into()),
                    description: None,
                    emoji: None,
                    lead_user_id: None,
                },
            );
            assert!(
                matches!(result, Err(LificError::BadRequest(_))),
                "identifier {bad:?} must be rejected on update, got: {result:?}"
            );
        }
        // Unchanged after the failed updates.
        assert_eq!(get_project(&conn, project.id).unwrap().identifier, "GOOD");
    }

    #[test]
    fn update_project_fields() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Old Name".into(),
                identifier: "OLD".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        let updated = update_project(
            &conn,
            project.id,
            &UpdateProject {
                name: Some("New Name".into()),
                identifier: None,
                description: Some("Now with description".into()),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        assert_eq!(updated.name, "New Name");
        assert_eq!(updated.identifier, "OLD"); // unchanged
        assert_eq!(updated.description, "Now with description");
    }

    #[test]
    fn delete_project_removes_it() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Doomed".into(),
                identifier: "DEL".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        delete_project(&conn, project.id).unwrap();
        assert!(get_project(&conn, project.id).is_err());
    }

    #[test]
    fn delete_project_not_found() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let result = delete_project(&conn, 99999);
        assert!(result.is_err());
    }

    #[test]
    fn list_projects_returns_all() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        for (name, ident) in [("Alpha", "A"), ("Beta", "B"), ("Gamma", "G")] {
            create_project(
                &conn,
                &CreateProject {
                    name: name.into(),
                    identifier: ident.into(),
                    description: String::new(),
                    emoji: None,
                    lead_user_id: None,
                },
            )
            .unwrap();
        }

        let projects = list_projects(&conn).unwrap();
        assert_eq!(projects.len(), 3);
    }

    #[test]
    fn project_agent_stats_counts_work_and_latest_activity() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project_id = seed_named(&conn, "Signals", "SIG");

        let insert_issue = |sequence, title, status, updated_at| {
            conn.execute(
                "INSERT INTO issues (project_id, sequence, title, status, updated_at)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![project_id, sequence, title, status, updated_at],
            )
            .unwrap();
            conn.last_insert_rowid()
        };
        let blocker = insert_issue(1, "Blocker", "active", "2026-01-01 00:00:00");
        insert_issue(2, "Unblocked", "todo", "2026-01-02 00:00:00");
        let blocked = insert_issue(3, "Blocked", "todo", "2026-01-03 00:00:00");
        insert_issue(4, "Done", "done", "2026-01-04 00:00:00");
        conn.execute(
            "INSERT INTO issue_relations (source_id, target_id, relation_type)
             VALUES (?1, ?2, 'blocks')",
            params![blocker, blocked],
        )
        .unwrap();

        conn.execute(
            "INSERT INTO pages (project_id, sequence, title, status, updated_at)
             VALUES (?1, 1, 'Page activity', 'active', '2026-01-05 00:00:00')",
            params![project_id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO plans (project_id, sequence, title, status, updated_at)
             VALUES (?1, 1, 'Active plan', 'active', '2026-01-06 00:00:00')",
            params![project_id],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO plans (project_id, sequence, title, status, updated_at)
             VALUES (?1, 2, 'Archived plan', 'archived', '2026-01-04 12:00:00')",
            params![project_id],
        )
        .unwrap();

        let stats = project_agent_stats(&conn).unwrap();
        let stats = stats.get(&project_id).expect("stats for project");
        assert_eq!(stats.workable, 2);
        assert_eq!(stats.active_plans, 1);
        assert_eq!(stats.last_activity.as_deref(), Some("2026-01-06 00:00:00"));
    }

    // โ”€โ”€ LIF-233: sidebar ordering โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    fn seed_named(conn: &Connection, name: &str, ident: &str) -> i64 {
        create_project(
            conn,
            &CreateProject {
                name: name.into(),
                identifier: ident.into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap()
        .id
    }

    #[test]
    fn list_projects_tie_breaks_by_name_at_equal_rank() {
        // After the 025 migration every pre-existing project has sort_order 0,
        // so the listing must stay deterministic โ€” alphabetical, as before the
        // feature. Force equal ranks to simulate that post-migration state
        // (create_project otherwise appends distinct ranks).
        let pool = test_db();
        let conn = pool.write().unwrap();
        seed_named(&conn, "Gamma", "G");
        seed_named(&conn, "Alpha", "A");
        seed_named(&conn, "Beta", "B");
        conn.execute("UPDATE projects SET sort_order = 0", []).unwrap();

        let names: Vec<String> = list_projects(&conn)
            .unwrap()
            .into_iter()
            .map(|p| p.name)
            .collect();
        assert_eq!(names, ["Alpha", "Beta", "Gamma"]);
    }

    #[test]
    fn reorder_projects_sets_explicit_order() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let a = seed_named(&conn, "Alpha", "A");
        let b = seed_named(&conn, "Beta", "B");
        let g = seed_named(&conn, "Gamma", "G");

        // Put Gamma first, then Alpha, then Beta โ€” the opposite of alphabetical.
        let reordered = reorder_projects(&conn, &[g, a, b]).unwrap();
        let names: Vec<String> = reordered.into_iter().map(|p| p.name).collect();
        assert_eq!(names, ["Gamma", "Alpha", "Beta"]);

        // Order persists across a fresh list (sort_order, not query happenstance).
        let names: Vec<String> = list_projects(&conn)
            .unwrap()
            .into_iter()
            .map(|p| p.name)
            .collect();
        assert_eq!(names, ["Gamma", "Alpha", "Beta"]);
    }

    #[test]
    fn reorder_rejects_unknown_id() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let a = seed_named(&conn, "Alpha", "A");
        let err = reorder_projects(&conn, &[a, 99999]).unwrap_err();
        assert!(matches!(err, LificError::BadRequest(_)), "got {err:?}");
        // The failed reorder is rolled back: Alpha keeps its original rank.
        assert_eq!(list_projects(&conn).unwrap()[0].name, "Alpha");
    }

    #[test]
    fn reorder_rejects_duplicate_id() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let a = seed_named(&conn, "Alpha", "A");
        let b = seed_named(&conn, "Beta", "B");
        let err = reorder_projects(&conn, &[a, b, a]).unwrap_err();
        assert!(matches!(err, LificError::BadRequest(_)), "got {err:?}");
    }

    #[test]
    fn new_project_appends_after_reorder() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let a = seed_named(&conn, "Alpha", "A");
        let b = seed_named(&conn, "Beta", "B");
        // Reorder so Beta(rank 0) precedes Alpha(rank 1).
        reorder_projects(&conn, &[b, a]).unwrap();
        // A brand-new project should land at the bottom, not jump to rank 0.
        seed_named(&conn, "Zeta", "Z");
        let names: Vec<String> = list_projects(&conn)
            .unwrap()
            .into_iter()
            .map(|p| p.name)
            .collect();
        assert_eq!(names, ["Beta", "Alpha", "Zeta"]);
    }

    #[test]
    fn unescape_in_description() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Escaped".into(),
                identifier: "ESC".into(),
                description: "line1\\nline2\\ttab".into(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        assert_eq!(project.description, "line1\nline2\ttab");
    }

    // โ”€โ”€ LIF-103: tristate clear-to-NULL semantics for emoji + lead_user_id โ”€โ”€

    /// Seed a real user so projects with lead_user_id pass the FK constraint.
    fn seed_user(conn: &Connection, username: &str) -> i64 {
        conn.execute(
            "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot)
             VALUES (?1, ?2, 'x', ?1, 0, 0)",
            params![username, format!("{username}@test.local")],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    #[test]
    fn update_can_clear_emoji() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Has Emoji".into(),
                identifier: "EMJ".into(),
                description: String::new(),
                emoji: Some("๐Ÿงช".into()),
                lead_user_id: None,
            },
        )
        .unwrap();
        assert_eq!(project.emoji.as_deref(), Some("๐Ÿงช"));

        let updated = update_project(
            &conn,
            project.id,
            &UpdateProject {
                name: None,
                identifier: None,
                description: None,
                emoji: Some(None), // explicit clear
                lead_user_id: None,
            },
        )
        .unwrap();
        assert_eq!(updated.emoji, None);
    }

    #[test]
    fn update_can_clear_lead() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let uid = seed_user(&conn, "alice");
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Has Lead".into(),
                identifier: "LDP".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: Some(uid),
            },
        )
        .unwrap();
        assert_eq!(project.lead_user_id, Some(uid));

        let updated = update_project(
            &conn,
            project.id,
            &UpdateProject {
                name: None,
                identifier: None,
                description: None,
                emoji: None,
                lead_user_id: Some(None), // explicit clear
            },
        )
        .unwrap();
        assert_eq!(updated.lead_user_id, None);
    }

    #[test]
    fn update_absent_field_preserves_value() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let uid = seed_user(&conn, "bob");
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Keep".into(),
                identifier: "KEP".into(),
                description: String::new(),
                emoji: Some("๐ŸŽฏ".into()),
                lead_user_id: Some(uid),
            },
        )
        .unwrap();

        // Update unrelated field; emoji + lead should survive.
        let updated = update_project(
            &conn,
            project.id,
            &UpdateProject {
                name: Some("Keep Renamed".into()),
                identifier: None,
                description: None,
                emoji: None, // absent โ€” preserve
                lead_user_id: None, // absent โ€” preserve
            },
        )
        .unwrap();
        assert_eq!(updated.name, "Keep Renamed");
        assert_eq!(updated.emoji.as_deref(), Some("๐ŸŽฏ"));
        assert_eq!(updated.lead_user_id, Some(uid));
    }

    #[test]
    fn update_lead_to_nonexistent_user_fails_with_bad_request() {
        let pool = test_db();
        let conn = pool.write().unwrap();
        let project = create_project(
            &conn,
            &CreateProject {
                name: "Orphan".into(),
                identifier: "ORP".into(),
                description: String::new(),
                emoji: None,
                lead_user_id: None,
            },
        )
        .unwrap();

        // 99999 doesn't exist. Should be a BadRequest, not a Database error.
        let result = update_project(
            &conn,
            project.id,
            &UpdateProject {
                name: None,
                identifier: None,
                description: None,
                emoji: None,
                lead_user_id: Some(Some(99999)),
            },
        );
        match result {
            Err(LificError::BadRequest(msg)) => {
                assert!(msg.contains("99999"), "got: {msg}");
                assert!(msg.contains("not found"), "got: {msg}");
            }
            other => panic!("expected BadRequest, got: {other:?}"),
        }

        // And the project should be unchanged (savepoint rolled back).
        let fetched = get_project(&conn, project.id).unwrap();
        assert_eq!(fetched.lead_user_id, None);
    }
}