trane 0.28.0

An automated system for learning complex skills
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
//! Defines the basic data structures used by Trane to describe courses, lessons, and exercises,
//! store the results of a student's attempt at mastering an exercise, the options avaialble to
//! control the behavior of the scheduler, among other things.

pub mod course_generator;
pub mod filter;

use anyhow::{Result, bail};
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
use ustr::Ustr;

use crate::data::course_generator::{
    knowledge_base::KnowledgeBaseConfig,
    literacy::{LiteracyConfig, LiteracyLessonType},
    music_piece::MusicPieceConfig,
    transcription::{TranscriptionConfig, TranscriptionLink, TranscriptionPreferences},
};

/// The score used by students to evaluate their mastery of a particular exercise after a trial.
/// More detailed descriptions of the levels are provided using the example of an exercise that
/// requires the student to learn a musical passage.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum MasteryScore {
    /// One signifies the student has barely any mastery of the exercise. For a musical passage,
    /// this level of mastery represents the initial attempts at hearing and reading the music, and
    /// figuring out the movements required to perform it.
    One,

    /// Two signifies the student has achieved some mastery of the exercise. For a musical passage,
    /// this level of mastery represents the stage at which the student knows the music, the
    /// required movements, and can perform the passage slowly with some mistakes.
    Two,

    /// Three signifies the student has achieved significant mastery of the exercise. For a musical
    /// passage, this level of mastery represents the stage at which the student can perform the
    /// material slowly with barely any mistakes, and has begun to learn it at higher tempos.
    Three,

    /// Four signifies the student has gained mastery of the exercise, requiring almost not
    /// conscious thought to complete it. For a musical passage, this level of mastery represents
    /// the stage at which the student can perform the material at the desired tempo with all
    /// elements (rhythm, dynamics, etc.) completely integrated into the performance.
    Four,

    /// Five signifies the student has gained total mastery of the material and can apply it in
    /// novel situations and come up with new variations. For exercises that test declarative
    /// knowledge or that do not easily lend themselves for variations (e.g., a question on some
    /// programming language's feature), the difference between the fourth and fifth level is just a
    /// matter of increased speed and accuracy. For a musical passage, this level of mastery
    /// represents the stage at which the student can perform the material without making mistakes.
    /// In addition, they can also play their own variations of the material by modifying the
    /// melody, harmony, dynamics, rhythm, etc., and do so effortlessly.
    Five,
}

impl MasteryScore {
    /// Assigns a float value to each of the values of `MasteryScore`.
    #[must_use]
    pub fn float_score(&self) -> f32 {
        match *self {
            Self::One => 1.0,
            Self::Two => 2.0,
            Self::Three => 3.0,
            Self::Four => 4.0,
            Self::Five => 5.0,
        }
    }
}

impl TryFrom<MasteryScore> for f32 {
    type Error = ();

    fn try_from(score: MasteryScore) -> Result<f32, ()> {
        Ok(score.float_score())
    }
}

impl TryFrom<f32> for MasteryScore {
    type Error = ();

    fn try_from(score: f32) -> Result<MasteryScore, ()> {
        if (score - 1.0_f32).abs() < f32::EPSILON {
            Ok(MasteryScore::One)
        } else if (score - 2.0_f32).abs() < f32::EPSILON {
            Ok(MasteryScore::Two)
        } else if (score - 3.0_f32).abs() < f32::EPSILON {
            Ok(MasteryScore::Three)
        } else if (score - 4.0_f32).abs() < f32::EPSILON {
            Ok(MasteryScore::Four)
        } else if (score - 5.0_f32).abs() < f32::EPSILON {
            Ok(MasteryScore::Five)
        } else {
            Err(())
        }
    }
}

//@<lp-example-4
/// The result of a single trial.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ExerciseTrial {
    /// The score assigned to the exercise after the trial.
    pub score: f32,

    /// The timestamp at which the trial happened.
    pub timestamp: i64,
}
//>@lp-example-4

/// The reward assigned to a single exercise. Rewards are used to adjust an exercise's score based
/// on performance of related exercises.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct UnitReward {
    /// The ID of the unit to which the reward is attached.
    pub unit_id: Ustr,

    /// The reward assigned to the exercise. The value can be negative, zero, or positive.
    pub value: f32,

    /// The weight assigned to the reward. Rewards from closer units are given more weight than
    /// those from distant units.
    pub weight: f32,

    /// The timestamp at which the reward was assigned.
    pub timestamp: i64,
}

/// The type of the units stored in the dependency graph.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum UnitType {
    /// A single task, which the student is meant to perform and assess.
    Exercise,

    /// A set of related exercises. There are no dependencies between the exercises in a single
    /// lesson, so students could see them in any order. Lessons themselves can depend on other
    /// lessons or courses. There is also an implicit dependency between a lesson and the course to
    /// which it belongs.
    Lesson,

    /// A set of related lessons around one or more similar topics. Courses can depend on other
    /// lessons or courses.
    Course,
}

impl std::fmt::Display for UnitType {
    /// Implements the [Display](std::fmt::Display) trait for [`UnitType`].
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Exercise => "Exercise".fmt(f),
            Self::Lesson => "Lesson".fmt(f),
            Self::Course => "Course".fmt(f),
        }
    }
}

/// Trait to convert relative paths to absolute paths so that objects stored in memory contain the
/// full path to all their assets.
pub trait NormalizePaths
where
    Self: Sized,
{
    /// Converts all relative paths in the object to absolute paths.
    fn normalize_paths(&self, working_dir: &Path) -> Result<Self>;
}

/// Converts a relative to an absolute path given a path and a working directory.
fn normalize_path(working_dir: &Path, path_str: &str) -> Result<String> {
    let path = Path::new(path_str);
    if path.is_absolute() {
        return Ok(path_str.to_string());
    }

    Ok(working_dir
        .join(path)
        .canonicalize()?
        .to_str()
        .unwrap_or(path_str)
        .to_string())
}

/// Trait to verify that the paths in the object are valid.
pub trait VerifyPaths
where
    Self: Sized,
{
    /// Checks that all the paths mentioned in the object exist in disk.
    fn verify_paths(&self, working_dir: &Path) -> Result<bool>;
}

