alix 0.5.0

A learning tool built for understanding, not just remembering.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
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
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
//! A local web frontend.
//!
//! Bare `alix` starts a small synchronous HTTP server (one request at a
//! time — correct for a single user) that serves an embedded web page and a
//! JSON API — the sole interactive frontend. The [`Session`]/[`Store`] drive
//! review, and cards are sent to the browser as a DTO built from
//! [`render::note_units`], so the note structuring lives in one place. Grades
//! persist to the same progress store the rest of the CLI (`deck`, `trace`,
//! `generate`, …) reads and writes, so studying in the browser and running
//! those commands share one history.
//!
//! It is deliberately local-only: no accounts, no database. By default it
//! binds to `127.0.0.1`; `--lan` binds all interfaces so a phone or tablet on
//! the same network can reach it (there is no authentication, so that is
//! opt-in).

mod catalog;
mod dto;
mod jobs;
mod respond;

use std::{
    collections::HashMap,
    net::SocketAddr,
    path::{Path, PathBuf},
    sync::Arc,
    time::Instant,
};

use anyhow::{Result, anyhow};
use catalog::*;
use dto::*;
use jobs::*;
use respond::*;
use serde::Deserialize;
use tiny_http::{Method, Server};

/// `SelectOptions` lives in `assemble` (the lib owns its own input type);
/// re-exported here so `serve::SelectOptions` keeps working for callers.
pub use crate::assemble::SelectOptions;
use crate::{
    assemble::{self, CardsBuild, SessionBuild},
    augment::{self, AugmentCache},
    config::{
        AiConfig, Audience, Bindings, BrowseBindings, ExamConfig, GenerateDeckConfig, PickerKeys,
    },
    deck::{self, Deck},
    doctor, exam, generate, import,
    recent::RecentDecks,
    review,
    session::now_ms,
    share,
    store::{self, Store},
    trace::{self, Walk},
};

const REVIEW_HTML: &str = include_str!("../../assets/web/review.html");
const KIDS_HTML: &str = include_str!("../../assets/web/kids/kids.html");
const THEME_CSS: &str = include_str!("../../assets/web/theme.css");
const THEME_JS: &str = include_str!("../../assets/web/theme.js");
const ALIX_LOGO_JS: &str = include_str!("../../assets/web/alix-logo.js");
const HEAD_HTML: &str = include_str!("../../assets/web/_head.html");
const BRAND_HTML: &str = include_str!("../../assets/web/_brand.html");

// Self-hosted IBM Plex webfonts (Latin + Latin-Ext subset; see
// `assets/web/fonts/OFL.txt`), embedded so the app works fully offline —
// served by name at `GET /fonts/<name>.woff2` (see `font_bytes`).
const PLEX_SANS_400: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-sans-400.woff2");
const PLEX_SANS_500: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-sans-500.woff2");
const PLEX_SANS_600: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-sans-600.woff2");
const PLEX_SANS_700: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-sans-700.woff2");
const PLEX_MONO_400: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-mono-400.woff2");
const PLEX_MONO_500: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-mono-500.woff2");
const PLEX_MONO_600: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-mono-600.woff2");
const PLEX_MONO_700: &[u8] = include_bytes!("../../assets/web/fonts/ibm-plex-mono-700.woff2");

// Self-hosted Baloo 2 webfonts (Latin subset; see `assets/web/kids/fonts/OFL.txt`),
// embedded so the app works fully offline — served by name at `GET /fonts/<name>.woff2`.
const BALOO2_400: &[u8] = include_bytes!("../../assets/web/kids/fonts/baloo2-400.woff2");
const BALOO2_500: &[u8] = include_bytes!("../../assets/web/kids/fonts/baloo2-500.woff2");
const BALOO2_600: &[u8] = include_bytes!("../../assets/web/kids/fonts/baloo2-600.woff2");
const BALOO2_700: &[u8] = include_bytes!("../../assets/web/kids/fonts/baloo2-700.woff2");
const BALOO2_800: &[u8] = include_bytes!("../../assets/web/kids/fonts/baloo2-800.woff2");

/// Maps a requested `/fonts/<name>` file name to its embedded bytes, or
/// `None` for anything not vendored (→ 404). The name map is the one place
/// that has to stay in sync with the font consts and the files in
/// `assets/web/fonts/` and `assets/web/kids/fonts/`.
fn font_bytes(name: &str) -> Option<&'static [u8]> {
    match name {
        "ibm-plex-sans-400.woff2" => Some(PLEX_SANS_400),
        "ibm-plex-sans-500.woff2" => Some(PLEX_SANS_500),
        "ibm-plex-sans-600.woff2" => Some(PLEX_SANS_600),
        "ibm-plex-sans-700.woff2" => Some(PLEX_SANS_700),
        "ibm-plex-mono-400.woff2" => Some(PLEX_MONO_400),
        "ibm-plex-mono-500.woff2" => Some(PLEX_MONO_500),
        "ibm-plex-mono-600.woff2" => Some(PLEX_MONO_600),
        "ibm-plex-mono-700.woff2" => Some(PLEX_MONO_700),
        "baloo2-400.woff2" => Some(BALOO2_400),
        "baloo2-500.woff2" => Some(BALOO2_500),
        "baloo2-600.woff2" => Some(BALOO2_600),
        "baloo2-700.woff2" => Some(BALOO2_700),
        "baloo2-800.woff2" => Some(BALOO2_800),
        _ => None,
    }
}

/// The review page with its shared-chrome placeholders filled once, so the head
/// boilerplate (`<!--%head%-->`) and brand mark (`<!--%brand%-->`) live in one place.
static REVIEW_PAGE: std::sync::LazyLock<String> =
    std::sync::LazyLock::new(|| compose_page(REVIEW_HTML));

/// The kid-facing frontend, composed the same way as [`REVIEW_PAGE`]. A
/// placeholder for now — fleshed out in later tasks.
static KIDS_PAGE: std::sync::LazyLock<String> =
    std::sync::LazyLock::new(|| compose_page(KIDS_HTML));

/// Fill the shared-chrome placeholders in a served page.
fn compose_page(html: &str) -> String {
    html.replace("<!--%head%-->", HEAD_HTML)
        .replace("<!--%brand%-->", BRAND_HTML)
}

/// Which single-page app `/` returns, keyed by `[serve] audience`. Small
/// lookup-by-key helper (mirrors [`font_bytes`]) so route dispatch and its
/// test can share one function.
fn app_page(audience: Audience) -> &'static str {
    match audience {
        Audience::Adult => &REVIEW_PAGE,
        Audience::Kids => &KIDS_PAGE,
    }
}

