Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public async Task<Result<DailySummaryResponse>> Handle(
summaryHabits,
request.DateFrom,
request.DateTo,
userToday,
effectiveLanguage,
currentLocalTime,
cancellationToken);
Expand Down
1 change: 1 addition & 0 deletions src/Orbit.Domain/Interfaces/ISummaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Task<Result<string>> GenerateSummaryAsync(
IEnumerable<Habit> allHabits,
DateOnly dateFrom,
DateOnly dateTo,
DateOnly userToday,
string language,
TimeOnly? currentLocalTime,
CancellationToken cancellationToken = default);
Expand Down
66 changes: 47 additions & 19 deletions src/Orbit.Infrastructure/Services/AiSummaryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,28 +18,12 @@ public async Task<Result<string>> GenerateSummaryAsync(
IEnumerable<Habit> allHabits,
DateOnly dateFrom,
DateOnly dateTo,
DateOnly userToday,
string language,
TimeOnly? currentLocalTime,
CancellationToken cancellationToken = default)
{
var habitList = allHabits.ToList();

var scheduledTopLevel = habitList
.Where(h => h.ParentHabitId is null
&& !HasSkipLogInRange(h, dateFrom, dateTo)
&& (HabitScheduleService.GetScheduledDates(h, dateFrom, dateTo).Count > 0
|| HasCompletedLogInRange(h, dateFrom, dateTo)))
.ToList();

var scheduledTopLevelIds = scheduledTopLevel.Select(h => h.Id).ToHashSet();

var children = habitList
.Where(h => h.ParentHabitId is not null
&& scheduledTopLevelIds.Contains(h.ParentHabitId.Value)
&& !HasSkipLogInRange(h, dateFrom, dateTo))
.ToList();

var scheduledHabits = scheduledTopLevel.Concat(children).ToList();
var scheduledHabits = SelectScheduledHabits(allHabits, userToday, dateFrom, dateTo);

var prompt = BuildSummaryPrompt(scheduledHabits, dateFrom, dateTo, language, currentLocalTime);

Expand Down Expand Up @@ -71,6 +55,38 @@ public async Task<Result<string>> GenerateSummaryAsync(
}
}

/// <summary>
/// Selects the habits the summary should reason about, using the same DueDate-authoritative
/// "due today" gate as the Today list (<see cref="IsDueToday"/>). A child is included on its
/// own merit, not merely because its parent qualified, so habits whose DueDate has already
/// advanced past today (logged good recurring habits) are not re-listed as pending.
/// </summary>
private static List<Habit> SelectScheduledHabits(
IEnumerable<Habit> allHabits,
DateOnly userToday,
DateOnly dateFrom,
DateOnly dateTo)
{
var habitList = allHabits.ToList();

var scheduledTopLevel = habitList
.Where(h => h.ParentHabitId is null
&& !HasSkipLogInRange(h, dateFrom, dateTo)
&& IsDueToday(h, userToday, dateFrom, dateTo))
.ToList();

var scheduledTopLevelIds = scheduledTopLevel.Select(h => h.Id).ToHashSet();

var children = habitList
.Where(h => h.ParentHabitId is not null
&& scheduledTopLevelIds.Contains(h.ParentHabitId.Value)
&& !HasSkipLogInRange(h, dateFrom, dateTo)
&& IsDueToday(h, userToday, dateFrom, dateTo))
.ToList();

return scheduledTopLevel.Concat(children).ToList();
}