/// Trait to get the metadata from a lesson or course manifest.
pub trait GetMetadata {
    /// Returns the manifest's metadata.
    fn get_metadata(&self) -> Option<&BTreeMap<String, Vec<String>>>;
}

/// Trait to get the unit type from a manifest.
pub trait GetUnitType {
    /// Returns the type of the unit associated with the manifest.
    fn get_unit_type(&self) -> UnitType;
}

/// An asset attached to a unit, which could be used to store instructions, or present the material
/// introduced by a course or lesson.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum BasicAsset {
    /// An asset containing the path to a markdown file.
    MarkdownAsset {
        /// The path to the markdown file.
        path: String,
    },

    /// An asset containing its content as a string.
    InlinedAsset {
        /// The content of the asset.
        content: String,
    },

    /// An asset containing its content as a unique string. Useful for generating assets that are
    /// replicated across many units.
    InlinedUniqueAsset {
        /// The content of the asset.
        content: Ustr,
    },
}

impl NormalizePaths for BasicAsset {
    fn normalize_paths(&self, working_dir: &Path) -> Result<Self> {
        match &self {
            BasicAsset::InlinedAsset { .. } | BasicAsset::InlinedUniqueAsset { .. } => {
                Ok(self.clone()) // grcov-excl-line
            }
            BasicAsset::MarkdownAsset { path } => {
                let abs_path = normalize_path(working_dir, path)?;
                Ok(BasicAsset::MarkdownAsset { path: abs_path })
            }
        }
    }
}

impl VerifyPaths for BasicAsset {
    fn verify_paths(&self, working_dir: &Path) -> Result<bool> {
        match &self {
            BasicAsset::InlinedAsset { .. } | BasicAsset::InlinedUniqueAsset { .. } => Ok(true),
            BasicAsset::MarkdownAsset { path } => {
                let abs_path = working_dir.join(Path::new(path));
                Ok(abs_path.exists())
            }
        }
    }
}

//@<course-generator
/// A configuration used for generating special types of courses on the fly.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum CourseGenerator {
    /// The configuration for generating a knowledge base course. Currently, there are no
    /// configuration options, but the struct was added to implement the [GenerateManifests] trait
    /// and for future extensibility.
    KnowledgeBase(KnowledgeBaseConfig),

    /// The configuration for generating a literacy course.
    Literacy(LiteracyConfig),

    /// The configuration for generating a music piece course.
    MusicPiece(MusicPieceConfig),

    /// The configuration for generating a transcription course.
    Transcription(TranscriptionConfig),
}
//>@course-generator

/// A struct holding the results from running a course generator.
#[derive(Debug, PartialEq)]
pub struct GeneratedCourse {
    /// The lessons and exercise manifests generated for the course.
    pub lessons: Vec<(LessonManifest, Vec<ExerciseManifest>)>,

    /// Updated course metadata. If None, the existing metadata is used.
    pub updated_metadata: Option<BTreeMap<String, Vec<String>>>,

    /// Updated course instructions. If None, the existing instructions are used.
    pub updated_instructions: Option<BasicAsset>,
}

/// The trait to return all the generated lesson and exercise manifests for a course.
pub trait GenerateManifests {
    /// Returns all the generated lesson and exercise manifests for a course.
    fn generate_manifests(
        &self,
        course_root: &Path,
        course_manifest: &CourseManifest,
        preferences: &UserPreferences,
    ) -> Result<GeneratedCourse>;
}

impl GenerateManifests for CourseGenerator {
    fn generate_manifests(
        &self,
        course_root: &Path,
        course_manifest: &CourseManifest,
        preferences: &UserPreferences,
    ) -> Result<GeneratedCourse> {
        match self {
            CourseGenerator::KnowledgeBase(config) => {
                config.generate_manifests(course_root, course_manifest, preferences)
            }
            CourseGenerator::Literacy(config) => {
                config.generate_manifests(course_root, course_manifest, preferences)
            }
            CourseGenerator::MusicPiece(config) => {
                config.generate_manifests(course_root, course_manifest, preferences)
            }
            CourseGenerator::Transcription(config) => {
                config.generate_manifests(course_root, course_manifest, preferences)
            }
        }
    }
}

/// The type of knowledge tested by an exercise.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub enum ExerciseType {
    /// Represents an exercise that tests mastery of factual knowledge. For example, an exercise
    /// asking students to name the notes in a D Major chord.
    Declarative,

    /// Represents an exercises that requires more complex actions to be performed. For example, an
    /// exercise asking students to play a D Major chords in a piano.
    #[default]
    Procedural,
}

/// A manifest describing the contents of a course.
#[derive(Builder, Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CourseManifest {
    /// The ID assigned to this course.
    ///
    /// For example, `music::instrument::guitar::basic_jazz_chords`.
    #[builder(setter(into))]
    pub id: Ustr,

    /// The name of the course to be presented to the user.
    ///
    /// For example, "Basic Jazz Chords on Guitar".
    #[builder(default)]
    #[serde(default)]
    pub name: String,

    /// The IDs of all dependencies of this course.
    #[builder(default)]
    #[serde(default)]
    pub dependencies: Vec<Ustr>,

    /// The IDs of the courses or lessons encompassed by this course expressed as a tuple (ID,
    ///weight). By default, all dependencies are encompassed with a weight of 1.0. Adding an entry
    /// to this list is only needed when:
    ///
    /// - A course or lesson that is not a dependency of this course is encompassed by it.
    /// - A dependency relationship does not always imply an encompassing one. In that case, such
    ///   dependencies should be added to this list with a weight of 0.0.
    ///  
    /// See the documentation of the [`graph`](crate::graph) and [`scheduler`](crate::scheduler)
    /// modules for a full explanation of this concept and how it is used to reduce reviews of
    /// exercises that are covered by those in other units.
    #[builder(default)]
    #[serde(default)]
    pub encompassed: Vec<(Ustr, f32)>,

    /// The IDs of the courses or lessons superseded by this course. If this course is mastered,
    /// then exercises from the superseded courses or lessons will no longer be shown to the
    /// student.
    #[builder(default)]
    #[serde(default)]
    pub superseded: Vec<Ustr>,

    /// An optional description of the course.
    #[builder(default)]
    #[serde(default)]
    pub description: Option<String>,

    /// An optional list of the course's authors.
    #[builder(default)]
    #[serde(default)]
    pub authors: Option<Vec<String>>,

    //@<lp-example-5
    //// A mapping of String keys to a list of String values. For example, ("genre", ["jazz"]) could
    /// be attached to a course named "Basic Jazz Chords on Guitar".
    ///
    /// The purpose of this metadata is to allow students to focus on more specific material during
    /// a study session which does not belong to a single lesson or course. For example, a student
    /// might want to only focus on guitar scales or ear training.
    #[builder(default)]
    #[serde(default)]
    pub metadata: Option<BTreeMap<String, Vec<String>>>,

    //>@lp-example-5
    /// An optional asset, which presents the material covered in the course.
    #[builder(default)]
    #[serde(default)]
    pub course_material: Option<BasicAsset>,

    /// An optional asset, which presents instructions common to all exercises in the course.
    #[builder(default)]
    #[serde(default)]
    pub course_instructions: Option<BasicAsset>,

    /// An optional configuration to generate material for this course. Generated courses allow
    /// easier creation of courses for specific purposes without requiring the manual creation of
    /// all the files a normal course would need.
    #[builder(default)]
    #[serde(default)]
    pub generator_config: Option<CourseGenerator>,
}