/// Global options for a served review, independent of which decks are chosen
/// (the per-session label and deck paths come from [`SessionBuild`]).
pub struct ReviewOptions {
    pub keys: Bindings,
    /// Deck-picker navigation keys (the `[picker]` section), bound on the
    /// selection screen.
    pub picker: PickerKeys,
    /// Browse-mode keys (the `[browse]` section), bound on the `/browse` page
    /// this server also hosts.
    pub browse: BrowseBindings,
    /// AI-exam settings (model, question count, default strictness, …).
    pub exam: ExamConfig,
    /// AI augmentation settings (model, per-target counts), for generating
    /// augmentations from the picker's Augment screen.
    pub ai: AiConfig,
    /// AI deck-generation settings (model, timeout, max cards, guidance, …),
    /// for `POST /api/generate`.
    pub generate: GenerateDeckConfig,
    /// Which frontend `/` serves (`[serve] audience`); also selects the
    /// ask-tutor's kid-safe vs. adult preamble (`start_ask`).
    pub audience: Audience,
    /// Pairing token required on `/api/*` when set (auto-generated for `--lan`);
    /// `None` leaves the server open (the localhost default).
    pub auth: Option<String>,
    /// The `--config` path the launcher loaded config from (`None` → the
    /// platform default), passed through so `/api/doctor` checks the same file.
    pub config_path: Option<PathBuf>,
    /// How this instance is reached, for `/api/pair`'s pairing sheet.
    pub pair: PairInfo,
    /// `true` for a scoped `alix <dir>` launch — its decks dir is pinned to
    /// that folder forever. `false` for the config-derived launch (bare
    /// `alix`), whose `/api/decks` re-resolves the configured dir on every
    /// fetch so a `decks_dir` edit takes effect without a restart.
    pub scoped: bool,
    /// Everything [`assemble::select`] needs to turn a deck-selection into a
    /// review session or a trace walk (review/ask config, trace auto-grade,
    /// pacing, this instance's store).
    pub cfg: assemble::AssembleConfig,
}

/// How this instance is reached, for the pairing sheet. Built by the
/// launcher, which is the only place that knows bind + token + LAN IP.
pub struct PairInfo {
    pub url: String,
    pub lan: bool,
}

/// Binds the server socket — separated from [`run_review`] so a port clash
/// errors before the caller announces a URL, and with the multi-instance
/// remedy in the message.
pub fn bind(addr: SocketAddr) -> Result<Server> {
    Server::http(addr).map_err(|e| {
        anyhow!(
            "cannot start the server on {addr}: {e} — is another alix using this port? try --port"
        )
    })
}