private static string BuildSummaryPrompt(
List<Habit> scheduledHabits,
DateOnly date,
Expand Down Expand Up @@ -99,6 +115,7 @@ Write a short message to this person about their day.
Rules:
- LEAD with a specific, genuine acknowledgment of what they have ALREADY completed today -- name the activity naturally, don't just say "good job"
- THEN, gently point at one or two of the still-pending habits as easy next moves -- never list everything, never frame it as a checklist, never guilt-trip
- If EVERYTHING is already done (nothing is pending), simply celebrate the full day warmly and leave it there -- do NOT invent, imply, or suggest any remaining task
- If nothing is done yet, stay warm and forward-looking; do NOT imply they are behind or failing
- Describe the ACTIVITY naturally, don't just parrot the exact habit title
- BAD: "You have Yoga, Morning Routine, and Guitar Playing left."
Expand All @@ -109,7 +126,7 @@ Write a short message to this person about their day.
- Do NOT use phrases like "right now", "just woke up", "now that the afternoon is here", "as the day begins", "earlier today", or "upcoming later today"
- Do NOT use markdown, bullet points, emojis, or JSON
- Do NOT mention the date explicitly
- Write ONLY in {languageName}
- Write ONLY in {languageName}, using natural, fluent, grammatically correct phrasing a native speaker would actually use
- No greeting like "good morning", no sign-off -- just the message
""";
}
Expand Down Expand Up @@ -152,6 +169,17 @@ private static bool HasCompletedLogInRange(Habit habit, DateOnly dateFrom, DateO
private static bool IsDoneInRange(Habit habit, DateOnly dateFrom, DateOnly dateTo) =>
habit.IsCompleted || HasCompletedLogInRange(habit, dateFrom, dateTo);

/// <summary>
/// DueDate-authoritative "due today" gate shared with the Today list
/// (see <c>GetHabitScheduleQuery.DetermineOverdueStatus</c> / <c>MapChildren</c>):
/// a habit belongs in the summary only if it is scheduled today or has an unresolved
/// past occurrence. Habits completed in range are kept so they can be acknowledged as done.
/// </summary>
private static bool IsDueToday(Habit habit, DateOnly userToday, DateOnly dateFrom, DateOnly dateTo) =>
HabitScheduleService.IsHabitDueOnDate(habit, userToday)
|| HabitScheduleService.HasMissedPastOccurrence(habit, userToday)
|| IsDoneInRange(habit, dateFrom, dateTo);

private static string BuildTimeContext(TimeOnly? currentLocalTime)
{
if (!currentLocalTime.HasValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public async Task Handle_GeneratesNewSummary_WhenNotCached()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("Test summary content"));
Expand Down Expand Up @@ -76,7 +76,7 @@ public async Task Handle_ReturnsCachedSummary_WhenCached()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("First call summary"));
Expand Down Expand Up @@ -114,7 +114,7 @@ public async Task Handle_ExcludesHabitsSkippedInRequestedRange()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("Summary"));
Expand All @@ -127,7 +127,7 @@ public async Task Handle_ExcludesHabitsSkippedInRequestedRange()
await _summaryService.Received(1).GenerateSummaryAsync(
Arg.Is<IEnumerable<Habit>>(habits =>
habits.Select(h => h.Title).SequenceEqual(new[] { "Read" })),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>());
}
Expand Down Expand Up @@ -192,7 +192,7 @@ public async Task Handle_SummaryServiceFails_ReturnsFailure()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Failure<string>("AI service unavailable"));
Expand Down Expand Up @@ -221,7 +221,7 @@ public async Task Handle_UsesUserProfileLanguage_WhenRequestLanguageDiffers()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "pt-BR",
Today, Today, Arg.Any<DateOnly>(), "pt-BR",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("Resumo em portugues"));
Expand All @@ -234,12 +234,12 @@ public async Task Handle_UsesUserProfileLanguage_WhenRequestLanguageDiffers()
result.IsSuccess.Should().BeTrue();
await _summaryService.Received(1).GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "pt-BR",
Today, Today, Arg.Any<DateOnly>(), "pt-BR",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>());
await _summaryService.DidNotReceive().GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>());
}
Expand All @@ -259,7 +259,7 @@ public async Task Handle_FallsBackToRequestLanguage_WhenUserLanguageEmpty()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "pt-BR",
Today, Today, Arg.Any<DateOnly>(), "pt-BR",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("Resumo"));
Expand All @@ -271,7 +271,7 @@ public async Task Handle_FallsBackToRequestLanguage_WhenUserLanguageEmpty()
result.IsSuccess.Should().BeTrue();
await _summaryService.Received(1).GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "pt-BR",
Today, Today, Arg.Any<DateOnly>(), "pt-BR",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>());
}
Expand All @@ -291,7 +291,7 @@ public async Task Handle_FallsBackToEnglish_WhenBothEmpty()

_summaryService.GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>())
.Returns(Result.Success("Summary"));
Expand All @@ -303,7 +303,7 @@ public async Task Handle_FallsBackToEnglish_WhenBothEmpty()
result.IsSuccess.Should().BeTrue();
await _summaryService.Received(1).GenerateSummaryAsync(
Arg.Any<IEnumerable<Habit>>(),
Today, Today, "en",
Today, Today, Arg.Any<DateOnly>(), "en",
Arg.Any<TimeOnly?>(),
Arg.Any<CancellationToken>());
}
Expand Down
117 changes: 117 additions & 0 deletions tests/Orbit.Infrastructure.Tests/Services/AiSummaryServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,99 @@ public void BuildHabitSection_Children_IndentedWithTwoSpaces()
result.Should().Contain(" - Child (pending)");
}

// ── SelectScheduledHabits: DueDate-authoritative parity with the Today list ──

[Fact]
public void SelectScheduledHabits_DailyGoodHabitLoggedToday_KeptAndLabeledDoneNotPending()
{
// Logging a recurring good habit advances its DueDate past today (mirrors LogHabitCommand).
// It must still appear so it can be acknowledged -- but as done, never pending.
var habit = CreateHabit("Café da manhã");
habit.Log(Today);

var selected = InvokeSelectScheduledHabits([habit], Today);

selected.Should().ContainSingle();
var section = InvokeBuildHabitSection(selected);
section.Should().Contain("Café da manhã (done)");
section.Should().NotContain("pending");
}

[Fact]
public void SelectScheduledHabits_WeeklyGoodHabitLoggedToday_KeptAndLabeledDone()
{
var habit = CreateRecurring("Pesar na balança", FrequencyUnit.Week);
habit.Log(Today);

var selected = InvokeSelectScheduledHabits([habit], Today);

selected.Should().ContainSingle();
InvokeBuildHabitSection(selected).Should().Contain("Pesar na balança (done)");
}

[Fact]
public void SelectScheduledHabits_WeeklyChildResolvedOnItsOccurrence_NotSelected()
{
// Regression: a weekly child resolved on its real occurrence has a DueDate that has
// advanced past today, so it is neither due today nor overdue. The old code force-included
// every child of a due parent and labeled it pending because the prior-week completion
// fell outside today's range.
var parent = CreateHabit("Morning routine");
var weeklyChild = CreateRecurring(
"Pesar na balança", FrequencyUnit.Week, dueDate: Today.AddDays(7), parentId: parent.Id);
weeklyChild.Log(Today.AddDays(-7), advanceDueDate: false);

var selected = InvokeSelectScheduledHabits([parent, weeklyChild], Today);

selected.Should().ContainSingle(h => h.Id == parent.Id);
selected.Should().NotContain(h => h.Id == weeklyChild.Id);
}

[Fact]
public void SelectScheduledHabits_RoutineWithNonDueChild_DoesNotSurfaceChildAsPending()
{
// Same defect viewed through the prompt: a monthly child whose DueDate has advanced
// past today must never be listed as a pending sub-task just because its parent is due.
var parent = CreateHabit("Morning routine");
var monthlyChild = CreateRecurring(
"Deep clean", FrequencyUnit.Month, dueDate: Today.AddDays(14), parentId: parent.Id);

var selected = InvokeSelectScheduledHabits([parent, monthlyChild], Today);
var section = InvokeBuildHabitSection(selected);

section.Should().NotContain("Deep clean");
section.Should().Contain("Morning routine (pending)");
}

[Fact]
public void SelectScheduledHabits_RoutineChildrenAllLoggedToday_NoChildPending()
{
var parent = CreateHabit("Morning routine");
var child1 = CreateHabit("Café da manhã", parentId: parent.Id);
var child2 = CreateHabit("Stretch", parentId: parent.Id);
child1.Log(Today);
child2.Log(Today);

var selected = InvokeSelectScheduledHabits([parent, child1, child2], Today);
var section = InvokeBuildHabitSection(selected);

section.Should().NotContain("pending)");
section.Should().Contain("Café da manhã (done)");
section.Should().Contain("Stretch (done)");
}

[Fact]
public void SelectScheduledHabits_OverdueHabit_StillSelected()
{
// An unresolved recurring habit (DueDate fell before today) is overdue and must remain.
var overdue = CreateRecurring("Take vitamins", FrequencyUnit.Day, dueDate: Today.AddDays(-2));

var selected = InvokeSelectScheduledHabits([overdue], Today);

selected.Should().ContainSingle();
InvokeBuildHabitSection(selected).Should().Contain("Take vitamins (pending)");
}

// ── Helpers ──

private static Habit CreateHabit(
Expand All @@ -508,6 +601,22 @@ private static Habit CreateHabit(
ParentHabitId: parentId)).Value;
}

private static Habit CreateRecurring(
string title,
FrequencyUnit unit,
int quantity = 1,
DateOnly? dueDate = null,
Guid? parentId = null)
{
return Habit.Create(new HabitCreateParams(
ValidUserId,
title,
unit,
quantity,
DueDate: dueDate ?? Today,
ParentHabitId: parentId)).Value;
}

private static string InvokeBuildSummaryPrompt(
List<Habit> scheduledHabits,
DateOnly date,
Expand All @@ -525,4 +634,12 @@ private static string InvokeBuildHabitSection(List<Habit> scheduledHabits)
.GetMethod("BuildHabitSection", PrivateStatic)!;
return (string)method.Invoke(null, [scheduledHabits, Today, Today])!;
}

private static List<Habit> InvokeSelectScheduledHabits(
List<Habit> allHabits, DateOnly userToday)
{
var method = typeof(AiSummaryService)
.GetMethod("SelectScheduledHabits", PrivateStatic)!;
return (List<Habit>)method.Invoke(null, [allHabits, userToday, userToday, userToday])!;
}
}
Loading