impl NormalizePaths for CourseManifest {
    fn normalize_paths(&self, working_directory: &Path) -> Result<Self> {
        let mut clone = self.clone();
        match &self.course_instructions {
            None => (),
            Some(asset) => {
                clone.course_instructions = Some(asset.normalize_paths(working_directory)?);
            }
        }
        match &self.course_material {
            None => (),
            Some(asset) => clone.course_material = Some(asset.normalize_paths(working_directory)?),
        }
        Ok(clone)
    }
}

impl VerifyPaths for CourseManifest {
    fn verify_paths(&self, working_dir: &Path) -> Result<bool> {
        // The paths mentioned in the instructions and material must both exist.
        let instructions_exist = match &self.course_instructions {
            None => true,
            Some(asset) => asset.verify_paths(working_dir)?,
        };
        let material_exists = match &self.course_material {
            None => true,
            Some(asset) => asset.verify_paths(working_dir)?,
        };
        Ok(instructions_exist && material_exists)
    }
}

impl GetMetadata for CourseManifest {
    fn get_metadata(&self) -> Option<&BTreeMap<String, Vec<String>>> {
        self.metadata.as_ref()
    }
}

impl GetUnitType for CourseManifest {
    fn get_unit_type(&self) -> UnitType {
        UnitType::Course
    }
}

/// A manifest describing the contents of a lesson.
#[derive(Builder, Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct LessonManifest {
    /// The ID assigned to this lesson.
    ///
    /// For example, `music::instrument::guitar::basic_jazz_chords::major_chords`.
    #[builder(setter(into))]
    pub id: Ustr,

    /// The IDs of all dependencies of this lesson.
    #[builder(default)]
    #[serde(default)]
    pub dependencies: Vec<Ustr>,

    /// The IDs of the courses or lessons encompassed by this lesson expressed as a tuple (ID,
    /// weight). By default, all dependencies are encompassed with a weight of 1.0. Adding an entry
    /// to this list is only needed when:
    ///
    /// - A course or lesson that is not a dependency of this lesson is encompassed by it.
    /// - A dependency relationship does not always imply an encompassing one. In that case, such
    ///   dependencies should be added to this list with a weight of 0.0.
    ///  
    /// See the documentation of the [`graph`](crate::graph) and [`scheduler`](crate::scheduler)
    /// modules for a full explanation of this concept and how it is used to reduce reviews of
    /// exercises that are covered by those in other units.
    #[builder(default)]
    #[serde(default)]
    pub encompassed: Vec<(Ustr, f32)>,

    ///The IDs of the courses or lessons superseded by this lesson. If this lesson is mastered, then
    /// exercises from the superseded courses or lessons will no longer be shown to the student.
    #[builder(default)]
    #[serde(default)]
    pub superseded: Vec<Ustr>,

    /// The ID of the course to which the lesson belongs.
    #[builder(setter(into))]
    pub course_id: Ustr,

    /// The name of the lesson to be presented to the user.
    ///
    /// For example, "Basic Jazz Major Chords".
    #[builder(default)]
    #[serde(default)]
    pub name: String,

    /// An optional description of the lesson.
    #[builder(default)]
    #[serde(default)]
    pub description: Option<String>,

    //// A mapping of String keys to a list of String values. For example, ("key", ["C"]) could
    /// be attached to a lesson named "C Major Scale". The purpose is the same as the metadata
    /// stored in the course manifest but allows finer control over which lessons are selected.
    #[builder(default)]
    #[serde(default)]
    pub metadata: Option<BTreeMap<String, Vec<String>>>,

    /// An optional asset, which presents the material covered in the lesson.
    #[builder(default)]
    #[serde(default)]
    pub lesson_material: Option<BasicAsset>,

    /// An optional asset, which presents instructions common to all exercises in the lesson.
    #[builder(default)]
    #[serde(default)]
    pub lesson_instructions: Option<BasicAsset>,
}

impl NormalizePaths for LessonManifest {
    fn normalize_paths(&self, working_dir: &Path) -> Result<Self> {
        let mut clone = self.clone();
        if let Some(asset) = &self.lesson_instructions {
            clone.lesson_instructions = Some(asset.normalize_paths(working_dir)?);
        }
        if let Some(asset) = &self.lesson_material {
            clone.lesson_material = Some(asset.normalize_paths(working_dir)?);
        }
        Ok(clone)
    }
}

impl VerifyPaths for LessonManifest {
    fn verify_paths(&self, working_dir: &Path) -> Result<bool> {
        // The paths mentioned in the instructions and material must both exist.
        let instruction_exists = match &self.lesson_instructions {
            None => true,
            Some(asset) => asset.verify_paths(working_dir)?,
        };
        let material_exists = match &self.lesson_material {
            None => true,
            Some(asset) => asset.verify_paths(working_dir)?,
        };
        Ok(instruction_exists && material_exists)
    }
}