/// Serves review on the already-bound `server` until the process is stopped
/// (binding happens at the call site, *before* the URL is announced — so a
/// port clash errors before any success-looking output), opening on the
/// in-browser deck-selection screen; picking decks (`POST /api/select`) calls
/// [`assemble::select`] to construct a session (or a trace walk) in place,
/// using `opts.cfg`.
///
/// `server` is shared (`Arc`) so a caller can stop the loop from outside it:
/// call `.unblock()` on a clone of the same `Arc<Server>` to end
/// `incoming_requests()` — tiny_http queues that as a one-shot stop signal
/// rather than polling a flag, so it is race-free even if the loop is mid-request
/// when called. Production (`launch.rs`) never calls it — the process just
/// exits on Ctrl-C — but `tests/api.rs`'s round-trip harness uses it to run this
/// real loop against a temp store + fixture deck and tear it down deterministically
/// after each test.
pub fn run_review(
    mut store: Store,
    mut recent: RecentDecks,
    mut decks_dir: PathBuf,
    server: Arc<Server>,
    opts: ReviewOptions,
) -> Result<()> {
    let ReviewOptions {
        keys: bindings,
        picker: picker_keys,
        browse: browse_bindings,
        exam: exam_cfg,
        ai: ai_cfg,
        generate: generate_cfg,
        audience,
        auth,
        config_path,
        pair,
        scoped,
        cfg,
    } = opts;
    // `review`/`ask` used to also live at the top level of `ReviewOptions`,
    // kept in sync with `cfg` by hand at every construction site — `cfg` is
    // now their one source.
    let ask_cfg = cfg.ask.clone();
    let review_cfg = cfg.review;
    let keys = ReviewKeys::from(&bindings);
    let picker_keys = PickerKeysDto::from(&picker_keys);
    // The `/browse` page this server also hosts needs its own next/prev/remove
    // keys, distinct from the review grade keys served at `/api/keys`.
    let browse_keys = BrowseKeys::from(&browse_bindings);
    let ask_info = AskInfoDto::from(&ask_cfg);
    // The server always opens on the picker; review/browse states are entered
    // from it (`/api/select`, `/api/browse`) — browse is a native mode of the
    // review server, not a separate page.
    let (mut reviewing, mut browsing): (Option<Reviewing>, Option<Browsing>) = (None, None);
    let mut examining: Option<Examining> = None;
    // The picker's "Augment" action opens a deck's augmentation screen here.
    let mut augmenting: Option<Augmenting> = None;
    // The add-sheet's "Generate from URL" action; one deck generation at a time.
    let mut generating: Option<Generating> = None;
    // The picker's "Share" action; one wormhole send in flight at a time. An
    // abandoned/replaced job always drops through `Sharing`/`ShareJob` (never
    // leaked), so its child process is cancelled even without a close call.
    let mut sharing: Option<Sharing> = None;
    // The picker's "Receive" action; one wormhole receive in flight at a time.
    // Same drop-cancels invariant as `sharing` — an abandoned/replaced job
    // always drops through `ShareJob`, cancelling its wormhole child.
    let mut receiving: Option<Receiving> = None;
    // A trace picked from the selection screen walks in-page inside review.html
    // (no navigation to a separate `/walk` page — the walk is an in-page mode).
    let mut walking: Option<Walking> = None;
    // `browsing` (seeded above for a `--serve` browse launch) is also entered
    // from the picker's "Browse" action (POST /api/browse) — in-page, no page nav.
    // Workspace icons resolved while building the picker, served via `/img/` at
    // launcher time (when no review/browse session owns the registry).
    let mut launcher_icons: HashMap<String, PathBuf> = HashMap::new();
    // Diagnostic net for {#server-subresource-stall}: with ALIX_HTTP_LOG set,
    // one stderr line as each request is POPPED off tiny_http's queue. On the
    // next stall the pattern is decisive: a wedged request that never prints
    // never left tiny_http's connection reader; one that prints but is
    // followed by nothing hung in a handler (this loop is single-threaded).
    let http_log = std::env::var_os("ALIX_HTTP_LOG").is_some();
    for mut request in server.incoming_requests() {
        let method = request.method().clone();
        let path = request_path(&request);
        if http_log {
            eprintln!("[http] {method} {path}");
        }
        if !is_authorized(
            &path,
            header_value(&request, "Authorization"),
            query_param(request.url(), "token").as_deref(),
            auth.as_deref(),
        ) {
            respond_status(request, 401);
            continue;
        }
        match (&method, path.as_str()) {
            (Method::Get, "/") => respond_html(request, app_page(audience)),
            (Method::Get, "/theme.css") => {
                respond_asset(request, THEME_CSS, "text/css; charset=utf-8")
            }
            (Method::Get, "/theme.js") => {
                respond_asset(request, THEME_JS, "application/javascript; charset=utf-8")
            }
            (Method::Get, key) if key.starts_with("/fonts/") => {
                let name = &key["/fonts/".len()..];
                match font_bytes(name) {
                    Some(bytes) => respond_font(request, bytes),
                    None => respond_status(request, 404),
                }
            }
            (Method::Get, "/alix-logo.js") => respond_asset(
                request,
                ALIX_LOGO_JS,
                "application/javascript; charset=utf-8",
            ),
            (Method::Get, "/api/keys") => respond_json(request, &keys),
            (Method::Get, "/api/version") => respond_json(
                request,
                &VersionDto {
                    version: env!("CARGO_PKG_VERSION"),
                },
            ),
            (Method::Get, "/api/doctor") => {
                let (cfg, _) = doctor::check_config(config_path.as_deref());
                let rows = vec![
                    cfg,
                    doctor::check_store(Some(store.path().to_path_buf())),
                    doctor::check_decks(&decks_dir),
                    // Mirrors `main.rs::doctor_cmd`'s binary lines verbatim
                    // (names, purposes, remedies) — the web report must match
                    // the CLI's, minus the costed `--backends` probe.
                    doctor::check_binary(
                        "backend",
                        &ask_cfg.command,
                        "the AI features (tutor, exam, generate)",
                        "install it and log in — or switch `[ask] backend` in the config",
                    ),
                    doctor::check_binary(
                        "share",
                        "wormhole",
                        "sharing (`alix share`/`receive`)",
                        "install magic-wormhole (e.g. `pipx install magic-wormhole`, or your package manager)",
                    ),
                ]
                .into_iter()
                .map(DoctorRowDto::from)
                .collect();
                respond_json(request, &DoctorDto { rows })
            }
            (Method::Get, "/api/pair") => {
                let svg = if pair.lan {
                    crate::qr::svg(&pair.url)
                } else {
                    None
                };
                respond_json(
                    request,
                    &PairDto {
                        url: pair.url.clone(),
                        svg,
                        lan: pair.lan,
                    },
                )
            }
            (Method::Get, "/api/browse-keys") => respond_json(request, &browse_keys),
            (Method::Get, "/api/picker-keys") => respond_json(request, &picker_keys),
            (Method::Get, "/api/ask-info") => respond_json(request, &ask_info),
            (Method::Get, "/api/decks") => {
                let catalog = decks_list_dto(
                    scoped,
                    config_path.as_deref(),
                    &mut decks_dir,
                    &recent,
                    &store,
                    &mut launcher_icons,
                    review_cfg,
                );
                respond_json(request, &catalog)
            }
            // Image cards: served from whichever session is live (review or browse).
            (Method::Get, key) if key.starts_with("/img/") => {
                let name = &key["/img/".len()..];
                if let Some(r) = &reviewing {
                    serve_image(request, &r.images, name)
                } else if let Some(b) = &browsing {
                    serve_image(request, &b.images, name)
                } else {
                    serve_image(request, &launcher_icons, name)
                }
            }
            (Method::Get, "/api/state") => {
                // Browse is an in-page mode: when a browse list is live (a
                // `--serve` browse launch), the page gets the browse payload here
                // and opens the browse overlay instead of a review session.
                if let Some(b) = &browsing {
                    respond_json(request, &browse_payload(Some(b)))
                } else {
                    // A missed card may have cooled back into due-ness since the
                    // last fetch; re-check so it re-enters review on this poll
                    // (stats preserved), no manual restart needed.
                    if let Some(r) = reviewing.as_mut() {
                        r.session.poll(&store, now_ms());
                    }
                    respond_json(request, &review_state(reviewing.as_ref(), &store))
                }
            }
            (Method::Post, "/api/select") => {
                match read_selection(&mut request, &decks_dir, &recent) {
                    Some(sel) => {
                        let opts = sel.opts;
                        let paths = vec![sel.deck];
                        // Write to the deck's own store — a workspace's `progress.json`
                        // when they share one, else the global store — the same store
                        // the picker's badges are read from.
                        if let Err(e) = assemble::store_for(&paths, cfg.instance_store.as_deref())
                            .map(|s| store = s)
                        {
                            eprintln!("warning: could not open the progress store: {e}");
                            respond_status(request, 400);
                            continue;
                        }
                        // `select` reborrows `paths` for its own walk-vs-review
                        // classification, so keep a copy for the recent-decks
                        // record below (only taken on an unfinished review).
                        let recorded_paths = paths.clone();
                        match assemble::select(paths, &mut store, &cfg, &opts) {
                            Ok(assemble::Selected::Walk(wb)) => {
                                let w = Walking::new(wb.walk, wb.grade);
                                let dto = walk_dto(&w);
                                walking = Some(w);
                                reviewing = None;
                                examining = None;
                                respond_json(request, &dto);
                            }
                            Ok(assemble::Selected::Review(b)) => {
                                // Remember these decks for next time's picker — but
                                // only when there is actually something to review, so
                                // merely opening a deck with nothing due doesn't bump
                                // it to the top of the recent list.
                                if !b.session.is_finished() {
                                    recent.record(&recorded_paths, now_ms());
                                    let _ = recent.save();
                                }
                                let mut r = Reviewing::new(b);
                                r.open_augment(store.path());
                                r.rotate_variant();
                                reviewing = Some(r);
                                walking = None;
                                respond_json(request, &review_state(reviewing.as_ref(), &store));
                            }
                            Err(e) => {
                                eprintln!("warning: could not load the selected decks: {e}");
                                respond_status(request, 400);
                            }
                        }
                    }
                    None => respond_status(request, 400),
                }
            }
            // The picker's "Browse" action: build a read-only card list and return
            // it, so the page opens the browse overlay in place (no page nav).
            (Method::Post, "/api/browse") => {
                match read_selection(&mut request, &decks_dir, &recent) {
                    Some(sel) => {
                        let paths = vec![sel.deck];
                        if let Err(e) = assemble::store_for(&paths, cfg.instance_store.as_deref())
                            .map(|s| store = s)
                        {
                            eprintln!("warning: could not open the progress store: {e}");
                            respond_status(request, 400);
                            continue;
                        }
                        // `browse` takes `paths` by value, so keep a copy for the
                        // recent-decks record below.
                        let recorded_paths = paths.clone();
                        match assemble::browse(paths) {
                            Ok(b) => {
                                // Browse always remembers its deck for next time's
                                // picker (unlike a review, which only records when
                                // there is something to review).
                                recent.record(&recorded_paths, now_ms());
                                let _ = recent.save();
                                browsing = Some(Browsing::new(b));
                                reviewing = None;
                                walking = None;
                                examining = None;
                                respond_json(request, &browse_payload(browsing.as_ref()));
                            }
                            Err(e) => {
                                eprintln!("warning: could not load the selected decks: {e}");
                                respond_status(request, 400);
                            }
                        }
                    }
                    None => respond_status(request, 400),
                }
            }
            // The focus drawer asks for a deck's stored topologies + region
            // heatmaps when it's selected. Read-only: open the deck's own store
            // transiently, never disturbing the active session store.
            (Method::Post, "/api/deck-topology") => {
                let dto = match read_selection(&mut request, &decks_dir, &recent) {
                    Some(sel) => {
                        match (
                            Deck::load(&sel.deck),
                            assemble::store_for(
                                std::slice::from_ref(&sel.deck),
                                cfg.instance_store.as_deref(),
                            ),
                        ) {
                            (Ok(deck), Ok(s)) => {
                                let augment =
                                    AugmentCache::open(augment::augment_path_for(s.path()));
                                deck_topology_dto(&augment, &s, &deck, review_cfg)
                            }
                            _ => DeckTopologyDto::default(),
                        }
                    }
                    None => DeckTopologyDto::default(),
                };
                respond_json(request, &dto);
            }
            // Wipe a row's review progress (the sheet's typed-name gate is
            // client UX; a token holder is trusted — same class as grading).
            (Method::Post, "/api/reset") => {
                #[derive(Deserialize)]
                struct Body {
                    deck: String,
                }
                let Some(body) = serde_json::from_reader::<_, Body>(request.as_reader()).ok()
                else {
                    respond_status(request, 400);
                    continue;
                };
                // Rows resolve to their deck files: a workspace/folder row to
                // its members, a deck row to itself.
                let paths = match resolve_row(&body.deck, &decks_dir, &recent) {
                    Resolved::One(p) => vec![p],
                    Resolved::Many { files, .. } => files,
                    Resolved::Ambiguous | Resolved::Unknown => {
                        respond_status(request, 400);
                        continue;
                    }
                };
                let name = body.deck;
                let decks: Vec<Deck> = match paths.iter().map(Deck::load).collect() {
                    Ok(d) => d,
                    Err(_) => {
                        respond_status(request, 400);
                        continue;
                    }
                };
                let cleared = assemble::store_for(&paths, cfg.instance_store.as_deref())
                    .and_then(|mut s| crate::library::reset_decks(&mut s, decks.iter()));
                match cleared {
                    Ok(n) => {
                        // The in-memory global store may now be stale — reload.
                        if let Ok(s) = assemble::store_for(&[], cfg.instance_store.as_deref()) {
                            store = s;
                        }
                        respond_json(
                            request,
                            &ResetDto {
                                deck: name,
                                cards_cleared: n,
                            },
                        );
                    }
                    Err(_) => respond_status(request, 400),
                }
            }
            // Set, move, or clear (`date: null`) a workspace's "ready by"
            // deadline in its `alix.local.toml` ({#deadlines}). Responds with
            // the refreshed decks payload so the picker re-renders the
            // readout in one round trip, matching `/api/reset`'s pattern of
            // returning caller-relevant state rather than a bare 200.
            (Method::Post, "/api/workspace/deadline") => {
                // `date` is required. A missing key is a 400 (a client bug
                // must never be read as "clear"); an explicit JSON `null` is
                // the real clear signal. Serde's "double option" idiom tells
                // them apart: `#[serde(default)]` supplies the outer `None`
                // only when the key is absent, and `deserialize_some` fires
                // when the key IS present, wrapping whatever it parses to
                // (including `null`) in `Some`.
                fn deserialize_some<'de, D>(
                    deserializer: D,
                ) -> Result<Option<Option<String>>, D::Error>
                where
                    D: serde::Deserializer<'de>,
                {
                    Option::<String>::deserialize(deserializer).map(Some)
                }
                #[derive(Deserialize)]
                struct Body {
                    name: String,
                    #[serde(default, deserialize_with = "deserialize_some")]
                    date: Option<Option<String>>,
                }
                let Some(body) = serde_json::from_reader::<_, Body>(request.as_reader()).ok()
                else {
                    respond_status(request, 400);
                    continue;
                };
                let date = match body.date {
                    None => {
                        respond_status(request, 400);
                        continue;
                    }
                    Some(None) => None,
                    Some(Some(s)) => match chrono::NaiveDate::parse_from_str(&s, "%Y-%m-%d") {
                        Ok(d) => Some(d),
                        Err(_) => {
                            respond_status(request, 400);
                            continue;
                        }
                    },
                };
                // Only a workspace row (an `alix.toml` manifest, not just a
                // plain folder of decks) has a deadline concept, see
                // `workspace::is_workspace`; the catalog only ever computes a
                // `deadline` readout for one.
                let dir = match resolve_row(&body.name, &decks_dir, &recent) {
                    Resolved::Many { dir, .. } if crate::workspace::is_workspace(&dir) => dir,
                    _ => {
                        respond_status(request, 400);
                        continue;
                    }
                };
                if let Err(e) = crate::workspace::set_deadline(&dir, date) {
                    eprintln!("workspace deadline write failed: {e:#}");
                    respond_status(request, 500);
                    continue;
                }
                let catalog = decks_list_dto(
                    scoped,
                    config_path.as_deref(),
                    &mut decks_dir,
                    &recent,
                    &store,
                    &mut launcher_icons,
                    review_cfg,
                );
                respond_json(request, &catalog);
            }
            // Land an uploaded `.tsv`/`.txt` file via `place_deck`. Strict
            // unlike `generate`'s lenient save: an invalid upload is 400 and
            // no file remains — the upload still exists on the user's
            // device, so nothing is lost by refusing to keep a broken copy.
            (Method::Post, "/api/import") => {
                #[derive(Deserialize)]
                struct Body {
                    name: String,
                    text: String,
                    dest: Option<String>,
                }
                let Some(b) = serde_json::from_reader::<_, Body>(request.as_reader()).ok() else {
                    respond_status(request, 400);
                    continue;
                };
                let Some(dir) = resolve_dest(b.dest.as_deref(), &decks_dir, &recent) else {
                    respond_status(request, 400);
                    continue;
                };
                // `.tsv` converts (Anki export); `.txt` is a deck as-is. Case
                // folded so `FILE.TSV` matches — the browser's file picker
                // accept filter offers upper-case extensions too.
                let lower_name = b.name.to_ascii_lowercase();
                let text = if lower_name.ends_with(".tsv") {
                    match import::tsv_to_deck(&b.text) {
                        Ok(t) => t,
                        Err(_) => {
                            respond_status(request, 400);
                            continue;
                        }
                    }
                } else if lower_name.ends_with(".txt") {
                    b.text
                } else {
                    respond_status(request, 400);
                    continue;
                };
                let place_name = normalize_txt_extension(&b.name, &lower_name);
                match crate::library::place_deck(&dir, &place_name, &text) {
                    Ok(p) if p.parse_error.is_none() => {
                        let deck = p
                            .path
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_default();
                        respond_json(
                            request,
                            &ImportDto {
                                deck,
                                cards: p.cards,
                            },
                        );
                    }
                    // Uploads are strict: don't keep an invalid deck around.
                    Ok(p) => {
                        std::fs::remove_file(&p.path).ok();
                        respond_status(request, 400);
                    }
                    Err(_) => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/generate") => {
                #[derive(Deserialize)]
                struct Body {
                    url: String,
                    guidance: Option<String>,
                    dest: Option<String>,
                }
                // A worker may have finished while nobody polled (the page
                // went away) — drain it first, so "finished" means finished
                // even without a GET, and only a live worker 409s.
                if let Some(g) = generating.as_mut() {
                    g.poll();
                }
                if generating.as_ref().is_some_and(|g| g.outcome.is_none()) {
                    respond_status(request, 409); // one costed job at a time
                    continue;
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(b) =
                    body.filter(|b| b.url.starts_with("http://") || b.url.starts_with("https://"))
                else {
                    respond_status(request, 400); // the web generates from URLs only
                    continue;
                };
                let Some(dest) = resolve_dest(b.dest.as_deref(), &decks_dir, &recent) else {
                    respond_status(request, 400);
                    continue;
                };
                // A collision discovered only after the (costed) model call
                // would throw away paid work for nothing — check before
                // spawning, mirroring `library::place_deck`'s stem/extension
                // logic (stage-then-merge: fail fast on what's already
                // knowable, same principle as the CLI's destination guard).
                let name = generate::deck_name(&b.url);
                let stem = name.strip_suffix(".txt").unwrap_or(&name);
                let file = format!("{stem}.txt");
                if dest.join(&file).exists() {
                    respond_json(
                        request,
                        &GenerateDto {
                            phase: "error",
                            deck: None,
                            cards: None,
                            elapsed: Some(0),
                            error: Some(format!(
                                "{file} already exists — rename it or generate into another destination"
                            )),
                        },
                    );
                    continue;
                }
                let mut cfg = generate_cfg.clone();
                if let Some(g) = b
                    .guidance
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                {
                    cfg.extra = Some(g);
                }
                let g = Generating {
                    rx: generate::spawn(b.url.clone(), cfg, ask_cfg.clone()),
                    url: b.url,
                    dest,
                    started: Instant::now(),
                    outcome: None,
                };
                let dto = g.dto();
                generating = Some(g);
                respond_json(request, &dto);
            }
            (Method::Get, "/api/generate") => {
                let Some(g) = generating.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                g.poll();
                respond_json(request, &g.dto());
            }
            (Method::Post, "/api/generate/close") => {
                generating = None; // a running worker finishes and is discarded
                respond_status(request, 200);
            }
            (Method::Post, "/api/share") => {
                #[derive(Deserialize)]
                struct Body {
                    deck: Option<String>,
                }
                // Drain a finished-but-unpolled job first, so a completed send is
                // replaced by the next POST even without an intervening GET —
                // mirroring the `/api/generate` fix (only a *live* job 409s).
                if let Some(s) = sharing.as_mut() {
                    s.poll();
                }
                if sharing.as_ref().is_some_and(|s| s.outcome.is_none()) {
                    respond_status(request, 409); // one share at a time
                    continue;
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let path = match body.and_then(|b| b.deck) {
                    None => Some(decks_dir.clone()),
                    Some(name) => resolved_path(resolve_row(&name, &decks_dir, &recent)),
                };
                let Some(path) = path else {
                    respond_status(request, 400);
                    continue;
                };
                let started = tempfile::tempdir()
                    .map_err(|e| anyhow!("{e}"))
                    .and_then(|tmp| {
                        let to_send = stage_for_share(&path, &tmp)?;
                        let job = share::send_spawn(&to_send)?;
                        Ok(Sharing {
                            job,
                            _stage: tmp,
                            code: None,
                            started: Instant::now(),
                            outcome: None,
                        })
                    });
                match started {
                    Ok(s) => {
                        let dto = s.dto();
                        sharing = Some(s);
                        respond_json(request, &dto);
                    }
                    // Spawn failures (missing binary) surface as an error-phase
                    // job so the sheet shows the install hint, not a bare 400.
                    Err(e) => respond_json(
                        request,
                        &ShareDto {
                            phase: "error",
                            code: None,
                            elapsed: Some(0),
                            error: Some(format!("{e:#}")),
                        },
                    ),
                }
            }
            (Method::Get, "/api/share") => {
                let Some(s) = sharing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                s.poll();
                respond_json(request, &s.dto());
            }
            (Method::Post, "/api/share/close") => {
                // Dropping the (former) job cancels its wormhole child — see
                // `ShareJob`'s `Drop`; `cancel()` here is just for clarity.
                if let Some(s) = sharing.take() {
                    s.job.cancel();
                }
                respond_status(request, 200);
            }
            (Method::Get, "/api/share/zip") => {
                // `request_path` (used for dispatch) already strips the query
                // string, so the plain literal above matches regardless of
                // `?deck=...` — read the param back off the full URL here.
                let name = query_param(request.url(), "deck");
                let path = match &name {
                    None => Some(decks_dir.clone()),
                    Some(n) => resolved_path(resolve_row(n, &decks_dir, &recent)),
                };
                let Some(path) = path else {
                    respond_status(request, 400);
                    continue;
                };
                let zipped = tempfile::tempdir().ok().and_then(|tmp| {
                    let staged = stage_for_share(&path, &tmp).ok()?;
                    let out = tmp.path().join("share.zip");
                    share::zip_to(&staged, &out).ok()?;
                    std::fs::read(&out).ok()
                });
                match zipped {
                    Some(bytes) => {
                        let stem = name
                            .as_deref()
                            .map(|n| n.rsplit('/').next().unwrap_or(n))
                            .unwrap_or("shared-decks");
                        respond_download(request, bytes, "application/zip", &format!("{stem}.zip"));
                    }
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/receive") => {
                #[derive(Deserialize)]
                struct Body {
                    code: String,
                    dest: Option<String>,
                }
                // Drain a finished-but-unpolled job first — same fix as
                // generate/share: only a *live* job 409s.
                if let Some(r) = receiving.as_mut() {
                    r.poll();
                }
                if receiving.as_ref().is_some_and(|r| r.outcome.is_none()) {
                    respond_status(request, 409); // one receive at a time
                    continue;
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(b) = body else {
                    respond_status(request, 400);
                    continue;
                };
                let Some(dest) = resolve_dest(b.dest.as_deref(), &decks_dir, &recent) else {
                    respond_status(request, 400);
                    continue;
                };
                let started = tempfile::tempdir()
                    .map_err(|e| anyhow!("{e}"))
                    .and_then(|tmp| {
                        let job = share::receive_spawn(&b.code, tmp.path())?;
                        Ok(Receiving {
                            job,
                            tmp,
                            dest,
                            started: Instant::now(),
                            outcome: None,
                        })
                    });
                match started {
                    Ok(r) => {
                        let dto = r.dto();
                        receiving = Some(r);
                        respond_json(request, &dto);
                    }
                    // Spawn failures (missing binary) surface as an error-phase
                    // job so the sheet shows the install hint, not a bare 400.
                    Err(e) => respond_json(
                        request,
                        &ReceiveDto {
                            phase: "error",
                            landed: None,
                            stripped: Vec::new(),
                            elapsed: Some(0),
                            error: Some(format!("{e:#}")),
                        },
                    ),
                }
            }
            (Method::Get, "/api/receive") => {
                let Some(r) = receiving.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.poll();
                respond_json(request, &r.dto());
            }
            (Method::Post, "/api/receive/close") => {
                // Dropping the (former) job cancels its wormhole child — see
                // `ShareJob`'s `Drop`; `cancel()` here is just for clarity.
                if let Some(r) = receiving.take() {
                    r.job.cancel();
                }
                respond_status(request, 200);
            }
            (Method::Post, "/api/receive/zip") => {
                // `request_path` (used for dispatch) already strips the query
                // string (Task 10 confirmed), so the plain literal above
                // matches regardless of `?dest=...` — read the param back off
                // the full URL here, same as `/api/share/zip`.
                const MAX_ZIP: usize = 50 * 1024 * 1024;
                if request.body_length().is_some_and(|l| l > MAX_ZIP) {
                    respond_status(request, 400);
                    continue;
                }
                let Some(dest) = resolve_dest(
                    query_param(request.url(), "dest").as_deref(),
                    &decks_dir,
                    &recent,
                ) else {
                    respond_status(request, 400);
                    continue;
                };
                // `body_length` can lie or be absent, so `read_capped` also
                // bounds the actual read, not just the declared length.
                let Some(bytes) = read_capped(request.as_reader(), MAX_ZIP) else {
                    respond_status(request, 400);
                    continue;
                };
                // `land_received`'s collision check is check-then-act; safe
                // only because this server loop is single-threaded — do not
                // introduce threads here (see `Receiving::poll`'s note).
                let landed = tempfile::tempdir().ok().and_then(|tmp| {
                    let zip_path = tmp.path().join("got.zip");
                    std::fs::write(&zip_path, &bytes).ok()?;
                    let scratch = tmp.path().join("out");
                    std::fs::create_dir_all(&scratch).ok()?;
                    share::unzip_to(&zip_path, &scratch).ok()?;
                    share::land_received(&scratch, &dest).ok()
                });
                match landed {
                    Some((landed, stripped)) => respond_json(
                        request,
                        &ReceiveDto {
                            phase: "done",
                            landed: Some(landed),
                            stripped,
                            elapsed: Some(0),
                            error: None,
                        },
                    ),
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/deselect") => {
                reviewing = None;
                walking = None;
                browsing = None;
                // Back at the picker: read the global store again (loose-deck
                // badges live there, not in any workspace's store).
                if let Ok(s) = assemble::store_for(&[], cfg.instance_store.as_deref()) {
                    store = s;
                }
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            (Method::Post, "/api/grade") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                match read_grade(&mut request) {
                    Some(grade) => {
                        let now = now_ms();
                        r.session.grade(&mut store, grade, now);
                        // Refresh the deck's per-depth badge earn dates from this
                        // session's cards (high-water first-earn marks; badges gate
                        // nothing). Keyed by deck subject, like the rest of the
                        // deck-level store (exam mastery, last depth).
                        if let Some(subject) = r.files.paths.keys().next() {
                            store::note_badges(&mut store, subject, r.session.cards(), now);
                        }
                        if let Err(e) = store.save() {
                            eprintln!("warning: could not save progress: {e}");
                        }
                        r.rotate_variant(); // a fresh phrasing for the next card
                        respond_json(request, &review_state(reviewing.as_ref(), &store));
                    }
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/skip") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.session.skip(&store, now_ms());
                r.rotate_variant(); // a fresh phrasing for the next card
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            (Method::Post, "/api/acquire") => {
                // Acknowledge a never-seen card: record it as acquired (no grade)
                // and move on. Its first quiz comes back ~1 min later, this session.
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.session.acquire_current(&mut store, now_ms());
                if let Err(e) = store.save() {
                    eprintln!("warning: could not save progress: {e}");
                }
                r.rotate_variant(); // a fresh phrasing for the next card
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            (Method::Post, "/api/check") => {
                let Some(r) = reviewing.as_ref() else {
                    respond_status(request, 409);
                    continue;
                };
                // Check the typed lines against the current card: pure evidence,
                // like choose (the learner-final grade is applied separately on
                // Continue via `/api/grade`). Orderedness derives from the card's
                // mode in core (TypeLine pairs line-by-position, everything else
                // matches any order); the client sends only its lines.
                #[derive(Deserialize)]
                struct Body {
                    lines: Vec<String>,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let result = body.and_then(|body| review::check_typed(&r.session, &body.lines));
                match result {
                    Some(f) => respond_json(request, &f),
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/choose") => {
                let Some(r) = reviewing.as_ref() else {
                    respond_status(request, 409);
                    continue;
                };
                // Just reports which option is correct: core `review::choose`
                // rebuilds the question from the same seed `review_state` served
                // it with, so the pick and the state can never diverge. The grade
                // is applied later via /api/grade on Continue, so the session
                // stays on this card during the result (Remove still works on it).
                let picked = read_index(&mut request)
                    .and_then(|chosen| review::choose(&r.session, &store, &r.augment, chosen));
                match picked {
                    Some(f) => respond_json(request, &f),
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/remove") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let dropped = r.session.remove_current(&store, now_ms());
                if let Some(first) = dropped.first() {
                    let subject = first.subject.to_string();
                    let line = first.line;
                    for card in &dropped {
                        store.remove(card.id());
                    }
                    let _ = store.save();
                    r.files.remove_block(&subject, line);
                }
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            // Promotes the current virtual (remediation) card into its deck
            // file (`store::promote_virtual` does the append-then-drop; the
            // schedule needs no transfer, since it already lives in
            // `store.cards` under the id the appended deck card hashes to, so
            // the promoted card keeps its earned schedule for free). A clean
            // 400 — never a panic — when the current card isn't virtual or
            // its deck file isn't known.
            (Method::Post, "/api/promote") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if !r.session.current_is_virtual(&store) {
                    respond_status(request, 400);
                    continue;
                }
                let Some(id) = r.session.current_id() else {
                    respond_status(request, 400);
                    continue;
                };
                let Some(subject) = r.session.current().map(|c| c.subject.to_string()) else {
                    respond_status(request, 400);
                    continue;
                };
                let Some(path) = r.files.paths.get(&subject).cloned() else {
                    respond_status(request, 400);
                    continue;
                };
                if store::promote_virtual(&mut store, id, &path).is_err() {
                    respond_status(request, 400);
                    continue;
                }
                r.session.poll(&store, now_ms());
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            (Method::Post, "/api/restart") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.session.restart(&store, now_ms());
                r.rotate_variant(); // a fresh phrasing for the new session's first card
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            // Ask Claude about the current card — runs the CLI on a background
            // thread (ask::spawn) and returns immediately; the page polls
            // `GET /api/ask` for the answer so the server loop never blocks.
            (Method::Post, "/api/ask") => {
                #[derive(Deserialize)]
                struct Body {
                    question: String,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let question = body.map(|b| b.question).filter(|q| !q.trim().is_empty());
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(q) = question {
                    r.start_ask(&ask_cfg, audience, AskAction::Question(q));
                }
                respond_json(request, &r.ask_dto(None, None));
            }
            // Condense the conversation into note lines appended to the deck.
            (Method::Post, "/api/ask/note") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.start_ask(&ask_cfg, audience, AskAction::Condense);
                respond_json(request, &r.ask_dto(None, None));
            }
            // Distill the conversation into one draft card, surfaced on the ask DTO.
            (Method::Post, "/api/ask/card/draft") => {
                if audience == Audience::Kids {
                    respond_status(request, 403);
                    continue;
                }
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                r.start_ask(&ask_cfg, audience, AskAction::DraftCard);
                respond_json(request, &r.ask_dto(None, None));
            }
            // Land an edited draft as a free-standing Tutor virtual card on the
            // current deck. Minting logic lives in `store::mint_tutor_card`; this
            // handler only reads the body, gathers session context (the current
            // card's deck subject and its authored ids, for dedup), and maps the
            // result to a status code.
            (Method::Post, "/api/ask/card/create") => {
                if audience == Audience::Kids {
                    respond_status(request, 403);
                    continue;
                }
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let Some(req) =
                    serde_json::from_reader::<_, CreateCardReq>(request.as_reader()).ok()
                else {
                    respond_status(request, 400);
                    continue;
                };
                let Some(card) = r.session.current() else {
                    respond_status(request, 409);
                    continue;
                };
                let subject = card.subject.to_string();
                let deck_ids: std::collections::HashSet<u64> =
                    r.session.cards().iter().map(|c| c.id()).collect();
                let now = now_ms();
                match store::mint_tutor_card(
                    &mut store, &subject, &req.front, &req.back, now, &deck_ids,
                ) {
                    Ok(id) => {
                        if let Err(e) = store.save() {
                            eprintln!("warning: could not save progress: {e}");
                        }
                        // No status-carrying JSON responder exists yet (only
                        // `respond_json`, always 200, and `respond_status`, no
                        // body): 200 here, not the 201 a "created" response
                        // would ideally carry. Documented as such in API.md.
                        respond_json(request, &CreateCardResp { id: id.to_string() });
                    }
                    Err(store::MintError::Duplicate | store::MintError::Malformed(_)) => {
                        respond_status(request, 422);
                    }
                }
            }
            // Poll for a pending reply; the page calls this every ~400ms while
            // `thinking`.
            (Method::Get, "/api/ask") => {
                let Some(r) = reviewing.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let (status, error) = r.poll_ask();
                respond_json(request, &r.ask_dto(status, error));
            }
            // ── AI exam ───────────────────────────────────────────────────
            // Start an exam for one `% source:` deck: validate the name and
            // drill state, then spawn question generation on a background
            // thread; the page polls `GET /api/exam`.
            (Method::Post, "/api/exam/start") => {
                #[derive(Deserialize)]
                struct Body {
                    deck: String,
                }
                let Some(body) = serde_json::from_reader::<_, Body>(request.as_reader()).ok()
                else {
                    respond_status(request, 400);
                    continue;
                };
                // Include workspace members (by their qualified `<ws>/<file>`
                // name) so an exam can be started on a deck inside a workspace,
                // not just a top-level deck — mirroring `/api/select`. Resolved
                // through the shared catalog lookup, so a bare name duplicated
                // across containers is rejected here too, instead of silently
                // writing mastery to whichever container's row won a last-wins
                // map (this endpoint gates progression, so ambiguity must 400,
                // not guess).
                let Some(path) = resolved_path(resolve_row(&body.deck, &decks_dir, &recent)) else {
                    respond_status(request, 400);
                    continue;
                };
                // The exam reads drill state and writes mastery/unlocks to the
                // deck's own store (a workspace's, or the global one).
                if let Ok(s) =
                    assemble::store_for(std::slice::from_ref(&path), cfg.instance_store.as_deref())
                {
                    store = s;
                }
                match Deck::load(&path) {
                    // Examable when it has an exam (a `% source:` fact deck, or a
                    // trace) and its `% requires:` are satisfied — drilled or not
                    // (you may test out early).
                    Ok(deck)
                        if deck.has_exam()
                            && !deck::is_locked(&deck, Some(decks_dir.as_path()), &store) =>
                    {
                        let strictness =
                            deck.settings.exam_strictness.unwrap_or(exam_cfg.strictness);
                        // A trace's exam is the graded compression (one fixed
                        // question), gated by the re-sit cooldown after a fail; a
                        // fact deck's exam generates questions from its source.
                        let sitting = if deck.is_trace() {
                            match trace::Trace::from_deck(&deck) {
                                Ok(t) => {
                                    if let Some(ms) = exam::cooldown_remaining_ms(
                                        &store,
                                        &deck.subject,
                                        exam_cfg.retry_cooldown_secs,
                                        now_ms(),
                                    ) {
                                        // One shape per endpoint: the cooldown is an
                                        // ExamDto in its own phase, not an untagged
                                        // {cooldown_ms} the client must key-sniff.
                                        respond_json(request, &cooldown_dto(&deck.subject, ms));
                                        continue;
                                    }
                                    exam::Sitting::start_trace(
                                        t.description.clone(),
                                        t.compression_rubric(),
                                        deck.subject.clone(),
                                        strictness,
                                        exam_cfg.clone(),
                                        ask_cfg.clone(),
                                    )
                                }
                                Err(_) => {
                                    respond_status(request, 409);
                                    continue;
                                }
                            }
                        } else {
                            // Fact-deck pre-flight: confirm the configured
                            // backend can reach every `% source:` before
                            // starting the sitting, so a capability gap is a
                            // clean refusal at launch, not an error surfaced
                            // mid-exam through the background job's poll.
                            if exam::ensure_backend_can_examine(&deck, &ask_cfg).is_err() {
                                respond_status(request, 409);
                                continue;
                            }
                            exam::Sitting::start(
                                &deck,
                                strictness,
                                exam_cfg.clone(),
                                ask_cfg.clone(),
                            )
                        };
                        let ex = Examining {
                            sitting,
                            deck_path: path,
                        };
                        let dto = exam_dto(&ex, &decks_dir);
                        examining = Some(ex);
                        respond_json(request, &dto);
                    }
                    _ => respond_status(request, 409),
                }
            }
            // Poll the exam: advance any finished background call, return state.
            (Method::Get, "/api/exam") => {
                let Some(ex) = examining.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                // A workspace member's exam remediation honors its own
                // `alix.local.toml` retirement cap, same as its review session.
                let parent = ex.deck_path.parent().unwrap_or_else(|| Path::new(""));
                let retire_after_days = review_cfg.for_workspace(parent).retire_after_days;
                ex.sitting.poll(&mut store, now_ms(), retire_after_days);
                respond_json(request, &exam_dto(ex, &decks_dir));
            }
            // Save the current answer and (optionally) navigate to another question.
            (Method::Post, "/api/exam/answer") => {
                #[derive(Deserialize)]
                struct Body {
                    text: String,
                    goto: Option<usize>,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(ex) = examining.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(b) = body {
                    ex.sitting.set_answer(b.text);
                    if let Some(i) = b.goto {
                        ex.sitting.goto(i);
                    }
                }
                respond_json(request, &exam_dto(ex, &decks_dir));
            }
            // Save the last answer and submit everything for grading.
            (Method::Post, "/api/exam/grade") => {
                #[derive(Deserialize)]
                struct Body {
                    text: String,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(ex) = examining.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(b) = body {
                    ex.sitting.set_answer(b.text);
                }
                ex.sitting.submit();
                respond_json(request, &exam_dto(ex, &decks_dir));
            }
            // On a fail, generate remediation cards into the store as virtual cards.
            (Method::Post, "/api/exam/remediate") => {
                let Some(ex) = examining.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                ex.sitting.remediate();
                respond_json(request, &exam_dto(ex, &decks_dir));
            }
            // Leave the exam, back to the deck list / summary.
            (Method::Post, "/api/exam/close") => {
                examining = None;
                if let Ok(s) = assemble::store_for(&[], cfg.instance_store.as_deref()) {
                    store = s;
                }
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            // ── Deck augmentation (the picker's "Augment" action, decks only) ──
            // Open the Augment screen and report what its cache holds. Resolves
            // the name through the catalog (incl. workspace members) like the
            // exam; a workspace name opens the screen over the UNION of its
            // members' cards, which also unlocks the icon target.
            (Method::Post, "/api/augment/open") => {
                #[derive(Deserialize)]
                struct Body {
                    deck: String,
                }
                let Some(body) = serde_json::from_reader::<_, Body>(request.as_reader()).ok()
                else {
                    respond_status(request, 400);
                    continue;
                };
                let (files, workspace_dir) = match resolve_row(&body.deck, &decks_dir, &recent) {
                    Resolved::One(p) => (vec![p], None),
                    Resolved::Many { dir, files } => (files, Some(dir)),
                    _ => {
                        respond_status(request, 400);
                        continue;
                    }
                };
                let name = body.deck;
                // The cache lives beside the selection's own store (a workspace's,
                // or the global one), mirroring how review reads it.
                if let Ok(s) = assemble::store_for(&files, cfg.instance_store.as_deref()) {
                    store = s;
                }
                // A plain deck is a one-member union; any member failing to load
                // fails the open, so a broken deck never half-opens the screen.
                let mut cards = Vec::new();
                let loaded = files
                    .iter()
                    .try_for_each(|f| Deck::load(f).map(|d| cards.extend(d.cards)).map(|_| ()));
                match loaded {
                    Ok(()) => {
                        let aug = Augmenting::open(
                            name,
                            cards,
                            augment::augment_path_for(store.path()),
                            workspace_dir,
                        );
                        let dto = aug.dto();
                        augmenting = Some(aug);
                        respond_json(request, &dto);
                    }
                    Err(_) => respond_status(request, 409),
                }
            }
            // Start fill-the-gaps generation for one target (a costed background
            // call); the page polls `GET /api/augment`.
            (Method::Post, "/api/augment/generate") => {
                #[derive(Deserialize)]
                struct TargetBody {
                    target: String,
                    with: Option<String>,
                }
                #[derive(Deserialize)]
                struct Body {
                    targets: Vec<TargetBody>,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(aug) = augmenting.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(b) = body {
                    let targets = b
                        .targets
                        .into_iter()
                        .map(|t| {
                            let guidance = t
                                .with
                                .map(|s| s.trim().to_string())
                                .filter(|s| !s.is_empty());
                            (t.target, guidance)
                        })
                        .collect();
                    aug.generate_batch(targets, &ai_cfg, &ask_cfg);
                }
                respond_json(request, &aug.dto());
            }
            // Poll the in-flight generation: apply a finished outcome, return state.
            (Method::Get, "/api/augment") => {
                let Some(aug) = augmenting.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                aug.poll(&ai_cfg, &ask_cfg);
                respond_json(request, &aug.dto());
            }
            // Remove a target's augmentations (or `all`) for this deck.
            (Method::Post, "/api/augment/remove") => {
                #[derive(Deserialize)]
                struct Body {
                    target: String,
                    topology: Option<String>,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let Some(aug) = augmenting.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(b) = body {
                    aug.remove(&b.target, b.topology.as_deref());
                }
                respond_json(request, &aug.dto());
            }
            // Leave the Augment screen, back to the picker (reset to the global store).
            (Method::Post, "/api/augment/close") => {
                augmenting = None;
                if let Ok(s) = assemble::store_for(&[], cfg.instance_store.as_deref()) {
                    store = s;
                }
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            // ── Trace walk (a single trace picked from the selection screen) ──
            // The web trace-walk flow (predict → reveal → grade), guarded on `walking`.
            (Method::Get, "/api/walk") => {
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                w.poll();
                respond_json(request, &walk_dto(w));
            }
            (Method::Post, "/api/walk/predict") => {
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                #[derive(Deserialize)]
                struct Body {
                    text: String,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                if let Some(b) = body {
                    w.walk.predict(b.text);
                    w.start_grade();
                }
                respond_json(request, &walk_dto(w));
            }
            (Method::Post, "/api/walk/grade") => {
                let self_delta = read_delta(&mut request);
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let delta = w.grade_result.as_ref().map(|(d, _)| *d).or(self_delta);
                match delta {
                    Some(delta) => {
                        w.walk.grade(&mut store, delta, now_ms());
                        if let Err(e) = store.save() {
                            eprintln!("warning: could not save progress: {e}");
                        }
                        w.clear_grade();
                        respond_json(request, &walk_dto(w));
                    }
                    None => respond_status(request, 400),
                }
            }
            (Method::Post, "/api/walk/restart") => {
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let fresh = Walk::new(w.walk.trace().clone());
                let grade = w.grade.take();
                *w = Walking::new(fresh, grade);
                respond_json(request, &walk_dto(w));
            }
            // Ask-Claude about the current checkpoint — the same tutor a review
            // uses (its subject is the checkpoint). Runs on a background thread;
            // the page polls `GET /api/walk/ask`.
            (Method::Post, "/api/walk/ask") => {
                #[derive(Deserialize)]
                struct Body {
                    question: String,
                }
                let body: Option<Body> = serde_json::from_reader(request.as_reader()).ok();
                let question = body.map(|b| b.question).filter(|q| !q.trim().is_empty());
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                if let Some(q) = question {
                    w.start_ask(&ask_cfg, audience, Some(q));
                }
                respond_json(request, &w.ask_dto(None, None));
            }
            // Condense the conversation into a `!` note on the checkpoint.
            (Method::Post, "/api/walk/ask/note") => {
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                w.start_ask(&ask_cfg, audience, None);
                respond_json(request, &w.ask_dto(None, None));
            }
            (Method::Get, "/api/walk/ask") => {
                let Some(w) = walking.as_mut() else {
                    respond_status(request, 409);
                    continue;
                };
                let (status, error) = w.poll_ask();
                respond_json(request, &w.ask_dto(status, error));
            }
            // Back to decks: abandon the walk and return to the picker (global store).
            (Method::Post, "/api/walk/leave") => {
                walking = None;
                if let Ok(s) = assemble::store_for(&[], cfg.instance_store.as_deref()) {
                    store = s;
                }
                // Every closer returns the picker StateDto — one teardown rule.
                respond_json(request, &review_state(reviewing.as_ref(), &store));
            }
            _ => respond_status(request, 404),
        }
    }
    Ok(())
}

/// Builds the decks-catalog payload `GET /api/decks` returns: first
/// re-resolving the served decks dir for an unscoped instance (a `decks_dir`
/// edit takes effect on the next reload/focus without a restart,
/// `{#page-reload-refetches-decks}`), then the catalog itself (review
/// enforces locking; the picker won't start a locked deck). Shared with any
/// mutation that wants the picker to re-render in one round trip instead of
/// a second `GET /api/decks` (e.g. `POST /api/workspace/deadline`).
fn decks_list_dto(
    scoped: bool,
    config_path: Option<&Path>,
    decks_dir: &mut PathBuf,
    recent: &RecentDecks,
    store: &Store,
    launcher_icons: &mut HashMap<String, PathBuf>,
    review_cfg: crate::config::ReviewConfig,
) -> DeckListDto {
    let dir = effective_decks_dir(scoped, config_path, decks_dir);
    if dir != *decks_dir {
        *decks_dir = dir;
    }
    deck_catalog(decks_dir, recent, store, true, launcher_icons, review_cfg)
}

#[cfg(test)]
mod contract;
#[cfg(test)]
mod tests;