Merge branch 'phase/43-whisper'

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Leonid Pershin
2026-08-20 10:40:35 +03:00
co-authored by Cursor
23 changed files with 1062 additions and 37 deletions
+178
View File
@@ -0,0 +1,178 @@
using HSchool.Content;
using HSchool.People;
namespace HSchool.Ai.Tests;
public class WhisperTests
{
[Fact]
public void BlocksOnLesson_AllowsWhisper_NotChat()
{
Assert.True(TalkCircles.BlocksOnLesson(TalkActions.Chat));
Assert.True(TalkCircles.BlocksOnLesson(TalkActions.StaffChat));
Assert.True(TalkCircles.BlocksOnLesson(TalkActions.PhoneChat));
Assert.True(TalkCircles.BlocksOnLesson(TalkActions.TeacherTalk));
Assert.False(TalkCircles.BlocksOnLesson(TalkActions.Whisper));
}
[Fact]
public void FixedSeed_DoesNotCatchEveryWhisperWithTeacherChance()
{
var (catalog, _, _) = World();
var rules = catalog.BehaviorRules!;
var caught = 0;
const int attempts = 40;
for (var i = 0; i < attempts; i++)
{
var roll = TalkCircles.Roll01(Seed.Mix(1, i, Seed.WhisperSalt));
if (TalkCircles.WhisperCaught(roll, rules.WhisperCatchChance, rules.WhisperCatchMax, 1f))
{
caught++;
}
}
Assert.True(caught > 0);
Assert.True(caught < attempts);
Assert.True(rules.WhisperCatchMax < 1f);
}
[Fact]
public void CatchChance_NeverReachesOne_EvenWithLoudTraits()
{
var (catalog, _, _) = World();
var multiplier = TalkCircles.WhisperCatchMultiplier(["Outgoing", "Leader"], catalog);
Assert.True(multiplier > 1f);
var rules = catalog.BehaviorRules!;
const int attempts = 80;
var missed = 0;
for (var i = 0; i < attempts; i++)
{
var roll = TalkCircles.Roll01(Seed.Mix(2, i, Seed.WhisperSalt));
if (!TalkCircles.WhisperCaught(roll, rules.WhisperCatchChance, rules.WhisperCatchMax, multiplier))
{
missed++;
}
}
Assert.True(missed > 0);
}
[Fact]
public void HighPedagogy_AfterPraise_PlusesOpinionMoreThanLow()
{
var (catalog, _, _) = World();
var rules = catalog.BehaviorRules!;
var topic = catalog.Topics[TeacherTopics.Praise];
var from = Person("pupil", ["RussianLanguage"]);
var to = Person("teacher", ["RussianLanguage"]);
var raw = TalkCircles.OpinionDelta(
from,
to,
topic,
50f,
sharedLanguage: true,
TalkActions.TeacherTalk,
ApparelIssue.None,
rules,
catalog);
Assert.True(raw > 0);
var high = TalkCircles.ScaleByPedagogy(raw, 90f, rules);
var low = TalkCircles.ScaleByPedagogy(raw, 20f, rules);
Assert.True(high > low);
}
[Fact]
public void BoundToLesson_SocialZero_StartsWhisperNotChat()
{
var (catalog, map, walks) = World();
var classroom = map.Rooms.First(room => room.Def == "Classroom").Id;
var decision = DecisionPlanner.Decide(
catalog,
map,
walks,
new ActorState(
classroom,
classroom,
false,
false,
true,
false,
false,
true,
classroom,
Needs(social: 0f),
Intent.None,
Talk: new TalkPlannerContext(
"p1",
new Dictionary<string, int>(),
new Dictionary<string, string>(),
"c1",
false,
false,
catalog.BehaviorRules)),
(_, _) => 0);
Assert.Equal(TalkActions.Whisper, decision.StartAction);
Assert.NotEqual(TalkActions.Chat, decision.StartAction);
}
[Fact]
public void PickTopic_OnLesson_OnlyWhisperTopics()
{
var (catalog, _, _) = World();
var picker = Person("a", ["RussianLanguage"]);
for (var seed = 0; seed < 30; seed++)
{
var id = TalkCircles.PickTopic(catalog, picker, age: 14, seed, whisperOnLesson: true);
Assert.NotNull(id);
Assert.True(catalog.Topics[id!].WhisperOnLesson);
}
}
private static Dictionary<string, float> Needs(float social = 1f) => new(StringComparer.Ordinal)
{
["Social"] = social,
["Hunger"] = 1f,
["Sleep"] = 1f,
["Toilet"] = 1f,
};
private static (DefCatalog Catalog, MapLayout Map, WalkGraph Walks) World()
{
var (catalog, map) = Fixtures.Vanilla();
return (catalog, map, WalkGraph.Build(catalog, map));
}
private static Person Person(string id, string[] languages)
{
var skills = languages.ToDictionary(skill => skill, _ => 60, StringComparer.Ordinal);
skills["Communication"] = 50;
var cases = new CaseTable
{
Nom = "A",
Gen = "A",
Dat = "A",
Acc = "A",
Ins = "A",
Pre = "A",
};
return new Person
{
Id = id,
FamilyId = "f1",
Female = false,
BirthDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc),
Name = new PersonName("A", "B", "C", cases, cases, cases),
IsStudent = true,
IsStaff = false,
IsParent = false,
Numbers = new Dictionary<string, int>(StringComparer.Ordinal),
Choices = new Dictionary<string, string>(StringComparer.Ordinal),
Skills = skills,
Traits = [],
Needs = new Dictionary<string, float>(StringComparer.Ordinal),
Opinions = new Dictionary<string, int>(StringComparer.Ordinal),
};
}
}
@@ -113,6 +113,8 @@ public class BehaviorDefTests
Assert.NotNull(catalog.BehaviorRules);
Assert.Equal(0, catalog.BehaviorRules.CommuteRainMinutes);
Assert.Equal(0, catalog.BehaviorRules.CommuteSnowMinutes);
Assert.Equal(0.4f, catalog.BehaviorRules.LessonWhisperSkillFactor);
Assert.Equal(0.4f, catalog.BehaviorRules.WhisperCatchChance);
}
[Theory]
@@ -16,6 +16,10 @@ public class TopicDefTests
Assert.True(catalog.Topics.Count >= 8);
Assert.True(catalog.Topics.ContainsKey("TopicStudy"));
Assert.Contains("study", catalog.Topics["TopicStudy"].Tags);
Assert.True(catalog.Topics["TopicGames"].WhisperOnLesson);
Assert.False(catalog.Topics["TopicRude"].WhisperOnLesson);
Assert.True(catalog.Topics.ContainsKey("TopicPraise"));
Assert.True(catalog.Topics.ContainsKey("TopicDiscipline"));
}
[Fact]
@@ -0,0 +1,301 @@
using Arch.Core;
using HSchool.Ai;
using HSchool.Content;
using HSchool.People;
using HSchool.Schedule;
namespace HSchool.Simulation.Tests;
public class WhisperTests
{
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 WhisperOnLesson_GainsLessThanQuietLesson()
{
var (school, homeroom, firstId, secondId, teacherId) = TwoPupilsAndTeacher();
using (school)
{
AdvanceTo(school, LessonStart);
var schoolClass = school.Roster!.Classes.First(row => row.PupilIds.Contains(firstId));
foreach (var id in schoolClass.PupilIds)
{
PlaceAt(school, id, id == firstId || id == secondId ? homeroom : "corridor-1");
}
PlaceAt(school, firstId, homeroom);
PlaceAt(school, secondId, homeroom);
PlaceAt(school, teacherId, homeroom);
PlaceTextbook(school, firstId, "Mathematics");
PlaceTextbook(school, secondId, "Mathematics");
Assert.True(school.TryStartAction(firstId, TalkActions.Whisper));
Assert.Equal(TalkActions.Whisper, ActivityOf(school, firstId));
Assert.Equal(TalkActions.Whisper, ActivityOf(school, secondId));
var whisperBefore = SkillOf(school, firstId, "Mathematics");
var quietId = schoolClass.PupilIds.First(id => id != firstId && id != secondId);
PlaceAt(school, quietId, homeroom);
PlaceTextbook(school, quietId, "Mathematics");
var quietBefore = SkillOf(school, quietId, "Mathematics");
LessonLearningSystem.Apply(school, 45);
var whisperGain = SkillOf(school, firstId, "Mathematics") - whisperBefore;
var quietGain = SkillOf(school, quietId, "Mathematics") - quietBefore;
Assert.True(quietGain > 0);
Assert.True(whisperGain > 0);
Assert.True(quietGain > whisperGain);
}
}
[Fact]
public void WithoutTeacherInNode_WhisperIsNotCaught()
{
var (school, homeroom, firstId, secondId, teacherId) = TwoPupilsAndTeacher();
using (school)
{
AdvanceTo(school, LessonStart);
var schoolClass = school.Roster!.Classes.First(row => row.PupilIds.Contains(firstId));
foreach (var id in schoolClass.PupilIds)
{
PlaceAt(school, id, id == firstId || id == secondId ? homeroom : "corridor-1");
}
PlaceAt(school, firstId, homeroom);
PlaceAt(school, secondId, homeroom);
PlaceAt(school, teacherId, "restroom-1");
Assert.True(school.TryStartAction(firstId, TalkActions.Whisper));
TalkCircleSystem.Apply(school, 0.5d);
Assert.Equal(TalkActions.Whisper, ActivityOf(school, firstId));
Assert.DoesNotContain(
school.DayLog,
row => (row.PersonId == firstId || row.PersonId == secondId)
&& row.Type.Equals(PersonLogTypes.TeacherInterrupted, StringComparison.Ordinal)
&& row.Time == school.Clock.Time);
Assert.Contains(
school.DayLog,
row => row.PersonId == firstId
&& row.Type.Equals(PersonLogTypes.Whispered, StringComparison.Ordinal)
&& row.Time == school.Clock.Time);
Assert.Equal(
"шептались",
school.DayLog.Last(row => row.Type == PersonLogTypes.Whispered).Caption(school.Catalog!, "ru"));
}
}
[Fact]
public void FixedSeed_WithTeacherInRoom_DoesNotCatchEveryWhisper()
{
var (school, homeroom, firstId, secondId, teacherId) = TwoPupilsAndTeacher();
using (school)
{
AdvanceTo(school, LessonStart);
var caught = 0;
var missed = 0;
for (var i = 0; i < 24; i++)
{
school.Clock.JumpTo(LessonStart.AddMinutes(i));
TalkCircleSystem.Interrupt(school, firstId);
TalkCircleSystem.Interrupt(school, secondId);
TalkCircleSystem.Interrupt(school, teacherId);
var schoolClass = school.Roster!.Classes.First(row => row.PupilIds.Contains(firstId));
foreach (var id in schoolClass.PupilIds)
{
PlaceAt(school, id, id == firstId || id == secondId ? homeroom : "corridor-1");
}
PlaceAt(school, firstId, homeroom);
PlaceAt(school, secondId, homeroom);
PlaceAt(school, teacherId, homeroom);
Assert.True(school.TryStartAction(firstId, TalkActions.Whisper));
TalkCircleSystem.Apply(school, 0.2d);
if (school.DayLog.Any(row =>
(row.PersonId == firstId || row.PersonId == secondId)
&& row.Type.Equals(PersonLogTypes.TeacherInterrupted, StringComparison.Ordinal)
&& row.Time == school.Clock.Time))
{
caught++;
Assert.Equal(
"учитель оборвал",
school.DayLog.Last(row => row.Type == PersonLogTypes.TeacherInterrupted).Caption(school.Catalog!, "ru"));
}
else
{
missed++;
Assert.Equal(TalkActions.Whisper, ActivityOf(school, firstId));
}
}
Assert.True(caught > 0);
Assert.True(missed > 0);
}
}
[Fact]
public void OrdinaryChat_DoesNotStartOnLesson()
{
var (school, homeroom, firstId, secondId, teacherId) = TwoPupilsAndTeacher();
using (school)
{
AdvanceTo(school, LessonStart);
var schoolClass = school.Roster!.Classes.First(row => row.PupilIds.Contains(firstId));
foreach (var id in schoolClass.PupilIds)
{
PlaceAt(school, id, id == firstId || id == secondId ? homeroom : "corridor-1");
}
PlaceAt(school, firstId, homeroom);
PlaceAt(school, secondId, homeroom);
PlaceAt(school, teacherId, homeroom);
Assert.False(school.TryStartAction(firstId, TalkActions.Chat));
Assert.Null(ActivityOf(school, firstId));
Assert.True(school.TryStartAction(firstId, TalkActions.Whisper));
}
}
[Fact]
public void TeacherAfterLesson_TakesTwoToFourPupils()
{
var (school, homeroom, firstId, secondId, teacherId) = TwoPupilsAndTeacher();
using (school)
{
var schoolClass = school.Roster!.Classes.First(row => row.PupilIds.Contains(firstId));
var thirdId = schoolClass.PupilIds.First(id => id != firstId && id != secondId);
AdvanceTo(school, new DateTime(2012, 4, 3, 9, 16, 0, DateTimeKind.Utc));
foreach (var id in schoolClass.PupilIds)
{
PlaceAt(school, id, id == firstId || id == secondId || id == thirdId ? homeroom : "corridor-1");
}
PlaceAt(school, firstId, homeroom);
PlaceAt(school, secondId, homeroom);
PlaceAt(school, thirdId, homeroom);
PlaceAt(school, teacherId, homeroom);
Assert.True(school.TryStartAction(teacherId, TalkActions.TeacherTalk));
var members = new[] { firstId, secondId, thirdId, teacherId }
.Count(id => ActivityOf(school, id) == TalkActions.TeacherTalk);
Assert.InRange(members, 3, 5);
var pupils = new[] { firstId, secondId, thirdId }
.Count(id => ActivityOf(school, id) == TalkActions.TeacherTalk);
Assert.InRange(pupils, 2, 4);
}
}
private static (School School, string Homeroom, string FirstId, string SecondId, string TeacherId) TwoPupilsAndTeacher()
{
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 pupils = schoolClass.PupilIds
.Select(id => school.Roster!.People.First(person => person.Id == id))
.Take(2)
.ToArray();
return (school, schoolClass.RoomId, pupils[0].Id, pupils[1].Id, hiredId);
}
private static void PlaceTextbook(School school, string personId, string subject)
{
var person = school.Roster!.People.First(row => row.Id.Equals(personId, StringComparison.Ordinal));
if (person.Items is not IList<InventoryItem> items || items.IsReadOnly)
{
throw new InvalidOperationException($"Cannot mutate items for {personId}.");
}
for (var i = items.Count - 1; i >= 0; i--)
{
if (items[i].Subject is not null)
{
items.RemoveAt(i);
}
}
items.Add(new InventoryItem("Textbook", Color: null, Condition: 1f, ItemLocations.Bag, subject));
}
private static void AdvanceTo(School school, DateTime until)
{
while (school.Clock.Time < until)
{
school.Tick(0.2d, 5d);
}
}
private static void PlaceAt(School school, string personId, string nodeId)
{
TalkCircleSystem.Interrupt(school, personId);
school.TalkCircleByPerson.Remove(personId);
var query = new QueryDescription().WithAll<PersonIdentity, Presence, PersonActivity, Intent>();
school.World.Query(
in query,
(ref PersonIdentity identity, ref Presence presence, ref PersonActivity activity, ref Intent intent) =>
{
if (identity.Id.Equals(personId, StringComparison.Ordinal))
{
presence = new Presence(nodeId, 0f, nodeId, false, []);
activity = PersonActivity.Idle;
intent = Intent.None;
}
});
}
private static string? ActivityOf(School school, string personId) =>
school.CapturePresence().Single(row => row.PersonId == personId).ActionId;
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 (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;
}
documents.Add(new ContentDocument(
CatalogLoader.CorePackId,
Path.GetRelativePath(root, path).Replace('\\', '/'),
File.ReadAllText(path)));
}
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
Assert.NotNull(map);
return (catalog, map);
}
}