impl GetMetadata for LessonManifest {
    fn get_metadata(&self) -> Option<&BTreeMap<String, Vec<String>>> {
        self.metadata.as_ref()
    }
}

impl GetUnitType for LessonManifest {
    fn get_unit_type(&self) -> UnitType {
        UnitType::Lesson
    }
}

/// The asset storing the material of a particular exercise.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum ExerciseAsset {
    /// A basic asset storing the material of the exercise.
    BasicAsset(BasicAsset),

    /// An asset representing a flashcard with a front and back each stored in a markdown file.
    FlashcardAsset {
        /// The path to the file containing the front of the flashcard.
        front_path: String,

        /// The path to the file containing the back of the flashcard. This path is optional,
        /// because a flashcard is not required to provide an answer. For example, the exercise is
        /// open-ended, or it is referring to an external resource which contains the exercise and
        /// possibly the answer.
        #[serde(default)]
        back_path: Option<String>,
    },

    /// An asset representing a flashcard with a front and back with the content of both stored as
    /// strings.
    InlineFlashcardAsset {
        /// The content of the front of the flashcard.
        front_content: String,

        /// The content of the back of the flashcard. This field is optional, because a flashcard
        /// is not required to provide an answer. For example, the exercise is open-ended, or it is
        /// referring to an external resource which contains the exercise and possibly the answer.
        #[serde(default)]
        back_content: Option<String>,
    },

    /// An asset representing a literacy exercise.
    LiteracyAsset {
        /// The type of the lesson.
        lesson_type: LiteracyLessonType,

        /// The examples to use in the lesson's exercise.
        #[serde(default)]
        examples: Vec<String>,

        /// The exceptions to the examples to use in the lesson's exercise.
        #[serde(default)]
        exceptions: Vec<String>,
    },

    /// An asset which stores a link to a SoundSlice.
    SoundSliceAsset {
        /// The link to the SoundSlice asset.
        link: String,

        /// An optional description of the exercise tied to this asset. For example, "Play this
        /// slice in the key of D Major" or "Practice measures 1 through 4". A missing description
        /// implies the entire slice should be practiced as is.
        #[serde(default)]
        description: Option<String>,

        /// An optional path to a MusicXML file containing the sheet music for the exercise.
        #[serde(default)]
        backup: Option<String>,
    },

    /// A transcription asset, containing an exercise's content and an optional external link to the
    /// audio for the exercise.
    TranscriptionAsset {
        /// The content of the exercise.
        #[serde(default)]
        content: String,

        /// An optional link to the audio for the exercise.
        #[serde(default)]
        external_link: Option<TranscriptionLink>,
    },
}

impl NormalizePaths for ExerciseAsset {
    fn normalize_paths(&self, working_dir: &Path) -> Result<Self> {
        match &self {
            // grcov-excl-start
            ExerciseAsset::BasicAsset(asset) => Ok(ExerciseAsset::BasicAsset(
                asset.normalize_paths(working_dir)?,
            )),
            // grcov-excl-stop
            ExerciseAsset::FlashcardAsset {
                front_path,
                back_path,
            } => {
                let abs_front_path = normalize_path(working_dir, front_path)?;
                let abs_back_path = if let Some(back_path) = back_path {
                    Some(normalize_path(working_dir, back_path)?)
                } else {
                    None // grcov-excl-line
                };
                Ok(ExerciseAsset::FlashcardAsset {
                    front_path: abs_front_path,
                    back_path: abs_back_path,
                })
            }
            ExerciseAsset::InlineFlashcardAsset { .. } => Ok(self.clone()), // grcov-excl-line
            ExerciseAsset::LiteracyAsset { .. } | ExerciseAsset::TranscriptionAsset { .. } => {
                Ok(self.clone()) // grcov-excl-line
            }
            ExerciseAsset::SoundSliceAsset {
                link,
                description,
                backup,
            } => match backup {
                None => Ok(self.clone()),
                Some(path) => {
                    let abs_path = normalize_path(working_dir, path)?;
                    Ok(ExerciseAsset::SoundSliceAsset {
                        link: link.clone(),
                        description: description.clone(),
                        backup: Some(abs_path),
                    })
                }
            },
        }
    }
}

impl VerifyPaths for ExerciseAsset {
    fn verify_paths(&self, working_dir: &Path) -> Result<bool> {
        match &self {
            ExerciseAsset::BasicAsset(asset) => asset.verify_paths(working_dir),
            ExerciseAsset::FlashcardAsset {
                front_path,
                back_path,
            } => {
                let front_abs_path = working_dir.join(Path::new(front_path));
                if let Some(back_path) = back_path {
                    // The paths to the front and back of the flashcard must both exist.
                    let back_abs_path = working_dir.join(Path::new(back_path));
                    Ok(front_abs_path.exists() && back_abs_path.exists())
                } else {
                    // If the back of the flashcard is missing, then the front must exist.
                    Ok(front_abs_path.exists())
                }
            }
            ExerciseAsset::InlineFlashcardAsset { .. } => Ok(true),
            ExerciseAsset::LiteracyAsset { .. } | ExerciseAsset::TranscriptionAsset { .. } => {
                Ok(true)
            }
            ExerciseAsset::SoundSliceAsset { backup, .. } => match backup {
                None => Ok(true),
                Some(path) => {
                    // The backup path must exist.
                    let abs_path = working_dir.join(Path::new(path));
                    Ok(abs_path.exists())
                }
            },
        }
    }
}

/// Manifest describing a single exercise.
#[derive(Builder, Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ExerciseManifest {
    /// The ID assigned to this exercise.
    ///
    /// For example, `music::instrument::guitar::basic_jazz_chords::major_chords::exercise_1`.
    #[builder(setter(into))]
    pub id: Ustr,

    /// The ID of the lesson to which this exercise belongs.
    #[builder(setter(into))]
    pub lesson_id: Ustr,

    /// The ID of the course to which this exercise belongs.
    #[builder(setter(into))]
    pub course_id: Ustr,

    /// The name of the exercise to be presented to the user.
    ///
    /// For example, "Exercise 1".
    #[builder(default)]
    #[serde(default)]
    pub name: String,

    /// An optional description of the exercise.
    #[builder(default)]
    #[serde(default)]
    pub description: Option<String>,

    /// The type of knowledge the exercise tests.
    #[builder(default)]
    #[serde(default)]
    pub exercise_type: ExerciseType,

    /// The asset containing the exercise itself.
    pub exercise_asset: ExerciseAsset,
}

