lific 2.8.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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
use axum::{
    Extension,
    extract::{Json, Path, Query, State},
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

use crate::authz;
use crate::db::{DbPool, models::*};
use crate::error::LificError;
use crate::realtime::{RealtimeEvent, RealtimeHub};

use super::{
    filter_visible, require_project_delete, require_project_lead, require_user, with_read,
    with_write,
};

pub(super) async fn list_projects(
    State(db): State<DbPool>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
) -> Result<Json<Vec<Project>>, LificError> {
    // Cross-project list (LIF-197 scope item 2): filter, don't deny.
    let visible = authz::visible_project_ids(&db, &identity)?;
    let projects = with_read(&db, crate::db::queries::list_projects)?;
    Ok(Json(filter_visible(projects, &visible, |p| Some(p.id))))
}

pub(super) async fn get_project(
    State(db): State<DbPool>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    Path(id): Path<i64>,
) -> Result<Json<Project>, LificError> {
    let project = with_read(&db, |conn| crate::db::queries::get_project(conn, id))?;
    authz::require_role(&db, &identity, project.id, Role::Viewer)?;
    Ok(Json(project))
}

/// POST /api/projects.
///
/// `create_project` upserts a `lead` membership for whoever `lead_user_id`
/// names (LIF-195), so naming somebody else is a lasting access grant, exactly
/// as `PUT /api/projects/{id}` is. It is a grant on a project that is empty at
/// the moment it is made, but the project does not stay empty, and the
/// membership does not expire, so it is gated on the same terms as every other
/// grant: a browser session authenticated in the last 15 minutes.
///
/// Naming *yourself*, or naming nobody (the default), grants nothing that the
/// act of creating the project did not already grant, so neither needs
/// recency. That keeps `lific connect`-style API-key automation creating its
/// own projects exactly as before.
///
/// "Yourself" means the **effective** user, not `identity.user`. A bot's
/// permissions are its owner's ([`crate::authz::effective_user`]), so a
/// connected tool creating a project leads it as its owner, which is what the
/// project would resolve to anyway. That also closes the alternative reading:
/// a bot cannot use "my owner is not literally me" to smuggle in a grant,
/// because naming the owner *is* naming itself here.
pub(super) async fn create_project(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    headers: axum::http::HeaderMap,
    Json(mut input): Json<CreateProject>,
) -> Result<Json<Project>, LificError> {
    let caller = super::require_user(&identity)?;
    // Only parsed when the body asks for a lead that might not be the caller;
    // resolving "might not be" needs the effective user, which needs the
    // transaction, so the token is captured here and judged there.
    let session_token = crate::auth::recent_session_token(&headers).ok();

    let project = db.transaction(|tx| {
        let fresh = crate::auth::fresh_caller(tx, caller.id)?;
        let effective =
            crate::authz::effective_user(tx, &Some(crate::auth::fresh_auth_user(&fresh)))
                .ok_or_else(|| LificError::Forbidden("authentication required".into()))?;

        match input.lead_user_id {
            // LIF-102 fix #1: no lead supplied means the creator leads it.
            // Without this, `require_project_lead` rejects everyone but admins
            // and the project is unowned.
            None => input.lead_user_id = Some(effective.id),
            // Naming yourself grants nothing new.
            Some(id) if id == effective.id => {}
            // Naming anybody else does, so it needs a recent human sign-in.
            Some(_) => {
                let token = session_token.as_deref().ok_or_else(|| {
                    LificError::Forbidden("recent authentication required".into())
                })?;
                let session_user = crate::auth::revalidate_recent_session(tx, token, caller.id)?;
                // A session belongs to a human, so the effective user is that
                // human; assert it rather than assume it.
                if session_user.id != effective.id {
                    return Err(LificError::Forbidden(
                        "recent authentication required".into(),
                    ));
                }
            }
        }

        crate::db::queries::create_project(tx, &input)
    })?;
    realtime.send(RealtimeEvent::ProjectCreated {
        project_id: project.id,
    });
    Ok(Json(project))
}

pub(super) async fn update_project(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    headers: axum::http::HeaderMap,
    Json(input): Json<UpdateProject>,
) -> Result<Json<Project>, LificError> {
    require_project_lead(&db, &identity, id)?;

    // Naming a lead is a membership grant in disguise: `update_project` upserts
    // a `lead` row for whoever is named (LIF-195), which is the same access
    // expansion `POST /api/projects/{id}/members` performs and must carry the
    // same rule. Renames, descriptions, emoji and *clearing* the lead are not
    // expansions and stay ungated.
    let grants_lead = matches!(input.lead_user_id, Some(Some(_)));
    let recent = if grants_lead {
        let granter = super::require_user(&identity)?;
        Some((crate::auth::recent_session_token(&headers)?, granter.id))
    } else {
        None
    };

    let project = db.transaction(|tx| {
        // When this grants a lead membership the gate re-runs against the
        // freshly read session user, so a lead revoked since the request
        // arrived cannot hand the role to anyone.
        let gate_identity = match &recent {
            Some((token, granter_id)) => {
                let fresh = crate::auth::revalidate_recent_session(tx, token, *granter_id)?;
                Some(crate::auth::fresh_identity(
                    &fresh,
                    crate::actor::Transport::Web,
                ))
            }
            // Not a grant (a rename, or clearing the lead). No recency, but
            // still not the middleware's snapshot: the caller is re-read here
            // so a demoted admin cannot edit on the strength of a stale
            // `is_admin`.
            None => {
                let caller = super::require_user(&identity)?;
                let fresh = crate::auth::fresh_caller(tx, caller.id)?;
                Some(crate::auth::fresh_identity(
                    &fresh,
                    crate::actor::Transport::Web,
                ))
            }
        };
        crate::authz::require_role_conn(tx, &gate_identity, id, Role::Lead)?;
        crate::db::queries::update_project(tx, id, &input)
    })?;
    realtime.send(RealtimeEvent::ProjectUpdated {
        project_id: project.id,
    });
    Ok(Json(project))
}

/// PUT /api/projects/reorder — persist the sidebar order (LIF-233). Takes the
/// full id list top-to-bottom; the server reindexes `sort_order`. Gated only on
/// being authenticated (order is instance-wide, not a privileged project edit),
/// so any logged-in user can rearrange — unlike `update_project`, which is
/// lead/admin-only.
pub(super) async fn reorder_projects(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    Json(input): Json<ReorderProjects>,
) -> Result<Json<Vec<Project>>, LificError> {
    require_user(&identity)?;
    let projects = with_write(&db, |conn| {
        crate::db::queries::reorder_projects(conn, &input.ids)
    })?;
    realtime.send(RealtimeEvent::ProjectsReordered);
    Ok(Json(projects))
}

pub(super) async fn delete_project_handler(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Path(id): Path<i64>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
) -> Result<Json<serde_json::Value>, LificError> {
    // Preflight on a read connection so an unauthorized caller never reaches
    // the writer; re-run authoritatively inside the transaction below.
    require_project_delete(&db, &identity, id)?;
    let caller = super::require_user(&identity)?;
    let (project, audience) = db.transaction(|tx| {
        // Deleting a project destroys everything in it, so the decision is
        // made from state read here rather than from the snapshot the
        // middleware attached before the request was routed.
        let fresh = crate::auth::fresh_caller(tx, caller.id)?;
        let fresh_identity = Some(crate::auth::fresh_identity(
            &fresh,
            crate::actor::Transport::Web,
        ));
        crate::authz::require_project_delete_role_conn(tx, &fresh_identity, id)?;
        crate::db::queries::delete_project_with_audience(tx, id)
    })?;
    let event = RealtimeEvent::ProjectDeleted {
        project_id: project.id,
    };
    match audience {
        Some(user_ids) => realtime.send_to_users(event, user_ids),
        None => realtime.send(event),
    }
    Ok(Json(serde_json::json!({"deleted": true})))
}

/// Per-status issue counts + total for the topbar (LIF-161). Separate from
/// the list endpoint because that one is limit-capped — counting its rows
/// client-side silently undercounts past the cap.
pub(super) async fn issue_counts(
    State(db): State<DbPool>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    Path(project_id): Path<i64>,
) -> Result<Json<IssueStatusCounts>, LificError> {
    authz::require_role(&db, &identity, project_id, Role::Viewer)?;
    with_read(&db, |conn| {
        crate::db::queries::count_issues_by_status(conn, project_id)
    })
    .map(Json)
}

#[derive(serde::Deserialize)]
pub(super) struct BoardQuery {
    #[serde(default = "default_group_by")]
    group_by: String,
}

fn default_group_by() -> String {
    "status".to_string()
}

pub(super) async fn get_board(
    State(db): State<DbPool>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    Path(project_id): Path<i64>,
    Query(q): Query<BoardQuery>,
) -> Result<Json<serde_json::Value>, LificError> {
    authz::require_role(&db, &identity, project_id, Role::Viewer)?;
    let issues = with_read(&db, |conn| {
        crate::db::queries::list_issues(
            conn,
            &ListIssuesQuery {
                project_id: Some(project_id),
                limit: Some(500),
                ..Default::default()
            },
        )
    })?;

    let module_names: std::collections::HashMap<i64, String> = if q.group_by == "module" {
        with_read(&db, |conn| {
            crate::db::queries::list_modules(conn, project_id)
        })
        .unwrap_or_default()
        .into_iter()
        .map(|m| (m.id, m.name))
        .collect()
    } else {
        std::collections::HashMap::new()
    };

    let mut board: std::collections::BTreeMap<String, Vec<&Issue>> =
        std::collections::BTreeMap::new();
    for issue in &issues {
        let key = match q.group_by.as_str() {
            "priority" => issue.priority.to_string(),
            "module" => issue
                .module_id
                .and_then(|m| module_names.get(&m).cloned())
                .unwrap_or_else(|| "unassigned".into()),
            _ => issue.status.to_string(),
        };
        board.entry(key).or_default().push(issue);
    }

    Ok(Json(serde_json::json!(board)))
}

// ── GitHub import (LIF-264, web surface) ─────────────────────

/// Request body for `POST /api/projects/{id}/import/github`.
///
/// The web Import panel posts repo + token + mapping here. `dry_run` drives the
/// preview step (counts only, no writes). Only GitHub is exposed on the web;
/// Linear/Jira are CLI-only per LIF-265.
#[derive(serde::Deserialize)]
pub(super) struct GithubImportRequest {
    /// Source repo as `owner/name`.
    repo: String,
    /// Optional GitHub token. Public repos work without one (subject to the
    /// anon rate limit).
    #[serde(default)]
    token: Option<String>,
    /// open / closed / all. Defaults to all.
    #[serde(default = "default_import_state")]
    state: String,
    /// Lific status for open issues.
    #[serde(default = "default_map_open")]
    map_open: String,
    /// Lific status for closed issues.
    #[serde(default = "default_map_closed")]
    map_closed: String,
    /// Preview only — count, write nothing.
    #[serde(default)]
    dry_run: bool,
}

// Keep a small global ceiling while allowing unrelated projects to import in
// parallel. The per-project gate below is the important isolation boundary:
// one expensive import cannot make another import for the same project race
// its writes or consume unbounded resources.
const GITHUB_IMPORT_GLOBAL_LIMIT: usize = 4;
static GITHUB_IMPORT_SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
static GITHUB_IMPORT_PROJECT_SLOTS: OnceLock<Mutex<HashMap<i64, Weak<Semaphore>>>> =
    OnceLock::new();

fn github_import_permits(
    project_id: i64,
) -> Result<(OwnedSemaphorePermit, OwnedSemaphorePermit), LificError> {
    let project_slot = {
        let slots = GITHUB_IMPORT_PROJECT_SLOTS.get_or_init(|| Mutex::new(HashMap::new()));
        let mut slots = slots
            .lock()
            .map_err(|_| LificError::Internal("GitHub import gate poisoned".into()))?;
        slots.retain(|_, slot| slot.strong_count() > 0);
        match slots.entry(project_id) {
            std::collections::hash_map::Entry::Occupied(mut entry) => {
                if let Some(slot) = entry.get().upgrade() {
                    slot
                } else {
                    let slot = Arc::new(Semaphore::new(1));
                    entry.insert(Arc::downgrade(&slot));
                    slot
                }
            }
            std::collections::hash_map::Entry::Vacant(entry) => {
                let slot = Arc::new(Semaphore::new(1));
                entry.insert(Arc::downgrade(&slot));
                slot
            }
        }
    };
    let project_permit = project_slot.try_acquire_owned().map_err(|_| {
        LificError::Conflict("a GitHub import is already running for this project".into())
    })?;
    let global_permit = GITHUB_IMPORT_SLOTS
        .get_or_init(|| Arc::new(Semaphore::new(GITHUB_IMPORT_GLOBAL_LIMIT)))
        .clone()
        .try_acquire_owned()
        .map_err(|_| LificError::Conflict("too many GitHub imports are already running".into()))?;
    Ok((global_permit, project_permit))
}

fn default_import_state() -> String {
    "all".to_string()
}
fn default_map_open() -> String {
    "backlog".to_string()
}
fn default_map_closed() -> String {
    "done".to_string()
}

/// POST /api/projects/{id}/import/github — run (or preview) a GitHub import
/// into this project.
///
/// Synchronous for v1: the request blocks until the import completes and
/// returns the [`crate::import::ImportSummary`]. The fetch + DB work runs in a
/// `spawn_blocking` task because the importer uses the blocking reqwest client.
/// Progress is a spinner on the client; a real dry-run preview precedes the
/// write so the operator sees counts first. Gated on project-lead (same bar as
/// editing project structure).
///
/// The actual collect/apply is delegated to [`import_github_with`], which takes
/// the fetcher as a parameter so tests can stub the network entirely.
pub(super) async fn import_github(
    State(db): State<DbPool>,
    Extension(realtime): Extension<RealtimeHub>,
    Extension(identity): Extension<Option<crate::resolve_caller::ResolvedIdentity>>,
    Path(project_id): Path<i64>,
    Json(req): Json<GithubImportRequest>,
) -> Result<Json<crate::import::ImportSummary>, LificError> {
    require_project_lead(&db, &identity, project_id)?;
    // Move both permits into the blocking closure. `spawn_blocking` cannot
    // stop a running blocking task when this request is cancelled; keeping
    // the permits in that closure prevents a cancelled request from releasing
    // admission while its network/DB work is still running.
    let (global_permit, project_permit) = github_import_permits(project_id)?;

    // Resolve the import-bot owner from the authenticated user (the bot is
    // owned by whoever ran the import), so audit provenance is correct. On a
    // dry run we skip bot creation entirely.
    let owner_id = identity.as_ref().map(|i| i.user.id);
    let dry_run = req.dry_run;

    let db2 = db.clone();
    let summary = tokio::task::spawn_blocking(move || {
        let _global_permit = global_permit;
        let _project_permit = project_permit;
        run_github_import_blocking(&db2, project_id, owner_id, &req)
    })
    .await
    .map_err(|e| LificError::Internal(format!("import task failed: {e}")))??;

    if !dry_run {
        realtime.send(RealtimeEvent::ProjectUpdated { project_id });
    }

    Ok(Json(summary))
}

/// The blocking body of [`import_github`], factored out so it runs off the
/// async runtime (blocking reqwest) and so tests can call the injectable
/// [`import_github_with`] variant directly.
fn run_github_import_blocking(
    db: &DbPool,
    project_id: i64,
    owner_id: Option<i64>,
    req: &GithubImportRequest,
) -> Result<crate::import::ImportSummary, LificError> {
    let (owner, name) =
        crate::import::github::parse_repo(&req.repo).map_err(LificError::BadRequest)?;
    let state =
        crate::import::github::StateFilter::parse(&req.state).map_err(LificError::BadRequest)?;
    let fetcher = crate::import::github::LiveGithub::new(&owner, &name, req.token.clone())?;
    let slug = format!("{owner}/{name}");
    import_github_with(db, project_id, owner_id, &fetcher, &slug, state, req)
}

/// Core import logic with the fetcher injected. `owner_id` is the human who
/// owns the import bot (comments are attributed to it); `None` (fresh install /
/// dry run) skips comment attribution. Shared by the live handler and tests.
pub(super) fn import_github_with(
    db: &DbPool,
    project_id: i64,
    owner_id: Option<i64>,
    fetcher: &dyn crate::import::github::GithubFetcher,
    slug: &str,
    state: crate::import::github::StateFilter,
    req: &GithubImportRequest,
) -> Result<crate::import::ImportSummary, LificError> {
    // LIF-385: `map_open` / `map_closed` arrive as free text from the web
    // Import panel; reject a bad one with 400 up front instead of letting every
    // insert fail against the status CHECK constraint.
    let status_map = crate::import::StatusMap {
        open: req.map_open.parse().map_err(LificError::BadRequest)?,
        closed: req.map_closed.parse().map_err(LificError::BadRequest)?,
    };
    // A resource-ceiling refusal surfaces as 413 (see the `GithubImportError`
    // conversion in `crate::error`); GitHub being unreachable stays a 500.
    let fetched = crate::import::github::collect(fetcher, slug, state, &status_map)?;

    // A dry run never mints a bot or writes; a real run resolves/creates the
    // import bot owned by the requester.
    let bot = if req.dry_run {
        None
    } else {
        match owner_id {
            Some(owner) => Some(crate::import::ensure_import_bot(
                db,
                owner,
                "github",
                "GitHub Import",
            )?),
            None => None,
        }
    };

    crate::import::run_import(db, project_id, bot, &fetched, req.dry_run)
}

#[cfg(test)]
mod tests {
    use super::{GithubImportRequest, github_import_permits, import_github_with};
    use crate::api::test_helpers::*;
    use crate::db::models::*;
    use axum::Extension;
    use axum::http::{Request, StatusCode};
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    #[tokio::test]
    async fn github_import_gate_is_per_project_and_survives_task_abort() {
        let project_id = i64::MIN + 1;
        let (global, project) = github_import_permits(project_id).unwrap();
        let (started_tx, started_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let task = tokio::task::spawn_blocking(move || {
            // A blocking task keeps running after JoinHandle::abort(). The
            // permits must therefore live in this closure, not in the request
            // future that spawned it.
            let _global = global;
            let _project = project;
            started_tx.send(()).unwrap();
            release_rx.recv().unwrap();
        });
        started_rx.recv().unwrap();
        task.abort();
        assert!(
            github_import_permits(project_id).is_err(),
            "same project must remain closed while aborted blocking work runs"
        );

        // A different project is admitted while the first one is occupied.
        let (_other_global, _other_project) = github_import_permits(project_id + 1).unwrap();
        release_tx.send(()).unwrap();
        let _ = task.await;
    }

    #[tokio::test]
    async fn project_crud_lifecycle() {
        let app = test_app();

        // Create
        let (id, project) = seed_project(&app).await;
        assert_eq!(project["identifier"], "TST");

        // Get
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/api/projects/{id}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // List
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri("/api/projects")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let list: Vec<serde_json::Value> = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(list.len(), 1);

        // Update
        let update = serde_json::json!({"name": "Renamed"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let updated: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(updated["name"], "Renamed");
        assert_eq!(updated["identifier"], "TST"); // unchanged

        // Delete
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri(format!("/api/projects/{id}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Verify gone
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/api/projects/{id}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn get_nonexistent_project_returns_404() {
        let app = test_app();
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/api/projects/99999")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn board_groups_by_status() {
        let app = test_app();
        let (project_id, _) = seed_project(&app).await;

        for (title, status) in [("A", "todo"), ("B", "active"), ("C", "todo")] {
            let body = serde_json::json!({
                "project_id": project_id,
                "title": title,
                "status": status
            });
            app.clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/api/issues")
                        .header("content-type", "application/json")
                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap();
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/api/projects/{project_id}/board"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let board: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(board["todo"].as_array().unwrap().len(), 2);
        assert_eq!(board["active"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn issue_counts_returns_per_status_tallies_and_total() {
        let app = test_app();
        let (project_id, _) = seed_project(&app).await;

        for (title, status) in [("A", "todo"), ("B", "active"), ("C", "todo"), ("D", "done")] {
            let body = serde_json::json!({
                "project_id": project_id,
                "title": title,
                "status": status
            });
            json_post(&app, "/api/issues", body).await;
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/api/projects/{project_id}/issue-counts"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let counts = parse_json(resp).await;
        assert_eq!(counts["backlog"], 0);
        assert_eq!(counts["todo"], 2);
        assert_eq!(counts["active"], 1);
        assert_eq!(counts["done"], 1);
        assert_eq!(counts["cancelled"], 0);
        assert_eq!(counts["total"], 4);
    }

    #[tokio::test]
    async fn board_groups_by_module_resolves_names() {
        let db = crate::db::open_memory().expect("test db");
        // Seed a real admin so create_project's lead-defaulting (LIF-102)
        // can FK to a valid user row.
        let admin_id = {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot)
                 VALUES ('test-admin', 'admin@test.local', 'x', 'Test Admin', 1, 0)",
                [],
            )
            .unwrap();
            conn.last_insert_rowid()
        };
        let app = crate::api::router(db.clone(), &[])
            .layer(Extension(crate::realtime::RealtimeHub::new()))
            .layer(Extension(crate::config::AuthConfig {
                allow_signup: true,
                required: true,
                secure_cookies: false,
            }))
            .layer(Extension(Some(AuthUser {
                id: admin_id,
                username: "test-admin".into(),
                display_name: "Test Admin".into(),
                is_admin: true,
            })))
            .layer(Extension(Some(crate::resolve_caller::ResolvedIdentity {
                user: AuthUser {
                    id: admin_id,
                    username: "test-admin".into(),
                    display_name: "Test Admin".into(),
                    is_admin: true,
                },
                transport: crate::actor::Transport::Web,
            })))
            .layer(Extension(Some(crate::resolve_caller::ResolvedIdentity {
                user: AuthUser {
                    id: admin_id,
                    username: "test-admin".into(),
                    display_name: "Test Admin".into(),
                    is_admin: true,
                },
                transport: crate::actor::Transport::Web,
            })));
        let (project_id, _) = seed_project(&app).await;

        // Create a module via direct DB access
        let conn = db.read().unwrap();
        crate::db::queries::create_module(
            &conn,
            &CreateModule {
                project_id,
                name: "Backend".into(),
                description: String::new(),
                status: "active".into(),
                emoji: None,
            },
        )
        .unwrap();
        let modules = crate::db::queries::list_modules(&conn, project_id).unwrap();
        let module_id = modules[0].id;
        drop(conn);

        // Create issues: one with module, one without
        for (title, mid) in [("With mod", Some(module_id)), ("No mod", None)] {
            let mut body = serde_json::json!({
                "project_id": project_id,
                "title": title,
            });
            if let Some(m) = mid {
                body["module_id"] = serde_json::json!(m);
            }
            app.clone()
                .oneshot(
                    Request::builder()
                        .method("POST")
                        .uri("/api/issues")
                        .header("content-type", "application/json")
                        .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                        .unwrap(),
                )
                .await
                .unwrap();
        }

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(format!("/api/projects/{project_id}/board?group_by=module"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let board: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert!(
            board.get("has_module").is_none(),
            "should not use 'has_module' as key"
        );
        assert_eq!(board["Backend"].as_array().unwrap().len(), 1);
        assert_eq!(board["unassigned"].as_array().unwrap().len(), 1);
    }

    /// LIF-364 (dr.leech's report): with `authz_enforced` ON, an instance
    /// admin must see every project in `GET /api/projects` — including ones
    /// they are not a member of — while a plain non-member sees none. This
    /// pins the full REST stack (identity extension → visible_project_ids →
    /// filter_visible), not just the authz unit.
    #[tokio::test]
    async fn enforced_admin_sees_all_projects_non_member_sees_none() {
        let (db, admin, _lead, _maint, _viewer, non_member, project_id) = setup_membership_test();

        let resp = json_get(&app_as_user(db.clone(), &admin), "/api/projects").await;
        assert_eq!(resp.status(), StatusCode::OK);
        let projects = parse_json(resp).await;
        let ids: Vec<i64> = projects
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["id"].as_i64().unwrap())
            .collect();
        assert!(
            ids.contains(&project_id),
            "admin (non-member) must see the project, got {ids:?}"
        );

        let resp = json_get(&app_as_user(db, &non_member), "/api/projects").await;
        assert_eq!(resp.status(), StatusCode::OK);
        let projects = parse_json(resp).await;
        assert_eq!(
            projects.as_array().unwrap().len(),
            0,
            "plain non-member must see no projects under enforcement"
        );
    }

    // ── Project lead permission tests ────────────────────────

    #[tokio::test]
    async fn project_lead_can_update_own_project() {
        let (db, _, lead, _, project_id) = setup_lead_test();
        let app = app_as_user(db, &lead);

        let update = serde_json::json!({"name": "Renamed by lead"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        assert_eq!(data["name"], "Renamed by lead");
    }

    #[tokio::test]
    async fn admin_can_update_any_project() {
        let (db, admin, _, _, project_id) = setup_lead_test();
        let app = app_as_user(db, &admin);

        let update = serde_json::json!({"name": "Renamed by admin"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn regular_user_cannot_update_project() {
        let (db, _, _, regular, project_id) = setup_lead_test();
        let app = app_as_user(db, &regular);

        let update = serde_json::json!({"name": "Hijacked"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn only_admin_can_delete_project() {
        let (db, admin, lead, _, project_id) = setup_lead_test();

        // Lead cannot delete
        let lead_app = app_as_user(db.clone(), &lead);
        let resp = lead_app
            .clone()
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri(format!("/api/projects/{project_id}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        // Admin can delete
        let admin_app = app_as_user(db, &admin);
        let resp = admin_app
            .clone()
            .oneshot(
                Request::builder()
                    .method("DELETE")
                    .uri(format!("/api/projects/{project_id}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ── LIF-102: project edit blocked when project has no lead ────────────
    //
    // The previous behavior compared `Some(user.id)` to `project.lead_user_id`,
    // which was `None`, so every non-admin user was rejected forever. The fix
    // is two-part: default the creator as lead on create (so the unowned state
    // is uncommon), and explicitly route the `None` case to admin-only access.

    /// Create a project with `lead_user_id = NULL` via direct DB access,
    /// bypassing the API's default-creator-as-lead behavior.
    fn seed_unowned_project(db: &crate::db::DbPool) -> i64 {
        let conn = db.write().unwrap();
        crate::db::queries::create_project(
            &conn,
            &CreateProject {
                name: "Unowned".into(),
                identifier: "UNO".into(),
                ..Default::default()
            },
        )
        .unwrap()
        .id
    }

    #[tokio::test]
    async fn non_admin_cannot_edit_unowned_project() {
        let (db, _, _, regular, _) = setup_lead_test();
        let project_id = seed_unowned_project(&db);
        let app = app_as_user(db, &regular);

        let update = serde_json::json!({"name": "Sneaky rename"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let data = parse_json(resp).await;
        // Distinct message tells the user *why* they can't edit: no lead exists.
        assert!(
            data["error"].as_str().unwrap_or("").contains("no lead"),
            "expected 'no lead' in error, got: {}",
            data["error"]
        );
    }

    #[tokio::test]
    async fn admin_can_edit_unowned_project() {
        let (db, admin, _, _, _) = setup_lead_test();
        let project_id = seed_unowned_project(&db);
        let app = app_as_user(db, &admin);

        let update = serde_json::json!({"name": "Renamed by admin"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        assert_eq!(data["name"], "Renamed by admin");
    }

    // ── LIF-103: tristate clear via HTTP ─────────────────────────────────
    //
    // The model now distinguishes "field absent" from "field explicitly null"
    // so clients can wipe emoji/lead back to NULL. Before the fix, both
    // shapes collapsed to None and the update path skipped the column.

    #[tokio::test]
    async fn update_with_null_emoji_clears_emoji() {
        let (db, admin, _, _, _) = setup_lead_test();
        let app = app_as_user(db.clone(), &admin);

        // Seed a project with an emoji set.
        let project = {
            let conn = db.write().unwrap();
            crate::db::queries::create_project(
                &conn,
                &CreateProject {
                    name: "With Emoji".into(),
                    identifier: "EMJ".into(),
                    emoji: Some("🧪".into()),
                    lead_user_id: Some(admin.id),
                    ..Default::default()
                },
            )
            .unwrap()
        };
        assert_eq!(project.emoji.as_deref(), Some("🧪"));

        // PUT with explicit null.
        let update = serde_json::json!({"emoji": null});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{}", project.id))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        assert!(
            data["emoji"].is_null(),
            "expected null emoji, got: {}",
            data["emoji"]
        );
    }

    #[tokio::test]
    async fn update_with_null_lead_clears_lead() {
        let (db, admin, lead, _, project_id) = setup_lead_test();
        // setup_lead_test creates project with lead set.
        let app = app_as_user(db.clone(), &admin); // admin can edit any project

        // Sanity check: lead is set.
        let pre: serde_json::Value = {
            let conn = db.read().unwrap();
            let p = crate::db::queries::get_project(&conn, project_id).unwrap();
            serde_json::to_value(&p).unwrap()
        };
        assert_eq!(pre["lead_user_id"].as_i64(), Some(lead.id));

        let update = serde_json::json!({"lead_user_id": null});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        assert!(
            data["lead_user_id"].is_null(),
            "expected null lead_user_id, got: {}",
            data["lead_user_id"]
        );
    }

    #[tokio::test]
    async fn update_with_empty_body_changes_nothing() {
        let (db, admin, lead, _, project_id) = setup_lead_test();
        let app = app_as_user(db, &admin);

        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(b"{}".to_vec()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        // Project from setup_lead_test has name "Lead Test", identifier "LDT",
        // lead set, no emoji.
        assert_eq!(data["name"], "Lead Test");
        assert_eq!(data["identifier"], "LDT");
        assert_eq!(data["lead_user_id"].as_i64(), Some(lead.id));
        assert!(data["emoji"].is_null());
    }

    #[tokio::test]
    async fn update_lead_to_nonexistent_user_returns_400() {
        let (db, admin, _, _, project_id) = setup_lead_test();
        let app = app_as_user(db, &admin);

        let update = serde_json::json!({"lead_user_id": 99999});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{project_id}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let data = parse_json(resp).await;
        assert!(
            data["error"].as_str().unwrap_or("").contains("not found"),
            "expected 'not found' in error, got: {}",
            data["error"]
        );
    }

    // ── LIF-233: sidebar reordering ──────────────────────────

    /// POST a project with an explicit identifier; return its id.
    async fn seed_named_project(app: &axum::Router, name: &str, ident: &str) -> i64 {
        let resp = json_post(
            app,
            "/api/projects",
            serde_json::json!({ "name": name, "identifier": ident }),
        )
        .await;
        parse_json(resp).await["id"].as_i64().unwrap()
    }

    async fn list_project_names(app: &axum::Router) -> Vec<String> {
        let resp = json_get(app, "/api/projects").await;
        parse_json(resp)
            .await
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap().to_string())
            .collect()
    }

    #[tokio::test]
    async fn reorder_persists_new_order() {
        let app = test_app();
        let a = seed_named_project(&app, "Alpha", "AAA").await;
        let b = seed_named_project(&app, "Beta", "BBB").await;
        let c = seed_named_project(&app, "Gamma", "GGG").await;

        // Default order is alphabetical.
        assert_eq!(list_project_names(&app).await, ["Alpha", "Beta", "Gamma"]);

        // Reorder: Gamma, Alpha, Beta.
        let resp = json_put(
            &app,
            "/api/projects/reorder",
            serde_json::json!({ "ids": [c, a, b] }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        // Response echoes the new order.
        let returned: Vec<String> = parse_json(resp)
            .await
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p["name"].as_str().unwrap().to_string())
            .collect();
        assert_eq!(returned, ["Gamma", "Alpha", "Beta"]);
        // And a fresh GET reflects it.
        assert_eq!(list_project_names(&app).await, ["Gamma", "Alpha", "Beta"]);
    }

    #[tokio::test]
    async fn reorder_allowed_for_non_lead_user() {
        // Unlike update_project (lead/admin-only), reordering is open to any
        // authenticated user since sidebar order is instance-wide chrome.
        let (db, _, _, regular, _) = setup_lead_test();
        let app = app_as_user(db, &regular);

        // setup_lead_test already created project "LDT"; add a second.
        let ldt = {
            // resolve LDT's id from the list
            let names = json_get(&app, "/api/projects").await;
            parse_json(names).await[0]["id"].as_i64().unwrap()
        };
        let second = seed_named_project(&app, "Second", "SEC").await;

        let resp = json_put(
            &app,
            "/api/projects/reorder",
            serde_json::json!({ "ids": [second, ldt] }),
        )
        .await;
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "a regular (non-lead) user should be allowed to reorder"
        );
        assert_eq!(list_project_names(&app).await, ["Second", "Lead Test"]);
    }

    #[tokio::test]
    async fn reorder_with_unknown_id_returns_400() {
        let app = test_app();
        let a = seed_named_project(&app, "Alpha", "AAA").await;
        let resp = json_put(
            &app,
            "/api/projects/reorder",
            serde_json::json!({ "ids": [a, 99999] }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn create_project_defaults_lead_to_creator() {
        // setup_lead_test gives us a real lead user we can authenticate as.
        let (db, _, lead, _, _) = setup_lead_test();
        let app = app_as_user(db, &lead);

        let body = serde_json::json!({
            "name": "My Project",
            "identifier": "MINE",
            "description": ""
            // intentionally no lead_user_id
        });
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/api/projects")
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&body).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let data = parse_json(resp).await;
        assert_eq!(
            data["lead_user_id"].as_i64(),
            Some(lead.id),
            "expected lead defaulted to creator, got: {}",
            data["lead_user_id"]
        );

        // And the creator can subsequently edit it (the whole point — no more trap).
        let pid = data["id"].as_i64().unwrap();
        let update = serde_json::json!({"name": "Renamed by creator"});
        let resp = app
            .clone()
            .oneshot(
                Request::builder()
                    .method("PUT")
                    .uri(format!("/api/projects/{pid}"))
                    .header("content-type", "application/json")
                    .body(axum::body::Body::from(serde_json::to_vec(&update).unwrap()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ── GitHub import endpoint (LIF-264) ─────────────────────
    //
    // The HTTP handler wires a LiveGithub fetcher (real network), so we test
    // the injectable core `import_github_with` with a fake fetcher — exercising
    // the same collect → apply pipeline the endpoint uses, with zero network.

    use crate::db::DbPool;
    use crate::import::github::{
        GithubComment, GithubFetcher, GithubImportError, GithubIssue, GithubUser, StateFilter,
    };

    fn import_pool() -> (DbPool, i64, i64) {
        let db = crate::db::open_memory().unwrap();
        let (pid, owner) = {
            let conn = db.write().unwrap();
            conn.execute(
                "INSERT INTO users (username, email, password_hash, display_name, is_admin, is_bot)
                 VALUES ('boss', 'boss@test.local', 'x', 'Boss', 1, 0)",
                [],
            )
            .unwrap();
            let owner = conn.last_insert_rowid();
            let pid = crate::db::queries::create_project(
                &conn,
                &CreateProject {
                    name: "App".into(),
                    identifier: "APP".into(),
                    lead_user_id: Some(owner),
                    ..Default::default()
                },
            )
            .unwrap()
            .id;
            (pid, owner)
        };
        (db, pid, owner)
    }

    struct FakeGithub;
    impl GithubFetcher for FakeGithub {
        fn fetch_issues_page(
            &self,
            page: u32,
            _state: StateFilter,
        ) -> Result<(Vec<GithubIssue>, bool), GithubImportError> {
            if page > 1 {
                return Ok((vec![], false));
            }
            let issues: Vec<GithubIssue> = serde_json::from_str(
                r#"[
                    {"number":1,"title":"Open one","body":"b","state":"open","labels":[{"name":"bug","color":"d73a4a"}],"assignees":[]},
                    {"number":2,"title":"Closed one","body":"","state":"closed","labels":[],"assignees":[]},
                    {"number":3,"title":"A PR","body":"","state":"open","labels":[],"assignees":[],"pull_request":{"url":"x"}}
                ]"#,
            )
            .unwrap();
            Ok((issues, false))
        }
        fn fetch_comments(&self, _n: i64) -> Result<Vec<GithubComment>, GithubImportError> {
            Ok(vec![GithubComment {
                user: Some(GithubUser {
                    login: "octocat".into(),
                }),
                body: Some("nice".into()),
                created_at: Some("2024-01-01T00:00:00Z".into()),
            }])
        }
    }

    /// Returns one real issue, then fails `fetch_comments` with whatever the
    /// test wants — the cheapest way to drive a specific import error through
    /// the same `collect → LificError` path the endpoint uses.
    struct FailingGithub(GithubImportError);
    impl GithubFetcher for FailingGithub {
        fn fetch_issues_page(
            &self,
            page: u32,
            _state: StateFilter,
        ) -> Result<(Vec<GithubIssue>, bool), GithubImportError> {
            if page > 1 {
                return Ok((vec![], false));
            }
            let issues: Vec<GithubIssue> = serde_json::from_str(
                r#"[{"number":1,"title":"Open one","body":"b","state":"open","labels":[],"assignees":[]}]"#,
            )
            .unwrap();
            Ok((issues, false))
        }
        fn fetch_comments(&self, _n: i64) -> Result<Vec<GithubComment>, GithubImportError> {
            Err(self.0.clone())
        }
    }

    fn req(dry_run: bool) -> GithubImportRequest {
        GithubImportRequest {
            repo: "octocat/hello".into(),
            token: None,
            state: "all".into(),
            map_open: "backlog".into(),
            map_closed: "done".into(),
            dry_run,
        }
    }

    #[test]
    fn import_github_dry_run_counts_and_writes_nothing() {
        let (db, pid, owner) = import_pool();
        let summary = import_github_with(
            &db,
            pid,
            Some(owner),
            &FakeGithub,
            "octocat/hello",
            StateFilter::All,
            &req(true),
        )
        .unwrap();
        assert!(summary.dry_run);
        assert_eq!(summary.issues_created, 2, "PR filtered out");
        assert_eq!(summary.skipped_non_issues, 1);
        assert_eq!(summary.comments_planned, 2);
        assert_eq!(summary.labels_planned, 1);
        // Nothing written.
        let conn = db.read().unwrap();
        let n: i64 = conn
            .query_row("SELECT COUNT(*) FROM issues", [], |r| r.get(0))
            .unwrap();
        assert_eq!(n, 0);
    }

    #[test]
    fn import_github_real_run_writes_and_is_idempotent() {
        let (db, pid, owner) = import_pool();
        let s1 = import_github_with(
            &db,
            pid,
            Some(owner),
            &FakeGithub,
            "octocat/hello",
            StateFilter::All,
            &req(false),
        )
        .unwrap();
        assert_eq!(s1.issues_created, 2);
        assert_eq!(s1.comments_created, 2);
        assert_eq!(s1.labels_created, 1);

        // Re-run: idempotent no-op.
        let s2 = import_github_with(
            &db,
            pid,
            Some(owner),
            &FakeGithub,
            "octocat/hello",
            StateFilter::All,
            &req(false),
        )
        .unwrap();
        assert_eq!(s2.issues_created, 0);
        assert_eq!(s2.issues_skipped_existing, 2);

        // Verify status mapping + source markers landed.
        let conn = db.read().unwrap();
        let (open_status, open_src): (String, String) = conn
            .query_row(
                "SELECT status, source FROM issues WHERE source = 'github:octocat/hello#1'",
                [],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(open_status, "backlog");
        assert_eq!(open_src, "github:octocat/hello#1");
        let closed_status: String = conn
            .query_row(
                "SELECT status FROM issues WHERE source = 'github:octocat/hello#2'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(closed_status, "done");
    }

    // ── import resource limits are the caller's problem, not a 500 ────────

    use crate::error::LificError;
    use crate::import::github::GithubLimit;
    use axum::response::IntoResponse;

    fn import_error(failure: GithubImportError) -> LificError {
        let (db, pid, owner) = import_pool();
        import_github_with(
            &db,
            pid,
            Some(owner),
            &FailingGithub(failure),
            "octocat/hello",
            StateFilter::All,
            &req(true),
        )
        .expect_err("the fetcher was rigged to fail")
    }

    async fn status_and_message(error: LificError) -> (StatusCode, String) {
        let response = error.into_response();
        let status = response.status();
        let bytes = BodyExt::collect(response.into_body())
            .await
            .unwrap()
            .to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        (status, body["error"].as_str().unwrap().to_string())
    }

    /// Every deliberate ceiling reaches the client as 413 with the limit
    /// named. It used to be a bare 500 "internal server error", which reads
    /// as a Lific bug and tells the operator nothing about their repository.
    #[tokio::test]
    async fn import_resource_limits_answer_413_naming_the_limit() {
        let cases = [
            GithubLimit::Issues { max: 10_000 },
            GithubLimit::CommentsPerIssue {
                issue_number: 7,
                max: 1_000,
            },
            GithubLimit::NormalizedBytes { max: 4096 },
            GithubLimit::ResponseBytes {
                label: "issues",
                max: 4096,
            },
        ];
        for limit in cases {
            let error = import_error(GithubImportError::Limit(limit));
            assert!(
                matches!(error, LificError::PayloadTooLarge(_)),
                "{limit} must map to PayloadTooLarge, got {error:?}"
            );
            let (status, message) = status_and_message(error).await;
            assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
            assert_eq!(
                message,
                limit.to_string(),
                "the response must name the limit that was hit"
            );
        }
    }

    /// GitHub being unreachable is a server-side fault and keeps the generic
    /// 500 it has always returned, with the detail staying in the logs.
    #[tokio::test]
    async fn import_upstream_failures_stay_internal() {
        for failure in [
            GithubImportError::Upstream("request failed: connection reset".into()),
            GithubImportError::Internal("GitHub import content size overflow".into()),
        ] {
            let error = import_error(failure);
            assert!(
                matches!(error, LificError::Internal(_)),
                "upstream/internal failures must not become a client error: {error:?}"
            );
            let (status, message) = status_and_message(error).await;
            assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(
                message, "internal server error",
                "server-side detail must not leak to the client"
            );
        }
    }
}