Merge branch 'phase/82-sick-staff-lessons'

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Leonid Pershin
2026-08-21 20:07:22 +03:00
co-authored by Cursor
13 changed files with 367 additions and 10 deletions
@@ -12,18 +12,18 @@
## Задачи ## Задачи
- [ ] Учитель с тяжёлой стадией / «остаться дома» не появляется на уроке (явная стыковка с 14) - [x] Учитель с тяжёлой стадией / «остаться дома» не появляется на уроке (явная стыковка с 14)
- [ ] Урок без учителя → рост/оценка по уже принятым правилам 48/73 - [x] Урок без учителя → рост/оценка по уже принятым правилам 48/73
- [ ] Лог и/или `EventDef` info «без учителя» / сорванный урок — без спама каждый тик - [x] Лог и/или `EventDef` info «без учителя» / сорванный урок — без спама каждый тик
- [ ] Больничный лист и перерасчёт зарплаты не моделируем - [x] Больничный лист и перерасчёт зарплаты не моделируем
- [ ] Детерминизм: тот же сид болезни → тот же приход/неприход - [x] Детерминизм: тот же сид болезни → тот же приход/неприход
## Тесты, без которых фаза не закрыта ## Тесты, без которых фаза не закрыта
- [ ] Больной учитель вне школы → у учеников нет роста «как с учителем в кабинете» - [x] Больной учитель вне школы → у учеников нет роста «как с учителем в кабинете»
- [ ] Здоровый контроль при тех же слотах растёт - [x] Здоровый контроль при тех же слотах растёт
- [ ] Notice/лог не чаще порога - [x] Notice/лог не чаще порога
- [ ] Явка учеников при сорванном уроке не помечается как их прогул ошибочно - [x] Явка учеников при сорванном уроке не помечается как их прогул ошибочно
## Критерий готовности ## Критерий готовности
+1 -1
View File
@@ -18,7 +18,7 @@
| Фаза | Статус | Зачем | | Фаза | Статус | Зачем |
| --- | --- | --- | | --- | --- | --- |
| [82. Больной учитель](82-sick-staff-lessons.md) | 🔄 | Нет на уроке → журнал/тост | | [82. Больной учитель](82-sick-staff-lessons.md) | | Нет на уроке → журнал/тост |
**Этап C — семья.** **Этап C — семья.**
+2
View File
@@ -516,6 +516,8 @@ phase 34 appends it), `apparel-changed` (dressing, when phase 35 appends it),
`lesson-cold` (warmth below the behaviour threshold during a lesson that otherwise taught), `lesson-cold` (warmth below the behaviour threshold during a lesson that otherwise taught),
`lesson-no-textbook` (the bag had no textbook for that lesson; locker and home do not count). `lesson-no-textbook` (the bag had no textbook for that lesson; locker and home do not count).
`thingDef` is the action, apparel or subject def the caption was built from. `thingDef` is the action, apparel or subject def the caption was built from.
When the assigned teacher stays home sick, the school also raises a one-shot info notice
`LessonCancelled` (`trigger` `lessonNoTeacher`) — once per class slot, not every tick.
```json ```json
{ {
+1
View File
@@ -17,6 +17,7 @@ internal static class EventDefValidator
EventTriggers.DirectorSummon, EventTriggers.DirectorSummon,
EventTriggers.ParentMeeting, EventTriggers.ParentMeeting,
EventTriggers.DiseaseOutbreak, EventTriggers.DiseaseOutbreak,
EventTriggers.LessonNoTeacher,
}; };
private static readonly HashSet<string> Actions = new(StringComparer.Ordinal) private static readonly HashSet<string> Actions = new(StringComparer.Ordinal)
+1
View File
@@ -15,6 +15,7 @@ public static class EventTriggers
public const string DirectorSummon = "directorSummon"; public const string DirectorSummon = "directorSummon";
public const string ParentMeeting = "parentMeeting"; public const string ParentMeeting = "parentMeeting";
public const string DiseaseOutbreak = "diseaseOutbreak"; public const string DiseaseOutbreak = "diseaseOutbreak";
public const string LessonNoTeacher = "lessonNoTeacher";
} }
public static class EventActions public static class EventActions
@@ -47,4 +47,12 @@
"trigger": "diseaseOutbreak", "trigger": "diseaseOutbreak",
"action": "none", "action": "none",
}, },
{
"defName": "LessonCancelled",
"severity": "info",
"pause": false,
"ttlMs": 8000,
"trigger": "lessonNoTeacher",
"action": "none",
},
] ]
@@ -237,6 +237,7 @@
"DirectorSummoned": "A pupil was summoned to the principal", "DirectorSummoned": "A pupil was summoned to the principal",
"ParentMeeting": "A parent meeting is under way", "ParentMeeting": "A parent meeting is under way",
"DiseaseOutbreak": "An illness is spreading at school", "DiseaseOutbreak": "An illness is spreading at school",
"LessonCancelled": "Lesson without a teacher",
"GoingToPrincipal": "going to the principal", "GoingToPrincipal": "going to the principal",
"WaitForPrincipal": "waiting at the principal's office", "WaitForPrincipal": "waiting at the principal's office",
"GoingToParentMeeting": "going to a parent meeting", "GoingToParentMeeting": "going to a parent meeting",
@@ -237,6 +237,7 @@
"DirectorSummoned": "Ученика вызвали к директору", "DirectorSummoned": "Ученика вызвали к директору",
"ParentMeeting": "Идёт родительское собрание", "ParentMeeting": "Идёт родительское собрание",
"DiseaseOutbreak": "В школе распространяется болезнь", "DiseaseOutbreak": "В школе распространяется болезнь",
"LessonCancelled": "Урок без учителя",
"GoingToPrincipal": "идёт к директору", "GoingToPrincipal": "идёт к директору",
"WaitForPrincipal": "ждёт у кабинета директора", "WaitForPrincipal": "ждёт у кабинета директора",
"GoingToParentMeeting": "идёт на собрание", "GoingToParentMeeting": "идёт на собрание",
@@ -54,6 +54,8 @@ internal static class LessonLearningSystem
teacherSkills[identity.Id] = personSkills.Values; teacherSkills[identity.Id] = personSkills.Values;
}); });
RaiseSickTeacherLessons(school, places, weekday, slot.Index);
world.Query( world.Query(
in People, in People,
(ref PersonIdentity identity, ref PersonSkills skills, ref PersonTraits traits, ref PersonNeeds needs, ref PersonRoles roles, ref Presence presence, ref PersonActivity activity) => (ref PersonIdentity identity, ref PersonSkills skills, ref PersonTraits traits, ref PersonNeeds needs, ref PersonRoles roles, ref Presence presence, ref PersonActivity activity) =>
@@ -208,6 +210,56 @@ internal static class LessonLearningSystem
&& teacher.NodeId is not null && teacher.NodeId is not null
&& teacher.NodeId.Equals(roomId, StringComparison.Ordinal); && teacher.NodeId.Equals(roomId, StringComparison.Ordinal);
/// <summary>
/// One school toast per class slot when the assigned teacher stayed home sick (slice 15).
/// Uses the morning day plan — re-rolling <see cref="DiseaseEffects.ShouldStayHome"/> at
/// lesson time can flip after severity ticks. Toilet trips keep the per-pupil log only.
/// </summary>
private static void RaiseSickTeacherLessons(
School school,
Dictionary<string, Presence> places,
int weekday,
int period)
{
if (school.Timetable is null || school.Roster is null || school.Catalog is null)
{
return;
}
foreach (var lesson in school.Timetable.Lessons)
{
if (lesson.Day != weekday || lesson.Period != period)
{
continue;
}
if (TeacherStandingIn(places, lesson.TeacherId, lesson.RoomId))
{
continue;
}
if (!school.Plans.TryGetValue(lesson.TeacherId, out var plan) || plan.Comes)
{
continue;
}
var teacher = school.Roster.People.FirstOrDefault(row =>
row.Id.Equals(lesson.TeacherId, StringComparison.Ordinal));
if (teacher is null
|| DiseaseEffects.StayHomeChance(teacher, school.Catalog, school.Clock.Time) <= 0f)
{
continue;
}
if (!school.TryClaimLessonNoTeacherEvent(lesson.ClassId, school.Clock.Time.Date, lesson.Period))
{
continue;
}
school.RaiseWorldEvent(new WorldEvent(EventTriggers.LessonNoTeacher, lesson.TeacherId));
}
}
private static LessonPlacement? CurrentLesson(School school, Person person, int weekday, int period) private static LessonPlacement? CurrentLesson(School school, Person person, int weekday, int period)
{ {
foreach (var lesson in Duty.LessonsToday(person, ClassOf(school, person), school.Timetable, weekday)) foreach (var lesson in Duty.LessonsToday(person, ClassOf(school, person), school.Timetable, weekday))
+11
View File
@@ -19,6 +19,7 @@ public sealed class School : IDisposable
private readonly List<PersonLogEvent> _dayLog = []; private readonly List<PersonLogEvent> _dayLog = [];
private readonly HashSet<string> _lessonLogOnce = new(StringComparer.Ordinal); private readonly HashSet<string> _lessonLogOnce = new(StringComparer.Ordinal);
private readonly HashSet<string> _lessonMarkOnce = new(StringComparer.Ordinal); private readonly HashSet<string> _lessonMarkOnce = new(StringComparer.Ordinal);
private readonly HashSet<string> _lessonNoTeacherEventOnce = new(StringComparer.Ordinal);
private readonly List<WorldEvent> _worldEvents = []; private readonly List<WorldEvent> _worldEvents = [];
internal School(int id, string name, DateTime startDate, DefCatalog? catalog, MapLayout? map) internal School(int id, string name, DateTime startDate, DefCatalog? catalog, MapLayout? map)
@@ -176,6 +177,7 @@ public sealed class School : IDisposable
LoggedActivity.Clear(); LoggedActivity.Clear();
_lessonLogOnce.Clear(); _lessonLogOnce.Clear();
_lessonMarkOnce.Clear(); _lessonMarkOnce.Clear();
_lessonNoTeacherEventOnce.Clear();
LastAttendanceSlot = null; LastAttendanceSlot = null;
} }
@@ -205,6 +207,15 @@ public sealed class School : IDisposable
return _lessonMarkOnce.Add(key); return _lessonMarkOnce.Add(key);
} }
/// <summary>
/// One school toast per class lesson slot when the assigned teacher stays home sick.
/// </summary>
internal bool TryClaimLessonNoTeacherEvent(string classId, DateTime day, int period)
{
var key = string.Concat(classId, "\0", day.ToString("yyyy-MM-dd"), "\0", period.ToString());
return _lessonNoTeacherEventOnce.Add(key);
}
public void QueueDecision(string personId) public void QueueDecision(string personId)
{ {
ObjectDisposedException.ThrowIf(_disposed, this); ObjectDisposedException.ThrowIf(_disposed, this);
@@ -35,6 +35,14 @@ public class DiseaseDefTests
Assert.True(catalog.Events.ContainsKey("DiseaseOutbreak")); Assert.True(catalog.Events.ContainsKey("DiseaseOutbreak"));
Assert.Equal(EventTriggers.DiseaseOutbreak, catalog.Events["DiseaseOutbreak"].Trigger); Assert.Equal(EventTriggers.DiseaseOutbreak, catalog.Events["DiseaseOutbreak"].Trigger);
Assert.Equal("В школе распространяется болезнь", catalog.Label("ru", catalog.Events["DiseaseOutbreak"])); Assert.Equal("В школе распространяется болезнь", catalog.Label("ru", catalog.Events["DiseaseOutbreak"]));
Assert.True(catalog.Events.ContainsKey("LessonCancelled"));
Assert.Equal(EventTriggers.LessonNoTeacher, catalog.Events["LessonCancelled"].Trigger);
Assert.Equal(EventSeverities.Info, catalog.Events["LessonCancelled"].Severity);
Assert.False(catalog.Events["LessonCancelled"].Pause);
Assert.Equal(8000, catalog.Events["LessonCancelled"].TtlMs);
Assert.Equal("Урок без учителя", catalog.Label("ru", catalog.Events["LessonCancelled"]));
Assert.Equal("Lesson without a teacher", catalog.Label("en", catalog.Events["LessonCancelled"]));
} }
[Fact] [Fact]
@@ -42,6 +42,10 @@ public class EventDefTests
Assert.Equal(EventActions.None, catalog.Events["DirectorSummoned"].Action); Assert.Equal(EventActions.None, catalog.Events["DirectorSummoned"].Action);
Assert.Equal("Ученика вызвали к директору", catalog.Label("ru", catalog.Events["DirectorSummoned"])); Assert.Equal("Ученика вызвали к директору", catalog.Label("ru", catalog.Events["DirectorSummoned"]));
Assert.Equal("A pupil was summoned to the principal", catalog.Label("en", catalog.Events["DirectorSummoned"])); Assert.Equal("A pupil was summoned to the principal", catalog.Label("en", catalog.Events["DirectorSummoned"]));
Assert.True(catalog.Events.ContainsKey("LessonCancelled"));
Assert.Equal(EventTriggers.LessonNoTeacher, catalog.Events["LessonCancelled"].Trigger);
Assert.Equal("Урок без учителя", catalog.Label("ru", catalog.Events["LessonCancelled"]));
} }
[Fact] [Fact]
@@ -0,0 +1,268 @@
using Arch.Core;
using HSchool.Ai;
using HSchool.Content;
using HSchool.People;
using HSchool.Schedule;
namespace HSchool.Simulation.Tests;
public class SickStaffLessonTests
{
private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
private static readonly DateTime LessonStart = new(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc);
[Fact]
public void SickTeacherOffCampus_PupilsDoNotGainLikeWithTeacher()
{
var (sickSchool, room, pupilId, teacherId) = StaffedMath();
using (sickSchool)
{
InfectHeavyFlu(sickSchool, teacherId);
var stayDay = TuesdayWithStayHome(sickSchool, teacherId);
RebuildDayAt(sickSchool, stayDay);
AdvanceTo(sickSchool, stayDay.Date.Add(LessonStart.TimeOfDay));
Assert.False(IsOnCampus(sickSchool, teacherId));
SetPlace(sickSchool, pupilId, room);
var before = SkillOf(sickSchool, pupilId, "Mathematics");
LessonLearningSystem.Apply(sickSchool, 45);
Assert.Equal(before, SkillOf(sickSchool, pupilId, "Mathematics"));
Assert.Equal(2, MarkOf(sickSchool, pupilId)!.Value);
}
var (healthySchool, healthyRoom, healthyPupil, healthyTeacher) = StaffedMath();
using (healthySchool)
{
AdvanceTo(healthySchool, LessonStart);
SetPlace(healthySchool, healthyPupil, healthyRoom);
SetPlace(healthySchool, healthyTeacher, healthyRoom);
var before = SkillOf(healthySchool, healthyPupil, "Mathematics");
LessonLearningSystem.Apply(healthySchool, 45);
Assert.True(SkillOf(healthySchool, healthyPupil, "Mathematics") > before);
}
}
[Fact]
public void SickTeacher_NoticeAndLog_AtMostOncePerSlot()
{
var (school, room, pupilId, teacherId) = StaffedMath();
using (school)
{
InfectHeavyFlu(school, teacherId);
var stayDay = TuesdayWithStayHome(school, teacherId);
RebuildDayAt(school, stayDay);
// Jump — do not AdvanceTo through the lesson, or Tick raises the event and claims it.
school.Clock.JumpTo(DateTime.SpecifyKind(stayDay.Date.Add(LessonStart.TimeOfDay), DateTimeKind.Utc));
SetPlace(school, pupilId, room);
SetPlace(school, teacherId, null);
school.DrainWorldEvents();
Assert.True(school.Plans.TryGetValue(teacherId, out var plan) && !plan.Comes);
LessonLearningSystem.Apply(school, 5);
LessonLearningSystem.Apply(school, 5);
LessonLearningSystem.Apply(school, 5);
var logs = school.DayLog
.Where(row => row.PersonId == pupilId && row.Type == PersonLogTypes.LessonNoTeacher)
.ToArray();
Assert.Single(logs);
var facts = school.DrainWorldEvents()
.Where(row => row.Trigger.Equals(EventTriggers.LessonNoTeacher, StringComparison.Ordinal))
.ToArray();
Assert.Single(facts);
Assert.Equal(teacherId, facts[0].PersonKey);
}
}
[Fact]
public void PupilsPresent_WhileTeacherSick_AreNotMarkedTruancy()
{
var (school, room, pupilId, teacherId) = StaffedMath();
using (school)
{
InfectHeavyFlu(school, teacherId);
var stayDay = TuesdayWithStayHome(school, teacherId);
RebuildDayAt(school, stayDay);
var lessonAt = stayDay.Date.Add(LessonStart.TimeOfDay);
AdvanceTo(school, lessonAt.AddMinutes(-1));
SetPlace(school, pupilId, room);
SetPlace(school, teacherId, null);
school.Clock.JumpTo(lessonAt);
AttendanceSystem.Apply(school);
school.Clock.JumpTo(lessonAt.AddMinutes(45));
AttendanceSystem.Apply(school);
var row = school.Roster!.People.First(p => p.Id == pupilId).Attendance?.LastOrDefault();
Assert.NotNull(row);
Assert.Equal(AttendanceStatuses.Present, row!.Status);
Assert.Null(row.AbsenceReason);
Assert.NotEqual(AbsenceReasons.Truancy, row.AbsenceReason);
}
}
[Fact]
public void SameDiseaseSeed_SameStayHomeDecision()
{
var (school, _, _, teacherId) = StaffedMath();
using (school)
{
InfectHeavyFlu(school, teacherId);
var teacher = school.Roster!.People.First(row => row.Id == teacherId);
var when = LessonStart.AddDays(2);
var first = DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, when);
var second = DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, when);
Assert.Equal(first, second);
}
}
private static void InfectHeavyFlu(School school, string teacherId)
{
var teacher = school.Roster!.People.First(row => row.Id == teacherId);
HealthConditions.Add(
teacher,
new HealthCondition
{
DefName = "Influenza",
Severity = 0.85f,
Progress = 0.1f,
Source = "cold",
StartedAt = TuesdayMorning.AddDays(-3),
});
Assert.True(DiseaseEffects.StayHomeChance(teacher, school.Catalog!, LessonStart) >= 0.9f);
}
private static DateTime TuesdayWithStayHome(School school, string teacherId)
{
var teacher = school.Roster!.People.First(row => row.Id == teacherId);
for (var i = 0; i < 60; i++)
{
var candidate = LessonStart.AddDays(i * 7);
if (DiseaseEffects.ShouldStayHome(teacher, school.Catalog!, school.PeopleSeed, candidate))
{
return candidate;
}
}
throw new InvalidOperationException("Heavy flu should stay home on some Tuesday.");
}
private static void RebuildDayAt(School school, DateTime lessonInstant)
{
school.PlanDay = null;
school.Clock.JumpTo(DateTime.SpecifyKind(lessonInstant.Date.AddHours(6), DateTimeKind.Utc));
school.Tick(0.2d, 5d);
}
private static bool IsOnCampus(School school, string personId)
{
var on = false;
var query = new QueryDescription().WithAll<PersonIdentity, Presence>();
school.World.Query(
in query,
(ref PersonIdentity identity, ref Presence presence) =>
{
if (identity.Id.Equals(personId, StringComparison.Ordinal))
{
on = presence.IsOnCampus;
}
});
return on;
}
private static LessonMarkRecord? MarkOf(School school, string pupilId) =>
school.Roster!.People.First(row => row.Id == pupilId).LessonMarks?.LastOrDefault();
private static void AdvanceTo(School school, DateTime until)
{
while (school.Clock.Time < until)
{
school.Tick(0.2d, 5d);
}
}
private static void SetPlace(School school, string personId, string? nodeId)
{
var query = new QueryDescription().WithAll<PersonIdentity, Presence>();
school.World.Query(
in query,
(ref PersonIdentity identity, ref Presence presence) =>
{
if (!identity.Id.Equals(personId, StringComparison.Ordinal))
{
return;
}
presence = nodeId is null
? Presence.OffCampus
: new Presence(nodeId, 0f, nodeId, false, []);
});
}
private static float SkillOf(School school, string personId, string skill)
{
var value = float.NaN;
var query = new QueryDescription().WithAll<PersonIdentity, PersonSkills>();
school.World.Query(
in query,
(ref PersonIdentity identity, ref PersonSkills skills) =>
{
if (identity.Id.Equals(personId, StringComparison.Ordinal))
{
value = skills.Values.GetValueOrDefault(skill);
}
});
return value;
}
private static (School School, string Homeroom, string PupilId, string TeacherId) StaffedMath()
{
var (catalog, map) = Vanilla();
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", TuesdayMorning);
var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", TuesdayMorning);
var hired = Staffing.Hire(catalog, map, roster, pool, pool.Applicants[0].Person.Id, Staffing.TeacherPosition, 1_000_000f);
Assert.Equal(StaffingError.None, hired.Error);
roster = hired.Roster;
pool = hired.Pool;
var hiredId = roster.People.First(person => person.IsStaff).Id;
var schoolClass = roster.Classes.First(row =>
row.RoomId is "classroom-101" or "classroom-102" or "classroom-103" or "classroom-104");
var school = School.Create(1, "Больной учитель", TuesdayMorning, catalog, map);
school.InstallPeople(roster, seed: 1, "Russia", pool);
school.SetTimetable(new Timetable(
[new LessonPlacement(schoolClass.Id, "Mathematics", hiredId, schoolClass.RoomId, Day: 1, Period: 1)],
[]));
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
var pupil = schoolClass.PupilIds
.Select(id => school.Roster!.People.First(person => person.Id == id))
.First(person => !person.Traits.Contains("Lazy"));
return (school, schoolClass.RoomId, pupil.Id, hiredId);
}
private static (DefCatalog Catalog, MapLayout Map) Vanilla()
{
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
var documents = new List<ContentDocument>();
foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories))
{
if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase)
&& !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var relative = Path.GetRelativePath(root, path).Replace('\\', '/');
documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path)));
}
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
Assert.NotNull(map);
return (catalog, map);
}
}