impl NormalizePaths for ExerciseManifest {
    fn normalize_paths(&self, working_dir: &Path) -> Result<Self> {
        let mut clone = self.clone();
        clone.exercise_asset = clone.exercise_asset.normalize_paths(working_dir)?;
        Ok(clone)
    }
}

impl VerifyPaths for ExerciseManifest {
    fn verify_paths(&self, working_dir: &Path) -> Result<bool> {
        self.exercise_asset.verify_paths(working_dir)
    }
}

impl GetUnitType for ExerciseManifest {
    fn get_unit_type(&self) -> UnitType {
        UnitType::Exercise
    }
}

/// The score at which fractional selection reaches 100% of lesson candidates.
pub const FULL_CANDIDATES_SCORE: f32 = 4.0;

/// Options to control the passing score. Instead of a binary decision of whether a unit should
/// block its dependents, Trane allows a more gradual transition so that a single unit without very
/// high scores does not block progress along a path.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PassingScoreOptions {
    /// Instead of adding all the exercises of a passing score, the scheduler adds this fraction
    /// of the exercises when the score of a unit is exactly passing_score and gradually ramps up
    /// to adding all the exercises as the score increases.
    pub min_fraction: f32,

    /// The minimum score of a unit required to move on to the unit's dependents. Because of the
    /// gradual transition achieved by min_fraction, this score can be made lower than it would be
    /// otherwise.
    pub min_score: f32,

    /// The minimum average number of trials per exercise required to move on to the unit's
    /// dependents. Prevents moving on from this lesson too early without sufficient evidence of
    /// mastery.
    pub min_avg_trials: f32,
}

impl Default for PassingScoreOptions {
    fn default() -> Self {
        PassingScoreOptions {
            min_score: 3.0,
            min_fraction: 0.5,
            min_avg_trials: 1.8,
        }
    }
}

impl PassingScoreOptions {
    /// Verifies that the options are valid.
    pub fn verify(&self) -> Result<()> {
        if self.min_score < 0.0 || self.min_score >= FULL_CANDIDATES_SCORE {
            bail!("invalid minimum score: {}", self.min_score);
        }

        if self.min_fraction < 0.0 || self.min_fraction > 1.0 {
            bail!("invalid minimum fraction: {}", self.min_fraction);
        }

        if self.min_avg_trials < 1.0 {
            bail!("invalid minimum average trials: {}", self.min_avg_trials);
        }
        Ok(())
    }
}

/// A mastery window consists a range of scores and the percentage of the total exercises in the
/// batch returned by the scheduler that will fall within that range.
///
/// Mastery windows are used by the scheduler to control the amount of exercises for a given range
/// of difficulty given to the student to try to keep an optimal balance. For example, exercises
/// that are already fully mastered should not be shown very often lest the student becomes bored.
/// Very difficult exercises should not be shown too often either lest the student becomes
/// frustrated.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct MasteryWindow {
    /// The percentage of the exercises in each batch returned by the scheduler whose scores should
    /// fall within this window. Percentages might be adjusted by the scheduler based on the success
    /// rate of the exercises shown to the student, but this value provides the target.
    pub percentage: f32,

    /// The range of scores which fall on this window. Scores whose values are in the range
    /// `[range.0, range.1)` fall within this window. If `range.1` is equal to 5.0 (the float
    /// representation of the maximum possible score), then the range becomes inclusive.
    pub range: (f32, f32),
}

impl MasteryWindow {
    /// Returns whether the given score falls within this window.
    #[must_use]
    pub fn in_window(&self, score: f32) -> bool {
        // Handle the special case of the window containing the maximum score. Scores greater than
        // 5.0 are allowed because float comparison is not exact.
        if self.range.1 >= 5.0 && score >= 5.0 {
            return true;
        }

        // Return true if the score falls within the range `[range.0, range.1)`.
        self.range.0 <= score && score < self.range.1
    }
}

/// Options to control how the scheduler selects exercises.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct SchedulerOptions {
    /// The maximum number of candidates to return each time the scheduler is called.
    pub batch_size: usize,

    /// The number of recently failed exercises to re-schedule as a fraction of the batch size.
    pub relearn_fraction: f32,

    /// The options of the new mastery window. That is, the window of exercises that have not
    /// received a score so far.
    pub new_window_opts: MasteryWindow,

    /// The options of the target mastery window. That is, the window of exercises that lie outside
    /// the user's current abilities.
    pub target_window_opts: MasteryWindow,

    /// The options of the current mastery window. That is, the window of exercises that lie
    /// slightly outside the user's current abilities.
    pub current_window_opts: MasteryWindow,

    /// The options of the easy mastery window. That is, the window of exercises that lie well
    /// within the user's current abilities.
    pub easy_window_opts: MasteryWindow,

    /// The options for the mastered mastery window. That is, the window of exercises that the user
    /// has properly mastered.
    pub mastered_window_opts: MasteryWindow,

    /// The options to control how the scheduler decides when to move on to the dependents of a
    /// unit.
    pub passing_score: PassingScoreOptions,

    /// The minimum score required to supersede a unit. If unit A is superseded by B, then the
    /// exercises from unit A will not be shown once the score of unit B is greater than or equal to
    /// this value.
    pub superseding_score: f32,

    /// The number of trials to retrieve from the practice stats to compute an exercise's score.
    pub num_trials: u32,

    /// The number of rewards to retrieve from the practice rewards to compute a unit's reward.
    pub num_rewards: u32,

    /// The maximum number of lessons in progress to include in a batch. A lesson is in progress if
    /// it's not been seen before or its score is below the target window's range. The limit
    /// prevents the student from splitting attention between too many new or difficult lessons.
    pub max_lessons_in_progress: usize,
}

impl SchedulerOptions {
    #[must_use]
    fn float_equals(f1: f32, f2: f32) -> bool {
        (f1 - f2).abs() < f32::EPSILON
    }

