diff --git a/.opencode/agents/Complete.md b/.opencode/agents/Complete.md new file mode 100644 index 00000000..e69de29b diff --git a/.plans/180-apollo-time-format-flexibility.md b/.plans/180-apollo-time-format-flexibility.md new file mode 100644 index 00000000..2e2f3f1b --- /dev/null +++ b/.plans/180-apollo-time-format-flexibility.md @@ -0,0 +1,199 @@ +# Apollo Is Too Picky About The Time Format + +## Description + +Apollo's time parsing is overly restrictive. The `FuzzyTimeParser` only supports 4 narrow patterns (`in N unit`, `tomorrow`, `next week`), and the fallback to `DateTime.TryParse` is unreliable (no explicit culture or format specifiers). There is also a mismatch between what the AI prompts tell the LLM to produce (e.g., `"tomorrow at 3pm"`) and what the parser can actually accept. Additionally, the parsing logic is duplicated across three locations (`ToDoPlugin`, `RemindersPlugin`, `ApolloGrpcService`) with subtle differences (the gRPC version doesn't do timezone-aware conversion). + +**Goal:** Expand the accepted time formats by (1) adding more regex patterns to `FuzzyTimeParser`, (2) improving the C# `DateTime.TryParse` fallback with explicit format strings, (3) consolidating all parsing into a shared service, and (4) as a last resort, creating an efficient LLM prompt specifically for time parsing. Fix the prompt/parser mismatch so the LLM knows what formats are actually accepted. + +**GitHub Issue:** #180 + +## Steps + +### Step 1 - Expand FuzzyTimeParser With New Patterns + +Add new source-generated regex patterns to support common natural language time expressions that users expect to work. This step is self-contained and affects only the parser and its tests. + +**New patterns to support:** +- `tomorrow at 3pm` / `tomorrow at 15:00` (compound day + time-of-day) +- `at 3pm` / `at 15:00` / `at noon` / `at midnight` (time-of-day today) +- `tonight` / `this morning` / `this afternoon` / `this evening` (time-of-day aliases) +- `noon` / `midnight` (standalone time aliases) +- `next Monday` / `on Tuesday` / `on Friday at 3pm` (day-of-week with optional time) +- `in an hour` / `in half an hour` (word-based durations) +- `5 minutes` / `30 minutes` (without "in" prefix — lenient matching) +- `end of day` / `end of week` (common natural anchors) + +#### Files + +#### `src/Apollo.Application/ToDos/FuzzyTimeParser.cs`: Add new `[GeneratedRegex]` patterns and corresponding parse branches + +The current parser has only 3 regex patterns (`InRelativeTimeRegex`, `TomorrowRegex`, `NextWeekRegex`). Add new patterns for each supported expression type. Each new pattern should follow the existing convention of using `[GeneratedRegex]` source generators and `RegexOptions.IgnoreCase | RegexOptions.Compiled`. Add corresponding match-and-compute logic in `TryParseFuzzyTime` following the same `Result` return pattern. + +#### Tests + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: Add test methods for each new pattern + +Add tests following the existing naming convention (e.g., `TryParseFuzzyTimeWithTomorrowAtTimeReturnsFutureDate`). Cover: +- `TryParseFuzzyTimeWithTomorrowAtTimeReturnsCorrectDateTime` — "tomorrow at 3pm", "tomorrow at 15:00" +- `TryParseFuzzyTimeWithAtTimeReturnsTodayAtTime` — "at 3pm", "at 15:00", "at noon", "at midnight" +- `TryParseFuzzyTimeWithTonightReturnsEveningTime` — "tonight" +- `TryParseFuzzyTimeWithThisMorningReturnsMorningTime` — "this morning" +- `TryParseFuzzyTimeWithThisAfternoonReturnsAfternoonTime` — "this afternoon" +- `TryParseFuzzyTimeWithThisEveningReturnsEveningTime` — "this evening" +- `TryParseFuzzyTimeWithNoonReturnsTodayAtNoon` — "noon" +- `TryParseFuzzyTimeWithMidnightReturnsTomorrowMidnight` — "midnight" +- `TryParseFuzzyTimeWithNextDayOfWeekReturnsCorrectDate` — "next Monday", "next Friday" +- `TryParseFuzzyTimeWithOnDayOfWeekReturnsCorrectDate` — "on Tuesday", "on Wednesday" +- `TryParseFuzzyTimeWithDayOfWeekAtTimeReturnsCorrectDateTime` — "on Friday at 3pm", "next Monday at 9am" +- `TryParseFuzzyTimeWithInAnHourReturnsOneHourFromNow` — "in an hour" +- `TryParseFuzzyTimeWithInHalfAnHourReturnsThirtyMinutesFromNow` — "in half an hour" +- `TryParseFuzzyTimeWithDurationWithoutPrefixReturnsFutureDate` — "5 minutes", "30 minutes", "2 hours" +- `TryParseFuzzyTimeWithEndOfDayReturnsEndOfDay` — "end of day", "eod" +- `TryParseFuzzyTimeWithEndOfWeekReturnsEndOfWeek` — "end of week" + +--- + +### Step 2 - Create Consolidated Time Parsing Service + +Extract the duplicated parse-then-fallback logic from `ToDoPlugin`, `RemindersPlugin`, and `ApolloGrpcService` into a single shared service. This service implements the full parsing pipeline: FuzzyTimeParser → C# TryParseExact with common formats → C# TryParse with InvariantCulture → (future) LLM fallback. + +#### Files + +#### `src/Apollo.Core/ToDos/ITimeParsingService.cs`: Create new interface + +Define the interface for the consolidated time parsing service: +```csharp +public interface ITimeParsingService +{ + Task> ParseTimeAsync(string input, string? userTimeZoneId = null, CancellationToken cancellationToken = default); +} +``` +This interface abstracts all parsing strategies behind a single method. The `userTimeZoneId` parameter handles timezone-aware conversion (replacing the duplicated `ConvertToUtcAsync` methods). The return value is always UTC. + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Create new implementation + +Implement the parsing pipeline: +1. Try `IFuzzyTimeParser.TryParseFuzzyTime()` — handles natural language patterns +2. Try `DateTime.TryParseExact()` with an array of common format strings (ISO 8601 variants, "h:mm tt", "hh:mm tt", "HH:mm", "MMM d", "MMMM d", etc.) using `CultureInfo.InvariantCulture` +3. Try `DateTime.TryParse()` with `CultureInfo.InvariantCulture` and `DateTimeStyles.None` as a general fallback +4. Return `Result.Fail()` with a helpful error message listing supported format examples + +Include the timezone conversion logic currently duplicated in `ToDoPlugin.ConvertToUtcAsync` and `RemindersPlugin.ConvertToUtcAsync`. The service should look up the user's timezone from `IPersonStore` using the `userTimeZoneId` parameter and convert local times to UTC. Inject `IPersonStore`, `IFuzzyTimeParser`, and `TimeProvider`. + +#### `src/Apollo.Application/ServiceCollectionExtension.cs`: Register ITimeParsingService + +Add `services.AddScoped();` to the DI registration. Scoped because it uses `IPersonStore` which is scoped. + +#### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: Create comprehensive tests + +Test the full pipeline: +- `ParseTimeAsyncWithFuzzyTimeReturnsParsedUtcDateTime` — verifies FuzzyTimeParser is tried first +- `ParseTimeAsyncWithIso8601ReturnsUtcDateTime` — "2025-12-31T10:00:00" +- `ParseTimeAsyncWithCommonTimeFormatReturnsUtcDateTime` — "3:00 PM", "15:00" +- `ParseTimeAsyncWithDateTimeReturnsParsedDateTime` — "December 31, 2025" +- `ParseTimeAsyncWithInvalidInputReturnsFailure` — "not a time at all" +- `ParseTimeAsyncWithUserTimeZoneConvertsToUtc` — verify timezone conversion using mocked IPersonStore +- `ParseTimeAsyncWithoutUserTimeZoneAssumesUtc` — verify behavior when no timezone is provided +- `ParseTimeAsyncWithUnspecifiedKindTreatsAsUserLocal` — verify DateTimeKind.Unspecified is treated as user-local when timezone is known + +--- + +### Step 3 - Create LLM Time Parsing Prompt (Last Resort Fallback) + +Create an efficient, minimal prompt that asks the LLM to convert a natural language time expression to ISO 8601 format. This is the last-resort fallback when all other parsing strategies fail. The prompt should be designed for minimal token usage and fast response. + +#### Files + +#### `src/Apollo.AI/Prompts/ApolloTimeParsing.yml`: Create new prompt template + +Create a minimal prompt that: +- Receives `current_datetime`, `user_timezone`, and the raw `time_expression` as template variables +- Instructs the LLM to return ONLY an ISO 8601 datetime string (no explanation) +- Includes a few-shot examples for clarity +- Is designed to be as short as possible for efficiency (small input/output) +- Specifies that if the expression cannot be parsed, return "UNPARSEABLE" + +#### `src/Apollo.Core/ToDos/ITimeParsingService.cs`: No additional changes needed + +The LLM fallback is an internal implementation detail of `TimeParsingService`. The interface remains the same. The service internally calls the AI agent when simpler methods fail. + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Add LLM fallback step + +After step 3 (C# TryParse) fails, add step 4: call the LLM with the `ApolloTimeParsing` prompt. Parse the LLM's ISO 8601 response with `DateTime.TryParse`. If the LLM returns "UNPARSEABLE" or the response can't be parsed, return `Result.Fail()`. Inject `IApolloAIAgent` (or a lighter LLM client) for this. + +#### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: Add LLM fallback tests + +- `ParseTimeAsyncWhenAllParsersFallsBackToLlmReturnsUtcDateTime` — mock the AI agent to return a valid ISO 8601 string +- `ParseTimeAsyncWhenLlmReturnsUnparseableReturnsFailure` — mock the AI agent to return "UNPARSEABLE" +- `ParseTimeAsyncWhenLlmReturnsInvalidFormatReturnsFailure` — mock the AI agent to return garbage +- `ParseTimeAsyncDoesNotCallLlmWhenFuzzyParserSucceeds` — verify the LLM is NOT called when earlier stages succeed (efficiency) +- `ParseTimeAsyncDoesNotCallLlmWhenCSharpParseSucceeds` — verify the LLM is NOT called when C# parsing succeeds + +--- + +### Step 4 - Refactor Consumers to Use TimeParsingService + +Replace the duplicated parsing logic in `ToDoPlugin`, `RemindersPlugin`, and `ApolloGrpcService` with calls to the new `ITimeParsingService`. Remove the private `ParseReminderDateAsync`, `ParseReminderTimeAsync`, `ParseReminderTime`, and `ConvertToUtcAsync` methods. + +#### Files + +#### `src/Apollo.Application/ToDos/ToDoPlugin.cs`: Replace ParseReminderDateAsync and ConvertToUtcAsync with ITimeParsingService + +Remove the private `ParseReminderDateAsync` method (lines 552-570) and `ConvertToUtcAsync` method (lines 572-591). Inject `ITimeParsingService` via the constructor. In `CreateToDoAsync`, replace the call to `ParseReminderDateAsync` with `await _timeParsingService.ParseTimeAsync(reminderDate, userTimeZoneId, cancellationToken)`. The `userTimeZoneId` should come from the person context already available in the plugin. + +#### `src/Apollo.Application/Reminders/RemindersPlugin.cs`: Replace ParseReminderTimeAsync and ConvertToUtcAsync with ITimeParsingService + +Remove the private `ParseReminderTimeAsync` method (lines 97-115) and `ConvertToUtcAsync` method (lines 117-136). Inject `ITimeParsingService` via the constructor. In `CreateReminderAsync`, replace the call to `ParseReminderTimeAsync` with `await _timeParsingService.ParseTimeAsync(reminderTime, userTimeZoneId, cancellationToken)`. + +#### `src/Apollo.GRPC/Service/ApolloGrpcService.cs`: Replace ParseReminderTime with ITimeParsingService + +Remove the private `ParseReminderTime` method (lines 105-131). Inject `ITimeParsingService` via the constructor. In `CreateReminderAsync`, replace the call to `ParseReminderTime` with `await _timeParsingService.ParseTimeAsync(reminderTime, null, cancellationToken)`. Note: the gRPC service currently doesn't do timezone-aware conversion, so pass `null` for `userTimeZoneId` to maintain backwards compatibility (or improve by passing the user's timezone if available from the request context). + +#### Tests + +#### `tests/Apollo.Application.Tests/ToDos/ToDoPluginTests.cs`: Update tests to verify ITimeParsingService usage + +Update existing tests that cover `CreateToDoAsync` to mock `ITimeParsingService` instead of `IFuzzyTimeParser`. Verify that `ParseTimeAsync` is called with the correct arguments. Remove any tests that directly tested the now-removed private parsing methods (if any were tested indirectly). + +#### `tests/Apollo.Application.Tests/Reminders/RemindersPluginTests.cs`: Update tests to verify ITimeParsingService usage + +Update existing tests that cover `CreateReminderAsync` to mock `ITimeParsingService`. Verify delegation to the shared service. + +#### `tests/Apollo.GRPC.Tests/Service/ApolloGrpcServiceTests.cs`: Update tests to verify ITimeParsingService usage + +Update existing tests for `CreateReminderAsync` to mock `ITimeParsingService`. Verify delegation and that timezone conversion behavior is preserved. + +--- + +### Step 5 - Update AI Prompt Files and Plugin Descriptions + +Fix the mismatch between what the LLM is told it can produce and what the parser actually accepts. Now that the parser supports more formats, update the prompts and plugin `[Description]` attributes to accurately reflect the expanded capabilities. + +#### Files + +#### `src/Apollo.AI/Prompts/ApolloToolPlanning.yml`: Update time format examples + +The existing examples already show `"tomorrow at 3pm"` (which will now be supported). Review and add more examples that demonstrate the newly supported formats, such as "tonight", "next Monday", "at 3pm", "in an hour". Ensure the examples accurately reflect what `TimeParsingService` can parse. + +#### `src/Apollo.AI/Prompts/ApolloToolCalling.yml`: Update time-related instructions + +The existing instructions reference natural language like "10 minutes from now", "on the 3rd". Update these to accurately list supported formats. Add guidance that the LLM should prefer simple, parseable formats (fuzzy time or ISO 8601) over complex natural language to avoid hitting the LLM fallback unnecessarily. + +#### `src/Apollo.Application/ToDos/ToDoPlugin.cs`: Update [Description] attribute on reminderDate parameter + +Change the `[Description]` from listing only `'in 10 minutes', 'in 2 hours', 'tomorrow', 'next week'` to include the newly supported formats. Example: `"Supports natural language like 'in 10 minutes', 'tomorrow at 3pm', 'next Monday', 'tonight', 'at noon', or ISO 8601 format."`. + +#### `src/Apollo.Application/Reminders/RemindersPlugin.cs`: Update [Description] attribute on reminderTime parameter + +Same change as ToDoPlugin — update the description to reflect all supported formats. + +#### Tests + +#### No new tests needed for this step + +The prompt changes are configuration/documentation. The `[Description]` attribute changes affect LLM behavior but are not testable in unit tests. Integration testing of prompt quality is out of scope for this issue. diff --git a/.plans/182-resolve-pr-review-comments.md b/.plans/182-resolve-pr-review-comments.md new file mode 100644 index 00000000..b66905e7 --- /dev/null +++ b/.plans/182-resolve-pr-review-comments.md @@ -0,0 +1,227 @@ +# Resolve PR #182 Review Comments + +## Description + +PR #182 ("✨ feat(reminders): expand time format flexibility and consolidate parsing") received 10 review +comments from GitHub Copilot. All comments identify real bugs or code quality issues in the new +`TimeParsingService`, `FuzzyTimeParser`, plugin whitespace validation, prompt accuracy, and timezone +handling. This plan addresses every comment with concrete code and test changes grouped into +parallelizable steps. + +### Comment Summary + +| # | File | Issue | +|---|------|-------| +| 1 | `ToDoPlugin.cs:42` | `IsNullOrEmpty` → `IsNullOrWhiteSpace` for `reminderDate` | +| 2 | `TimeParsingService.cs:153-154` | `FindSystemTimeZoneById` can throw; wrap in try/catch | +| 3 | `ApolloToolCalling.yml:45` | "tomorrow morning" listed but not deterministically parsed | +| 4 | `TimeParsingService.cs:72` | Fuzzy results skip `ConvertToUtc`; user-local times treated as UTC | +| 5 | `TimeParsingService.cs:27-29` | ISO formats with `Z`/offset use wrong `DateTimeStyles`; use `K` specifier | +| 6 | `ApolloToolPlanning.yml:93` | Same "tomorrow morning" issue as #3 | +| 7 | `RemindersPlugin.cs:35` | `IsNullOrEmpty` → `IsNullOrWhiteSpace` for `reminderTime` | +| 8 | `ApolloGrpcService.cs:73` | `ParseTimeAsync` called without user timezone | +| 9 | `TimeParsingService.cs:34-39` | Time-only formats produce DateTime with year 0001 | +| 10 | `FuzzyTimeParser.cs (TimeParserHelpers):333` | Bare hour 0–12 parsed as AM; restrict to 13–23 | + +## Steps + +### 1 - Fix whitespace validation in plugins (Comments 1, 7) + +Both `ToDoPlugin.CreateToDoAsync` and `RemindersPlugin.CreateReminderAsync` use +`string.IsNullOrEmpty` to check for missing time input. Whitespace-only strings like `" "` slip +through and hit the parsing service with a different error message. Change to `IsNullOrWhiteSpace`. + +### Files + +#### `src/Apollo.Application/ToDos/ToDoPlugin.cs`: Change `string.IsNullOrEmpty(reminderDate)` to `string.IsNullOrWhiteSpace(reminderDate)` on line 42 +**Reason:** Whitespace-only `reminderDate` should be treated as "no reminder" and not forwarded to +the parsing service where it would fail with a different error message. + +#### `src/Apollo.Application/Reminders/RemindersPlugin.cs`: Change `string.IsNullOrEmpty(reminderTime)` to `string.IsNullOrWhiteSpace(reminderTime)` on line 35 +**Reason:** Same issue — whitespace-only `reminderTime` should be treated as missing input and +return the explicit "Reminder time is required" error. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/ToDoPluginTests.cs`: `CreateToDoAsyncWithWhitespaceReminderDateDoesNotCallTimeParsingServiceAsync` +**Reason:** Verify that a whitespace-only `reminderDate` is treated as no reminder and the parsing +service is never called. + +#### `tests/Apollo.Application.Tests/Reminders/RemindersPluginTests.cs`: `CreateReminderAsyncWithWhitespaceTimeReturnsErrorAsync` +**Reason:** Verify that a whitespace-only `reminderTime` returns the "required" error immediately. + +--- + +### 2 - Apply timezone conversion to fuzzy parser results (Comment 4) + +`TimeParsingService.ParseTimeAsync` returns fuzzy parser results directly without calling +`ConvertToUtc`. For expressions like "tomorrow at 3pm" or "at 3pm", the parsed time is treated +as UTC rather than the user's local time. This causes reminders to be scheduled at the wrong time. + +### Files + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Wrap fuzzy result with `ConvertToUtc(fuzzyResult.Value, userTimeZoneId)` at line 72 +**Reason:** Fuzzy results for absolute clock times ("tomorrow at 3pm", "at noon", "tonight") need +the same timezone conversion as Steps 2-4. Change `return Result.Ok(fuzzyResult.Value)` to +`return Result.Ok(ConvertToUtc(fuzzyResult.Value, userTimeZoneId))`. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithFuzzyTimeAndUserTimezoneConvertsToUtcAsync` +**Reason:** Verify that when a fuzzy result is returned and a user timezone is provided, the result +is converted from user-local to UTC. + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithFuzzyTimeAndNoTimezoneReturnsUtcDirectlyAsync` +**Reason:** Verify that when no timezone is provided, fuzzy results are returned as-is (treated as +UTC). + +--- + +### 3 - Fix ISO 8601 format specifiers for timezone-aware parsing (Comment 5) + +The `ExactFormats` array uses literal `Z` and `zzz` format specifiers with `DateTimeStyles.None`, +which does not correctly interpret timezone offsets. Replace with `K` specifier and use +`DateTimeStyles.RoundtripKind` so `Z` is correctly parsed as UTC and offsets are preserved. + +### Files + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Replace ISO format specifiers and add `RoundtripKind` +**Reason:** Replace `"yyyy-MM-ddTHH:mm:ssZ"` and `"yyyy-MM-ddTHH:mm:ss.fffffffZ"` with +`"yyyy-MM-ddTHH:mm:ssK"` and `"yyyy-MM-ddTHH:mm:ss.fffffffK"`. Remove the `"yyyy-MM-ddTHH:mm:sszzz"` +entry (now covered by `K`). Change `DateTimeStyles.None` to `DateTimeStyles.RoundtripKind` in the +`TryParseExact` call so that `Z` is correctly interpreted as UTC kind. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithIso8601ZSuffixReturnsUtcKindAsync` +**Reason:** Verify that `"2025-12-31T10:00:00Z"` is parsed with `DateTimeKind.Utc` and not +double-converted through timezone logic. + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithIso8601OffsetConvertsToUtcAsync` +**Reason:** Verify that `"2025-12-31T10:00:00-05:00"` is correctly converted to +`2025-12-31T15:00:00Z`. + +--- + +### 4 - Handle time-only formats by anchoring to reference date (Comment 9) + +Time-only format strings like `"h:mm tt"`, `"HH:mm"`, `"h tt"` in `ExactFormats` produce a +`DateTime` with the default date (year 0001). These should be removed from `ExactFormats` since +they are already handled by the fuzzy parser's `ClockTimeParser` (which anchors to today's date). +Alternatively, detect time-only results and anchor them to `now.Date`. + +### Files + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Remove time-only formats from `ExactFormats` array (lines 34-38: `"h:mm tt"`, `"hh:mm tt"`, `"HH:mm"`, `"h tt"`) +**Reason:** Time-only inputs are already handled by the fuzzy parser in Step 1 (via +`ClockTimeParser`). Leaving them in `ExactFormats` creates a fallthrough path that produces +dates in year 0001. If the fuzzy parser misses a time-only input, it should fall through to +the LLM rather than produce a nonsensical date. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithTimeOnlyInputIsHandledByFuzzyParserAsync` +**Reason:** Verify that `"3:00 PM"` is handled by the fuzzy parser (mocked to succeed with a +sensible date) and not by the exact format fallback. Update existing test +`ParseTimeAsyncWithCommonTimeFormatReturnsUtcDateTime` to reflect the new behavior. + +--- + +### 5 - Guard `FindSystemTimeZoneById` against invalid timezone IDs (Comment 2) + +`ConvertUnspecifiedToUtc` calls `TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneId)` which +can throw `TimeZoneNotFoundException` or `InvalidTimeZoneException`. This violates the +`Result` error-handling convention. + +### Files + +#### `src/Apollo.Application/ToDos/TimeParsingService.cs`: Wrap `FindSystemTimeZoneById` in try/catch, falling back to UTC +**Reason:** Invalid timezone IDs should not cause unhandled exceptions. On failure, treat the +parsed time as UTC (same behavior as when no timezone is provided). Catch both +`TimeZoneNotFoundException` and `InvalidTimeZoneException`. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithInvalidTimezoneIdFallsBackToUtcAsync` +**Reason:** Verify that an invalid timezone ID like `"Invalid/Timezone"` does not throw an +exception and instead falls back to treating the time as UTC. + +#### `tests/Apollo.Application.Tests/ToDos/TimeParsingServiceTests.cs`: `ParseTimeAsyncWithEmptyTimezoneIdTreatsAsUtcAsync` +**Reason:** Verify that an empty or whitespace timezone ID is treated the same as null (UTC). + +--- + +### 6 - Restrict bare hour parsing to 13–23 range (Comment 10) + +`TimeParserHelpers.ParseTimeOfDay` accepts bare integers 0–23 as hours. A bare `"3"` becomes +03:00 AM, which is almost certainly not what the user meant when saying "at 3" or "tomorrow at 3". +Restrict bare hour parsing to the unambiguous 13–23 range; hours 0–12 should require AM/PM. + +### Files + +#### `src/Apollo.Application/ToDos/Parsers/TimeParserHelpers.cs`: Change `hour is >= 0 and <= 23` to `hour is >= 13 and <= 23` +**Reason:** Bare hours 0–12 are ambiguous (could be AM or PM). Restricting to 13–23 ensures +only unambiguous 24-hour values are accepted. Ambiguous inputs like "at 3" will fail the fuzzy +parser and fall through to the LLM which can use conversation context to disambiguate. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: `TryParseFuzzyTimeWithBareHour3DoesNotParseAs3AmAsync` +**Reason:** Verify that "at 3" (bare hour < 13) is NOT parsed by the fuzzy parser (returns failure). + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: `TryParseFuzzyTimeWithBareHour15ParsesAs1500Async` +**Reason:** Verify that "at 15" (bare hour ≥ 13) IS parsed as 15:00. + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: Update existing "tomorrow at 3" test expectations +**Reason:** Tests that rely on "tomorrow at 3" resolving to 03:00 need to be updated — they should +now expect a failure (bare 3 is ambiguous) while "tomorrow at 3pm" and "tomorrow at 15" still work. + +--- + +### 7 - Add "tomorrow morning/afternoon/evening" to `TomorrowParser` (Comments 3, 6) + +The prompts list "tomorrow morning" as a supported format, but no deterministic parser handles it. +Rather than removing it from the prompts (which reduces user-friendliness), add support to +`TomorrowParser` for "tomorrow morning", "tomorrow afternoon", and "tomorrow evening" using the +same time-of-day mappings as `TimeOfDayAliasParser`. + +### Files + +#### `src/Apollo.Application/ToDos/Parsers/TomorrowParser.cs`: Add a new regex pattern `TomorrowPeriodPattern` matching `tomorrow morning|afternoon|evening` +**Reason:** "tomorrow morning" is a natural expression users will say. Adding deterministic +support avoids unnecessary LLM fallback calls and latency. Map to the same hours as +`TimeOfDayAliasParser`: morning=09:00, afternoon=14:00, evening=18:00. + +### Tests + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: `TryParseFuzzyTimeWithTomorrowMorningReturnsNextDay9Am` +**Reason:** Verify "tomorrow morning" resolves to tomorrow at 09:00 UTC. + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: `TryParseFuzzyTimeWithTomorrowAfternoonReturnsNextDay2Pm` +**Reason:** Verify "tomorrow afternoon" resolves to tomorrow at 14:00 UTC. + +#### `tests/Apollo.Application.Tests/ToDos/FuzzyTimeParserTests.cs`: `TryParseFuzzyTimeWithTomorrowEveningReturnsNextDay6Pm` +**Reason:** Verify "tomorrow evening" resolves to tomorrow at 18:00 UTC. + +--- + +### 8 - Pass user timezone in `ApolloGrpcService.CreateReminderAsync` (Comment 8) + +The gRPC service calls `ParseTimeAsync(request.ReminderTime)` without passing the user's timezone, +so user-local clock times like "at 3pm" are interpreted as UTC. The `Person` object is available +via `userContext.Person!` and has a `TimeZoneId` property. + +### Files + +#### `src/Apollo.GRPC/Service/ApolloGrpcService.cs`: Extract person's timezone and pass to `ParseTimeAsync` +**Reason:** Without the timezone, all user-local time expressions are interpreted as UTC, +causing reminders to fire at the wrong time. Derive timezone from +`person.TimeZoneId?.ToString()` (or equivalent) and pass as the second argument. + +### Tests + +#### `tests/Apollo.GRPC.Tests/ApolloGrpcServiceTests.cs`: `CreateReminderAsyncPassesUserTimezoneToTimeParsingServiceAsync` +**Reason:** Verify that when a person has a timezone set, it is forwarded to `ParseTimeAsync`. + +#### `tests/Apollo.GRPC.Tests/ApolloGrpcServiceTests.cs`: `CreateReminderAsyncWithNoTimezonePassesNullToTimeParsingServiceAsync` +**Reason:** Verify that when a person has no timezone, `null` is passed (default behavior). diff --git a/src/Apollo.AI/Apollo.AI.csproj b/src/Apollo.AI/Apollo.AI.csproj index bd1a4933..c0683cbb 100644 --- a/src/Apollo.AI/Apollo.AI.csproj +++ b/src/Apollo.AI/Apollo.AI.csproj @@ -10,7 +10,7 @@ - + diff --git a/src/Apollo.AI/ApolloAIAgent.cs b/src/Apollo.AI/ApolloAIAgent.cs index 381fc72e..40e87058 100644 --- a/src/Apollo.AI/ApolloAIAgent.cs +++ b/src/Apollo.AI/ApolloAIAgent.cs @@ -17,18 +17,19 @@ public sealed class ApolloAIAgent( private const string ResponsePromptName = "ApolloResponse"; private const string ReminderPromptName = "ApolloReminder"; private const string DailyPlanningPromptName = "ApolloDailyPlanning"; + private const string TimeParsingPromptName = "ApolloTimeParsing"; public IAIRequestBuilder CreateRequest() { return new AIRequestBuilder(config, templateProcessor, logger); } - public IAIRequestBuilder CreateToolPlanningRequest( + public async Task CreateToolPlanningRequestAsync( IEnumerable messages, string userTimezone, string activeTodos) { - var prompt = promptLoader.Load(ToolPlanningPromptName); + var prompt = await promptLoader.LoadAsync(ToolPlanningPromptName); var currentDateTime = DateTimeOffset.Now.ToString("yyyy-MM-ddTHH:mm:sszzz", System.Globalization.CultureInfo.InvariantCulture); var variables = new Dictionary @@ -46,12 +47,12 @@ public IAIRequestBuilder CreateToolPlanningRequest( .WithTemplateVariables(variables); } - public IAIRequestBuilder CreateResponseRequest( + public async Task CreateResponseRequestAsync( IEnumerable messages, string actionsSummary, string userTimezone) { - var prompt = promptLoader.Load(ResponsePromptName); + var prompt = await promptLoader.LoadAsync(ResponsePromptName); var variables = new Dictionary { @@ -66,12 +67,12 @@ public IAIRequestBuilder CreateResponseRequest( .WithTemplateVariables(variables); } - public IAIRequestBuilder CreateReminderRequest( + public async Task CreateReminderRequestAsync( string userTimezone, string currentTime, string reminderItems) { - var prompt = promptLoader.Load(ReminderPromptName); + var prompt = await promptLoader.LoadAsync(ReminderPromptName); var variables = new Dictionary { @@ -85,13 +86,13 @@ public IAIRequestBuilder CreateReminderRequest( .WithTemplateVariables(variables); } - public IAIRequestBuilder CreateDailyPlanRequest( + public async Task CreateDailyPlanRequestAsync( string userTimezone, string currentTime, string activeTodos, int taskCount) { - var prompt = promptLoader.Load(DailyPlanningPromptName); + var prompt = await promptLoader.LoadAsync(DailyPlanningPromptName); var variables = new Dictionary { @@ -107,4 +108,24 @@ public IAIRequestBuilder CreateDailyPlanRequest( .WithJsonMode(enabled: true) .WithTemplateVariables(variables); } + + public async Task CreateTimeParsingRequestAsync( + string timeExpression, + string userTimezone, + string currentDateTime) + { + var prompt = await promptLoader.LoadAsync(TimeParsingPromptName); + + var variables = new Dictionary + { + ["current_datetime"] = currentDateTime, + ["user_timezone"] = userTimezone + }; + + return CreateRequest() + .FromPromptDefinition(prompt) + .WithMessage(new ChatMessageDTO(Enums.ChatRole.User, timeExpression, DateTime.UtcNow)) + .WithToolCalling(enabled: false) + .WithTemplateVariables(variables); + } } diff --git a/src/Apollo.AI/ApolloReminderMessageGenerator.cs b/src/Apollo.AI/ApolloReminderMessageGenerator.cs index 0005ef82..569ea9e4 100644 --- a/src/Apollo.AI/ApolloReminderMessageGenerator.cs +++ b/src/Apollo.AI/ApolloReminderMessageGenerator.cs @@ -45,8 +45,8 @@ public async Task> GenerateReminderMessageAsync( var offset = timeZoneInfo.GetUtcOffset(utcNow); var localTime = new DateTimeOffset(utcNow, TimeSpan.Zero).ToOffset(offset); - var requestBuilder = apolloAIAgent - .CreateReminderRequest( + var requestBuilder = await apolloAIAgent + .CreateReminderRequestAsync( timeZoneId, localTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), taskList diff --git a/src/Apollo.AI/IApolloAI.cs b/src/Apollo.AI/IApolloAI.cs index c2438eec..24d1564a 100644 --- a/src/Apollo.AI/IApolloAI.cs +++ b/src/Apollo.AI/IApolloAI.cs @@ -1,3 +1,6 @@ namespace Apollo.AI; +/// +/// Marker interface for Apollo AI components +/// public interface IApolloAI; diff --git a/src/Apollo.AI/IApolloAIAgent.cs b/src/Apollo.AI/IApolloAIAgent.cs index 866f0a30..4dee69c2 100644 --- a/src/Apollo.AI/IApolloAIAgent.cs +++ b/src/Apollo.AI/IApolloAIAgent.cs @@ -10,24 +10,29 @@ public interface IApolloAIAgent /// IAIRequestBuilder CreateRequest(); - IAIRequestBuilder CreateToolPlanningRequest( + Task CreateToolPlanningRequestAsync( IEnumerable messages, string userTimezone, string activeTodos); - IAIRequestBuilder CreateResponseRequest( + Task CreateResponseRequestAsync( IEnumerable messages, string actionsSummary, string userTimezone); - IAIRequestBuilder CreateReminderRequest( + Task CreateReminderRequestAsync( string userTimezone, string currentTime, string reminderItems); - IAIRequestBuilder CreateDailyPlanRequest( + Task CreateDailyPlanRequestAsync( string userTimezone, string currentTime, string activeTodos, int taskCount); + + Task CreateTimeParsingRequestAsync( + string timeExpression, + string userTimezone, + string currentDateTime); } diff --git a/src/Apollo.AI/Prompts/ApolloTimeParsing.yml b/src/Apollo.AI/Prompts/ApolloTimeParsing.yml new file mode 100644 index 00000000..38c6fd11 --- /dev/null +++ b/src/Apollo.AI/Prompts/ApolloTimeParsing.yml @@ -0,0 +1,19 @@ +temperature: 0.0 +systemPrompt: > + Convert the time expression to ISO 8601 format (yyyy-MM-ddTHH:mm:ss). + + Current datetime: {current_datetime} + User timezone: {user_timezone} + + Rules: + - Output ONLY the ISO 8601 string, nothing else. + - Interpret the expression relative to the current datetime. + - If the expression cannot be interpreted as a date/time, output exactly: UNPARSEABLE + - Use the user's timezone for interpretation, output in that timezone. + + Examples: + "next thursday" -> 2025-01-02T09:00:00 + "day after tomorrow at 5pm" -> 2025-12-28T17:00:00 + "this coming saturday morning" -> 2025-12-27T09:00:00 + "two weeks from now" -> 2026-01-09T14:30:00 + "buy groceries" -> UNPARSEABLE diff --git a/src/Apollo.AI/Prompts/ApolloToolCalling.yml b/src/Apollo.AI/Prompts/ApolloToolCalling.yml index 673ee31e..e591738f 100644 --- a/src/Apollo.AI/Prompts/ApolloToolCalling.yml +++ b/src/Apollo.AI/Prompts/ApolloToolCalling.yml @@ -38,23 +38,49 @@ systemPrompt: > get_timezone: Use when user asks what their current timezone is + + When specifying a time for reminders or todos, pass it as-is in natural language. Supported formats include: + - Relative: "in 10 minutes", "in 2 hours", "in half an hour", "in an hour", "in 3 days" + - Bare durations: "5 minutes", "2 hours" + - Day references: "tomorrow", "tomorrow at 3pm" + - Time of day: "at 3pm", "at 9:00 AM", "at 14:30" + - Named times: "tonight", "this morning", "this afternoon", "this evening", "noon", "midnight" + - Day of week: "next Monday", "on Friday", "next week" + - End of period: "end of day", "eod", "end of week" + - ISO 8601: "2025-12-31T10:00:00" + Prefer simple, parseable formats over complex natural language. If the user's phrasing is unusual, + simplify it to one of the forms above rather than passing it verbatim. + + Remind me to brush my teeth in 10 minutes User wants a simple reminder notification - create_reminder with text "Brush my teeth" and time 10 minutes from now + create_reminder with text "Brush my teeth" and time "in 10 minutes" + + + + Remind me to check the oven at noon + User wants a reminder at a named time + create_reminder with text "Check the oven" and time "noon" + + + + Remind me to call back tonight + User wants a reminder this evening + create_reminder with text "Call back" and time "tonight" - I have a doctor's appointment on the 3rd + I have a doctor's appointment next Monday User has an appointment (a task with a deadline) - create_todo with text "Doctor's appointment" and due date on the next 3rd, plus a reminder + create_todo with text "Doctor's appointment" and reminderDate "next Monday" I have a paper that's due in a month, but I want to get started on it next week User has a task with a due date and wants a reminder to start early - create_todo with text "Complete paper" and due date 1 month from now, plus reminder "Start on paper" for 1 week from now + create_todo with text "Complete paper" and due date "in a month", plus reminder "Start on paper" for "next week" diff --git a/src/Apollo.AI/Prompts/ApolloToolPlanning.yml b/src/Apollo.AI/Prompts/ApolloToolPlanning.yml index 152d27d6..6bd23f6e 100644 --- a/src/Apollo.AI/Prompts/ApolloToolPlanning.yml +++ b/src/Apollo.AI/Prompts/ApolloToolPlanning.yml @@ -86,6 +86,19 @@ systemPrompt: > A todo CAN have a reminder attached, but a reminder does NOT create a todo unless the user explicitly wants task tracking. + + When specifying reminderDate or reminderTime, use any of the following supported formats: + - Relative durations: "in 10 minutes", "in 2 hours", "in 3 days", "in half an hour", "in an hour" + - Bare durations: "5 minutes", "2 hours", "3 days" + - Day references: "tomorrow", "tomorrow at 3pm", "tomorrow morning" + - Time of day: "at 3pm", "at 14:30", "at 9:00 AM" + - Named times: "tonight", "this morning", "this afternoon", "this evening", "noon", "midnight" + - Day of week: "next Monday", "on Friday", "next week" + - End of period: "end of day", "eod", "end of week" + - ISO 8601: "2025-12-31T10:00:00" + Prefer simple parseable formats. Never guess a time if the user has not specified one. + + { "tool_calls": [ @@ -117,6 +130,31 @@ systemPrompt: > {"tool_calls":[{"plugin_name":"ToDos","function_name":"create_todo","arguments":{"description":"Call mom","reminderDate":"tomorrow at 3pm"}}]} + + Remind me to take my meds tonight + {"tool_calls":[{"plugin_name":"Reminders","function_name":"create_reminder","arguments":{"message":"Take meds","reminderTime":"tonight"}}]} + + + + Add "submit report" to my todos with a reminder at noon + {"tool_calls":[{"plugin_name":"ToDos","function_name":"create_todo","arguments":{"description":"Submit report","reminderDate":"noon"}}]} + + + + Remind me to call the dentist next Monday + {"tool_calls":[{"plugin_name":"Reminders","function_name":"create_reminder","arguments":{"message":"Call the dentist","reminderTime":"next Monday"}}]} + + + + Remind me to check email in an hour + {"tool_calls":[{"plugin_name":"Reminders","function_name":"create_reminder","arguments":{"message":"Check email","reminderTime":"in an hour"}}]} + + + + Add "wrap up weekly review" with a reminder end of day + {"tool_calls":[{"plugin_name":"ToDos","function_name":"create_todo","arguments":{"description":"Wrap up weekly review","reminderDate":"end of day"}}]} + + Add "finish report" with high priority and high energy {"tool_calls":[{"plugin_name":"ToDos","function_name":"create_todo","arguments":{"description":"Finish report","priority":"high","energy":"high"}}]} diff --git a/src/Apollo.AI/Prompts/IPromptLoader.cs b/src/Apollo.AI/Prompts/IPromptLoader.cs index 182da26a..27b89237 100644 --- a/src/Apollo.AI/Prompts/IPromptLoader.cs +++ b/src/Apollo.AI/Prompts/IPromptLoader.cs @@ -2,6 +2,5 @@ namespace Apollo.AI.Prompts; public interface IPromptLoader { - PromptDefinition Load(string promptName); Task LoadAsync(string promptName, CancellationToken ct = default); } diff --git a/src/Apollo.AI/Prompts/PromptDefinition.cs b/src/Apollo.AI/Prompts/PromptDefinition.cs index fcf49350..f4f995b6 100644 --- a/src/Apollo.AI/Prompts/PromptDefinition.cs +++ b/src/Apollo.AI/Prompts/PromptDefinition.cs @@ -2,6 +2,6 @@ namespace Apollo.AI.Prompts; public sealed record PromptDefinition { - public double Temperature { get; init; } = 0.7; + public double Temperature { get; init; } = 0.1; public string SystemPrompt { get; init; } = ""; } diff --git a/src/Apollo.AI/Prompts/PromptLoader.cs b/src/Apollo.AI/Prompts/PromptLoader.cs index d989cdb2..1d5c8736 100644 --- a/src/Apollo.AI/Prompts/PromptLoader.cs +++ b/src/Apollo.AI/Prompts/PromptLoader.cs @@ -14,21 +14,6 @@ public sealed class PromptLoader(string? promptsDirectory = null) : IPromptLoade .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); - public PromptDefinition Load(string promptName) - { - return _cache.GetOrAdd(promptName, name => - { - var filePath = Path.Combine(_promptsDirectory, $"{name}.yml"); - if (!File.Exists(filePath)) - { - throw new FileNotFoundException($"Prompt file not found: {filePath}"); - } - - var yaml = File.ReadAllText(filePath); - return _deserializer.Deserialize(yaml); - }); - } - public async Task LoadAsync(string promptName, CancellationToken ct = default) { if (_cache.TryGetValue(promptName, out var cached)) diff --git a/src/Apollo.AI/Prompts/PromptTemplateProcessor.cs b/src/Apollo.AI/Prompts/PromptTemplateProcessor.cs index 1031ab60..5b4c8ce8 100644 --- a/src/Apollo.AI/Prompts/PromptTemplateProcessor.cs +++ b/src/Apollo.AI/Prompts/PromptTemplateProcessor.cs @@ -19,15 +19,9 @@ public interface IPromptTemplateProcessor /// public sealed class PromptTemplateProcessor : IPromptTemplateProcessor { - /// public string Process(string templateText, IDictionary variables) { - if (string.IsNullOrEmpty(templateText)) - { - return templateText; - } - - if (variables == null || variables.Count == 0) + if (string.IsNullOrEmpty(templateText) || variables == null || variables.Count == 0) { return templateText; } diff --git a/src/Apollo.AI/Requests/AIRequestResult.cs b/src/Apollo.AI/Requests/AIRequestResult.cs index 0fed1cc4..ea8f35e6 100644 --- a/src/Apollo.AI/Requests/AIRequestResult.cs +++ b/src/Apollo.AI/Requests/AIRequestResult.cs @@ -18,11 +18,9 @@ public sealed record AIRequestResult public bool HasToolCalls => ToolCalls.Count > 0; - public IEnumerable SuccessfulToolCalls => - ToolCalls.Where(tc => tc.Success); + public IEnumerable SuccessfulToolCalls => ToolCalls.Where(tc => tc.Success); - public IEnumerable FailedToolCalls => - ToolCalls.Where(tc => !tc.Success); + public IEnumerable FailedToolCalls => ToolCalls.Where(tc => !tc.Success); public string FormatActionsSummary() { diff --git a/src/Apollo.AI/Tooling/ToolPlanValidator.cs b/src/Apollo.AI/Tooling/ToolPlanValidator.cs index 27ee7f60..ce98c064 100644 --- a/src/Apollo.AI/Tooling/ToolPlanValidator.cs +++ b/src/Apollo.AI/Tooling/ToolPlanValidator.cs @@ -83,9 +83,12 @@ public static ToolPlanValidationResult Validate(ToolPlan plan, ToolPlanValidatio private static bool HasRequiredArguments(MethodInfo method, IDictionary arguments, out List missing) { missing = []; - var argumentLookup = arguments is null - ? new Dictionary(StringComparer.OrdinalIgnoreCase) - : new Dictionary(arguments, StringComparer.OrdinalIgnoreCase); + var argumentLookup = arguments switch + { + null => new(StringComparer.OrdinalIgnoreCase), + _ => new Dictionary(arguments, StringComparer.OrdinalIgnoreCase) + }; + foreach (var parameter in method.GetParameters()) { if (parameter.ParameterType == typeof(CancellationToken)) diff --git a/src/Apollo.Application/Conversations/ProcessIncomingMessageCommand.cs b/src/Apollo.Application/Conversations/ProcessIncomingMessageCommand.cs index 95da6f5f..9ae04ffa 100644 --- a/src/Apollo.Application/Conversations/ProcessIncomingMessageCommand.cs +++ b/src/Apollo.Application/Conversations/ProcessIncomingMessageCommand.cs @@ -31,7 +31,7 @@ public sealed record ProcessIncomingMessageCommand(PersonId PersonId, Content Co public sealed class ProcessIncomingMessageCommandHandler( IApolloAIAgent apolloAIAgent, IConversationStore conversationStore, - IFuzzyTimeParser fuzzyTimeParser, + ITimeParsingService timeParsingService, ILogger logger, IMediator mediator, IPersonStore personStore, @@ -96,8 +96,8 @@ private async Task ProcessWithAIAsync(Conversation conversation, Person var toolPlanningMessages = ConversationHistoryBuilder.BuildForToolPlanning(conversation, activeTodosSnapshot.TodoIds); // Phase 1: Tool Planning (JSON output) - var toolPlanResult = await apolloAIAgent - .CreateToolPlanningRequest(toolPlanningMessages, userTimezone, activeTodosSnapshot.Summary) + var toolPlanResult = await (await apolloAIAgent + .CreateToolPlanningRequestAsync(toolPlanningMessages, userTimezone, activeTodosSnapshot.Summary)) .ExecuteAsync(cancellationToken); var toolPlan = new ToolPlan(); @@ -148,8 +148,8 @@ private async Task ProcessWithAIAsync(Conversation conversation, Person ConversationLogs.ActionsTaken(logger, person.Id.Value, [actionsSummary]); - var responseResult = await apolloAIAgent - .CreateResponseRequest(responseMessages, actionsSummary, userTimezone) + var responseResult = await (await apolloAIAgent + .CreateResponseRequestAsync(responseMessages, actionsSummary, userTimezone)) .ExecuteAsync(cancellationToken); return !responseResult.Success @@ -159,8 +159,8 @@ private async Task ProcessWithAIAsync(Conversation conversation, Person private Dictionary CreatePlugins(Person person) { - var toDoPlugin = new ToDoPlugin(mediator, personStore, fuzzyTimeParser, timeProvider, personConfig, person.Id); - var remindersPlugin = new RemindersPlugin(mediator, personStore, fuzzyTimeParser, timeProvider, personConfig, person.Id); + var toDoPlugin = new ToDoPlugin(mediator, personStore, timeParsingService, personConfig, person.Id); + var remindersPlugin = new RemindersPlugin(mediator, personStore, timeParsingService, personConfig, person.Id); var personPlugin = new PersonPlugin(personStore, personConfig, person.Id); return new Dictionary(StringComparer.OrdinalIgnoreCase) diff --git a/src/Apollo.Application/Reminders/RemindersPlugin.cs b/src/Apollo.Application/Reminders/RemindersPlugin.cs index 5619d1f7..634a2d78 100644 --- a/src/Apollo.Application/Reminders/RemindersPlugin.cs +++ b/src/Apollo.Application/Reminders/RemindersPlugin.cs @@ -16,24 +16,29 @@ namespace Apollo.Application.Reminders; public sealed class RemindersPlugin( IMediator mediator, IPersonStore personStore, - IFuzzyTimeParser fuzzyTimeParser, - TimeProvider timeProvider, + ITimeParsingService timeParsingService, PersonConfig personConfig, PersonId personId) { public const string PluginName = "Reminders"; [KernelFunction("create_reminder")] - [Description("Creates a one-time reminder notification. Use this for ephemeral reminders like 'take a break', 'check the oven', 'stand up and stretch' - things that don't need to be tracked as tasks. For persistent tasks that should appear in a todo list, use ToDos.create_todo instead. Supports fuzzy times like 'in 10 minutes', 'in 2 hours', 'tomorrow', or ISO 8601 format.")] + [Description("Creates a one-time reminder notification. Use this for ephemeral reminders like 'take a break', 'check the oven', 'stand up and stretch' - things that don't need to be tracked as tasks. For persistent tasks that should appear in a todo list, use ToDos.create_todo instead. Supports a wide range of time expressions including 'in 10 minutes', 'tomorrow at 3pm', 'tonight', 'next Monday', 'noon', 'end of day', or ISO 8601 format.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0046:Convert to conditional expression", Justification = "Maintains better code readability")] public async Task CreateReminderAsync( [Description("What to remind the user about (e.g., 'take a break', 'check the oven')")] string message, - [Description("When to send the reminder. Supports fuzzy formats like 'in 10 minutes', 'in 2 hours', 'tomorrow', 'next week', or ISO 8601 format (e.g., 2025-12-31T10:00:00).")] string reminderTime, + [Description("When to send the reminder. Supports: 'in 10 minutes', 'in 2 hours', 'in half an hour', 'in an hour', 'tomorrow', 'tomorrow at 3pm', 'at 3pm', 'tonight', 'this morning', 'this afternoon', 'this evening', 'noon', 'midnight', 'next Monday', 'on Friday', 'next week', 'end of day', 'eod', 'end of week', or ISO 8601 (e.g., 2025-12-31T10:00:00).")] string reminderTime, CancellationToken cancellationToken = default) { try { - var parsedTime = await ParseReminderTimeAsync(reminderTime, cancellationToken); + if (string.IsNullOrWhiteSpace(reminderTime)) + { + return "Failed to create reminder: Reminder time is required."; + } + + var userTimeZoneId = await GetUserTimeZoneIdAsync(cancellationToken); + var parsedTime = await timeParsingService.ParseTimeAsync(reminderTime, userTimeZoneId, cancellationToken); if (parsedTime.IsFailed) { return $"Failed to create reminder: {parsedTime.GetErrorMessages()}"; @@ -94,44 +99,11 @@ private static Result TryParseReminderId(string reminderId) : Result.Ok(reminderGuid); } - private async Task> ParseReminderTimeAsync(string? reminderTime, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(reminderTime)) - { - return Result.Fail("Reminder time is required."); - } - - // First, try to parse as fuzzy time (e.g., "in 10 minutes") - var fuzzyResult = fuzzyTimeParser.TryParseFuzzyTime(reminderTime, timeProvider.GetUtcNow().UtcDateTime); - if (fuzzyResult.IsSuccess) - { - return Result.Ok(fuzzyResult.Value); - } - - // Fall back to ISO 8601 parsing - return !DateTime.TryParse(reminderTime, out var parsedDate) - ? Result.Fail("Invalid reminder time format. Use fuzzy time like 'in 10 minutes' or ISO 8601 format like 2025-12-31T10:00:00.") - : await ConvertToUtcAsync(parsedDate, cancellationToken); - } - - private async Task> ConvertToUtcAsync(DateTime parsedDate, CancellationToken cancellationToken) + private async Task GetUserTimeZoneIdAsync(CancellationToken cancellationToken) { - // Get user's timezone or use default var personResult = await personStore.GetAsync(personId, cancellationToken); - var timeZoneId = personResult.IsSuccess && personResult.Value.TimeZoneId.HasValue + return personResult.IsSuccess && personResult.Value.TimeZoneId.HasValue ? personResult.Value.TimeZoneId.Value.Value : personConfig.DefaultTimeZoneId; - - var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); - - // Convert from user's local time to UTC - var reminder = parsedDate.Kind switch - { - DateTimeKind.Unspecified => TimeZoneInfo.ConvertTimeToUtc(parsedDate, timeZoneInfo), - DateTimeKind.Local => parsedDate.ToUniversalTime(), - _ => parsedDate - }; - - return Result.Ok(reminder); } } diff --git a/src/Apollo.Application/ServiceCollectionExtension.cs b/src/Apollo.Application/ServiceCollectionExtension.cs index 5431e114..3f37e223 100644 --- a/src/Apollo.Application/ServiceCollectionExtension.cs +++ b/src/Apollo.Application/ServiceCollectionExtension.cs @@ -11,12 +11,11 @@ public static class ServiceCollectionExtension public static IServiceCollection AddApplicationServices(this IServiceCollection services) { _ = services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); - services.TryAddScoped(); _ = services.AddTransient(_ => TimeProvider.System); - _ = services.AddSingleton(); + _ = services.AddScoped(); return services; } diff --git a/src/Apollo.Application/ToDos/AddReminderCommand.cs b/src/Apollo.Application/ToDos/AddReminderCommand.cs index b4a0419f..abe71a6b 100644 --- a/src/Apollo.Application/ToDos/AddReminderCommand.cs +++ b/src/Apollo.Application/ToDos/AddReminderCommand.cs @@ -34,15 +34,12 @@ public async Task> Handle(AddReminderCommand request, Cancellat } var createResult = await CreateAndLinkReminderAsync(toDoResult.Value, request.ReminderDate, jobResult.Value, cancellationToken); - if (createResult.IsFailed) + return (await EnsureJobExistsAsync(request.ReminderDate, cancellationToken), createResult) switch { - return createResult; - } - - var ensureResult = await EnsureJobExistsAsync(request.ReminderDate, cancellationToken); - return ensureResult.IsFailed - ? Result.Fail($"Reminder created but failed to ensure job exists: {ensureResult.GetErrorMessages()}") - : createResult; + (_, { IsFailed: true } createFailed) => createFailed, + ({ IsFailed: true } ensureFailed, _) => Result.Fail($"Reminder created but failed to ensure job exists: {ensureFailed.GetErrorMessages()}"), + _ => createResult + }; } catch (Exception ex) { diff --git a/src/Apollo.Application/ToDos/CreateReminderCommand.cs b/src/Apollo.Application/ToDos/CreateReminderCommand.cs index 7613f1cb..a20bdc20 100644 --- a/src/Apollo.Application/ToDos/CreateReminderCommand.cs +++ b/src/Apollo.Application/ToDos/CreateReminderCommand.cs @@ -34,6 +34,7 @@ public async Task> Handle(CreateReminderCommand request, Cancel request.ReminderDate, jobResult.Value, cancellationToken); + if (createResult.IsFailed) { return createResult; diff --git a/src/Apollo.Application/ToDos/FuzzyTimeParser.cs b/src/Apollo.Application/ToDos/FuzzyTimeParser.cs index 38f33a80..8d909c9d 100644 --- a/src/Apollo.Application/ToDos/FuzzyTimeParser.cs +++ b/src/Apollo.Application/ToDos/FuzzyTimeParser.cs @@ -1,5 +1,4 @@ -using System.Globalization; -using System.Text.RegularExpressions; +using System.Reflection; using Apollo.Core.ToDos; @@ -8,30 +7,22 @@ namespace Apollo.Application.ToDos; /// -/// Parses fuzzy/relative time expressions into absolute DateTime values. -/// Supports patterns like: -/// - "in N minute(s)", "in N min(s)", "in Nm" -/// - "in N hour(s)", "in N hr(s)", "in Nh" -/// - "in N day(s)", "in Nd" -/// - "in N week(s)", "in Nw" -/// - "tomorrow" -/// - "next week" +/// +/// Orchestrates time expression parsing by delegating to a chain of +/// implementations that are discovered +/// automatically at startup via . +/// +/// +/// To add a new time format, create a class that: +/// 1. Implements +/// 2. Is decorated with +/// 3. Has a public parameterless constructor +/// +/// No changes to this class or any registration code are required. /// -public partial class FuzzyTimeParser : IFuzzyTimeParser +public sealed class FuzzyTimeParser : IFuzzyTimeParser { - // Pattern: "in N unit" where unit can be minutes, hours, days, weeks with various abbreviations - [GeneratedRegex( - @"^\s*in\s+(?\d+)\s*(?minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w)\s*$", - RegexOptions.IgnoreCase | RegexOptions.Compiled)] - private static partial Regex InDurationPattern(); - - // Pattern: "tomorrow" - [GeneratedRegex(@"^\s*tomorrow\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled)] - private static partial Regex TomorrowPattern(); - - // Pattern: "next week" - [GeneratedRegex(@"^\s*next\s+week\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled)] - private static partial Regex NextWeekPattern(); + private static readonly IReadOnlyList Parsers = DiscoverParsers(); public Result TryParseFuzzyTime(string input, DateTime referenceTimeUtc) { @@ -40,47 +31,33 @@ public Result TryParseFuzzyTime(string input, DateTime referenceTimeUt return Result.Fail("Input is empty or whitespace"); } - // Ensure reference time is UTC var reference = referenceTimeUtc.Kind == DateTimeKind.Utc ? referenceTimeUtc : DateTime.SpecifyKind(referenceTimeUtc, DateTimeKind.Utc); - // Try "in N unit" pattern - var durationMatch = InDurationPattern().Match(input); - if (durationMatch.Success) + foreach (var parser in Parsers) { - var number = int.Parse(durationMatch.Groups["number"].Value, CultureInfo.InvariantCulture); - var unit = durationMatch.Groups["unit"].Value.ToLowerInvariant(); - - var duration = unit switch + var result = parser.TryParse(input, reference); + if (result.IsSuccess) { - "m" or "min" or "mins" or "minute" or "minutes" => TimeSpan.FromMinutes(number), - "h" or "hr" or "hrs" or "hour" or "hours" => TimeSpan.FromHours(number), - "d" or "day" or "days" => TimeSpan.FromDays(number), - "w" or "week" or "weeks" => TimeSpan.FromDays(number * 7), - _ => TimeSpan.Zero - }; - - if (duration > TimeSpan.Zero) - { - return Result.Ok(DateTime.SpecifyKind(reference.Add(duration), DateTimeKind.Utc)); + return result; } } - // Try "tomorrow" pattern - if (TomorrowPattern().IsMatch(input)) - { - var tomorrow = reference.AddDays(1); - return Result.Ok(DateTime.SpecifyKind(tomorrow, DateTimeKind.Utc)); - } - - // Try "next week" pattern - if (NextWeekPattern().IsMatch(input)) - { - var nextWeek = reference.AddDays(7); - return Result.Ok(DateTime.SpecifyKind(nextWeek, DateTimeKind.Utc)); - } - return Result.Fail($"Could not parse '{input}' as a fuzzy time expression"); } + + private static List DiscoverParsers() + { + var parserType = typeof(ITimeExpressionParser); + var attributeType = typeof(TimeExpressionParserAttribute); + + return [.. Assembly.GetExecutingAssembly() + .GetTypes() + .Where(t => t.IsClass + && !t.IsAbstract + && parserType.IsAssignableFrom(t) + && t.IsDefined(attributeType, inherit: false)) + .Select(t => (ITimeExpressionParser)Activator.CreateInstance(t)!)]; + } } diff --git a/src/Apollo.Application/ToDos/GetDailyPlanQuery.cs b/src/Apollo.Application/ToDos/GetDailyPlanQuery.cs index 2c96ca72..ce72bfc1 100644 --- a/src/Apollo.Application/ToDos/GetDailyPlanQuery.cs +++ b/src/Apollo.Application/ToDos/GetDailyPlanQuery.cs @@ -107,13 +107,13 @@ private async Task> GenerateAIPlanAsync(List todos, stri var todosFormatted = FormatToDosForAI(todos); // Call AI agent - var aiResult = await aiAgent - .CreateDailyPlanRequest( + var aiResult = await (await aiAgent + .CreateDailyPlanRequestAsync( timeZoneId, localTime, todosFormatted, dailyTaskCount - ) + )) .ExecuteAsync(cancellationToken); if (!aiResult.Success) diff --git a/src/Apollo.Application/ToDos/Parsers/ClockTimeParser.cs b/src/Apollo.Application/ToDos/Parsers/ClockTimeParser.cs new file mode 100644 index 00000000..348a8748 --- /dev/null +++ b/src/Apollo.Application/ToDos/Parsers/ClockTimeParser.cs @@ -0,0 +1,54 @@ +using System.Text.RegularExpressions; + +using Apollo.Core.ToDos; + +using FluentResults; + +namespace Apollo.Application.ToDos.Parsers; + +/// +/// Handles explicit clock-time expressions: "at 3pm", "at 15:00", "at noon", "at midnight". +/// Also handles standalone "noon" and "midnight". +/// +[TimeExpressionParser] +public sealed partial class ClockTimeParser : ITimeExpressionParser +{ + [GeneratedRegex( + @"^\s*at\s+(?