    /// Verifies that the scheduler options are valid.
    pub fn verify(&self) -> Result<()> {
        // The batch size must be greater than 0, the relearn fraction must be between 0.0 and 1.0,
        // and the passing options must be valid.
        if self.batch_size == 0 {
            bail!("invalid scheduler options: batch_size must be greater than 0");
        }
        if self.relearn_fraction < 0.0 || self.relearn_fraction > 1.0 {
            bail!("invalid scheduler options: relearn_fraction must be between 0.0 and 1.0");
        }
        self.passing_score.verify()?;

        // The sum of the percentages of the mastery windows must be 1.0.
        if !Self::float_equals(
            self.mastered_window_opts.percentage
                + self.easy_window_opts.percentage
                + self.current_window_opts.percentage
                + self.target_window_opts.percentage
                + self.new_window_opts.percentage,
            1.0,
        ) {
            bail!(
                "invalid scheduler options: the sum of the percentages of the mastery windows \
                must be 1.0"
            );
        }

        // The new window's range must start at 0.0.
        if !Self::float_equals(self.new_window_opts.range.0, 0.0) {
            bail!("invalid scheduler options: the new window's range must start at 0.0");
        }

        // The mastered window's range must end at 5.0.
        if !Self::float_equals(self.mastered_window_opts.range.1, 5.0) {
            bail!("invalid scheduler options: the mastered window's range must end at 5.0");
        }

        // There must be no gaps in the mastery windows.
        if !Self::float_equals(
            self.new_window_opts.range.1,
            self.target_window_opts.range.0,
        ) || !Self::float_equals(
            self.target_window_opts.range.1,
            self.current_window_opts.range.0,
        ) || !Self::float_equals(
            self.current_window_opts.range.1,
            self.easy_window_opts.range.0,
        ) || !Self::float_equals(
            self.easy_window_opts.range.1,
            self.mastered_window_opts.range.0,
        ) {
            bail!("invalid scheduler options: there must be no gaps in the mastery windows");
        }

        // The maximum number of lessons in progress must be at least 1.
        if self.max_lessons_in_progress == 0 {
            bail!("invalid scheduler options: max_lessons_in_progress must be greater than 0");
        }

        Ok(())
    }
}

impl Default for SchedulerOptions {
    /// Returns the default scheduler options.
    fn default() -> Self {
        // Consider an exercise to be new if its score is less than 0.1. In reality, all such
        // exercises will have a score of 0.0, but we add a small margin to make this window act
        // like all the others.
        SchedulerOptions {
            batch_size: 50,
            relearn_fraction: 0.1,
            new_window_opts: MasteryWindow {
                percentage: 0.2,
                range: (0.0, 0.1),
            },
            target_window_opts: MasteryWindow {
                percentage: 0.2,
                range: (0.1, 2.5),
            },
            current_window_opts: MasteryWindow {
                percentage: 0.3,
                range: (2.5, 3.75),
            },
            easy_window_opts: MasteryWindow {
                percentage: 0.2,
                range: (3.75, 4.5),
            },
            mastered_window_opts: MasteryWindow {
                percentage: 0.1,
                range: (4.5, 5.0),
            },
            passing_score: PassingScoreOptions::default(),
            superseding_score: 4.0,
            num_trials: 15,
            num_rewards: 10,
            max_lessons_in_progress: 10,
        }
    }
}

/// Represents the scheduler's options that can be customized by the user.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct SchedulerPreferences {
    /// The maximum number of candidates to return each time the scheduler is called.
    #[serde(default)]
    pub batch_size: Option<usize>,
}

/// Represents a repository containing Trane courses.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct RepositoryMetadata {
    /// The ID of the repository, which is also used to name the directory.
    pub id: String,

    /// The URL of the repository.
    pub url: String,
}

//@<user-preferences
/// The user-specific configuration
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct UserPreferences {
    /// The preferences for generating transcription courses.
    #[serde(default)]
    pub transcription: Option<TranscriptionPreferences>,

    /// The preferences for customizing the behavior of the scheduler.
    #[serde(default)]
    pub scheduler: Option<SchedulerPreferences>,

    /// The paths to ignore when opening the course library. The paths are relative to the
    /// repository root. All child paths are also ignored. For example, adding the directory
    /// "foo/bar" will ignore any courses in "foo/bar" or any of its subdirectories.
    #[serde(default)]
    pub ignored_paths: Vec<String>,
}
//>@user-preferences

#[cfg(test)]
#[cfg_attr(coverage, coverage(off))]
mod test {
    use crate::data::*;

    // Verifies the conversion of mastery scores to float values.
    #[test]
    fn score_to_float() {
        assert_eq!(1.0, MasteryScore::One.float_score());
        assert_eq!(2.0, MasteryScore::Two.float_score());
        assert_eq!(3.0, MasteryScore::Three.float_score());
        assert_eq!(4.0, MasteryScore::Four.float_score());
        assert_eq!(5.0, MasteryScore::Five.float_score());

        assert_eq!(1.0, f32::try_from(MasteryScore::One).unwrap());
        assert_eq!(2.0, f32::try_from(MasteryScore::Two).unwrap());
        assert_eq!(3.0, f32::try_from(MasteryScore::Three).unwrap());
        assert_eq!(4.0, f32::try_from(MasteryScore::Four).unwrap());
        assert_eq!(5.0, f32::try_from(MasteryScore::Five).unwrap());
    }

    /// Verifies the conversion of floats to mastery scores.
    #[test]
    fn float_to_score() {
        assert_eq!(MasteryScore::One, MasteryScore::try_from(1.0).unwrap());
        assert_eq!(MasteryScore::Two, MasteryScore::try_from(2.0).unwrap());
        assert_eq!(MasteryScore::Three, MasteryScore::try_from(3.0).unwrap());
        assert_eq!(MasteryScore::Four, MasteryScore::try_from(4.0).unwrap());
        assert_eq!(MasteryScore::Five, MasteryScore::try_from(5.0).unwrap());
        assert!(MasteryScore::try_from(-1.0).is_err());
        assert!(MasteryScore::try_from(0.0).is_err());
        assert!(MasteryScore::try_from(3.5).is_err());
        assert!(MasteryScore::try_from(5.1).is_err());
    }

    /// Verifies that each type of manifest returns the correct unit type.
    #[test]
    fn get_unit_type() {
        assert_eq!(
            UnitType::Course,
            CourseManifestBuilder::default()
                .id("test")
                .name("Test".to_string())
                .dependencies(vec![])
                .build()
                .unwrap()
                .get_unit_type()
        );
        assert_eq!(
            UnitType::Lesson,
            LessonManifestBuilder::default()
                .id("test")
                .course_id("test")
                .name("Test".to_string())
                .dependencies(vec![])
                .build()
                .unwrap()
                .get_unit_type()
        );
        assert_eq!(
            UnitType::Exercise,
            ExerciseManifestBuilder::default()
                .id("test")
                .course_id("test")
                .lesson_id("test")
                .name("Test".to_string())
                .exercise_type(ExerciseType::Procedural)
                .exercise_asset(ExerciseAsset::FlashcardAsset {
                    front_path: "front.png".to_string(),
                    back_path: Some("back.png".to_string()),
                })
                .build()
                .unwrap()
                .get_unit_type()
        );
    }

    /// Verifies the `NormalizePaths` trait works for a `SoundSlice` asset.
    #[test]
    fn soundslice_normalize_paths() -> Result<()> {
        let soundslice = ExerciseAsset::SoundSliceAsset {
            link: "https://www.soundslice.com/slices/QfZcc/".to_string(),
            description: Some("Test".to_string()),
            backup: None,
        };
        soundslice.normalize_paths(Path::new("./"))?;

        let temp_dir = tempfile::tempdir()?;
        let temp_file = tempfile::NamedTempFile::new_in(temp_dir.path())?;
        let soundslice = ExerciseAsset::SoundSliceAsset {
            link: "https://www.soundslice.com/slices/QfZcc/".to_string(),
            description: Some("Test".to_string()),
            backup: Some(temp_file.path().as_os_str().to_str().unwrap().to_string()),
        };
        soundslice.normalize_paths(temp_dir.path())?;
        Ok(())
    }

    /// Tests that the `VerifyPaths` trait works for a `SoundSlice` asset.
    #[test]
    fn soundslice_verify_paths() -> Result<()> {
        let soundslice = ExerciseAsset::SoundSliceAsset {
            link: "https://www.soundslice.com/slices/QfZcc/".to_string(),
            description: Some("Test".to_string()),
            backup: None,
        };
        assert!(soundslice.verify_paths(Path::new("./"))?);

        let soundslice = ExerciseAsset::SoundSliceAsset {
            link: "https://www.soundslice.com/slices/QfZcc/".to_string(),
            description: Some("Test".to_string()),
            backup: Some("./bad_file".to_string()),
        };
        assert!(!soundslice.verify_paths(Path::new("./"))?);
        Ok(())
    }

    /// Tests that the `VerifyPaths` trait works for a flashcard asset.
    #[test]
    fn flashcard_verify_paths() -> Result<()> {
        // Verify a flashcard with no back.
        let temp_dir = tempfile::tempdir()?;
        let front_file = tempfile::NamedTempFile::new_in(temp_dir.path())?;
        let flashcard_asset = ExerciseAsset::FlashcardAsset {
            front_path: front_file.path().as_os_str().to_str().unwrap().to_string(),
            back_path: None,
        };
        assert!(flashcard_asset.verify_paths(temp_dir.path())?);

        // Verify a flashcard with front and back.
        let back_file = tempfile::NamedTempFile::new_in(temp_dir.path())?;
        let flashcard_asset = ExerciseAsset::FlashcardAsset {
            front_path: front_file.path().as_os_str().to_str().unwrap().to_string(),
            back_path: Some(back_file.path().as_os_str().to_str().unwrap().to_string()),
        };
        assert!(flashcard_asset.verify_paths(temp_dir.path())?);

        // Verify an inlined flashcard.
        let flashcard_asset = ExerciseAsset::InlineFlashcardAsset {
            front_content: "Front".to_string(),
            back_content: Some("Back".to_string()),
        };
        assert!(flashcard_asset.verify_paths(temp_dir.path())?);
        Ok(())
    }

    /// Tests that the `VerifyPaths` trait works for a literacy asset.
    #[test]
    fn literacy_verify_paths() -> Result<()> {
        let temp_dir = tempfile::tempdir()?;
        let literacy_asset = ExerciseAsset::LiteracyAsset {
            lesson_type: LiteracyLessonType::Reading,
            examples: vec!["C".to_string(), "D".to_string()],
            exceptions: vec!["E".to_string()],
        };
        assert!(literacy_asset.verify_paths(temp_dir.path())?);
        Ok(())
    }

    /// Verifies the `Display` trait for each unit type.
    #[test]
    fn unit_type_display() {
        assert_eq!("Course", UnitType::Course.to_string());
        assert_eq!("Lesson", UnitType::Lesson.to_string());
        assert_eq!("Exercise", UnitType::Exercise.to_string());
    }

    /// Verifies that normalizing a path works with the path to a valid file.
    #[test]
    fn normalize_good_path() -> Result<()> {
        let temp_dir = tempfile::tempdir()?;
        let temp_file = tempfile::NamedTempFile::new_in(temp_dir.path())?;
        let temp_file_path = temp_file.path().to_str().unwrap();
        let normalized_path = normalize_path(temp_dir.path(), temp_file_path)?;
        assert_eq!(
            temp_dir.path().join(temp_file_path).to_str().unwrap(),
            normalized_path
        );
        Ok(())
    }

    /// Verifies that normalizing an absolute path returns the original path.
    #[test]
    fn normalize_absolute_path() {
        let normalized_path = normalize_path(Path::new("/working/dir"), "/absolute/path").unwrap();
        assert_eq!("/absolute/path", normalized_path,);
    }

    /// Verifies that normalizing a path fails with the path to a missing file.
    #[test]
    fn normalize_bad_path() -> Result<()> {
        let temp_dir = tempfile::tempdir()?;
        let temp_file_path = "missing_file";
        assert!(normalize_path(temp_dir.path(), temp_file_path).is_err());
        Ok(())
    }

    /// Verifies the default scheduler options are valid.
    #[test]
    fn valid_default_scheduler_options() {
        let options = SchedulerOptions::default();
        assert!(options.verify().is_ok());
    }

    /// Verifies scheduler options with a batch size of 0 are invalid.
    #[test]
    fn scheduler_options_invalid_batch_size() {
        let options = SchedulerOptions {
            batch_size: 0,
            ..Default::default()
        };
        assert!(options.verify().is_err());
    }

    /// Verifies scheduler options with an invalid relearn fraction are invalid.
    #[test]
    fn scheduler_options_invalid_relearn_fraction() {
        let options = SchedulerOptions {
            relearn_fraction: -0.1,
            ..Default::default()
        };
        assert!(options.verify().is_err());

        let options = SchedulerOptions {
            relearn_fraction: 1.1,
            ..Default::default()
        };
        assert!(options.verify().is_err());
    }

    /// Verifies scheduler options with an invalid mastered window range are invalid.
    #[test]
    fn scheduler_options_invalid_mastered_window() {
        let mut options = SchedulerOptions::default();
        options.mastered_window_opts.range.1 = 4.9;
        assert!(options.verify().is_err());
    }

    /// Verifies scheduler options with an invalid new window range are invalid.
    #[test]
    fn scheduler_options_invalid_new_window() {
        let mut options = SchedulerOptions::default();
        options.new_window_opts.range.0 = 0.1;
        assert!(options.verify().is_err());
    }

    /// Verifies that scheduler options with a gap in the windows are invalid.
    #[test]
    fn scheduler_options_gap_in_windows() {
        let mut options = SchedulerOptions::default();
        options.new_window_opts.range.1 -= 0.1;
        assert!(options.verify().is_err());

        let mut options = SchedulerOptions::default();
        options.target_window_opts.range.1 -= 0.1;
        assert!(options.verify().is_err());

        let mut options = SchedulerOptions::default();
        options.current_window_opts.range.1 -= 0.1;
        assert!(options.verify().is_err());

        let mut options = SchedulerOptions::default();
        options.easy_window_opts.range.1 -= 0.1;
        assert!(options.verify().is_err());
    }

    /// Verifies that scheduler options with a percentage sum other than 1 are invalid.
    #[test]
    fn scheduler_options_invalid_percentage_sum() {
        let mut options = SchedulerOptions::default();
        options.target_window_opts.percentage -= 0.1;
        assert!(options.verify().is_err());
    }

    /// Verifies scheduler options with invalid passing score V2 settings are rejected.
    #[test]
    fn scheduler_options_invalid_passing_score() {
        let mut options = SchedulerOptions::default();
        options.passing_score.min_fraction = -0.1;
        assert!(options.verify().is_err());
    }

    /// Verifies that valid passing score V2 options are recognized as such.
    #[test]
    fn verify_passing_score_options() {
        let options = PassingScoreOptions::default();
        assert!(options.verify().is_ok());

        let options = PassingScoreOptions {
            min_score: 3.75,
            min_fraction: 0.75,
            min_avg_trials: 1.0,
        };
        assert!(options.verify().is_ok());
    }

    /// Verifies that invalid passing score V2 options are recognized as such.
    #[test]
    fn verify_passing_score_options_invalid() {
        let options = PassingScoreOptions {
            min_score: -1.0,
            min_fraction: 0.2,
            min_avg_trials: 1.0,
        };
        assert!(options.verify().is_err());

        let options = PassingScoreOptions {
            min_score: 4.6,
            min_fraction: 0.2,
            min_avg_trials: 1.0,
        };
        assert!(options.verify().is_err());

        let options = PassingScoreOptions {
            min_score: 3.0,
            min_fraction: -0.1,
            min_avg_trials: 1.0,
        };
        assert!(options.verify().is_err());

        let options = PassingScoreOptions {
            min_score: 3.0,
            min_fraction: 1.1,
            min_avg_trials: 1.0,
        };
        assert!(options.verify().is_err());

        let options = PassingScoreOptions {
            min_score: 3.0,
            min_fraction: 0.2,
            min_avg_trials: -0.1,
        };
        assert!(options.verify().is_err());
    }

    /// Verifies that scheduler options with max_lessons_in_progress set to 0 fail verification.
    #[test]
    fn verify_scheduler_options_zero_max_lessons() {
        let options = SchedulerOptions {
            max_lessons_in_progress: 0,
            ..Default::default()
        };
        assert!(options.verify().is_err());
    }

    /// Verifies that the default exercise type is Procedural. Written to satisfy code coverage.
    #[test]
    fn default_exercise_type() {
        let exercise_type = ExerciseType::default();
        assert_eq!(exercise_type, ExerciseType::Procedural);
    }

    /// Verifies the clone method for the `RepositoryMetadata` struct. Written to satisfy code
    /// coverage.
    #[test]
    fn repository_metadata_clone() {
        let metadata = RepositoryMetadata {
            id: "id".to_string(),
            url: "url".to_string(),
        };
        assert_eq!(metadata, metadata.clone());
    }

    /// Verifies the clone method for the `UserPreferences` struct. Written to satisfy code
    /// coverage.
    #[test]
    fn user_preferences_clone() {
        let preferences = UserPreferences {
            transcription: Some(TranscriptionPreferences {
                instruments: vec![],
                download_path: Some("/a/b/c".to_owned()),
                download_path_alias: Some("alias".to_owned()),
            }),
            scheduler: Some(SchedulerPreferences {
                batch_size: Some(10),
            }),
            ignored_paths: vec!["courses/".to_owned()],
        };
        assert_eq!(preferences, preferences.clone());
    }

    /// Verifies the clone method for the `ExerciseTrial` struct. Written to satisfy code coverage.
    #[test]
    fn exercise_trial_clone() {
        let trial = ExerciseTrial {
            score: 5.0,
            timestamp: 1,
        };
        assert_eq!(trial, trial.clone());
    }

    /// Verifies the clone method for the `UnitReward` struct. Written to satisfy code coverage.
    #[test]
    fn unit_reward_clone() {
        let reward = UnitReward {
            unit_id: Ustr::from("unit"),
            timestamp: 1,
            value: 1.0,
            weight: 1.0,
        };
        assert_eq!(reward, reward.clone());
    }
}