Meddy fresh source reviews 3; no material findings files 101 commits 3

Pre-push review: Meddy development tooling and Swift cleanup

Repeatable simulator commands, repository guidance, strict SwiftLint, and compiler-warning cleanup.

At a glance

  • Three fresh full-diff local reviews (reuse, quality, efficiency) found no material source defects. Both branches remain clean and unchanged draft PRs.

  • Correction: the pre-push-review skill does not require an external Claude call. A globally installed CLI was mistaken for a Meddy-specific reviewer. No repository reviewer configuration or GitHub integration was found. The directly approved CLI attempt exited during MCP configuration validation with no review result; further external calls are paused.

Verdict

Needs fixes — verification incomplete

Fresh source reviews found no material defects. Strict lint, whitespace, simulator builds and 199 domain cases pass. The latest full UI attempt logged all ten declared cases passing with zero failures, then stopped after 180 seconds without log progress (exit -15). Its bundle is unfinalized, so fix verification is incomplete: test run timed out. No owned runner remained to sample; the latest post-suite cause is unknown. Further UI validation must wait for the heavy slot. The draft remains published under the user exception.

Review findings

1 raised · 0 fixed · 1 skipped

Jump to findings →

Tests

Pass rate: 100% (199 of 199)

New tests: 0

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

Meddy now has one place to find development commands and guidance for future coding sessions. Its Swift files follow a checked style policy, and the Watch runtime uses the current application API.

Why it matters

Commands fail visibly when checks fail, and tests use simulators and synthetic stores. Cleanup makes the existing code easier to navigate without adding care features.

Key concepts

A Makefile names repeatable commands. A linter checks source conventions. Regression tests check that existing behavior still works.

Changes overview

The Makefile separates the development loop from full serial pre-push gates. AGENTS.md and development.md document destinations, isolated caches and test-store requirements. The lint config combines strict default rules with Prism opt-ins and practical SwiftUI size thresholds.

Implementation

Long service and view methods are split into focused helpers. Named edit/reminder values replace sprawling argument lists; fixtures retain their ModelContainer. Timer and Watch operations move into a synchronized-source-folder extension.

Trade-offs

Tests keep their real Apple runtime dependencies. Only two essential UI journeys form the inner-loop smoke target, while the full UI bundle remains a publication gate.

Deep dive

Reminder helpers retain the original scheduling order, cancellation checks, drained prior-writer task, absolute snooze deadlines and receipt semantics. Companion ownership validation keeps error ordering and version/lifecycle checks. Linear min selection preserves the original first-match ties.

Architecture impact

The service extension shares internal transaction and lookup helpers; no public, encoded or persisted API changes. Named edits keep every supplied field explicit, while fixture structs retain the persistent-store owner for the entire test.

Edge cases and completeness

The SwiftUI observation declaration retains a documented single-line redundant_discardable_let exception to avoid a known result-builder type-checking problem. Phone and Watch domain verification is complete. All ten UI case bodies logged passes, but the test command remained unfinished and its bundle unfinalized; the latest post-suite cause is unknown. Physical device behavior and account migration are outside this cleanup. The ecosystem registry only detects Swift Package runners, so native xcresult test data was converted to JUnit rather than invoking a nonexistent Package.swift.

Important changes — detailed

Makefile adds a serial simulator workflow

Makefile

Why it matters. Preserves exit status, cache isolation and full publication gates.

What to look at. run-xcode and pre-push

Takeaway. Use pipefail with tee and retain a unique result bundle per invocation.
Rationale. Apply recalled Swift Makefile conventions without physical install or reset targets.

Reminder helpers preserve existing delivery ordering

Meddy/Meddy/Services/ReminderService.swift

Why it matters. Avoids changing cancellation, receipt and snooze semantics during cleanup.

What to look at. deliverPlanned, medicationPlans, timerPlans

Takeaway. Extract complete operations while retaining the outer cancellation boundary.
Rationale. Reduce lint complexity without altering captured-action behavior.

Routine timer operations move into a focused extension

Meddy/Meddy/Services/RoutineSessionTimerService.swift

Why it matters. Improves navigation while sharing the same transaction/ownership helpers.

What to look at. timer and Watch import methods

Takeaway. Keep common save and identity checks in the same service.
Rationale. Split an oversized source/type without changing model schema.

Test fixtures explicitly retain their store owner

Meddy/MeddyTests/MeddySessionTests.swift

Why it matters. Avoids a known SwiftData orphan-context crash class.

What to look at. Fixture

Takeaway. Retain ModelContainer alongside model values returned from helpers.
Rationale. Apply recalled container-lifetime knowledge while replacing large tuples.

Watch runtime uses WKApplication

Meddy/MeddyWatch/RoundRuntime.swift

Why it matters. Removes the confirmed deprecated API compiler warning.

What to look at. start(deadline:)

Rationale. Use the SDK-declared replacement with the same active-state guard.

Key decisions

Keep the full native gate

Faster selected checks do not replace Apple-runtime domain tests or full UI acceptance at publication boundaries.

Document one narrow SwiftUI lint exception

Preserve the observation declaration that avoids the recalled result-builder regression; default rules remain enabled.

Do not add a framework just to silence metadata extraction

Watch and test targets without App Intents retain the Xcode metadata warning; the actual deprecated WatchKit API was fixed.

Review findings

SeverityAreaFindingResolution
majorFull UI gateTest command did not finish despite all ten case bodies logging passes.Preserve qualified evidence. Normal command completion remains required; no further UI run started.

Tests

Source: local run at 2026-10-07T00:18:18.412518+00:00 · snapshot 0965d675e0e1f86f4028a90b8003b34afbaf5212

Baseline: none

Execution: timed out (partial results) · JUnit: 2 files · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

Totals: 199 passed · 0 failed · 0 skipped · 0 errored · 0 flaky

New and removed tests

Derived by declaration name, from the diff (no baseline run).

No new or removed test declarations.

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base bcba6d9c71b0ce3770f101dabb9ffd99f1758d0e.

Dependents none found Changed Dependencies none found . Meddy/Meddy Meddy/Meddy/App Meddy/Meddy/Features Meddy/Meddy/Intents Meddy/Meddy/Models Meddy/Meddy/Services Meddy/MeddyTests Meddy/MeddyUITests Meddy/MeddyWatch Meddy/MeddyWatchTests Meddy/Shared/Companion Meddy/Shared/RoutineExecution Meddy/Shared/Scheduling Meddy/Shared/Snapshots MakefileMakefile Meddy/Meddy/ContentView.swiftMeddy/Meddy/ContentView.swift Meddy/Meddy/MyApp.swiftMeddy/Meddy/MyApp.swift Meddy/Meddy/App/AppEnvironment.swift…eddy/App/AppEnvironment.swift Meddy/Meddy/App/AppRootView.swift…y/Meddy/App/AppRootView.swift Meddy/Meddy/App/PhoneNavigation.swift…ddy/App/PhoneNavigation.swift Meddy/Meddy/Features/AsNeededLimitViews.swift…ures/AsNeededLimitViews.swift Meddy/Meddy/Features/CareEditors.swift…dy/Features/CareEditors.swift Meddy/Meddy/Features/ConsultationMarkdown.swift…es/ConsultationMarkdown.swift Meddy/Meddy/Features/LogicalDayEnvironment.swift…s/LogicalDayEnvironment.swift Meddy/Meddy/Features/LogicalDayPresentation.swift…/LogicalDayPresentation.swift Meddy/Meddy/Features/MedicationFollowupFields.swift…edicationFollowupFields.swift Meddy/Meddy/Features/MedicationPhoto.swift…eatures/MedicationPhoto.swift Meddy/Meddy/Features/MedicationScheduleFields.swift…edicationScheduleFields.swift Meddy/Meddy/Features/PhoneTimerControl.swift…tures/PhoneTimerControl.swift Meddy/Meddy/Features/ProfileViews.swift…y/Features/ProfileViews.swift Meddy/Meddy/Features/ReminderActions.swift…eatures/ReminderActions.swift Meddy/Meddy/Features/RoutineRunView.swift…Features/RoutineRunView.swift Meddy/Meddy/Features/RoutinesView.swift…y/Features/RoutinesView.swift Meddy/Meddy/Features/TodayRoutineSections.swift…es/TodayRoutineSections.swift Meddy/Meddy/Intents/RecordWakingUpIntent.swift…ts/RecordWakingUpIntent.swift Meddy/Meddy/Models/CareProfile.swift…eddy/Models/CareProfile.swift Meddy/Meddy/Models/Models.swift…ddy/Meddy/Models/Models.swift Meddy/Meddy/Models/RoutineModels.swift…dy/Models/RoutineModels.swift Meddy/Meddy/Models/WakeEvent.swift…/Meddy/Models/WakeEvent.swift Meddy/Meddy/Services/AsNeededLimitService.swift…es/AsNeededLimitService.swift Meddy/Meddy/Services/CloudSyncMonitor.swift…rvices/CloudSyncMonitor.swift Meddy/Meddy/Services/EditorTransaction.swift…vices/EditorTransaction.swift Meddy/Meddy/Services/MedicationFollowupService.swift…dicationFollowupService.swift Meddy/Meddy/Services/MedicationPhotoService.swift…/MedicationPhotoService.swift Meddy/Meddy/Services/MedicationService.swift…vices/MedicationService.swift Meddy/Meddy/Services/PhoneCompanionService.swift…s/PhoneCompanionService.swift Meddy/Meddy/Services/PhoneRoundAlertService.swift…/PhoneRoundAlertService.swift Meddy/Meddy/Services/ProfileAccess.swift…/Services/ProfileAccess.swift Meddy/Meddy/Services/ProfileMigration.swift…rvices/ProfileMigration.swift Meddy/Meddy/Services/ProfileService.swift…Services/ProfileService.swift Meddy/Meddy/Services/ReminderService.swift…ervices/ReminderService.swift Meddy/Meddy/Services/RoutineService.swift…Services/RoutineService.swift Meddy/Meddy/Services/RoutineSessionService.swift…s/RoutineSessionService.swift Meddy/Meddy/Services/RoutineSessionTimerService.swift…tineSessionTimerService.swift Meddy/Meddy/Services/ScheduleService.swift…ervices/ScheduleService.swift Meddy/Meddy/Services/TreatmentService.swift…rvices/TreatmentService.swift Meddy/Meddy/Services/WakeService.swift…dy/Services/WakeService.swift Meddy/MeddyTests/MeddyAsNeededLimitTests.swift…MeddyAsNeededLimitTests.swift Meddy/MeddyTests/MeddyCompanionStoreTests.swift…eddyCompanionStoreTests.swift Meddy/MeddyTests/MeddyDefinitionTests.swift…ts/MeddyDefinitionTests.swift Meddy/MeddyTests/MeddyEditorReviewTests.swift…/MeddyEditorReviewTests.swift Meddy/MeddyTests/MeddyExecutionTests.swift…sts/MeddyExecutionTests.swift Meddy/MeddyTests/MeddyFirstSliceTests.swift…ts/MeddyFirstSliceTests.swift Meddy/MeddyTests/MeddyFollowupTests.swift…ests/MeddyFollowupTests.swift Meddy/MeddyTests/MeddyLogicalDayTests.swift…ts/MeddyLogicalDayTests.swift Meddy/MeddyTests/MeddyMarkdownExportTests.swift…eddyMarkdownExportTests.swift Meddy/MeddyTests/MeddyMedicationPhotoTests.swift…ddyMedicationPhotoTests.swift Meddy/MeddyTests/MeddyOwnerTransferTests.swift…MeddyOwnerTransferTests.swift Meddy/MeddyTests/MeddyPhoneCompanionTests.swift…eddyPhoneCompanionTests.swift Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift…ddyPhoneRoundAlertTests.swift Meddy/MeddyTests/MeddyPhoneTimerControlTests.swift…yPhoneTimerControlTests.swift Meddy/MeddyTests/MeddyProfileIsolationTests.swift…dyProfileIsolationTests.swift Meddy/MeddyTests/MeddyProfileMigrationTests.swift…dyProfileMigrationTests.swift Meddy/MeddyTests/MeddyProfileRoutingTests.swift…eddyProfileRoutingTests.swift Meddy/MeddyTests/MeddyReminderServiceTests.swift…ddyReminderServiceTests.swift Meddy/MeddyTests/MeddyReminderTests.swift…ests/MeddyReminderTests.swift Meddy/MeddyTests/MeddyScheduleServiceTests.swift…ddyScheduleServiceTests.swift Meddy/MeddyTests/MeddyScheduleTests.swift…ests/MeddyScheduleTests.swift Meddy/MeddyTests/MeddySchemaTests.swift…yTests/MeddySchemaTests.swift Meddy/MeddyTests/MeddySessionTests.swift…Tests/MeddySessionTests.swift Meddy/MeddyTests/MeddySnoozeTests.swift…yTests/MeddySnoozeTests.swift Meddy/MeddyTests/MeddyTimedSessionTests.swift…/MeddyTimedSessionTests.swift Meddy/MeddyTests/MeddyWakeTests.swift…ddyTests/MeddyWakeTests.swift Meddy/MeddyUITests/MeddyEditorUITests.swift…ests/MeddyEditorUITests.swift Meddy/MeddyUITests/MeddyFirstSliceUITests.swift…/MeddyFirstSliceUITests.swift Meddy/MeddyUITests/MeddyProfileUITests.swift…sts/MeddyProfileUITests.swift Meddy/MeddyUITests/MeddyRoutineUITests.swift…sts/MeddyRoutineUITests.swift Meddy/MeddyUITests/MeddyWakeUITests.swift…ITests/MeddyWakeUITests.swift Meddy/MeddyWatch/ContentView.swift…/MeddyWatch/ContentView.swift Meddy/MeddyWatch/MeddyWatchApp.swift…eddyWatch/MeddyWatchApp.swift Meddy/MeddyWatch/RoundRuntime.swift…MeddyWatch/RoundRuntime.swift Meddy/MeddyWatch/WatchController.swift…dyWatch/WatchController.swift Meddy/MeddyWatchTests/MeddyWatchProfileTests.swift…/MeddyWatchProfileTests.swift Meddy/MeddyWatchTests/MeddyWatchTests.swift…chTests/MeddyWatchTests.swift Meddy/Shared/Companion/CompanionOwnership.swift…nion/CompanionOwnership.swift Meddy/Shared/Companion/CompanionTransport.swift…nion/CompanionTransport.swift Meddy/Shared/Companion/CompanionValues.swift…mpanion/CompanionValues.swift Meddy/Shared/RoutineExecution/ExecutionValues.swift…ecution/ExecutionValues.swift Meddy/Shared/RoutineExecution/TimerOperation.swift…xecution/TimerOperation.swift Meddy/Shared/Scheduling/AsNeededDoseLimits.swift…ling/AsNeededDoseLimits.swift Meddy/Shared/Scheduling/MedicationFollowup.swift…ling/MedicationFollowup.swift Meddy/Shared/Scheduling/MedicationScheduleEngine.swift…edicationScheduleEngine.swift Meddy/Shared/Scheduling/NotificationPlanner.swift…ing/NotificationPlanner.swift Meddy/Shared/Scheduling/RoutineScheduleEngine.swift…g/RoutineScheduleEngine.swift Meddy/Shared/Scheduling/ScheduleValues.swift…heduling/ScheduleValues.swift Meddy/Shared/Scheduling/TimingCue.swift…ed/Scheduling/TimingCue.swift Meddy/Shared/Scheduling/WakeAnchor.swift…d/Scheduling/WakeAnchor.swift Meddy/Shared/Snapshots/DefinitionEnums.swift…apshots/DefinitionEnums.swift Meddy/Shared/Snapshots/DefinitionValues.swift…pshots/DefinitionValues.swift Meddy/Shared/Snapshots/ProfileIdentity.swift…apshots/ProfileIdentity.swift Meddy/Shared/Snapshots/RecordingValues.swift…apshots/RecordingValues.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

101 files: 98 code · 3 docs. Click to expand.

Code (98)

.swiftlint.yml Added
diff --git a/.swiftlint.yml b/.swiftlint.ymlnew file mode 100644index 0000000..84e77e4--- /dev/null+++ b/.swiftlint.yml@@ -0,0 +1,146 @@+# Default rules plus Prism's opt-ins and SwiftUI size conventions; no global disabled rules.+included:+  - Meddy+excluded:+  - .build+  - .claude+  - .codex+  - build+  - DerivedData++opt_in_rules:+  - array_init+  - closure_end_indentation+  - closure_spacing+  - collection_alignment+  - contains_over_filter_count+  - contains_over_filter_is_empty+  - contains_over_first_not_nil+  - discouraged_object_literal+  - empty_collection_literal+  - enum_case_associated_values_count+  - explicit_init+  - fallthrough+  - fatal_error_message+  - file_name_no_space+  - first_where+  - flatmap_over_map_reduce+  - identical_operands+  - implicit_return+  - joined_default_parameter+  - last_where+  - literal_expression_end_indentation+  - lower_acl_than_parent+  - modifier_order+  - overridden_super_call+  - override_in_extension+  - prefer_zero_over_explicit_init+  - private_action+  - private_outlet+  - prohibited_super_call+  - redundant_nil_coalescing+  - sorted_first_last+  - static_operator+  - toggle_bool+  - unavailable_function+  - unowned_variable_capture+  - yoda_condition++line_length:+  warning: 140+  error: 200+  ignores_comments: true+  ignores_urls: true+  ignores_function_declarations: false+  ignores_interpolated_strings: true++type_body_length:+  warning: 700+  error: 1000++file_length:+  warning: 900+  error: 1500+  ignore_comment_only_lines: true++function_body_length:+  warning: 100+  error: 150++function_parameter_count:+  warning: 6+  error: 8++type_name:+  min_length: 3+  max_length:+    warning: 50+    error: 60++identifier_name:+  min_length:+    warning: 2+    error: 1+  max_length:+    warning: 50+    error: 60+  excluded:+    - id+    - x+    - y+    - z+    - i+    - j+    - k+    - m+    - n+    - r+    - g+    - b+    - ok+    - to+    - _++nesting:+  type_level:+    warning: 2+    error: 3+  function_level:+    warning: 3+    error: 5++cyclomatic_complexity:+  warning: 15+  error: 25+  ignores_case_statements: true++enum_case_associated_values_count:+  warning: 7+  error: 8++large_tuple:+  warning: 3+  error: 4++vertical_whitespace:+  max_empty_lines: 2++trailing_whitespace:+  ignores_empty_lines: true+  ignores_comments: true++colon:+  flexible_right_spacing: false+  apply_to_dictionaries: true++comma:+  severity: warning++force_cast:+  severity: warning++force_try:+  severity: warning++implicit_getter:+  severity: warning
Makefile Added
diff --git a/Makefile b/Makefilenew file mode 100644index 0000000..02d8415--- /dev/null+++ b/Makefile@@ -0,0 +1,108 @@+SHELL := /bin/bash+.SHELLFLAGS := -eu -o pipefail -c+.DEFAULT_GOAL := help+.NOTPARALLEL:++PROJECT := Meddy/Meddy.xcodeproj+CONFIG ?= Debug+XCODEBUILD ?= xcodebuild+DERIVED_DATA ?= $(CURDIR)/DerivedData/phone+WATCH_DERIVED_DATA ?= $(CURDIR)/DerivedData/watch+RESULTS_DIR ?= $(CURDIR)/build/results+PHONE_DESTINATION ?= platform=iOS Simulator,name=iPhone 18 Pro,OS=latest+WATCH_DESTINATION ?= platform=watchOS Simulator,name=Apple Watch SE 3 (44mm),OS=latest+DESTINATION_TIMEOUT ?= 20+DOMAIN_TEST ?= MeddyTests+UI_TEST ?=+UI_TEST_TIMEOUTS ?= YES+SWIFTLINT ?= swiftlint+SWIFTLINT_CACHE ?= $(CURDIR)/build/swiftlint-cache++.PHONY: lint lint-fix help build build-watch check simulators test-quick test-domain test-watch test-ui test-ui-smoke test-ui-all test pre-push++help: ## Show development commands; no build or device action+	@printf '%s\n' \+	  'Development:' \+	  '  build           Unsigned iPhone simulator build' \+	  '  build-watch     Unsigned Watch simulator build' \+	  '  test-quick      Phone domain tests, no UI (alias of test-domain)' \+	  '  test-domain     All phone domain tests; DOMAIN_TEST=Bundle/Suite narrows it' \+	  '  test-watch      Watch domain tests on a simulator' \+	  '  test-ui         One explicit UI_TEST=MeddyUITests/Class/Method or class' \+	  '  test-ui-smoke   Only the recording and whole-routine smoke journeys' \+	  'Before pushing:' \+	  '  pre-push        Strict lint, then serial phone domain, Watch domain, and phone UI gates' \+	  '  test            Alias of pre-push; not the development inner loop' \+	  'Utilities:' \+	  '  lint            Strict SwiftLint checks (no automatic edits)' \+	  '  lint-fix        Apply SwiftLint corrections; inspect the diff afterwards' \+	  '  check           Git whitespace validation' \+	  '  simulators      List available simulators without booting them' \+	  '' \+	  'Override PHONE_DESTINATION/WATCH_DESTINATION with platform=... Simulator,id=...' \+	  'Logs and unique .xcresult bundles: build/results; caches: DerivedData.' \+	  'Coordinate the shared heavy-work slot before builds/tests. No install/reset targets.'++# Keep failures visible through tee. No command or device discovery runs at Make parse time.+# Each invocation gets a new result directory; existing results are never removed.+define run-xcode+	@set -euo pipefail; \+	case "$(4)" in generic/platform=iOS\ Simulator|platform=iOS\ Simulator,*|generic/platform=watchOS\ Simulator|platform=watchOS\ Simulator,*) ;; *) printf '%s\n' 'Only simulator destinations are supported.' >&2; exit 2;; esac; \+	mkdir -p "$(RESULTS_DIR)"; \+	run_dir=$$(mktemp -d "$(RESULTS_DIR)/$(1).XXXXXX"); \+	printf 'Results: %s\n' "$$run_dir"; \+	"$(XCODEBUILD)" $(2) -project "$(PROJECT)" -scheme "$(3)" \+	  -configuration "$(CONFIG)" -destination-timeout "$(DESTINATION_TIMEOUT)" \+	  -destination "$(4)" -derivedDataPath "$(5)" \+	  -resultBundlePath "$$run_dir/Results.xcresult" \+	  CODE_SIGNING_ALLOWED=NO $(6) 2>&1 | tee "$$run_dir/xcodebuild.log"+endef++# Test actions use the shared schemes' MEDDY_TESTING=1 and isolated synthetic stores.+TEST_FLAGS := -parallel-testing-enabled NO -maximum-concurrent-test-simulator-destinations 1 -test-timeouts-enabled YES -default-test-execution-time-allowance 120 -maximum-test-execution-time-allowance 180+# UI-only diagnostic override; defaults remain unchanged until a bounded probe verifies the alternative.+UI_TEST_FLAGS := $(subst -test-timeouts-enabled YES,-test-timeouts-enabled $(UI_TEST_TIMEOUTS),$(TEST_FLAGS))++build: ## Build for the iPhone simulator without signing+	$(call run-xcode,build,build,Meddy,generic/platform=iOS Simulator,$(DERIVED_DATA),)++build-watch: ## Build for the Watch simulator without signing+	$(call run-xcode,build-watch,build,MeddyWatch,generic/platform=watchOS Simulator,$(WATCH_DERIVED_DATA),)++test-quick: test-domain ## Fast development loop; no UI runner++test-domain: ## Phone domain/service tests, optionally a specific suite+	@case "$(DOMAIN_TEST)" in MeddyTests|MeddyTests/*) ;; *) printf '%s\n' 'DOMAIN_TEST must select MeddyTests or a suite/method within it.' >&2; exit 2;; esac+	$(call run-xcode,test-domain,test,Meddy,$(PHONE_DESTINATION),$(DERIVED_DATA),$(TEST_FLAGS) "-only-testing:$(DOMAIN_TEST)")++test-watch: ## Watch domain tests; never a physical Watch+	$(call run-xcode,test-watch,test,MeddyWatch,$(WATCH_DESTINATION),$(WATCH_DERIVED_DATA),$(TEST_FLAGS) -only-testing:MeddyWatchTests)++test-ui: ## Require an explicit affected UI class or method+	@case "$(UI_TEST)" in MeddyUITests/?*) ;; *) printf '%s\n' 'Set UI_TEST=MeddyUITests/Class/Method (or Class); use test-ui-smoke for the two essential journeys.' >&2; exit 2;; esac+	$(call run-xcode,test-ui,test,Meddy,$(PHONE_DESTINATION),$(DERIVED_DATA),$(UI_TEST_FLAGS) "-only-testing:$(UI_TEST)")++test-ui-smoke: ## The two essential development UI journeys+	$(call run-xcode,test-ui-smoke,test,Meddy,$(PHONE_DESTINATION),$(DERIVED_DATA),$(UI_TEST_FLAGS) -only-testing:MeddyUITests/MeddyFirstSliceUITests/testNameOnlyCreationTakenAndUndoWithoutNotificationPermission -only-testing:MeddyUITests/MeddyRoutineUITests/testTwoUntimedSessionsKeepIndependentProgressThroughWholePhoneSequence)++test-ui-all: ## Full phone UI gate, reserved for pre-push verification+	$(call run-xcode,test-ui-all,test,Meddy,$(PHONE_DESTINATION),$(DERIVED_DATA),$(UI_TEST_FLAGS) -only-testing:MeddyUITests)++test: pre-push ## Full pre-push gates++pre-push: check lint ## Do not push automatically; full suites must pass before publication+	$(MAKE) test-domain DOMAIN_TEST=MeddyTests+	$(MAKE) test-watch+	$(MAKE) test-ui-all++lint: ## Strict SwiftLint policy with a local ignored cache+	"$(SWIFTLINT)" lint --strict --config .swiftlint.yml --cache-path "$(SWIFTLINT_CACHE)"++lint-fix: ## Explicit source corrections; always inspect the resulting diff+	"$(SWIFTLINT)" lint --fix --strict --config .swiftlint.yml --cache-path "$(SWIFTLINT_CACHE)"++check: ## Lightweight whitespace validator+	git diff --check++simulators: ## Read-only simulator discovery+	xcrun simctl list devices available
Meddy/Meddy/App/AppEnvironment.swift Modified
diff --git a/Meddy/Meddy/App/AppEnvironment.swift b/Meddy/Meddy/App/AppEnvironment.swiftindex e762a27..822b880 100644--- a/Meddy/Meddy/App/AppEnvironment.swift+++ b/Meddy/Meddy/App/AppEnvironment.swift@@ -3,29 +3,31 @@ import SwiftData  @MainActor enum AppEnvironment {-    private static var liveContainer: ModelContainer?-    static var schema: Schema {-        Schema([Purpose.self, Medication.self, Administration.self,-                Treatment.self, TreatmentCompletion.self, Routine.self,-                RoutineStep.self, RoutineRun.self, CareProfile.self, WakeEvent.self])-    }+  private static var liveContainer: ModelContainer?+  static var schema: Schema {+    Schema([+      Purpose.self, Medication.self, Administration.self,+      Treatment.self, TreatmentCompletion.self, Routine.self,+      RoutineStep.self, RoutineRun.self, CareProfile.self, WakeEvent.self+    ])+  } -    static func makeContainer(isolated: Bool) throws -> ModelContainer {-        if !isolated, let liveContainer { return liveContainer }-        let schema = self.schema-        let configuration = ModelConfiguration(-            schema: schema,-            isStoredInMemoryOnly: isolated,-            cloudKitDatabase: isolated ? .none : .private("iCloud.me.nore.ig.meddy")-        )-        let container = try ModelContainer(for: schema, configurations: [configuration])-        try ProfileMigration.bootstrap(container.mainContext)-        if !isolated { liveContainer = container }-        return container-    }+  static func makeContainer(isolated: Bool) throws -> ModelContainer {+    if !isolated, let liveContainer { return liveContainer }+    let schema = self.schema+    let configuration = ModelConfiguration(+      schema: schema,+      isStoredInMemoryOnly: isolated,+      cloudKitDatabase: isolated ? .none : .private("iCloud.me.nore.ig.meddy")+    )+    let container = try ModelContainer(for: schema, configurations: [configuration])+    try ProfileMigration.bootstrap(container.mainContext)+    if !isolated { liveContainer = container }+    return container+  } -    static var isTesting: Bool {-        ProcessInfo.processInfo.environment["MEDDY_TESTING"] == "1"-            || ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil-    }+  static var isTesting: Bool {+    ProcessInfo.processInfo.environment["MEDDY_TESTING"] == "1"+      || ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil+  } }
Meddy/Meddy/App/AppRootView.swift Modified
diff --git a/Meddy/Meddy/App/AppRootView.swift b/Meddy/Meddy/App/AppRootView.swiftindex a85ebe4..1f2e080 100644--- a/Meddy/Meddy/App/AppRootView.swift+++ b/Meddy/Meddy/App/AppRootView.swift@@ -1,78 +1,146 @@-import SwiftUI+import CoreData import SwiftData+import SwiftUI import UIKit-import CoreData  struct AppRootView: View {-    let container: ModelContainer-    @Environment(\.scenePhase) private var scenePhase-    @State private var selectedProfileID = ProfileIdentity.me-    @State private var navigation: PhoneNavigation-    @State private var cloud: CloudSyncMonitor-    @State private var roundAlerts: PhoneRoundAlertService-    @State private var reminders: ReminderService?-    @State private var companion: PhoneCompanionService?-    init(container: ModelContainer) {-        self.container = container-        _navigation = State(initialValue: PhoneNavigation(context: container.mainContext))-        _cloud = State(initialValue: CloudSyncMonitor(isolated: AppEnvironment.isTesting))-        _roundAlerts = State(initialValue: PhoneRoundAlertService(context: container.mainContext))+  let container: ModelContainer+  @Environment(\.scenePhase) private var scenePhase+  @State private var selectedProfileID = ProfileIdentity.me+  @State private var navigation: PhoneNavigation+  @State private var cloud: CloudSyncMonitor+  @State private var roundAlerts: PhoneRoundAlertService+  @State private var reminders: ReminderService?+  @State private var companion: PhoneCompanionService?+  init(container: ModelContainer) {+    self.container = container+    _navigation = State(initialValue: PhoneNavigation(context: container.mainContext))+    _cloud = State(initialValue: CloudSyncMonitor(isolated: AppEnvironment.isTesting))+    _roundAlerts = State(initialValue: PhoneRoundAlertService(context: container.mainContext))+  }+  var body: some View {+    VStack(spacing: 0) {+      ProfilePicker(selection: $selectedProfileID)+      if !AppEnvironment.isTesting {+        HStack {+          Text(cloud.message).font(.caption).foregroundStyle(.secondary)+          if cloud.needsAttention { Button("Retry") { cloud.refresh() }.font(.caption) }+        }.padding(.horizontal)+      }+      TimelineView(.everyMinute) { timeline in+        ContentView().id(selectedProfileID).environment(\.careProfileID, selectedProfileID)+          .environment(\.logicalDayNow, timeline.date)+          .environment(\.snoozeMedication) { reminders?.snoozeMedication($0) }+          .onChange(of: ScheduleCalendar.localDate(timeline.date, calendar: .current)) { _, _ in+            reminders?.refresh()+            companion?.publish()+          }+      }+    }+    .environment(navigation)+    .environment(\.careProfileID, selectedProfileID)+    .onChange(of: selectedProfileID) { _, new in+      if navigation.selectedRun?.profileID != new { navigation.selectedRun = nil }+      navigation.cancelPending()     }-    var body: some View {-        VStack(spacing: 0) {-            ProfilePicker(selection: $selectedProfileID)-            if !AppEnvironment.isTesting {-                HStack {-                    Text(cloud.message).font(.caption).foregroundStyle(.secondary)-                    if cloud.needsAttention { Button("Retry") { cloud.refresh() }.font(.caption) }-                }.padding(.horizontal)-            }-            TimelineView(.everyMinute) { timeline in-                ContentView().id(selectedProfileID).environment(\.careProfileID, selectedProfileID).environment(\.logicalDayNow, timeline.date)-                    .environment(\.snoozeMedication) { reminders?.snoozeMedication($0) }-                    .onChange(of: ScheduleCalendar.localDate(timeline.date, calendar: .current)) { _, _ in-                        reminders?.refresh(); companion?.publish()-                    }-            }+    .task {+      guard reminders == nil else { return }+      let manager = ReminderService(context: container.mainContext)+      manager.onError = { navigation.error = $0 }+      manager.openRun = { run in+        selectedProfileID = run.profileID ?? ProfileIdentity.me+        navigation.open(run)+      }+      let watch = PhoneCompanionService(context: container.mainContext)+      watch.onError = { navigation.error = $0 }+      watch.onOpen = { run in+        selectedProfileID = run.profileID ?? ProfileIdentity.me+        navigation.open(run)+      }+      navigation.localDeviceID = watch.deviceID+      roundAlerts.deviceID = watch.deviceID+      roundAlerts.onError = { navigation.error = $0 }+      manager.localDeviceID = watch.deviceID+      roundAlerts.setActive(scenePhase == .active)+      navigation.watchReachable = { watch.watchReachable }+      navigation.requestHandoff = { run, offline in+        do { try watch.takeOnPhone(run, offlineConfirmed: offline) } catch {+          navigation.error = error.localizedDescription+        }+      }+      watch.onHandoffWaiting = { id, waiting in+        if waiting {+          navigation.waitingHandoff.insert(id)+        } else {+          navigation.waitingHandoff.remove(id)         }-        .environment(navigation)-        .environment(\.careProfileID, selectedProfileID)-        .onChange(of: selectedProfileID) { _, new in if navigation.selectedRun?.profileID != new { navigation.selectedRun = nil }; navigation.cancelPending() }-        .task {-            guard reminders == nil else { return }-            let manager = ReminderService(context: container.mainContext)-            manager.onError = { navigation.error = $0 }-            manager.openRun = { run in selectedProfileID = run.profileID ?? ProfileIdentity.me; navigation.open(run) }-            let watch = PhoneCompanionService(context: container.mainContext)-            watch.onError = { navigation.error = $0 }; watch.onOpen = { run in selectedProfileID = run.profileID ?? ProfileIdentity.me; navigation.open(run) }-            navigation.localDeviceID = watch.deviceID-            roundAlerts.deviceID = watch.deviceID; roundAlerts.onError = { navigation.error = $0 }-            manager.localDeviceID = watch.deviceID-            roundAlerts.setActive(scenePhase == .active)-            navigation.watchReachable = { watch.watchReachable }-            navigation.requestHandoff = { run, offline in do { try watch.takeOnPhone(run, offlineConfirmed: offline) } catch { navigation.error = error.localizedDescription } }-            watch.onHandoffWaiting = { id, waiting in if waiting { navigation.waitingHandoff.insert(id) } else { navigation.waitingHandoff.remove(id) } }-            companion = watch; reminders = manager; if !AppEnvironment.isTesting { WakeIntentExecution.activeReminders = manager }; manager.refresh()-            #if DEBUG-            if AppEnvironment.isTesting, ProcessInfo.processInfo.environment["MEDDY_TEST_TIMER_CIRCLE"] == "1" {-                do {-                    let routine = try RoutineService(context: container.mainContext).createTimed(name: "Synthetic accessibility timer", rounds: 1, durationSeconds: 60)-                    navigation.start(routine, occurrence: nil)-                } catch { navigation.error = error.localizedDescription }-            }-            #endif+      }+      companion = watch+      reminders = manager+      if !AppEnvironment.isTesting { WakeIntentExecution.activeReminders = manager }+      manager.refresh()+      #if DEBUG+        if AppEnvironment.isTesting,+          ProcessInfo.processInfo.environment["MEDDY_TEST_TIMER_CIRCLE"] == "1" {+          do {+            let routine = try RoutineService(context: container.mainContext).createTimed(+              name: "Synthetic accessibility timer", rounds: 1, durationSeconds: 60)+            navigation.start(routine, occurrence: nil)+          } catch { navigation.error = error.localizedDescription }         }-        .onChange(of: scenePhase) { _, phase in roundAlerts.setActive(phase == .active); if phase == .active { reminders?.refresh(); companion?.publish(); cloud.refresh() } }-        .onReceive(NotificationCenter.default.publisher(for: UIApplication.significantTimeChangeNotification)) { _ in reminders?.refresh(); companion?.publish() }-        .onReceive(NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange)) { _ in do { try ProfileMigration.bootstrap(container.mainContext) } catch { navigation.error = error.localizedDescription }; reminders?.refresh(); companion?.publish() }-        .sheet(item: $navigation.selectedRun) { run in-            NavigationStack { RoutineRunView(run: run).toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { navigation.selectedRun = nil } } } }.environment(navigation).modelContainer(container)+      #endif+    }+    .onChange(of: scenePhase) { _, phase in+      roundAlerts.setActive(phase == .active)+      if phase == .active {+        reminders?.refresh()+        companion?.publish()+        cloud.refresh()+      }+    }+    .onReceive(+      NotificationCenter.default.publisher(for: UIApplication.significantTimeChangeNotification)+    ) { _ in+      reminders?.refresh()+      companion?.publish()+    }+    .onReceive(NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange)) { _ in+      do { try ProfileMigration.bootstrap(container.mainContext) } catch {+        navigation.error = error.localizedDescription+      }+      reminders?.refresh()+      companion?.publish()+    }+    .sheet(item: $navigation.selectedRun) { run in+      NavigationStack {+        RoutineRunView(run: run).toolbar {+          ToolbarItem(placement: .cancellationAction) {+            Button("Close") { navigation.selectedRun = nil }+          }         }-        .alert("Another session is incomplete", isPresented: Binding(get: { navigation.hasPending }, set: { if !$0 { navigation.cancelPending() } })) {-            Button("Return to saved session") { navigation.returnToSaved() }-            Button("Start selected session") { navigation.confirmSelected() }-            Button("Cancel", role: .cancel) { navigation.cancelPending() }-        } message: { Text("The saved session and real history are kept. Active timing pauses before opening the selected session.") }-        .alert("Meddy needs attention", isPresented: Binding(get: { navigation.error != nil }, set: { if !$0 { navigation.error = nil } })) { Button("OK") { navigation.error = nil } } message: { Text(navigation.error ?? "") }+      }.environment(navigation).modelContainer(container)+    }+    .alert(+      "Another session is incomplete",+      isPresented: Binding(+        get: { navigation.hasPending }, set: { if !$0 { navigation.cancelPending() } })+    ) {+      Button("Return to saved session") { navigation.returnToSaved() }+      Button("Start selected session") { navigation.confirmSelected() }+      Button("Cancel", role: .cancel) { navigation.cancelPending() }+    } message: {+      Text(+        "The saved session and real history are kept. Active timing pauses before opening the selected session."+      )+    }+    .alert(+      "Meddy needs attention",+      isPresented: Binding(+        get: { navigation.error != nil }, set: { if !$0 { navigation.error = nil } })+    ) {+      Button("OK") { navigation.error = nil }+    } message: {+      Text(navigation.error ?? "")     }+  } }
Meddy/Meddy/App/PhoneNavigation.swift Modified
diff --git a/Meddy/Meddy/App/PhoneNavigation.swift b/Meddy/Meddy/App/PhoneNavigation.swiftindex 35ee0cb..c40138a 100644--- a/Meddy/Meddy/App/PhoneNavigation.swift+++ b/Meddy/Meddy/App/PhoneNavigation.swift@@ -4,60 +4,103 @@ import SwiftData  @MainActor @Observable final class PhoneNavigation {-    struct StartRequest { var routine: Routine; var occurrence: RoutineOccurrence? }-    private let context: ModelContext-    var selectedRun: RoutineRun?-    var pendingStart: StartRequest?-    var pendingOpen: RoutineRun?-    var incomplete: RoutineRun?-    var error: String?-    var localDeviceID: String?-    var waitingHandoff: Set<UUID> = []-    var watchReachable: () -> Bool = { false }-    var requestHandoff: (RoutineRun, Bool) -> Void = { _, _ in }-    var hasPending: Bool { pendingStart != nil || pendingOpen != nil }-    init(context: ModelContext) { self.context = context }-    func start(_ routine: Routine, occurrence: RoutineOccurrence?) {-        do {-            _ = try ProfileAccess.owner(routine, context: context)-            let runs = try context.fetch(FetchDescriptor<RoutineRun>())-            if let id = occurrence?.existingRunID, let existing = runs.first(where: { $0.id == id && !$0.isDeleted }) { open(existing); return }-            if occurrence == nil, let existing = runs.first(where: { $0.routineID == routine.id && !$0.isDeleted && $0.parentRoutineRunID == nil && ["active", "paused", "needsReview"].contains($0.statusRaw) }) { open(existing); return }-            let request = StartRequest(routine: routine, occurrence: occurrence)-            if let other = unfinished(runs.filter { $0.profileID == routine.profileID }, except: nil) { incomplete = other; pendingStart = request }-            else { try create(request) }-        } catch { self.error = error.localizedDescription }+  struct StartRequest {+    var routine: Routine+    var occurrence: RoutineOccurrence?+  }+  private let context: ModelContext+  var selectedRun: RoutineRun?+  var pendingStart: StartRequest?+  var pendingOpen: RoutineRun?+  var incomplete: RoutineRun?+  var error: String?+  var localDeviceID: String?+  var waitingHandoff: Set<UUID> = []+  var watchReachable: () -> Bool = { false }+  var requestHandoff: (RoutineRun, Bool) -> Void = { _, _ in }+  var hasPending: Bool { pendingStart != nil || pendingOpen != nil }+  init(context: ModelContext) { self.context = context }+  func start(_ routine: Routine, occurrence: RoutineOccurrence?) {+    do {+      _ = try ProfileAccess.owner(routine, context: context)+      let runs = try context.fetch(FetchDescriptor<RoutineRun>())+      if let id = occurrence?.existingRunID,+        let existing = runs.first(where: { $0.id == id && !$0.isDeleted }) {+        open(existing)+        return+      }+      if occurrence == nil,+        let existing = runs.first(where: {+          $0.routineID == routine.id && !$0.isDeleted && $0.parentRoutineRunID == nil+            && ["active", "paused", "needsReview"].contains($0.statusRaw)+        }) {+        open(existing)+        return+      }+      let request = StartRequest(routine: routine, occurrence: occurrence)+      if let other = unfinished(runs.filter { $0.profileID == routine.profileID }, except: nil) {+        incomplete = other+        pendingStart = request+      } else {+        try create(request)+      }+    } catch { self.error = error.localizedDescription }+  }+  func open(_ run: RoutineRun) {+    do {+      _ = try ProfileAccess.owner(run, context: context)+      if let other = unfinished(+        try context.fetch(FetchDescriptor<RoutineRun>()).filter { $0.profileID == run.profileID },+        except: run.id) {+        incomplete = other+        pendingOpen = run+      } else {+        selectedRun = run+      }+    } catch { self.error = error.localizedDescription }+  }+  func returnToSaved() {+    selectedRun = incomplete+    cancelPending()+  }+  func confirmSelected() {+    do {+      if let incomplete { try pause(incomplete) }+      if let pendingStart { try create(pendingStart) } else { selectedRun = pendingOpen }+      cancelPending()+    } catch { self.error = error.localizedDescription }+  }+  func cancelPending() {+    pendingStart = nil+    pendingOpen = nil+    incomplete = nil+  }+  private func unfinished(_ runs: [RoutineRun], except id: UUID?) -> RoutineRun? {+    runs.first {+      $0.id != id && !$0.isDeleted && $0.parentRoutineRunID == nil+        && ["active", "paused", "needsReview"].contains($0.statusRaw)     }-    func open(_ run: RoutineRun) {-        do {-            _ = try ProfileAccess.owner(run, context: context)-            if let other = unfinished(try context.fetch(FetchDescriptor<RoutineRun>()).filter { $0.profileID == run.profileID }, except: run.id) { incomplete = other; pendingOpen = run }-            else { selectedRun = run }-        } catch { self.error = error.localizedDescription }+  }+  private func create(_ request: StartRequest) throws {+    if let occurrence = request.occurrence {+      selectedRun = try ScheduleService(context: context).startOccurrence(+        occurrence, routine: request.routine, deviceID: localDeviceID)+    } else {+      selectedRun = try RoutineSessionService(context: context).start(+        request.routine, deviceID: localDeviceID)     }-    func returnToSaved() { selectedRun = incomplete; cancelPending() }-    func confirmSelected() {-        do {-            if let incomplete { try pause(incomplete) }-            if let pendingStart { try create(pendingStart) }-            else { selectedRun = pendingOpen }-            cancelPending()-        } catch { self.error = error.localizedDescription }-    }-    func cancelPending() { pendingStart = nil; pendingOpen = nil; incomplete = nil }-    private func unfinished(_ runs: [RoutineRun], except id: UUID?) -> RoutineRun? {-        runs.first { $0.id != id && !$0.isDeleted && $0.parentRoutineRunID == nil && ["active", "paused", "needsReview"].contains($0.statusRaw) }-    }-    private func create(_ request: StartRequest) throws {-        if let occurrence = request.occurrence { selectedRun = try ScheduleService(context: context).startOccurrence(occurrence, routine: request.routine, deviceID: localDeviceID) }-        else { selectedRun = try RoutineSessionService(context: context).start(request.routine, deviceID: localDeviceID) }-    }-    private func pause(_ run: RoutineRun) throws {-        // Opening a different phone runner cannot mutate the Watch owner's checkpoint.-        guard run.executionDeviceID == nil || run.executionDeviceID == localDeviceID else { return }-        let service = RoutineSessionService(context: context)-        if run.timerCheckpointData != nil {-            if try service.timer(run).phase == .running { try service.changeTimer(run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .pause) }-        } else if ["active", "needsReview"].contains(run.statusRaw) { try service.pause(run, actionID: UUID()) }+  }+  private func pause(_ run: RoutineRun) throws {+    // Opening a different phone runner cannot mutate the Watch owner's checkpoint.+    guard run.executionDeviceID == nil || run.executionDeviceID == localDeviceID else { return }+    let service = RoutineSessionService(context: context)+    if run.timerCheckpointData != nil {+      if try service.timer(run).phase == .running {+        try service.changeTimer(+          run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .pause)+      }+    } else if ["active", "needsReview"].contains(run.statusRaw) {+      try service.pause(run, actionID: UUID())     }+  } }
Meddy/Meddy/ContentView.swift Modified
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex fea006d..ec54ece 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -1,504 +1,648 @@-import SwiftUI import SwiftData+import SwiftUI  struct ContentView: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(\.logicalDayNow) private var logicalTick-    private var logicalNow: Date { _ = logicalTick; return Date() }-    @Query(sort: \Medication.name) private var allMedications: [Medication]-    private var medications: [Medication] { allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \Administration.timestamp, order: .reverse) private var allEvents: [Administration]-    private var events: [Administration] { allEvents.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @State private var addingMedication = false-    @State private var showArchived = false-    @State private var error: String?-    @Environment(\.snoozeMedication) private var snoozeMedication-    @State private var editingTodayEvent: Administration?-    @State private var undoEvent: Administration?+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(\.logicalDayNow) private var logicalTick+  private var logicalNow: Date {+    _ = logicalTick+    return Date()+  }+  @Query(sort: \Medication.name) private var allMedications: [Medication]+  private var medications: [Medication] {+    allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \Administration.timestamp, order: .reverse) private var allEvents: [Administration]+  private var events: [Administration] {+    allEvents.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @State private var addingMedication = false+  @State private var showArchived = false+  @State private var error: String?+  @Environment(\.snoozeMedication) private var snoozeMedication+  @State private var editingTodayEvent: Administration?+  @State private var undoEvent: Administration? -    private var service: MedicationService { MedicationService(context: context) }-    private var active: [Medication] { medications.filter(\.isActive) }-    private var scheduled: [Medication] {-        active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.sorted { left, right in-            let a = (try? MedicationPresentation.result(left, now: logicalNow, context: context).next) ?? .distantFuture-            let b = (try? MedicationPresentation.result(right, now: logicalNow, context: context).next) ?? .distantFuture-            if a != b { return a < b }-            return left.name.localizedCaseInsensitiveCompare(right.name) == .orderedAscending-        }+  private var service: MedicationService { MedicationService(context: context) }+  private var active: [Medication] { medications.filter(\.isActive) }+  private var scheduled: [Medication] {+    active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.sorted { left, right in+      let leftNext =+        (try? MedicationPresentation.result(left, now: logicalNow, context: context).next)+        ?? .distantFuture+      let rightNext =+        (try? MedicationPresentation.result(right, now: logicalNow, context: context).next)+        ?? .distantFuture+      if leftNext != rightNext { return leftNext < rightNext }+      return left.name.localizedCaseInsensitiveCompare(right.name) == .orderedAscending     }+  } -    var body: some View {-        TabView {-            NavigationStack {-                List {-                    Section("Scheduled medications") {-                        ForEach(scheduled) { medication in-                            VStack(alignment: .leading) {-                                MedicationRow(medication: medication) { record(medication) }-                                if !medication.requirements.isEmpty { Text("Requirements").font(.caption); Text(medication.requirements).font(.caption) }-                                if !medication.administrationMethod.isEmpty { Text(medication.administrationMethod).font(.caption) }-                                if medication.remindersEnabled { Button("Remind me later") { snoozeMedication(medication.id) } }-                                if let result = try? MedicationPresentation.result(medication, now: logicalNow, context: context) {-                                    if result.cannotFitInWindow { Text("Remaining administrations cannot fit in today's window").font(.caption) }-                                    else if let next = result.next { Text("Next \(next.formatted(date: .abbreviated, time: .shortened))").font(.caption) }-                                    if let remaining = result.remainingToday {-                                        Text(remaining == 0 ? "Completed for today" : "\(result.takenToday) recorded · \(remaining) remaining today").font(.caption)-                                    }-                                }-                            }-                        }-                    }-                    TodayRoutineSections()-                    Section("As needed") {-                        ForEach(active.filter { $0.scheduleTypeRaw == MedicationScheduleType.asNeeded.rawValue }) { medication in-                            MedicationRow(medication: medication) { record(medication) }-                        }-                        Button("Add as-needed medication", systemImage: "plus") { addingMedication = true }-                    }-                    Section("Taken today") {-                        ForEach(events.filter { !$0.isDeleted && ScheduleCalendar.sameDay($0.timestamp, logicalNow, calendar: .current) }) { event in-                            Button { editingTodayEvent = event } label: {-                                VStack(alignment: .leading) {-                                    Text(event.medication?.name ?? "Medication")-                                    Text(event.timestamp, style: .time).font(.caption)-                                    Text(event.recordedDose.displayText).font(.caption).foregroundStyle(.secondary)-                                    if event.routineRunID != nil { Text("Routine-linked administration").font(.caption) }-                                }-                            }-                        }-                    }+  var body: some View {+    TabView {+      NavigationStack {+        List {+          Section("Scheduled medications") {+            ForEach(scheduled) { medication in+              VStack(alignment: .leading) {+                MedicationRow(medication: medication) { record(medication) }+                if !medication.requirements.isEmpty {+                  Text("Requirements").font(.caption)+                  Text(medication.requirements).font(.caption)                 }-                .navigationTitle("Today")-                .toolbar {-                    if let event = undoEvent, !event.isDeleted {-                        Button("Undo Taken") {-                            perform { try service.delete(event); undoEvent = nil }-                        }-                    }+                if !medication.administrationMethod.isEmpty {+                  Text(medication.administrationMethod).font(.caption)                 }-            }-            .tabItem { Label("Today", systemImage: "sun.max") }-            NavigationStack {-                List {-                    Picker("Show", selection: $showArchived) {-                        Text("Active").tag(false)-                        Text("Archived").tag(true)-                    }.pickerStyle(.segmented)-                    let displayed = medications.filter { $0.isActive != showArchived }-                    let groups = Dictionary(grouping: displayed) { $0.purpose?.name ?? "Ungrouped" }-                    ForEach(groups.keys.sorted(), id: \.self) { purpose in-                        Section(purpose) {-                            ForEach(groups[purpose] ?? []) { medication in-                                MedicationRow(medication: medication) { record(medication) }-                            }-                        }-                    }+                if medication.remindersEnabled {+                  Button("Remind me later") { snoozeMedication(medication.id) }                 }-                .navigationTitle("Medications")-                .toolbar {-                    Button("Add medication", systemImage: "plus") { addingMedication = true }-                    NavigationLink { CurrentMedicationsView() } label: { Label("Current Medications", systemImage: "list.bullet.rectangle") }+                if let result = try? MedicationPresentation.result(+                  medication, now: logicalNow, context: context) {+                  if result.cannotFitInWindow {+                    Text("Remaining administrations cannot fit in today's window").font(.caption)+                  } else if let next = result.next {+                    Text("Next \(next.formatted(date: .abbreviated, time: .shortened))").font(+                      .caption)+                  }+                  if let remaining = result.remainingToday {+                    Text(+                      remaining == 0+                        ? "Completed for today"+                        : "\(result.takenToday) recorded · \(remaining) remaining today"+                    ).font(.caption)+                  }                 }+              }+            }+          }+          TodayRoutineSections()+          Section("As needed") {+            ForEach(+              active.filter { $0.scheduleTypeRaw == MedicationScheduleType.asNeeded.rawValue }+            ) { medication in+              MedicationRow(medication: medication) { record(medication) }             }-            .tabItem { Label("Medications", systemImage: "pills") }-            NavigationStack {-                RoutinesView()+            Button("Add as-needed medication", systemImage: "plus") { addingMedication = true }+          }+          Section("Taken today") {+            ForEach(+              events.filter {+                !$0.isDeleted+                  && ScheduleCalendar.sameDay($0.timestamp, logicalNow, calendar: .current)+              }+            ) { event in+              Button {+                editingTodayEvent = event+              } label: {+                VStack(alignment: .leading) {+                  Text(event.medication?.name ?? "Medication")+                  Text(event.timestamp, style: .time).font(.caption)+                  Text(event.recordedDose.displayText).font(.caption).foregroundStyle(.secondary)+                  if event.routineRunID != nil {+                    Text("Routine-linked administration").font(.caption)+                  }+                }+              }             }-            .tabItem { Label("Routines", systemImage: "list.bullet.clipboard") }+          }         }-        .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: selectedProfileID) }-        .sheet(item: $editingTodayEvent) { event in-            if let medication = event.medication { AdministrationEditor(medication: medication, event: event) }-            else { ContentUnavailableView("Medication unavailable", systemImage: "pills") }+        .navigationTitle("Today")+        .toolbar {+          if let event = undoEvent, !event.isDeleted {+            Button("Undo Taken") {+              perform {+                try service.delete(event)+                undoEvent = nil+              }+            }+          }         }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {-            Button("OK") { error = nil }-        } message: { Text(error ?? "") }-    }--    private func record(_ medication: Medication) {-        perform {-            undoEvent = try service.record(ProfileAccess.stamp(AdministrationAction(-                eventID: UUID(), medicationID: medication.id, timestamp: Date(),-                source: .phone, dose: medication.defaultDose,-                scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded,-                scheduleGenerationID: medication.scheduleGenerationID-            ), target: medication, context: context))+      }+      .tabItem { Label("Today", systemImage: "sun.max") }+      NavigationStack {+        List {+          Picker("Show", selection: $showArchived) {+            Text("Active").tag(false)+            Text("Archived").tag(true)+          }.pickerStyle(.segmented)+          let displayed = medications.filter { $0.isActive != showArchived }+          let groups = Dictionary(grouping: displayed) { $0.purpose?.name ?? "Ungrouped" }+          ForEach(groups.keys.sorted(), id: \.self) { purpose in+            Section(purpose) {+              ForEach(groups[purpose] ?? []) { medication in+                MedicationRow(medication: medication) { record(medication) }+              }+            }+          }         }+        .navigationTitle("Medications")+        .toolbar {+          Button("Add medication", systemImage: "plus") { addingMedication = true }+          NavigationLink {+            CurrentMedicationsView()+          } label: {+            Label("Current Medications", systemImage: "list.bullet.rectangle")+          }+        }+      }+      .tabItem { Label("Medications", systemImage: "pills") }+      NavigationStack {+        RoutinesView()+      }+      .tabItem { Label("Routines", systemImage: "list.bullet.clipboard") }+    }+    .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: selectedProfileID) }+    .sheet(item: $editingTodayEvent) { event in+      if let medication = event.medication {+        AdministrationEditor(medication: medication, event: event)+      } else {+        ContentUnavailableView("Medication unavailable", systemImage: "pills")+      }     }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")+    }+  } -    private func perform(_ work: () throws -> Void) {-        do { try work() } catch { self.error = error.localizedDescription }+  private func record(_ medication: Medication) {+    perform {+      undoEvent = try service.record(+        ProfileAccess.stamp(+          AdministrationAction(+            eventID: UUID(), medicationID: medication.id, timestamp: Date(),+            source: .phone, dose: medication.defaultDose,+            scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw)+              ?? .asNeeded,+            scheduleGenerationID: medication.scheduleGenerationID+          ), target: medication, context: context))     }+  }++  private func perform(_ work: () throws -> Void) {+    do { try work() } catch { self.error = error.localizedDescription }+  } }  struct MedicationRow: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(PhoneNavigation.self) private var navigation-    @Query(sort: \Routine.name) private var allRoutines: [Routine]-    private var routines: [Routine] { allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    let medication: Medication-    let taken: () -> Void+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(PhoneNavigation.self) private var navigation+  @Query(sort: \Routine.name) private var allRoutines: [Routine]+  private var routines: [Routine] {+    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  let medication: Medication+  let taken: () -> Void -    var body: some View {-        HStack {-            NavigationLink {-                MedicationDetailView(medication: medication)-            } label: {-                HStack(alignment: .top) {-                    MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)-                    VStack(alignment: .leading, spacing: 4) {-                        Text(medication.name).font(.headline)-                        Text(MedicationPresentation.scheduleLabel(medication, routines: routines)).font(.caption).foregroundStyle(.secondary)-                        if medication.defaultDose != .unknown {-                            Text(medication.defaultDose.displayText).font(.caption)-                        }-                        if let last = medication.visibleAdministrations.first {-                            Text("Last taken \(last.timestamp.formatted(date: .abbreviated, time: .shortened))")-                                .font(.caption).foregroundStyle(.secondary)-                        } else {-                            Text("Not logged yet").font(.caption).foregroundStyle(.secondary)-                        }-                    }-                }+  var body: some View {+    HStack {+      NavigationLink {+        MedicationDetailView(medication: medication)+      } label: {+        HStack(alignment: .top) {+          MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+          VStack(alignment: .leading, spacing: 4) {+            Text(medication.name).font(.headline)+            Text(MedicationPresentation.scheduleLabel(medication, routines: routines)).font(+              .caption+            ).foregroundStyle(.secondary)+            if medication.defaultDose != .unknown {+              Text(medication.defaultDose.displayText).font(.caption)             }-            if medication.isActive {-                if let ownerID = medication.managedByRoutineID, let owner = routines.first(where: { $0.id == ownerID }) {-                    NavigationLink("Open routine") { RoutineDetailView(routine: owner, onStart: { navigation.start($0, occurrence: $1) }, onOpen: navigation.open) }-                } else { Button("Taken", action: taken).buttonStyle(.bordered)-                    .accessibilityLabel("Mark \(medication.name) taken") }+            if let last = medication.visibleAdministrations.first {+              Text("Last taken \(last.timestamp.formatted(date: .abbreviated, time: .shortened))")+                .font(.caption).foregroundStyle(.secondary)+            } else {+              Text("Not logged yet").font(.caption).foregroundStyle(.secondary)             }+          }         }-        if medication.scheduleTypeRaw == "asNeeded", medication.asNeededDoseLimitsData != nil { AsNeededLimitStatus(medication: medication) }+      }+      if medication.isActive {+        if let ownerID = medication.managedByRoutineID,+          let owner = routines.first(where: { $0.id == ownerID }) {+          NavigationLink("Open routine") {+            RoutineDetailView(+              routine: owner, onStart: { navigation.start($0, occurrence: $1) },+              onOpen: navigation.open)+          }+        } else {+          Button("Taken", action: taken).buttonStyle(.bordered)+            .accessibilityLabel("Mark \(medication.name) taken")+        }+      }+    }+    if medication.scheduleTypeRaw == "asNeeded", medication.asNeededDoseLimitsData != nil {+      AsNeededLimitStatus(medication: medication)     }+  } }  struct MedicationDetailView: View {-    @Environment(\.modelContext) private var context-    let medication: Medication-    @State private var editing = false-    @State private var logDetails = false-    @State private var editingEvent: Administration?-    @State private var error: String?-    @State private var lastSaved: Administration?+  @Environment(\.modelContext) private var context+  let medication: Medication+  @State private var editing = false+  @State private var logDetails = false+  @State private var editingEvent: Administration?+  @State private var error: String?+  @State private var lastSaved: Administration? -    private var service: MedicationService { MedicationService(context: context) }+  private var service: MedicationService { MedicationService(context: context) } -    var body: some View {-        List {-            if medication.scheduleTypeRaw == "asNeeded" { Section("Dose check") { AsNeededLimitStatus(medication: medication) } }-            if medication.recognitionPhotoData != nil {-                Section("Recognition photo") { MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 220) }-            }-            Section {-                Text(medication.purpose?.name ?? "Ungrouped")-                Text((MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title).foregroundStyle(.secondary)-                if medication.defaultDose != .unknown { Text(medication.defaultDose.displayText) }-                if !medication.administrationMethod.isEmpty { Text(medication.administrationMethod) }-                if !medication.requirements.isEmpty {-                    VStack(alignment: .leading) {-                        Text("Requirements").font(.headline)-                        Text(medication.requirements)-                    }-                }-                if !medication.notes.isEmpty { Text(medication.notes) }-            }-            if let followup = try? MedicationFollowupService.configuration(medication) {-                Section("Follow-up notification") {-                    Text(followup.message)-                    Text("\((followup.delaySeconds / 60).formatted()) minutes after the recorded taken time").foregroundStyle(.secondary)-                }+  var body: some View {+    List {+      if medication.scheduleTypeRaw == "asNeeded" {+        Section("Dose check") { AsNeededLimitStatus(medication: medication) }+      }+      if medication.recognitionPhotoData != nil {+        Section("Recognition photo") {+          MedicationPhotoView(+            data: medication.recognitionPhotoData, name: medication.name, size: 220)+        }+      }+      Section {+        Text(medication.purpose?.name ?? "Ungrouped")+        Text((MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title)+          .foregroundStyle(.secondary)+        if medication.defaultDose != .unknown { Text(medication.defaultDose.displayText) }+        if !medication.administrationMethod.isEmpty { Text(medication.administrationMethod) }+        if !medication.requirements.isEmpty {+          VStack(alignment: .leading) {+            Text("Requirements").font(.headline)+            Text(medication.requirements)+          }+        }+        if !medication.notes.isEmpty { Text(medication.notes) }+      }+      if let followup = try? MedicationFollowupService.configuration(medication) {+        Section("Follow-up notification") {+          Text(followup.message)+          Text("\((followup.delaySeconds / 60).formatted()) minutes after the recorded taken time")+            .foregroundStyle(.secondary)+        }+      }+      Section {+        if medication.isActive {+          Button(medication.managedByRoutineID == nil ? "Taken" : "Log outside routine") {+            perform {+              lastSaved = try service.record(+                ProfileAccess.stamp(+                  AdministrationAction(+                    eventID: UUID(), medicationID: medication.id, timestamp: Date(),+                    source: .phone, dose: medication.defaultDose,+                    scheduleTypeAtRecording: MedicationScheduleType(+                      rawValue: medication.scheduleTypeRaw) ?? .asNeeded,+                    scheduleGenerationID: medication.scheduleGenerationID+                  ), target: medication, context: context))             }-            Section {-                if medication.isActive {-                    Button(medication.managedByRoutineID == nil ? "Taken" : "Log outside routine") {-                        perform {-                            lastSaved = try service.record(ProfileAccess.stamp(AdministrationAction(-                                eventID: UUID(), medicationID: medication.id, timestamp: Date(),-                                source: .phone, dose: medication.defaultDose,-                                scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded,-                                scheduleGenerationID: medication.scheduleGenerationID-                            ), target: medication, context: context))-                        }-                    }-                }-                Button("Log details…") { logDetails = true }-                if let event = lastSaved, !event.isDeleted {-                    Text("Saved").foregroundStyle(.secondary)-                    Button("Undo Taken") { perform { try service.delete(event); lastSaved = nil } }-                }+          }+        }+        Button("Log details…") { logDetails = true }+        if let event = lastSaved, !event.isDeleted {+          Text("Saved").foregroundStyle(.secondary)+          Button("Undo Taken") {+            perform {+              try service.delete(event)+              lastSaved = nil             }-            let history = Dictionary(grouping: medication.visibleAdministrations) { ScheduleCalendar.localDate($0.timestamp, calendar: .current) }-            ForEach(history.keys.sorted(by: >), id: \.self) { day in-                Section("Administration history · \(day)") {-                    ForEach(history[day] ?? []) { event in-                        Button { editingEvent = event } label: {-                            VStack(alignment: .leading) {-                                Text(event.timestamp.formatted(date: .abbreviated, time: .shortened))-                                Text(event.recordedDose.displayText)-                                    .font(.caption).foregroundStyle(.secondary)-                            }-                        }-                        .swipeActions {-                            Button("Delete", role: .destructive) { perform { try RoutineSessionService(context: context).correct(event, timestamp: event.timestamp, dose: event.recordedDose, delete: true) } }-                        }-                    }-                }+          }+        }+      }+      let history = Dictionary(grouping: medication.visibleAdministrations) {+        ScheduleCalendar.localDate($0.timestamp, calendar: .current)+      }+      ForEach(history.keys.sorted(by: >), id: \.self) { day in+        Section("Administration history · \(day)") {+          ForEach(history[day] ?? []) { event in+            Button {+              editingEvent = event+            } label: {+              VStack(alignment: .leading) {+                Text(event.timestamp.formatted(date: .abbreviated, time: .shortened))+                Text(event.recordedDose.displayText)+                  .font(.caption).foregroundStyle(.secondary)+              }             }-            Section {-                Button(medication.isActive ? "Archive" : "Reactivate") {-                    perform { try service.setActive(medication, !medication.isActive) }+            .swipeActions {+              Button("Delete", role: .destructive) {+                perform {+                  try RoutineSessionService(context: context).correct(+                    event, timestamp: event.timestamp, dose: event.recordedDose, delete: true)                 }+              }             }+          }         }-        .navigationTitle(medication.name)-        .toolbar { Button("Edit") { editing = true } }-        .sheet(isPresented: $editing) { MedicationEditor(medication: medication) }-        .sheet(isPresented: $logDetails) { AdministrationEditor(medication: medication) }-        .sheet(item: $editingEvent) { AdministrationEditor(medication: medication, event: $0) }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {-            Button("OK") { error = nil }-        } message: { Text(error ?? "") }+      }+      Section {+        Button(medication.isActive ? "Archive" : "Reactivate") {+          perform { try service.setActive(medication, !medication.isActive) }+        }+      }     }--    private func perform(_ work: () throws -> Void) {-        do { try work() } catch { self.error = error.localizedDescription }+    .navigationTitle(medication.name)+    .toolbar { Button("Edit") { editing = true } }+    .sheet(isPresented: $editing) { MedicationEditor(medication: medication) }+    .sheet(isPresented: $logDetails) { AdministrationEditor(medication: medication) }+    .sheet(item: $editingEvent) { AdministrationEditor(medication: medication, event: $0) }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")     }+  }++  private func perform(_ work: () throws -> Void) {+    do { try work() } catch { self.error = error.localizedDescription }+  } }  struct MedicationEditor: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    @Query(sort: \Purpose.name) private var allPurposes: [Purpose]-    private var purposes: [Purpose] { allPurposes.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    private let medication: Medication?-    private let profileID: UUID-    @State private var photo: MedicationPhotoDraft-    @State private var limits: AsNeededLimitDraft-    @State private var followup: MedicationFollowupDraft-    @State private var name: String-    @State private var description: String-    @State private var amount: String-    @State private var unit: String-    @State private var purpose: Purpose?-    @State private var method: String-    @State private var requirements: String-    @State private var notes: String-    @State private var scheduleMode: MedicationScheduleType-    @State private var scheduleDoses: String-    @State private var scheduleStart: String-    @State private var scheduleEnd: String-    @State private var scheduleMinimum: String-    @State private var scheduleInterval: String-    @State private var scheduleFirst: String-    @State private var scheduleWakeOffset: String-    @State private var scheduleFixed: String-    @State private var reminders: Bool-    @State private var addingPurpose = false-    @State private var purposeName = ""-    @State private var error: String?+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  @Query(sort: \Purpose.name) private var allPurposes: [Purpose]+  private var purposes: [Purpose] {+    allPurposes.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  private let medication: Medication?+  private let profileID: UUID+  @State private var photo: MedicationPhotoDraft+  @State private var limits: AsNeededLimitDraft+  @State private var followup: MedicationFollowupDraft+  @State private var name: String+  @State private var description: String+  @State private var amount: String+  @State private var unit: String+  @State private var purpose: Purpose?+  @State private var method: String+  @State private var requirements: String+  @State private var notes: String+  @State private var scheduleMode: MedicationScheduleType+  @State private var scheduleDoses: String+  @State private var scheduleStart: String+  @State private var scheduleEnd: String+  @State private var scheduleMinimum: String+  @State private var scheduleInterval: String+  @State private var scheduleFirst: String+  @State private var scheduleWakeOffset: String+  @State private var scheduleFixed: String+  @State private var reminders: Bool+  @State private var addingPurpose = false+  @State private var purposeName = ""+  @State private var error: String? -    init(medication: Medication? = nil, profileID: UUID = ProfileIdentity.me) {-        self.profileID = medication?.profileID ?? profileID-        self.medication = medication-        _photo = State(initialValue: MedicationPhotoDraft(data: medication?.recognitionPhotoData))-        _limits = State(initialValue: AsNeededLimitDraft(medication: medication))-        _followup = State(initialValue: MedicationFollowupDraft(medication: medication))-        _name = State(initialValue: medication?.name ?? "")-        _description = State(initialValue: medication?.doseDescription ?? "")-        _amount = State(initialValue: medication?.defaultDoseAmount.map { String($0) } ?? "")-        _unit = State(initialValue: medication?.defaultDoseUnit ?? "")-        _purpose = State(initialValue: medication?.purpose)-        _method = State(initialValue: medication?.administrationMethod ?? "")-        _requirements = State(initialValue: medication?.requirements ?? "")-        _notes = State(initialValue: medication?.notes ?? "")-        _scheduleMode = State(initialValue: MedicationScheduleType(rawValue: medication?.scheduleTypeRaw ?? "asNeeded") ?? .asNeeded)-        _scheduleDoses = State(initialValue: medication?.dosesPerDay.map(String.init) ?? "")-        _scheduleStart = State(initialValue: medication?.dayStartMinuteOfDay.map(ScheduleTimeInput.text) ?? "")-        _scheduleEnd = State(initialValue: medication?.dayEndMinuteOfDay.map(ScheduleTimeInput.text) ?? "")-        _scheduleMinimum = State(initialValue: medication?.minimumIntervalMinutes.map(String.init) ?? "")-        _scheduleInterval = State(initialValue: medication?.intervalMinutes.map(String.init) ?? "")-        _scheduleFirst = State(initialValue: medication?.firstReminderMinuteOfDay.map(ScheduleTimeInput.text) ?? "")-        let fixed = medication?.fixedTimesData.flatMap { try? JSONDecoder().decode([Int].self, from: $0) } ?? []-        _scheduleFixed = State(initialValue: fixed.map(ScheduleTimeInput.text).joined(separator: ", "))-        _scheduleWakeOffset = State(initialValue: medication?.wakeOffsetMinutes.map(String.init) ?? "0")-        _reminders = State(initialValue: medication?.remindersEnabled ?? false)-    }+  init(medication: Medication? = nil, profileID: UUID = ProfileIdentity.me) {+    self.profileID = medication?.profileID ?? profileID+    self.medication = medication+    _photo = State(initialValue: MedicationPhotoDraft(data: medication?.recognitionPhotoData))+    _limits = State(initialValue: AsNeededLimitDraft(medication: medication))+    _followup = State(initialValue: MedicationFollowupDraft(medication: medication))+    _name = State(initialValue: medication?.name ?? "")+    _description = State(initialValue: medication?.doseDescription ?? "")+    _amount = State(initialValue: medication?.defaultDoseAmount.map { String($0) } ?? "")+    _unit = State(initialValue: medication?.defaultDoseUnit ?? "")+    _purpose = State(initialValue: medication?.purpose)+    _method = State(initialValue: medication?.administrationMethod ?? "")+    _requirements = State(initialValue: medication?.requirements ?? "")+    _notes = State(initialValue: medication?.notes ?? "")+    _scheduleMode = State(+      initialValue: MedicationScheduleType(rawValue: medication?.scheduleTypeRaw ?? "asNeeded")+        ?? .asNeeded)+    _scheduleDoses = State(initialValue: medication?.dosesPerDay.map(String.init) ?? "")+    _scheduleStart = State(+      initialValue: medication?.dayStartMinuteOfDay.map(ScheduleTimeInput.text) ?? "")+    _scheduleEnd = State(+      initialValue: medication?.dayEndMinuteOfDay.map(ScheduleTimeInput.text) ?? "")+    _scheduleMinimum = State(+      initialValue: medication?.minimumIntervalMinutes.map(String.init) ?? "")+    _scheduleInterval = State(initialValue: medication?.intervalMinutes.map(String.init) ?? "")+    _scheduleFirst = State(+      initialValue: medication?.firstReminderMinuteOfDay.map(ScheduleTimeInput.text) ?? "")+    let fixed =+      medication?.fixedTimesData.flatMap { try? JSONDecoder().decode([Int].self, from: $0) } ?? []+    _scheduleFixed = State(initialValue: fixed.map(ScheduleTimeInput.text).joined(separator: ", "))+    _scheduleWakeOffset = State(initialValue: medication?.wakeOffsetMinutes.map(String.init) ?? "0")+    _reminders = State(initialValue: medication?.remindersEnabled ?? false)+  } -    var body: some View {-        NavigationStack {-            Form {-                Section {-                    TextField("Name", text: $name)-                    Picker("Purpose", selection: $purpose) {-                        Text("None").tag(nil as Purpose?)-                        ForEach(purposes.filter { !$0.isArchived || $0 == purpose }) { item in-                            Text(item.name).tag(item as Purpose?)-                        }-                    }-                    Button("Add Purpose…") { addingPurpose = true }-                }-                MedicationPhotoEditor(draft: photo, name: name)-                Section("Optional recording defaults") {-                    TextField("Dose description", text: $description)-                    TextField(scheduleMode == .asNeeded ? "Quantity per dose" : "Amount", text: $amount).keyboardType(.decimalPad)-                    TextField("Unit", text: $unit)-                }-                Section {-                    TextField("How to take / apply", text: $method, axis: .vertical)-                    TextField("Requirements", text: $requirements, axis: .vertical).accessibilityIdentifier("medicationRequirements")-                    Menu("Timing option") {-                        Button(TimingCue.beforeSleeping.rawValue) { requirements = TimingCue.beforeSleeping.adding(to: requirements) }-                    }-                    Text("Before sleeping is a cue, without a fixed clock reminder.").font(.caption).foregroundStyle(.secondary)-                    TextField("Notes", text: $notes, axis: .vertical)-                }-                if medication?.managedByRoutineID == nil {-                    scheduleFields-                    if scheduleMode == .asNeeded { AsNeededLimitFields(draft: limits) }-                } else {-                    Section("Schedule") { Text("Managed by its ordered routine. Change ownership from the routine editor.") }-                }-                MedicationFollowupFields(draft: followup)-                if let error { Section { Text(error).foregroundStyle(.red) } }+  var body: some View {+    NavigationStack {+      Form {+        Section {+          TextField("Name", text: $name)+          Picker("Purpose", selection: $purpose) {+            Text("None").tag(nil as Purpose?)+            ForEach(purposes.filter { !$0.isArchived || $0 == purpose }) { item in+              Text(item.name).tag(item as Purpose?)             }-            .scrollDismissesKeyboard(.immediately)-            .navigationTitle(medication == nil ? "Add medication" : "Edit medication")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save", action: save).disabled(photo.loading) }-            }-            .alert("Add purpose", isPresented: $addingPurpose) {-                TextField("Name", text: $purposeName)-                Button("Cancel", role: .cancel) {}-                Button("Add") {-                    do { purpose = try MedicationService(context: context).createPurpose(name: purposeName, profileID: profileID) }-                    catch { self.error = error.localizedDescription }-                }+          }+          Button("Add Purpose…") { addingPurpose = true }+        }+        MedicationPhotoEditor(draft: photo, name: name)+        Section("Optional recording defaults") {+          TextField("Dose description", text: $description)+          TextField(scheduleMode == .asNeeded ? "Quantity per dose" : "Amount", text: $amount)+            .keyboardType(.decimalPad)+          TextField("Unit", text: $unit)+        }+        Section {+          TextField("How to take / apply", text: $method, axis: .vertical)+          TextField("Requirements", text: $requirements, axis: .vertical).accessibilityIdentifier(+            "medicationRequirements")+          Menu("Timing option") {+            Button(TimingCue.beforeSleeping.rawValue) {+              requirements = TimingCue.beforeSleeping.adding(to: requirements)             }+          }+          Text("Before sleeping is a cue, without a fixed clock reminder.").font(.caption)+            .foregroundStyle(.secondary)+          TextField("Notes", text: $notes, axis: .vertical)+        }+        if medication?.managedByRoutineID == nil {+          scheduleFields+          if scheduleMode == .asNeeded { AsNeededLimitFields(draft: limits) }+        } else {+          Section("Schedule") {+            Text("Managed by its ordered routine. Change ownership from the routine editor.")+          }+        }+        MedicationFollowupFields(draft: followup)+        if let error { Section { Text(error).foregroundStyle(.red) } }+      }+      .scrollDismissesKeyboard(.immediately)+      .navigationTitle(medication == nil ? "Add medication" : "Edit medication")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) {+          Button("Save", action: save).disabled(photo.loading)         }+      }+      .alert("Add purpose", isPresented: $addingPurpose) {+        TextField("Name", text: $purposeName)+        Button("Cancel", role: .cancel) {}+        Button("Add") {+          do {+            purpose = try MedicationService(context: context).createPurpose(+              name: purposeName, profileID: profileID)+          } catch { self.error = error.localizedDescription }+        }+      }     }+  } -    private var scheduleFields: MedicationScheduleFields {-        MedicationScheduleFields(mode: $scheduleMode, doses: $scheduleDoses, start: $scheduleStart, end: $scheduleEnd,-                                 minimum: $scheduleMinimum, interval: $scheduleInterval, first: $scheduleFirst,-                                 fixed: $scheduleFixed, reminders: $reminders, wakeOffset: $scheduleWakeOffset)-    }+  private var scheduleFields: MedicationScheduleFields {+    MedicationScheduleFields(+      mode: $scheduleMode, doses: $scheduleDoses, start: $scheduleStart, end: $scheduleEnd,+      minimum: $scheduleMinimum, interval: $scheduleInterval, first: $scheduleFirst,+      fixed: $scheduleFixed, reminders: $reminders, wakeOffset: $scheduleWakeOffset)+  } -    private var doseUnit: String {-        if scheduleMode == .asNeeded && limits.enabled && !amount.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return "units" }-        return unit+  private var doseUnit: String {+    if scheduleMode == .asNeeded && limits.enabled+      && !amount.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+      && unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+      return "units"     }+    return unit+  } -    private func save() {-        do {-            let dose = try enteredDose(description: description, amount: amount, unit: doseUnit)-            let draft = medication?.managedByRoutineID == nil ? try scheduleFields.draft() : nil-            if scheduleMode == .asNeeded { _ = try limits.rules(doseUnit: doseUnit) }-            _ = try followup.value()-            _ = try EditorTransaction.save(context: context) {-                let service = MedicationService(context: context, deferSave: true)-                let saved: Medication-                if let medication {-                    try service.update(medication, name: name, dose: dose, purpose: purpose,-                                       method: method, requirements: requirements, notes: notes)-                    saved = medication-                } else {-                    saved = try service.createAsNeededMedication(name: name, dose: dose, purpose: purpose,-                                                                method: method, requirements: requirements, notes: notes, profileID: profileID)-                }-                if let draft { try ScheduleService(context: context, deferSave: true).configure(saved, draft: draft, reminders: reminders) }-                try photo.apply(to: saved, context: context)-                try followup.apply(to: saved)-                if scheduleMode == .asNeeded { try limits.apply(to: saved, context: context, doseUnit: doseUnit) }-                return saved-            }-            dismiss()-        } catch { self.error = error.localizedDescription }-    }+  private func save() {+    do {+      let dose = try enteredDose(description: description, amount: amount, unit: doseUnit)+      let draft = medication?.managedByRoutineID == nil ? try scheduleFields.draft() : nil+      if scheduleMode == .asNeeded { _ = try limits.rules(doseUnit: doseUnit) }+      _ = try followup.value()+      _ = try EditorTransaction.save(context: context) {+        let service = MedicationService(context: context, deferSave: true)+        let saved: Medication+        if let medication {+          try service.update(+            medication, edit: MedicationEdit(name: name, dose: dose, purpose: purpose,+            method: method, requirements: requirements, notes: notes))+          saved = medication+        } else {+          saved = try service.createAsNeededMedication(+            name: name, dose: dose, purpose: purpose,+            method: method, requirements: requirements, notes: notes, profileID: profileID)+        }+        if let draft {+          try ScheduleService(context: context, deferSave: true).configure(+            saved, draft: draft, reminders: reminders)+        }+        try photo.apply(to: saved, context: context)+        try followup.apply(to: saved)+        if scheduleMode == .asNeeded {+          try limits.apply(to: saved, context: context, doseUnit: doseUnit)+        }+        return saved+      }+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }  struct AdministrationEditor: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    let medication: Medication-    let event: Administration?-    @State private var timestamp: Date-    @State private var description: String-    @State private var amount: String-    @State private var unit: String-    @State private var error: String?-    @State private var eventID = UUID()+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  let medication: Medication+  let event: Administration?+  @State private var timestamp: Date+  @State private var description: String+  @State private var amount: String+  @State private var unit: String+  @State private var error: String?+  @State private var eventID = UUID() -    init(medication: Medication, event: Administration? = nil) {-        self.medication = medication-        self.event = event-        let dose = event?.recordedDose ?? medication.defaultDose-        _timestamp = State(initialValue: event?.timestamp ?? Date())-        _description = State(initialValue: dose.description)-        _amount = State(initialValue: dose.amount.map { String($0) } ?? "")-        _unit = State(initialValue: dose.unit ?? "")-    }+  init(medication: Medication, event: Administration? = nil) {+    self.medication = medication+    self.event = event+    let dose = event?.recordedDose ?? medication.defaultDose+    _timestamp = State(initialValue: event?.timestamp ?? Date())+    _description = State(initialValue: dose.description)+    _amount = State(initialValue: dose.amount.map { String($0) } ?? "")+    _unit = State(initialValue: dose.unit ?? "")+  } -    var body: some View {-        NavigationStack {-            Form {-                MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 160)-                DatePicker("Taken", selection: $timestamp, in: ...Date())-                TextField("Recorded dose description", text: $description)-                TextField("Amount", text: $amount).keyboardType(.decimalPad)-                    .onChange(of: amount) { _, _ in description = "" }-                TextField("Unit", text: $unit)-                    .onChange(of: unit) { _, _ in description = "" }-                Button("Dose not recorded") { description = ""; amount = ""; unit = "" }-                if medication.scheduleTypeRaw == "asNeeded" {-                    AsNeededLimitStatus(medication: medication, proposedDose: (try? enteredDose(description: description, amount: amount, unit: unit)) ?? .unknown)-                    Text("Log doses actually taken even if they exceed entered limits; records are needed for an accurate check.").font(.caption)-                }-                Text("Recording details leaves medication defaults unchanged.").font(.caption)-                if let error { Text(error).foregroundStyle(.red) }-            }-            .navigationTitle(event == nil ? "Log details" : "Correct entry")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) {-                    Button("Save") {-                        do {-                            let dose = try enteredDose(description: description, amount: amount, unit: unit)-                            let service = MedicationService(context: context)-                            if let event { try RoutineSessionService(context: context).correct(event, timestamp: timestamp, dose: dose) }-                            else {-                                _ = try service.record(ProfileAccess.stamp(AdministrationAction(-                                    eventID: eventID, medicationID: medication.id,-                                    timestamp: timestamp, source: .manualHistory, dose: dose,-                                    scheduleTypeAtRecording: MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded,-                                    scheduleGenerationID: medication.scheduleGenerationID-                                ), target: medication, context: context))-                            }-                            dismiss()-                        } catch { self.error = error.localizedDescription }-                    }-                }-            }+  var body: some View {+    NavigationStack {+      Form {+        MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 160)+        DatePicker("Taken", selection: $timestamp, in: ...Date())+        TextField("Recorded dose description", text: $description)+        TextField("Amount", text: $amount).keyboardType(.decimalPad)+          .onChange(of: amount) { _, _ in description = "" }+        TextField("Unit", text: $unit)+          .onChange(of: unit) { _, _ in description = "" }+        Button("Dose not recorded") {+          description = ""+          amount = ""+          unit = ""+        }+        if medication.scheduleTypeRaw == "asNeeded" {+          AsNeededLimitStatus(+            medication: medication,+            proposedDose: (try? enteredDose(description: description, amount: amount, unit: unit))+              ?? .unknown)+          Text(+            "Log doses actually taken even if they exceed entered limits; records are needed for an accurate check."+          ).font(.caption)         }+        Text("Recording details leaves medication defaults unchanged.").font(.caption)+        if let error { Text(error).foregroundStyle(.red) }+      }+      .navigationTitle(event == nil ? "Log details" : "Correct entry")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) {+          Button("Save") {+            do {+              let dose = try enteredDose(description: description, amount: amount, unit: unit)+              let service = MedicationService(context: context)+              if let event {+                try RoutineSessionService(context: context).correct(+                  event, timestamp: timestamp, dose: dose)+              } else {+                _ = try service.record(+                  ProfileAccess.stamp(+                    AdministrationAction(+                      eventID: eventID, medicationID: medication.id,+                      timestamp: timestamp, source: .manualHistory, dose: dose,+                      scheduleTypeAtRecording: MedicationScheduleType(+                        rawValue: medication.scheduleTypeRaw) ?? .asNeeded,+                      scheduleGenerationID: medication.scheduleGenerationID+                    ), target: medication, context: context))+              }+              dismiss()+            } catch { self.error = error.localizedDescription }+          }+        }+      }     }+  } } -private func enteredDose(description: String, amount: String, unit: String) throws -> RecordedDoseSnapshot {-    let amountText = amount.trimmingCharacters(in: .whitespacesAndNewlines)-    let unitText = unit.trimmingCharacters(in: .whitespacesAndNewlines)-    if !amountText.isEmpty && Double(amountText) == nil { throw RecordingError.invalidDose }-    let dose = RecordedDoseSnapshot(description: description, amount: Double(amountText),-                                    unit: unitText.isEmpty ? nil : unitText)-    try dose.validate()-    return dose+private func enteredDose(description: String, amount: String, unit: String) throws+  -> RecordedDoseSnapshot {+  let amountText = amount.trimmingCharacters(in: .whitespacesAndNewlines)+  let unitText = unit.trimmingCharacters(in: .whitespacesAndNewlines)+  if !amountText.isEmpty && Double(amountText) == nil { throw RecordingError.invalidDose }+  let dose = RecordedDoseSnapshot(+    description: description, amount: Double(amountText),+    unit: unitText.isEmpty ? nil : unitText)+  try dose.validate()+  return dose }  #Preview {-    if let container = try? AppEnvironment.makeContainer(isolated: true) {-        ContentView().modelContainer(container)-    }+  if let container = try? AppEnvironment.makeContainer(isolated: true) {+    ContentView().modelContainer(container)+  } }
Meddy/Meddy/Features/AsNeededLimitViews.swift Modified
diff --git a/Meddy/Meddy/Features/AsNeededLimitViews.swift b/Meddy/Meddy/Features/AsNeededLimitViews.swiftindex 498f199..1855fd5 100644--- a/Meddy/Meddy/Features/AsNeededLimitViews.swift+++ b/Meddy/Meddy/Features/AsNeededLimitViews.swift@@ -1,115 +1,145 @@-import SwiftUI import SwiftData+import SwiftUI  @MainActor @Observable final class AsNeededLimitDraft {-    var enabled: Bool-    var intervalHours: String-    var maximum: String-    var unit: String-    var useDailyWindow = false-    var legacyWindowHours: Double? {-        guard let window = originalRules?.windowSeconds, window != 86400, !useDailyWindow else { return nil }-        return window / 3600+  var enabled: Bool+  var intervalHours: String+  var maximum: String+  var unit: String+  var useDailyWindow = false+  var legacyWindowHours: Double? {+    guard let window = originalRules?.windowSeconds, window != 86400, !useDailyWindow else {+      return nil     }-    private let originalDoseUnit: String-    private let originalRules: AsNeededDoseLimits?-    private let originalDataExists: Bool-    init(medication: Medication?) {-        let originalData = medication?.asNeededDoseLimitsData-        let rules = originalData.flatMap { try? JSONDecoder().decode(AsNeededDoseLimits.self, from: $0) }-        originalRules = rules; originalDataExists = originalData != nil-        originalDoseUnit = medication?.defaultDoseUnit ?? ""-        enabled = originalData != nil-        intervalHours = rules?.minimumIntervalSeconds.map { String($0 / 3600) } ?? ""-        maximum = rules?.maximumAmount.map { String($0) } ?? ""-        unit = rules?.unit ?? medication?.defaultDoseUnit ?? ""+    return window / 3600+  }+  private let originalDoseUnit: String+  private let originalRules: AsNeededDoseLimits?+  private let originalDataExists: Bool+  init(medication: Medication?) {+    let originalData = medication?.asNeededDoseLimitsData+    let rules = originalData.flatMap {+      try? JSONDecoder().decode(AsNeededDoseLimits.self, from: $0)     }-    private func number(_ text: String) throws -> Double? {-        let clean = text.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !clean.isEmpty else { return nil }-        guard let value = Double(clean), value.isFinite, value > 0 else { throw AsNeededLimitError.invalidConfiguration }-        return value+    originalRules = rules+    originalDataExists = originalData != nil+    originalDoseUnit = medication?.defaultDoseUnit ?? ""+    enabled = originalData != nil+    intervalHours = rules?.minimumIntervalSeconds.map { String($0 / 3600) } ?? ""+    maximum = rules?.maximumAmount.map { String($0) } ?? ""+    unit = rules?.unit ?? medication?.defaultDoseUnit ?? ""+  }+  private func number(_ text: String) throws -> Double? {+    let clean = text.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !clean.isEmpty else { return nil }+    guard let value = Double(clean), value.isFinite, value > 0 else {+      throw AsNeededLimitError.invalidConfiguration     }-    func rules(now: Date = Date(), doseUnit: String? = nil) throws -> AsNeededDoseLimits? {-        guard enabled else { return nil }-        // Preserve legacy context and windows unless the user explicitly chooses the daily cap.-        var value = originalRules ?? AsNeededDoseLimits()-        value.minimumIntervalSeconds = try number(intervalHours).map { $0 * 3600 }-        value.maximumAmount = try number(maximum)-        value.windowSeconds = value.maximumAmount == nil ? nil : (useDailyWindow ? 86400 : originalRules?.windowSeconds ?? 86400)-        let enteredUnit = doseUnit ?? unit-        let initialUnit = originalDoseUnit.trimmingCharacters(in: .whitespacesAndNewlines)-        if originalRules != nil && (enteredUnit == originalDoseUnit || initialUnit.isEmpty && enteredUnit == "units") {-            value.unit = unit-        } else {-            value.unit = enteredUnit-        }-        if value.unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { value.unit = "units" }-        try value.validate(now: now)-        return value+    return value+  }+  func rules(now: Date = Date(), doseUnit: String? = nil) throws -> AsNeededDoseLimits? {+    guard enabled else { return nil }+    // Preserve legacy context and windows unless the user explicitly chooses the daily cap.+    var value = originalRules ?? AsNeededDoseLimits()+    value.minimumIntervalSeconds = try number(intervalHours).map { $0 * 3600 }+    value.maximumAmount = try number(maximum)+    value.windowSeconds =+      value.maximumAmount == nil+      ? nil : (useDailyWindow ? 86400 : originalRules?.windowSeconds ?? 86400)+    let enteredUnit = doseUnit ?? unit+    let initialUnit = originalDoseUnit.trimmingCharacters(in: .whitespacesAndNewlines)+    if originalRules != nil+      && (enteredUnit == originalDoseUnit || initialUnit.isEmpty && enteredUnit == "units") {+      value.unit = unit+    } else {+      value.unit = enteredUnit     }-    func apply(to medication: Medication, context: ModelContext, doseUnit: String? = nil) throws {-        let value = try rules(doseUnit: doseUnit)-        if value != originalRules || (originalDataExists && originalRules == nil) { try AsNeededLimitService(context: context, deferSave: true).configure(medication, limits: value) }+    if value.unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { value.unit = "units" }+    try value.validate(now: now)+    return value+  }+  func apply(to medication: Medication, context: ModelContext, doseUnit: String? = nil) throws {+    let value = try rules(doseUnit: doseUnit)+    if value != originalRules || (originalDataExists && originalRules == nil) {+      try AsNeededLimitService(context: context, deferSave: true).configure(+        medication, limits: value)     }+  } }  struct AsNeededLimitFields: View {-    @Bindable var draft: AsNeededLimitDraft-    var body: some View {-        Section("As-needed limits") {-            Toggle("Use dose limits", isOn: $draft.enabled).accessibilityIdentifier("doseLimitsEnabled")-            if draft.enabled {-                TextField("Minimum interval (hours)", text: $draft.intervalHours).accessibilityIdentifier("doseLimitintervalHours").keyboardType(.decimalPad)-                TextField("Maximum quantity per day", text: $draft.maximum).accessibilityIdentifier("doseLimitmaximum").keyboardType(.decimalPad)-                if let hours = draft.legacyWindowHours {-                    Text("Your saved maximum still uses the last \(hours.formatted()) hours.").font(.caption)-                    Button("Use 24-hour daily limit") { draft.useDailyWindow = true }-                    Text("This keeps your recorded doses and applies the maximum above to the last 24 hours when you save.").font(.caption)-                } else {-                    Text("Per day means the preceding 24 hours; it does not reset at midnight or 2 am.").font(.caption)-                }-            }+  @Bindable var draft: AsNeededLimitDraft+  var body: some View {+    Section("As-needed limits") {+      Toggle("Use dose limits", isOn: $draft.enabled).accessibilityIdentifier("doseLimitsEnabled")+      if draft.enabled {+        TextField("Minimum interval (hours)", text: $draft.intervalHours).accessibilityIdentifier(+          "doseLimitintervalHours"+        ).keyboardType(.decimalPad)+        TextField("Maximum quantity per day", text: $draft.maximum).accessibilityIdentifier(+          "doseLimitmaximum"+        ).keyboardType(.decimalPad)+        if let hours = draft.legacyWindowHours {+          Text("Your saved maximum still uses the last \(hours.formatted()) hours.").font(.caption)+          Button("Use 24-hour daily limit") { draft.useDailyWindow = true }+          Text(+            "This keeps your recorded doses and applies the maximum above to the last 24 hours when you save."+          ).font(.caption)+        } else {+          Text("Per day means the preceding 24 hours; it does not reset at midnight or 2 am.").font(+            .caption)         }+      }     }+  } }  struct AsNeededLimitStatus: View {-    @Environment(\.modelContext) private var context-    let medication: Medication-    var proposedDose: RecordedDoseSnapshot? = nil-    @Query private var administrations: [Administration]-    @State private var refreshDate = Date()-    init(medication: Medication, proposedDose: RecordedDoseSnapshot? = nil) {-        self.medication = medication; self.proposedDose = proposedDose-        let id = medication.id-        _administrations = Query(filter: #Predicate<Administration> { $0.medicationID == id })-    }-    var body: some View {-        let _ = (administrations.count, refreshDate) // Observe records and wake-ups; evaluate using the actual clock.-        let result = AsNeededLimitService(context: context).check(medication, proposedDose: proposedDose, now: Date())-        VStack(alignment: .leading, spacing: 4) {-            Text(result.title).font(.headline).foregroundStyle(result.state == .wait ? Color.orange : Color.primary)-            if let remaining = result.remainingAmount, result.issues.isEmpty {-                Text("Remaining: \(remaining.formatted()) \(result.unit) in the last \(((result.windowSeconds ?? 86400) / 3600).formatted()) hours").font(.caption)-            }-            if let time = result.earliestFromLoggedDoses, result.issues.isEmpty {-                if time > result.evaluatedAt {-                    Text("Next dose: \(time.formatted(date: .abbreviated, time: .standard))").font(.caption)-                } else {-                    Text("Next dose: now").font(.caption)-                }-            }-            ForEach(result.issues, id: \.self) { Text($0).font(.caption) }-            if result.state != .notConfigured { Text("Based on doses logged for this medication.").font(.caption).foregroundStyle(.secondary) }-        }.accessibilityElement(children: .combine).accessibilityIdentifier("asNeededDoseCheck")-        .task {-            refreshDate = Date()-            while !Task.isCancelled {-                do { try await Task.sleep(for: .seconds(30)) } catch { return }-                refreshDate = Date()-            }+  @Environment(\.modelContext) private var context+  let medication: Medication+  var proposedDose: RecordedDoseSnapshot?+  @Query private var administrations: [Administration]+  @State private var refreshDate = Date()+  init(medication: Medication, proposedDose: RecordedDoseSnapshot? = nil) {+    self.medication = medication+    self.proposedDose = proposedDose+    let id = medication.id+    _administrations = Query(filter: #Predicate<Administration> { $0.medicationID == id })+  }+  var body: some View {+    // Keep a declaration: a bare assignment bloats the SwiftUI result-builder type-check chain.+    // swiftlint:disable:next redundant_discardable_let+    let _ = (administrations.count, refreshDate)  // Observe records and wake-ups; evaluate using the actual clock.+    let result = AsNeededLimitService(context: context).check(+      medication, proposedDose: proposedDose, now: Date())+    VStack(alignment: .leading, spacing: 4) {+      Text(result.title).font(.headline).foregroundStyle(+        result.state == .wait ? Color.orange : Color.primary)+      if let remaining = result.remainingAmount, result.issues.isEmpty {+        Text(+          "Remaining: \(remaining.formatted()) \(result.unit) in the last \(((result.windowSeconds ?? 86400) / 3600).formatted()) hours"+        ).font(.caption)+      }+      if let time = result.earliestFromLoggedDoses, result.issues.isEmpty {+        if time > result.evaluatedAt {+          Text("Next dose: \(time.formatted(date: .abbreviated, time: .standard))").font(.caption)+        } else {+          Text("Next dose: now").font(.caption)         }-    }+      }+      ForEach(result.issues, id: \.self) { Text($0).font(.caption) }+      if result.state != .notConfigured {+        Text("Based on doses logged for this medication.").font(.caption).foregroundStyle(+          .secondary)+      }+    }.accessibilityElement(children: .combine).accessibilityIdentifier("asNeededDoseCheck")+      .task {+        refreshDate = Date()+        while !Task.isCancelled {+          do { try await Task.sleep(for: .seconds(30)) } catch { return }+          refreshDate = Date()+        }+      }+  } }
Meddy/Meddy/Features/CareEditors.swift Modified
diff --git a/Meddy/Meddy/Features/CareEditors.swift b/Meddy/Meddy/Features/CareEditors.swiftindex 7a4b320..c8227ba 100644--- a/Meddy/Meddy/Features/CareEditors.swift+++ b/Meddy/Meddy/Features/CareEditors.swift@@ -1,355 +1,565 @@-import SwiftUI import SwiftData+import SwiftUI import UserNotifications  nonisolated enum ScheduleTimeInput {-    static func minute(_ text: String) throws -> Int {-        let parts = text.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: ":", omittingEmptySubsequences: false)-        guard parts.count == 2, let hour = Int(parts[0]), let minute = Int(parts[1]), (0..<24).contains(hour), (0..<60).contains(minute) else { throw DefinitionError.invalidSchedule }-        return hour * 60 + minute-    }-    static func text(_ minute: Int) -> String { String(format: "%02d:%02d", minute / 60, minute % 60) }+  static func minute(_ text: String) throws -> Int {+    let parts = text.trimmingCharacters(in: .whitespacesAndNewlines).split(+      separator: ":", omittingEmptySubsequences: false)+    guard parts.count == 2, let hour = Int(parts[0]), let minute = Int(parts[1]),+      (0..<24).contains(hour), (0..<60).contains(minute)+    else { throw DefinitionError.invalidSchedule }+    return hour * 60 + minute+  }+  static func text(_ minute: Int) -> String {+    String(format: "%02d:%02d", minute / 60, minute % 60)+  } }  struct PurposeField: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Query(sort: \Purpose.name) private var allPurposes: [Purpose]-    private var purposes: [Purpose] { allPurposes.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Binding var purpose: Purpose?-    @State private var adding = false-    @State private var name = ""-    @State private var error: String?-    var body: some View {-        Picker("Purpose", selection: $purpose) {-            Text("None").tag(nil as Purpose?)-            ForEach(purposes.filter { !$0.isArchived || $0.id == purpose?.id }) { Text($0.name).tag($0 as Purpose?) }-        }-        Button("Add Purpose…") { adding = true }-            .alert("Add purpose", isPresented: $adding) {-                TextField("Name", text: $name)-                Button("Cancel", role: .cancel) {}-                Button("Add") {-                    do { purpose = try MedicationService(context: context).createPurpose(name: name, profileID: selectedProfileID) }-                    catch { self.error = error.localizedDescription }-                }-            }-        if let error { Text(error).foregroundStyle(.red) }+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Query(sort: \Purpose.name) private var allPurposes: [Purpose]+  private var purposes: [Purpose] {+    allPurposes.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Binding var purpose: Purpose?+  @State private var adding = false+  @State private var name = ""+  @State private var error: String?+  var body: some View {+    Picker("Purpose", selection: $purpose) {+      Text("None").tag(nil as Purpose?)+      ForEach(purposes.filter { !$0.isArchived || $0.id == purpose?.id }) {+        Text($0.name).tag($0 as Purpose?)+      }     }+    Button("Add Purpose…") { adding = true }+      .alert("Add purpose", isPresented: $adding) {+        TextField("Name", text: $name)+        Button("Cancel", role: .cancel) {}+        Button("Add") {+          do {+            purpose = try MedicationService(context: context).createPurpose(+              name: name, profileID: selectedProfileID)+          } catch { self.error = error.localizedDescription }+        }+      }+    if let error { Text(error).foregroundStyle(.red) }+  } }  struct TreatmentEditor: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    let profileID: UUID-    let treatment: Treatment?-    var onSaved: (Treatment) -> Void = { _ in }-    @State private var name: String-    @State private var instructions: String-    @State private var notes: String-    @State private var purpose: Purpose?-    @State private var error: String?-    init(treatment: Treatment? = nil, profileID: UUID = ProfileIdentity.me, onSaved: @escaping (Treatment) -> Void = { _ in }) {-        self.profileID = treatment?.profileID ?? profileID-        self.treatment = treatment; self.onSaved = onSaved-        _name = State(initialValue: treatment?.name ?? "")-        _instructions = State(initialValue: treatment?.instructions ?? "")-        _notes = State(initialValue: treatment?.notes ?? "")-        _purpose = State(initialValue: treatment?.purpose)-    }-    var body: some View {-        NavigationStack {-            Form {-                Section { TextField("Name", text: $name); PurposeField(purpose: $purpose).environment(\.careProfileID, profileID) }-                Section { TextField("Instructions", text: $instructions, axis: .vertical); TextField("Notes", text: $notes, axis: .vertical) }-                if let error { Text(error).foregroundStyle(.red) }-            }-            .scrollDismissesKeyboard(.immediately)-            .navigationTitle(treatment == nil ? "Add treatment" : "Edit treatment")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } }-            }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  let profileID: UUID+  let treatment: Treatment?+  var onSaved: (Treatment) -> Void = { _ in }+  @State private var name: String+  @State private var instructions: String+  @State private var notes: String+  @State private var purpose: Purpose?+  @State private var error: String?+  init(+    treatment: Treatment? = nil, profileID: UUID = ProfileIdentity.me,+    onSaved: @escaping (Treatment) -> Void = { _ in }+  ) {+    self.profileID = treatment?.profileID ?? profileID+    self.treatment = treatment+    self.onSaved = onSaved+    _name = State(initialValue: treatment?.name ?? "")+    _instructions = State(initialValue: treatment?.instructions ?? "")+    _notes = State(initialValue: treatment?.notes ?? "")+    _purpose = State(initialValue: treatment?.purpose)+  }+  var body: some View {+    NavigationStack {+      Form {+        Section {+          TextField("Name", text: $name)+          PurposeField(purpose: $purpose).environment(\.careProfileID, profileID)         }+        Section {+          TextField("Instructions", text: $instructions, axis: .vertical)+          TextField("Notes", text: $notes, axis: .vertical)+        }+        if let error { Text(error).foregroundStyle(.red) }+      }+      .scrollDismissesKeyboard(.immediately)+      .navigationTitle(treatment == nil ? "Add treatment" : "Edit treatment")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } }+      }     }-    private func save() {-        do {-            let service = TreatmentService(context: context)-            let saved: Treatment-            if let treatment { try service.update(treatment, name: name, instructions: instructions, notes: notes, purpose: purpose); saved = treatment }-            else { saved = try service.create(name: name, instructions: instructions, notes: notes, purpose: purpose, profileID: profileID) }-            onSaved(saved); dismiss()-        } catch { self.error = error.localizedDescription }-    }+  }+  private func save() {+    do {+      let service = TreatmentService(context: context)+      let saved: Treatment+      if let treatment {+        try service.update(+          treatment, name: name, instructions: instructions, notes: notes, purpose: purpose)+        saved = treatment+      } else {+        saved = try service.create(+          name: name, instructions: instructions, notes: notes, purpose: purpose,+          profileID: profileID)+      }+      onSaved(saved)+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }  struct TimedRoutineEditor: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    let profileID: UUID-    let routine: Routine?-    var onSaved: (Routine) -> Void = { _ in }-    @State private var name: String-    @State private var rounds: String-    @State private var seconds: String-    @State private var instructions: String-    @State private var between: String-    @State private var purpose: Purpose?-    @State private var error: String?-    init(routine: Routine? = nil, profileID: UUID = ProfileIdentity.me, onSaved: @escaping (Routine) -> Void = { _ in }) {-        self.profileID = routine?.profileID ?? profileID-        self.routine = routine; self.onSaved = onSaved-        _name = State(initialValue: routine?.name ?? "")-        _rounds = State(initialValue: routine?.roundCount.map(String.init) ?? "")-        _seconds = State(initialValue: routine?.roundDurationSeconds.map(String.init) ?? "")-        _instructions = State(initialValue: routine?.instructions ?? "")-        _between = State(initialValue: routine?.betweenRoundInstructions ?? "")-        _purpose = State(initialValue: routine?.purpose)-    }-    var body: some View {-        NavigationStack {-            Form {-                Section { TextField("Name", text: $name); PurposeField(purpose: $purpose).environment(\.careProfileID, profileID) }-                Section("Timer") {-                    TextField("Number of rounds", text: $rounds).keyboardType(.numberPad)-                    TextField("Seconds per round", text: $seconds).keyboardType(.numberPad)-                    Text("Each round starts only when you choose Start or Start next round.").font(.caption).foregroundStyle(.secondary)-                }-                Section { TextField("Instructions", text: $instructions, axis: .vertical); TextField("Between-round instructions", text: $between, axis: .vertical) }-                Section { Text("Existing sessions keep their saved timer settings.").font(.caption).foregroundStyle(.secondary) }-                if let error { Text(error).foregroundStyle(.red) }-            }-            .scrollDismissesKeyboard(.immediately)-            .navigationTitle(routine == nil ? "Add timed routine" : "Edit timed routine")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }-            }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  let profileID: UUID+  let routine: Routine?+  var onSaved: (Routine) -> Void = { _ in }+  @State private var name: String+  @State private var rounds: String+  @State private var seconds: String+  @State private var instructions: String+  @State private var between: String+  @State private var purpose: Purpose?+  @State private var error: String?+  init(+    routine: Routine? = nil, profileID: UUID = ProfileIdentity.me,+    onSaved: @escaping (Routine) -> Void = { _ in }+  ) {+    self.profileID = routine?.profileID ?? profileID+    self.routine = routine+    self.onSaved = onSaved+    _name = State(initialValue: routine?.name ?? "")+    _rounds = State(initialValue: routine?.roundCount.map(String.init) ?? "")+    _seconds = State(initialValue: routine?.roundDurationSeconds.map(String.init) ?? "")+    _instructions = State(initialValue: routine?.instructions ?? "")+    _between = State(initialValue: routine?.betweenRoundInstructions ?? "")+    _purpose = State(initialValue: routine?.purpose)+  }+  var body: some View {+    NavigationStack {+      Form {+        Section {+          TextField("Name", text: $name)+          PurposeField(purpose: $purpose).environment(\.careProfileID, profileID)         }+        Section("Timer") {+          TextField("Number of rounds", text: $rounds).keyboardType(.numberPad)+          TextField("Seconds per round", text: $seconds).keyboardType(.numberPad)+          Text("Each round starts only when you choose Start or Start next round.").font(.caption)+            .foregroundStyle(.secondary)+        }+        Section {+          TextField("Instructions", text: $instructions, axis: .vertical)+          TextField("Between-round instructions", text: $between, axis: .vertical)+        }+        Section {+          Text("Existing sessions keep their saved timer settings.").font(.caption).foregroundStyle(+            .secondary)+        }+        if let error { Text(error).foregroundStyle(.red) }+      }+      .scrollDismissesKeyboard(.immediately)+      .navigationTitle(routine == nil ? "Add timed routine" : "Edit timed routine")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }+      }     }-    private func save() {-        do {-            guard let rounds = Int(rounds), let seconds = Int(seconds) else { throw DefinitionError.invalidTimer }-            let service = RoutineService(context: context)-            let saved: Routine-            if let routine { try service.updateTimed(routine, name: name, rounds: rounds, durationSeconds: seconds, instructions: instructions, betweenRounds: between, purpose: purpose); saved = routine }-            else { saved = try service.createTimed(name: name, rounds: rounds, durationSeconds: seconds, instructions: instructions, betweenRounds: between, purpose: purpose, profileID: profileID) }-            onSaved(saved); dismiss()-        } catch { self.error = error.localizedDescription }-    }+  }+  private func save() {+    do {+      guard let rounds = Int(rounds), let seconds = Int(seconds) else {+        throw DefinitionError.invalidTimer+      }+      let service = RoutineService(context: context)+      let saved: Routine+      if let routine {+        try service.updateTimed(+          routine, edit: TimedRoutineEdit(name: name, rounds: rounds, durationSeconds: seconds, instructions: instructions,+          betweenRounds: between, purpose: purpose))+        saved = routine+      } else {+        saved = try service.createTimed(+          name: name, rounds: rounds, durationSeconds: seconds, instructions: instructions,+          betweenRounds: between, purpose: purpose, profileID: profileID)+      }+      onSaved(saved)+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }  struct OrderedRoutineEditor: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    @Query(sort: \Treatment.name) private var allTreatments: [Treatment]-    private var treatments: [Treatment] { allTreatments.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \Routine.name) private var allRoutines: [Routine]-    private var routines: [Routine] { allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \Medication.name) private var allMedications: [Medication]-    private var medications: [Medication] { allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    let profileID: UUID-    let routine: Routine?-    @State private var name: String-    @State private var instructions: String-    @State private var purpose: Purpose?-    @State private var steps: [RoutineStepDraft]-    @State private var scheduled: Bool-    @State private var slotCount: String-    @State private var wakeOffsetTexts: [UUID: String]-    @State private var slots: [DailyRoutineSlot]-    @State private var timeTexts: [UUID: String]-    @State private var reminders: Bool-    @State private var ownershipConfirmed = false-    @State private var archiveEmptyOwners: Set<UUID> = []-    @State private var releaseAsNeeded: Set<UUID> = []-    @State private var addingTreatment = false-    @State private var addingTimed = false-    @State private var addingMedication = false-    @State private var error: String?+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  @Query(sort: \Treatment.name) private var allTreatments: [Treatment]+  private var treatments: [Treatment] {+    allTreatments.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \Routine.name) private var allRoutines: [Routine]+  private var routines: [Routine] {+    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \Medication.name) private var allMedications: [Medication]+  private var medications: [Medication] {+    allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  let profileID: UUID+  let routine: Routine?+  @State private var name: String+  @State private var instructions: String+  @State private var purpose: Purpose?+  @State private var steps: [RoutineStepDraft]+  @State private var scheduled: Bool+  @State private var slotCount: String+  @State private var wakeOffsetTexts: [UUID: String]+  @State private var slots: [DailyRoutineSlot]+  @State private var timeTexts: [UUID: String]+  @State private var reminders: Bool+  @State private var ownershipConfirmed = false+  @State private var archiveEmptyOwners: Set<UUID> = []+  @State private var releaseAsNeeded: Set<UUID> = []+  @State private var addingTreatment = false+  @State private var addingTimed = false+  @State private var addingMedication = false+  @State private var error: String? -    init(routine: Routine? = nil, profileID: UUID = ProfileIdentity.me) {-        self.profileID = routine?.profileID ?? profileID-        self.routine = routine-        _name = State(initialValue: routine?.name ?? "")-        _instructions = State(initialValue: routine?.instructions ?? "")-        _purpose = State(initialValue: routine?.purpose)-        _steps = State(initialValue: (routine?.steps ?? []).sorted { $0.position < $1.position }.compactMap { step in-            RoutineStepTargetKind(rawValue: step.targetKindRaw).map { RoutineStepDraft(id: step.id, kind: $0, targetID: step.targetID) }-        })-        let pending = routine?.pendingScheduleData.flatMap { try? JSONDecoder().decode(PendingRoutineSchedule.self, from: $0) }-        let slots = pending?.configuration.slots ?? routine?.dailySlotsData.flatMap { try? JSONDecoder().decode([DailyRoutineSlot].self, from: $0) } ?? []-        _slots = State(initialValue: slots)-        _wakeOffsetTexts = State(initialValue: Dictionary(uniqueKeysWithValues: slots.map { ($0.id, $0.wakeOffsetMinutes.map(String.init) ?? "0") }))-        _timeTexts = State(initialValue: Dictionary(uniqueKeysWithValues: slots.map { ($0.id, $0.minuteOfDay.map(ScheduleTimeInput.text) ?? "") }))-        _scheduled = State(initialValue: routine?.scheduleTypeRaw == "dailySlots" || pending != nil)-        _slotCount = State(initialValue: slots.isEmpty ? "" : String(slots.count))-        _reminders = State(initialValue: routine?.remindersEnabled ?? false)+  init(routine: Routine? = nil, profileID: UUID = ProfileIdentity.me) {+    self.profileID = routine?.profileID ?? profileID+    self.routine = routine+    _name = State(initialValue: routine?.name ?? "")+    _instructions = State(initialValue: routine?.instructions ?? "")+    _purpose = State(initialValue: routine?.purpose)+    _steps = State(+      initialValue: (routine?.steps ?? []).sorted { $0.position < $1.position }.compactMap { step in+        RoutineStepTargetKind(rawValue: step.targetKindRaw).map {+          RoutineStepDraft(id: step.id, kind: $0, targetID: step.targetID)+        }+      })+    let pending = routine?.pendingScheduleData.flatMap {+      try? JSONDecoder().decode(PendingRoutineSchedule.self, from: $0)     }+    let slots =+      pending?.configuration.slots ?? routine?.dailySlotsData.flatMap {+        try? JSONDecoder().decode([DailyRoutineSlot].self, from: $0)+      } ?? []+    _slots = State(initialValue: slots)+    _wakeOffsetTexts = State(+      initialValue: Dictionary(+        uniqueKeysWithValues: slots.map { ($0.id, $0.wakeOffsetMinutes.map(String.init) ?? "0") }))+    _timeTexts = State(+      initialValue: Dictionary(+        uniqueKeysWithValues: slots.map {+          ($0.id, $0.minuteOfDay.map(ScheduleTimeInput.text) ?? "")+        }))+    _scheduled = State(initialValue: routine?.scheduleTypeRaw == "dailySlots" || pending != nil)+    _slotCount = State(initialValue: slots.isEmpty ? "" : String(slots.count))+    _reminders = State(initialValue: routine?.remindersEnabled ?? false)+  } -    private var oldMedicationIDs: Set<UUID> { Set((routine?.steps ?? []).filter { $0.targetKindRaw == "medication" }.map(\.targetID)) }-    private var medicationIDs: Set<UUID> { Set(steps.filter { $0.kind == .medication }.map(\.targetID)) }-    private var addedMedicationIDs: Set<UUID> { medicationIDs.subtracting(oldMedicationIDs) }-    private var removedMedicationIDs: Set<UUID> { oldMedicationIDs.subtracting(medicationIDs) }+  private var oldMedicationIDs: Set<UUID> {+    Set((routine?.steps ?? []).filter { $0.targetKindRaw == "medication" }.map(\.targetID))+  }+  private var medicationIDs: Set<UUID> {+    Set(steps.filter { $0.kind == .medication }.map(\.targetID))+  }+  private var addedMedicationIDs: Set<UUID> { medicationIDs.subtracting(oldMedicationIDs) }+  private var removedMedicationIDs: Set<UUID> { oldMedicationIDs.subtracting(medicationIDs) } -    private var transfers: Set<UUID> { Set(medications.filter { medicationIDs.contains($0.id) && $0.managedByRoutineID != nil && $0.managedByRoutineID != routine?.id }.map(\.id)) }-    private var emptyOwners: [Routine] { routines.filter { item in-        item.id != routine?.id && !(item.steps ?? []).isEmpty && (item.steps ?? []).allSatisfy { $0.targetKindRaw == "medication" && transfers.contains($0.targetID) }-    } }+  private var transfers: Set<UUID> {+    Set(+      medications.filter {+        medicationIDs.contains($0.id) && $0.managedByRoutineID != nil+          && $0.managedByRoutineID != routine?.id+      }.map(\.id))+  }+  private var emptyOwners: [Routine] {+    routines.filter { item in+      item.id != routine?.id && !(item.steps ?? []).isEmpty+        && (item.steps ?? []).allSatisfy {+          $0.targetKindRaw == "medication" && transfers.contains($0.targetID)+        }+    }+  } -    var body: some View {-        NavigationStack {-            Form {-                Section { TextField("Name", text: $name); PurposeField(purpose: $purpose).environment(\.careProfileID, profileID); TextField("Instructions", text: $instructions, axis: .vertical) }-                Section("Ordered steps") {-                    ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in-                        VStack(alignment: .leading) {-                            Text("\(index + 1). \(targetName(step))")-                            if !targetIsAvailable(step) { Text("Item missing or archived · Repair this plan").font(.caption).foregroundStyle(.red) }-                            HStack {-                                Button("Move up") { steps.swapAt(index, index - 1) }.disabled(index == 0)-                                Button("Move down") { steps.swapAt(index, index + 1) }.disabled(index + 1 == steps.count)-                                Button("Remove", role: .destructive) { steps.remove(at: index) }-                            }.font(.caption).buttonStyle(.borderless)-                        }-                    }.onMove { indices, destination in steps.move(fromOffsets: indices, toOffset: destination) }-                    Menu("Add existing step", systemImage: "plus") {-                        Section("Treatment items") { ForEach(treatments.filter(\.isActive)) { item in Button(item.name) { steps.append(.init(kind: .treatment, targetID: item.id)) } } }-                        Section("Timed routines") { ForEach(routines.filter { $0.isActive && $0.kindRaw == "timedRounds" }) { item in Button(item.name) { steps.append(.init(kind: .timedRoutine, targetID: item.id)) } } }-                        Section("Medications") { ForEach(medications.filter(\.isActive)) { item in-                            Button { steps.append(.init(kind: .medication, targetID: item.id)) } label: {-                                HStack { MedicationPhotoView(data: item.recognitionPhotoData, name: item.name); Text(item.name) }-                            }-                                .disabled(medicationIDs.contains(item.id))-                        } }-                    }-                    Menu("Create an item") {-                        Button("Treatment item") { addingTreatment = true }-                        Button("Timed routine") { addingTimed = true }-                        Button("Medication") { addingMedication = true }-                    }+  var body: some View {+    NavigationStack {+      Form {+        Section {+          TextField("Name", text: $name)+          PurposeField(purpose: $purpose).environment(\.careProfileID, profileID)+          TextField("Instructions", text: $instructions, axis: .vertical)+        }+        Section("Ordered steps") {+          ForEach(Array(steps.enumerated()), id: \.element.id) { index, step in+            VStack(alignment: .leading) {+              Text("\(index + 1). \(targetName(step))")+              if !targetIsAvailable(step) {+                Text("Item missing or archived · Repair this plan").font(.caption).foregroundStyle(+                  .red)+              }+              HStack {+                Button("Move up") { steps.swapAt(index, index - 1) }.disabled(index == 0)+                Button("Move down") { steps.swapAt(index, index + 1) }.disabled(+                  index + 1 == steps.count)+                Button("Remove", role: .destructive) { steps.remove(at: index) }+              }.font(.caption).buttonStyle(.borderless)+            }+          }.onMove { indices, destination in steps.move(fromOffsets: indices, toOffset: destination)+          }+          Menu("Add existing step", systemImage: "plus") {+            Section("Treatment items") {+              ForEach(treatments.filter(\.isActive)) { item in+                Button(item.name) { steps.append(.init(kind: .treatment, targetID: item.id)) }+              }+            }+            Section("Timed routines") {+              ForEach(routines.filter { $0.isActive && $0.kindRaw == "timedRounds" }) { item in+                Button(item.name) { steps.append(.init(kind: .timedRoutine, targetID: item.id)) }+              }+            }+            Section("Medications") {+              ForEach(medications.filter(\.isActive)) { item in+                Button {+                  steps.append(.init(kind: .medication, targetID: item.id))+                } label: {+                  HStack {+                    MedicationPhotoView(data: item.recognitionPhotoData, name: item.name)+                    Text(item.name)+                  }                 }-                if !addedMedicationIDs.isEmpty {-                    Section("Medication reminder ownership") {-                        ForEach(medications.filter { addedMedicationIDs.contains($0.id) }) { Text($0.name) }-                        Text("Saving will cancel their standalone reminders and snoozes. History is preserved; this routine will own their reminders.").font(.caption)-                        ForEach(medications.filter { transfers.contains($0.id) }) { item in-                            Text("Move \(item.name) from \(routines.first { $0.id == item.managedByRoutineID }?.name ?? "earlier routine"). This edits both plans together and keeps saved histories.").font(.caption)-                        }-                        ForEach(emptyOwners) { owner in-                            Toggle("Archive empty \(owner.name)", isOn: Binding(get: { archiveEmptyOwners.contains(owner.id) }, set: { if $0 { archiveEmptyOwners.insert(owner.id) } else { archiveEmptyOwners.remove(owner.id) } }))-                        }-                        Toggle("Confirm ownership change", isOn: $ownershipConfirmed)+                .disabled(medicationIDs.contains(item.id))+              }+            }+          }+          Menu("Create an item") {+            Button("Treatment item") { addingTreatment = true }+            Button("Timed routine") { addingTimed = true }+            Button("Medication") { addingMedication = true }+          }+        }+        if !addedMedicationIDs.isEmpty {+          Section("Medication reminder ownership") {+            ForEach(medications.filter { addedMedicationIDs.contains($0.id) }) { Text($0.name) }+            Text(+              "Saving will cancel their standalone reminders and snoozes. History is preserved; this routine will own their reminders."+            ).font(.caption)+            ForEach(medications.filter { transfers.contains($0.id) }) { item in+              Text(+                "Move \(item.name) from \(routines.first { $0.id == item.managedByRoutineID }?.name ?? "earlier routine"). This edits both plans together and keeps saved histories."+              ).font(.caption)+            }+            ForEach(emptyOwners) { owner in+              Toggle(+                "Archive empty \(owner.name)",+                isOn: Binding(+                  get: { archiveEmptyOwners.contains(owner.id) },+                  set: {+                    if $0 {+                      archiveEmptyOwners.insert(owner.id)+                    } else {+                      archiveEmptyOwners.remove(owner.id)                     }-                }-                if !removedMedicationIDs.isEmpty {-                    Section("Removed medications") {-                        ForEach(medications.filter { removedMedicationIDs.contains($0.id) }) { item in-                            Toggle("Return \(item.name) to As needed", isOn: Binding(get: { releaseAsNeeded.contains(item.id) }, set: { if $0 { releaseAsNeeded.insert(item.id) } else { releaseAsNeeded.remove(item.id) } }))-                        }-                        Text("No old schedule or reminders are restored. Unfinished saved medication steps need explicit resolution first.").font(.caption)+                  }))+            }+            Toggle("Confirm ownership change", isOn: $ownershipConfirmed)+          }+        }+        if !removedMedicationIDs.isEmpty {+          Section("Removed medications") {+            ForEach(medications.filter { removedMedicationIDs.contains($0.id) }) { item in+              Toggle(+                "Return \(item.name) to As needed",+                isOn: Binding(+                  get: { releaseAsNeeded.contains(item.id) },+                  set: {+                    if $0 {+                      releaseAsNeeded.insert(item.id)+                    } else {+                      releaseAsNeeded.remove(item.id)                     }+                  }))+            }+            Text(+              "No old schedule or reminders are restored. Unfinished saved medication steps need explicit resolution first."+            ).font(.caption)+          }+        }+        Section("Group schedule") {+          Toggle("Daily sessions", isOn: $scheduled)+          if scheduled {+            TextField("Daily session count", text: $slotCount).keyboardType(.numberPad)+              .onChange(of: slotCount) { _, _ in resizeSlots() }+            ForEach($slots) { $slot in+              VStack(alignment: .leading) {+                TextField("Optional session label", text: $slot.label)+                if slot.wakeOffsetMinutes != nil {+                  TextField(+                    "Minutes after waking (0–1440)",+                    text: Binding(+                      get: { wakeOffsetTexts[slot.id] ?? "0" },+                      set: { wakeOffsetTexts[slot.id] = $0 })+                  ).keyboardType(.numberPad)+                } else {+                  TextField(+                    "Optional time (HH:mm)",+                    text: Binding(+                      get: { timeTexts[slot.id] ?? "" }, set: { timeTexts[slot.id] = $0 })+                  ).keyboardType(.numbersAndPunctuation)                 }-                Section("Group schedule") {-                    Toggle("Daily sessions", isOn: $scheduled)-                    if scheduled {-                        TextField("Daily session count", text: $slotCount).keyboardType(.numberPad)-                            .onChange(of: slotCount) { _, _ in resizeSlots() }-                        ForEach($slots) { $slot in-                            VStack(alignment: .leading) {-                                TextField("Optional session label", text: $slot.label)-                                if slot.wakeOffsetMinutes != nil {-                                    TextField("Minutes after waking (0–1440)", text: Binding(get: { wakeOffsetTexts[slot.id] ?? "0" }, set: { wakeOffsetTexts[slot.id] = $0 })).keyboardType(.numberPad)-                                } else {-                                    TextField("Optional time (HH:mm)", text: Binding(get: { timeTexts[slot.id] ?? "" }, set: { timeTexts[slot.id] = $0 })).keyboardType(.numbersAndPunctuation)-                                }-                                Menu("Session timing option") {-                                    Button("After waking") { slot.minuteOfDay = nil; slot.wakeOffsetMinutes = 0; timeTexts[slot.id] = ""; wakeOffsetTexts[slot.id] = "0" }-                                    Button("Clock time / untimed") { slot.wakeOffsetMinutes = nil }-                                    Button(TimingCue.beforeSleeping.rawValue) {-                                        TimingCue.beforeSleeping.applying(to: &slot)-                                        timeTexts[slot.id] = ""; reminders = false-                                    }-                                }-                            }-                        }-                        Toggle("Enable reminders", isOn: $reminders)-                            .onChange(of: reminders) { _, enabled in if enabled { requestReminders() } }-                        Text("After waking uses Record Waking Up in Shortcuts for this profile; 0 means at wake, and changes wait for the next wake. Untimed sessions have no due time. Days start at 02:00. Before sleeping is untimed. A frequency change takes effect at the next logical-day boundary; saved sessions keep their plan.").font(.caption).foregroundStyle(.secondary)-                    }+                Menu("Session timing option") {+                  Button("After waking") {+                    slot.minuteOfDay = nil+                    slot.wakeOffsetMinutes = 0+                    timeTexts[slot.id] = ""+                    wakeOffsetTexts[slot.id] = "0"+                  }+                  Button("Clock time / untimed") { slot.wakeOffsetMinutes = nil }+                  Button(TimingCue.beforeSleeping.rawValue) {+                    TimingCue.beforeSleeping.applying(to: &slot)+                    timeTexts[slot.id] = ""+                    reminders = false+                  }                 }-                if let error { Text(error).foregroundStyle(.red) }+              }             }-            .scrollDismissesKeyboard(.immediately)-            .navigationTitle(routine == nil ? "Add ordered routine" : "Edit ordered routine")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }-                ToolbarItem(placement: .bottomBar) { EditButton() }-            }-            .sheet(isPresented: $addingTreatment) { TreatmentEditor(profileID: profileID) { steps.append(.init(kind: .treatment, targetID: $0.id)) } }-            .sheet(isPresented: $addingTimed) { TimedRoutineEditor(profileID: profileID) { steps.append(.init(kind: .timedRoutine, targetID: $0.id)) } }-            .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: profileID) }+            Toggle("Enable reminders", isOn: $reminders)+              .onChange(of: reminders) { _, enabled in if enabled { requestReminders() } }+            Text(+              """+              After waking uses Record Waking Up in Shortcuts for this profile; 0 means at wake, and changes wait for the \+              next wake. Untimed sessions have no due time. Days start at 02:00. Before sleeping is untimed. A frequency \+              change takes effect at the next logical-day boundary; saved sessions keep their plan.+              """+            ).font(.caption).foregroundStyle(.secondary)+          }+        }+        if let error { Text(error).foregroundStyle(.red) }+      }+      .scrollDismissesKeyboard(.immediately)+      .navigationTitle(routine == nil ? "Add ordered routine" : "Edit ordered routine")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }+        ToolbarItem(placement: .bottomBar) { EditButton() }+      }+      .sheet(isPresented: $addingTreatment) {+        TreatmentEditor(profileID: profileID) {+          steps.append(.init(kind: .treatment, targetID: $0.id))+        }+      }+      .sheet(isPresented: $addingTimed) {+        TimedRoutineEditor(profileID: profileID) {+          steps.append(.init(kind: .timedRoutine, targetID: $0.id))         }+      }+      .sheet(isPresented: $addingMedication) { MedicationEditor(profileID: profileID) }     }-    private func resizeSlots() {-        guard let count = Int(slotCount), count > 0, count <= 1000 else { return }-        while slots.count < count { slots.append(.init()) }-        if slots.count > count { slots.removeLast(slots.count - count) }+  }+  private func resizeSlots() {+    guard let count = Int(slotCount), count > 0, count <= 1000 else { return }+    while slots.count < count { slots.append(.init()) }+    if slots.count > count { slots.removeLast(slots.count - count) }+  }+  private func targetName(_ step: RoutineStepDraft) -> String {+    switch step.kind {+    case .treatment: treatments.first { $0.id == step.targetID }?.name ?? "Missing treatment"+    case .timedRoutine: routines.first { $0.id == step.targetID }?.name ?? "Missing timed routine"+    case .medication: medications.first { $0.id == step.targetID }?.name ?? "Missing medication"     }-    private func targetName(_ step: RoutineStepDraft) -> String {-        switch step.kind {-        case .treatment: treatments.first { $0.id == step.targetID }?.name ?? "Missing treatment"-        case .timedRoutine: routines.first { $0.id == step.targetID }?.name ?? "Missing timed routine"-        case .medication: medications.first { $0.id == step.targetID }?.name ?? "Missing medication"-        }+  }+  private func targetIsAvailable(_ step: RoutineStepDraft) -> Bool {+    switch step.kind {+    case .treatment: treatments.first { $0.id == step.targetID }?.isActive == true+    case .timedRoutine:+      routines.first { $0.id == step.targetID }.map { $0.isActive && $0.kindRaw == "timedRounds" }+        == true+    case .medication: medications.first { $0.id == step.targetID }?.isActive == true     }-    private func targetIsAvailable(_ step: RoutineStepDraft) -> Bool {-        switch step.kind {-        case .treatment: treatments.first { $0.id == step.targetID }?.isActive == true-        case .timedRoutine: routines.first { $0.id == step.targetID }.map { $0.isActive && $0.kindRaw == "timedRounds" } == true-        case .medication: medications.first { $0.id == step.targetID }?.isActive == true-        }+  }+  private func requestReminders() {+    guard+      slots.allSatisfy({+        $0.wakeOffsetMinutes != nil+          || (try? ScheduleTimeInput.minute(timeTexts[$0.id] ?? "")) != nil+      })+    else {+      reminders = false+      error = "Set a time for every daily session before enabling reminders."+      return     }-    private func requestReminders() {-        guard slots.allSatisfy({ $0.wakeOffsetMinutes != nil || (try? ScheduleTimeInput.minute(timeTexts[$0.id] ?? "")) != nil }) else {-            reminders = false; error = "Set a time for every daily session before enabling reminders."; return+    Task {+      do {+        guard !AppEnvironment.isTesting else {+          reminders = false+          return         }-        Task {-            do {-                guard !AppEnvironment.isTesting else { reminders = false; return }-                let granted = try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])-                if !granted { reminders = false; error = "Notifications are not allowed. You can still use every session." }-            } catch { reminders = false; self.error = error.localizedDescription }+        let granted = try await UNUserNotificationCenter.current().requestAuthorization(options: [+          .alert, .sound, .badge+        ])+        if !granted {+          reminders = false+          error = "Notifications are not allowed. You can still use every session."         }+      } catch {+        reminders = false+        self.error = error.localizedDescription+      }     }-    private func save() {-        do {-            if scheduled {-                guard let count = Int(slotCount), count > 0, count == slots.count else { throw DefinitionError.invalidSchedule }-            }-            let chosenSlots: [DailyRoutineSlot]? = scheduled ? try slots.map { slot in-                var value = slot; let text = (timeTexts[slot.id] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)-                if value.wakeOffsetMinutes != nil {-                    guard let offset = Int((wakeOffsetTexts[slot.id] ?? "0").trimmingCharacters(in: .whitespacesAndNewlines)), WakeTiming.valid(offset) else { throw DefinitionError.invalidSchedule }-                    value.wakeOffsetMinutes = offset; value.minuteOfDay = nil-                } else { value.minuteOfDay = text.isEmpty ? nil : try ScheduleTimeInput.minute(text) }-                return value-            } : nil-            _ = try EditorTransaction.save(context: context) {-                let definitions = RoutineService(context: context, deferSave: true)-                let saved: Routine-                if let routine {-                    try definitions.updateOrdered(routine, name: name, steps: steps, instructions: instructions, purpose: purpose, confirmedMedicationIDs: ownershipConfirmed ? addedMedicationIDs : [], releasedAsNeededMedicationIDs: releaseAsNeeded, transferredMedicationIDs: ownershipConfirmed ? transfers : [], archiveEmptyOwnerIDs: archiveEmptyOwners)-                    saved = routine-                } else {-                    saved = try definitions.createOrdered(name: name, steps: steps, instructions: instructions, purpose: purpose, confirmedMedicationIDs: ownershipConfirmed ? addedMedicationIDs : [], transferredMedicationIDs: ownershipConfirmed ? transfers : [], archiveEmptyOwnerIDs: archiveEmptyOwners, profileID: profileID)-                }-                try ScheduleService(context: context, deferSave: true).configure(saved, slots: chosenSlots, reminders: scheduled && reminders)-                return saved-            }-            dismiss()-        } catch { self.error = error.localizedDescription }-    }+  }+  private func save() {+    do {+      if scheduled {+        guard let count = Int(slotCount), count > 0, count == slots.count else {+          throw DefinitionError.invalidSchedule+        }+      }+      let chosenSlots: [DailyRoutineSlot]? =+        scheduled+        ? try slots.map { slot in+          var value = slot+          let text = (timeTexts[slot.id] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)+          if value.wakeOffsetMinutes != nil {+            guard+              let offset = Int(+                (wakeOffsetTexts[slot.id] ?? "0").trimmingCharacters(in: .whitespacesAndNewlines)),+              WakeTiming.valid(offset)+            else { throw DefinitionError.invalidSchedule }+            value.wakeOffsetMinutes = offset+            value.minuteOfDay = nil+          } else {+            value.minuteOfDay = text.isEmpty ? nil : try ScheduleTimeInput.minute(text)+          }+          return value+        } : nil+      _ = try EditorTransaction.save(context: context) {+        let definitions = RoutineService(context: context, deferSave: true)+        let saved: Routine+        if let routine {+          try definitions.updateOrdered(+            routine, name: name, steps: steps, instructions: instructions, purpose: purpose,+            confirmedMedicationIDs: ownershipConfirmed ? addedMedicationIDs : [],+            releasedAsNeededMedicationIDs: releaseAsNeeded,+            transferredMedicationIDs: ownershipConfirmed ? transfers : [],+            archiveEmptyOwnerIDs: archiveEmptyOwners)+          saved = routine+        } else {+          saved = try definitions.createOrdered(+            name: name, steps: steps, instructions: instructions, purpose: purpose,+            confirmedMedicationIDs: ownershipConfirmed ? addedMedicationIDs : [],+            transferredMedicationIDs: ownershipConfirmed ? transfers : [],+            archiveEmptyOwnerIDs: archiveEmptyOwners, profileID: profileID)+        }+        try ScheduleService(context: context, deferSave: true).configure(+          saved, slots: chosenSlots, reminders: scheduled && reminders)+        return saved+      }+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }
Meddy/Meddy/Features/ConsultationMarkdown.swift Modified
diff --git a/Meddy/Meddy/Features/ConsultationMarkdown.swift b/Meddy/Meddy/Features/ConsultationMarkdown.swiftindex f33ec02..af06cbd 100644--- a/Meddy/Meddy/Features/ConsultationMarkdown.swift+++ b/Meddy/Meddy/Features/ConsultationMarkdown.swift@@ -1,70 +1,88 @@-import Foundation import CoreTransferable+import Foundation import UniformTypeIdentifiers  nonisolated struct ConsultationMedication: Sendable {-    var id: UUID-    var purpose: String-    var name: String-    var dose: String?-    var method: String-    var requirements: String-    var schedule: String+  var id: UUID+  var purpose: String+  var name: String+  var dose: String?+  var method: String+  var requirements: String+  var schedule: String }  nonisolated struct ConsultationMarkdownExport: Transferable {-    let markdown: String-    let filename: String-    var data: Data { Data(markdown.utf8) }-    static var transferRepresentation: some TransferRepresentation {-        DataRepresentation(exportedContentType: .markdown) { $0.data }-            .suggestedFileName { $0.filename }-    }+  let markdown: String+  let filename: String+  var data: Data { Data(markdown.utf8) }+  static var transferRepresentation: some TransferRepresentation {+    DataRepresentation(exportedContentType: .markdown) { $0.data }+      .suggestedFileName { $0.filename }+  } }  nonisolated enum ConsultationMarkdown {-    static func make(_ medications: [ConsultationMedication], preparedAt: Date, timeZone: TimeZone, profileID: UUID? = nil, profileLabel: String = "Me") -> ConsultationMarkdownExport {-        let timestamp = ISO8601DateFormatter()-        timestamp.timeZone = timeZone-        timestamp.formatOptions = [.withInternetDateTime]-        let date = DateFormatter()-        date.locale = Locale(identifier: "en_US_POSIX")-        date.calendar = Calendar(identifier: .gregorian)-        date.timeZone = timeZone-        date.dateFormat = "yyyy-MM-dd"-        var lines = ["# Current medications", "", "Prepared: \(timestamp.string(from: preparedAt))", ""]-        if let profileID { lines += ["Profile: \(inline(profileLabel)) (\(profileID.uuidString))", ""] }-        let ordered = medications.sorted { left, right in-            if left.purpose != right.purpose { return left.purpose < right.purpose }-            if left.name != right.name { return left.name < right.name }-            return left.id.uuidString < right.id.uuidString-        }-        var lastPurpose: String?-        for medication in ordered {-            if medication.purpose != lastPurpose {-                lines += ["## \(inline(medication.purpose))", ""]-                lastPurpose = medication.purpose-            }-            lines += ["### \(inline(medication.name))", ""]-            if let dose = medication.dose { lines.append("- **Dose:** \(inline(dose))") }-            if !medication.method.isEmpty { lines.append("- **How to take / apply:** \(inline(medication.method))") }-            if !medication.requirements.isEmpty { lines.append("- **Requirements:** \(inline(medication.requirements))") }-            lines.append("- **Schedule:** \(inline(medication.schedule))")-            lines.append("")-        }-        if ordered.isEmpty { lines += ["No active medications recorded.", ""] }-        return .init(markdown: lines.joined(separator: "\n"), filename: "meddy-current-medications-\(profileID.map { $0.uuidString + "-" } ?? "")\(date.string(from: preparedAt)).md")+  static func make(+    _ medications: [ConsultationMedication], preparedAt: Date, timeZone: TimeZone,+    profileID: UUID? = nil, profileLabel: String = "Me"+  ) -> ConsultationMarkdownExport {+    let timestamp = ISO8601DateFormatter()+    timestamp.timeZone = timeZone+    timestamp.formatOptions = [.withInternetDateTime]+    let date = DateFormatter()+    date.locale = Locale(identifier: "en_US_POSIX")+    date.calendar = Calendar(identifier: .gregorian)+    date.timeZone = timeZone+    date.dateFormat = "yyyy-MM-dd"+    var lines = [+      "# Current medications", "", "Prepared: \(timestamp.string(from: preparedAt))", ""+    ]+    if let profileID {+      lines += ["Profile: \(inline(profileLabel)) (\(profileID.uuidString))", ""]     }--    // Escape user-authored Markdown/HTML rather than letting it change the document structure.-    // Generated <br> keeps intentional newlines inside one heading/list item, including blank lines.-    static func inline(_ value: String) -> String {-        let punctuation = Set("\\`*_{}[]()<>#+-.!|~&")-        return value.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")-            .components(separatedBy: "\n").map { line in-                String(line.flatMap { character -> [Character] in-                    punctuation.contains(character) ? ["\\", character] : [character]-                })-            }.joined(separator: "<br>")+    let ordered = medications.sorted { left, right in+      if left.purpose != right.purpose { return left.purpose < right.purpose }+      if left.name != right.name { return left.name < right.name }+      return left.id.uuidString < right.id.uuidString+    }+    var lastPurpose: String?+    for medication in ordered {+      if medication.purpose != lastPurpose {+        lines += ["## \(inline(medication.purpose))", ""]+        lastPurpose = medication.purpose+      }+      lines += ["### \(inline(medication.name))", ""]+      if let dose = medication.dose { lines.append("- **Dose:** \(inline(dose))") }+      if !medication.method.isEmpty {+        lines.append("- **How to take / apply:** \(inline(medication.method))")+      }+      if !medication.requirements.isEmpty {+        lines.append("- **Requirements:** \(inline(medication.requirements))")+      }+      lines.append("- **Schedule:** \(inline(medication.schedule))")+      lines.append("")     }+    if ordered.isEmpty { lines += ["No active medications recorded.", ""] }+    return .init(+      markdown: lines.joined(separator: "\n"),+      filename:+        "meddy-current-medications-\(profileID.map { $0.uuidString + "-" } ?? "")\(date.string(from: preparedAt)).md"+    )+  }++  // Escape user-authored Markdown/HTML rather than letting it change the document structure.+  // Generated <br> keeps intentional newlines inside one heading/list item, including blank lines.+  static func inline(_ value: String) -> String {+    let punctuation = Set("\\`*_{}[]()<>#+-.!|~&")+    return value.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(+      of: "\r", with: "\n"+    )+    .components(separatedBy: "\n").map { line in+      String(+        line.flatMap { character -> [Character] in+          punctuation.contains(character) ? ["\\", character] : [character]+        })+    }.joined(separator: "<br>")+  } }
Meddy/Meddy/Features/LogicalDayEnvironment.swift Modified
diff --git a/Meddy/Meddy/Features/LogicalDayEnvironment.swift b/Meddy/Meddy/Features/LogicalDayEnvironment.swiftindex e148001..92cf23b 100644--- a/Meddy/Meddy/Features/LogicalDayEnvironment.swift+++ b/Meddy/Meddy/Features/LogicalDayEnvironment.swift@@ -2,11 +2,11 @@ import Foundation import SwiftUI  private struct LogicalDayNowKey: EnvironmentKey {-    static var defaultValue: Date { Date() }+  static var defaultValue: Date { Date() } } extension EnvironmentValues {-    var logicalDayNow: Date {-        get { self[LogicalDayNowKey.self] }-        set { self[LogicalDayNowKey.self] = newValue }-    }+  var logicalDayNow: Date {+    get { self[LogicalDayNowKey.self] }+    set { self[LogicalDayNowKey.self] = newValue }+  } }
Meddy/Meddy/Features/LogicalDayPresentation.swift Modified
diff --git a/Meddy/Meddy/Features/LogicalDayPresentation.swift b/Meddy/Meddy/Features/LogicalDayPresentation.swiftindex 2f6a869..16ba4bd 100644--- a/Meddy/Meddy/Features/LogicalDayPresentation.swift+++ b/Meddy/Meddy/Features/LogicalDayPresentation.swift@@ -2,9 +2,14 @@ import Foundation  @MainActor extension RoutineRun {-    var logicalDayLabel: String? {-        ScheduleCalendar.runDate(.init(id: id, routineID: routineID, occurrenceKey: occurrenceKey, slotID: slotID,-            localDate: scheduledLocalDate ?? startedAt.map { ScheduleCalendar.localDate($0, calendar: .current) }, startedAt: startedAt, timeZoneID: scheduledTimeZoneID,-            scheduledAt: scheduledAt, status: SessionPhase(rawValue: statusRaw) ?? .needsReview, isDeleted: isDeleted), calendar: .current)-    }+  var logicalDayLabel: String? {+    ScheduleCalendar.runDate(+      .init(+        id: id, routineID: routineID, occurrenceKey: occurrenceKey, slotID: slotID,+        localDate: scheduledLocalDate+          ?? startedAt.map { ScheduleCalendar.localDate($0, calendar: .current) },+        startedAt: startedAt, timeZoneID: scheduledTimeZoneID,+        scheduledAt: scheduledAt, status: SessionPhase(rawValue: statusRaw) ?? .needsReview,+        isDeleted: isDeleted), calendar: .current)+  } }
Meddy/Meddy/Features/MedicationFollowupFields.swift Modified
diff --git a/Meddy/Meddy/Features/MedicationFollowupFields.swift b/Meddy/Meddy/Features/MedicationFollowupFields.swiftindex 68fa314..05c6fa3 100644--- a/Meddy/Meddy/Features/MedicationFollowupFields.swift+++ b/Meddy/Meddy/Features/MedicationFollowupFields.swift@@ -1,63 +1,77 @@-import SwiftUI import SwiftData+import SwiftUI import UserNotifications  @MainActor @Observable final class MedicationFollowupDraft {-    var enabled: Bool-    var message: String-    var minutes: String-    private let original: MedicationFollowup?-    private let originalDataExists: Bool-    init(medication: Medication?) {-        let data = medication?.followupNotificationData-        original = data.flatMap { try? JSONDecoder().decode(MedicationFollowup.self, from: $0) }-        originalDataExists = data != nil-        enabled = data != nil-        message = original?.message ?? ""-        minutes = original.map { String($0.delaySeconds / 60) } ?? ""+  var enabled: Bool+  var message: String+  var minutes: String+  private let original: MedicationFollowup?+  private let originalDataExists: Bool+  init(medication: Medication?) {+    let data = medication?.followupNotificationData+    original = data.flatMap { try? JSONDecoder().decode(MedicationFollowup.self, from: $0) }+    originalDataExists = data != nil+    enabled = data != nil+    message = original?.message ?? ""+    minutes = original.map { String($0.delaySeconds / 60) } ?? ""+  }+  func value(locale: Locale = .current) throws -> MedicationFollowup? {+    guard enabled else { return nil }+    let entered = minutes.trimmingCharacters(in: .whitespacesAndNewlines)+      .replacingOccurrences(of: locale.decimalSeparator ?? ".", with: ".")+    guard let number = Double(entered) else { throw MedicationFollowupError.invalidConfiguration }+    let value = MedicationFollowup(+      message: message.trimmingCharacters(in: .whitespacesAndNewlines), delaySeconds: number * 60)+    try value.validate()+    return value+  }+  func apply(to medication: Medication) throws {+    if enabled == originalDataExists, message == (original?.message ?? ""),+      minutes == (original.map { String($0.delaySeconds / 60) } ?? "") {+      return     }-    func value(locale: Locale = .current) throws -> MedicationFollowup? {-        guard enabled else { return nil }-        let entered = minutes.trimmingCharacters(in: .whitespacesAndNewlines)-            .replacingOccurrences(of: locale.decimalSeparator ?? ".", with: ".")-        guard let number = Double(entered) else { throw MedicationFollowupError.invalidConfiguration }-        let value = MedicationFollowup(message: message.trimmingCharacters(in: .whitespacesAndNewlines), delaySeconds: number * 60)-        try value.validate()-        return value-    }-    func apply(to medication: Medication) throws {-        if enabled == originalDataExists, message == (original?.message ?? ""),-           minutes == (original.map { String($0.delaySeconds / 60) } ?? "") { return }-        let next = try value()-        // An untouched editor preserves a newer saved configuration.-        if next != original || (originalDataExists && original == nil) {-            try MedicationFollowupService.configure(medication, value: next)-        }+    let next = try value()+    // An untouched editor preserves a newer saved configuration.+    if next != original || (originalDataExists && original == nil) {+      try MedicationFollowupService.configure(medication, value: next)     }+  } }  struct MedicationFollowupFields: View {-    @Bindable var draft: MedicationFollowupDraft-    @State private var permissionMessage: String?-    var body: some View {-        Section("After recording taken") {-            Toggle("Follow-up notification", isOn: $draft.enabled).accessibilityIdentifier("followupEnabled")-                .onChange(of: draft.enabled) { _, enabled in-                    guard enabled, !AppEnvironment.isTesting else { return }-                    Task {-                        do {-                            let granted = try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])-                            permissionMessage = granted ? nil : "Notifications are disabled. Your message and dose records can still be saved; enable notifications in Settings to receive future follow-ups."-                        } catch { permissionMessage = error.localizedDescription }-                    }-                }-            if draft.enabled {-                TextField("Your follow-up message", text: $draft.message, axis: .vertical).accessibilityIdentifier("followupMessage")-                TextField("Delay after taken (minutes)", text: $draft.minutes).keyboardType(.decimalPad).accessibilityIdentifier("followupMinutes")-                Text("Uses the actual recorded taken time. Your own message is a reminder, not medical guidance. Past follow-ups are not replayed.").font(.caption).foregroundStyle(.secondary)-            }-            if let permissionMessage { Text(permissionMessage).font(.caption) }+  @Bindable var draft: MedicationFollowupDraft+  @State private var permissionMessage: String?+  var body: some View {+    Section("After recording taken") {+      Toggle("Follow-up notification", isOn: $draft.enabled).accessibilityIdentifier(+        "followupEnabled"+      )+      .onChange(of: draft.enabled) { _, enabled in+        guard enabled, !AppEnvironment.isTesting else { return }+        Task {+          do {+            let granted = try await UNUserNotificationCenter.current().requestAuthorization(+              options: [.alert, .sound, .badge])+            permissionMessage =+              granted+              ? nil+              : "Notifications are disabled. Your message and dose records can still be saved; "+                + "enable notifications in Settings to receive future follow-ups."+          } catch { permissionMessage = error.localizedDescription }         }+      }+      if draft.enabled {+        TextField("Your follow-up message", text: $draft.message, axis: .vertical)+          .accessibilityIdentifier("followupMessage")+        TextField("Delay after taken (minutes)", text: $draft.minutes).keyboardType(.decimalPad)+          .accessibilityIdentifier("followupMinutes")+        Text(+          "Uses the actual recorded taken time. Your own message is a reminder, not medical guidance. Past follow-ups are not replayed."+        ).font(.caption).foregroundStyle(.secondary)+      }+      if let permissionMessage { Text(permissionMessage).font(.caption) }     }+  } }
Meddy/Meddy/Features/MedicationPhoto.swift Modified
diff --git a/Meddy/Meddy/Features/MedicationPhoto.swift b/Meddy/Meddy/Features/MedicationPhoto.swiftindex f5eea1a..c9eb690 100644--- a/Meddy/Meddy/Features/MedicationPhoto.swift+++ b/Meddy/Meddy/Features/MedicationPhoto.swift@@ -1,95 +1,137 @@-import SwiftUI-import SwiftData-import PhotosUI-import ImageIO import CryptoKit+import ImageIO+import PhotosUI+import SwiftData+import SwiftUI  @MainActor @Observable final class MedicationPhotoDraft {-    var data: Data?-    private(set) var loading = false-    private(set) var error: String?-    private var revision = UUID()-    private let originalData: Data?-    init(data: Data? = nil) { self.data = data; originalData = data }-    func apply(to medication: Medication, context: ModelContext) throws {-        // An untouched photo must not overwrite a newer model/CloudKit value.-        if data != originalData { try MedicationPhotoService(context: context, deferSave: true).setPhoto(data, for: medication) }+  var data: Data?+  private(set) var loading = false+  private(set) var error: String?+  private var revision = UUID()+  private let originalData: Data?+  init(data: Data? = nil) {+    self.data = data+    originalData = data+  }+  func apply(to medication: Medication, context: ModelContext) throws {+    // An untouched photo must not overwrite a newer model/CloudKit value.+    if data != originalData {+      try MedicationPhotoService(context: context, deferSave: true).setPhoto(data, for: medication)     }+  } -    func load(using importer: () async throws -> Data?) async {-        let token = UUID(); revision = token; loading = true; error = nil-        do {-            guard let input = try await importer() else { throw MedicationPhotoError.unavailable }-            guard revision == token, !Task.isCancelled else { finish(token); return }-            let prepared = try await Task.detached(priority: .userInitiated) { try MedicationPhotoProcessor.prepare(input) }.value-            guard revision == token, !Task.isCancelled else { finish(token); return }-            data = prepared; finish(token)-        } catch {-            guard revision == token else { return }-            if !Task.isCancelled && !(error is CancellationError) { self.error = (error as? MedicationPhotoError)?.localizedDescription ?? MedicationPhotoError.unavailable.localizedDescription }-            finish(token)-        }+  func load(using importer: () async throws -> Data?) async {+    let token = UUID()+    revision = token+    loading = true+    error = nil+    do {+      guard let input = try await importer() else { throw MedicationPhotoError.unavailable }+      guard revision == token, !Task.isCancelled else {+        finish(token)+        return+      }+      let prepared = try await Task.detached(priority: .userInitiated) {+        try MedicationPhotoProcessor.prepare(input)+      }.value+      guard revision == token, !Task.isCancelled else {+        finish(token)+        return+      }+      data = prepared+      finish(token)+    } catch {+      guard revision == token else { return }+      if !Task.isCancelled && !(error is CancellationError) {+        self.error =+          (error as? MedicationPhotoError)?.localizedDescription+          ?? MedicationPhotoError.unavailable.localizedDescription+      }+      finish(token)     }-    func remove() { revision = UUID(); data = nil; error = nil; loading = false }-    private func finish(_ token: UUID) { if revision == token { loading = false } }+  }+  func remove() {+    revision = UUID()+    data = nil+    error = nil+    loading = false+  }+  private func finish(_ token: UUID) { if revision == token { loading = false } } }  @MainActor private enum MedicationPhotoCache {-    static let images: NSCache<NSString, UIImage> = {-        let cache = NSCache<NSString, UIImage>(); cache.countLimit = 64; cache.totalCostLimit = 12 * 1024 * 1024; return cache-    }()-    static func image(_ data: Data, side: Int) -> UIImage? {-        guard data.count <= MedicationPhotoProcessor.storedLimit else { return nil }-        let key = (SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + "|\(side)") as NSString-        if let cached = images.object(forKey: key) { return cached }-        guard let source = CGImageSourceCreateWithData(data as CFData, nil),-              let thumbnail = MedicationPhotoProcessor.thumbnail(source, side: side) else { return nil }-        let image = UIImage(cgImage: thumbnail)-        images.setObject(image, forKey: key, cost: thumbnail.bytesPerRow * thumbnail.height)-        return image-    }+  static let images: NSCache<NSString, UIImage> = {+    let cache = NSCache<NSString, UIImage>()+    cache.countLimit = 64+    cache.totalCostLimit = 12 * 1024 * 1024+    return cache+  }()+  static func image(_ data: Data, side: Int) -> UIImage? {+    guard data.count <= MedicationPhotoProcessor.storedLimit else { return nil }+    let key =+      (SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() + "|\(side)") as NSString+    if let cached = images.object(forKey: key) { return cached }+    guard let source = CGImageSourceCreateWithData(data as CFData, nil),+      let thumbnail = MedicationPhotoProcessor.thumbnail(source, side: side)+    else { return nil }+    let image = UIImage(cgImage: thumbnail)+    images.setObject(image, forKey: key, cost: thumbnail.bytesPerRow * thumbnail.height)+    return image+  } }  struct MedicationPhotoView: View {-    let data: Data?-    let name: String-    var size: CGFloat = 48-    var body: some View {-        if let data {-            Group {-                if let image = MedicationPhotoCache.image(data, side: size > 100 ? 768 : 144) {-                    Image(uiImage: image).resizable().scaledToFit()-                        .accessibilityLabel("Recognition photo for \(name)")-                } else { Image(systemName: "photo.badge.exclamationmark").accessibilityLabel("Recognition photo unavailable for \(name)") }-            }-            .frame(width: size, height: size).background(.quaternary, in: RoundedRectangle(cornerRadius: 8))-            .accessibilityIdentifier("medicationRecognitionPhoto")+  let data: Data?+  let name: String+  var size: CGFloat = 48+  var body: some View {+    if let data {+      Group {+        if let image = MedicationPhotoCache.image(data, side: size > 100 ? 768 : 144) {+          Image(uiImage: image).resizable().scaledToFit()+            .accessibilityLabel("Recognition photo for \(name)")+        } else {+          Image(systemName: "photo.badge.exclamationmark").accessibilityLabel(+            "Recognition photo unavailable for \(name)")         }+      }+      .frame(width: size, height: size).background(+        .quaternary, in: RoundedRectangle(cornerRadius: 8)+      )+      .accessibilityIdentifier("medicationRecognitionPhoto")     }+  } }  struct MedicationPhotoEditor: View {-    @Bindable var draft: MedicationPhotoDraft-    @State private var selection: PhotosPickerItem?-    let name: String-    var body: some View {-        let pickerTitle = draft.data == nil ? "Add photo" : "Replace photo"-        Section("Recognition photo") {-            if draft.data != nil { MedicationPhotoView(data: draft.data, name: name, size: 160) }-            PhotosPicker(selection: $selection, matching: .images, preferredItemEncoding: .current) {-                Label(pickerTitle, systemImage: "photo")-            }-            if draft.data != nil { Button("Remove photo", role: .destructive) { selection = nil; draft.remove() } }-            if draft.loading { ProgressView("Loading photo…") }-            if let error = draft.error { Text(error).foregroundStyle(.red) }-            Text("Optional photo for recognition. Changes are kept when you save.").font(.caption).foregroundStyle(.secondary)-        }-        .task(id: selection) {-            guard let selection else { return }-            await draft.load { try await selection.loadTransferable(type: Data.self) }-            if !Task.isCancelled && self.selection == selection { self.selection = nil }+  @Bindable var draft: MedicationPhotoDraft+  @State private var selection: PhotosPickerItem?+  let name: String+  var body: some View {+    let pickerTitle = draft.data == nil ? "Add photo" : "Replace photo"+    Section("Recognition photo") {+      if draft.data != nil { MedicationPhotoView(data: draft.data, name: name, size: 160) }+      PhotosPicker(selection: $selection, matching: .images, preferredItemEncoding: .current) {+        Label(pickerTitle, systemImage: "photo")+      }+      if draft.data != nil {+        Button("Remove photo", role: .destructive) {+          selection = nil+          draft.remove()         }+      }+      if draft.loading { ProgressView("Loading photo…") }+      if let error = draft.error { Text(error).foregroundStyle(.red) }+      Text("Optional photo for recognition. Changes are kept when you save.").font(.caption)+        .foregroundStyle(.secondary)+    }+    .task(id: selection) {+      guard let selection else { return }+      await draft.load { try await selection.loadTransferable(type: Data.self) }+      if !Task.isCancelled && self.selection == selection { self.selection = nil }     }+  } }
Meddy/Meddy/Features/MedicationScheduleFields.swift Modified
diff --git a/Meddy/Meddy/Features/MedicationScheduleFields.swift b/Meddy/Meddy/Features/MedicationScheduleFields.swiftindex 01c1953..940d514 100644--- a/Meddy/Meddy/Features/MedicationScheduleFields.swift+++ b/Meddy/Meddy/Features/MedicationScheduleFields.swift@@ -1,127 +1,189 @@-import SwiftUI import SwiftData+import SwiftUI import UserNotifications  nonisolated extension MedicationScheduleType {-    var title: String {-        switch self {-        case .asNeeded: "As needed"-        case .spreadThroughDay: "Spread through day"-        case .interval: "Interval"-        case .fixedTimes: "Fixed times"-        case .afterWaking: "After waking"-        case .routineManaged: "Managed by routine"-        }+  var title: String {+    switch self {+    case .asNeeded: "As needed"+    case .spreadThroughDay: "Spread through day"+    case .interval: "Interval"+    case .fixedTimes: "Fixed times"+    case .afterWaking: "After waking"+    case .routineManaged: "Managed by routine"     }+  } }  struct MedicationScheduleFields: View {-    @Binding var mode: MedicationScheduleType-    @Binding var doses: String-    @Binding var start: String-    @Binding var end: String-    @Binding var minimum: String-    @Binding var interval: String-    @Binding var first: String-    @Binding var fixed: String-    @Binding var reminders: Bool-    @Binding var wakeOffset: String-    @State private var permissionMessage: String?+  @Binding var mode: MedicationScheduleType+  @Binding var doses: String+  @Binding var start: String+  @Binding var end: String+  @Binding var minimum: String+  @Binding var interval: String+  @Binding var first: String+  @Binding var fixed: String+  @Binding var reminders: Bool+  @Binding var wakeOffset: String+  @State private var permissionMessage: String? -    var body: some View {-        Section("Schedule") {-            Picker("Schedule", selection: $mode) {-                ForEach(MedicationScheduleType.allCases.filter { $0 != .routineManaged }, id: \.self) { Text($0.title).tag($0) }-            }.accessibilityIdentifier("medicationSchedulePicker").onChange(of: mode) { _, value in if value == .asNeeded { reminders = false } }-            switch mode {-            case .spreadThroughDay:-                TextField("Doses per day", text: $doses).keyboardType(.numberPad)-                TextField("Day starts (HH:mm)", text: $start)-                TextField("Day ends (HH:mm)", text: $end)-                TextField("Optional minimum interval (minutes)", text: $minimum).keyboardType(.numberPad)-            case .interval:-                TextField("Interval (minutes)", text: $interval).keyboardType(.numberPad)-                TextField("First reminder (HH:mm)", text: $first)-            case .afterWaking:-                TextField("Minutes after waking (0–1440)", text: $wakeOffset).keyboardType(.numberPad).accessibilityIdentifier("wakeOffsetMinutes")-                Text("0 means at wake. Use Record Waking Up in Shortcuts for this profile. First wake per 02:00-based day wins; schedule changes wait for the next wake.").font(.caption)-            case .fixedTimes:-                TextField("Times (HH:mm, separated by commas)", text: $fixed)-            case .asNeeded: Text("No due count or reminders.").foregroundStyle(.secondary)-            case .routineManaged: EmptyView()+  var body: some View {+    Section("Schedule") {+      Picker("Schedule", selection: $mode) {+        ForEach(MedicationScheduleType.allCases.filter { $0 != .routineManaged }, id: \.self) {+          Text($0.title).tag($0)+        }+      }.accessibilityIdentifier("medicationSchedulePicker").onChange(of: mode) { _, value in+        if value == .asNeeded { reminders = false }+      }+      switch mode {+      case .spreadThroughDay:+        TextField("Doses per day", text: $doses).keyboardType(.numberPad)+        TextField("Day starts (HH:mm)", text: $start)+        TextField("Day ends (HH:mm)", text: $end)+        TextField("Optional minimum interval (minutes)", text: $minimum).keyboardType(.numberPad)+      case .interval:+        TextField("Interval (minutes)", text: $interval).keyboardType(.numberPad)+        TextField("First reminder (HH:mm)", text: $first)+      case .afterWaking:+        TextField("Minutes after waking (0–1440)", text: $wakeOffset).keyboardType(.numberPad)+          .accessibilityIdentifier("wakeOffsetMinutes")+        Text(+          """+          0 means at wake. Use Record Waking Up in Shortcuts for this profile. First wake per 02:00-based day wins; \+          schedule changes wait for the next wake.+          """+        ).font(.caption)+      case .fixedTimes:+        TextField("Times (HH:mm, separated by commas)", text: $fixed)+      case .asNeeded: Text("No due count or reminders.").foregroundStyle(.secondary)+      case .routineManaged: EmptyView()+      }+      if mode != .asNeeded {+        Toggle("Enable reminders", isOn: $reminders).onChange(of: reminders) { _, enabled in+          guard enabled else { return }+          Task {+            guard !AppEnvironment.isTesting else {+              reminders = false+              return             }-            if mode != .asNeeded {-                Toggle("Enable reminders", isOn: $reminders).onChange(of: reminders) { _, enabled in-                    guard enabled else { return }-                    Task {-                        guard !AppEnvironment.isTesting else { reminders = false; return }-                        do {-                            let granted = try await UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])-                            if !granted { reminders = false; permissionMessage = "Notifications are not allowed. The schedule still works in Meddy." }-                        } catch { reminders = false; permissionMessage = error.localizedDescription }-                    }-                }-                Text("Only actual administrations count. Changing the schedule starts a new generation; history remains.").font(.caption).foregroundStyle(.secondary)+            do {+              let granted = try await UNUserNotificationCenter.current().requestAuthorization(+                options: [.alert, .sound, .badge])+              if !granted {+                reminders = false+                permissionMessage =+                  "Notifications are not allowed. The schedule still works in Meddy."+              }+            } catch {+              reminders = false+              permissionMessage = error.localizedDescription             }-            if let permissionMessage { Text(permissionMessage).font(.caption) }+          }         }+        Text(+          "Only actual administrations count. Changing the schedule starts a new generation; history remains."+        ).font(.caption).foregroundStyle(.secondary)+      }+      if let permissionMessage { Text(permissionMessage).font(.caption) }     }+  } -    func draft() throws -> MedicationScheduleDraft {-        func optionalInteger(_ value: String) throws -> Int? {-            let clean = value.trimmingCharacters(in: .whitespacesAndNewlines)-            guard !clean.isEmpty else { return nil }-            guard let number = Int(clean), number > 0 else { throw DefinitionError.invalidSchedule }-            return number-        }-        switch mode {-        case .asNeeded: return .init(mode: mode)-        case .spreadThroughDay:-            return try .init(mode: mode, dosesPerDay: optionalInteger(doses), dayStartMinute: ScheduleTimeInput.minute(start), dayEndMinute: ScheduleTimeInput.minute(end), minimumIntervalMinutes: optionalInteger(minimum))-        case .interval:-            return try .init(mode: mode, intervalMinutes: optionalInteger(interval), firstReminderMinute: ScheduleTimeInput.minute(first))-        case .afterWaking:-            guard let offset = Int(wakeOffset.trimmingCharacters(in: .whitespacesAndNewlines)), WakeTiming.valid(offset) else { throw DefinitionError.invalidSchedule }-            return .init(mode: mode, wakeOffsetMinutes: offset)-        case .fixedTimes:-            return try .init(mode: mode, fixedMinutes: fixed.split(separator: ",", omittingEmptySubsequences: false).map { try ScheduleTimeInput.minute(String($0)) })-        case .routineManaged: throw DefinitionError.otherOwner-        }+  func draft() throws -> MedicationScheduleDraft {+    func optionalInteger(_ value: String) throws -> Int? {+      let clean = value.trimmingCharacters(in: .whitespacesAndNewlines)+      guard !clean.isEmpty else { return nil }+      guard let number = Int(clean), number > 0 else { throw DefinitionError.invalidSchedule }+      return number     }+    switch mode {+    case .asNeeded: return .init(mode: mode)+    case .spreadThroughDay:+      return try .init(+        mode: mode, dosesPerDay: optionalInteger(doses),+        dayStartMinute: ScheduleTimeInput.minute(start),+        dayEndMinute: ScheduleTimeInput.minute(end),+        minimumIntervalMinutes: optionalInteger(minimum))+    case .interval:+      return try .init(+        mode: mode, intervalMinutes: optionalInteger(interval),+        firstReminderMinute: ScheduleTimeInput.minute(first))+    case .afterWaking:+      guard let offset = Int(wakeOffset.trimmingCharacters(in: .whitespacesAndNewlines)),+        WakeTiming.valid(offset)+      else { throw DefinitionError.invalidSchedule }+      return .init(mode: mode, wakeOffsetMinutes: offset)+    case .fixedTimes:+      return try .init(+        mode: mode,+        fixedMinutes: fixed.split(separator: ",", omittingEmptySubsequences: false).map {+          try ScheduleTimeInput.minute(String($0))+        })+    case .routineManaged: throw DefinitionError.otherOwner+    }+  } }  @MainActor enum MedicationPresentation {-    static func result(_ medication: Medication, now: Date = Date(), context: ModelContext) throws -> MedicationScheduleResult {-        let snapshot = try ScheduleService(context: context).snapshot(medication)-        return MedicationScheduleEngine().evaluate(snapshot, administrations: (medication.administrations ?? []).map {-            .init(id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp, mode: MedicationScheduleType(rawValue: $0.scheduleTypeAtRecordingRaw) ?? .asNeeded, generationID: $0.scheduleGenerationID, routineRunID: $0.routineRunID, isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch, wakeEventID: $0.wakeEventID)-        }, now: now, calendar: .current)-    }+  static func result(_ medication: Medication, now: Date = Date(), context: ModelContext) throws+    -> MedicationScheduleResult {+    let snapshot = try ScheduleService(context: context).snapshot(medication)+    return MedicationScheduleEngine().evaluate(+      snapshot,+      administrations: (medication.administrations ?? []).map {+        .init(+          id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp,+          mode: MedicationScheduleType(rawValue: $0.scheduleTypeAtRecordingRaw) ?? .asNeeded,+          generationID: $0.scheduleGenerationID, routineRunID: $0.routineRunID,+          isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch,+          wakeEventID: $0.wakeEventID)+      }, now: now, calendar: .current)+  } -    static func scheduleLabel(_ medication: Medication, routines: [Routine]) -> String {-        guard let id = medication.managedByRoutineID else {-            if medication.scheduleTypeRaw == "afterWaking", let minutes = medication.wakeOffsetMinutes { return minutes == 0 ? "At recorded wake" : "\(minutes) minutes after recorded wake" }-            return (MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title-        }-        guard let owner = routines.first(where: { $0.id == id }) else { return "In saved routine" }-        var label = "In \(owner.name)"-        if owner.scheduleTypeRaw == "dailySlots", let data = owner.dailySlotsData, let slots = try? JSONDecoder().decode([DailyRoutineSlot].self, from: data) { label += " · \(slots.count) sessions per day" }-        if !owner.isActive { label += " · Archived routine" }-        return label+  static func scheduleLabel(_ medication: Medication, routines: [Routine]) -> String {+    guard let id = medication.managedByRoutineID else {+      if medication.scheduleTypeRaw == "afterWaking", let minutes = medication.wakeOffsetMinutes {+        return minutes == 0 ? "At recorded wake" : "\(minutes) minutes after recorded wake"+      }+      return (MedicationScheduleType(rawValue: medication.scheduleTypeRaw) ?? .asNeeded).title     }--    static func consultation(_ medications: [Medication], routines: [Routine] = [], preparedAt: Date = Date(), timeZone: TimeZone = .current) -> String {-        consultationExport(medications, routines: routines, preparedAt: preparedAt, timeZone: timeZone).markdown+    guard let owner = routines.first(where: { $0.id == id }) else { return "In saved routine" }+    var label = "In \(owner.name)"+    if owner.scheduleTypeRaw == "dailySlots", let data = owner.dailySlotsData,+      let slots = try? JSONDecoder().decode([DailyRoutineSlot].self, from: data) {+      label += " · \(slots.count) sessions per day"     }+    if !owner.isActive { label += " · Archived routine" }+    return label+  } -    static func consultationExport(_ medications: [Medication], routines: [Routine] = [], preparedAt: Date = Date(), timeZone: TimeZone = .current, profileID: UUID? = nil, profileLabel: String = "Me") -> ConsultationMarkdownExport {-        let active = medications.filter { $0.isActive && (profileID == nil || $0.profileID == profileID && $0.ownershipVersion == ProfileIdentity.ownershipVersion) }.map { item in-            ConsultationMedication(id: item.id, purpose: item.purpose?.name ?? "Ungrouped", name: item.name,-                                   dose: item.defaultDose == .unknown ? nil : item.defaultDose.displayText,-                                   method: item.administrationMethod, requirements: item.requirements,-                                   schedule: scheduleLabel(item, routines: routines))-        }-        return ConsultationMarkdown.make(active, preparedAt: preparedAt, timeZone: timeZone, profileID: profileID, profileLabel: profileLabel)+  static func consultation(+    _ medications: [Medication], routines: [Routine] = [], preparedAt: Date = Date(),+    timeZone: TimeZone = .current+  ) -> String {+    consultationExport(medications, routines: routines, preparedAt: preparedAt, timeZone: timeZone)+      .markdown+  }++  static func consultationExport(+    _ medications: [Medication], routines: [Routine] = [], preparedAt: Date = Date(),+    timeZone: TimeZone = .current, profileID: UUID? = nil, profileLabel: String = "Me"+  ) -> ConsultationMarkdownExport {+    let active = medications.filter {+      $0.isActive+        && (profileID == nil+          || $0.profileID == profileID && $0.ownershipVersion == ProfileIdentity.ownershipVersion)+    }.map { item in+      ConsultationMedication(+        id: item.id, purpose: item.purpose?.name ?? "Ungrouped", name: item.name,+        dose: item.defaultDose == .unknown ? nil : item.defaultDose.displayText,+        method: item.administrationMethod, requirements: item.requirements,+        schedule: scheduleLabel(item, routines: routines))     }+    return ConsultationMarkdown.make(+      active, preparedAt: preparedAt, timeZone: timeZone, profileID: profileID,+      profileLabel: profileLabel)+  } }
Meddy/Meddy/Features/PhoneTimerControl.swift Modified
diff --git a/Meddy/Meddy/Features/PhoneTimerControl.swift b/Meddy/Meddy/Features/PhoneTimerControl.swiftindex 087293b..0014b2d 100644--- a/Meddy/Meddy/Features/PhoneTimerControl.swift+++ b/Meddy/Meddy/Features/PhoneTimerControl.swift@@ -2,39 +2,52 @@ import Foundation  /// Presentation only: the session service owns all timer transitions and deadlines. nonisolated struct PhoneTimerControl {-    let phase: TimerPhase-    let title: String-    let countdown: String?-    let instruction: String-    let operation: TimerOperation?-    let accessibilityLabel: String+  let phase: TimerPhase+  let title: String+  let countdown: String?+  let instruction: String+  let operation: TimerOperation?+  let accessibilityLabel: String -    init(checkpoint: TimerCheckpoint, clock: ClockSample) {-        phase = checkpoint.phase-        let round = min(checkpoint.roundIndex + (phase == .waiting ? 2 : 1), checkpoint.roundCount)-        let remaining = ceil(checkpoint.remaining(at: clock))-        let time = String(format: "%02.0f:%02.0f", floor(remaining / 60), remaining.truncatingRemainder(dividingBy: 60))-        switch phase {-        case .ready, .waiting:-            title = "Start round \(round)"; countdown = nil; operation = .start-            instruction = phase == .waiting ? "Tap to continue" : "Tap to start"-            accessibilityLabel = "Start round \(round) of \(checkpoint.roundCount)"-        case .running:-            title = "Round \(round)"; countdown = time; operation = .pause-            instruction = "Tap to pause"-            accessibilityLabel = "Pause round \(round) of \(checkpoint.roundCount)"-        case .paused, .interrupted:-            title = "Resume\nround \(round)"; countdown = time; operation = .resume-            instruction = phase == .interrupted ? "Interrupted · confirm remaining time" : "Paused · tap to resume"-            accessibilityLabel = "Resume \(phase == .interrupted ? "remaining time in " : "")round \(round) of \(checkpoint.roundCount)"-        case .completed:-            title = "Completed"; countdown = nil; operation = nil-            instruction = "All \(checkpoint.roundCount) rounds completed"-            accessibilityLabel = instruction-        case .ended:-            title = "Reopen timer"; countdown = nil; operation = .reopen-            instruction = "Ended incomplete · tap to reopen"-            accessibilityLabel = "Reopen ended timer without starting a round"-        }+  init(checkpoint: TimerCheckpoint, clock: ClockSample) {+    phase = checkpoint.phase+    let round = min(checkpoint.roundIndex + (phase == .waiting ? 2 : 1), checkpoint.roundCount)+    let remaining = ceil(checkpoint.remaining(at: clock))+    let time = String(+      format: "%02.0f:%02.0f", floor(remaining / 60), remaining.truncatingRemainder(dividingBy: 60))+    switch phase {+    case .ready, .waiting:+      title = "Start round \(round)"+      countdown = nil+      operation = .start+      instruction = phase == .waiting ? "Tap to continue" : "Tap to start"+      accessibilityLabel = "Start round \(round) of \(checkpoint.roundCount)"+    case .running:+      title = "Round \(round)"+      countdown = time+      operation = .pause+      instruction = "Tap to pause"+      accessibilityLabel = "Pause round \(round) of \(checkpoint.roundCount)"+    case .paused, .interrupted:+      title = "Resume\nround \(round)"+      countdown = time+      operation = .resume+      instruction =+        phase == .interrupted ? "Interrupted · confirm remaining time" : "Paused · tap to resume"+      accessibilityLabel =+        "Resume \(phase == .interrupted ? "remaining time in " : "")round \(round) of \(checkpoint.roundCount)"+    case .completed:+      title = "Completed"+      countdown = nil+      operation = nil+      instruction = "All \(checkpoint.roundCount) rounds completed"+      accessibilityLabel = instruction+    case .ended:+      title = "Reopen timer"+      countdown = nil+      operation = .reopen+      instruction = "Ended incomplete · tap to reopen"+      accessibilityLabel = "Reopen ended timer without starting a round"     }+  } }
Meddy/Meddy/Features/ProfileViews.swift Modified
diff --git a/Meddy/Meddy/Features/ProfileViews.swift b/Meddy/Meddy/Features/ProfileViews.swiftindex 45fb195..f9c5ef6 100644--- a/Meddy/Meddy/Features/ProfileViews.swift+++ b/Meddy/Meddy/Features/ProfileViews.swift@@ -1,86 +1,142 @@-import SwiftUI import SwiftData+import SwiftUI  private struct CareProfileKey: EnvironmentKey { static let defaultValue = ProfileIdentity.me }-extension EnvironmentValues { var careProfileID: UUID { get { self[CareProfileKey.self] } set { self[CareProfileKey.self] = newValue } } }+extension EnvironmentValues {+  var careProfileID: UUID {+    get { self[CareProfileKey.self] }+    set { self[CareProfileKey.self] = newValue }+  }+}  struct ProfilePicker: View {-    @Environment(\.modelContext) private var context-    @Query private var profiles: [CareProfile]-    @Binding var selection: UUID-    @State private var managing = false-    private var active: [CareProfile] { profiles.filter { $0.archivedAt == nil }.sorted { a,b in a.id != b.id && (a.id == ProfileIdentity.me || b.id != ProfileIdentity.me && (a.label,a.id.uuidString) < (b.label,b.id.uuidString)) } }-    var body: some View {-        HStack {-            Menu {-                Picker("Care profile", selection: $selection) { ForEach(active) { Text($0.label).tag($0.id) } }-                Button("Manage profiles…") { managing = true }-            } label: { Label("Profile: " + (active.first { $0.id == selection }?.label ?? "Me"), systemImage: "person.crop.circle") }-            .accessibilityIdentifier("careProfilePicker")-            Spacer()-        }.padding(.horizontal).padding(.vertical, 6)-        .sheet(isPresented: $managing) { ProfileManagement(selection: $selection) }-        .onChange(of: profiles.map { $0.id.uuidString + String($0.archivedAt != nil) }) { _, _ in if !active.contains(where: { $0.id == selection }) { selection = ProfileIdentity.me } }+  @Environment(\.modelContext) private var context+  @Query private var profiles: [CareProfile]+  @Binding var selection: UUID+  @State private var managing = false+  private var active: [CareProfile] {+    profiles.filter { $0.archivedAt == nil }.sorted { left, right in+      left.id != right.id+        && (left.id == ProfileIdentity.me+          || right.id != ProfileIdentity.me && (left.label, left.id.uuidString) < (right.label, right.id.uuidString))     }+  }+  var body: some View {+    HStack {+      Menu {+        Picker("Care profile", selection: $selection) {+          ForEach(active) { Text($0.label).tag($0.id) }+        }+        Button("Manage profiles…") { managing = true }+      } label: {+        Label(+          "Profile: " + (active.first { $0.id == selection }?.label ?? "Me"),+          systemImage: "person.crop.circle")+      }+      .accessibilityIdentifier("careProfilePicker")+      Spacer()+    }.padding(.horizontal).padding(.vertical, 6)+      .sheet(isPresented: $managing) { ProfileManagement(selection: $selection) }+      .onChange(of: profiles.map { $0.id.uuidString + String($0.archivedAt != nil) }) { _, _ in+        if !active.contains(where: { $0.id == selection }) { selection = ProfileIdentity.me }+      }+  } }  struct ProfileManagement: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    @Query private var profiles: [CareProfile]-    @Binding var selection: UUID-    @State private var adding = false-    @State private var editing: CareProfile?-    @State private var error: String?-    var body: some View {-        NavigationStack {-            List {-                Section { Text("Each profile keeps separate care and history. Update all active Meddy copies before using dependants.").font(.caption) }-                ForEach(profiles.sorted { $0.id != $1.id && ($0.id == ProfileIdentity.me || $1.id != ProfileIdentity.me && $0.id.uuidString < $1.id.uuidString) }) { profile in-                    VStack(alignment: .leading) {-                        HStack { Text(profile.label); if profile.archivedAt != nil { Text("Archived").font(.caption) } }-                        if profile.id != ProfileIdentity.me {-                            HStack {-                                Button("Rename") { editing = profile }-                                Button(profile.archivedAt == nil ? "Archive" : "Restore") {-                                    do { try ProfileService(context: context).setArchived(profile, profile.archivedAt == nil); if profile.archivedAt != nil && selection == profile.id { selection = ProfileIdentity.me } }-                                    catch { self.error = error.localizedDescription }-                                }-                            }.buttonStyle(.borderless)-                        }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  @Query private var profiles: [CareProfile]+  @Binding var selection: UUID+  @State private var adding = false+  @State private var editing: CareProfile?+  @State private var error: String?+  var body: some View {+    NavigationStack {+      List {+        Section {+          Text(+            "Each profile keeps separate care and history. Update all active Meddy copies before using dependants."+          ).font(.caption)+        }+        ForEach(+          profiles.sorted {+            $0.id != $1.id+              && ($0.id == ProfileIdentity.me+                || $1.id != ProfileIdentity.me && $0.id.uuidString < $1.id.uuidString)+          }+        ) { profile in+          VStack(alignment: .leading) {+            HStack {+              Text(profile.label)+              if profile.archivedAt != nil { Text("Archived").font(.caption) }+            }+            if profile.id != ProfileIdentity.me {+              HStack {+                Button("Rename") { editing = profile }+                Button(profile.archivedAt == nil ? "Archive" : "Restore") {+                  do {+                    try ProfileService(context: context).setArchived(+                      profile, profile.archivedAt == nil)+                    if profile.archivedAt != nil && selection == profile.id {+                      selection = ProfileIdentity.me                     }+                  } catch { self.error = error.localizedDescription }                 }-                Button("Add dependant", systemImage: "plus") { adding = true }.accessibilityIdentifier("addDependant")-                if let error { Text(error).foregroundStyle(.red) }-            }.navigationTitle("Care profiles")-            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }-            .sheet(isPresented: $adding) { ProfileNameEditor { selection = $0.id } }-            .sheet(item: $editing) { profile in ProfileNameEditor(profile: profile) { _ in } }+              }.buttonStyle(.borderless)+            }+          }         }+        Button("Add dependant", systemImage: "plus") { adding = true }.accessibilityIdentifier(+          "addDependant")+        if let error { Text(error).foregroundStyle(.red) }+      }.navigationTitle("Care profiles")+        .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }+        .sheet(isPresented: $adding) { ProfileNameEditor { selection = $0.id } }+        .sheet(item: $editing) { profile in ProfileNameEditor(profile: profile) { _ in } }     }+  } }  struct ProfileNameEditor: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    let profile: CareProfile?-    let saved: (CareProfile) -> Void-    @State private var name: String-    @State private var error: String?-    init(profile: CareProfile? = nil, saved: @escaping (CareProfile) -> Void) { self.profile = profile; self.saved = saved; _name = State(initialValue: profile?.displayName ?? "") }-    var body: some View {-        NavigationStack {-            Form { TextField("Display name (optional)", text: $name).accessibilityIdentifier("profileDisplayName"); if let error { Text(error).foregroundStyle(.red) } }-            .navigationTitle(profile == nil ? "Add dependant" : "Rename profile")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save") {-                    do { let service = ProfileService(context: context); let value: CareProfile-                        if let profile { try service.rename(profile, displayName: name); value = profile } else { value = try service.create(displayName: name) }-                        saved(value); dismiss()-                    } catch { self.error = error.localizedDescription }-                } }-            }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  let profile: CareProfile?+  let saved: (CareProfile) -> Void+  @State private var name: String+  @State private var error: String?+  init(profile: CareProfile? = nil, saved: @escaping (CareProfile) -> Void) {+    self.profile = profile+    self.saved = saved+    _name = State(initialValue: profile?.displayName ?? "")+  }+  var body: some View {+    NavigationStack {+      Form {+        TextField("Display name (optional)", text: $name).accessibilityIdentifier(+          "profileDisplayName")+        if let error { Text(error).foregroundStyle(.red) }+      }+      .navigationTitle(profile == nil ? "Add dependant" : "Rename profile")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) {+          Button("Save") {+            do {+              let service = ProfileService(context: context)+              let value: CareProfile+              if let profile {+                try service.rename(profile, displayName: name)+                value = profile+              } else {+                value = try service.create(displayName: name)+              }+              saved(value)+              dismiss()+            } catch { self.error = error.localizedDescription }+          }         }+      }     }+  } }
Meddy/Meddy/Features/ReminderActions.swift Modified
diff --git a/Meddy/Meddy/Features/ReminderActions.swift b/Meddy/Meddy/Features/ReminderActions.swiftindex d437b0a..2186c47 100644--- a/Meddy/Meddy/Features/ReminderActions.swift+++ b/Meddy/Meddy/Features/ReminderActions.swift@@ -1,11 +1,11 @@ import SwiftUI  private struct MedicationSnoozeKey: EnvironmentKey {-    static let defaultValue: (UUID) -> Void = { _ in }+  static let defaultValue: (UUID) -> Void = { _ in } } extension EnvironmentValues {-    var snoozeMedication: (UUID) -> Void {-        get { self[MedicationSnoozeKey.self] }-        set { self[MedicationSnoozeKey.self] = newValue }-    }+  var snoozeMedication: (UUID) -> Void {+    get { self[MedicationSnoozeKey.self] }+    set { self[MedicationSnoozeKey.self] = newValue }+  } }
Meddy/Meddy/Features/RoutineRunView.swift Modified
diff --git a/Meddy/Meddy/Features/RoutineRunView.swift b/Meddy/Meddy/Features/RoutineRunView.swiftindex 3943d6b..af68828 100644--- a/Meddy/Meddy/Features/RoutineRunView.swift+++ b/Meddy/Meddy/Features/RoutineRunView.swift@@ -1,345 +1,589 @@-import SwiftUI import SwiftData+import SwiftUI import UserNotifications  struct RoutineRunView: View {-    @Environment(PhoneNavigation.self) private var navigation-    @Environment(\.modelContext) private var context-    @Query private var allMedications: [Medication]-    private var medications: [Medication] { allMedications.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    @Query private var allAdministrations: [Administration]-    private var administrations: [Administration] { allAdministrations.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    @Query private var allCompletions: [TreatmentCompletion]-    private var completions: [TreatmentCompletion] { allCompletions.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    @Query private var allRuns: [RoutineRun]-    private var runs: [RoutineRun] { allRuns.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    let run: RoutineRun-    @State private var error: String?-    @State private var pendingMedication: AdministrationAction?-    @State private var pendingTreatment: TreatmentAction?-    @State private var correctingTreatment: TreatmentCompletion?-    @State private var correctingMedication: Administration?-    @State private var linkingStep: FrozenRoutineStep?-    @State private var endConfirmation = false-    private var service: RoutineSessionService { RoutineSessionService(context: context) }-    private var definition: FrozenRoutineDefinition? { try? service.definition(run) }-    private var canExecute: Bool { (run.executionDeviceID == nil || run.executionDeviceID == navigation.localDeviceID) && !navigation.waitingHandoff.contains(run.id) }-    private var progress: OrderedCheckpoint? { try? service.progress(run) }+  @Environment(PhoneNavigation.self) private var navigation+  @Environment(\.modelContext) private var context+  @Query private var allMedications: [Medication]+  private var medications: [Medication] {+    allMedications.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)+    }+  }+  @Query private var allAdministrations: [Administration]+  private var administrations: [Administration] {+    allAdministrations.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)+    }+  }+  @Query private var allCompletions: [TreatmentCompletion]+  private var completions: [TreatmentCompletion] {+    allCompletions.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)+    }+  }+  @Query private var allRuns: [RoutineRun]+  private var runs: [RoutineRun] {+    allRuns.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)+    }+  }+  let run: RoutineRun+  @State private var error: String?+  @State private var pendingMedication: AdministrationAction?+  @State private var pendingTreatment: TreatmentAction?+  @State private var correctingTreatment: TreatmentCompletion?+  @State private var correctingMedication: Administration?+  @State private var linkingStep: FrozenRoutineStep?+  @State private var endConfirmation = false+  private var service: RoutineSessionService { RoutineSessionService(context: context) }+  private var definition: FrozenRoutineDefinition? { try? service.definition(run) }+  private var canExecute: Bool {+    (run.executionDeviceID == nil || run.executionDeviceID == navigation.localDeviceID)+      && !navigation.waitingHandoff.contains(run.id)+  }+  private var progress: OrderedCheckpoint? { try? service.progress(run) } -    var body: some View {-        Group {-            if let definition {-                if definition.kind == .timedRounds { TimerRunView(run: run) }-                else { VStack(spacing: 0) { PhoneHandoffControls(run: run); orderedContent(definition) } }-            } else { ContentUnavailableView("Saved plan needs review", systemImage: "exclamationmark.triangle", description: Text("The session could not be read. No action has been recorded.")) }+  var body: some View {+    Group {+      if let definition {+        if definition.kind == .timedRounds {+          TimerRunView(run: run)+        } else {+          VStack(spacing: 0) {+            PhoneHandoffControls(run: run)+            orderedContent(definition)+          }         }-        .navigationTitle(definition?.name ?? "Saved session")-        .onAppear { perform { try service.reconcile(run) } }-        .sheet(item: $correctingTreatment) { TreatmentCompletionEditor(event: $0) }-        .sheet(item: $correctingMedication) { event in if let medication = event.medication { AdministrationEditor(medication: medication, event: event) } }-        .sheet(item: $linkingStep) { step in ExistingLogPicker(run: run, step: step) }-        .alert("End this session?", isPresented: $endConfirmation) {-            Button("End incomplete", role: .destructive) { perform { try service.end(run, actionID: UUID()) } }-            Button("Cancel", role: .cancel) {}-        } message: { Text("Completed actions stay in history. This session will not resume until you explicitly reopen it.") }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { Button("OK") { error = nil } } message: { Text(error ?? "") }+      } else {+        ContentUnavailableView(+          "Saved plan needs review", systemImage: "exclamationmark.triangle",+          description: Text("The session could not be read. No action has been recorded."))+      }+    }+    .navigationTitle(definition?.name ?? "Saved session")+    .onAppear { perform { try service.reconcile(run) } }+    .sheet(item: $correctingTreatment) { TreatmentCompletionEditor(event: $0) }+    .sheet(item: $correctingMedication) { event in+      if let medication = event.medication {+        AdministrationEditor(medication: medication, event: event)+      }+    }+    .sheet(item: $linkingStep) { step in ExistingLogPicker(run: run, step: step) }+    .alert("End this session?", isPresented: $endConfirmation) {+      Button("End incomplete", role: .destructive) {+        perform { try service.end(run, actionID: UUID()) }+      }+      Button("Cancel", role: .cancel) {}+    } message: {+      Text(+        "Completed actions stay in history. This session will not resume until you explicitly reopen it."+      )     }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")+    }+  } -    @ViewBuilder private func orderedContent(_ definition: FrozenRoutineDefinition) -> some View {-        if let progress {-            List {-                Section {-                    Text(SessionLabels.text(run.statusRaw)).font(.headline)-                    if let occurrence = definition.occurrence {-                        Text("Saved session: \(run.logicalDayLabel ?? occurrence.localDate)")-                        if let time = occurrence.scheduledAt { Text(time.formatted(date: .abbreviated, time: .shortened)) }-                        Text(occurrence.timeZoneID).font(.caption).foregroundStyle(.secondary)-                    }-                    if !definition.instructions.isEmpty { Text(definition.instructions) }-                    if run.routine?.definitionRevision != definition.revision { Text("The plan has changed. This session keeps its saved plan.").font(.caption).foregroundStyle(.secondary) }-                    if run.routine?.isActive == false { Text("This routine is archived. Its saved session and history are preserved.").font(.caption) }-                    Text("\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps completed").font(.caption)+  @ViewBuilder private func orderedContent(_ definition: FrozenRoutineDefinition) -> some View {+    if let progress {+      List {+        sessionHeading(definition, progress: progress)+        ForEach(definition.steps) { step in+          if let state = progress.steps.first(where: { $0.id == step.id }) {+            Section("\(step.position + 1). \(step.name)") {+              if step.kind == .medication,+                let medication = medications.first(where: { $0.id == step.targetID }) {+                MedicationPhotoView(data: medication.recognitionPhotoData, name: step.name)+              }+              Text(stepState(state)).font(.caption).foregroundStyle(+                state.state == .needsReview ? Color.orange : Color.secondary)+              if !step.instructions.isEmpty { Text(step.instructions) }+              if !step.requirements.isEmpty { Text(step.requirements) }+              if let dose = step.dose { Text(dose.displayText) }+              if state.state == .needsReview {+                Text(+                  "Later real actions are kept. Review the original log or explicitly skip this unresolved step."+                ).font(.caption)+                Button("Use an existing log") { linkingStep = step }+                Button("Accept reviewed log") {+                  perform {+                    try service.resolveReview(+                      run, stepID: step.id, resolution: .acceptCanonical, actionID: UUID())+                  }                 }-                ForEach(definition.steps) { step in-                    if let state = progress.steps.first(where: { $0.id == step.id }) {-                        Section("\(step.position + 1). \(step.name)") {-                            if step.kind == .medication, let medication = medications.first(where: { $0.id == step.targetID }) {-                                MedicationPhotoView(data: medication.recognitionPhotoData, name: step.name)-                            }-                            Text(stepState(state)).font(.caption).foregroundStyle(state.state == .needsReview ? Color.orange : Color.secondary)-                            if !step.instructions.isEmpty { Text(step.instructions) }-                            if !step.requirements.isEmpty { Text(step.requirements) }-                            if let dose = step.dose { Text(dose.displayText) }-                            if state.state == .needsReview {-                                Text("Later real actions are kept. Review the original log or explicitly skip this unresolved step.").font(.caption)-                                Button("Use an existing log") { linkingStep = step }-                                Button("Accept reviewed log") { perform { try service.resolveReview(run, stepID: step.id, resolution: .acceptCanonical, actionID: UUID()) } }-                                Button("Skip unresolved step") { perform { try service.resolveReview(run, stepID: step.id, resolution: .skip, actionID: UUID()) } }-                            } else if state.state == .skipped && !state.skipConfirmed && canExecute {-                                Button("Continue with skipped step") { perform { try service.continueAfterSkip(run, stepID: step.id, actionID: UUID()) } }-                            } else if progress.nextReadyStepID == step.id && canExecute {-                                stepAction(step, state: state)-                                Button("Use an existing log") { linkingStep = step }-                                Button("Skip step") { perform { try service.skip(run, stepID: step.id, actionID: UUID(), reason: "Explicit user skip") } }-                            }-                            if let eventID = state.canonicalEventID {-                                canonicalLink(eventID, kind: step.kind)-                            }-                            ForEach(Array(state.audit.enumerated()), id: \.offset) { _, audit in-                                VStack(alignment: .leading) { Text(audit.reason); Text(audit.timestamp.formatted(date: .abbreviated, time: .shortened)) }.font(.caption).foregroundStyle(.secondary)-                            }-                        }-                    }+                Button("Skip unresolved step") {+                  perform {+                    try service.resolveReview(+                      run, stepID: step.id, resolution: .skip, actionID: UUID())+                  }                 }-                Section {-                    if progress.phase == .active { Button("Pause session") { perform { try service.pause(run, actionID: UUID()) } } }-                    if progress.phase == .paused { Button("Resume session") { perform { try service.resume(run, actionID: UUID()) } } }-                    if progress.phase == .endedIncomplete { Button("Reopen session") { perform { try service.reopen(run, actionID: UUID()) } } }-                    if [.active, .paused, .needsReview].contains(progress.phase) { Button("End session", role: .destructive) { endConfirmation = true } }-                }.disabled(!canExecute)-            }-        } else { ContentUnavailableView("Checkpoint needs review", systemImage: "exclamationmark.triangle") }-    }-    @ViewBuilder private func stepAction(_ step: FrozenRoutineStep, state: StepProgress) -> some View {-        switch step.kind {-        case .treatment:-            Button("Done") {-                perform {-                    let action = try pendingTreatment ?? ProfileAccess.stamp(TreatmentAction(eventID: UUID(), treatmentID: step.targetID, timestamp: Date(), instructionsSnapshot: step.instructions, source: .phone), target: run, context: context)-                    pendingTreatment = action-                    _ = try service.recordTreatment(action, in: run, stepID: step.id)-                    pendingTreatment = nil+              } else if state.state == .skipped && !state.skipConfirmed && canExecute {+                Button("Continue with skipped step") {+                  perform { try service.continueAfterSkip(run, stepID: step.id, actionID: UUID()) }                 }-            }.buttonStyle(.borderedProminent)-        case .medication:-            Button("Taken / Applied") {-                perform {-                    let action = try pendingMedication ?? ProfileAccess.stamp(AdministrationAction(eventID: UUID(), medicationID: step.targetID, timestamp: Date(), source: .phone, dose: step.dose ?? .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil), target: run, context: context)-                    pendingMedication = action-                    _ = try service.recordMedication(action, in: run, stepID: step.id)-                    pendingMedication = nil+              } else if progress.nextReadyStepID == step.id && canExecute {+                stepAction(step, state: state)+                Button("Use an existing log") { linkingStep = step }+                Button("Skip step") {+                  perform {+                    try service.skip(+                      run, stepID: step.id, actionID: UUID(), reason: "Explicit user skip")+                  }                 }-            }.buttonStyle(.borderedProminent)-        case .timedRoutine:-            if let childID = state.canonicalEventID, let child = runs.first(where: { $0.id == childID }) {-                NavigationLink("Open saved timer") { TimerRunView(run: child) }-            } else {-                Button("Start timer") { perform { _ = try service.beginTimedStep(run, stepID: step.id) } }.buttonStyle(.borderedProminent)+              }+              if let eventID = state.canonicalEventID {+                canonicalLink(eventID, kind: step.kind)+              }+              ForEach(Array(state.audit.enumerated()), id: \.offset) { _, audit in+                VStack(alignment: .leading) {+                  Text(audit.reason)+                  Text(audit.timestamp.formatted(date: .abbreviated, time: .shortened))+                }.font(.caption).foregroundStyle(.secondary)+              }             }+          }         }+        Section {+          if progress.phase == .active {+            Button("Pause session") { perform { try service.pause(run, actionID: UUID()) } }+          }+          if progress.phase == .paused {+            Button("Resume session") { perform { try service.resume(run, actionID: UUID()) } }+          }+          if progress.phase == .endedIncomplete {+            Button("Reopen session") { perform { try service.reopen(run, actionID: UUID()) } }+          }+          if [.active, .paused, .needsReview].contains(progress.phase) {+            Button("End session", role: .destructive) { endConfirmation = true }+          }+        }.disabled(!canExecute)+      }+    } else {+      ContentUnavailableView("Checkpoint needs review", systemImage: "exclamationmark.triangle")     }-    @ViewBuilder private func canonicalLink(_ id: UUID, kind: RoutineStepTargetKind) -> some View {-        switch kind {-        case .treatment:-            if let event = completions.first(where: { $0.id == id }) {-                Button(event.isDeleted ? "Original completion · Undone" : "Completion details") { correctingTreatment = event }-                    .disabled(event.isDeleted)-                Text(event.timestamp.formatted(date: .abbreviated, time: .shortened)).font(.caption)-            }-        case .medication:-            if let event = administrations.first(where: { $0.id == id }) {-                Button(event.isDeleted ? "Original administration · Undone" : "Administration details") { correctingMedication = event }.disabled(event.isDeleted)-                Text(event.recordedDose.displayText).font(.caption)-                Text(event.timestamp.formatted(date: .abbreviated, time: .shortened)).font(.caption)-                if event.hasClockMismatch { Text("Reported device time needs review").font(.caption).foregroundStyle(.orange) }+  }+  @ViewBuilder private func sessionHeading(+    _ definition: FrozenRoutineDefinition, progress: OrderedCheckpoint+  ) -> some View {+        Section {+          Text(SessionLabels.text(run.statusRaw)).font(.headline)+          if let occurrence = definition.occurrence {+            Text("Saved session: \(run.logicalDayLabel ?? occurrence.localDate)")+            if let time = occurrence.scheduledAt {+              Text(time.formatted(date: .abbreviated, time: .shortened))             }-        case .timedRoutine:-            if let child = runs.first(where: { $0.id == id }) { NavigationLink("Timer history") { TimerRunView(run: child) } }+            Text(occurrence.timeZoneID).font(.caption).foregroundStyle(.secondary)+          }+          if !definition.instructions.isEmpty { Text(definition.instructions) }+          if run.routine?.definitionRevision != definition.revision {+            Text("The plan has changed. This session keeps its saved plan.").font(.caption)+              .foregroundStyle(.secondary)+          }+          if run.routine?.isActive == false {+            Text("This routine is archived. Its saved session and history are preserved.").font(+              .caption)+          }+          Text(+            "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps completed"+          ).font(.caption)         }+  }++  @ViewBuilder private func stepAction(_ step: FrozenRoutineStep, state: StepProgress) -> some View {+    switch step.kind {+    case .treatment:+      Button("Done") {+        perform {+          let action =+            try pendingTreatment+            ?? ProfileAccess.stamp(+              TreatmentAction(+                eventID: UUID(), treatmentID: step.targetID, timestamp: Date(),+                instructionsSnapshot: step.instructions, source: .phone), target: run,+              context: context)+          pendingTreatment = action+          _ = try service.recordTreatment(action, in: run, stepID: step.id)+          pendingTreatment = nil+        }+      }.buttonStyle(.borderedProminent)+    case .medication:+      Button("Taken / Applied") {+        perform {+          let action =+            try pendingMedication+            ?? ProfileAccess.stamp(+              AdministrationAction(+                eventID: UUID(), medicationID: step.targetID, timestamp: Date(), source: .phone,+                dose: step.dose ?? .unknown, scheduleTypeAtRecording: .routineManaged,+                scheduleGenerationID: nil), target: run, context: context)+          pendingMedication = action+          _ = try service.recordMedication(action, in: run, stepID: step.id)+          pendingMedication = nil+        }+      }.buttonStyle(.borderedProminent)+    case .timedRoutine:+      if let childID = state.canonicalEventID, let child = runs.first(where: { $0.id == childID }) {+        NavigationLink("Open saved timer") { TimerRunView(run: child) }+      } else {+        Button("Start timer") { perform { _ = try service.beginTimedStep(run, stepID: step.id) } }+          .buttonStyle(.borderedProminent)+      }     }-    private func stepState(_ state: StepProgress) -> String {-        switch state.state {-        case .pending: "Waiting"-        case .inProgress: "In progress"-        case .paused: "Paused"-        case .completed: "Completed"-        case .skipped: state.skipConfirmed ? "Skipped · Continued explicitly" : "Skipped · Confirmation required"-        case .needsReview: "Needs review"+  }+  @ViewBuilder private func canonicalLink(_ id: UUID, kind: RoutineStepTargetKind) -> some View {+    switch kind {+    case .treatment:+      if let event = completions.first(where: { $0.id == id }) {+        Button(event.isDeleted ? "Original completion · Undone" : "Completion details") {+          correctingTreatment = event+        }+        .disabled(event.isDeleted)+        Text(event.timestamp.formatted(date: .abbreviated, time: .shortened)).font(.caption)+      }+    case .medication:+      if let event = administrations.first(where: { $0.id == id }) {+        Button(event.isDeleted ? "Original administration · Undone" : "Administration details") {+          correctingMedication = event+        }.disabled(event.isDeleted)+        Text(event.recordedDose.displayText).font(.caption)+        Text(event.timestamp.formatted(date: .abbreviated, time: .shortened)).font(.caption)+        if event.hasClockMismatch {+          Text("Reported device time needs review").font(.caption).foregroundStyle(.orange)         }+      }+    case .timedRoutine:+      if let child = runs.first(where: { $0.id == id }) {+        NavigationLink("Timer history") { TimerRunView(run: child) }+      }     }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { self.error = error.localizedDescription } }+  }+  private func stepState(_ state: StepProgress) -> String {+    switch state.state {+    case .pending: "Waiting"+    case .inProgress: "In progress"+    case .paused: "Paused"+    case .completed: "Completed"+    case .skipped:+      state.skipConfirmed ? "Skipped · Continued explicitly" : "Skipped · Confirmation required"+    case .needsReview: "Needs review"+    }+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { self.error = error.localizedDescription }+  } }  struct TimerRunView: View {-    @Environment(PhoneNavigation.self) private var navigation-    @Environment(\.modelContext) private var context-    let run: RoutineRun-    @ScaledMetric(relativeTo: .largeTitle) private var countdownFontSize = 52-    @State private var actionID = UUID()-    @State private var error: String?-    private var service: RoutineSessionService { RoutineSessionService(context: context) }-    private var checkpoint: TimerCheckpoint? { try? service.timer(run) }-    private var definition: FrozenRoutineDefinition? { try? service.definition(run) }-    private var canExecute: Bool {-        run.statusRaw != "needsReview" && (run.executionDeviceID == nil || run.executionDeviceID == navigation.localDeviceID) && !navigation.waitingHandoff.contains(run.id)-    }-    var body: some View {-        GeometryReader { geometry in-            ScrollView {-                if let checkpoint, let definition {-                    VStack(spacing: 20) {-                        VStack(spacing: 8) {-                            PhoneHandoffControls(run: run)-                            if !definition.instructions.isEmpty { Text(definition.instructions) }-                            Text("\(checkpoint.completedRounds) rounds completed").font(.subheadline).foregroundStyle(.secondary)-                        }-                        Spacer(minLength: 0)-                        TimelineView(.periodic(from: .now, by: 1)) { _ in-                            let presentation = PhoneTimerControl(checkpoint: checkpoint, clock: ExecutionClock.sample())-                            timerCircle(presentation, diameter: min(geometry.size.width - 32, 340))-                        }-                        Spacer(minLength: 0)-                        VStack(spacing: 12) {-                            if checkpoint.phase == .waiting {-                                if !definition.betweenRoundInstructions.isEmpty { Text(definition.betweenRoundInstructions) }-                                Text("Waiting between rounds. No timer is running.").font(.subheadline)-                            }-                            if checkpoint.phase == .interrupted {-                                Text("Timing was interrupted or the clock changed. Confirm the remaining active time before resuming.")-                            }-                            if run.statusRaw == "needsReview" {-                                Text("Saved timing needs review. Another device or clock checkpoint conflicts with this result.")-                                Button("Accept saved timer result") {-                                    do { try service.reviewTimer(run, actionID: UUID()) } catch { self.error = error.localizedDescription }-                                }.buttonStyle(.bordered)-                            }-                            if !canExecute { Text("Timer controls are unavailable until the saved result is reviewed or this iPhone has execution control.").font(.caption) }-                            if ![.completed, .ended].contains(checkpoint.phase) {-                                Button("End timer", role: .destructive) { transition(.end) }.buttonStyle(.bordered).disabled(!canExecute)-                            }-                            Text("\(definition.roundCount ?? 0) rounds · \(definition.roundDurationSeconds ?? 0) seconds per round from the saved plan.").font(.caption).foregroundStyle(.secondary)-                            if let error { Text(error).foregroundStyle(.red) }-                        }-                    }-                    .multilineTextAlignment(.center)-                    .padding(16)-                    .frame(maxWidth: .infinity, minHeight: max(0, geometry.size.height))-                } else { ContentUnavailableView("Saved timer needs review", systemImage: "exclamationmark.triangle") }+  @Environment(PhoneNavigation.self) private var navigation+  @Environment(\.modelContext) private var context+  let run: RoutineRun+  @ScaledMetric(relativeTo: .largeTitle) private var countdownFontSize = 52+  @State private var actionID = UUID()+  @State private var error: String?+  private var service: RoutineSessionService { RoutineSessionService(context: context) }+  private var checkpoint: TimerCheckpoint? { try? service.timer(run) }+  private var definition: FrozenRoutineDefinition? { try? service.definition(run) }+  private var canExecute: Bool {+    run.statusRaw != "needsReview"+      && (run.executionDeviceID == nil || run.executionDeviceID == navigation.localDeviceID)+      && !navigation.waitingHandoff.contains(run.id)+  }+  var body: some View {+    GeometryReader { geometry in+      ScrollView {+        if let checkpoint, let definition {+          VStack(spacing: 20) {+            VStack(spacing: 8) {+              PhoneHandoffControls(run: run)+              if !definition.instructions.isEmpty { Text(definition.instructions) }+              Text("\(checkpoint.completedRounds) rounds completed").font(.subheadline)+                .foregroundStyle(.secondary)             }-        }-        .navigationTitle(definition?.name ?? "Saved timer")-        .navigationBarTitleDisplayMode(.inline)-    }-    private func timerCircle(_ presentation: PhoneTimerControl, diameter: CGFloat) -> some View {-        VStack(spacing: 12) {-            Button {-                if let operation = presentation.operation { transition(operation) }-            } label: {-                VStack(spacing: 12) {-                    Text(presentation.title).font(.title3.weight(.semibold)).multilineTextAlignment(.center).contentTransition(.identity)-                    if let countdown = presentation.countdown { Text(countdown).font(.system(size: countdownFontSize, weight: .bold, design: .rounded)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.6).contentTransition(.identity) }+            Spacer(minLength: 0)+            TimelineView(.periodic(from: .now, by: 1)) { _ in+              let presentation = PhoneTimerControl(+                checkpoint: checkpoint, clock: ExecutionClock.sample())+              timerCircle(presentation, diameter: min(geometry.size.width - 32, 340))+            }+            Spacer(minLength: 0)+            VStack(spacing: 12) {+              if checkpoint.phase == .waiting {+                if !definition.betweenRoundInstructions.isEmpty {+                  Text(definition.betweenRoundInstructions)                 }-                .padding(24)-                .frame(width: max(180, diameter), height: max(180, diameter))-                .foregroundStyle(.white)-                .background(!canExecute ? Color(red: 0.35, green: 0.35, blue: 0.35) : presentation.phase == .completed ? Color(red: 0.05, green: 0.40, blue: 0.24) : presentation.phase == .running ? Color(red: 0.65, green: 0.25, blue: 0.02) : Color(red: 0.04, green: 0.28, blue: 0.62), in: Circle())-                .contentShape(Circle())+                Text("Waiting between rounds. No timer is running.").font(.subheadline)+              }+              if checkpoint.phase == .interrupted {+                Text(+                  "Timing was interrupted or the clock changed. Confirm the remaining active time before resuming."+                )+              }+              if run.statusRaw == "needsReview" {+                Text(+                  "Saved timing needs review. Another device or clock checkpoint conflicts with this result."+                )+                Button("Accept saved timer result") {+                  do { try service.reviewTimer(run, actionID: UUID()) } catch {+                    self.error = error.localizedDescription+                  }+                }.buttonStyle(.bordered)+              }+              if !canExecute {+                Text(+                  "Timer controls are unavailable until the saved result is reviewed or this iPhone has execution control."+                ).font(.caption)+              }+              if ![.completed, .ended].contains(checkpoint.phase) {+                Button("End timer", role: .destructive) { transition(.end) }.buttonStyle(.bordered)+                  .disabled(!canExecute)+              }+              Text(+                "\(definition.roundCount ?? 0) rounds · \(definition.roundDurationSeconds ?? 0) seconds per round from the saved plan."+              ).font(.caption).foregroundStyle(.secondary)+              if let error { Text(error).foregroundStyle(.red) }             }-            .buttonStyle(.plain)-            .disabled(!canExecute || presentation.operation == nil)-            .accessibilityIdentifier("phoneTimerCircle")-            .accessibilityLabel(presentation.accessibilityLabel)-            .accessibilityValue(presentation.countdown.map { "\($0) remaining" } ?? "")-            .accessibilityHint(presentation.instruction)-            Text(presentation.instruction).font(.subheadline).multilineTextAlignment(.center)+          }+          .multilineTextAlignment(.center)+          .padding(16)+          .frame(maxWidth: .infinity, minHeight: max(0, geometry.size.height))+        } else {+          ContentUnavailableView(+            "Saved timer needs review", systemImage: "exclamationmark.triangle")         }-        .transaction { $0.animation = nil; $0.disablesAnimations = true }+      }     }-    private func transition(_ operation: TimerOperation) {-        do {-            try service.changeTimer(run, actionID: actionID, clock: ExecutionClock.sample(), operation: operation)-            actionID = UUID(); error = nil-            if operation == .start || operation == .resume {-                Task {-                    guard !AppEnvironment.isTesting else { return }-                    let center = UNUserNotificationCenter.current()-                    if await center.notificationSettings().authorizationStatus == .notDetermined {-                        do {-                            let granted = try await center.requestAuthorization(options: [.alert, .sound])-                            if !granted { error = "Notifications are unavailable. Keep Meddy open for the round-completion buzz. Locked/background alerts require notification permission and iPhone sound/haptic settings." }-                        } catch { self.error = error.localizedDescription }-                    }-                    MutationEffects.saved(context)-                }-            }+    .navigationTitle(definition?.name ?? "Saved timer")+    .navigationBarTitleDisplayMode(.inline)+  }+  private func timerCircle(_ presentation: PhoneTimerControl, diameter: CGFloat) -> some View {+    VStack(spacing: 12) {+      Button {+        if let operation = presentation.operation { transition(operation) }+      } label: {+        VStack(spacing: 12) {+          Text(presentation.title).font(.title3.weight(.semibold)).multilineTextAlignment(.center)+            .contentTransition(.identity)+          if let countdown = presentation.countdown {+            Text(countdown).font(.system(size: countdownFontSize, weight: .bold, design: .rounded))+              .monospacedDigit().lineLimit(1).minimumScaleFactor(0.6).contentTransition(.identity)+          }         }-        catch { self.error = error.localizedDescription }+        .padding(24)+        .frame(width: max(180, diameter), height: max(180, diameter))+        .foregroundStyle(.white)+        .background(+          !canExecute+            ? Color(red: 0.35, green: 0.35, blue: 0.35)+            : presentation.phase == .completed+              ? Color(red: 0.05, green: 0.40, blue: 0.24)+              : presentation.phase == .running+                ? Color(red: 0.65, green: 0.25, blue: 0.02)+                : Color(red: 0.04, green: 0.28, blue: 0.62), in: Circle()+        )+        .contentShape(Circle())+      }+      .buttonStyle(.plain)+      .disabled(!canExecute || presentation.operation == nil)+      .accessibilityIdentifier("phoneTimerCircle")+      .accessibilityLabel(presentation.accessibilityLabel)+      .accessibilityValue(presentation.countdown.map { "\($0) remaining" } ?? "")+      .accessibilityHint(presentation.instruction)+      Text(presentation.instruction).font(.subheadline).multilineTextAlignment(.center)+    }+    .transaction {+      $0.animation = nil+      $0.disablesAnimations = true     }+  }+  private func transition(_ operation: TimerOperation) {+    do {+      try service.changeTimer(+        run, actionID: actionID, clock: ExecutionClock.sample(), operation: operation)+      actionID = UUID()+      error = nil+      if operation == .start || operation == .resume {+        Task {+          guard !AppEnvironment.isTesting else { return }+          let center = UNUserNotificationCenter.current()+          if await center.notificationSettings().authorizationStatus == .notDetermined {+            do {+              let granted = try await center.requestAuthorization(options: [.alert, .sound])+              if !granted {+                error =+                  """+                  Notifications are unavailable. Keep Meddy open for the round-completion buzz. Locked/background alerts \+                  require notification permission and iPhone sound/haptic settings.+                  """+              }+            } catch { self.error = error.localizedDescription }+          }+          MutationEffects.saved(context)+        }+      }+    } catch { self.error = error.localizedDescription }+  }  }  struct ExistingLogPicker: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    @Query(sort: \Administration.timestamp, order: .reverse) private var allAdministrations: [Administration]-    private var administrations: [Administration] { allAdministrations.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions: [TreatmentCompletion]-    private var completions: [TreatmentCompletion] { allCompletions.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    @Query(sort: \RoutineRun.completedAt, order: .reverse) private var allRuns: [RoutineRun]-    private var runs: [RoutineRun] { allRuns.filter { ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context) } }-    let run: RoutineRun-    let step: FrozenRoutineStep-    @State private var confirmation: UUID?-    @State private var error: String?-    var body: some View {-        NavigationStack {-            List {-                Text("Choose a real matching log. Its original time and details are preserved. Moving an associated log marks its earlier session for review.").font(.caption)-                switch step.kind {-                case .medication:-                    ForEach(administrations.filter { !$0.isDeleted && $0.medicationID == step.targetID && ["asNeeded", "routineManaged"].contains($0.scheduleTypeAtRecordingRaw) }) { event in-                        Button { confirmation = event.id } label: { logLabel(event.timestamp, detail: event.recordedDose.displayText, linked: event.routineRunID != nil) }-                    }-                case .treatment:-                    ForEach(completions.filter { !$0.isDeleted && $0.treatmentID == step.targetID }) { event in Button { confirmation = event.id } label: { logLabel(event.timestamp, detail: event.instructionsSnapshot, linked: event.routineRunID != nil) } }-                case .timedRoutine:-                    ForEach(runs.filter { !$0.isDeleted && $0.wasCompleted && $0.routineID == step.targetID }) { event in Button { confirmation = event.id } label: { RunSummaryRow(run: event) } }-                }-                if let error { Text(error).foregroundStyle(.red) }-            }-            .navigationTitle("Use an existing log")-            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }-            .confirmationDialog("Use this original log for the selected step?", isPresented: Binding(get: { confirmation != nil }, set: { if !$0 { confirmation = nil } })) {-                Button("Confirm link or move") { if let id = confirmation { link(id) }; confirmation = nil }-                Button("Cancel", role: .cancel) { confirmation = nil }-            } message: { Text("This creates no additional dose, completion or timer run. Any conflicting recorded order remains visible for review.") }-        }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  @Query(sort: \Administration.timestamp, order: .reverse) private var allAdministrations:+    [Administration]+  private var administrations: [Administration] {+    allAdministrations.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)     }-    private func logLabel(_ date: Date, detail: String, linked: Bool) -> some View {-        VStack(alignment: .leading) { Text(date.formatted(date: .abbreviated, time: .shortened)); Text(detail).font(.caption); Text(linked ? "Already linked · Explicit move required" : "Unlinked").font(.caption).foregroundStyle(.secondary) }+  }+  @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions:+    [TreatmentCompletion]+  private var completions: [TreatmentCompletion] {+    allCompletions.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)     }-    private func link(_ id: UUID) {-        do {-            let service = RoutineSessionService(context: context)-            switch step.kind {-            case .medication: if let event = administrations.first(where: { $0.id == id }) { try service.link(event, to: run, stepID: step.id, confirmedMove: true) }-            case .treatment: if let event = completions.first(where: { $0.id == id }) { try service.link(event, to: run, stepID: step.id, confirmedMove: true) }-            case .timedRoutine: if let event = runs.first(where: { $0.id == id }) { try service.link(event, to: run, stepID: step.id, confirmedMove: true) }+  }+  @Query(sort: \RoutineRun.completedAt, order: .reverse) private var allRuns: [RoutineRun]+  private var runs: [RoutineRun] {+    allRuns.filter {+      ProfileAccess.visible($0, for: run.profileID ?? ProfileIdentity.me, context: context)+    }+  }+  let run: RoutineRun+  let step: FrozenRoutineStep+  @State private var confirmation: UUID?+  @State private var error: String?+  var body: some View {+    NavigationStack {+      List {+        Text(+          """+          Choose a real matching log. Its original time and details are preserved. Moving an associated log marks its \+          earlier session for review.+          """+        ).font(.caption)+        switch step.kind {+        case .medication:+          ForEach(+            administrations.filter {+              !$0.isDeleted && $0.medicationID == step.targetID+                && ["asNeeded", "routineManaged"].contains($0.scheduleTypeAtRecordingRaw)+            }+          ) { event in+            Button {+              confirmation = event.id+            } label: {+              logLabel(+                event.timestamp, detail: event.recordedDose.displayText,+                linked: event.routineRunID != nil)+            }+          }+        case .treatment:+          ForEach(completions.filter { !$0.isDeleted && $0.treatmentID == step.targetID }) { event in+            Button {+              confirmation = event.id+            } label: {+              logLabel(+                event.timestamp, detail: event.instructionsSnapshot,+                linked: event.routineRunID != nil)+            }+          }+        case .timedRoutine:+          ForEach(runs.filter { !$0.isDeleted && $0.wasCompleted && $0.routineID == step.targetID }) { event in+            Button {+              confirmation = event.id+            } label: {+              RunSummaryRow(run: event)             }-            dismiss()-        } catch { self.error = error.localizedDescription }+          }+        }+        if let error { Text(error).foregroundStyle(.red) }+      }+      .navigationTitle("Use an existing log")+      .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }+      .confirmationDialog(+        "Use this original log for the selected step?",+        isPresented: Binding(get: { confirmation != nil }, set: { if !$0 { confirmation = nil } })+      ) {+        Button("Confirm link or move") {+          if let id = confirmation { link(id) }+          confirmation = nil+        }+        Button("Cancel", role: .cancel) { confirmation = nil }+      } message: {+        Text(+          "This creates no additional dose, completion or timer run. Any conflicting recorded order remains visible for review."+        )+      }     }+  }+  private func logLabel(_ date: Date, detail: String, linked: Bool) -> some View {+    VStack(alignment: .leading) {+      Text(date.formatted(date: .abbreviated, time: .shortened))+      Text(detail).font(.caption)+      Text(linked ? "Already linked · Explicit move required" : "Unlinked").font(.caption)+        .foregroundStyle(.secondary)+    }+  }+  private func link(_ id: UUID) {+    do {+      let service = RoutineSessionService(context: context)+      switch step.kind {+      case .medication:+        if let event = administrations.first(where: { $0.id == id }) {+          try service.link(event, to: run, stepID: step.id, confirmedMove: true)+        }+      case .treatment:+        if let event = completions.first(where: { $0.id == id }) {+          try service.link(event, to: run, stepID: step.id, confirmedMove: true)+        }+      case .timedRoutine:+        if let event = runs.first(where: { $0.id == id }) {+          try service.link(event, to: run, stepID: step.id, confirmedMove: true)+        }+      }+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }  struct PhoneHandoffControls: View {-    @Environment(PhoneNavigation.self) private var navigation-    let run: RoutineRun-    @State private var offlineConfirmation = false-    var body: some View {-        if run.executionDeviceID != nil && run.executionDeviceID != navigation.localDeviceID {-            VStack(alignment: .leading, spacing: 8) {-                if navigation.waitingHandoff.contains(run.id) { Text("Waiting for Watch to save and pause its checkpoint…").font(.caption) }-                else {-                    Button(navigation.watchReachable() ? "Continue on iPhone" : "Continue offline on iPhone") {-                        if navigation.watchReachable() { navigation.requestHandoff(run, false) }-                        else { offlineConfirmation = true }-                    }-                }-            }.padding(.horizontal)-                .confirmationDialog("Continue this cached session offline?", isPresented: $offlineConfirmation) {-                    Button("Confirm offline execution") { navigation.requestHandoff(run, true) }-                    Button("Cancel", role: .cancel) {}-                } message: { Text("The Watch may still be running. Distinct actual actions are preserved and conflicting progress needs review; this does not establish a global lock.") }+  @Environment(PhoneNavigation.self) private var navigation+  let run: RoutineRun+  @State private var offlineConfirmation = false+  var body: some View {+    if run.executionDeviceID != nil && run.executionDeviceID != navigation.localDeviceID {+      VStack(alignment: .leading, spacing: 8) {+        if navigation.waitingHandoff.contains(run.id) {+          Text("Waiting for Watch to save and pause its checkpoint…").font(.caption)+        } else {+          Button(navigation.watchReachable() ? "Continue on iPhone" : "Continue offline on iPhone") {+            if navigation.watchReachable() {+              navigation.requestHandoff(run, false)+            } else {+              offlineConfirmation = true+            }+          }+        }+      }.padding(.horizontal)+        .confirmationDialog(+          "Continue this cached session offline?", isPresented: $offlineConfirmation+        ) {+          Button("Confirm offline execution") { navigation.requestHandoff(run, true) }+          Button("Cancel", role: .cancel) {}+        } message: {+          Text(+            """+            The Watch may still be running. Distinct actual actions are preserved and conflicting progress needs review; \+            this does not establish a global lock.+            """+          )         }     }+  } }
Meddy/Meddy/Features/RoutinesView.swift Modified
diff --git a/Meddy/Meddy/Features/RoutinesView.swift b/Meddy/Meddy/Features/RoutinesView.swiftindex 876c158..097d0d0 100644--- a/Meddy/Meddy/Features/RoutinesView.swift+++ b/Meddy/Meddy/Features/RoutinesView.swift@@ -1,250 +1,413 @@-import SwiftUI import SwiftData+import SwiftUI  private enum CareCreation: String, Identifiable {-    case treatment, timed, ordered-    var id: String { rawValue }+  case treatment, timed, ordered+  var id: String { rawValue } }  nonisolated enum SessionLabels {-    static func text(_ raw: String) -> String {-        switch raw {-        case "active": "In progress"-        case "paused": "Paused"-        case "completed": "Completed"-        case "finishedWithSkips": "Finished with skips"-        case "endedIncomplete": "Ended incomplete"-        case "needsReview": "Needs review"-        default: "Needs review"-        }+  static func text(_ raw: String) -> String {+    switch raw {+    case "active": "In progress"+    case "paused": "Paused"+    case "completed": "Completed"+    case "finishedWithSkips": "Finished with skips"+    case "endedIncomplete": "Ended incomplete"+    case "needsReview": "Needs review"+    default: "Needs review"     }+  } }  struct RoutinesView: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(PhoneNavigation.self) private var navigation-    @Environment(\.modelContext) private var context-    @Query(sort: \Routine.name) private var allRoutines: [Routine]-    private var routines: [Routine] { allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \Treatment.name) private var allTreatments: [Treatment]-    private var treatments: [Treatment] { allTreatments.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]-    private var runs: [RoutineRun] { allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @State private var archived = false-    @State private var creation: CareCreation?-    @State private var error: String?+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(PhoneNavigation.self) private var navigation+  @Environment(\.modelContext) private var context+  @Query(sort: \Routine.name) private var allRoutines: [Routine]+  private var routines: [Routine] {+    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \Treatment.name) private var allTreatments: [Treatment]+  private var treatments: [Treatment] {+    allTreatments.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]+  private var runs: [RoutineRun] {+    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @State private var archived = false+  @State private var creation: CareCreation?+  @State private var error: String? -    var body: some View {-        List {-            Picker("Show", selection: $archived) { Text("Active").tag(false); Text("Archived").tag(true) }.pickerStyle(.segmented)-            Section("Ordered routines") {-                ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "ordered" }) { routine in-                    NavigationLink { RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open) } label: {-                        VStack(alignment: .leading) { Text(routine.name); Text("\((routine.steps ?? []).count) ordered steps").font(.caption).foregroundStyle(.secondary) }-                    }.accessibilityLabel(routine.name)-                }+  var body: some View {+    List {+      Picker("Show", selection: $archived) {+        Text("Active").tag(false)+        Text("Archived").tag(true)+      }.pickerStyle(.segmented)+      Section("Ordered routines") {+        ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "ordered" }) { routine in+          NavigationLink {+            RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open)+          } label: {+            VStack(alignment: .leading) {+              Text(routine.name)+              Text("\((routine.steps ?? []).count) ordered steps").font(.caption).foregroundStyle(+                .secondary)             }-            Section("Timed routines") {-                ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "timedRounds" }) { routine in-                    HStack {-                        NavigationLink { RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open) } label: {-                            VStack(alignment: .leading) { Text(routine.name); Text("\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each").font(.caption).foregroundStyle(.secondary) }-                        }-                        if routine.isActive { Button(incomplete(for: routine) == nil ? "Start" : "Resume") { requestStart(routine, nil) }.buttonStyle(.bordered) }-                    }-                }-            }-            Section("Treatment items") {-                ForEach(treatments.filter { $0.isActive != archived }) { treatment in-                    NavigationLink { TreatmentDetailView(treatment: treatment) } label: { Text(treatment.name) }-                }+          }.accessibilityLabel(routine.name)+        }+      }+      Section("Timed routines") {+        ForEach(routines.filter { $0.isActive != archived && $0.kindRaw == "timedRounds" }) { routine in+          HStack {+            NavigationLink {+              RoutineDetailView(routine: routine, onStart: requestStart, onOpen: navigation.open)+            } label: {+              VStack(alignment: .leading) {+                Text(routine.name)+                Text(+                  "\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each"+                ).font(.caption).foregroundStyle(.secondary)+              }             }-            let previous = runs.filter { !$0.isDeleted && $0.parentRoutineRunID == nil && ["active", "paused", "needsReview"].contains($0.statusRaw) }-            if !previous.isEmpty {-                Section("Unfinished sessions") {-                    ForEach(previous) { run in Button { navigation.open(run) } label: { RunSummaryRow(run: run) } }-                }+            if routine.isActive {+              Button(incomplete(for: routine) == nil ? "Start" : "Resume") {+                requestStart(routine, nil)+              }.buttonStyle(.bordered)             }+          }         }-        .navigationTitle("Routines")-        .toolbar {-            Menu("Add care item", systemImage: "plus") {-                Button("Treatment item") { creation = .treatment }-                Button("Timed routine") { creation = .timed }-                Button("Ordered routine") { creation = .ordered }-            }+      }+      Section("Treatment items") {+        ForEach(treatments.filter { $0.isActive != archived }) { treatment in+          NavigationLink {+            TreatmentDetailView(treatment: treatment)+          } label: {+            Text(treatment.name)+          }         }-        .sheet(item: $creation) { kind in-            switch kind {-            case .treatment: TreatmentEditor(profileID: selectedProfileID)-            case .timed: TimedRoutineEditor(profileID: selectedProfileID)-            case .ordered: OrderedRoutineEditor(profileID: selectedProfileID)+      }+      let previous = runs.filter {+        !$0.isDeleted && $0.parentRoutineRunID == nil+          && ["active", "paused", "needsReview"].contains($0.statusRaw)+      }+      if !previous.isEmpty {+        Section("Unfinished sessions") {+          ForEach(previous) { run in+            Button {+              navigation.open(run)+            } label: {+              RunSummaryRow(run: run)             }+          }         }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { Button("OK") { error = nil } } message: { Text(error ?? "") }+      }+    }+    .navigationTitle("Routines")+    .toolbar {+      Menu("Add care item", systemImage: "plus") {+        Button("Treatment item") { creation = .treatment }+        Button("Timed routine") { creation = .timed }+        Button("Ordered routine") { creation = .ordered }+      }+    }+    .sheet(item: $creation) { kind in+      switch kind {+      case .treatment: TreatmentEditor(profileID: selectedProfileID)+      case .timed: TimedRoutineEditor(profileID: selectedProfileID)+      case .ordered: OrderedRoutineEditor(profileID: selectedProfileID)+      }     }-    private func incomplete(for routine: Routine) -> RoutineRun? {-        runs.first { $0.routineID == routine.id && !$0.isDeleted && $0.parentRoutineRunID == nil && ["active", "paused", "needsReview"].contains($0.statusRaw) }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")     }-    private func requestStart(_ routine: Routine, _ occurrence: RoutineOccurrence?) { navigation.start(routine, occurrence: occurrence) }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { self.error = error.localizedDescription } }+  }+  private func incomplete(for routine: Routine) -> RoutineRun? {+    runs.first {+      $0.routineID == routine.id && !$0.isDeleted && $0.parentRoutineRunID == nil+        && ["active", "paused", "needsReview"].contains($0.statusRaw)+    }+  }+  private func requestStart(_ routine: Routine, _ occurrence: RoutineOccurrence?) {+    navigation.start(routine, occurrence: occurrence)+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { self.error = error.localizedDescription }+  } }  struct RunSummaryRow: View {-    let run: RoutineRun-    var body: some View {-        VStack(alignment: .leading) {-            Text((try? JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData).name) ?? "Saved session")-            Text(SessionLabels.text(run.statusRaw)).font(.caption).foregroundStyle(.secondary)-            if let date = run.logicalDayLabel { Text(date).font(.caption) }-            else if let date = run.startedAt { Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption) }-        }+  let run: RoutineRun+  var body: some View {+    VStack(alignment: .leading) {+      Text(+        (try? JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData)+          .name) ?? "Saved session")+      Text(SessionLabels.text(run.statusRaw)).font(.caption).foregroundStyle(.secondary)+      if let date = run.logicalDayLabel {+        Text(date).font(.caption)+      } else if let date = run.startedAt {+        Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption)+      }     }+  } }  struct RoutineDetailView: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(\.logicalDayNow) private var logicalTick-    private var logicalNow: Date { _ = logicalTick; return Date() }-    @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]-    private var runs: [RoutineRun] { allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    let routine: Routine-    let onStart: (Routine, RoutineOccurrence?) -> Void-    let onOpen: (RoutineRun) -> Void-    @State private var editing = false-    @State private var error: String?-    private var snapshot: RoutineScheduleSnapshot? { try? ScheduleService(context: context).snapshot(routine) }-    private var occurrences: [RoutineOccurrence] {-        guard let snapshot else { return [] }-        let values = runs.map { ScheduledRunSnapshot(id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID, localDate: $0.scheduledLocalDate, startedAt: $0.startedAt, timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt, status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted) }-        return RoutineScheduleEngine().occurrences(snapshot, runs: values, day: logicalNow, now: logicalNow, calendar: .current)+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(\.logicalDayNow) private var logicalTick+  private var logicalNow: Date {+    _ = logicalTick+    return Date()+  }+  @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]+  private var runs: [RoutineRun] {+    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  let routine: Routine+  let onStart: (Routine, RoutineOccurrence?) -> Void+  let onOpen: (RoutineRun) -> Void+  @State private var editing = false+  @State private var error: String?+  private var snapshot: RoutineScheduleSnapshot? {+    try? ScheduleService(context: context).snapshot(routine)+  }+  private var occurrences: [RoutineOccurrence] {+    guard let snapshot else { return [] }+    let values = runs.map {+      ScheduledRunSnapshot(+        id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,+        localDate: $0.scheduledLocalDate, startedAt: $0.startedAt,+        timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt,+        status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted)     }-    var body: some View {-        List {-            Section {-                if let purpose = routine.purpose { Text(purpose.name) }-                if !routine.instructions.isEmpty { Text(routine.instructions) }-                if routine.kindRaw == "timedRounds" { Text("\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each") }-                else {-                    ForEach((routine.steps ?? []).sorted { $0.position < $1.position }) { step in-                        Text("Step \(step.position + 1): \((try? RoutineService(context: context).freeze(routine).steps.first { $0.id == step.id }?.name) ?? step.targetKindRaw)").font(.caption)-                    }-                }+    return RoutineScheduleEngine().occurrences(+      snapshot, runs: values, day: logicalNow, now: logicalNow, calendar: .current)+  }+  var body: some View {+    List {+      Section {+        if let purpose = routine.purpose { Text(purpose.name) }+        if !routine.instructions.isEmpty { Text(routine.instructions) }+        if routine.kindRaw == "timedRounds" {+          Text(+            "\(routine.roundCount ?? 0) rounds · \(routine.roundDurationSeconds ?? 0) seconds each")+        } else {+          ForEach((routine.steps ?? []).sorted { $0.position < $1.position }) { step in+            Text(+              "Step \(step.position + 1): \((try? RoutineService(context: context).freeze(routine).steps.first { $0.id == step.id }?.name) ?? step.targetKindRaw)"+            ).font(.caption)+          }+        }+      }+      if routine.isActive {+        Section("Sessions") {+          if let snapshot {+            if snapshot.current == nil && snapshot.pending == nil {+              Button("Start") { onStart(routine, nil) }             }-            if routine.isActive {-                Section("Sessions") {-                    if let snapshot {-                        if snapshot.current == nil && snapshot.pending == nil { Button("Start") { onStart(routine, nil) } }-                        ForEach(occurrences) { occurrence in-                            Button { onStart(routine, occurrence) } label: {-                                VStack(alignment: .leading) {-                                    Text(occurrence.label)-                                    if let time = occurrence.scheduledAt { Text(time.formatted(date: .omitted, time: .shortened)).font(.caption) }-                                    Text(occurrence.status.map { SessionLabels.text($0.rawValue) } ?? "Start").font(.caption)-                                    if occurrence.isEarlierUnfinished { Text("Saved date: \(occurrence.localDate)").font(.caption) }-                                }-                            }.accessibilityLabel("\(occurrence.existingRunID == nil ? "Start" : "Open") \(occurrence.label)")-                        }-                        if let pending = snapshot.pending { Text("Frequency change takes effect \(ScheduleCalendar.activationDate(pending, calendar: .current).formatted(date: .abbreviated, time: .shortened)).").font(.caption).foregroundStyle(.secondary) }-                    } else { Text("Schedule needs review. Edit this plan before creating a session.").foregroundStyle(.red) }+            ForEach(occurrences) { occurrence in+              Button {+                onStart(routine, occurrence)+              } label: {+                VStack(alignment: .leading) {+                  Text(occurrence.label)+                  if let time = occurrence.scheduledAt {+                    Text(time.formatted(date: .omitted, time: .shortened)).font(.caption)+                  }+                  Text(occurrence.status.map { SessionLabels.text($0.rawValue) } ?? "Start").font(+                    .caption)+                  if occurrence.isEarlierUnfinished {+                    Text("Saved date: \(occurrence.localDate)").font(.caption)+                  }                 }+              }.accessibilityLabel(+                "\(occurrence.existingRunID == nil ? "Start" : "Open") \(occurrence.label)")             }-            Section("History") {-                ForEach(runs.filter { $0.routineID == routine.id && !$0.isDeleted }) { run in Button { onOpen(run) } label: { RunSummaryRow(run: run) } }+            if let pending = snapshot.pending {+              Text(+                "Frequency change takes effect \(ScheduleCalendar.activationDate(pending, calendar: .current).formatted(date: .abbreviated, time: .shortened))."+              ).font(.caption).foregroundStyle(.secondary)             }-            Section { Button(routine.isActive ? "Archive" : "Reactivate") { perform { try RoutineService(context: context).setActive(routine, !routine.isActive) } } }+          } else {+            Text("Schedule needs review. Edit this plan before creating a session.")+              .foregroundStyle(.red)+          }+        }+      }+      Section("History") {+        ForEach(runs.filter { $0.routineID == routine.id && !$0.isDeleted }) { run in+          Button {+            onOpen(run)+          } label: {+            RunSummaryRow(run: run)+          }         }-        .navigationTitle(routine.name)-        .toolbar { Button("Edit") { editing = true } }-        .sheet(isPresented: $editing) { if routine.kindRaw == "timedRounds" { TimedRoutineEditor(routine: routine) } else { OrderedRoutineEditor(routine: routine) } }-        .onAppear { perform { _ = try ScheduleService(context: context).activatePending(routine) } }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { Button("OK") { error = nil } } message: { Text(error ?? "") }+      }+      Section {+        Button(routine.isActive ? "Archive" : "Reactivate") {+          perform { try RoutineService(context: context).setActive(routine, !routine.isActive) }+        }+      }+    }+    .navigationTitle(routine.name)+    .toolbar { Button("Edit") { editing = true } }+    .sheet(isPresented: $editing) {+      if routine.kindRaw == "timedRounds" {+        TimedRoutineEditor(routine: routine)+      } else {+        OrderedRoutineEditor(routine: routine)+      }     }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { self.error = error.localizedDescription } }+    .onAppear { perform { _ = try ScheduleService(context: context).activatePending(routine) } }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")+    }+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { self.error = error.localizedDescription }+  } }  struct TreatmentDetailView: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions: [TreatmentCompletion]-    private var completions: [TreatmentCompletion] { allCompletions.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    let treatment: Treatment-    @State private var editing = false-    @State private var correcting: TreatmentCompletion?-    @State private var lastSaved: TreatmentCompletion?-    @State private var pending: TreatmentAction?-    @State private var error: String?-    var body: some View {-        List {-            Section {-                if let purpose = treatment.purpose { Text(purpose.name) }-                if !treatment.instructions.isEmpty { Text(treatment.instructions) }-                if !treatment.notes.isEmpty { Text(treatment.notes) }-                if treatment.isActive {-                    Button("Done") {-                        perform {-                            let action = try pending ?? ProfileAccess.stamp(TreatmentAction(eventID: UUID(), treatmentID: treatment.id, timestamp: Date(), instructionsSnapshot: treatment.instructions, source: .phone), target: treatment, context: context)-                            pending = action; lastSaved = try TreatmentService(context: context).record(action); pending = nil-                        }-                    }-                }-                if let lastSaved, !lastSaved.isDeleted {-                    Text("Saved").foregroundStyle(.secondary)-                    Button("Undo Done") { perform { try RoutineSessionService(context: context).correct(lastSaved, timestamp: lastSaved.timestamp, delete: true) } }-                }+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Query(sort: \TreatmentCompletion.timestamp, order: .reverse) private var allCompletions:+    [TreatmentCompletion]+  private var completions: [TreatmentCompletion] {+    allCompletions.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  let treatment: Treatment+  @State private var editing = false+  @State private var correcting: TreatmentCompletion?+  @State private var lastSaved: TreatmentCompletion?+  @State private var pending: TreatmentAction?+  @State private var error: String?+  var body: some View {+    List {+      Section {+        if let purpose = treatment.purpose { Text(purpose.name) }+        if !treatment.instructions.isEmpty { Text(treatment.instructions) }+        if !treatment.notes.isEmpty { Text(treatment.notes) }+        if treatment.isActive {+          Button("Done") {+            perform {+              let action =+                try pending+                ?? ProfileAccess.stamp(+                  TreatmentAction(+                    eventID: UUID(), treatmentID: treatment.id, timestamp: Date(),+                    instructionsSnapshot: treatment.instructions, source: .phone),+                  target: treatment, context: context)+              pending = action+              lastSaved = try TreatmentService(context: context).record(action)+              pending = nil+            }+          }+        }+        if let lastSaved, !lastSaved.isDeleted {+          Text("Saved").foregroundStyle(.secondary)+          Button("Undo Done") {+            perform {+              try RoutineSessionService(context: context).correct(+                lastSaved, timestamp: lastSaved.timestamp, delete: true)             }-            let history = Dictionary(grouping: completions.filter { $0.treatmentID == treatment.id && !$0.isDeleted }) { ScheduleCalendar.localDate($0.timestamp, calendar: .current) }-            ForEach(history.keys.sorted(by: >), id: \.self) { day in-                Section("Completion history · \(day)") {-                    ForEach(history[day] ?? []) { completion in-                        Button { correcting = completion } label: {-                            VStack(alignment: .leading) {-                                Text(completion.timestamp.formatted(date: .abbreviated, time: .shortened))-                                if completion.routineRunID != nil { Text("Linked to a saved routine session").font(.caption) }-                                if completion.hasClockMismatch { Text("Reported device time needs review").font(.caption).foregroundStyle(.orange) }-                            }-                        }-                    }+          }+        }+      }+      let history = Dictionary(+        grouping: completions.filter { $0.treatmentID == treatment.id && !$0.isDeleted }+      ) { ScheduleCalendar.localDate($0.timestamp, calendar: .current) }+      ForEach(history.keys.sorted(by: >), id: \.self) { day in+        Section("Completion history · \(day)") {+          ForEach(history[day] ?? []) { completion in+            Button {+              correcting = completion+            } label: {+              VStack(alignment: .leading) {+                Text(completion.timestamp.formatted(date: .abbreviated, time: .shortened))+                if completion.routineRunID != nil {+                  Text("Linked to a saved routine session").font(.caption)                 }+                if completion.hasClockMismatch {+                  Text("Reported device time needs review").font(.caption).foregroundStyle(.orange)+                }+              }             }-            Section { Button(treatment.isActive ? "Archive" : "Reactivate") { perform { try TreatmentService(context: context).setActive(treatment, !treatment.isActive) } } }+          }+        }+      }+      Section {+        Button(treatment.isActive ? "Archive" : "Reactivate") {+          perform {+            try TreatmentService(context: context).setActive(treatment, !treatment.isActive)+          }         }-        .navigationTitle(treatment.name)-        .toolbar { Button("Edit") { editing = true } }-        .sheet(isPresented: $editing) { TreatmentEditor(treatment: treatment) }-        .sheet(item: $correcting) { TreatmentCompletionEditor(event: $0) }-        .alert("Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { Button("OK") { error = nil } } message: { Text(error ?? "") }+      }     }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { self.error = error.localizedDescription } }+    .navigationTitle(treatment.name)+    .toolbar { Button("Edit") { editing = true } }+    .sheet(isPresented: $editing) { TreatmentEditor(treatment: treatment) }+    .sheet(item: $correcting) { TreatmentCompletionEditor(event: $0) }+    .alert(+      "Could not save", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })+    ) {+      Button("OK") { error = nil }+    } message: {+      Text(error ?? "")+    }+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { self.error = error.localizedDescription }+  } }  struct TreatmentCompletionEditor: View {-    @Environment(\.modelContext) private var context-    @Environment(\.dismiss) private var dismiss-    let event: TreatmentCompletion-    @State private var timestamp: Date-    @State private var error: String?-    init(event: TreatmentCompletion) { self.event = event; _timestamp = State(initialValue: min(event.timestamp, Date())) }-    var body: some View {-        NavigationStack {-            Form {-                Text("Reported: \(event.timestamp.formatted(date: .abbreviated, time: .shortened))")-                DatePicker("Completion time", selection: $timestamp, in: ...Date())-                if !event.instructionsSnapshot.isEmpty { Text(event.instructionsSnapshot) }-                if event.routineRunID != nil { Text("A correction keeps later real actions and marks the saved session for review.").font(.caption) }-                Button("Undo completion", role: .destructive) { save(delete: true) }-                if let error { Text(error).foregroundStyle(.red) }-            }-            .navigationTitle("Completion details")-            .toolbar {-                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }-                ToolbarItem(placement: .confirmationAction) { Button("Save") { save(delete: false) } }-            }+  @Environment(\.modelContext) private var context+  @Environment(\.dismiss) private var dismiss+  let event: TreatmentCompletion+  @State private var timestamp: Date+  @State private var error: String?+  init(event: TreatmentCompletion) {+    self.event = event+    _timestamp = State(initialValue: min(event.timestamp, Date()))+  }+  var body: some View {+    NavigationStack {+      Form {+        Text("Reported: \(event.timestamp.formatted(date: .abbreviated, time: .shortened))")+        DatePicker("Completion time", selection: $timestamp, in: ...Date())+        if !event.instructionsSnapshot.isEmpty { Text(event.instructionsSnapshot) }+        if event.routineRunID != nil {+          Text("A correction keeps later real actions and marks the saved session for review.")+            .font(.caption)         }+        Button("Undo completion", role: .destructive) { save(delete: true) }+        if let error { Text(error).foregroundStyle(.red) }+      }+      .navigationTitle("Completion details")+      .toolbar {+        ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+        ToolbarItem(placement: .confirmationAction) { Button("Save") { save(delete: false) } }+      }     }-    private func save(delete: Bool) {-        do { try RoutineSessionService(context: context).correct(event, timestamp: timestamp, delete: delete); dismiss() }-        catch { self.error = error.localizedDescription }-    }+  }+  private func save(delete: Bool) {+    do {+      try RoutineSessionService(context: context).correct(+        event, timestamp: timestamp, delete: delete)+      dismiss()+    } catch { self.error = error.localizedDescription }+  } }
Meddy/Meddy/Features/TodayRoutineSections.swift Modified
diff --git a/Meddy/Meddy/Features/TodayRoutineSections.swift b/Meddy/Meddy/Features/TodayRoutineSections.swiftindex 0f882ca..7f74404 100644--- a/Meddy/Meddy/Features/TodayRoutineSections.swift+++ b/Meddy/Meddy/Features/TodayRoutineSections.swift@@ -1,74 +1,140 @@-import SwiftUI import SwiftData+import SwiftUI  struct TodayRoutineSections: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Environment(\.logicalDayNow) private var logicalTick-    private var logicalNow: Date { _ = logicalTick; return Date() }-    @Environment(PhoneNavigation.self) private var navigation-    @Query(sort: \Routine.name) private var allRoutines: [Routine]-    private var routines: [Routine] { allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]-    private var runs: [RoutineRun] { allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    private var cards: [(Routine, RoutineOccurrence)] {-        let represented = runs.map { ScheduledRunSnapshot(id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID, localDate: $0.scheduledLocalDate, startedAt: $0.startedAt, timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt, status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted) }-        return routines.filter { $0.isActive && $0.kindRaw == "ordered" }.flatMap { routine -> [(Routine, RoutineOccurrence)] in-            guard let schedule = try? ScheduleService(context: context).snapshot(routine) else { return [] }-            return RoutineScheduleEngine().occurrences(schedule, runs: represented, day: logicalNow, now: logicalNow, calendar: .current).filter { !$0.isEarlierUnfinished }.map { (routine, $0) }-        }.sorted { left, right in-            let terminal: [SessionPhase] = [.completed, .finishedWithSkips, .endedIncomplete]-            let a = left.1.status.map(terminal.contains) ?? false; let b = right.1.status.map(terminal.contains) ?? false-            if a != b { return !a }-            return (left.1.scheduledAt ?? .distantFuture) < (right.1.scheduledAt ?? .distantFuture)-        }+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Environment(\.logicalDayNow) private var logicalTick+  private var logicalNow: Date {+    _ = logicalTick+    return Date()+  }+  @Environment(PhoneNavigation.self) private var navigation+  @Query(sort: \Routine.name) private var allRoutines: [Routine]+  private var routines: [Routine] {+    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \RoutineRun.startedAt, order: .reverse) private var allRuns: [RoutineRun]+  private var runs: [RoutineRun] {+    allRuns.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  private var cards: [(Routine, RoutineOccurrence)] {+    let represented = runs.map {+      ScheduledRunSnapshot(+        id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,+        localDate: $0.scheduledLocalDate, startedAt: $0.startedAt,+        timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt,+        status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted)     }-    var body: some View {-        Section("Today's routines") {-            ForEach(cards, id: \.1.id) { routine, occurrence in-                Button { navigation.start(routine, occurrence: occurrence) } label: {-                    VStack(alignment: .leading, spacing: 4) {-                        Text("\(routine.name) · \(occurrence.label)").font(.headline)-                        if let date = occurrence.scheduledAt { Text(date <= logicalNow ? "Due \(date.formatted(date: .omitted, time: .shortened))" : "Next \(date.formatted(date: .omitted, time: .shortened))").font(.caption) }-                        if let id = occurrence.existingRunID, let run = runs.first(where: { $0.id == id }), let progress = try? RoutineSessionService(context: context).progress(run) {-                            Text("\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps · \(SessionLabels.text(run.statusRaw))").font(.caption)-                            if let stepID = progress.nextReadyStepID, let definition = try? RoutineSessionService(context: context).definition(run), let step = definition.steps.first(where: { $0.id == stepID }) { Text(step.name).font(.caption) }-                        } else { Text("Start").font(.caption) }-                    }-                }+    return routines.filter { $0.isActive && $0.kindRaw == "ordered" }.flatMap { routine -> [(Routine, RoutineOccurrence)] in+      guard let schedule = try? ScheduleService(context: context).snapshot(routine) else {+        return []+      }+      return RoutineScheduleEngine().occurrences(+        schedule, runs: represented, day: logicalNow, now: logicalNow, calendar: .current+      ).filter { !$0.isEarlierUnfinished }.map { (routine, $0) }+    }.sorted { left, right in+      let terminal: [SessionPhase] = [.completed, .finishedWithSkips, .endedIncomplete]+      let leftIsTerminal = left.1.status.map(terminal.contains) ?? false+      let rightIsTerminal = right.1.status.map(terminal.contains) ?? false+      if leftIsTerminal != rightIsTerminal { return !leftIsTerminal }+      return (left.1.scheduledAt ?? .distantFuture) < (right.1.scheduledAt ?? .distantFuture)+    }+  }+  var body: some View {+    Section("Today's routines") {+      ForEach(cards, id: \.1.id) { routine, occurrence in+        Button {+          navigation.start(routine, occurrence: occurrence)+        } label: {+          VStack(alignment: .leading, spacing: 4) {+            Text("\(routine.name) · \(occurrence.label)").font(.headline)+            if let date = occurrence.scheduledAt {+              Text(+                date <= logicalNow+                  ? "Due \(date.formatted(date: .omitted, time: .shortened))"+                  : "Next \(date.formatted(date: .omitted, time: .shortened))"+              ).font(.caption)+            }+            if let id = occurrence.existingRunID, let run = runs.first(where: { $0.id == id }),+              let progress = try? RoutineSessionService(context: context).progress(run) {+              Text(+                "\(progress.steps.filter { $0.state == .completed }.count) of \(progress.steps.count) steps · \(SessionLabels.text(run.statusRaw))"+              ).font(.caption)+              if let stepID = progress.nextReadyStepID,+                let definition = try? RoutineSessionService(context: context).definition(run),+                let step = definition.steps.first(where: { $0.id == stepID }) {+                Text(step.name).font(.caption)+              }+            } else {+              Text("Start").font(.caption)             }+          }         }-        let earlier = runs.filter { !$0.isDeleted && $0.parentRoutineRunID == nil && ["active", "paused", "needsReview"].contains($0.statusRaw) && ($0.logicalDayLabel.map { $0 != ScheduleCalendar.localDate(logicalNow, calendar: .current) } ?? true) }-        if !earlier.isEmpty {-            Section("Earlier unfinished sessions") { ForEach(earlier) { run in Button { navigation.open(run) } label: { RunSummaryRow(run: run) } } }+      }+    }+    let earlier = runs.filter {+      !$0.isDeleted && $0.parentRoutineRunID == nil+        && ["active", "paused", "needsReview"].contains($0.statusRaw)+        && ($0.logicalDayLabel.map {+          $0 != ScheduleCalendar.localDate(logicalNow, calendar: .current)+        } ?? true)+    }+    if !earlier.isEmpty {+      Section("Earlier unfinished sessions") {+        ForEach(earlier) { run in+          Button {+            navigation.open(run)+          } label: {+            RunSummaryRow(run: run)+          }         }+      }     }+  } }  struct CurrentMedicationsView: View {-    @Environment(\.careProfileID) private var selectedProfileID-    @Environment(\.modelContext) private var context-    @Query(sort: \Medication.name) private var allMedications: [Medication]-    private var medications: [Medication] { allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    @Query(sort: \Routine.name) private var allRoutines: [Routine]-    private var routines: [Routine] { allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) } }-    private var groups: [String: [Medication]] { Dictionary(grouping: medications.filter(\.isActive)) { $0.purpose?.name ?? "Ungrouped" } }-    var body: some View {-        List {-            ForEach(groups.keys.sorted(), id: \.self) { purpose in-                Section(purpose) {-                    ForEach(groups[purpose] ?? []) { item in-                        VStack(alignment: .leading, spacing: 6) {-                            Text(item.name).font(.headline)-                            if item.defaultDose != .unknown { Text(item.defaultDose.displayText) }-                            if !item.administrationMethod.isEmpty { Text(item.administrationMethod) }-                            if !item.requirements.isEmpty { Text("Requirements").font(.caption); Text(item.requirements) }-                            Text(MedicationPresentation.scheduleLabel(item, routines: routines)).foregroundStyle(.secondary)-                        }-                    }-                }+  @Environment(\.careProfileID) private var selectedProfileID+  @Environment(\.modelContext) private var context+  @Query(sort: \Medication.name) private var allMedications: [Medication]+  private var medications: [Medication] {+    allMedications.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  @Query(sort: \Routine.name) private var allRoutines: [Routine]+  private var routines: [Routine] {+    allRoutines.filter { ProfileAccess.visible($0, for: selectedProfileID, context: context) }+  }+  private var groups: [String: [Medication]] {+    Dictionary(grouping: medications.filter(\.isActive)) { $0.purpose?.name ?? "Ungrouped" }+  }+  var body: some View {+    List {+      ForEach(groups.keys.sorted(), id: \.self) { purpose in+        Section(purpose) {+          ForEach(groups[purpose] ?? []) { item in+            VStack(alignment: .leading, spacing: 6) {+              Text(item.name).font(.headline)+              if item.defaultDose != .unknown { Text(item.defaultDose.displayText) }+              if !item.administrationMethod.isEmpty { Text(item.administrationMethod) }+              if !item.requirements.isEmpty {+                Text("Requirements").font(.caption)+                Text(item.requirements)+              }+              Text(MedicationPresentation.scheduleLabel(item, routines: routines)).foregroundStyle(+                .secondary)             }-        }.navigationTitle("Current Medications")-            .toolbar { ShareLink(item: MedicationPresentation.consultationExport(medications, routines: routines, profileID: selectedProfileID, profileLabel: (try? ProfileAccess.profile(selectedProfileID, context: context)?.label) ?? "Me"), preview: SharePreview("Current medications")) { Label("Share", systemImage: "square.and.arrow.up") } }-    }+          }+        }+      }+    }.navigationTitle("Current Medications")+      .toolbar {+        ShareLink(+          item: MedicationPresentation.consultationExport(+            medications, routines: routines, profileID: selectedProfileID,+            profileLabel: (try? ProfileAccess.profile(selectedProfileID, context: context)?.label)+              ?? "Me"), preview: SharePreview("Current medications")+        ) { Label("Share", systemImage: "square.and.arrow.up") }+      }+  } }
Meddy/Meddy/Intents/RecordWakingUpIntent.swift Modified
diff --git a/Meddy/Meddy/Intents/RecordWakingUpIntent.swift b/Meddy/Meddy/Intents/RecordWakingUpIntent.swiftindex b9ecaea..0913fd2 100644--- a/Meddy/Meddy/Intents/RecordWakingUpIntent.swift+++ b/Meddy/Meddy/Intents/RecordWakingUpIntent.swift@@ -3,74 +3,109 @@ import Foundation import SwiftData  nonisolated struct WakeProfileEntity: AppEntity {-    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Care profile"-    static let defaultQuery = WakeProfileQuery()-    var id: UUID-    var label: String-    var displayRepresentation: DisplayRepresentation { .init(title: "\(label)") }-    static var me: Self { .init(id: ProfileIdentity.me, label: "Me") }+  static let typeDisplayRepresentation: TypeDisplayRepresentation = "Care profile"+  static let defaultQuery = WakeProfileQuery()+  var id: UUID+  var label: String+  var displayRepresentation: DisplayRepresentation { .init(title: "\(label)") }+  static var me: Self { .init(id: ProfileIdentity.me, label: "Me") } }  nonisolated struct WakeProfileQuery: EntityQuery {-    @MainActor func entities(for identifiers: [UUID]) async throws -> [WakeProfileEntity] {-        let context = try WakeIntentExecution.container().mainContext-        return try identifiers.map { id in-            let profile = try ProfileAccess.profile(id, context: context)-            return .init(id: id, label: id == ProfileIdentity.me ? "Me" : (profile?.label ?? "Profile") + " · " + String(id.uuidString.prefix(8)))-        }+  @MainActor func entities(for identifiers: [UUID]) async throws -> [WakeProfileEntity] {+    let context = try WakeIntentExecution.container().mainContext+    return try identifiers.map { id in+      let profile = try ProfileAccess.profile(id, context: context)+      return .init(+        id: id,+        label: id == ProfileIdentity.me+          ? "Me" : (profile?.label ?? "Profile") + " · " + String(id.uuidString.prefix(8)))     }-    @MainActor func suggestedEntities() async throws -> [WakeProfileEntity] {-        let context = try WakeIntentExecution.container().mainContext-        let ids = try context.fetch(FetchDescriptor<CareProfile>()).filter { $0.archivedAt == nil }.map(\.id)-        return try await entities(for: [ProfileIdentity.me] + ids.filter { $0 != ProfileIdentity.me })-    }-    func defaultResult() async -> WakeProfileEntity? { .me }+  }+  @MainActor func suggestedEntities() async throws -> [WakeProfileEntity] {+    let context = try WakeIntentExecution.container().mainContext+    let ids = try context.fetch(FetchDescriptor<CareProfile>()).filter { $0.archivedAt == nil }.map(+      \.id)+    return try await entities(for: [ProfileIdentity.me] + ids.filter { $0 != ProfileIdentity.me })+  }+  func defaultResult() async -> WakeProfileEntity? { .me } }  struct RecordWakingUpIntent: AppIntent {-    static let title: LocalizedStringResource = "Record Waking Up"-    static let description = IntentDescription("Record the first wake for a care profile in its 02:00-based day and schedule enabled after-waking reminders. Does not record a dose or detect sleep.")-    static var supportedModes: IntentModes { .background }-    static var authenticationPolicy: IntentAuthenticationPolicy { .alwaysAllowed }-    @Parameter(title: "Profile") var profile: WakeProfileEntity?-    static var parameterSummary: some ParameterSummary { Summary("Record waking up for \(\.$profile)") }-    @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {-        let context = try WakeIntentExecution.container().mainContext-        let id = profile?.id ?? ProfileIdentity.me-        let label = try ProfileAccess.profile(id, context: context)?.label ?? "Me"-        let timestamp = Date()-        try await WakeIntentExecution.record(profileID: id, at: timestamp, context: context)-        return .result(dialog: "Wake recorded for \(label). Enabled reminders use the first wake in this day; notification delivery depends on your settings.")-    }+  static let title: LocalizedStringResource = "Record Waking Up"+  static let description = IntentDescription(+    """+    Record the first wake for a care profile in its 02:00-based day and schedule enabled after-waking reminders. \+    Does not record a dose or detect sleep.+    """+  )+  static var supportedModes: IntentModes { .background }+  static var authenticationPolicy: IntentAuthenticationPolicy { .alwaysAllowed }+  @Parameter(title: "Profile") var profile: WakeProfileEntity?+  static var parameterSummary: some ParameterSummary {+    Summary("Record waking up for \(\.$profile)")+  }+  @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {+    let context = try WakeIntentExecution.container().mainContext+    let id = profile?.id ?? ProfileIdentity.me+    let label = try ProfileAccess.profile(id, context: context)?.label ?? "Me"+    let timestamp = Date()+    try await WakeIntentExecution.record(profileID: id, at: timestamp, context: context)+    return .result(+      dialog:+        "Wake recorded for \(label). Enabled reminders use the first wake in this day; notification delivery depends on your settings."+    )+  } }  nonisolated struct MeddyWakeShortcuts: AppShortcutsProvider {-    static var appShortcuts: [AppShortcut] {-        AppShortcut(intent: RecordWakingUpIntent(), phrases: ["Record waking up in \(.applicationName)"], shortTitle: "Record Waking Up", systemImageName: "sunrise")-    }+  static var appShortcuts: [AppShortcut] {+    AppShortcut(+      intent: RecordWakingUpIntent(), phrases: ["Record waking up in \(.applicationName)"],+      shortTitle: "Record Waking Up", systemImageName: "sunrise")+  } }  @MainActor enum WakeIntentExecution {-    #if DEBUG+  #if DEBUG     // Only honored in test processes; never substitutes a live store in production.     static var testContainer: ModelContainer?+  #endif+  static func container() throws -> ModelContainer {+    #if DEBUG+      if AppEnvironment.isTesting, let testContainer { return testContainer }     #endif-    static func container() throws -> ModelContainer {-        #if DEBUG-        if AppEnvironment.isTesting, let testContainer { return testContainer }-        #endif-        return try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting)+    return try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting)+  }+  static weak var activeReminders: ReminderService?+  static func record(+    profileID: UUID, at timestamp: Date, context: ModelContext,+    notifications: (any ReminderNotificationClient)? = nil, defaults: UserDefaults? = nil,+    localDeviceID: String? = nil, now: @escaping () -> Date = Date.init+  ) async throws {+    _ = try WakeService(context: context).record(+      profileID: profileID, at: timestamp, receivedAt: timestamp)+    let service =+      activeReminders.flatMap { $0.uses(context) ? $0 : nil }+      ?? ReminderService(+        context: context, notifications: notifications, wakeReceiptDefaults: defaults,+        registerDelegate: false, now: now)+    if service.localDeviceID == nil {+      service.localDeviceID =+        localDeviceID+        ?? (AppEnvironment.isTesting+          ? nil : UserDefaults.standard.string(forKey: "meddy.phone.identity"))     }-    weak static var activeReminders: ReminderService?-    static func record(profileID: UUID, at timestamp: Date, context: ModelContext, notifications: (any ReminderNotificationClient)? = nil, defaults: UserDefaults? = nil, localDeviceID: String? = nil, now: @escaping () -> Date = Date.init) async throws {-        _ = try WakeService(context: context).record(profileID: profileID, at: timestamp, receivedAt: timestamp)-        let service = activeReminders.flatMap { $0.uses(context) ? $0 : nil } ?? ReminderService(context: context, notifications: notifications, wakeReceiptDefaults: defaults, registerDelegate: false, now: now)-        if service.localDeviceID == nil {-            service.localDeviceID = localDeviceID ?? (AppEnvironment.isTesting ? nil : UserDefaults.standard.string(forKey: "meddy.phone.identity"))-        }-        service.error = nil-        service.refresh(); await service.waitForRefresh()-        if let error = service.error { throw WakeIntentFailure(message: "Wake was saved, but reminders could not be scheduled: " + error) }+    service.error = nil+    service.refresh()+    await service.waitForRefresh()+    if let error = service.error {+      throw WakeIntentFailure(+        message: "Wake was saved, but reminders could not be scheduled: " + error)     }+  }+}+nonisolated struct WakeIntentFailure: LocalizedError {+  var message: String+  var errorDescription: String? { message } }-nonisolated struct WakeIntentFailure: LocalizedError { var message: String; var errorDescription: String? { message } }
Meddy/Meddy/Models/CareProfile.swift Modified
diff --git a/Meddy/Meddy/Models/CareProfile.swift b/Meddy/Meddy/Models/CareProfile.swiftindex 1c97ca7..4b4fbc7 100644--- a/Meddy/Meddy/Models/CareProfile.swift+++ b/Meddy/Meddy/Models/CareProfile.swift@@ -2,25 +2,31 @@ import Foundation import SwiftData  @Model final class CareProfile {-    var id: UUID = UUID()-    var displayName: String? = nil-    var createdAt: Date = Date()-    var updatedAt: Date = Date()-    var archivedAt: Date? = nil-    var lifecycleID: UUID? = nil-    init(id: UUID = UUID(), displayName: String? = nil) {-        self.id = id; self.displayName = displayName-        lifecycleID = id == ProfileIdentity.me ? ProfileIdentity.selfLifecycle : UUID()-    }-    var label: String { id == ProfileIdentity.me ? "Me" : (displayName?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty ?? "Profile " + id.uuidString.prefix(6)) }+  var id: UUID = UUID()+  var displayName: String?+  var createdAt: Date = Date()+  var updatedAt: Date = Date()+  var archivedAt: Date?+  var lifecycleID: UUID?+  init(id: UUID = UUID(), displayName: String? = nil) {+    self.id = id+    self.displayName = displayName+    lifecycleID = id == ProfileIdentity.me ? ProfileIdentity.selfLifecycle : UUID()+  }+  var label: String {+    id == ProfileIdentity.me+      ? "Me"+      : (displayName?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty ?? "Profile "+        + id.uuidString.prefix(6))+  } } -private extension String { nonisolated var nilIfEmpty: String? { isEmpty ? nil : self } }+extension String { nonisolated fileprivate var nilIfEmpty: String? { isEmpty ? nil : self } }  @MainActor protocol ProfileOwned: PersistentModel {-    var id: UUID { get }-    var profileID: UUID? { get set }-    var ownershipVersion: Int? { get set }+  var id: UUID { get }+  var profileID: UUID? { get set }+  var ownershipVersion: Int? { get set } } extension Purpose: ProfileOwned {} extension Medication: ProfileOwned {}
Meddy/Meddy/Models/Models.swift Modified
diff --git a/Meddy/Meddy/Models/Models.swift b/Meddy/Meddy/Models/Models.swiftindex a468c1e..b882fc0 100644--- a/Meddy/Meddy/Models/Models.swift+++ b/Meddy/Meddy/Models/Models.swift@@ -3,108 +3,118 @@ import SwiftData  @Model final class Purpose {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var name: String = ""-    var notes: String = ""-    var isArchived: Bool = false-    var sortOrder: Int = 0-    var createdAt: Date = Date()-    @Relationship(inverse: \Medication.purpose)-    var medications: [Medication]?-    @Relationship(inverse: \Treatment.purpose)-    var treatments: [Treatment]?-    @Relationship(inverse: \Routine.purpose)-    var routines: [Routine]?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var name: String = ""+  var notes: String = ""+  var isArchived: Bool = false+  var sortOrder: Int = 0+  var createdAt: Date = Date()+  @Relationship(inverse: \Medication.purpose)+  var medications: [Medication]?+  @Relationship(inverse: \Treatment.purpose)+  var treatments: [Treatment]?+  @Relationship(inverse: \Routine.purpose)+  var routines: [Routine]? -    init(name: String) { self.name = name; profileID = ProfileIdentity.me; ownershipVersion = ProfileIdentity.ownershipVersion }+  init(name: String) {+    self.name = name+    profileID = ProfileIdentity.me+    ownershipVersion = ProfileIdentity.ownershipVersion+  } }  @Model final class Medication {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var name: String = ""-    var doseDescription: String = ""-    var defaultDoseAmount: Double?-    var defaultDoseUnit: String?-    var asNeededDoseLimitsData: Data? = nil-    var followupNotificationData: Data? = nil-    var recognitionPhotoData: Data? = nil-    var administrationMethod: String = ""-    var requirements: String = ""-    var notes: String = ""-    var isActive: Bool = true-    var remindersEnabled: Bool = false-    var createdAt: Date = Date()-    var archivedAt: Date?-    var purpose: Purpose?-    @Relationship(inverse: \Administration.medication)-    var administrations: [Administration]?-    var scheduleTypeRaw: String = MedicationScheduleType.asNeeded.rawValue-    var scheduleStartedAt: Date?-    var scheduleGenerationID: UUID?-    var managedByRoutineID: UUID?-    var dosesPerDay: Int?-    var intervalMinutes: Int?-    var firstReminderMinuteOfDay: Int?-    var dayStartMinuteOfDay: Int?-    var dayEndMinuteOfDay: Int?-    var minimumIntervalMinutes: Int?-    var wakeOffsetMinutes: Int? = nil-    var fixedTimesData: Data?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var name: String = ""+  var doseDescription: String = ""+  var defaultDoseAmount: Double?+  var defaultDoseUnit: String?+  var asNeededDoseLimitsData: Data?+  var followupNotificationData: Data?+  var recognitionPhotoData: Data?+  var administrationMethod: String = ""+  var requirements: String = ""+  var notes: String = ""+  var isActive: Bool = true+  var remindersEnabled: Bool = false+  var createdAt: Date = Date()+  var archivedAt: Date?+  var purpose: Purpose?+  @Relationship(inverse: \Administration.medication)+  var administrations: [Administration]?+  var scheduleTypeRaw: String = MedicationScheduleType.asNeeded.rawValue+  var scheduleStartedAt: Date?+  var scheduleGenerationID: UUID?+  var managedByRoutineID: UUID?+  var dosesPerDay: Int?+  var intervalMinutes: Int?+  var firstReminderMinuteOfDay: Int?+  var dayStartMinuteOfDay: Int?+  var dayEndMinuteOfDay: Int?+  var minimumIntervalMinutes: Int?+  var wakeOffsetMinutes: Int?+  var fixedTimesData: Data? -    init(name: String) { self.name = name; profileID = ProfileIdentity.me; ownershipVersion = ProfileIdentity.ownershipVersion }+  init(name: String) {+    self.name = name+    profileID = ProfileIdentity.me+    ownershipVersion = ProfileIdentity.ownershipVersion+  } -    var defaultDose: RecordedDoseSnapshot {-        RecordedDoseSnapshot(description: doseDescription, amount: defaultDoseAmount, unit: defaultDoseUnit)-    }+  var defaultDose: RecordedDoseSnapshot {+    RecordedDoseSnapshot(+      description: doseDescription, amount: defaultDoseAmount, unit: defaultDoseUnit)+  } -    var visibleAdministrations: [Administration] {-        (administrations ?? []).filter { !$0.isDeleted }.sorted { $0.timestamp > $1.timestamp }-    }+  var visibleAdministrations: [Administration] {+    (administrations ?? []).filter { !$0.isDeleted }.sorted { $0.timestamp > $1.timestamp }+  } }  @Model final class Administration {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var medicationID: UUID = UUID()-    var timestamp: Date = Date()-    var sourceRaw: String = AdministrationSource.phone.rawValue-    var doseDescriptionSnapshot: String = ""-    var doseAmount: Double?-    var doseUnit: String?-    var wakeEventID: UUID? = nil-    var scheduleTypeAtRecordingRaw: String = MedicationScheduleType.asNeeded.rawValue-    var scheduleGenerationID: UUID?-    var routineRunID: UUID?-    var routineStepID: UUID?-    var createdAt: Date = Date()-    var updatedAt: Date = Date()-    var isDeleted: Bool = false-    var hasClockMismatch: Bool = false-    var medication: Medication?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var medicationID: UUID = UUID()+  var timestamp: Date = Date()+  var sourceRaw: String = AdministrationSource.phone.rawValue+  var doseDescriptionSnapshot: String = ""+  var doseAmount: Double?+  var doseUnit: String?+  var wakeEventID: UUID?+  var scheduleTypeAtRecordingRaw: String = MedicationScheduleType.asNeeded.rawValue+  var scheduleGenerationID: UUID?+  var routineRunID: UUID?+  var routineStepID: UUID?+  var createdAt: Date = Date()+  var updatedAt: Date = Date()+  var isDeleted: Bool = false+  var hasClockMismatch: Bool = false+  var medication: Medication? -    init(action: AdministrationAction, medication: Medication) {-        profileID = medication.profileID; ownershipVersion = medication.ownershipVersion-        id = action.eventID-        medicationID = action.medicationID-        timestamp = action.timestamp-        sourceRaw = action.source.rawValue-        doseDescriptionSnapshot = action.dose.description-        doseAmount = action.dose.amount-        doseUnit = action.dose.unit-        wakeEventID = action.wakeEventID-        scheduleTypeAtRecordingRaw = action.scheduleTypeAtRecording.rawValue-        scheduleGenerationID = action.scheduleGenerationID-        self.medication = medication-    }+  init(action: AdministrationAction, medication: Medication) {+    profileID = medication.profileID+    ownershipVersion = medication.ownershipVersion+    id = action.eventID+    medicationID = action.medicationID+    timestamp = action.timestamp+    sourceRaw = action.source.rawValue+    doseDescriptionSnapshot = action.dose.description+    doseAmount = action.dose.amount+    doseUnit = action.dose.unit+    wakeEventID = action.wakeEventID+    scheduleTypeAtRecordingRaw = action.scheduleTypeAtRecording.rawValue+    scheduleGenerationID = action.scheduleGenerationID+    self.medication = medication+  } -    var recordedDose: RecordedDoseSnapshot {-        RecordedDoseSnapshot(description: doseDescriptionSnapshot, amount: doseAmount, unit: doseUnit)-    }+  var recordedDose: RecordedDoseSnapshot {+    RecordedDoseSnapshot(description: doseDescriptionSnapshot, amount: doseAmount, unit: doseUnit)+  } }
Meddy/Meddy/Models/RoutineModels.swift Modified
diff --git a/Meddy/Meddy/Models/RoutineModels.swift b/Meddy/Meddy/Models/RoutineModels.swiftindex 6138dfd..adc1790 100644--- a/Meddy/Meddy/Models/RoutineModels.swift+++ b/Meddy/Meddy/Models/RoutineModels.swift@@ -3,143 +3,153 @@ import SwiftData  @Model final class Treatment {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var name: String = ""-    var instructions: String = ""-    var notes: String = ""-    var isActive: Bool = true-    var createdAt: Date = Date()-    var purpose: Purpose?-    @Relationship(inverse: \TreatmentCompletion.treatment)-    var completions: [TreatmentCompletion]?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var name: String = ""+  var instructions: String = ""+  var notes: String = ""+  var isActive: Bool = true+  var createdAt: Date = Date()+  var purpose: Purpose?+  @Relationship(inverse: \TreatmentCompletion.treatment)+  var completions: [TreatmentCompletion]? -    init(name: String) { self.name = name; profileID = ProfileIdentity.me; ownershipVersion = ProfileIdentity.ownershipVersion }+  init(name: String) {+    self.name = name+    profileID = ProfileIdentity.me+    ownershipVersion = ProfileIdentity.ownershipVersion+  } }  @Model final class TreatmentCompletion {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var treatmentID: UUID = UUID()-    var timestamp: Date = Date()-    var instructionsSnapshot: String = ""-    var sourceRaw: String = AdministrationSource.phone.rawValue-    var routineRunID: UUID?-    var routineStepID: UUID?-    var createdAt: Date = Date()-    var updatedAt: Date = Date()-    var isDeleted: Bool = false-    var hasClockMismatch: Bool = false-    var treatment: Treatment?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var treatmentID: UUID = UUID()+  var timestamp: Date = Date()+  var instructionsSnapshot: String = ""+  var sourceRaw: String = AdministrationSource.phone.rawValue+  var routineRunID: UUID?+  var routineStepID: UUID?+  var createdAt: Date = Date()+  var updatedAt: Date = Date()+  var isDeleted: Bool = false+  var hasClockMismatch: Bool = false+  var treatment: Treatment? -    init(treatment: Treatment, timestamp: Date, source: AdministrationSource, eventID: UUID = UUID()) {-        profileID = treatment.profileID; ownershipVersion = treatment.ownershipVersion-        id = eventID-        treatmentID = treatment.id-        self.timestamp = timestamp-        sourceRaw = source.rawValue-        instructionsSnapshot = treatment.instructions-        self.treatment = treatment-    }+  init(treatment: Treatment, timestamp: Date, source: AdministrationSource, eventID: UUID = UUID()) {+    profileID = treatment.profileID+    ownershipVersion = treatment.ownershipVersion+    id = eventID+    treatmentID = treatment.id+    self.timestamp = timestamp+    sourceRaw = source.rawValue+    instructionsSnapshot = treatment.instructions+    self.treatment = treatment+  } }  @Model final class Routine {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var name: String = ""-    var kindRaw: String = RoutineKind.timedRounds.rawValue-    var instructions: String = ""-    var isActive: Bool = true-    var sortOrder: Int = 0-    var createdAt: Date = Date()-    var definitionRevision: Int = 1-    var roundCount: Int?-    var roundDurationSeconds: Int?-    var betweenRoundInstructions: String = ""-    var scheduleTypeRaw: String = "none"-    var scheduleGenerationID: UUID?-    var scheduleStartedAt: Date?-    var dailySlotsData: Data?-    var pendingScheduleData: Data?-    var remindersEnabled: Bool = false-    var purpose: Purpose?-    @Relationship(inverse: \RoutineStep.routine)-    var steps: [RoutineStep]?-    @Relationship(inverse: \RoutineRun.routine)-    var runs: [RoutineRun]?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var name: String = ""+  var kindRaw: String = RoutineKind.timedRounds.rawValue+  var instructions: String = ""+  var isActive: Bool = true+  var sortOrder: Int = 0+  var createdAt: Date = Date()+  var definitionRevision: Int = 1+  var roundCount: Int?+  var roundDurationSeconds: Int?+  var betweenRoundInstructions: String = ""+  var scheduleTypeRaw: String = "none"+  var scheduleGenerationID: UUID?+  var scheduleStartedAt: Date?+  var dailySlotsData: Data?+  var pendingScheduleData: Data?+  var remindersEnabled: Bool = false+  var purpose: Purpose?+  @Relationship(inverse: \RoutineStep.routine)+  var steps: [RoutineStep]?+  @Relationship(inverse: \RoutineRun.routine)+  var runs: [RoutineRun]? -    init(name: String, kind: RoutineKind) {-        profileID = ProfileIdentity.me; ownershipVersion = ProfileIdentity.ownershipVersion-        self.name = name-        kindRaw = kind.rawValue-    }+  init(name: String, kind: RoutineKind) {+    profileID = ProfileIdentity.me+    ownershipVersion = ProfileIdentity.ownershipVersion+    self.name = name+    kindRaw = kind.rawValue+  } }  @Model final class RoutineStep {-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var routineID: UUID = UUID()-    var position: Int = 0-    var targetKindRaw: String = RoutineStepTargetKind.treatment.rawValue-    var targetID: UUID = UUID()-    var routine: Routine?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var routineID: UUID = UUID()+  var position: Int = 0+  var targetKindRaw: String = RoutineStepTargetKind.treatment.rawValue+  var targetID: UUID = UUID()+  var routine: Routine? -    init(routine: Routine, targetKind: RoutineStepTargetKind, targetID: UUID, position: Int) {-        profileID = routine.profileID; ownershipVersion = routine.ownershipVersion-        routineID = routine.id-        targetKindRaw = targetKind.rawValue-        self.targetID = targetID-        self.position = position-        self.routine = routine-    }+  init(routine: Routine, targetKind: RoutineStepTargetKind, targetID: UUID, position: Int) {+    profileID = routine.profileID+    ownershipVersion = routine.ownershipVersion+    routineID = routine.id+    targetKindRaw = targetKind.rawValue+    self.targetID = targetID+    self.position = position+    self.routine = routine+  } }  @Model final class RoutineRun {-    var profileLifecycleID: UUID? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var id: UUID = UUID()-    var routineID: UUID = UUID()-    var occurrenceKey: String?-    var scheduledLocalDate: String?-    var scheduledTimeZoneID: String?-    var slotID: UUID?-    var scheduledAt: Date?-    var definitionRevision: Int = 1-    var definitionSnapshotData: Data = Data()-    var stepProgressData: Data = Data()-    var timerCheckpointData: Data?-    var statusRaw: String = "active"-    var startedAt: Date?-    var completedAt: Date?-    var endedAt: Date?-    var completedRounds: Int = 0-    var wasCompleted: Bool = false-    var sourceRaw: String = AdministrationSource.phone.rawValue-    var executionDeviceID: String?-    var revision: Int = 0-    var processedActionIDsData: Data = Data()-    var updatedAt: Date = Date()-    var isDeleted: Bool = false-    var parentRoutineRunID: UUID?-    var parentRoutineStepID: UUID?-    var routine: Routine?+  var profileLifecycleID: UUID?+  var profileID: UUID?+  var ownershipVersion: Int?+  var id: UUID = UUID()+  var routineID: UUID = UUID()+  var occurrenceKey: String?+  var scheduledLocalDate: String?+  var scheduledTimeZoneID: String?+  var slotID: UUID?+  var scheduledAt: Date?+  var definitionRevision: Int = 1+  var definitionSnapshotData: Data = Data()+  var stepProgressData: Data = Data()+  var timerCheckpointData: Data?+  var statusRaw: String = "active"+  var startedAt: Date?+  var completedAt: Date?+  var endedAt: Date?+  var completedRounds: Int = 0+  var wasCompleted: Bool = false+  var sourceRaw: String = AdministrationSource.phone.rawValue+  var executionDeviceID: String?+  var revision: Int = 0+  var processedActionIDsData: Data = Data()+  var updatedAt: Date = Date()+  var isDeleted: Bool = false+  var parentRoutineRunID: UUID?+  var parentRoutineStepID: UUID?+  var routine: Routine? -    init(routine: Routine, runID: UUID = UUID()) {-        profileID = routine.profileID; ownershipVersion = routine.ownershipVersion-        profileLifecycleID = routine.profileID == ProfileIdentity.me ? ProfileIdentity.selfLifecycle : nil-        id = runID-        profileID = routine.profileID; ownershipVersion = routine.ownershipVersion-        routineID = routine.id-        definitionRevision = routine.definitionRevision-        self.routine = routine-    }+  init(routine: Routine, runID: UUID = UUID()) {+    profileID = routine.profileID+    ownershipVersion = routine.ownershipVersion+    profileLifecycleID =+      routine.profileID == ProfileIdentity.me ? ProfileIdentity.selfLifecycle : nil+    id = runID+    profileID = routine.profileID+    ownershipVersion = routine.ownershipVersion+    routineID = routine.id+    definitionRevision = routine.definitionRevision+    self.routine = routine+  } }
Meddy/Meddy/Models/WakeEvent.swift Modified
diff --git a/Meddy/Meddy/Models/WakeEvent.swift b/Meddy/Meddy/Models/WakeEvent.swiftindex b944736..19d2eff 100644--- a/Meddy/Meddy/Models/WakeEvent.swift+++ b/Meddy/Meddy/Models/WakeEvent.swift@@ -2,20 +2,29 @@ import Foundation import SwiftData  @Model final class WakeEvent {-    var id: UUID = UUID()-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil-    var timestamp: Date = Date()-    var recordedAt: Date = Date()-    var sourceRaw: String = "shortcut"-    var localDate: String = ""-    var timeZoneID: String = ""-    init(profileID: UUID, lifecycleID: UUID, timestamp: Date, recordedAt: Date, calendar: Calendar) {-        self.profileID = profileID; ownershipVersion = 1; profileLifecycleID = lifecycleID-        self.timestamp = timestamp; self.recordedAt = recordedAt-        localDate = ScheduleCalendar.localDate(timestamp, calendar: calendar); timeZoneID = calendar.timeZone.identifier-        id = ScheduleCalendar.identity("wake|\(profileID)|\(lifecycleID)|\(localDate)")-    }-    var anchor: WakeAnchor { .init(id: id, timestamp: timestamp, recordedAt: recordedAt, localDate: localDate, timeZoneID: timeZoneID, profileID: profileID, ownershipVersion: ownershipVersion, profileLifecycleID: profileLifecycleID) }+  var id: UUID = UUID()+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID?+  var timestamp: Date = Date()+  var recordedAt: Date = Date()+  var sourceRaw: String = "shortcut"+  var localDate: String = ""+  var timeZoneID: String = ""+  init(profileID: UUID, lifecycleID: UUID, timestamp: Date, recordedAt: Date, calendar: Calendar) {+    self.profileID = profileID+    ownershipVersion = 1+    profileLifecycleID = lifecycleID+    self.timestamp = timestamp+    self.recordedAt = recordedAt+    localDate = ScheduleCalendar.localDate(timestamp, calendar: calendar)+    timeZoneID = calendar.timeZone.identifier+    id = ScheduleCalendar.identity("wake|\(profileID)|\(lifecycleID)|\(localDate)")+  }+  var anchor: WakeAnchor {+    .init(+      id: id, timestamp: timestamp, recordedAt: recordedAt, localDate: localDate,+      timeZoneID: timeZoneID, profileID: profileID, ownershipVersion: ownershipVersion,+      profileLifecycleID: profileLifecycleID)+  } }
Meddy/Meddy/MyApp.swift Modified
diff --git a/Meddy/Meddy/MyApp.swift b/Meddy/Meddy/MyApp.swiftindex 4757379..eae5bb6 100644--- a/Meddy/Meddy/MyApp.swift+++ b/Meddy/Meddy/MyApp.swift@@ -1,34 +1,37 @@-import SwiftUI import SwiftData+import SwiftUI  @main struct MyApp: App {-    @State private var container: ModelContainer?-    @State private var error: String?+  @State private var container: ModelContainer?+  @State private var error: String? -    init() {-        do { _container = State(initialValue: try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting)) }-        catch { _error = State(initialValue: error.localizedDescription) }-    }+  init() {+    do {+      _container = State(+        initialValue: try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting))+    } catch { _error = State(initialValue: error.localizedDescription) }+  } -    var body: some Scene {-        WindowGroup {-            if let container {-                AppRootView(container: container).modelContainer(container)-            } else {-                ContentUnavailableView {-                    Label("Meddy could not open its store", systemImage: "externaldrive.badge.exclamationmark")-                } description: {-                    Text(error ?? "Please try again.")-                } actions: {-                    Button("Try again") {-                        do {-                            container = try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting)-                            error = nil-                        } catch { self.error = error.localizedDescription }-                    }-                }-            }+  var body: some Scene {+    WindowGroup {+      if let container {+        AppRootView(container: container).modelContainer(container)+      } else {+        ContentUnavailableView {+          Label(+            "Meddy could not open its store", systemImage: "externaldrive.badge.exclamationmark")+        } description: {+          Text(error ?? "Please try again.")+        } actions: {+          Button("Try again") {+            do {+              container = try AppEnvironment.makeContainer(isolated: AppEnvironment.isTesting)+              error = nil+            } catch { self.error = error.localizedDescription }+          }         }+      }     }+  } }
Meddy/Meddy/Services/AsNeededLimitService.swift Modified
diff --git a/Meddy/Meddy/Services/AsNeededLimitService.swift b/Meddy/Meddy/Services/AsNeededLimitService.swiftindex bc5fbb4..3145984 100644--- a/Meddy/Meddy/Services/AsNeededLimitService.swift+++ b/Meddy/Meddy/Services/AsNeededLimitService.swift@@ -3,36 +3,56 @@ import SwiftData  @MainActor final class AsNeededLimitService {-    private let context: ModelContext-    private let deferSave: Bool-    init(context: ModelContext, deferSave: Bool = false) { self.context = context; self.deferSave = deferSave }-    func limits(_ medication: Medication) throws -> AsNeededDoseLimits? {-        guard let data = medication.asNeededDoseLimitsData else { return nil }-        do { return try JSONDecoder().decode(AsNeededDoseLimits.self, from: data) }-        catch { throw AsNeededLimitError.unreadableConfiguration }+  private let context: ModelContext+  private let deferSave: Bool+  init(context: ModelContext, deferSave: Bool = false) {+    self.context = context+    self.deferSave = deferSave+  }+  func limits(_ medication: Medication) throws -> AsNeededDoseLimits? {+    guard let data = medication.asNeededDoseLimitsData else { return nil }+    do { return try JSONDecoder().decode(AsNeededDoseLimits.self, from: data) } catch {+      throw AsNeededLimitError.unreadableConfiguration     }-    func configure(_ medication: Medication, limits: AsNeededDoseLimits?, now: Date = Date()) throws {-        _ = try ProfileAccess.owner(medication, context: context)-        let value = limits-        try value?.validate(now: now)-        context.autosaveEnabled = false-        medication.asNeededDoseLimitsData = try value.map { try JSONEncoder().encode($0) }-        guard !deferSave else { return }-        do { try context.save() } catch { context.rollback(); throw RecordingError.saveFailed }-        MutationEffects.saved(context)+  }+  func configure(_ medication: Medication, limits: AsNeededDoseLimits?, now: Date = Date()) throws {+    _ = try ProfileAccess.owner(medication, context: context)+    let value = limits+    try value?.validate(now: now)+    context.autosaveEnabled = false+    medication.asNeededDoseLimitsData = try value.map { try JSONEncoder().encode($0) }+    guard !deferSave else { return }+    do { try context.save() } catch {+      context.rollback()+      throw RecordingError.saveFailed     }-    func check(_ medication: Medication, proposedDose: RecordedDoseSnapshot? = nil, now: Date = Date()) -> DoseLimitCheck {-        do {-            let owner = try ProfileAccess.owner(medication, context: context)-            let rules = try limits(medication)-            // Fetch canonical rows: relationship caches can retain pre-save tombstone values.-            let medicationID = medication.id-            let administrations = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.medicationID == medicationID }))-            let events = administrations.filter { ProfileAccess.visible($0, for: owner, context: context) }.map {-                DoseLimitAdministration(id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp, dose: $0.recordedDose, isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch)-            }-            let result = AsNeededDoseLimitEngine().evaluate(medicationID: medication.id, limits: rules, administrations: events, proposedDose: proposedDose ?? medication.defaultDose, now: now)-            return result-        } catch { return .init(state: .needsReview, evaluatedAt: now, issues: [AsNeededLimitError.unreadableConfiguration.localizedDescription]) }+    MutationEffects.saved(context)+  }+  func check(+    _ medication: Medication, proposedDose: RecordedDoseSnapshot? = nil, now: Date = Date()+  ) -> DoseLimitCheck {+    do {+      let owner = try ProfileAccess.owner(medication, context: context)+      let rules = try limits(medication)+      // Fetch canonical rows: relationship caches can retain pre-save tombstone values.+      let medicationID = medication.id+      let administrations = try context.fetch(+        FetchDescriptor<Administration>(predicate: #Predicate { $0.medicationID == medicationID }))+      let events = administrations.filter {+        ProfileAccess.visible($0, for: owner, context: context)+      }.map {+        DoseLimitAdministration(+          id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp, dose: $0.recordedDose,+          isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch)+      }+      let result = AsNeededDoseLimitEngine().evaluate(+        medicationID: medication.id, limits: rules, administrations: events,+        proposedDose: proposedDose ?? medication.defaultDose, now: now)+      return result+    } catch {+      return .init(+        state: .needsReview, evaluatedAt: now,+        issues: [AsNeededLimitError.unreadableConfiguration.localizedDescription])     }+  } }
Meddy/Meddy/Services/CloudSyncMonitor.swift Modified
diff --git a/Meddy/Meddy/Services/CloudSyncMonitor.swift b/Meddy/Meddy/Services/CloudSyncMonitor.swiftindex b5e6737..b48ffed 100644--- a/Meddy/Meddy/Services/CloudSyncMonitor.swift+++ b/Meddy/Meddy/Services/CloudSyncMonitor.swift@@ -1,52 +1,85 @@-import Foundation import CloudKit import CoreData+import Foundation import Observation  @MainActor @Observable final class CloudSyncMonitor {-    var message = "Checking iCloud availability…"-    var lastSuccessfulSync: Date?-    var needsAttention = false-    @ObservationIgnored private var accountTask: Task<Void, Never>?-    @ObservationIgnored private var eventsTask: Task<Void, Never>?-    @ObservationIgnored private var changesTask: Task<Void, Never>?-    private var syncFailed = false-    private let isolated: Bool-    init(isolated: Bool) {-        self.isolated = isolated-        guard !isolated else { message = "Isolated test store"; return }-        eventsTask = Task { [weak self] in-            for await notification in NotificationCenter.default.notifications(named: NSPersistentCloudKitContainer.eventChangedNotification) {-                guard let self, let event = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event else { continue }-                if event.endDate == nil { message = "Syncing with iCloud…" }-                else if !event.succeeded { syncFailed = true; needsAttention = true; message = "iCloud sync needs attention. Your records remain on this iPhone." }-                else if event.type == .import || event.type == .export { syncFailed = false; needsAttention = false; lastSuccessfulSync = event.endDate; message = "iCloud sync completed" }-            }-        }-        changesTask = Task { [weak self] in-            for await _ in NotificationCenter.default.notifications(named: .CKAccountChanged) { self?.refresh() }+  var message = "Checking iCloud availability…"+  var lastSuccessfulSync: Date?+  var needsAttention = false+  @ObservationIgnored private var accountTask: Task<Void, Never>?+  @ObservationIgnored private var eventsTask: Task<Void, Never>?+  @ObservationIgnored private var changesTask: Task<Void, Never>?+  private var syncFailed = false+  private let isolated: Bool+  init(isolated: Bool) {+    self.isolated = isolated+    guard !isolated else {+      message = "Isolated test store"+      return+    }+    eventsTask = Task { [weak self] in+      for await notification in NotificationCenter.default.notifications(+        named: NSPersistentCloudKitContainer.eventChangedNotification) {+        guard let self,+          let event = notification.userInfo?[+            NSPersistentCloudKitContainer.eventNotificationUserInfoKey]+            as? NSPersistentCloudKitContainer.Event+        else { continue }+        if event.endDate == nil {+          message = "Syncing with iCloud…"+        } else if !event.succeeded {+          syncFailed = true+          needsAttention = true+          message = "iCloud sync needs attention. Your records remain on this iPhone."+        } else if event.type == .import || event.type == .export {+          syncFailed = false+          needsAttention = false+          lastSuccessfulSync = event.endDate+          message = "iCloud sync completed"         }-        refresh()+      }+    }+    changesTask = Task { [weak self] in+      for await _ in NotificationCenter.default.notifications(named: .CKAccountChanged) {+        self?.refresh()+      }     }-    func refresh() {-        guard !isolated else { return }-        accountTask?.cancel()-        accountTask = Task {-            do {-                let status = try await CKContainer(identifier: "iCloud.me.nore.ig.meddy").accountStatus()-                guard !Task.isCancelled else { return }-                switch status {-                case .available:-                    needsAttention = syncFailed-                    if syncFailed { message = "iCloud sync needs attention. Your records remain on this iPhone." }-                    else if lastSuccessfulSync == nil { message = "iCloud available · Waiting for sync" }-                case .noAccount: needsAttention = true; message = "Sign in to iCloud to sync. Your records remain on this iPhone."-                case .restricted: needsAttention = true; message = "iCloud access is restricted. Your records remain on this iPhone."-                case .couldNotDetermine, .temporarilyUnavailable: needsAttention = true; message = "iCloud is temporarily unavailable. Your records remain on this iPhone."-                @unknown default: needsAttention = true; message = "iCloud status is unavailable. Your records remain on this iPhone."-                }-            } catch { needsAttention = true; message = "Could not check iCloud availability. Your records remain on this iPhone." }+    refresh()+  }+  func refresh() {+    guard !isolated else { return }+    accountTask?.cancel()+    accountTask = Task {+      do {+        let status = try await CKContainer(identifier: "iCloud.me.nore.ig.meddy").accountStatus()+        guard !Task.isCancelled else { return }+        switch status {+        case .available:+          needsAttention = syncFailed+          if syncFailed {+            message = "iCloud sync needs attention. Your records remain on this iPhone."+          } else if lastSuccessfulSync == nil {+            message = "iCloud available · Waiting for sync"+          }+        case .noAccount:+          needsAttention = true+          message = "Sign in to iCloud to sync. Your records remain on this iPhone."+        case .restricted:+          needsAttention = true+          message = "iCloud access is restricted. Your records remain on this iPhone."+        case .couldNotDetermine, .temporarilyUnavailable:+          needsAttention = true+          message = "iCloud is temporarily unavailable. Your records remain on this iPhone."+        @unknown default:+          needsAttention = true+          message = "iCloud status is unavailable. Your records remain on this iPhone."         }+      } catch {+        needsAttention = true+        message = "Could not check iCloud availability. Your records remain on this iPhone."+      }     }+  } }
Meddy/Meddy/Services/EditorTransaction.swift Modified
diff --git a/Meddy/Meddy/Services/EditorTransaction.swift b/Meddy/Meddy/Services/EditorTransaction.swiftindex 46ca416..63a47af 100644--- a/Meddy/Meddy/Services/EditorTransaction.swift+++ b/Meddy/Meddy/Services/EditorTransaction.swift@@ -2,13 +2,16 @@ import SwiftData  @MainActor enum EditorTransaction {-    static func save<T>(context: ModelContext, _ body: () throws -> T) throws -> T {-        context.autosaveEnabled = false-        do {-            let result = try body()-            do { try context.save() } catch { throw RecordingError.saveFailed }-            MutationEffects.saved(context)-            return result-        } catch { context.rollback(); throw error }+  static func save<T>(context: ModelContext, _ body: () throws -> T) throws -> T {+    context.autosaveEnabled = false+    do {+      let result = try body()+      do { try context.save() } catch { throw RecordingError.saveFailed }+      MutationEffects.saved(context)+      return result+    } catch {+      context.rollback()+      throw error     }+  } }
Meddy/Meddy/Services/MedicationFollowupService.swift Modified
diff --git a/Meddy/Meddy/Services/MedicationFollowupService.swift b/Meddy/Meddy/Services/MedicationFollowupService.swiftindex 2e645d0..b764b49 100644--- a/Meddy/Meddy/Services/MedicationFollowupService.swift+++ b/Meddy/Meddy/Services/MedicationFollowupService.swift@@ -3,55 +3,84 @@ import SwiftData  @MainActor enum MedicationFollowupService {-    static func configuration(_ medication: Medication) throws -> MedicationFollowup? {-        guard let data = medication.followupNotificationData else { return nil }-        let value = try JSONDecoder().decode(MedicationFollowup.self, from: data)-        try value.validate()-        return value+  static func configuration(_ medication: Medication) throws -> MedicationFollowup? {+    guard let data = medication.followupNotificationData else { return nil }+    let value = try JSONDecoder().decode(MedicationFollowup.self, from: data)+    try value.validate()+    return value+  }+  static func configure(_ medication: Medication, value: MedicationFollowup?) throws {+    if let context = medication.modelContext {+      _ = try ProfileAccess.owner(medication, context: context)     }-    static func configure(_ medication: Medication, value: MedicationFollowup?) throws {-        if let context = medication.modelContext { _ = try ProfileAccess.owner(medication, context: context) }-        try value?.validate()-        medication.followupNotificationData = try value.map { try JSONEncoder().encode($0) }-    }-    // Canonical rows cover phone, Watch, notifications and routines, without schedule/day filtering.-    static func actions(context: ModelContext, now: Date) throws -> [MedicationFollowupAction] {-        let medications = try context.fetch(FetchDescriptor<Medication>())-        let events = try context.fetch(FetchDescriptor<Administration>())-        var result: [MedicationFollowupAction] = []-        for medication in medications where medication.isActive && (try? ProfileAccess.owner(medication, context: context)) != nil {-            guard let value = try? configuration(medication) else { continue }-            for event in events where event.medicationID == medication.id && event.profileID == medication.profileID && (try? ProfileAccess.owner(event, context: context)) != nil && !event.isDeleted && !event.hasClockMismatch && event.timestamp <= now {-                var action = MedicationFollowupAction(eventID: event.id, medicationID: medication.id, takenAt: event.timestamp, configuration: value)-                action.profileID = medication.profileID; result.append(action)-            }-        }-        return result+    try value?.validate()+    medication.followupNotificationData = try value.map { try JSONEncoder().encode($0) }+  }+  // Canonical rows cover phone, Watch, notifications and routines, without schedule/day filtering.+  static func actions(context: ModelContext, now: Date) throws -> [MedicationFollowupAction] {+    let medications = try context.fetch(FetchDescriptor<Medication>())+    let events = try context.fetch(FetchDescriptor<Administration>())+    var result: [MedicationFollowupAction] = []+    for medication in medications+    where medication.isActive && (try? ProfileAccess.owner(medication, context: context)) != nil {+      guard let value = try? configuration(medication) else { continue }+      for event in events+      where event.medicationID == medication.id && event.profileID == medication.profileID+        && (try? ProfileAccess.owner(event, context: context)) != nil && !event.isDeleted+        && !event.hasClockMismatch && event.timestamp <= now {+        var action = MedicationFollowupAction(+          eventID: event.id, medicationID: medication.id, takenAt: event.timestamp,+          configuration: value)+        action.profileID = medication.profileID+        result.append(action)+      }     }+    return result+  } }  // Device-local receipt means a scheduled deadline elapsed, not proof that iOS displayed an alert. // Keep UUID receipts after dismissal/relaunch so edits cannot replay an already elapsed follow-up. @MainActor final class FollowupReceipts {-    private struct State: Codable { var scheduled: [String: Date] = [:]; var elapsed: Set<String> = [] }-    private var state: State-    private let defaults: UserDefaults?-    private let key: String-    init(defaults: UserDefaults?, key: String = "meddy.notification.followup-receipts") {-        self.key = key-        self.defaults = defaults-        state = defaults?.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) } ?? State()-    }-    func advance(now: Date) {-        for (id, date) in state.scheduled where date <= now { state.elapsed.insert(id) }-        state.scheduled = state.scheduled.filter { !state.elapsed.contains($0.key) }-        persist()-    }-    func hasElapsed(_ id: String) -> Bool { state.elapsed.contains(id) }-    func scheduled(_ reminder: PlannedReminder) { state.scheduled[reminder.id] = reminder.deliveryAt; persist() }-    func forgetPending(_ id: String) { state.scheduled.removeValue(forKey: id); persist() }-    func retainPending(_ ids: Set<String>) { state.scheduled = state.scheduled.filter { ids.contains($0.key) }; persist() }-    func markElapsed(_ id: String) { state.elapsed.insert(id); state.scheduled.removeValue(forKey: id); persist() }-    private func persist() { if let data = try? JSONEncoder().encode(state) { defaults?.set(data, forKey: key) } }+  private struct State: Codable {+    var scheduled: [String: Date] = [:]+    var elapsed: Set<String> = []+  }+  private var state: State+  private let defaults: UserDefaults?+  private let key: String+  init(defaults: UserDefaults?, key: String = "meddy.notification.followup-receipts") {+    self.key = key+    self.defaults = defaults+    state =+      defaults?.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }+      ?? State()+  }+  func advance(now: Date) {+    for (id, date) in state.scheduled where date <= now { state.elapsed.insert(id) }+    state.scheduled = state.scheduled.filter { !state.elapsed.contains($0.key) }+    persist()+  }+  func hasElapsed(_ id: String) -> Bool { state.elapsed.contains(id) }+  func scheduled(_ reminder: PlannedReminder) {+    state.scheduled[reminder.id] = reminder.deliveryAt+    persist()+  }+  func forgetPending(_ id: String) {+    state.scheduled.removeValue(forKey: id)+    persist()+  }+  func retainPending(_ ids: Set<String>) {+    state.scheduled = state.scheduled.filter { ids.contains($0.key) }+    persist()+  }+  func markElapsed(_ id: String) {+    state.elapsed.insert(id)+    state.scheduled.removeValue(forKey: id)+    persist()+  }+  private func persist() {+    if let data = try? JSONEncoder().encode(state) { defaults?.set(data, forKey: key) }+  } }
Meddy/Meddy/Services/MedicationPhotoService.swift Modified
diff --git a/Meddy/Meddy/Services/MedicationPhotoService.swift b/Meddy/Meddy/Services/MedicationPhotoService.swiftindex 6c6c0b2..48f6820 100644--- a/Meddy/Meddy/Services/MedicationPhotoService.swift+++ b/Meddy/Meddy/Services/MedicationPhotoService.swift@@ -1,93 +1,120 @@ import Foundation-import SwiftData import ImageIO+import SwiftData import UniformTypeIdentifiers  nonisolated enum MedicationPhotoError: Error, LocalizedError, Sendable {-    case inputTooLarge, invalidImage, cannotFit, unavailable-    var errorDescription: String? {-        switch self {-        case .inputTooLarge: "Choose a photo smaller than 20 MiB."-        case .invalidImage: "This image could not be read. Choose another photo."-        case .cannotFit: "This photo could not be resized. Choose another photo."-        case .unavailable: "The selected photo could not be loaded. Try again when it is available."-        }+  case inputTooLarge, invalidImage, cannotFit, unavailable+  var errorDescription: String? {+    switch self {+    case .inputTooLarge: "Choose a photo smaller than 20 MiB."+    case .invalidImage: "This image could not be read. Choose another photo."+    case .cannotFit: "This photo could not be resized. Choose another photo."+    case .unavailable: "The selected photo could not be loaded. Try again when it is available."     }+  } }  nonisolated enum MedicationPhotoProcessor {-    static let inputLimit = 20 * 1024 * 1024-    static let storedLimit = 350 * 1024-    static let longestSide = 1024+  static let inputLimit = 20 * 1024 * 1024+  static let storedLimit = 350 * 1024+  static let longestSide = 1024 -    static func prepare(_ input: Data) throws -> Data {-        guard input.count <= inputLimit else { throw MedicationPhotoError.inputTooLarge }-        guard let source = CGImageSourceCreateWithData(input as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),-              let type = CGImageSourceGetType(source), UTType(type as String)?.conforms(to: .image) == true else { throw MedicationPhotoError.invalidImage }-        for side in [longestSide, 768, 512] {-            guard let preview = thumbnail(source, side: side), let image = opaque(preview) else { throw MedicationPhotoError.invalidImage }-            for quality in [0.82, 0.65, 0.5] {-                let output = NSMutableData()-                guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else { throw MedicationPhotoError.invalidImage }-                // Re-encode pixels only: never copy source EXIF, GPS or other dictionaries.-                CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)-                guard CGImageDestinationFinalize(destination) else { throw MedicationPhotoError.invalidImage }-                if output.length <= storedLimit { return output as Data }-            }+  static func prepare(_ input: Data) throws -> Data {+    guard input.count <= inputLimit else { throw MedicationPhotoError.inputTooLarge }+    guard+      let source = CGImageSourceCreateWithData(+        input as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),+      let type = CGImageSourceGetType(source), UTType(type as String)?.conforms(to: .image) == true+    else { throw MedicationPhotoError.invalidImage }+    for side in [longestSide, 768, 512] {+      guard let preview = thumbnail(source, side: side), let image = opaque(preview) else {+        throw MedicationPhotoError.invalidImage+      }+      for quality in [0.82, 0.65, 0.5] {+        let output = NSMutableData()+        guard+          let destination = CGImageDestinationCreateWithData(+            output, UTType.jpeg.identifier as CFString, 1, nil)+        else { throw MedicationPhotoError.invalidImage }+        // Re-encode pixels only: never copy source EXIF, GPS or other dictionaries.+        CGImageDestinationAddImage(+          destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)+        guard CGImageDestinationFinalize(destination) else {+          throw MedicationPhotoError.invalidImage         }-        throw MedicationPhotoError.cannotFit+        if output.length <= storedLimit { return output as Data }+      }     }+    throw MedicationPhotoError.cannotFit+  } -    static func validate(_ data: Data) throws {-        guard !data.isEmpty, data.count <= storedLimit,-              let source = CGImageSourceCreateWithData(data as CFData, nil),-              CGImageSourceGetType(source) as String? == UTType.jpeg.identifier,-              let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],-              let width = properties[kCGImagePropertyPixelWidth] as? Int,-              let height = properties[kCGImagePropertyPixelHeight] as? Int,-              (1...longestSide).contains(width), (1...longestSide).contains(height),-              properties[kCGImagePropertyGPSDictionary] == nil,-              thumbnail(source, side: 32) != nil else { throw MedicationPhotoError.invalidImage }-        // ImageIO creates these technical EXIF fields even when source metadata is stripped.-        let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] ?? [:]-        guard Set(exif.keys).isSubset(of: [kCGImagePropertyExifColorSpace, kCGImagePropertyExifPixelXDimension, kCGImagePropertyExifPixelYDimension]) else { throw MedicationPhotoError.invalidImage }-    }+  static func validate(_ data: Data) throws {+    guard !data.isEmpty, data.count <= storedLimit,+      let source = CGImageSourceCreateWithData(data as CFData, nil),+      CGImageSourceGetType(source) as String? == UTType.jpeg.identifier,+      let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],+      let width = properties[kCGImagePropertyPixelWidth] as? Int,+      let height = properties[kCGImagePropertyPixelHeight] as? Int,+      (1...longestSide).contains(width), (1...longestSide).contains(height),+      properties[kCGImagePropertyGPSDictionary] == nil,+      thumbnail(source, side: 32) != nil+    else { throw MedicationPhotoError.invalidImage }+    // ImageIO creates these technical EXIF fields even when source metadata is stripped.+    let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] ?? [:]+    guard+      Set(exif.keys).isSubset(of: [+        kCGImagePropertyExifColorSpace, kCGImagePropertyExifPixelXDimension,+        kCGImagePropertyExifPixelYDimension+      ])+    else { throw MedicationPhotoError.invalidImage }+  } -    private static func opaque(_ image: CGImage) -> CGImage? {-        guard let space = CGColorSpace(name: CGColorSpace.sRGB),-              let context = CGContext(data: nil, width: image.width, height: image.height, bitsPerComponent: 8,-                bytesPerRow: image.width * 4, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { return nil }-        let rect = CGRect(x: 0, y: 0, width: image.width, height: image.height)-        context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1)); context.fill(rect)-        context.draw(image, in: rect)-        return context.makeImage()-    }+  private static func opaque(_ image: CGImage) -> CGImage? {+    guard let space = CGColorSpace(name: CGColorSpace.sRGB),+      let context = CGContext(+        data: nil, width: image.width, height: image.height, bitsPerComponent: 8,+        bytesPerRow: image.width * 4, space: space,+        bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)+    else { return nil }+    let rect = CGRect(x: 0, y: 0, width: image.width, height: image.height)+    context.setFillColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))+    context.fill(rect)+    context.draw(image, in: rect)+    return context.makeImage()+  } -    static func thumbnail(_ source: CGImageSource, side: Int) -> CGImage? {-        CGImageSourceCreateThumbnailAtIndex(source, 0, [-            kCGImageSourceCreateThumbnailFromImageAlways: true,-            kCGImageSourceCreateThumbnailWithTransform: true,-            kCGImageSourceThumbnailMaxPixelSize: side,-            kCGImageSourceShouldCacheImmediately: true-        ] as CFDictionary)-    }+  static func thumbnail(_ source: CGImageSource, side: Int) -> CGImage? {+    CGImageSourceCreateThumbnailAtIndex(+      source, 0,+      [+        kCGImageSourceCreateThumbnailFromImageAlways: true,+        kCGImageSourceCreateThumbnailWithTransform: true,+        kCGImageSourceThumbnailMaxPixelSize: side,+        kCGImageSourceShouldCacheImmediately: true+      ] as CFDictionary)+  } }  @MainActor final class MedicationPhotoService {-    private let context: ModelContext-    private let deferSave: Bool-    private let saveOverride: (() throws -> Void)?-    init(context: ModelContext, deferSave: Bool = false, save: (() throws -> Void)? = nil) {-        self.context = context; self.deferSave = deferSave; saveOverride = save-        context.autosaveEnabled = false-    }-    func setPhoto(_ data: Data?, for medication: Medication) throws {-        if let data { try MedicationPhotoProcessor.validate(data) }-        medication.recognitionPhotoData = data-        guard !deferSave else { return }-        do { if let saveOverride { try saveOverride() } else { try context.save() } }-        catch { context.rollback(); throw RecordingError.saveFailed }-        MutationEffects.saved(context)+  private let context: ModelContext+  private let deferSave: Bool+  private let saveOverride: (() throws -> Void)?+  init(context: ModelContext, deferSave: Bool = false, save: (() throws -> Void)? = nil) {+    self.context = context+    self.deferSave = deferSave+    saveOverride = save+    context.autosaveEnabled = false+  }+  func setPhoto(_ data: Data?, for medication: Medication) throws {+    if let data { try MedicationPhotoProcessor.validate(data) }+    medication.recognitionPhotoData = data+    guard !deferSave else { return }+    do { if let saveOverride { try saveOverride() } else { try context.save() } } catch {+      context.rollback()+      throw RecordingError.saveFailed     }+    MutationEffects.saved(context)+  } }
Meddy/Meddy/Services/MedicationService.swift Modified
diff --git a/Meddy/Meddy/Services/MedicationService.swift b/Meddy/Meddy/Services/MedicationService.swiftindex 258e3b2..d9d62f4 100644--- a/Meddy/Meddy/Services/MedicationService.swift+++ b/Meddy/Meddy/Services/MedicationService.swift@@ -1,142 +1,158 @@ import Foundation import SwiftData +@MainActor+struct MedicationEdit {+  var name: String+  var dose: RecordedDoseSnapshot+  var purpose: Purpose?+  var method: String+  var requirements: String+  var notes: String+}+ @MainActor final class MedicationService {-    private let context: ModelContext-    private let deferSave: Bool-    var onChange: () -> Void = {}+  private let context: ModelContext+  private let deferSave: Bool+  var onChange: () -> Void = {} -    init(context: ModelContext, deferSave: Bool = false) {-        self.context = context-        self.deferSave = deferSave-        context.autosaveEnabled = false-    }+  init(context: ModelContext, deferSave: Bool = false) {+    self.context = context+    self.deferSave = deferSave+    context.autosaveEnabled = false+  } -    func createAsNeededMedication(-        name: String, dose: RecordedDoseSnapshot = .unknown,-        purpose: Purpose? = nil, method: String = "",-        requirements: String = "", notes: String = "", profileID: UUID = ProfileIdentity.me-    ) throws -> Medication {-        let name = name.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !name.isEmpty else { throw RecordingError.missingName }-        try dose.validate()-        let medication = Medication(name: name)-        try ProfileAccess.assign(medication, to: profileID, context: context)-        if let purpose { try ProfileAccess.same(medication, purpose, context: context) }-        medication.doseDescription = dose.description-        medication.defaultDoseAmount = dose.amount-        medication.defaultDoseUnit = dose.unit-        medication.purpose = purpose-        medication.administrationMethod = method-        medication.requirements = requirements-        medication.notes = notes-        context.insert(medication)-        try save()-        return medication-    }+  func createAsNeededMedication(+    name: String, dose: RecordedDoseSnapshot = .unknown,+    purpose: Purpose? = nil, method: String = "",+    requirements: String = "", notes: String = "", profileID: UUID = ProfileIdentity.me+  ) throws -> Medication {+    let name = name.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !name.isEmpty else { throw RecordingError.missingName }+    try dose.validate()+    let medication = Medication(name: name)+    try ProfileAccess.assign(medication, to: profileID, context: context)+    if let purpose { try ProfileAccess.same(medication, purpose, context: context) }+    medication.doseDescription = dose.description+    medication.defaultDoseAmount = dose.amount+    medication.defaultDoseUnit = dose.unit+    medication.purpose = purpose+    medication.administrationMethod = method+    medication.requirements = requirements+    medication.notes = notes+    context.insert(medication)+    try save()+    return medication+  } -    func record(_ input: AdministrationAction) throws -> Administration {-        var action = input-        let medication = try ProfileAccess.canonical(Medication.self, id: action.medicationID, context: context)-        try ProfileAccess.action(action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID, target: medication, context: context)-        if action.scheduleTypeAtRecording == .afterWaking {-            let wake = WakeService(context: context)-            let owner = medication.profileID ?? ProfileIdentity.me-            if action.wakeEventID == nil && action.source != .watch,-               let anchor = try wake.anchor(profileID: owner), action.timestamp >= anchor.timestamp { action.wakeEventID = anchor.id }-            if let id = action.wakeEventID { try wake.validate(id: id, profileID: owner) }-        }-        let id = action.eventID-        let existing = try context.fetch(FetchDescriptor<Administration>(-            predicate: #Predicate { $0.id == id }-        ))-        guard existing.count <= 1 else { throw ProfileError.conflictingOwnership }-        if let event = existing.first {-            try ProfileAccess.same(event, medication, context: context)-            guard event.medicationID == medication.id else { throw ProfileError.conflictingOwnership }-            return event-        }-        try action.dose.validate()-        guard action.source == .watch || action.timestamp <= Date() else { throw RecordingError.futureTime }-        let event = Administration(action: action, medication: medication)-        event.hasClockMismatch = action.timestamp > Date()-        context.insert(event)-        try save()-        return event+  func record(_ input: AdministrationAction) throws -> Administration {+    var action = input+    let medication = try ProfileAccess.canonical(+      Medication.self, id: action.medicationID, context: context)+    try ProfileAccess.action(+      action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID,+      target: medication, context: context)+    if action.scheduleTypeAtRecording == .afterWaking {+      let wake = WakeService(context: context)+      let owner = medication.profileID ?? ProfileIdentity.me+      if action.wakeEventID == nil && action.source != .watch,+        let anchor = try wake.anchor(profileID: owner), action.timestamp >= anchor.timestamp {+        action.wakeEventID = anchor.id+      }+      if let id = action.wakeEventID { try wake.validate(id: id, profileID: owner) }     }--    func correct(_ event: Administration, timestamp: Date, dose: RecordedDoseSnapshot) throws {-        _ = try ProfileAccess.owner(event, context: context)-        let medication = try ProfileAccess.canonical(Medication.self, id: event.medicationID, context: context)-        try ProfileAccess.same(event, medication, context: context)-        guard event.routineRunID == nil else { throw RecordingError.linkedCorrectionRequired }-        try dose.validate()-        guard timestamp <= Date() else { throw RecordingError.futureTime }-        event.timestamp = timestamp-        event.hasClockMismatch = false // Explicit correction validates the actual time above.-        event.doseDescriptionSnapshot = dose.description-        event.doseAmount = dose.amount-        event.doseUnit = dose.unit-        event.updatedAt = Date()-        try save()+    let id = action.eventID+    let existing = try context.fetch(+      FetchDescriptor<Administration>(+        predicate: #Predicate { $0.id == id }+      ))+    guard existing.count <= 1 else { throw ProfileError.conflictingOwnership }+    if let event = existing.first {+      try ProfileAccess.same(event, medication, context: context)+      guard event.medicationID == medication.id else { throw ProfileError.conflictingOwnership }+      return event     }--    func delete(_ event: Administration) throws {-        _ = try ProfileAccess.owner(event, context: context)-        let medication = try ProfileAccess.canonical(Medication.self, id: event.medicationID, context: context)-        try ProfileAccess.same(event, medication, context: context)-        guard event.routineRunID == nil else { throw RecordingError.linkedCorrectionRequired }-        event.isDeleted = true-        event.updatedAt = Date()-        try save()+    try action.dose.validate()+    guard action.source == .watch || action.timestamp <= Date() else {+      throw RecordingError.futureTime     }+    let event = Administration(action: action, medication: medication)+    event.hasClockMismatch = action.timestamp > Date()+    context.insert(event)+    try save()+    return event+  } -    func update(-        _ medication: Medication, name: String, dose: RecordedDoseSnapshot,-        purpose: Purpose?, method: String, requirements: String, notes: String-    ) throws {-        _ = try ProfileAccess.owner(medication, context: context)-        if let purpose { try ProfileAccess.same(medication, purpose, context: context) }-        let name = name.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !name.isEmpty else { throw RecordingError.missingName }-        try dose.validate()-        medication.name = name-        medication.doseDescription = dose.description-        medication.defaultDoseAmount = dose.amount-        medication.defaultDoseUnit = dose.unit-        medication.purpose = purpose-        medication.administrationMethod = method-        medication.requirements = requirements-        medication.notes = notes-        try save()-    }+  func correct(_ event: Administration, timestamp: Date, dose: RecordedDoseSnapshot) throws {+    _ = try ProfileAccess.owner(event, context: context)+    let medication = try ProfileAccess.canonical(+      Medication.self, id: event.medicationID, context: context)+    try ProfileAccess.same(event, medication, context: context)+    guard event.routineRunID == nil else { throw RecordingError.linkedCorrectionRequired }+    try dose.validate()+    guard timestamp <= Date() else { throw RecordingError.futureTime }+    event.timestamp = timestamp+    event.hasClockMismatch = false  // Explicit correction validates the actual time above.+    event.doseDescriptionSnapshot = dose.description+    event.doseAmount = dose.amount+    event.doseUnit = dose.unit+    event.updatedAt = Date()+    try save()+  } -    func setActive(_ medication: Medication, _ active: Bool) throws {-        _ = try ProfileAccess.owner(medication, context: context)-        medication.isActive = active-        medication.archivedAt = active ? nil : Date()-        try save()-    }+  func delete(_ event: Administration) throws {+    _ = try ProfileAccess.owner(event, context: context)+    let medication = try ProfileAccess.canonical(+      Medication.self, id: event.medicationID, context: context)+    try ProfileAccess.same(event, medication, context: context)+    guard event.routineRunID == nil else { throw RecordingError.linkedCorrectionRequired }+    event.isDeleted = true+    event.updatedAt = Date()+    try save()+  } -    func createPurpose(name: String, profileID: UUID = ProfileIdentity.me) throws -> Purpose {-        let name = name.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !name.isEmpty else { throw RecordingError.missingName }-        let purpose = Purpose(name: name)-        try ProfileAccess.assign(purpose, to: profileID, context: context)-        context.insert(purpose)-        try save()-        return purpose-    }+  func update(_ medication: Medication, edit: MedicationEdit) throws {+    _ = try ProfileAccess.owner(medication, context: context)+    if let purpose = edit.purpose { try ProfileAccess.same(medication, purpose, context: context) }+    let name = edit.name.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !name.isEmpty else { throw RecordingError.missingName }+    try edit.dose.validate()+    medication.name = name+    medication.doseDescription = edit.dose.description+    medication.defaultDoseAmount = edit.dose.amount+    medication.defaultDoseUnit = edit.dose.unit+    medication.purpose = edit.purpose+    medication.administrationMethod = edit.method+    medication.requirements = edit.requirements+    medication.notes = edit.notes+    try save()+  }++  func setActive(_ medication: Medication, _ active: Bool) throws {+    _ = try ProfileAccess.owner(medication, context: context)+    medication.isActive = active+    medication.archivedAt = active ? nil : Date()+    try save()+  }++  func createPurpose(name: String, profileID: UUID = ProfileIdentity.me) throws -> Purpose {+    let name = name.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !name.isEmpty else { throw RecordingError.missingName }+    let purpose = Purpose(name: name)+    try ProfileAccess.assign(purpose, to: profileID, context: context)+    context.insert(purpose)+    try save()+    return purpose+  } -    private func save() throws {-        if deferSave { return }-        do { try context.save() }-        catch {-            context.rollback()-            throw RecordingError.saveFailed-        }-        MutationEffects.saved(context)-        onChange()+  private func save() throws {+    if deferSave { return }+    do { try context.save() } catch {+      context.rollback()+      throw RecordingError.saveFailed     }+    MutationEffects.saved(context)+    onChange()+  } }
Meddy/Meddy/Services/PhoneCompanionService.swift Modified
diff --git a/Meddy/Meddy/Services/PhoneCompanionService.swift b/Meddy/Meddy/Services/PhoneCompanionService.swiftindex 6ad6a7e..f156dcd 100644--- a/Meddy/Meddy/Services/PhoneCompanionService.swift+++ b/Meddy/Meddy/Services/PhoneCompanionService.swift@@ -3,203 +3,381 @@ import SwiftData  @MainActor final class PhoneCompanionService {-    private let context: ModelContext-    private let transport = CompanionTransport()-    private let phoneID: UUID-    private var outbox: CompanionStore?-    var onError: (String) -> Void = { _ in }-    var onOpen: (RoutineRun) -> Void = { _ in }-    init(context: ModelContext) {-        self.context = context-        if AppEnvironment.isTesting { phoneID = UUID() }-        else if let value = UserDefaults.standard.string(forKey: "meddy.phone.identity"), let id = UUID(uuidString: value) { phoneID = id }-        else { phoneID = UUID(); UserDefaults.standard.set(phoneID.uuidString, forKey: "meddy.phone.identity") }-        guard !AppEnvironment.isTesting else { return }-        do {-            let file = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("MeddyPhoneTransport/outbox.json")-            outbox = try CompanionStore(file: file)-        } catch { onError("Phone handoff storage could not be opened. Existing requests were not discarded.") }-        transport.onActivation = { [weak self] in-            self?.publish()-            for action in self?.outbox?.state.pending ?? [] { try? self?.transport.send(.action(action)) }-        }-        transport.onError = { [weak self] in self?.onError($0) }-        transport.onMessage = { [weak self] message, reply in self?.receive(message, reply: reply) }-        MutationEffects.observe(context) { [weak self] in self?.publish() }-        transport.activate()-    }-    var deviceID: String { phoneID.uuidString }-    var watchReachable: Bool { transport.reachable }-    var onHandoffWaiting: (UUID, Bool) -> Void = { _, _ in }+  private let context: ModelContext+  private let transport = CompanionTransport()+  private let phoneID: UUID+  private var outbox: CompanionStore?+  var onError: (String) -> Void = { _ in }+  var onOpen: (RoutineRun) -> Void = { _ in }+  init(context: ModelContext) {+    self.context = context+    if AppEnvironment.isTesting {+      phoneID = UUID()+    } else if let value = UserDefaults.standard.string(forKey: "meddy.phone.identity"),+      let id = UUID(uuidString: value) {+      phoneID = id+    } else {+      phoneID = UUID()+      UserDefaults.standard.set(phoneID.uuidString, forKey: "meddy.phone.identity")+    }+    guard !AppEnvironment.isTesting else { return }+    do {+      let file = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+        .appendingPathComponent("MeddyPhoneTransport/outbox.json")+      outbox = try CompanionStore(file: file)+    } catch {+      onError("Phone handoff storage could not be opened. Existing requests were not discarded.")+    }+    transport.onActivation = { [weak self] in+      self?.publish()+      for action in self?.outbox?.state.pending ?? [] { try? self?.transport.send(.action(action)) }+    }+    transport.onError = { [weak self] in self?.onError($0) }+    transport.onMessage = { [weak self] message, reply in self?.receive(message, reply: reply) }+    MutationEffects.observe(context) { [weak self] in self?.publish() }+    transport.activate()+  }+  var deviceID: String { phoneID.uuidString }+  var watchReachable: Bool { transport.reachable }+  var onHandoffWaiting: (UUID, Bool) -> Void = { _, _ in } -    func takeOnPhone(_ run: RoutineRun, offlineConfirmed: Bool) throws {-        guard run.executionDeviceID != nil && run.executionDeviceID != deviceID else { return }-        let service = RoutineSessionService(context: context)-        if !transport.reachable {-            guard offlineConfirmed else { throw ExecutionError.invalidTransition }-            try service.handoff(run, toDeviceID: deviceID, actionID: UUID(), expectedRevision: run.revision)-            return-        }-        guard let outbox else { throw ExecutionError.saveFailed }-        if let existing = outbox.state.pending.first(where: { $0.operation.runID == run.id }) {-            if outbox.state.rejected[existing.id] != nil { try outbox.discardRejectedHandoff(existing.id) }-            else { onHandoffWaiting(run.id, true); try transport.send(.action(existing)); return }-        }-        let value = try snapshot().runs.first { $0.id == run.id }-        guard let value else { throw ExecutionError.unknownRun }-        var action = CompanionAction(id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: run.revision, operation: .handoff(runID: run.id, checkpoint: value, toDeviceID: deviceID), cachedRun: value)-        action.version = 2; action.profileID = run.profileID; action.ownershipVersion = run.ownershipVersion; action.profileLifecycleID = try ProfileAccess.lifecycle(run, context: context)-        try outbox.receive(snapshot())-        try outbox.enqueue(action)+  func takeOnPhone(_ run: RoutineRun, offlineConfirmed: Bool) throws {+    guard run.executionDeviceID != nil && run.executionDeviceID != deviceID else { return }+    let service = RoutineSessionService(context: context)+    if !transport.reachable {+      guard offlineConfirmed else { throw ExecutionError.invalidTransition }+      try service.handoff(+        run, toDeviceID: deviceID, actionID: UUID(), expectedRevision: run.revision)+      return+    }+    guard let outbox else { throw ExecutionError.saveFailed }+    if let existing = outbox.state.pending.first(where: { $0.operation.runID == run.id }) {+      if outbox.state.rejected[existing.id] != nil {+        try outbox.discardRejectedHandoff(existing.id)+      } else {         onHandoffWaiting(run.id, true)-        try transport.send(.action(action))+        try transport.send(.action(existing))+        return+      }     }+    let value = try snapshot().runs.first { $0.id == run.id }+    guard let value else { throw ExecutionError.unknownRun }+    var action = CompanionAction(+      id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: run.revision,+      operation: .handoff(runID: run.id, checkpoint: value, toDeviceID: deviceID), cachedRun: value)+    action.version = 2+    action.profileID = run.profileID+    action.ownershipVersion = run.ownershipVersion+    action.profileLifecycleID = try ProfileAccess.lifecycle(run, context: context)+    try outbox.receive(snapshot())+    try outbox.enqueue(action)+    onHandoffWaiting(run.id, true)+    try transport.send(.action(action))+  } -    private func receiveHandoff(_ actionID: UUID, checkpoint: CompanionRun, reply: ((Data) -> Void)?) throws {-        let id = checkpoint.id-        try CompanionOwnership.validate(checkpoint)-        let canonical = try ProfileAccess.canonical(RoutineRun.self, id: id, context: context)-        try ProfileAccess.action(checkpoint.profileID ?? checkpoint.definition.profileID, version: checkpoint.ownershipVersion, lifecycle: checkpoint.profileLifecycleID, target: canonical, context: context)-        guard canonical.profileID == ProfileIdentity.me || canonical.profileLifecycleID == checkpoint.profileLifecycleID else { throw ProfileError.staleLifecycle }-        guard let outbox else { throw ExecutionError.saveFailed }-        guard let request = outbox.state.pending.first(where: { $0.id == actionID }) else {-            if let run = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first,-               run.executionDeviceID == deviceID, (try? JSONDecoder().decode([UUID].self, from: run.processedActionIDsData).contains(actionID)) == true {-                let response = CompanionMessage.acknowledgement(.init(actionID: actionID, accepted: true, snapshot: try snapshot()))-                if let reply { reply(try JSONEncoder().encode(response)) } else { try transport.send(response) }-            }-            return+  private func receiveHandoff(_ actionID: UUID, checkpoint: CompanionRun, reply: ((Data) -> Void)?)+    throws {+    let id = checkpoint.id+    try CompanionOwnership.validate(checkpoint)+    let canonical = try ProfileAccess.canonical(RoutineRun.self, id: id, context: context)+    try ProfileAccess.action(+      checkpoint.profileID ?? checkpoint.definition.profileID, version: checkpoint.ownershipVersion,+      lifecycle: checkpoint.profileLifecycleID, target: canonical, context: context)+    guard+      canonical.profileID == ProfileIdentity.me+        || canonical.profileLifecycleID == checkpoint.profileLifecycleID+    else { throw ProfileError.staleLifecycle }+    guard let outbox else { throw ExecutionError.saveFailed }+    guard let request = outbox.state.pending.first(where: { $0.id == actionID }) else {+      if let run = try context.fetch(+        FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })+      ).first,+        run.executionDeviceID == deviceID,+        (try? JSONDecoder().decode([UUID].self, from: run.processedActionIDsData).contains(actionID))+          == true {+        let response = CompanionMessage.acknowledgement(+          .init(actionID: actionID, accepted: true, snapshot: try snapshot()))+        if let reply {+          reply(try JSONEncoder().encode(response))+        } else {+          try transport.send(response)         }-        try CompanionOwnership.validate(request, snapshot: snapshot())-        guard case .handoff(let requestedID, _, let destination) = request.operation, requestedID == checkpoint.id, destination == deviceID else { throw ExecutionError.invalidTransition }-        guard let run = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first else { throw ExecutionError.unknownRun }-        let service = RoutineSessionService(context: context)-        guard checkpoint.revision == run.revision, checkpoint.definition == (try service.definition(run)),-              checkpoint.timer?.phase != .running, checkpoint.progress.phase != .active || checkpoint.timer != nil else { throw ExecutionError.invalidTransition }-        try service.handoff(run, toDeviceID: deviceID, actionID: actionID, expectedRevision: run.revision)-        let ack = CompanionAcknowledgement(actionID: actionID, accepted: true, snapshot: try snapshot())-        try outbox.acknowledge(ack)-        onHandoffWaiting(run.id, false)-        if let reply { reply(try JSONEncoder().encode(CompanionMessage.acknowledgement(ack))) }-        else { try transport.send(.acknowledgement(ack)) }-        publish()+      }+      return     }+    try CompanionOwnership.validate(request, snapshot: snapshot())+    guard case .handoff(let requestedID, _, let destination) = request.operation,+      requestedID == checkpoint.id, destination == deviceID+    else { throw ExecutionError.invalidTransition }+    guard+      let run = try context.fetch(+        FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })+      ).first+    else { throw ExecutionError.unknownRun }+    let service = RoutineSessionService(context: context)+    guard checkpoint.revision == run.revision,+      checkpoint.definition == (try service.definition(run)),+      checkpoint.timer?.phase != .running,+      checkpoint.progress.phase != .active || checkpoint.timer != nil+    else { throw ExecutionError.invalidTransition }+    try service.handoff(+      run, toDeviceID: deviceID, actionID: actionID, expectedRevision: run.revision)+    let ack = CompanionAcknowledgement(actionID: actionID, accepted: true, snapshot: try snapshot())+    try outbox.acknowledge(ack)+    onHandoffWaiting(run.id, false)+    if let reply {+      reply(try JSONEncoder().encode(CompanionMessage.acknowledgement(ack)))+    } else {+      try transport.send(.acknowledgement(ack))+    }+    publish()+  } -    func publish() {-        guard !AppEnvironment.isTesting, transport.available else { return }-        do { try transport.publish(snapshot()) } catch { onError(error.localizedDescription) }-    }-    func snapshot() throws -> CompanionSnapshot {-        let service = RoutineSessionService(context: context)-        let schedules = ScheduleService(context: context)-        let medications = try context.fetch(FetchDescriptor<Medication>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let routines = try context.fetch(FetchDescriptor<Routine>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let events = try context.fetch(FetchDescriptor<Administration>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let treatments = try context.fetch(FetchDescriptor<Treatment>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let completions = try context.fetch(FetchDescriptor<TreatmentCompletion>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let represented = runs.map { ScheduledRunSnapshot(id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID, localDate: $0.scheduledLocalDate, startedAt: $0.startedAt, timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt, status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted) }-        let medicationValues = try medications.map { item in-            var value = CompanionMedication(id: item.id, name: item.name, purpose: item.purpose?.name, requirements: item.requirements, dose: item.defaultDose, schedule: try schedules.snapshot(item), next: try MedicationPresentation.result(item, context: context).next, lastTaken: item.visibleAdministrations.first?.timestamp, active: item.isActive, doseLimitCheck: item.scheduleTypeRaw == "asNeeded" ? AsNeededLimitService(context: context).check(item) : nil)-            value.profileID = item.profileID; value.ownershipVersion = item.ownershipVersion; value.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context)-            return value-        }-        let definitions = try routines.filter(\.isActive).map { item in-            CompanionRoutine(definition: try RoutineService(context: context).freeze(item), occurrences: item.kindRaw == "ordered" ? RoutineScheduleEngine().occurrences(try schedules.snapshot(item), runs: represented, day: Date(), now: Date(), calendar: .current) : [], schedule: item.kindRaw == "ordered" ? try schedules.snapshot(item) : nil)+  func publish() {+    guard !AppEnvironment.isTesting, transport.available else { return }+    do { try transport.publish(snapshot()) } catch { onError(error.localizedDescription) }+  }+  func snapshot() throws -> CompanionSnapshot {+    let service = RoutineSessionService(context: context)+    let schedules = ScheduleService(context: context)+    let medications = try context.fetch(FetchDescriptor<Medication>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let routines = try context.fetch(FetchDescriptor<Routine>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let events = try context.fetch(FetchDescriptor<Administration>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let treatments = try context.fetch(FetchDescriptor<Treatment>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let completions = try context.fetch(FetchDescriptor<TreatmentCompletion>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let represented = runs.map {+      ScheduledRunSnapshot(+        id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,+        localDate: $0.scheduledLocalDate, startedAt: $0.startedAt,+        timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt,+        status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted)+    }+    let medicationValues = try medications.map { item in+      var value = CompanionMedication(+        id: item.id, name: item.name, purpose: item.purpose?.name, requirements: item.requirements,+        dose: item.defaultDose, schedule: try schedules.snapshot(item),+        next: try MedicationPresentation.result(item, context: context).next,+        lastTaken: item.visibleAdministrations.first?.timestamp, active: item.isActive,+        doseLimitCheck: item.scheduleTypeRaw == "asNeeded"+          ? AsNeededLimitService(context: context).check(item) : nil)+      value.profileID = item.profileID+      value.ownershipVersion = item.ownershipVersion+      value.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context)+      return value+    }+    let definitions = try routines.filter(\.isActive).map { item in+      CompanionRoutine(+        definition: try RoutineService(context: context).freeze(item),+        occurrences: item.kindRaw == "ordered"+          ? RoutineScheduleEngine().occurrences(+            try schedules.snapshot(item), runs: represented, day: Date(), now: Date(),+            calendar: .current) : [],+        schedule: item.kindRaw == "ordered" ? try schedules.snapshot(item) : nil)+    }+    let runValues = try runs.map { try companionRun($0, service: service) }+    let revision =+      AppEnvironment.isTesting+      ? 1 : UserDefaults.standard.integer(forKey: "meddy.phone.snapshot-revision") + 1+    if !AppEnvironment.isTesting {+      UserDefaults.standard.set(revision, forKey: "meddy.phone.snapshot-revision")+    }+    var value = CompanionSnapshot(+      version: 2, phoneID: phoneID, revision: revision, generatedAt: Date(),+      medications: medicationValues, routines: definitions, runs: runValues,+      deletedEventIDs: events.filter(\.isDeleted).map(\.id)+        + completions.filter(\.isDeleted).map(\.id),+      appliedEventIDs: events.map(\.id) + completions.map(\.id),+      treatments: try treatments.map { item in+        var result = CompanionTreatment(+          id: item.id, name: item.name, instructions: item.instructions,+          lastDone: (item.completions ?? []).filter {+            !$0.isDeleted && $0.profileID == item.profileID+          }.map(\.timestamp).max(), active: item.isActive)+        result.profileID = item.profileID+        result.ownershipVersion = item.ownershipVersion+        result.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context)+        return result+      })+    value.profiles = try context.fetch(FetchDescriptor<CareProfile>()).compactMap { profile in+      profile.lifecycleID.map {+        CompanionProfile(+          id: profile.id, label: profile.label, archived: profile.archivedAt != nil, lifecycleID: $0+        )+      }+    }+    if value.profiles?.contains(where: { $0.id == ProfileIdentity.me }) != true {+      value.profiles?.insert(+        .init(+          id: ProfileIdentity.me, label: "Me", archived: false,+          lifecycleID: ProfileIdentity.selfLifecycle), at: 0)+    }+    var owners: [UUID: UUID] = [:]+    for event in events { owners[event.id] = event.profileID }+    for event in completions { owners[event.id] = event.profileID }+    value.eventOwners = owners+    try CompanionOwnership.validate(value)+    return value+  }+  private func companionRun(+    _ item: RoutineRun, service: RoutineSessionService+  ) throws -> CompanionRun {+    var value = CompanionRun(+      id: item.id, definition: try service.definition(item), progress: try service.progress(item),+      timer: try item.timerCheckpointData.map {+        try JSONDecoder().decode(TimerCheckpoint.self, from: $0)+      }, status: SessionPhase(rawValue: item.statusRaw) ?? .needsReview,+      startedAt: item.startedAt, completedAt: item.completedAt, revision: item.revision,+      executionDeviceID: item.executionDeviceID, parentRunID: item.parentRoutineRunID,+      parentStepID: item.parentRoutineStepID,+      processedActionIDs: try JSONDecoder().decode(+        [UUID].self, from: item.processedActionIDsData), isDeleted: item.isDeleted)+    value.profileID = item.profileID+    value.ownershipVersion = item.ownershipVersion+    value.profileLifecycleID = item.profileLifecycleID ?? ProfileIdentity.selfLifecycle+    if value.profileID != ProfileIdentity.me,+      value.profileLifecycleID != (try ProfileAccess.lifecycle(item, context: context)) {+      value.status = .paused+      if var timer = value.timer, timer.phase == .running {+        timer.phase = .interrupted+        timer.deadline = nil+        timer.anchor = nil+        value.timer = timer+      }+    }+    return value+  }++  private func receive(_ message: CompanionMessage, reply: ((Data) -> Void)?) {+    do {+      switch message {+      case .requestSnapshot:+        let value = try snapshot()+        if let reply {+          reply(try JSONEncoder().encode(CompanionMessage.snapshot(value)))+        } else {+          try transport.publish(value)         }-        let runValues = try runs.map { item in-            var value = CompanionRun(id: item.id, definition: try service.definition(item), progress: try service.progress(item), timer: try item.timerCheckpointData.map { try JSONDecoder().decode(TimerCheckpoint.self, from: $0) }, status: SessionPhase(rawValue: item.statusRaw) ?? .needsReview, startedAt: item.startedAt, completedAt: item.completedAt, revision: item.revision, executionDeviceID: item.executionDeviceID, parentRunID: item.parentRoutineRunID, parentStepID: item.parentRoutineStepID, processedActionIDs: try JSONDecoder().decode([UUID].self, from: item.processedActionIDsData), isDeleted: item.isDeleted)-            value.profileID = item.profileID; value.ownershipVersion = item.ownershipVersion; value.profileLifecycleID = item.profileLifecycleID ?? ProfileIdentity.selfLifecycle-            if value.profileID != ProfileIdentity.me, value.profileLifecycleID != (try ProfileAccess.lifecycle(item, context: context)) {-                value.status = .paused; if var timer = value.timer, timer.phase == .running { timer.phase = .interrupted; timer.deadline = nil; timer.anchor = nil; value.timer = timer }-            }-            return value+      case .handoffCheckpoint(let actionID, let checkpoint):+        do { try receiveHandoff(actionID, checkpoint: checkpoint, reply: reply) } catch {+          let ack = CompanionAcknowledgement(+            actionID: actionID, accepted: false, message: error.localizedDescription,+            snapshot: try? snapshot())+          if let reply {+            reply(try JSONEncoder().encode(CompanionMessage.acknowledgement(ack)))+          } else {+            try transport.send(.acknowledgement(ack))+          }+          try? outbox?.acknowledge(ack)+          onHandoffWaiting(checkpoint.id, false)+          onError(error.localizedDescription)         }-        let revision = AppEnvironment.isTesting ? 1 : UserDefaults.standard.integer(forKey: "meddy.phone.snapshot-revision") + 1-        if !AppEnvironment.isTesting { UserDefaults.standard.set(revision, forKey: "meddy.phone.snapshot-revision") }-        var value = CompanionSnapshot(version: 2, phoneID: phoneID, revision: revision, generatedAt: Date(), medications: medicationValues, routines: definitions, runs: runValues,-                     deletedEventIDs: events.filter(\.isDeleted).map(\.id) + completions.filter(\.isDeleted).map(\.id),-                     appliedEventIDs: events.map(\.id) + completions.map(\.id),-                     treatments: try treatments.map { item in-                        var result = CompanionTreatment(id: item.id, name: item.name, instructions: item.instructions, lastDone: (item.completions ?? []).filter { !$0.isDeleted && $0.profileID == item.profileID }.map(\.timestamp).max(), active: item.isActive)-                        result.profileID = item.profileID; result.ownershipVersion = item.ownershipVersion; result.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context); return result-                     })-        value.profiles = try context.fetch(FetchDescriptor<CareProfile>()).compactMap { profile in profile.lifecycleID.map { CompanionProfile(id: profile.id, label: profile.label, archived: profile.archivedAt != nil, lifecycleID: $0) } }-        if value.profiles?.contains(where: { $0.id == ProfileIdentity.me }) != true { value.profiles?.insert(.init(id: ProfileIdentity.me, label: "Me", archived: false, lifecycleID: ProfileIdentity.selfLifecycle), at: 0) }-        var owners: [UUID: UUID] = [:]-        for event in events { owners[event.id] = event.profileID }; for event in completions { owners[event.id] = event.profileID }-        value.eventOwners = owners-        try CompanionOwnership.validate(value)-        return value-    }-    private func receive(_ message: CompanionMessage, reply: ((Data) -> Void)?) {+      case .action(let action):+        let acknowledgement: CompanionAcknowledgement         do {-            switch message {-            case .requestSnapshot:-                let value = try snapshot()-                if let reply { reply(try JSONEncoder().encode(CompanionMessage.snapshot(value))) }-                else { try transport.publish(value) }-            case .handoffCheckpoint(let actionID, let checkpoint):-                do { try receiveHandoff(actionID, checkpoint: checkpoint, reply: reply) }-                catch {-                    let ack = CompanionAcknowledgement(actionID: actionID, accepted: false, message: error.localizedDescription, snapshot: try? snapshot())-                    if let reply { reply(try JSONEncoder().encode(CompanionMessage.acknowledgement(ack))) } else { try transport.send(.acknowledgement(ack)) }-                    try? outbox?.acknowledge(ack)-                    onHandoffWaiting(checkpoint.id, false); onError(error.localizedDescription)-                }-            case .action(let action):-                let acknowledgement: CompanionAcknowledgement-                do {-                    try apply(action)-                    acknowledgement = .init(actionID: action.id, accepted: true, snapshot: try snapshot())-                } catch {-                    acknowledgement = .init(actionID: action.id, accepted: false, message: error.localizedDescription, snapshot: try? snapshot())-                }-                let response = CompanionMessage.acknowledgement(acknowledgement)-                if let reply { reply(try JSONEncoder().encode(response)) }-                else { try transport.send(response) }-            default: break-            }-        } catch { onError(error.localizedDescription) }-    }-    func apply(_ action: CompanionAction, save: (() throws -> Void)? = nil) throws {-        try CompanionOwnership.validate(action, snapshot: snapshot())-        context.autosaveEnabled = false-        do {-        let service = RoutineSessionService(context: context, deferSave: true)-        if let parent = action.cachedParentRun { _ = try service.importWatchRun(parent, deviceID: action.deviceID, timestamp: action.timestamp) }-        func run(_ id: UUID) throws -> RoutineRun {-            if let existing = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first {-                try ProfileAccess.action(action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID, target: existing, context: context)-                if existing.profileID != ProfileIdentity.me, existing.profileLifecycleID != action.profileLifecycleID { throw ProfileError.staleLifecycle }-                return existing-            }-            guard let cached = action.cachedRun, cached.id == id else { throw ExecutionError.unknownRun }-            return try service.importWatchRun(cached, deviceID: action.deviceID, timestamp: action.timestamp)+          try apply(action)+          acknowledgement = .init(actionID: action.id, accepted: true, snapshot: try snapshot())+        } catch {+          acknowledgement = .init(+            actionID: action.id, accepted: false, message: error.localizedDescription,+            snapshot: try? snapshot())+        }+        let response = CompanionMessage.acknowledgement(acknowledgement)+        if let reply {+          reply(try JSONEncoder().encode(response))+        } else {+          try transport.send(response)+        }+      default: break+      }+    } catch { onError(error.localizedDescription) }+  }+  func apply(_ action: CompanionAction, save: (() throws -> Void)? = nil) throws {+    try CompanionOwnership.validate(action, snapshot: snapshot())+    context.autosaveEnabled = false+    do {+      let service = RoutineSessionService(context: context, deferSave: true)+      if let parent = action.cachedParentRun {+        _ = try service.importWatchRun(+          parent, deviceID: action.deviceID, timestamp: action.timestamp)+      }+      func run(_ id: UUID) throws -> RoutineRun {+        if let existing = try context.fetch(+          FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })+        ).first {+          try ProfileAccess.action(+            action.profileID, version: action.ownershipVersion,+            lifecycle: action.profileLifecycleID, target: existing, context: context)+          if existing.profileID != ProfileIdentity.me,+            existing.profileLifecycleID != action.profileLifecycleID {+            throw ProfileError.staleLifecycle+          }+          return existing+        }+        guard let cached = action.cachedRun, cached.id == id else {+          throw ExecutionError.unknownRun+        }+        return try service.importWatchRun(+          cached, deviceID: action.deviceID, timestamp: action.timestamp)+      }+      switch action.operation {+      case .start(let cached):+        _ = try service.importWatchRun(+          cached, deviceID: action.deviceID, timestamp: action.timestamp)+      case .medication(let event, let runID, let stepID):+        guard event.source == .watch, event.eventID == action.id else {+          throw ExecutionError.ineligibleLog+        }+        if let runID, let stepID {+          _ = try service.recordMedication(+            event, in: run(runID), stepID: stepID, expectedRevision: action.expectedRevision)+        } else {+          _ = try MedicationService(context: context, deferSave: true).record(event)+        }+      case .treatment(let event, let runID, let stepID):+        guard event.source == .watch, event.eventID == action.id else {+          throw ExecutionError.ineligibleLog         }-        switch action.operation {-        case .start(let cached): _ = try service.importWatchRun(cached, deviceID: action.deviceID, timestamp: action.timestamp)-        case .medication(let event, let runID, let stepID):-            guard event.source == .watch, event.eventID == action.id else { throw ExecutionError.ineligibleLog }-            if let runID, let stepID { _ = try service.recordMedication(event, in: run(runID), stepID: stepID, expectedRevision: action.expectedRevision) }-            else { _ = try MedicationService(context: context, deferSave: true).record(event) }-        case .treatment(let event, let runID, let stepID):-            guard event.source == .watch, event.eventID == action.id else { throw ExecutionError.ineligibleLog }-            if let runID, let stepID { _ = try service.recordTreatment(event, in: run(runID), stepID: stepID, expectedRevision: action.expectedRevision) }-            else { _ = try TreatmentService(context: context, deferSave: true).record(event) }-        case .timer(let runID, _, let checkpoint):-            try service.importWatchTimer(run(runID), checkpoint: checkpoint, actionID: action.id, timestamp: action.timestamp, expectedRevision: action.expectedRevision, deviceID: action.deviceID)-        case .skip(let id, let stepID): try service.skip(run(id), stepID: stepID, actionID: action.id, reason: "Explicitly skipped on Watch")-        case .continueAfterSkip(let id, let stepID): try service.continueAfterSkip(run(id), stepID: stepID, actionID: action.id)-        case .pause(let id): try service.pause(run(id), actionID: action.id)-        case .resume(let id): try service.resume(run(id), actionID: action.id)-        case .end(let id): try service.end(run(id), actionID: action.id)-        case .handoff(let id, _, let device):-            let value = try run(id)-            try service.handoff(value, toDeviceID: device, actionID: action.id, expectedRevision: action.expectedRevision)+        if let runID, let stepID {+          _ = try service.recordTreatment(+            event, in: run(runID), stepID: stepID, expectedRevision: action.expectedRevision)+        } else {+          _ = try TreatmentService(context: context, deferSave: true).record(event)         }-        try (save ?? { try self.context.save() })()-        MutationEffects.saved(context)-        } catch { context.rollback(); throw error }+      case .timer(let runID, _, let checkpoint):+        try service.importWatchTimer(+          run(runID), checkpoint: checkpoint, actionID: action.id, timestamp: action.timestamp,+          expectedRevision: action.expectedRevision, deviceID: action.deviceID)+      case .skip(let id, let stepID):+        try service.skip(+          run(id), stepID: stepID, actionID: action.id, reason: "Explicitly skipped on Watch")+      case .continueAfterSkip(let id, let stepID):+        try service.continueAfterSkip(run(id), stepID: stepID, actionID: action.id)+      case .pause(let id): try service.pause(run(id), actionID: action.id)+      case .resume(let id): try service.resume(run(id), actionID: action.id)+      case .end(let id): try service.end(run(id), actionID: action.id)+      case .handoff(let id, _, let device):+        let value = try run(id)+        try service.handoff(+          value, toDeviceID: device, actionID: action.id, expectedRevision: action.expectedRevision)+      }+      try (save ?? { try self.context.save() })()+      MutationEffects.saved(context)+    } catch {+      context.rollback()+      throw error     }+  } }
Meddy/Meddy/Services/PhoneRoundAlertService.swift Modified
diff --git a/Meddy/Meddy/Services/PhoneRoundAlertService.swift b/Meddy/Meddy/Services/PhoneRoundAlertService.swiftindex a370761..2e3a3d1 100644--- a/Meddy/Meddy/Services/PhoneRoundAlertService.swift+++ b/Meddy/Meddy/Services/PhoneRoundAlertService.swift@@ -7,125 +7,187 @@ protocol RoundDeadlineCancellation { func cancel() }  @MainActor protocol RoundDeadlineScheduling {-    func schedule(at deadline: Date, action: @escaping @MainActor () -> Void) -> any RoundDeadlineCancellation+  func schedule(at deadline: Date, action: @escaping @MainActor () -> Void)+    -> any RoundDeadlineCancellation }  @MainActor private final class SystemRoundDeadline: RoundDeadlineCancellation {-    let timer: Timer-    init(timer: Timer) { self.timer = timer }-    func cancel() { timer.invalidate() }+  let timer: Timer+  init(timer: Timer) { self.timer = timer }+  func cancel() { timer.invalidate() } }  @MainActor private struct SystemRoundDeadlineScheduler: RoundDeadlineScheduling {-    func schedule(at deadline: Date, action: @escaping @MainActor () -> Void) -> any RoundDeadlineCancellation {-        let timer = Timer(fire: deadline, interval: 0, repeats: false) { _ in Task { @MainActor in action() } }-        RunLoop.main.add(timer, forMode: .common)-        return SystemRoundDeadline(timer: timer)+  func schedule(at deadline: Date, action: @escaping @MainActor () -> Void)+    -> any RoundDeadlineCancellation {+    let timer = Timer(fire: deadline, interval: 0, repeats: false) { _ in+      Task { @MainActor in action() }     }+    RunLoop.main.add(timer, forMode: .common)+    return SystemRoundDeadline(timer: timer)+  } }  /// Foreground round completion is independent of any timer screen's redraw/lifetime. /// Background/locked delivery belongs to the scheduled system notification, not this timer. @MainActor final class PhoneRoundAlertService {-    private struct Pending {-        let token: UUID-        let round: Int-        let deadline: Date-        let cancellation: any RoundDeadlineCancellation-    }-    private let context: ModelContext-    private let scheduler: any RoundDeadlineScheduling-    private let clock: () -> ClockSample-    private let feedback: () -> Void-    private let keepAwake: (Bool) -> Void-    private let enabled: Bool-    private var pending: [UUID: Pending] = [:]-    private var signalled: Set<String> = []-    private var active = false-    var deviceID: String?-    var onError: (String) -> Void = { _ in }+  private struct Pending {+    let token: UUID+    let round: Int+    let deadline: Date+    let cancellation: any RoundDeadlineCancellation+  }+  private let context: ModelContext+  private let scheduler: any RoundDeadlineScheduling+  private let clock: () -> ClockSample+  private let feedback: () -> Void+  private let keepAwake: (Bool) -> Void+  private let enabled: Bool+  private var pending: [UUID: Pending] = [:]+  private var signalled: Set<String> = []+  private var active = false+  var deviceID: String?+  var onError: (String) -> Void = { _ in } -    init(context: ModelContext, scheduler: (any RoundDeadlineScheduling)? = nil,-         clock: @escaping () -> ClockSample = ExecutionClock.sample, feedback: (() -> Void)? = nil,-         keepAwake: ((Bool) -> Void)? = nil, enabled: Bool = true) {-        self.context = context; self.clock = clock-        self.scheduler = scheduler ?? SystemRoundDeadlineScheduler()-        self.feedback = feedback ?? {-            guard !AppEnvironment.isTesting else { return }-            let generator = UINotificationFeedbackGenerator(); generator.prepare(); generator.notificationOccurred(.success)-        }-        self.keepAwake = keepAwake ?? { if !AppEnvironment.isTesting { UIApplication.shared.isIdleTimerDisabled = $0 } }-        self.enabled = enabled-        if self.enabled { MutationEffects.observe(context) { [weak self] in self?.refresh() } }-    }+  init(+    context: ModelContext, scheduler: (any RoundDeadlineScheduling)? = nil,+    clock: @escaping () -> ClockSample = ExecutionClock.sample, feedback: (() -> Void)? = nil,+    keepAwake: ((Bool) -> Void)? = nil, enabled: Bool = true+  ) {+    self.context = context+    self.clock = clock+    self.scheduler = scheduler ?? SystemRoundDeadlineScheduler()+    self.feedback =+      feedback ?? {+        guard !AppEnvironment.isTesting else { return }+        let generator = UINotificationFeedbackGenerator()+        generator.prepare()+        generator.notificationOccurred(.success)+      }+    self.keepAwake =+      keepAwake ?? {+        if !AppEnvironment.isTesting { UIApplication.shared.isIdleTimerDisabled = $0 }+      }+    self.enabled = enabled+    if self.enabled { MutationEffects.observe(context) { [weak self] in self?.refresh() } }+  } -    func setActive(_ value: Bool) {-        guard enabled, value != active else { return }-        active = value-        if !value { cancelAll(); return }-        // No catch-up buzz on returning from background: the OS notification was responsible-        // for that deadline. Reconcile the saved boundary without duplicating that alert.-        do {-            for run in try context.fetch(FetchDescriptor<RoutineRun>()) where owns(run) {-                let service = RoutineSessionService(context: context)-                guard let timer = try? service.timer(run), timer.phase == .running else { continue }-                if timer.deadline.map({ $0 <= clock().wall }) == true || timer.anchor?.continuityID != clock().continuityID {-                    try service.changeTimer(run, actionID: boundaryID(run.id, timer), clock: clock(), operation: .advance)-                    if try service.timer(run).completedRounds > timer.roundIndex { signalled.insert(key(run.id, timer.roundIndex)) }-                }-            }-            refresh()-        } catch { onError(error.localizedDescription) }+  func setActive(_ value: Bool) {+    guard enabled, value != active else { return }+    active = value+    if !value {+      cancelAll()+      return     }+    // No catch-up buzz on returning from background: the OS notification was responsible+    // for that deadline. Reconcile the saved boundary without duplicating that alert.+    do {+      for run in try context.fetch(FetchDescriptor<RoutineRun>()) where owns(run) {+        let service = RoutineSessionService(context: context)+        guard let timer = try? service.timer(run), timer.phase == .running else { continue }+        if timer.deadline.map({ $0 <= clock().wall }) == true+          || timer.anchor?.continuityID != clock().continuityID {+          try service.changeTimer(+            run, actionID: boundaryID(run.id, timer), clock: clock(), operation: .advance)+          if try service.timer(run).completedRounds > timer.roundIndex {+            signalled.insert(key(run.id, timer.roundIndex))+          }+        }+      }+      refresh()+    } catch { onError(error.localizedDescription) }+  } -    func refresh() {-        guard enabled, active else { return }-        do {-            let runs = try context.fetch(FetchDescriptor<RoutineRun>())-            let service = RoutineSessionService(context: context)-            for (id, saved) in pending {-                guard let run = runs.first(where: { $0.id == id }), owns(run), let timer = try? service.timer(run) else {-                    saved.cancellation.cancel(); pending.removeValue(forKey: id); continue-                }-                if timer.completedRounds > saved.round {-                    let identity = key(id, saved.round)-                    if signalled.insert(identity).inserted { feedback() }-                }-                if timer.phase != .running || timer.roundIndex != saved.round || timer.deadline != saved.deadline {-                    saved.cancellation.cancel(); pending.removeValue(forKey: id)-                }-            }-            for run in runs where owns(run) {-                guard let timer = try? service.timer(run), timer.phase == .running, let deadline = timer.deadline else { continue }-                if let existing = pending[run.id], existing.round == timer.roundIndex, existing.deadline == deadline { continue }-                let token = UUID(); let id = run.id-                let cancellation = scheduler.schedule(at: deadline) { [weak self] in self?.complete(id, token: token) }-                pending[id] = Pending(token: token, round: timer.roundIndex, deadline: deadline, cancellation: cancellation)-            }-            keepAwake(!pending.isEmpty)-        } catch { onError(error.localizedDescription) }-    }+  func refresh() {+    guard enabled, active else { return }+    do {+      let runs = try context.fetch(FetchDescriptor<RoutineRun>())+      let service = RoutineSessionService(context: context)+      for (id, saved) in pending {+        guard let run = runs.first(where: { $0.id == id }), owns(run),+          let timer = try? service.timer(run)+        else {+          saved.cancellation.cancel()+          pending.removeValue(forKey: id)+          continue+        }+        if timer.completedRounds > saved.round {+          let identity = key(id, saved.round)+          if signalled.insert(identity).inserted { feedback() }+        }+        if timer.phase != .running || timer.roundIndex != saved.round+          || timer.deadline != saved.deadline {+          saved.cancellation.cancel()+          pending.removeValue(forKey: id)+        }+      }+      for run in runs where owns(run) {+        guard let timer = try? service.timer(run), timer.phase == .running,+          let deadline = timer.deadline+        else { continue }+        if let existing = pending[run.id], existing.round == timer.roundIndex,+          existing.deadline == deadline {+          continue+        }+        let token = UUID()+        let id = run.id+        let cancellation = scheduler.schedule(at: deadline) { [weak self] in+          self?.complete(id, token: token)+        }+        pending[id] = Pending(+          token: token, round: timer.roundIndex, deadline: deadline, cancellation: cancellation)+      }+      keepAwake(!pending.isEmpty)+    } catch { onError(error.localizedDescription) }+  } -    private func complete(_ id: UUID, token: UUID) {-        guard active, let expected = pending[id], expected.token == token else { return }-        do {-            guard let run = try context.fetch(FetchDescriptor<RoutineRun>()).first(where: { $0.id == id }), owns(run) else { refresh(); return }-            let service = RoutineSessionService(context: context); let timer = try service.timer(run)-            guard timer.phase == .running, timer.roundIndex == expected.round, timer.deadline == expected.deadline else { refresh(); return }-            // Saving invokes refresh, which emits only after the durable completed-round count advances.-            let changed = try service.changeTimer(run, actionID: boundaryID(id, timer), clock: clock(), operation: .advance)-            if !changed { expected.cancellation.cancel(); pending.removeValue(forKey: id); refresh() }-        } catch { onError(error.localizedDescription) }-    }-    private func owns(_ run: RoutineRun) -> Bool {-        (try? ProfileAccess.owner(run, context: context)) != nil && (run.profileID == ProfileIdentity.me || run.profileLifecycleID == (try? ProfileAccess.lifecycle(run, context: context))) && !run.isDeleted && run.statusRaw != "needsReview" && (run.executionDeviceID == nil || run.executionDeviceID == deviceID)-    }-    private func key(_ id: UUID, _ round: Int) -> String { "\(id)|\(round)" }-    private func boundaryID(_ id: UUID, _ timer: TimerCheckpoint) -> UUID {-        ScheduleCalendar.identity("phone-round-boundary|\(key(id, timer.roundIndex))|\(timer.deadline?.timeIntervalSince1970 ?? 0)|\(timer.anchor?.continuityID ?? "")|\(timer.anchor?.monotonic ?? 0)")-    }-    private func cancelAll() { pending.values.forEach { $0.cancellation.cancel() }; pending.removeAll(); keepAwake(false) }+  private func complete(_ id: UUID, token: UUID) {+    guard active, let expected = pending[id], expected.token == token else { return }+    do {+      guard+        let run = try context.fetch(FetchDescriptor<RoutineRun>()).first(where: { $0.id == id }),+        owns(run)+      else {+        refresh()+        return+      }+      let service = RoutineSessionService(context: context)+      let timer = try service.timer(run)+      guard timer.phase == .running, timer.roundIndex == expected.round,+        timer.deadline == expected.deadline+      else {+        refresh()+        return+      }+      // Saving invokes refresh, which emits only after the durable completed-round count advances.+      let changed = try service.changeTimer(+        run, actionID: boundaryID(id, timer), clock: clock(), operation: .advance)+      if !changed {+        expected.cancellation.cancel()+        pending.removeValue(forKey: id)+        refresh()+      }+    } catch { onError(error.localizedDescription) }+  }+  private func owns(_ run: RoutineRun) -> Bool {+    (try? ProfileAccess.owner(run, context: context)) != nil+      && (run.profileID == ProfileIdentity.me+        || run.profileLifecycleID == (try? ProfileAccess.lifecycle(run, context: context)))+      && !run.isDeleted && run.statusRaw != "needsReview"+      && (run.executionDeviceID == nil || run.executionDeviceID == deviceID)+  }+  private func key(_ id: UUID, _ round: Int) -> String { "\(id)|\(round)" }+  private func boundaryID(_ id: UUID, _ timer: TimerCheckpoint) -> UUID {+    ScheduleCalendar.identity(+      "phone-round-boundary|\(key(id, timer.roundIndex))|\(timer.deadline?.timeIntervalSince1970 ?? 0)|\(timer.anchor?.continuityID ?? "")|\(timer.anchor?.monotonic ?? 0)"+    )+  }+  private func cancelAll() {+    pending.values.forEach { $0.cancellation.cancel() }+    pending.removeAll()+    keepAwake(false)+  } }
Meddy/Meddy/Services/ProfileAccess.swift Modified
diff --git a/Meddy/Meddy/Services/ProfileAccess.swift b/Meddy/Meddy/Services/ProfileAccess.swiftindex beca117..d1c4465 100644--- a/Meddy/Meddy/Services/ProfileAccess.swift+++ b/Meddy/Meddy/Services/ProfileAccess.swift@@ -2,77 +2,114 @@ import Foundation import SwiftData  @MainActor enum ProfileAccess {-    static func profile(_ id: UUID, context: ModelContext, allowArchived: Bool = false) throws -> CareProfile? {-        let rows = try context.fetch(FetchDescriptor<CareProfile>()).filter { $0.id == id }-        if id == ProfileIdentity.me && rows.isEmpty { return nil }-        guard let first = rows.first, first.lifecycleID != nil else { throw ProfileError.unknownOwner }-        guard rows.allSatisfy({ $0.lifecycleID == first.lifecycleID && $0.archivedAt == first.archivedAt }) else { throw ProfileError.conflictingOwnership }-        guard allowArchived || first.archivedAt == nil else { throw ProfileError.archived }-        return first+  static func profile(_ id: UUID, context: ModelContext, allowArchived: Bool = false) throws+    -> CareProfile? {+    let rows = try context.fetch(FetchDescriptor<CareProfile>()).filter { $0.id == id }+    if id == ProfileIdentity.me && rows.isEmpty { return nil }+    guard let first = rows.first, first.lifecycleID != nil else { throw ProfileError.unknownOwner }+    guard+      rows.allSatisfy({ $0.lifecycleID == first.lifecycleID && $0.archivedAt == first.archivedAt })+    else { throw ProfileError.conflictingOwnership }+    guard allowArchived || first.archivedAt == nil else { throw ProfileError.archived }+    return first+  }+  static func owner(_ value: any ProfileOwned, context: ModelContext, allowArchived: Bool = false)+    throws -> UUID {+    guard value.ownershipVersion == ProfileIdentity.ownershipVersion, let id = value.profileID+    else { throw ProfileError.unknownOwner }+    _ = try profile(id, context: context, allowArchived: allowArchived)+    try validateLinks(value, owner: id, context: context)+    return id+  }+  private static func validateLinks(_ value: any ProfileOwned, owner: UUID, context: ModelContext)+    throws {+    let rows = try ProfileMigration.rows(context)+    let matching = rows.filter { $0.id == value.id }+    guard matching.count <= 1 else { throw ProfileError.conflictingOwnership }+    func link(_ id: UUID) throws {+      let matches = rows.filter { $0.id == id }+      guard matches.count == 1, let row = matches.first,+        row.profileID == owner, row.ownershipVersion == ProfileIdentity.ownershipVersion+      else { throw ProfileError.conflictingOwnership }     }-    static func owner(_ value: any ProfileOwned, context: ModelContext, allowArchived: Bool = false) throws -> UUID {-        guard value.ownershipVersion == ProfileIdentity.ownershipVersion, let id = value.profileID else { throw ProfileError.unknownOwner }-        _ = try profile(id, context: context, allowArchived: allowArchived)-        try validateLinks(value, owner: id, context: context)-        return id+    switch value {+    case let x as Purpose:+      for row in (x.medications ?? []).map({ $0 as any ProfileOwned })+        + (x.treatments ?? []).map({ $0 as any ProfileOwned })+        + (x.routines ?? []).map({ $0 as any ProfileOwned }) { try link(row.id) }+    case let x as Medication:+      if let purpose = x.purpose { try link(purpose.id) }+      if let id = x.managedByRoutineID { try link(id) }+    case let x as Administration:+      try link(x.medicationID)+      if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }+    case let x as Treatment: if let purpose = x.purpose { try link(purpose.id) }+    case let x as TreatmentCompletion:+      try link(x.treatmentID)+      if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }+    case let x as Routine:+      if let purpose = x.purpose { try link(purpose.id) }+      for step in x.steps ?? [] {+        try link(step.id)+        try link(step.targetID)+      }+    case let x as RoutineStep:+      try link(x.routineID)+      try link(x.targetID)+    case let x as RoutineRun:+      try link(x.routineID)+      if let id = x.parentRoutineRunID { try link(id) }+    default: break     }-    private static func validateLinks(_ value: any ProfileOwned, owner: UUID, context: ModelContext) throws {-        let rows = try ProfileMigration.rows(context)-        let matching = rows.filter { $0.id == value.id }-        guard matching.count <= 1 else { throw ProfileError.conflictingOwnership }-        func link(_ id: UUID) throws {-            let matches = rows.filter { $0.id == id }-            guard matches.count == 1, let row = matches.first,-                  row.profileID == owner, row.ownershipVersion == ProfileIdentity.ownershipVersion else { throw ProfileError.conflictingOwnership }-        }-        switch value {-        case let x as Purpose:-            for row in (x.medications ?? []).map({ $0 as any ProfileOwned }) + (x.treatments ?? []).map({ $0 as any ProfileOwned }) + (x.routines ?? []).map({ $0 as any ProfileOwned }) { try link(row.id) }-        case let x as Medication:-            if let purpose = x.purpose { try link(purpose.id) }; if let id = x.managedByRoutineID { try link(id) }-        case let x as Administration:-            try link(x.medicationID); if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }-        case let x as Treatment: if let purpose = x.purpose { try link(purpose.id) }-        case let x as TreatmentCompletion:-            try link(x.treatmentID); if let id = x.routineRunID, rows.contains(where: { $0.id == id }) { try link(id) }-        case let x as Routine:-            if let purpose = x.purpose { try link(purpose.id) }; for step in x.steps ?? [] { try link(step.id); try link(step.targetID) }-        case let x as RoutineStep: try link(x.routineID); try link(x.targetID)-        case let x as RoutineRun: try link(x.routineID); if let id = x.parentRoutineRunID { try link(id) }-        default: break-        }+  }+  static func canonical<T: ProfileOwned>(_ type: T.Type, id: UUID, context: ModelContext) throws+    -> T {+    let rows = try context.fetch(FetchDescriptor<T>()).filter { $0.id == id }+    guard rows.count == 1, let row = rows.first else { throw ProfileError.conflictingOwnership }+    _ = try owner(row, context: context)+    return row+  }+  static func lifecycle(_ row: any ProfileOwned, context: ModelContext) throws -> UUID {+    let id = try owner(row, context: context)+    return try profile(id, context: context)?.lifecycleID ?? ProfileIdentity.selfLifecycle+  }+  static func same(_ left: any ProfileOwned, _ right: any ProfileOwned, context: ModelContext)+    throws {+    guard try owner(left, context: context) == owner(right, context: context) else {+      throw ProfileError.conflictingOwnership     }-    static func canonical<T: ProfileOwned>(_ type: T.Type, id: UUID, context: ModelContext) throws -> T {-        let rows = try context.fetch(FetchDescriptor<T>()).filter { $0.id == id }-        guard rows.count == 1, let row = rows.first else { throw ProfileError.conflictingOwnership }-        _ = try owner(row, context: context)-        return row+  }+  static func action(+    _ profileID: UUID?, version: Int? = nil, lifecycle: UUID? = nil, target: any ProfileOwned,+    context: ModelContext+  ) throws {+    let owner = try owner(target, context: context)+    guard owner == (profileID ?? ProfileIdentity.me) else {+      throw ProfileError.conflictingOwnership     }-    static func lifecycle(_ row: any ProfileOwned, context: ModelContext) throws -> UUID {-        let id = try owner(row, context: context)-        return try profile(id, context: context)?.lifecycleID ?? ProfileIdentity.selfLifecycle-    }-    static func same(_ left: any ProfileOwned, _ right: any ProfileOwned, context: ModelContext) throws {-        guard try owner(left, context: context) == owner(right, context: context) else { throw ProfileError.conflictingOwnership }-    }-    static func action(_ profileID: UUID?, version: Int? = nil, lifecycle: UUID? = nil, target: any ProfileOwned, context: ModelContext) throws {-        let owner = try owner(target, context: context)-        guard owner == (profileID ?? ProfileIdentity.me) else { throw ProfileError.conflictingOwnership }-        if owner != ProfileIdentity.me {-            guard version == ProfileIdentity.ownershipVersion else { throw ProfileError.unknownOwner }-            guard lifecycle == (try profile(owner, context: context)?.lifecycleID) else { throw ProfileError.staleLifecycle }-        } else if let version, version != ProfileIdentity.ownershipVersion { throw ProfileError.unknownOwner }-    }-    static func stamp<T: ProfilePayload>(_ value: T, target: any ProfileOwned, context: ModelContext) throws -> T {-        var result = value; result.profileID = try owner(target, context: context)-        result.ownershipVersion = ProfileIdentity.ownershipVersion; result.profileLifecycleID = try lifecycle(target, context: context)-        return result-    }-    static func visible(_ value: any ProfileOwned, for ownerID: UUID, context: ModelContext) -> Bool {-        (try? owner(value, context: context)) == ownerID-    }-    static func assign(_ row: any ProfileOwned, to id: UUID, context: ModelContext) throws {-        _ = try profile(id, context: context)-        row.profileID = id; row.ownershipVersion = ProfileIdentity.ownershipVersion+    if owner != ProfileIdentity.me {+      guard version == ProfileIdentity.ownershipVersion else { throw ProfileError.unknownOwner }+      guard lifecycle == (try profile(owner, context: context)?.lifecycleID) else {+        throw ProfileError.staleLifecycle+      }+    } else if let version, version != ProfileIdentity.ownershipVersion {+      throw ProfileError.unknownOwner     }+  }+  static func stamp<T: ProfilePayload>(_ value: T, target: any ProfileOwned, context: ModelContext)+    throws -> T {+    var result = value+    result.profileID = try owner(target, context: context)+    result.ownershipVersion = ProfileIdentity.ownershipVersion+    result.profileLifecycleID = try lifecycle(target, context: context)+    return result+  }+  static func visible(_ value: any ProfileOwned, for ownerID: UUID, context: ModelContext) -> Bool {+    (try? owner(value, context: context)) == ownerID+  }+  static func assign(_ row: any ProfileOwned, to id: UUID, context: ModelContext) throws {+    _ = try profile(id, context: context)+    row.profileID = id+    row.ownershipVersion = ProfileIdentity.ownershipVersion+  } }
Meddy/Meddy/Services/ProfileMigration.swift Modified
diff --git a/Meddy/Meddy/Services/ProfileMigration.swift b/Meddy/Meddy/Services/ProfileMigration.swiftindex 473e8d7..0155513 100644--- a/Meddy/Meddy/Services/ProfileMigration.swift+++ b/Meddy/Meddy/Services/ProfileMigration.swift@@ -2,34 +2,44 @@ import Foundation import SwiftData  @MainActor enum ProfileMigration {-    static func rows(_ context: ModelContext) throws -> [any ProfileOwned] {-        var rows: [any ProfileOwned] = []-        rows += try context.fetch(FetchDescriptor<Purpose>())-        rows += try context.fetch(FetchDescriptor<Medication>())-        rows += try context.fetch(FetchDescriptor<Administration>())-        rows += try context.fetch(FetchDescriptor<Treatment>())-        rows += try context.fetch(FetchDescriptor<TreatmentCompletion>())-        rows += try context.fetch(FetchDescriptor<Routine>())-        rows += try context.fetch(FetchDescriptor<RoutineStep>())-        rows += try context.fetch(FetchDescriptor<RoutineRun>())-        return rows-    }-    // Personal-app transition: old ownerless rows become Me only before dependants exist.-    // Unknown/malformed rows after dependant creation remain unavailable, never guessed.-    static func bootstrap(_ context: ModelContext, save: (() throws -> Void)? = nil) throws {-        context.autosaveEnabled = false-        let profiles = try context.fetch(FetchDescriptor<CareProfile>())-        let all = try rows(context)-        let duplicateIDs = Set(Dictionary(grouping: all, by: { $0.id }).filter { $0.value.count > 1 }.keys)-        let hasDependants = profiles.contains { $0.id != ProfileIdentity.me } || all.contains { $0.profileID != nil && $0.profileID != ProfileIdentity.me }-        do {-            if !profiles.contains(where: { $0.id == ProfileIdentity.me }) { context.insert(CareProfile(id: ProfileIdentity.me)) }-            if !hasDependants {-                for row in all where row.profileID == nil && row.ownershipVersion == nil && !duplicateIDs.contains(row.id) {-                    row.profileID = ProfileIdentity.me; row.ownershipVersion = ProfileIdentity.ownershipVersion-                }-            }-            if context.hasChanges { try (save ?? { try context.save() })() }-        } catch { context.rollback(); throw error }+  static func rows(_ context: ModelContext) throws -> [any ProfileOwned] {+    var rows: [any ProfileOwned] = []+    rows += try context.fetch(FetchDescriptor<Purpose>())+    rows += try context.fetch(FetchDescriptor<Medication>())+    rows += try context.fetch(FetchDescriptor<Administration>())+    rows += try context.fetch(FetchDescriptor<Treatment>())+    rows += try context.fetch(FetchDescriptor<TreatmentCompletion>())+    rows += try context.fetch(FetchDescriptor<Routine>())+    rows += try context.fetch(FetchDescriptor<RoutineStep>())+    rows += try context.fetch(FetchDescriptor<RoutineRun>())+    return rows+  }+  // Personal-app transition: old ownerless rows become Me only before dependants exist.+  // Unknown/malformed rows after dependant creation remain unavailable, never guessed.+  static func bootstrap(_ context: ModelContext, save: (() throws -> Void)? = nil) throws {+    context.autosaveEnabled = false+    let profiles = try context.fetch(FetchDescriptor<CareProfile>())+    let all = try rows(context)+    let duplicateIDs = Set(+      Dictionary(grouping: all, by: { $0.id }).filter { $0.value.count > 1 }.keys)+    let hasDependants =+      profiles.contains { $0.id != ProfileIdentity.me }+      || all.contains { $0.profileID != nil && $0.profileID != ProfileIdentity.me }+    do {+      if !profiles.contains(where: { $0.id == ProfileIdentity.me }) {+        context.insert(CareProfile(id: ProfileIdentity.me))+      }+      if !hasDependants {+        for row in all+        where row.profileID == nil && row.ownershipVersion == nil && !duplicateIDs.contains(row.id) {+          row.profileID = ProfileIdentity.me+          row.ownershipVersion = ProfileIdentity.ownershipVersion+        }+      }+      if context.hasChanges { try (save ?? { try context.save() })() }+    } catch {+      context.rollback()+      throw error     }+  } }
Meddy/Meddy/Services/ProfileService.swift Modified
diff --git a/Meddy/Meddy/Services/ProfileService.swift b/Meddy/Meddy/Services/ProfileService.swiftindex eee6ebb..cdd9171 100644--- a/Meddy/Meddy/Services/ProfileService.swift+++ b/Meddy/Meddy/Services/ProfileService.swift@@ -2,44 +2,59 @@ import Foundation import SwiftData  @MainActor final class ProfileService {-    private let context: ModelContext-    init(context: ModelContext) { self.context = context }-    func create(displayName: String? = nil) throws -> CareProfile {-        try ProfileMigration.bootstrap(context)-        return try EditorTransaction.save(context: context) {-            let value = CareProfile(displayName: normalized(displayName))-            context.insert(value); return value-        }-    }-    func rename(_ profile: CareProfile, displayName: String?) throws {-        _ = try ProfileAccess.profile(profile.id, context: context, allowArchived: true)-        try EditorTransaction.save(context: context) { profile.displayName = normalized(displayName); profile.updatedAt = Date() }+  private let context: ModelContext+  init(context: ModelContext) { self.context = context }+  func create(displayName: String? = nil) throws -> CareProfile {+    try ProfileMigration.bootstrap(context)+    return try EditorTransaction.save(context: context) {+      let value = CareProfile(displayName: normalized(displayName))+      context.insert(value)+      return value     }-    func setArchived(_ profile: CareProfile, _ archived: Bool, save: (() throws -> Void)? = nil) throws {-        guard profile.id != ProfileIdentity.me else { throw ProfileError.conflictingOwnership }-        _ = try ProfileAccess.profile(profile.id, context: context, allowArchived: true)-        guard (profile.archivedAt != nil) != archived else { return }-        context.autosaveEnabled = false-        do {-            if archived {-                let sessions = RoutineSessionService(context: context, deferSave: true)-                for run in try context.fetch(FetchDescriptor<RoutineRun>()) where run.profileID == profile.id && !run.isDeleted {-                    if let timer = try? sessions.timer(run), timer.phase == .running {-                        _ = try sessions.changeTimer(run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .pause)-                    } else if run.statusRaw == "active", (try? sessions.definition(run).kind) == .ordered {-                        try sessions.pause(run, actionID: UUID())-                    }-                }-            }-            let lifecycle = UUID(); let now = Date()-            for row in try context.fetch(FetchDescriptor<CareProfile>()) where row.id == profile.id {-                row.archivedAt = archived ? now : nil; row.lifecycleID = lifecycle; row.updatedAt = now-            }-            try (save ?? { try self.context.save() })()-            MutationEffects.saved(context)-        } catch { context.rollback(); throw error }+  }+  func rename(_ profile: CareProfile, displayName: String?) throws {+    _ = try ProfileAccess.profile(profile.id, context: context, allowArchived: true)+    try EditorTransaction.save(context: context) {+      profile.displayName = normalized(displayName)+      profile.updatedAt = Date()     }-    private func normalized(_ label: String?) -> String? {-        guard let label else { return nil }; let text = label.trimmingCharacters(in: .whitespacesAndNewlines); return text.isEmpty ? nil : text+  }+  func setArchived(_ profile: CareProfile, _ archived: Bool, save: (() throws -> Void)? = nil)+    throws {+    guard profile.id != ProfileIdentity.me else { throw ProfileError.conflictingOwnership }+    _ = try ProfileAccess.profile(profile.id, context: context, allowArchived: true)+    guard (profile.archivedAt != nil) != archived else { return }+    context.autosaveEnabled = false+    do {+      if archived {+        let sessions = RoutineSessionService(context: context, deferSave: true)+        for run in try context.fetch(FetchDescriptor<RoutineRun>())+        where run.profileID == profile.id && !run.isDeleted {+          if let timer = try? sessions.timer(run), timer.phase == .running {+            _ = try sessions.changeTimer(+              run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .pause)+          } else if run.statusRaw == "active", (try? sessions.definition(run).kind) == .ordered {+            try sessions.pause(run, actionID: UUID())+          }+        }+      }+      let lifecycle = UUID()+      let now = Date()+      for row in try context.fetch(FetchDescriptor<CareProfile>()) where row.id == profile.id {+        row.archivedAt = archived ? now : nil+        row.lifecycleID = lifecycle+        row.updatedAt = now+      }+      try (save ?? { try self.context.save() })()+      MutationEffects.saved(context)+    } catch {+      context.rollback()+      throw error     }+  }+  private func normalized(_ label: String?) -> String? {+    guard let label else { return nil }+    let text = label.trimmingCharacters(in: .whitespacesAndNewlines)+    return text.isEmpty ? nil : text+  } }
Meddy/Meddy/Services/ReminderService.swift Modified
diff --git a/Meddy/Meddy/Services/ReminderService.swift b/Meddy/Meddy/Services/ReminderService.swiftindex 8ec501f..7ffbbd9 100644--- a/Meddy/Meddy/Services/ReminderService.swift+++ b/Meddy/Meddy/Services/ReminderService.swift@@ -4,350 +4,567 @@ import UserNotifications  @MainActor enum MutationEffects {-    private static var observers: [ObjectIdentifier: [() -> Void]] = [:]-    static func observe(_ context: ModelContext, saved: @escaping () -> Void) { observers[ObjectIdentifier(context), default: []].append(saved) }-    static func saved(_ context: ModelContext) { observers[ObjectIdentifier(context)]?.forEach { $0() } }-    static func remove(_ context: ModelContext) { observers.removeValue(forKey: ObjectIdentifier(context)) }+  private static var observers: [ObjectIdentifier: [() -> Void]] = [:]+  static func observe(_ context: ModelContext, saved: @escaping () -> Void) {+    observers[ObjectIdentifier(context), default: []].append(saved)+  }+  static func saved(_ context: ModelContext) {+    observers[ObjectIdentifier(context)]?.forEach { $0() }+  }+  static func remove(_ context: ModelContext) {+    observers.removeValue(forKey: ObjectIdentifier(context))+  } }  @MainActor protocol ReminderNotificationClient {-    func authorization() async -> UNAuthorizationStatus-    func pending() async -> [UNNotificationRequest]-    func delivered() async -> [UNNotification]-    func removePending(_ ids: [String])-    func removeDelivered(_ ids: [String])-    func add(_ request: UNNotificationRequest) async throws+  func authorization() async -> UNAuthorizationStatus+  func pending() async -> [UNNotificationRequest]+  func delivered() async -> [UNNotification]+  func removePending(_ ids: [String])+  func removeDelivered(_ ids: [String])+  func add(_ request: UNNotificationRequest) async throws }  @MainActor private struct SystemReminderNotifications: ReminderNotificationClient {-    let center = UNUserNotificationCenter.current()-    func authorization() async -> UNAuthorizationStatus { await center.notificationSettings().authorizationStatus }-    func pending() async -> [UNNotificationRequest] { await center.pendingNotificationRequests() }-    func delivered() async -> [UNNotification] { await center.deliveredNotifications() }-    func removePending(_ ids: [String]) { center.removePendingNotificationRequests(withIdentifiers: ids) }-    func removeDelivered(_ ids: [String]) { center.removeDeliveredNotifications(withIdentifiers: ids) }-    func add(_ request: UNNotificationRequest) async throws { try await center.add(request) }+  let center = UNUserNotificationCenter.current()+  func authorization() async -> UNAuthorizationStatus {+    await center.notificationSettings().authorizationStatus+  }+  func pending() async -> [UNNotificationRequest] { await center.pendingNotificationRequests() }+  func delivered() async -> [UNNotification] { await center.deliveredNotifications() }+  func removePending(_ ids: [String]) {+    center.removePendingNotificationRequests(withIdentifiers: ids)+  }+  func removeDelivered(_ ids: [String]) {+    center.removeDeliveredNotifications(withIdentifiers: ids)+  }+  func add(_ request: UNNotificationRequest) async throws { try await center.add(request) } }  @MainActor final class ReminderService: NSObject, UNUserNotificationCenterDelegate {-    private let context: ModelContext-    private let center = UNUserNotificationCenter.current()-    private let notifications: any ReminderNotificationClient-    private let injectedNotifications: Bool-    private var reconcileTask: Task<Void, Never>?-    private var reconcileRevision = 0-    private let followupReceipts: FollowupReceipts-    private let wakeReceipts: FollowupReceipts-    private let clock: () -> Date-    private let snoozeDefaults: UserDefaults?-    private var snoozes: [String: PlannedReminder] = [:]-    var localDeviceID: String?-    var openRun: (RoutineRun) -> Void = { _ in }-    var error: String? { didSet { if let error { onError(error) } } }-    var onError: (String) -> Void = { _ in }+  private let context: ModelContext+  private let center = UNUserNotificationCenter.current()+  private let notifications: any ReminderNotificationClient+  private let injectedNotifications: Bool+  private var reconcileTask: Task<Void, Never>?+  private var reconcileRevision = 0+  private let followupReceipts: FollowupReceipts+  private let wakeReceipts: FollowupReceipts+  private let clock: () -> Date+  private let snoozeDefaults: UserDefaults?+  private var snoozes: [String: PlannedReminder] = [:]+  var localDeviceID: String?+  var openRun: (RoutineRun) -> Void = { _ in }+  var error: String? { didSet { if let error { onError(error) } } }+  var onError: (String) -> Void = { _ in } -    init(context: ModelContext, notifications: (any ReminderNotificationClient)? = nil, receiptDefaults: UserDefaults? = nil, snoozeDefaults: UserDefaults? = nil, wakeReceiptDefaults: UserDefaults? = nil, registerDelegate: Bool = true, now: @escaping () -> Date = Date.init) {-        self.context = context-        clock = now-        self.snoozeDefaults = snoozeDefaults ?? (AppEnvironment.isTesting ? nil : .standard)-        wakeReceipts = FollowupReceipts(defaults: wakeReceiptDefaults ?? (AppEnvironment.isTesting ? nil : .standard), key: "meddy.notification.wake-receipts")-        followupReceipts = FollowupReceipts(defaults: receiptDefaults ?? (AppEnvironment.isTesting ? nil : .standard))-        self.notifications = notifications ?? SystemReminderNotifications()-        injectedNotifications = notifications != nil-        super.init()-        if let data = self.snoozeDefaults?.data(forKey: "meddy.notification.snoozes") {-            snoozes = (try? JSONDecoder().decode([String: PlannedReminder].self, from: data)) ?? [:]-        }-        guard !AppEnvironment.isTesting else { return }-        if registerDelegate { center.delegate = self }-        center.setNotificationCategories([-            UNNotificationCategory(identifier: "MEDICATION", actions: [UNNotificationAction(identifier: "TAKEN", title: "Taken / Applied"), UNNotificationAction(identifier: "SNOOZE", title: "Snooze 15 minutes")], intentIdentifiers: []),-            UNNotificationCategory(identifier: "ROUTINE", actions: [UNNotificationAction(identifier: "OPEN", title: "Open session", options: .foreground), UNNotificationAction(identifier: "SNOOZE", title: "Snooze 15 minutes")], intentIdentifiers: []),-            UNNotificationCategory(identifier: "FOLLOWUP", actions: [], intentIdentifiers: []),-            UNNotificationCategory(identifier: "TIMER", actions: [UNNotificationAction(identifier: "OPEN", title: "Open saved timer", options: .foreground)], intentIdentifiers: [])-        ])-        if registerDelegate { MutationEffects.observe(context) { [weak self] in self?.refresh() } }+  init(+    context: ModelContext, notifications: (any ReminderNotificationClient)? = nil,+    receiptDefaults: UserDefaults? = nil, snoozeDefaults: UserDefaults? = nil,+    wakeReceiptDefaults: UserDefaults? = nil, registerDelegate: Bool = true,+    now: @escaping () -> Date = Date.init+  ) {+    self.context = context+    clock = now+    self.snoozeDefaults = snoozeDefaults ?? (AppEnvironment.isTesting ? nil : .standard)+    wakeReceipts = FollowupReceipts(+      defaults: wakeReceiptDefaults ?? (AppEnvironment.isTesting ? nil : .standard),+      key: "meddy.notification.wake-receipts")+    followupReceipts = FollowupReceipts(+      defaults: receiptDefaults ?? (AppEnvironment.isTesting ? nil : .standard))+    self.notifications = notifications ?? SystemReminderNotifications()+    injectedNotifications = notifications != nil+    super.init()+    if let data = self.snoozeDefaults?.data(forKey: "meddy.notification.snoozes") {+      snoozes = (try? JSONDecoder().decode([String: PlannedReminder].self, from: data)) ?? [:]     }+    guard !AppEnvironment.isTesting else { return }+    if registerDelegate { center.delegate = self }+    center.setNotificationCategories([+      UNNotificationCategory(+        identifier: "MEDICATION",+        actions: [+          UNNotificationAction(identifier: "TAKEN", title: "Taken / Applied"),+          UNNotificationAction(identifier: "SNOOZE", title: "Snooze 15 minutes")+        ], intentIdentifiers: []),+      UNNotificationCategory(+        identifier: "ROUTINE",+        actions: [+          UNNotificationAction(identifier: "OPEN", title: "Open session", options: .foreground),+          UNNotificationAction(identifier: "SNOOZE", title: "Snooze 15 minutes")+        ], intentIdentifiers: []),+      UNNotificationCategory(identifier: "FOLLOWUP", actions: [], intentIdentifiers: []),+      UNNotificationCategory(+        identifier: "TIMER",+        actions: [+          UNNotificationAction(identifier: "OPEN", title: "Open saved timer", options: .foreground)+        ], intentIdentifiers: [])+    ])+    if registerDelegate { MutationEffects.observe(context) { [weak self] in self?.refresh() } }+  } -    func uses(_ value: ModelContext) -> Bool { context === value }-    func refresh() {-        guard !AppEnvironment.isTesting || injectedNotifications else { return }-        reconcileRevision += 1-        let previousTask = reconcileTask-        previousTask?.cancel()-        reconcileTask = Task { [weak self] in-            // Drain an in-flight add before the latest reconciliation removes obsolete requests.-            await previousTask?.value-            guard let self, !Task.isCancelled else { return }-            do {-                followupReceipts.advance(now: clock())-                let authorization = await notifications.authorization()-                guard !Task.isCancelled else { return }-                guard [.authorized, .provisional, .ephemeral].contains(authorization) else {-                    let pending = await notifications.pending()-                    notifications.removePending( pending.filter { $0.identifier.hasPrefix("meddy.") }.map(\.identifier))-                    let delivered = await notifications.delivered()-                    notifications.removeDelivered( delivered.filter { $0.request.identifier.hasPrefix("meddy.") }.map { $0.request.identifier })-                    return-                }-                let planned = try plan(now: clock())-                let semantic = try plan(now: clock(), includeElapsedWake: true)-                let validFollowups = try MedicationFollowupService.actions(context: context, now: clock())-                let pending = await notifications.pending()-                let delivered = await notifications.delivered()-                guard !Task.isCancelled else { return }-                notifications.removeDelivered( delivered.filter { notification in-                    guard notification.request.identifier.hasPrefix("meddy.") else { return false }-                    guard let data = notification.request.content.userInfo["meddy.payload"] as? Data,-                          let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data) else { return true }-                    if case .followup(let action) = previous.payload {-                        return !validFollowups.contains(action)-                    }-                    return !(previous.wakeEventID == nil ? planned : semantic).contains { $0.id == previous.id && sameAction($0.payload, previous.payload) }-                }.map { $0.request.identifier })-                notifications.removePending(pending.filter { request in-                    guard request.identifier.hasPrefix("meddy."), !planned.contains(where: { $0.id == request.identifier }) else { return false }-                    // A valid wake request already handed to the system may be awaiting delivery.-                    // Keep it; elapsed receipts prevent adding a replacement after dismissal.-                    if let data = request.content.userInfo["meddy.payload"] as? Data,-                       let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data), previous.wakeEventID != nil,-                       semantic.contains(where: { $0.id == previous.id && sameAction($0.payload, previous.payload) }) { return false }-                    return true-                }.map(\.identifier))-                for reminder in planned {-                    guard !Task.isCancelled else { return }-                    let alreadyDelivered = delivered.contains { notification in-                        guard let data = notification.request.content.userInfo["meddy.payload"] as? Data, let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data) else { return false }-                        return previous.id == reminder.id && sameAction(previous.payload, reminder.payload)-                    }-                    if case .followup = reminder.payload {-                        if alreadyDelivered { followupReceipts.markElapsed(reminder.id); continue }-                        if pending.contains(where: { request in-                            guard request.identifier == reminder.id,-                                  let data = request.content.userInfo["meddy.payload"] as? Data else { return false }-                            return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder-                        }) { followupReceipts.scheduled(reminder); continue }-                    }-                    if snoozes[reminder.id] != nil {-                        // A pending snooze already owns its absolute deadline. Do not replace it on wake-up.-                        let alreadyPending = pending.contains { request in-                            guard request.identifier == reminder.id,-                                  let data = request.content.userInfo["meddy.payload"] as? Data else { return false }-                            return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder-                        }-                        if alreadyPending || reminder.deliveryAt <= clock() { continue }-                        try await schedule(reminder)-                    } else if reminder.wakeEventID != nil {-                        if alreadyDelivered { wakeReceipts.markElapsed(reminder.id); continue }-                        let alreadyPending = pending.contains { request in-                            guard request.identifier == reminder.id, let data = request.content.userInfo["meddy.payload"] as? Data else { return false }-                            return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder-                        }-                        if alreadyPending { wakeReceipts.scheduled(reminder); continue }-                        if wakeReceipts.hasElapsed(reminder.id) { continue }-                        try await schedule(reminder)-                    } else if !alreadyDelivered { try await schedule(reminder) }-                }-            } catch { if !Task.isCancelled { self.error = error.localizedDescription } }+  func uses(_ value: ModelContext) -> Bool { context === value }+  func refresh() {+    guard !AppEnvironment.isTesting || injectedNotifications else { return }+    reconcileRevision += 1+    let previousTask = reconcileTask+    previousTask?.cancel()+    reconcileTask = Task { [weak self] in+      // Drain an in-flight add before the latest reconciliation removes obsolete requests.+      await previousTask?.value+      guard let self, !Task.isCancelled else { return }+      do {+        followupReceipts.advance(now: clock())+        let authorization = await notifications.authorization()+        guard !Task.isCancelled else { return }+        guard [.authorized, .provisional, .ephemeral].contains(authorization) else {+          let pending = await notifications.pending()+          notifications.removePending(+            pending.filter { $0.identifier.hasPrefix("meddy.") }.map(\.identifier))+          let delivered = await notifications.delivered()+          notifications.removeDelivered(+            delivered.filter { $0.request.identifier.hasPrefix("meddy.") }.map {+              $0.request.identifier+            })+          return         }-    }--    func waitForRefresh() async {-        while let task = reconcileTask {-            let revision = reconcileRevision-            await task.value-            if revision == reconcileRevision { return }+        let planned = try plan(now: clock())+        let semantic = try plan(now: clock(), includeElapsedWake: true)+        let validFollowups = try MedicationFollowupService.actions(context: context, now: clock())+        let pending = await notifications.pending()+        let delivered = await notifications.delivered()+        guard !Task.isCancelled else { return }+        notifications.removeDelivered(+          delivered.filter { notification in+            guard notification.request.identifier.hasPrefix("meddy.") else { return false }+            guard let data = notification.request.content.userInfo["meddy.payload"] as? Data,+              let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data)+            else { return true }+            if case .followup(let action) = previous.payload {+              return !validFollowups.contains(action)+            }+            return !(previous.wakeEventID == nil ? planned : semantic).contains {+              $0.id == previous.id && sameAction($0.payload, previous.payload)+            }+          }.map { $0.request.identifier })+        notifications.removePending(+          pending.filter { request in+            guard request.identifier.hasPrefix("meddy."),+              !planned.contains(where: { $0.id == request.identifier })+            else { return false }+            // A valid wake request already handed to the system may be awaiting delivery.+            // Keep it; elapsed receipts prevent adding a replacement after dismissal.+            if let data = request.content.userInfo["meddy.payload"] as? Data,+              let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data),+              previous.wakeEventID != nil,+              semantic.contains(where: {+                $0.id == previous.id && sameAction($0.payload, previous.payload)+              }) {+              return false+            }+            return true+          }.map(\.identifier))+        for reminder in planned {+          guard !Task.isCancelled else { return }+          try await deliverPlanned(reminder, pending: pending, delivered: delivered)         }+      } catch { if !Task.isCancelled { self.error = error.localizedDescription } }     }+  } -    func respond(_ reminder: PlannedReminder, action: String) async {-        handle(reminder, action: action)-        // Finish the current reconciliation before the background notification response returns.-        await waitForRefresh()-    }--    func plan(now: Date, includeElapsedWake: Bool = false) throws -> [PlannedReminder] {-        let planner = NotificationPlanner()-        let schedules = ScheduleService(context: context)-        let medications = try context.fetch(FetchDescriptor<Medication>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let routines = try context.fetch(FetchDescriptor<Routine>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter { (try? ProfileAccess.owner($0, context: context)) != nil }-        var result: [PlannedReminder] = []-        followupReceipts.advance(now: now)-        wakeReceipts.advance(now: now)-        for action in try MedicationFollowupService.actions(context: context, now: now) where action.deliveryAt > now && !followupReceipts.hasElapsed(action.requestID) {-            if let medication = medications.first(where: { $0.id == action.medicationID }) { result.append(try owned(action.reminder(name: medication.name), target: medication)) }-        }-        for medication in medications {-            let administrations = (medication.administrations ?? []).map { ScheduledAdministration(id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp, mode: MedicationScheduleType(rawValue: $0.scheduleTypeAtRecordingRaw) ?? .asNeeded, generationID: $0.scheduleGenerationID, routineRunID: $0.routineRunID, isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch, wakeEventID: $0.wakeEventID) }-            let base = try schedules.snapshot(medication)-            let variants: [MedicationScheduleSnapshot] = base.mode == .afterWaking ? (base.wakeAnchors ?? []).map { anchor in var value = base; value.wakeAnchor = anchor; return value } : [base]-            for variant in variants {-            if let reminder = planner.medication(variant, name: medication.name, dose: medication.defaultDose, reminders: medication.remindersEnabled, active: medication.isActive, administrations: administrations, now: now, calendar: .current) { result.append(try owned(reminder, target: medication)) }+  private func deliverPlanned(+    _ reminder: PlannedReminder, pending: [UNNotificationRequest], delivered: [UNNotification]+  ) async throws {+          let alreadyDelivered = delivered.contains { notification in+            guard let data = notification.request.content.userInfo["meddy.payload"] as? Data,+              let previous = try? JSONDecoder().decode(PlannedReminder.self, from: data)+            else { return false }+            return previous.id == reminder.id && sameAction(previous.payload, reminder.payload)+          }+          if case .followup = reminder.payload {+            if alreadyDelivered {+              followupReceipts.markElapsed(reminder.id)+              return             }-        }-        for routine in routines where routine.kindRaw == "ordered" && routine.isActive {-            _ = try schedules.activatePending(routine)-            let snapshot = try schedules.snapshot(routine)-            let represented = runs.map { ScheduledRunSnapshot(id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID, localDate: $0.scheduledLocalDate, startedAt: $0.startedAt, timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt, status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted) }-            for offset in -1...1 {-                guard let day = Calendar.current.date(byAdding: .day, value: offset, to: now) else { continue }-                for occurrence in RoutineScheduleEngine().occurrences(snapshot, runs: represented, day: day, now: now, calendar: .current) {-                    if offset < 0 && occurrence.wakeEventID == nil { continue }-                    if let reminder = planner.routine(name: routine.name, occurrence: occurrence, reminders: snapshot.remindersEnabled, now: now) { result.append(try owned(reminder, target: routine)) }-                }+            if pending.contains(where: { request in+              guard request.identifier == reminder.id,+                let data = request.content.userInfo["meddy.payload"] as? Data+              else { return false }+              return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder+            }) {+              followupReceipts.scheduled(reminder)+              return             }-        }-        for run in runs where (run.profileID == ProfileIdentity.me || run.profileLifecycleID == (try? ProfileAccess.lifecycle(run, context: context))) && !run.isDeleted && run.statusRaw != "needsReview" && (run.executionDeviceID == nil || run.executionDeviceID == localDeviceID) {-            if let data = run.timerCheckpointData, let checkpoint = try? JSONDecoder().decode(TimerCheckpoint.self, from: data), let reminder = planner.timer(name: run.routine?.name ?? "Saved timer", runID: run.id, revision: run.revision, checkpoint: checkpoint, now: now) { result.append(try owned(reminder, target: run)) }-        }-        // A snooze changes delivery only, and is discarded if the current semantic action changes.-        snoozes = snoozes.filter { key, value in result.contains { $0.id == key && sameAction($0.payload, value.payload) } }-        try persistSnoozes()-        result = Array(Dictionary(result.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }).values)-        var ordered: [PlannedReminder] = result.compactMap { base in-            if let snooze = snoozes[base.id] { return snooze }-            guard base.wakeEventID != nil, !includeElapsedWake else { return base }-            if wakeReceipts.hasElapsed(base.id) { return nil }-            if base.deliveryAt <= now && !(base.wakeImmediateUntil.map { now <= $0 } ?? false) { wakeReceipts.markElapsed(base.id); return nil }-            return base-        }-        ordered.sort { left, right in-            if left.deliveryAt == right.deliveryAt { return left.id < right.id }-            return left.deliveryAt < right.deliveryAt-        }-        let selected: [PlannedReminder] = includeElapsedWake ? ordered : Array(ordered.prefix(60))-        let followupIDs: [String] = selected.compactMap { reminder in-            if case .followup = reminder.payload { return reminder.id }-            return nil-        }-        if !includeElapsedWake { followupReceipts.retainPending(Set(followupIDs)) }-        return selected-    }+          }+          if snoozes[reminder.id] != nil {+            // A pending snooze already owns its absolute deadline. Do not replace it on wake-up.+            let alreadyPending = pending.contains { request in+              guard request.identifier == reminder.id,+                let data = request.content.userInfo["meddy.payload"] as? Data+              else { return false }+              return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder+            }+            if alreadyPending || reminder.deliveryAt <= clock() { return }+            try await schedule(reminder)+          } else if reminder.wakeEventID != nil {+            if alreadyDelivered {+              wakeReceipts.markElapsed(reminder.id)+              return+            }+            let alreadyPending = pending.contains { request in+              guard request.identifier == reminder.id,+                let data = request.content.userInfo["meddy.payload"] as? Data+              else { return false }+              return (try? JSONDecoder().decode(PlannedReminder.self, from: data)) == reminder+            }+            if alreadyPending {+              wakeReceipts.scheduled(reminder)+              return+            }+            if wakeReceipts.hasElapsed(reminder.id) { return }+            try await schedule(reminder)+          } else if !alreadyDelivered {+            try await schedule(reminder)+          }+  } -    private func persistSnoozes() throws {-        snoozeDefaults?.set(try JSONEncoder().encode(snoozes), forKey: "meddy.notification.snoozes")+  func waitForRefresh() async {+    while let task = reconcileTask {+      let revision = reconcileRevision+      await task.value+      if revision == reconcileRevision { return }     }+  } -    private func sameAction(_ left: ReminderPayload, _ right: ReminderPayload) -> Bool {-        switch (left, right) {-        case (.medication(let a), .medication(let b)):-            return a.eventID == b.eventID && a.medicationID == b.medicationID && a.scheduleGenerationID == b.scheduleGenerationID && a.dose == b.dose-        default: return left == right-        }-    }+  func respond(_ reminder: PlannedReminder, action: String) async {+    handle(reminder, action: action)+    // Finish the current reconciliation before the background notification response returns.+    await waitForRefresh()+  } -    private func schedule(_ reminder: PlannedReminder) async throws {-        let isFollowup: Bool-        if case .followup = reminder.payload { isFollowup = true } else { isFollowup = false }-        if isFollowup && reminder.deliveryAt <= clock() {-            followupReceipts.markElapsed(reminder.id)-            notifications.removePending([reminder.id])-            return+  func plan(now: Date, includeElapsedWake: Bool = false) throws -> [PlannedReminder] {+    let planner = NotificationPlanner()+    let schedules = ScheduleService(context: context)+    let medications = try context.fetch(FetchDescriptor<Medication>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let routines = try context.fetch(FetchDescriptor<Routine>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    let runs = try context.fetch(FetchDescriptor<RoutineRun>()).filter {+      (try? ProfileAccess.owner($0, context: context)) != nil+    }+    var result: [PlannedReminder] = []+    followupReceipts.advance(now: now)+    wakeReceipts.advance(now: now)+    for action in try MedicationFollowupService.actions(context: context, now: now)+    where action.deliveryAt > now && !followupReceipts.hasElapsed(action.requestID) {+      if let medication = medications.first(where: { $0.id == action.medicationID }) {+        result.append(try owned(action.reminder(name: medication.name), target: medication))+      }+    }+    result.append(contentsOf: try medicationPlans(medications, now: now))+    for routine in routines where routine.kindRaw == "ordered" && routine.isActive {+      _ = try schedules.activatePending(routine)+      let snapshot = try schedules.snapshot(routine)+      let represented = runs.map {+        ScheduledRunSnapshot(+          id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,+          localDate: $0.scheduledLocalDate, startedAt: $0.startedAt,+          timeZoneID: $0.scheduledTimeZoneID, scheduledAt: $0.scheduledAt,+          status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted)+      }+      for offset in -1...1 {+        guard let day = Calendar.current.date(byAdding: .day, value: offset, to: now) else {+          continue         }-        if reminder.wakeEventID != nil && snoozes[reminder.id] == nil && reminder.deliveryAt <= clock() && !(reminder.wakeImmediateUntil.map { clock() <= $0 } ?? false) {-            wakeReceipts.markElapsed(reminder.id); return+        for occurrence in RoutineScheduleEngine().occurrences(+          snapshot, runs: represented, day: day, now: now, calendar: .current) {+          if offset < 0 && occurrence.wakeEventID == nil { continue }+          if let reminder = planner.routine(+            name: routine.name, occurrence: occurrence, reminders: snapshot.remindersEnabled,+            now: now) {+            result.append(try owned(reminder, target: routine))+          }         }-        let content = UNMutableNotificationContent()-        content.title = reminder.title; content.body = reminder.body; content.sound = .default-        content.userInfo = ["meddy.payload": try JSONEncoder().encode(reminder)]-        switch reminder.payload {-        case .medication: content.categoryIdentifier = "MEDICATION"-        case .routine: content.categoryIdentifier = "ROUTINE"-        case .timer: content.categoryIdentifier = "TIMER"-        case .followup: content.categoryIdentifier = "FOLLOWUP"+      }+    }+    result.append(contentsOf: try timerPlans(runs, now: now))+    // A snooze changes delivery only, and is discarded if the current semantic action changes.+    snoozes = snoozes.filter { key, value in+      result.contains { $0.id == key && sameAction($0.payload, value.payload) }+    }+    try persistSnoozes()+    result = Array(+      Dictionary(result.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }).values)+    var ordered: [PlannedReminder] = result.compactMap { base in+      if let snooze = snoozes[base.id] { return snooze }+      guard base.wakeEventID != nil, !includeElapsedWake else { return base }+      if wakeReceipts.hasElapsed(base.id) { return nil }+      if base.deliveryAt <= now && !(base.wakeImmediateUntil.map { now <= $0 } ?? false) {+        wakeReceipts.markElapsed(base.id)+        return nil+      }+      return base+    }+    ordered.sort { left, right in+      if left.deliveryAt == right.deliveryAt { return left.id < right.id }+      return left.deliveryAt < right.deliveryAt+    }+    let selected: [PlannedReminder] = includeElapsedWake ? ordered : Array(ordered.prefix(60))+    let followupIDs: [String] = selected.compactMap { reminder in+      if case .followup = reminder.payload { return reminder.id }+      return nil+    }+    if !includeElapsedWake { followupReceipts.retainPending(Set(followupIDs)) }+    return selected+  }++  private func medicationPlans(+    _ medications: [Medication], now: Date+  ) throws -> [PlannedReminder] {+    let planner = NotificationPlanner()+    let schedules = ScheduleService(context: context)+    var result: [PlannedReminder] = []+    for medication in medications {+      let administrations = (medication.administrations ?? []).map {+        ScheduledAdministration(+          id: $0.id, medicationID: $0.medicationID, timestamp: $0.timestamp,+          mode: MedicationScheduleType(rawValue: $0.scheduleTypeAtRecordingRaw) ?? .asNeeded,+          generationID: $0.scheduleGenerationID, routineRunID: $0.routineRunID,+          isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch,+          wakeEventID: $0.wakeEventID)+      }+      let base = try schedules.snapshot(medication)+      let variants: [MedicationScheduleSnapshot] =+        base.mode == .afterWaking+        ? (base.wakeAnchors ?? []).map { anchor in+          var value = base+          value.wakeAnchor = anchor+          return value+        } : [base]+      for variant in variants {+        if let reminder = planner.medication(+          variant, details: MedicationReminderDetails(name: medication.name, dose: medication.defaultDose,+          reminders: medication.remindersEnabled, active: medication.isActive),+          administrations: administrations, now: now, calendar: .current) {+          result.append(try owned(reminder, target: medication))         }-        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: max(isFollowup ? 0.001 : 1, reminder.deliveryAt.timeIntervalSince(clock())), repeats: false)-        if isFollowup { followupReceipts.scheduled(reminder) }-        do { try await notifications.add(UNNotificationRequest(identifier: reminder.id, content: content, trigger: trigger)); if reminder.wakeEventID != nil && snoozes[reminder.id] == nil { wakeReceipts.scheduled(reminder) } }-        catch { if isFollowup { followupReceipts.forgetPending(reminder.id) }; throw error }+      }     }+    return result+  } -    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {-        guard let data = response.notification.request.content.userInfo["meddy.payload"] as? Data,-              let reminder = try? JSONDecoder().decode(PlannedReminder.self, from: data) else { return }-        let identifier = response.actionIdentifier-        await respond(reminder, action: identifier)+  private func timerPlans(_ runs: [RoutineRun], now: Date) throws -> [PlannedReminder] {+    let planner = NotificationPlanner()+    var result: [PlannedReminder] = []+    for run in runs+    where+      (run.profileID == ProfileIdentity.me+      || run.profileLifecycleID == (try? ProfileAccess.lifecycle(run, context: context)))+      && !run.isDeleted && run.statusRaw != "needsReview"+      && (run.executionDeviceID == nil || run.executionDeviceID == localDeviceID) {+      if let data = run.timerCheckpointData,+        let checkpoint = try? JSONDecoder().decode(TimerCheckpoint.self, from: data),+        let reminder = planner.timer(+          name: run.routine?.name ?? "Saved timer", runID: run.id, revision: run.revision,+          checkpoint: checkpoint, now: now) {+        result.append(try owned(reminder, target: run))+      }     }+    return result+  }++  private func persistSnoozes() throws {+    snoozeDefaults?.set(try JSONEncoder().encode(snoozes), forKey: "meddy.notification.snoozes")+  } -    func snoozeMedication(_ id: UUID) {-        do {-            guard let reminder = try plan(now: clock()).first(where: { item in-                if case .medication(let event) = item.payload { return event.medicationID == id }; return false-            }) else { return }-            handle(reminder, action: "SNOOZE")-        } catch { self.error = error.localizedDescription }+  private func sameAction(_ left: ReminderPayload, _ right: ReminderPayload) -> Bool {+    switch (left, right) {+    case (.medication(let left), .medication(let right)):+      return left.eventID == right.eventID && left.medicationID == right.medicationID+        && left.scheduleGenerationID == right.scheduleGenerationID && left.dose == right.dose+    default: return left == right     }+  } -    private func owned(_ reminder: PlannedReminder, target: any ProfileOwned) throws -> PlannedReminder {-        var result = try ProfileAccess.stamp(reminder, target: target, context: context)-        if case .medication(let event) = result.payload, target.profileID != ProfileIdentity.me { result.payload = .medication(action: try ProfileAccess.stamp(event, target: target, context: context)) }-        let owner = try ProfileAccess.owner(target, context: context)-        let label = try ProfileAccess.profile(owner, context: context)?.label ?? "Me"-        result.title = label + " · " + result.title-        if owner != ProfileIdentity.me && !result.id.hasPrefix("meddy.profile.") { result.id = "meddy.profile.\(owner)." + result.id }-        return result+  private func schedule(_ reminder: PlannedReminder) async throws {+    let isFollowup: Bool+    if case .followup = reminder.payload { isFollowup = true } else { isFollowup = false }+    if isFollowup && reminder.deliveryAt <= clock() {+      followupReceipts.markElapsed(reminder.id)+      notifications.removePending([reminder.id])+      return     }-    private func validateOwner(_ reminder: PlannedReminder) throws {-        let target: any ProfileOwned-        switch reminder.payload {-        case .medication(let event):-            let medication = try ProfileAccess.canonical(Medication.self, id: event.medicationID, context: context)-            try ProfileAccess.action(event.profileID, version: event.ownershipVersion, lifecycle: event.profileLifecycleID, target: medication, context: context)-            target = medication-        case .routine(let occurrence): target = try ProfileAccess.canonical(Routine.self, id: occurrence.routineID, context: context)-        case .timer(let id, _, _): target = try ProfileAccess.canonical(RoutineRun.self, id: id, context: context)-        case .followup(let event): target = try ProfileAccess.canonical(Medication.self, id: event.medicationID, context: context)-        }-        try ProfileAccess.action(reminder.profileID, version: reminder.ownershipVersion, lifecycle: reminder.profileLifecycleID, target: target, context: context)+    if reminder.wakeEventID != nil && snoozes[reminder.id] == nil && reminder.deliveryAt <= clock()+      && !(reminder.wakeImmediateUntil.map { clock() <= $0 } ?? false) {+      wakeReceipts.markElapsed(reminder.id)+      return     }-    func handle(_ reminder: PlannedReminder, action: String) {-        do {-            try validateOwner(reminder)-            if case .followup = reminder.payload { return } // Informational only; cannot record or snooze another dose.-            if action == "SNOOZE" {-                switch reminder.payload { case .medication, .routine: break; default: return }-                let actionAt = clock()-                guard let current = try plan(now: actionAt, includeElapsedWake: reminder.wakeEventID != nil).first(where: { $0.id == reminder.id && ($0.profileID ?? ProfileIdentity.me) == (reminder.profileID ?? ProfileIdentity.me) && ($0.profileLifecycleID ?? ProfileIdentity.selfLifecycle) == (reminder.profileLifecycleID ?? ProfileIdentity.selfLifecycle) && sameAction($0.payload, reminder.payload) }) else { refresh(); return }-                // A callback from the already-snoozed delivery is a repeat, not another user snooze.-                // The later delivered snooze carries its own deadline and can be snoozed again.-                if let previous = snoozes[reminder.id], reminder.deliveryAt < previous.deliveryAt {-                    refresh(); return-                }-                var deferred = current; deferred.deliveryAt = actionAt.addingTimeInterval(15 * 60)-                snoozes[reminder.id] = deferred-                try persistSnoozes()-                notifications.removePending([reminder.id]) // Cancel any queued overdue original immediately.-                notifications.removeDelivered([reminder.id])-                refresh(); return-            }-            switch reminder.payload {-            case .medication(var event):-                guard action == "TAKEN" else { return }-                event.timestamp = clock()-                // Preserve the delivered generation and dose, including a stale response, without crediting a new regimen.-                _ = try MedicationService(context: context).record(event)-            case .routine(let occurrence):-                let id = occurrence.routineID-                guard let routine = try context.fetch(FetchDescriptor<Routine>(predicate: #Predicate { $0.id == id })).first else { return }-                let run = try ScheduleService(context: context).startOccurrence(occurrence, routine: routine, source: .notification)-                openRun(run)-            case .followup: break-            case .timer(let id, _, _):-                if let run = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first, !run.isDeleted { openRun(run) }-            }-            refresh()-        } catch { self.error = error.localizedDescription }+    let content = UNMutableNotificationContent()+    content.title = reminder.title+    content.body = reminder.body+    content.sound = .default+    content.userInfo = ["meddy.payload": try JSONEncoder().encode(reminder)]+    switch reminder.payload {+    case .medication: content.categoryIdentifier = "MEDICATION"+    case .routine: content.categoryIdentifier = "ROUTINE"+    case .timer: content.categoryIdentifier = "TIMER"+    case .followup: content.categoryIdentifier = "FOLLOWUP"+    }+    let trigger = UNTimeIntervalNotificationTrigger(+      timeInterval: max(isFollowup ? 0.001 : 1, reminder.deliveryAt.timeIntervalSince(clock())),+      repeats: false)+    if isFollowup { followupReceipts.scheduled(reminder) }+    do {+      try await notifications.add(+        UNNotificationRequest(identifier: reminder.id, content: content, trigger: trigger))+      if reminder.wakeEventID != nil && snoozes[reminder.id] == nil {+        wakeReceipts.scheduled(reminder)+      }+    } catch {+      if isFollowup { followupReceipts.forgetPending(reminder.id) }+      throw error     }+  }++  nonisolated func userNotificationCenter(+    _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse+  ) async {+    guard let data = response.notification.request.content.userInfo["meddy.payload"] as? Data,+      let reminder = try? JSONDecoder().decode(PlannedReminder.self, from: data)+    else { return }+    let identifier = response.actionIdentifier+    await respond(reminder, action: identifier)+  } -    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {-        Self.foregroundPresentation(category: notification.request.content.categoryIdentifier)+  func snoozeMedication(_ id: UUID) {+    do {+      guard+        let reminder = try plan(now: clock()).first(where: { item in+          if case .medication(let event) = item.payload { return event.medicationID == id }+          return false+        })+      else { return }+      handle(reminder, action: "SNOOZE")+    } catch { self.error = error.localizedDescription }+  }++  private func owned(_ reminder: PlannedReminder, target: any ProfileOwned) throws+    -> PlannedReminder {+    var result = try ProfileAccess.stamp(reminder, target: target, context: context)+    if case .medication(let event) = result.payload, target.profileID != ProfileIdentity.me {+      result.payload = .medication(+        action: try ProfileAccess.stamp(event, target: target, context: context))+    }+    let owner = try ProfileAccess.owner(target, context: context)+    let label = try ProfileAccess.profile(owner, context: context)?.label ?? "Me"+    result.title = label + " · " + result.title+    if owner != ProfileIdentity.me && !result.id.hasPrefix("meddy.profile.") {+      result.id = "meddy.profile.\(owner)." + result.id     }-    nonisolated static func foregroundPresentation(category: String) -> UNNotificationPresentationOptions {-        // The foreground deadline service owns the timer buzz; avoid a second system alert.-        category == "TIMER" ? [] : [.banner, .sound]+    return result+  }+  private func validateOwner(_ reminder: PlannedReminder) throws {+    let target: any ProfileOwned+    switch reminder.payload {+    case .medication(let event):+      let medication = try ProfileAccess.canonical(+        Medication.self, id: event.medicationID, context: context)+      try ProfileAccess.action(+        event.profileID, version: event.ownershipVersion, lifecycle: event.profileLifecycleID,+        target: medication, context: context)+      target = medication+    case .routine(let occurrence):+      target = try ProfileAccess.canonical(Routine.self, id: occurrence.routineID, context: context)+    case .timer(let id, _, _):+      target = try ProfileAccess.canonical(RoutineRun.self, id: id, context: context)+    case .followup(let event):+      target = try ProfileAccess.canonical(+        Medication.self, id: event.medicationID, context: context)     }+    try ProfileAccess.action(+      reminder.profileID, version: reminder.ownershipVersion,+      lifecycle: reminder.profileLifecycleID, target: target, context: context)+  }+  func handle(_ reminder: PlannedReminder, action: String) {+    do {+      try validateOwner(reminder)+      if case .followup = reminder.payload { return }  // Informational only; cannot record or snooze another dose.+      if action == "SNOOZE" {+        switch reminder.payload {+        case .medication, .routine: break+        default: return+        }+        let actionAt = clock()+        guard+          let current = try plan(now: actionAt, includeElapsedWake: reminder.wakeEventID != nil)+            .first(where: {+              $0.id == reminder.id+                && ($0.profileID ?? ProfileIdentity.me)+                  == (reminder.profileID ?? ProfileIdentity.me)+                && ($0.profileLifecycleID ?? ProfileIdentity.selfLifecycle)+                  == (reminder.profileLifecycleID ?? ProfileIdentity.selfLifecycle)+                && sameAction($0.payload, reminder.payload)+            })+        else {+          refresh()+          return+        }+        // A callback from the already-snoozed delivery is a repeat, not another user snooze.+        // The later delivered snooze carries its own deadline and can be snoozed again.+        if let previous = snoozes[reminder.id], reminder.deliveryAt < previous.deliveryAt {+          refresh()+          return+        }+        var deferred = current+        deferred.deliveryAt = actionAt.addingTimeInterval(15 * 60)+        snoozes[reminder.id] = deferred+        try persistSnoozes()+        notifications.removePending([reminder.id])  // Cancel any queued overdue original immediately.+        notifications.removeDelivered([reminder.id])+        refresh()+        return+      }+      switch reminder.payload {+      case .medication(var event):+        guard action == "TAKEN" else { return }+        event.timestamp = clock()+        // Preserve the delivered generation and dose, including a stale response, without crediting a new regimen.+        _ = try MedicationService(context: context).record(event)+      case .routine(let occurrence):+        let id = occurrence.routineID+        guard+          let routine = try context.fetch(+            FetchDescriptor<Routine>(predicate: #Predicate { $0.id == id })+          ).first+        else { return }+        let run = try ScheduleService(context: context).startOccurrence(+          occurrence, routine: routine, source: .notification)+        openRun(run)+      case .followup: break+      case .timer(let id, _, _):+        if let run = try context.fetch(+          FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })+        ).first, !run.isDeleted {+          openRun(run)+        }+      }+      refresh()+    } catch { self.error = error.localizedDescription }+  }++  nonisolated func userNotificationCenter(+    _ center: UNUserNotificationCenter, willPresent notification: UNNotification+  ) async -> UNNotificationPresentationOptions {+    Self.foregroundPresentation(category: notification.request.content.categoryIdentifier)+  }+  nonisolated static func foregroundPresentation(category: String)+    -> UNNotificationPresentationOptions {+    // The foreground deadline service owns the timer buzz; avoid a second system alert.+    category == "TIMER" ? [] : [.banner, .sound]+  } }
Meddy/Meddy/Services/RoutineService.swift Modified
diff --git a/Meddy/Meddy/Services/RoutineService.swift b/Meddy/Meddy/Services/RoutineService.swiftindex d370076..ef8711e 100644--- a/Meddy/Meddy/Services/RoutineService.swift+++ b/Meddy/Meddy/Services/RoutineService.swift@@ -1,271 +1,431 @@ import Foundation import SwiftData +@MainActor+struct TimedRoutineEdit {+  var name: String+  var rounds: Int+  var durationSeconds: Int+  var instructions: String+  var betweenRounds: String+  var purpose: Purpose?+}+ @MainActor final class RoutineService {-    private let context: ModelContext-    private let deferSave: Bool-    var onChange: () -> Void = {}+  private let context: ModelContext+  private let deferSave: Bool+  var onChange: () -> Void = {} -    init(context: ModelContext, deferSave: Bool = false) {-        self.context = context-        self.deferSave = deferSave-        context.autosaveEnabled = false-    }+  init(context: ModelContext, deferSave: Bool = false) {+    self.context = context+    self.deferSave = deferSave+    context.autosaveEnabled = false+  } -    func createTimed(name: String, rounds: Int, durationSeconds: Int, instructions: String = "", betweenRounds: String = "", purpose: Purpose? = nil, profileID: UUID = ProfileIdentity.me) throws -> Routine {-        let name = try validName(name)-        try validateTimer(rounds: rounds, duration: durationSeconds)-        let routine = Routine(name: name, kind: .timedRounds)-        try ProfileAccess.assign(routine, to: profileID, context: context)-        if let purpose { try ProfileAccess.same(routine, purpose, context: context) }-        routine.roundCount = rounds-        routine.roundDurationSeconds = durationSeconds-        routine.instructions = instructions-        routine.betweenRoundInstructions = betweenRounds-        routine.purpose = purpose-        context.insert(routine)-        try save()-        return routine-    }+  func createTimed(+    name: String, rounds: Int, durationSeconds: Int, instructions: String = "",+    betweenRounds: String = "", purpose: Purpose? = nil, profileID: UUID = ProfileIdentity.me+  ) throws -> Routine {+    let name = try validName(name)+    try validateTimer(rounds: rounds, duration: durationSeconds)+    let routine = Routine(name: name, kind: .timedRounds)+    try ProfileAccess.assign(routine, to: profileID, context: context)+    if let purpose { try ProfileAccess.same(routine, purpose, context: context) }+    routine.roundCount = rounds+    routine.roundDurationSeconds = durationSeconds+    routine.instructions = instructions+    routine.betweenRoundInstructions = betweenRounds+    routine.purpose = purpose+    context.insert(routine)+    try save()+    return routine+  } -    func updateTimed(_ routine: Routine, name: String, rounds: Int, durationSeconds: Int, instructions: String, betweenRounds: String, purpose: Purpose?) throws {-        _ = try ProfileAccess.owner(routine, context: context)-        if let purpose { try ProfileAccess.same(routine, purpose, context: context) }-        guard routine.kindRaw == RoutineKind.timedRounds.rawValue else { throw DefinitionError.nestedRoutine }-        let name = try validName(name)-        try validateTimer(rounds: rounds, duration: durationSeconds)-        routine.name = name-        routine.roundCount = rounds-        routine.roundDurationSeconds = durationSeconds-        routine.instructions = instructions-        routine.betweenRoundInstructions = betweenRounds-        routine.purpose = purpose-        routine.definitionRevision += 1-        try save()+  func updateTimed(_ routine: Routine, edit: TimedRoutineEdit) throws {+    _ = try ProfileAccess.owner(routine, context: context)+    if let purpose = edit.purpose { try ProfileAccess.same(routine, purpose, context: context) }+    guard routine.kindRaw == RoutineKind.timedRounds.rawValue else {+      throw DefinitionError.nestedRoutine     }+    let name = try validName(edit.name)+    try validateTimer(rounds: edit.rounds, duration: edit.durationSeconds)+    routine.name = name+    routine.roundCount = edit.rounds+    routine.roundDurationSeconds = edit.durationSeconds+    routine.instructions = edit.instructions+    routine.betweenRoundInstructions = edit.betweenRounds+    routine.purpose = edit.purpose+    routine.definitionRevision += 1+    try save()+  } -    func createOrdered(name: String, steps: [RoutineStepDraft], instructions: String = "", purpose: Purpose? = nil, confirmedMedicationIDs: Set<UUID> = [], transferredMedicationIDs: Set<UUID> = [], archiveEmptyOwnerIDs: Set<UUID> = [], profileID: UUID = ProfileIdentity.me) throws -> Routine {-        let routine = Routine(name: try validName(name), kind: .ordered)-        try ProfileAccess.assign(routine, to: profileID, context: context)-        if let purpose { try ProfileAccess.same(routine, purpose, context: context) }-        try validateSteps(steps, profileID: profileID, ownerID: routine.id, existingMedicationIDs: [], confirmedMedicationIDs: confirmedMedicationIDs, transferredMedicationIDs: transferredMedicationIDs)-        guard transferredMedicationIDs.isSubset(of: Set(steps.filter { $0.kind == .medication }.map(\.targetID))) else { throw ProfileError.conflictingOwnership }-        try validateTransfers(transferredMedicationIDs, profileID: routine.profileID ?? ProfileIdentity.me, destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)-        routine.instructions = instructions-        routine.purpose = purpose-        context.insert(routine)-        do {-            try detachTransferred(transferredMedicationIDs, destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)-            try applySteps(steps, to: routine)-            try save()-        } catch { context.rollback(); throw error }-        return routine+  func createOrdered(+    name: String, steps: [RoutineStepDraft], instructions: String = "", purpose: Purpose? = nil,+    confirmedMedicationIDs: Set<UUID> = [], transferredMedicationIDs: Set<UUID> = [],+    archiveEmptyOwnerIDs: Set<UUID> = [], profileID: UUID = ProfileIdentity.me+  ) throws -> Routine {+    let routine = Routine(name: try validName(name), kind: .ordered)+    try ProfileAccess.assign(routine, to: profileID, context: context)+    if let purpose { try ProfileAccess.same(routine, purpose, context: context) }+    try validateSteps(+      steps, profileID: profileID, ownerID: routine.id, existingMedicationIDs: [],+      confirmedMedicationIDs: confirmedMedicationIDs,+      transferredMedicationIDs: transferredMedicationIDs)+    guard+      transferredMedicationIDs.isSubset(+        of: Set(steps.filter { $0.kind == .medication }.map(\.targetID)))+    else { throw ProfileError.conflictingOwnership }+    try validateTransfers(+      transferredMedicationIDs, profileID: routine.profileID ?? ProfileIdentity.me,+      destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)+    routine.instructions = instructions+    routine.purpose = purpose+    context.insert(routine)+    do {+      try detachTransferred(+        transferredMedicationIDs, destination: routine.id,+        archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)+      try applySteps(steps, to: routine)+      try save()+    } catch {+      context.rollback()+      throw error     }+    return routine+  } -    func updateOrdered(_ routine: Routine, name: String, steps: [RoutineStepDraft], instructions: String, purpose: Purpose?, confirmedMedicationIDs: Set<UUID> = [], releasedAsNeededMedicationIDs: Set<UUID> = [], transferredMedicationIDs: Set<UUID> = [], archiveEmptyOwnerIDs: Set<UUID> = []) throws {-        _ = try ProfileAccess.owner(routine, context: context)-        if let purpose { try ProfileAccess.same(routine, purpose, context: context) }-        guard routine.kindRaw == RoutineKind.ordered.rawValue else { throw DefinitionError.nestedRoutine }-        let name = try validName(name)-        let oldMedicationIDs = Set((routine.steps ?? []).filter { $0.targetKindRaw == RoutineStepTargetKind.medication.rawValue }.map(\.targetID))-        let newMedicationIDs = Set(steps.filter { $0.kind == .medication }.map(\.targetID))-        let removed = oldMedicationIDs.subtracting(newMedicationIDs)-        guard removed.isSubset(of: releasedAsNeededMedicationIDs) else { throw DefinitionError.releaseChoiceRequired }-        try validateSteps(steps, profileID: try ProfileAccess.owner(routine, context: context), ownerID: routine.id, existingMedicationIDs: oldMedicationIDs, confirmedMedicationIDs: confirmedMedicationIDs, transferredMedicationIDs: transferredMedicationIDs)-        guard transferredMedicationIDs.isSubset(of: Set(steps.filter { $0.kind == .medication }.map(\.targetID))) else { throw ProfileError.conflictingOwnership }-        try validateTransfers(transferredMedicationIDs, profileID: routine.profileID ?? ProfileIdentity.me, destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)-        for medicationID in removed { try validateRelease(medicationID) }-        routine.name = name-        routine.instructions = instructions-        routine.purpose = purpose-        routine.definitionRevision += 1-        for medicationID in removed {-            if let medication = try medication(medicationID) {-                medication.managedByRoutineID = nil-                clearStandaloneSchedule(medication)-                medication.scheduleTypeRaw = MedicationScheduleType.asNeeded.rawValue-            }-        }-        do {-            try detachTransferred(transferredMedicationIDs, destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)-            try applySteps(steps, to: routine)-            try save()-        } catch { context.rollback(); throw error }+  func updateOrdered(+    _ routine: Routine, name: String, steps: [RoutineStepDraft], instructions: String,+    purpose: Purpose?, confirmedMedicationIDs: Set<UUID> = [],+    releasedAsNeededMedicationIDs: Set<UUID> = [], transferredMedicationIDs: Set<UUID> = [],+    archiveEmptyOwnerIDs: Set<UUID> = []+  ) throws {+    _ = try ProfileAccess.owner(routine, context: context)+    if let purpose { try ProfileAccess.same(routine, purpose, context: context) }+    guard routine.kindRaw == RoutineKind.ordered.rawValue else {+      throw DefinitionError.nestedRoutine     }--    func setActive(_ routine: Routine, _ active: Bool) throws {-        _ = try ProfileAccess.owner(routine, context: context)-        routine.isActive = active-        if !active {-            routine.remindersEnabled = false-            routine.scheduleTypeRaw = "none"-            routine.pendingScheduleData = nil-        }-        try save()+    let name = try validName(name)+    let oldMedicationIDs = Set(+      (routine.steps ?? []).filter { $0.targetKindRaw == RoutineStepTargetKind.medication.rawValue }+        .map(\.targetID))+    let newMedicationIDs = Set(steps.filter { $0.kind == .medication }.map(\.targetID))+    let removed = oldMedicationIDs.subtracting(newMedicationIDs)+    guard removed.isSubset(of: releasedAsNeededMedicationIDs) else {+      throw DefinitionError.releaseChoiceRequired     }--    func freeze(_ routine: Routine) throws -> FrozenRoutineDefinition {-        let profileID = try ProfileAccess.owner(routine, context: context)-        guard routine.isActive, let kind = RoutineKind(rawValue: routine.kindRaw) else { throw DefinitionError.invalidTarget }-        var frozen: [FrozenRoutineStep] = []-        if kind == .timedRounds {-            try validateTimer(rounds: routine.roundCount ?? 0, duration: routine.roundDurationSeconds ?? 0)-        } else {-            let drafts = try (routine.steps ?? []).sorted { $0.position < $1.position }.map { step in-                guard let kind = RoutineStepTargetKind(rawValue: step.targetKindRaw) else { throw DefinitionError.invalidTarget }-                return RoutineStepDraft(id: step.id, kind: kind, targetID: step.targetID)-            }-            try validateSteps(drafts, profileID: profileID, ownerID: routine.id, existingMedicationIDs: Set(drafts.filter { $0.kind == .medication }.map(\.targetID)), confirmedMedicationIDs: [])-            for (position, step) in drafts.enumerated() {-                var value = FrozenRoutineStep(id: step.id, position: position, kind: step.kind, targetID: step.targetID, name: "", instructions: "", requirements: "", dose: nil, roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "")-                switch step.kind {-                case .treatment:-                    guard let target = try treatment(step.targetID) else { throw DefinitionError.invalidTarget }-                    value.name = target.name; value.instructions = target.instructions-                case .timedRoutine:-                    guard let target = try timedRoutine(step.targetID) else { throw DefinitionError.invalidTarget }-                    value.name = target.name; value.instructions = target.instructions-                    value.roundCount = target.roundCount; value.roundDurationSeconds = target.roundDurationSeconds-                    value.betweenRoundInstructions = target.betweenRoundInstructions-                case .medication:-                    guard let target = try medication(step.targetID) else { throw DefinitionError.invalidTarget }-                    value.name = target.name; value.instructions = target.administrationMethod-                    value.requirements = target.requirements; value.dose = target.defaultDose-                }-                frozen.append(value)-            }-        }-        var definition = FrozenRoutineDefinition(routineID: routine.id, revision: routine.definitionRevision, kind: kind, name: routine.name, instructions: routine.instructions, roundCount: routine.roundCount, roundDurationSeconds: routine.roundDurationSeconds, betweenRoundInstructions: routine.betweenRoundInstructions, steps: frozen)-        definition.profileID = profileID; definition.ownershipVersion = ProfileIdentity.ownershipVersion-        definition.profileLifecycleID = try ProfileAccess.lifecycle(routine, context: context)-        for index in definition.steps.indices { definition.steps[index].profileID = profileID; definition.steps[index].ownershipVersion = ProfileIdentity.ownershipVersion; definition.steps[index].profileLifecycleID = definition.profileLifecycleID }-        return definition+    try validateSteps(+      steps, profileID: try ProfileAccess.owner(routine, context: context), ownerID: routine.id,+      existingMedicationIDs: oldMedicationIDs, confirmedMedicationIDs: confirmedMedicationIDs,+      transferredMedicationIDs: transferredMedicationIDs)+    guard+      transferredMedicationIDs.isSubset(+        of: Set(steps.filter { $0.kind == .medication }.map(\.targetID)))+    else { throw ProfileError.conflictingOwnership }+    try validateTransfers(+      transferredMedicationIDs, profileID: routine.profileID ?? ProfileIdentity.me,+      destination: routine.id, archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)+    for medicationID in removed { try validateRelease(medicationID) }+    routine.name = name+    routine.instructions = instructions+    routine.purpose = purpose+    routine.definitionRevision += 1+    for medicationID in removed {+      if let medication = try medication(medicationID) {+        medication.managedByRoutineID = nil+        clearStandaloneSchedule(medication)+        medication.scheduleTypeRaw = MedicationScheduleType.asNeeded.rawValue+      }+    }+    do {+      try detachTransferred(+        transferredMedicationIDs, destination: routine.id,+        archiveEmptyOwnerIDs: archiveEmptyOwnerIDs)+      try applySteps(steps, to: routine)+      try save()+    } catch {+      context.rollback()+      throw error     }+  } -    private func validateSteps(_ steps: [RoutineStepDraft], profileID: UUID, ownerID: UUID, existingMedicationIDs: Set<UUID>, confirmedMedicationIDs: Set<UUID>, transferredMedicationIDs: Set<UUID> = []) throws {-        guard !steps.isEmpty else { throw DefinitionError.emptySteps }-        guard Set(steps.map(\.id)).count == steps.count else { throw DefinitionError.duplicateStepID }-        var medicationIDs: Set<UUID> = []-        for step in steps {-            switch step.kind {-            case .treatment:-                guard let target = try treatment(step.targetID), target.isActive else { throw DefinitionError.invalidTarget }-                guard try ProfileAccess.owner(target, context: context) == profileID else { throw ProfileError.conflictingOwnership }-            case .timedRoutine:-                guard step.targetID != ownerID, let target = try timedRoutine(step.targetID), target.isActive else { throw DefinitionError.invalidTarget }-                guard try ProfileAccess.owner(target, context: context) == profileID else { throw ProfileError.conflictingOwnership }-                guard target.kindRaw == RoutineKind.timedRounds.rawValue else { throw DefinitionError.nestedRoutine }-                try validateTimer(rounds: target.roundCount ?? 0, duration: target.roundDurationSeconds ?? 0)-            case .medication:-                guard medicationIDs.insert(step.targetID).inserted else { throw DefinitionError.duplicateMedication }-                guard let target = try medication(step.targetID), target.isActive else { throw DefinitionError.invalidTarget }-                guard try ProfileAccess.owner(target, context: context) == profileID else { throw ProfileError.conflictingOwnership }-                guard target.managedByRoutineID == nil || target.managedByRoutineID == ownerID || transferredMedicationIDs.contains(target.id) else { throw DefinitionError.otherOwner }-                if !existingMedicationIDs.contains(target.id) && !confirmedMedicationIDs.contains(target.id) { throw DefinitionError.ownershipConfirmationRequired }-            }-        }+  func setActive(_ routine: Routine, _ active: Bool) throws {+    _ = try ProfileAccess.owner(routine, context: context)+    routine.isActive = active+    if !active {+      routine.remindersEnabled = false+      routine.scheduleTypeRaw = "none"+      routine.pendingScheduleData = nil     }+    try save()+  } -    private func applySteps(_ drafts: [RoutineStepDraft], to routine: Routine) throws {-        var old: [UUID: RoutineStep] = [:]-        for step in routine.steps ?? [] {-            guard old[step.id] == nil else { throw DefinitionError.duplicateStepID }-            old[step.id] = step+  func freeze(_ routine: Routine) throws -> FrozenRoutineDefinition {+    let profileID = try ProfileAccess.owner(routine, context: context)+    guard routine.isActive, let kind = RoutineKind(rawValue: routine.kindRaw) else {+      throw DefinitionError.invalidTarget+    }+    var frozen: [FrozenRoutineStep] = []+    if kind == .timedRounds {+      try validateTimer(+        rounds: routine.roundCount ?? 0, duration: routine.roundDurationSeconds ?? 0)+    } else {+      let drafts = try (routine.steps ?? []).sorted { $0.position < $1.position }.map { step in+        guard let kind = RoutineStepTargetKind(rawValue: step.targetKindRaw) else {+          throw DefinitionError.invalidTarget         }-        for step in routine.steps ?? [] where !drafts.contains(where: { $0.id == step.id }) { context.delete(step) }-        var steps: [RoutineStep] = []-        for (position, draft) in drafts.enumerated() {-            let step = old[draft.id] ?? RoutineStep(routine: routine, targetKind: draft.kind, targetID: draft.targetID, position: position)-            step.id = draft.id-            step.position = position; step.targetID = draft.targetID; step.targetKindRaw = draft.kind.rawValue-            if old[draft.id] == nil { context.insert(step) }-            steps.append(step)-            if draft.kind == .medication, let medication = try medication(draft.targetID) {-                clearStandaloneSchedule(medication)-                medication.scheduleTypeRaw = MedicationScheduleType.routineManaged.rawValue-                medication.managedByRoutineID = routine.id-            }+        return RoutineStepDraft(id: step.id, kind: kind, targetID: step.targetID)+      }+      try validateSteps(+        drafts, profileID: profileID, ownerID: routine.id,+        existingMedicationIDs: Set(drafts.filter { $0.kind == .medication }.map(\.targetID)),+        confirmedMedicationIDs: [])+      for (position, step) in drafts.enumerated() {+        var value = FrozenRoutineStep(+          id: step.id, position: position, kind: step.kind, targetID: step.targetID, name: "",+          instructions: "", requirements: "", dose: nil, roundCount: nil, roundDurationSeconds: nil,+          betweenRoundInstructions: "")+        switch step.kind {+        case .treatment:+          guard let target = try treatment(step.targetID) else {+            throw DefinitionError.invalidTarget+          }+          value.name = target.name+          value.instructions = target.instructions+        case .timedRoutine:+          guard let target = try timedRoutine(step.targetID) else {+            throw DefinitionError.invalidTarget+          }+          value.name = target.name+          value.instructions = target.instructions+          value.roundCount = target.roundCount+          value.roundDurationSeconds = target.roundDurationSeconds+          value.betweenRoundInstructions = target.betweenRoundInstructions+        case .medication:+          guard let target = try medication(step.targetID) else {+            throw DefinitionError.invalidTarget+          }+          value.name = target.name+          value.instructions = target.administrationMethod+          value.requirements = target.requirements+          value.dose = target.defaultDose         }-        routine.steps = steps+        frozen.append(value)+      }+    }+    var definition = FrozenRoutineDefinition(+      routineID: routine.id, revision: routine.definitionRevision, kind: kind, name: routine.name,+      instructions: routine.instructions, roundCount: routine.roundCount,+      roundDurationSeconds: routine.roundDurationSeconds,+      betweenRoundInstructions: routine.betweenRoundInstructions, steps: frozen)+    definition.profileID = profileID+    definition.ownershipVersion = ProfileIdentity.ownershipVersion+    definition.profileLifecycleID = try ProfileAccess.lifecycle(routine, context: context)+    for index in definition.steps.indices {+      definition.steps[index].profileID = profileID+      definition.steps[index].ownershipVersion = ProfileIdentity.ownershipVersion+      definition.steps[index].profileLifecycleID = definition.profileLifecycleID     }+    return definition+  } -    private func validateTransfers(_ ids: Set<UUID>, profileID: UUID, destination: UUID, archiveEmptyOwnerIDs: Set<UUID>) throws {-        var owners: Set<UUID> = []-        for id in ids {-            guard let item = try medication(id), let owner = item.managedByRoutineID, owner != destination else { throw DefinitionError.otherOwner }-            guard try ProfileAccess.owner(item, context: context) == profileID else { throw ProfileError.conflictingOwnership }-            guard let source = try timedRoutine(owner), try ProfileAccess.owner(source, context: context) == profileID else { throw ProfileError.conflictingOwnership }-            try validateRelease(id); owners.insert(owner)+  private func validateSteps(+    _ steps: [RoutineStepDraft], profileID: UUID, ownerID: UUID, existingMedicationIDs: Set<UUID>,+    confirmedMedicationIDs: Set<UUID>, transferredMedicationIDs: Set<UUID> = []+  ) throws {+    guard !steps.isEmpty else { throw DefinitionError.emptySteps }+    guard Set(steps.map(\.id)).count == steps.count else { throw DefinitionError.duplicateStepID }+    var medicationIDs: Set<UUID> = []+    for step in steps {+      switch step.kind {+      case .treatment:+        guard let target = try treatment(step.targetID), target.isActive else {+          throw DefinitionError.invalidTarget         }-        for id in owners {-            guard let owner = try timedRoutine(id) else { throw DefinitionError.invalidTarget }-            let remaining = (owner.steps ?? []).filter { !($0.targetKindRaw == "medication" && ids.contains($0.targetID)) }-            if remaining.isEmpty && !archiveEmptyOwnerIDs.contains(id) { throw DefinitionError.emptyOwnerConfirmationRequired }+        guard try ProfileAccess.owner(target, context: context) == profileID else {+          throw ProfileError.conflictingOwnership         }-    }-    private func detachTransferred(_ ids: Set<UUID>, destination: UUID, archiveEmptyOwnerIDs: Set<UUID>) throws {-        var owners: Set<UUID> = []-        for id in ids { if let owner = try medication(id)?.managedByRoutineID, owner != destination { owners.insert(owner) } }-        for id in owners {-            guard let owner = try timedRoutine(id) else { throw DefinitionError.invalidTarget }-            let removed = (owner.steps ?? []).filter { $0.targetKindRaw == "medication" && ids.contains($0.targetID) }-            let remaining = (owner.steps ?? []).filter { !removed.contains($0) }.sorted { $0.position < $1.position }-            for step in removed { context.delete(step) }-            owner.steps = remaining-            for (position, step) in remaining.enumerated() { step.position = position }-            owner.definitionRevision += 1-            if remaining.isEmpty {-                guard archiveEmptyOwnerIDs.contains(id) else { throw DefinitionError.emptyOwnerConfirmationRequired }-                owner.isActive = false; owner.remindersEnabled = false; owner.scheduleTypeRaw = "none"; owner.pendingScheduleData = nil-            }+      case .timedRoutine:+        guard step.targetID != ownerID, let target = try timedRoutine(step.targetID),+          target.isActive+        else { throw DefinitionError.invalidTarget }+        guard try ProfileAccess.owner(target, context: context) == profileID else {+          throw ProfileError.conflictingOwnership         }-    }--    private func validateRelease(_ medicationID: UUID) throws {-        let runs = try context.fetch(FetchDescriptor<RoutineRun>())-        for run in runs where !run.isDeleted && !["completed", "finishedWithSkips", "endedIncomplete"].contains(run.statusRaw) {-            if let definition = try? JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData),-               definition.steps.contains(where: { step in-                   guard step.kind == .medication && step.targetID == medicationID else { return false }-                   guard let progress = try? JSONDecoder().decode(OrderedCheckpoint.self, from: run.stepProgressData), let saved = progress.steps.first(where: { $0.id == step.id }) else { return true }-                   return !(saved.state == .completed || (saved.state == .skipped && saved.skipConfirmed))-               }) {-                throw DefinitionError.unresolvedFrozenStep-            }+        guard target.kindRaw == RoutineKind.timedRounds.rawValue else {+          throw DefinitionError.nestedRoutine+        }+        try validateTimer(+          rounds: target.roundCount ?? 0, duration: target.roundDurationSeconds ?? 0)+      case .medication:+        guard medicationIDs.insert(step.targetID).inserted else {+          throw DefinitionError.duplicateMedication+        }+        guard let target = try medication(step.targetID), target.isActive else {+          throw DefinitionError.invalidTarget+        }+        guard try ProfileAccess.owner(target, context: context) == profileID else {+          throw ProfileError.conflictingOwnership+        }+        guard+          target.managedByRoutineID == nil || target.managedByRoutineID == ownerID+            || transferredMedicationIDs.contains(target.id)+        else { throw DefinitionError.otherOwner }+        if !existingMedicationIDs.contains(target.id) && !confirmedMedicationIDs.contains(target.id) {+          throw DefinitionError.ownershipConfirmationRequired         }+      }     }+  } -    private func clearStandaloneSchedule(_ medication: Medication) {-        medication.remindersEnabled = false-        medication.scheduleStartedAt = nil; medication.scheduleGenerationID = nil-        medication.dosesPerDay = nil; medication.intervalMinutes = nil-        medication.firstReminderMinuteOfDay = nil; medication.dayStartMinuteOfDay = nil-        medication.dayEndMinuteOfDay = nil; medication.minimumIntervalMinutes = nil; medication.fixedTimesData = nil+  private func applySteps(_ drafts: [RoutineStepDraft], to routine: Routine) throws {+    var old: [UUID: RoutineStep] = [:]+    for step in routine.steps ?? [] {+      guard old[step.id] == nil else { throw DefinitionError.duplicateStepID }+      old[step.id] = step     }+    for step in routine.steps ?? [] where !drafts.contains(where: { $0.id == step.id }) {+      context.delete(step)+    }+    var steps: [RoutineStep] = []+    for (position, draft) in drafts.enumerated() {+      let step =+        old[draft.id]+        ?? RoutineStep(+          routine: routine, targetKind: draft.kind, targetID: draft.targetID, position: position)+      step.id = draft.id+      step.position = position+      step.targetID = draft.targetID+      step.targetKindRaw = draft.kind.rawValue+      if old[draft.id] == nil { context.insert(step) }+      steps.append(step)+      if draft.kind == .medication, let medication = try medication(draft.targetID) {+        clearStandaloneSchedule(medication)+        medication.scheduleTypeRaw = MedicationScheduleType.routineManaged.rawValue+        medication.managedByRoutineID = routine.id+      }+    }+    routine.steps = steps+  } -    private func medication(_ id: UUID) throws -> Medication? {-        try context.fetch(FetchDescriptor<Medication>(predicate: #Predicate { $0.id == id })).first+  private func validateTransfers(+    _ ids: Set<UUID>, profileID: UUID, destination: UUID, archiveEmptyOwnerIDs: Set<UUID>+  ) throws {+    var owners: Set<UUID> = []+    for id in ids {+      guard let item = try medication(id), let owner = item.managedByRoutineID, owner != destination+      else { throw DefinitionError.otherOwner }+      guard try ProfileAccess.owner(item, context: context) == profileID else {+        throw ProfileError.conflictingOwnership+      }+      guard let source = try timedRoutine(owner),+        try ProfileAccess.owner(source, context: context) == profileID+      else { throw ProfileError.conflictingOwnership }+      try validateRelease(id)+      owners.insert(owner)     }-    private func treatment(_ id: UUID) throws -> Treatment? {-        try context.fetch(FetchDescriptor<Treatment>(predicate: #Predicate { $0.id == id })).first+    for id in owners {+      guard let owner = try timedRoutine(id) else { throw DefinitionError.invalidTarget }+      let remaining = (owner.steps ?? []).filter {+        !($0.targetKindRaw == "medication" && ids.contains($0.targetID))+      }+      if remaining.isEmpty && !archiveEmptyOwnerIDs.contains(id) {+        throw DefinitionError.emptyOwnerConfirmationRequired+      }     }-    private func timedRoutine(_ id: UUID) throws -> Routine? {-        try context.fetch(FetchDescriptor<Routine>(predicate: #Predicate { $0.id == id })).first+  }+  private func detachTransferred(+    _ ids: Set<UUID>, destination: UUID, archiveEmptyOwnerIDs: Set<UUID>+  ) throws {+    var owners: Set<UUID> = []+    for id in ids {+      if let owner = try medication(id)?.managedByRoutineID, owner != destination {+        owners.insert(owner)+      }     }-    private func validName(_ value: String) throws -> String {-        let name = value.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !name.isEmpty else { throw DefinitionError.missingName }-        return name+    for id in owners {+      guard let owner = try timedRoutine(id) else { throw DefinitionError.invalidTarget }+      let removed = (owner.steps ?? []).filter {+        $0.targetKindRaw == "medication" && ids.contains($0.targetID)+      }+      let remaining = (owner.steps ?? []).filter { !removed.contains($0) }.sorted {+        $0.position < $1.position+      }+      for step in removed { context.delete(step) }+      owner.steps = remaining+      for (position, step) in remaining.enumerated() { step.position = position }+      owner.definitionRevision += 1+      if remaining.isEmpty {+        guard archiveEmptyOwnerIDs.contains(id) else {+          throw DefinitionError.emptyOwnerConfirmationRequired+        }+        owner.isActive = false+        owner.remindersEnabled = false+        owner.scheduleTypeRaw = "none"+        owner.pendingScheduleData = nil+      }     }-    private func validateTimer(rounds: Int, duration: Int) throws {-        guard rounds >= 1, duration >= 1 else { throw DefinitionError.invalidTimer }+  }++  private func validateRelease(_ medicationID: UUID) throws {+    let runs = try context.fetch(FetchDescriptor<RoutineRun>())+    for run in runs+    where !run.isDeleted+      && !["completed", "finishedWithSkips", "endedIncomplete"].contains(run.statusRaw) {+      if let definition = try? JSONDecoder().decode(+        FrozenRoutineDefinition.self, from: run.definitionSnapshotData),+        definition.steps.contains(where: { step in+          guard step.kind == .medication && step.targetID == medicationID else { return false }+          guard+            let progress = try? JSONDecoder().decode(+              OrderedCheckpoint.self, from: run.stepProgressData),+            let saved = progress.steps.first(where: { $0.id == step.id })+          else { return true }+          return !(saved.state == .completed || (saved.state == .skipped && saved.skipConfirmed))+        }) {+        throw DefinitionError.unresolvedFrozenStep+      }     }-    private func save() throws {-        if deferSave { return }-        do { try context.save() }-        catch { context.rollback(); throw DefinitionError.saveFailed }-        MutationEffects.saved(context)-        onChange()+  }++  private func clearStandaloneSchedule(_ medication: Medication) {+    medication.remindersEnabled = false+    medication.scheduleStartedAt = nil+    medication.scheduleGenerationID = nil+    medication.dosesPerDay = nil+    medication.intervalMinutes = nil+    medication.firstReminderMinuteOfDay = nil+    medication.dayStartMinuteOfDay = nil+    medication.dayEndMinuteOfDay = nil+    medication.minimumIntervalMinutes = nil+    medication.fixedTimesData = nil+  }++  private func medication(_ id: UUID) throws -> Medication? {+    try context.fetch(FetchDescriptor<Medication>(predicate: #Predicate { $0.id == id })).first+  }+  private func treatment(_ id: UUID) throws -> Treatment? {+    try context.fetch(FetchDescriptor<Treatment>(predicate: #Predicate { $0.id == id })).first+  }+  private func timedRoutine(_ id: UUID) throws -> Routine? {+    try context.fetch(FetchDescriptor<Routine>(predicate: #Predicate { $0.id == id })).first+  }+  private func validName(_ value: String) throws -> String {+    let name = value.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !name.isEmpty else { throw DefinitionError.missingName }+    return name+  }+  private func validateTimer(rounds: Int, duration: Int) throws {+    guard rounds >= 1, duration >= 1 else { throw DefinitionError.invalidTimer }+  }+  private func save() throws {+    if deferSave { return }+    do { try context.save() } catch {+      context.rollback()+      throw DefinitionError.saveFailed     }+    MutationEffects.saved(context)+    onChange()+  } }
Meddy/Meddy/Services/RoutineSessionService.swift Modified
diff --git a/Meddy/Meddy/Services/RoutineSessionService.swift b/Meddy/Meddy/Services/RoutineSessionService.swiftindex b52dc90..000aa8e 100644--- a/Meddy/Meddy/Services/RoutineSessionService.swift+++ b/Meddy/Meddy/Services/RoutineSessionService.swift@@ -3,642 +3,661 @@ import SwiftData  @MainActor final class RoutineSessionService {-    private let context: ModelContext-    private let now: () -> Date-    private let deferSave: Bool-    private var transactionDepth = 0-    var onChange: () -> Void = {}+  let context: ModelContext+  let now: () -> Date+  private let deferSave: Bool+  private var transactionDepth = 0+  var onChange: () -> Void = {} -    init(context: ModelContext, now: @escaping () -> Date = Date.init, deferSave: Bool = false) {-        self.deferSave = deferSave-        self.context = context-        self.now = now-        context.autosaveEnabled = false-    }+  init(context: ModelContext, now: @escaping () -> Date = Date.init, deferSave: Bool = false) {+    self.deferSave = deferSave+    self.context = context+    self.now = now+    context.autosaveEnabled = false+  } -    func start(_ routine: Routine, runID: UUID = UUID(), occurrenceKey: String? = nil, source: AdministrationSource = .phone, deviceID: String? = nil, scheduledLocalDate: String? = nil, scheduledTimeZoneID: String? = nil, slotID: UUID? = nil, scheduledAt: Date? = nil) throws -> RoutineRun {-        _ = try ProfileAccess.owner(routine, context: context)-        if let existing = try run(runID) { try ProfileAccess.same(existing, routine, context: context); return existing }-        if let occurrenceKey,-           let existing = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.occurrenceKey == occurrenceKey })).first { try ProfileAccess.same(existing, routine, context: context); return existing }-        var definition = try RoutineService(context: context).freeze(routine)-        if let occurrenceKey, let slotID, let scheduledLocalDate, let scheduledTimeZoneID {-            definition.occurrence = .init(key: occurrenceKey, slotID: slotID, localDate: scheduledLocalDate, timeZoneID: scheduledTimeZoneID, scheduledAt: scheduledAt)-        }-        return try transaction {-            let value = RoutineRun(routine: routine, runID: runID)-            value.profileLifecycleID = try ProfileAccess.lifecycle(routine, context: context)-            value.occurrenceKey = occurrenceKey-            value.scheduledLocalDate = scheduledLocalDate; value.scheduledTimeZoneID = scheduledTimeZoneID-            value.slotID = slotID; value.scheduledAt = scheduledAt-            value.definitionSnapshotData = try encode(definition)-            value.stepProgressData = try encode(OrderedCheckpoint(definition: definition))-            if definition.kind == .timedRounds {-                value.timerCheckpointData = try encode(TimerCheckpoint(rounds: definition.roundCount ?? 0, durationSeconds: definition.roundDurationSeconds ?? 0))-            }-            value.processedActionIDsData = try encode([UUID]())-            value.startedAt = now(); value.updatedAt = now()-            value.sourceRaw = source.rawValue; value.executionDeviceID = deviceID-            context.insert(value)-            return value-        }-    }+  func start(+    _ routine: Routine, runID: UUID = UUID(), occurrenceKey: String? = nil,+    source: AdministrationSource = .phone, deviceID: String? = nil,+    scheduledLocalDate: String? = nil, scheduledTimeZoneID: String? = nil, slotID: UUID? = nil,+    scheduledAt: Date? = nil+  ) throws -> RoutineRun {+    _ = try ProfileAccess.owner(routine, context: context)+    if let existing = try run(runID) {+      try ProfileAccess.same(existing, routine, context: context)+      return existing+    }+    if let occurrenceKey,+      let existing = try context.fetch(+        FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.occurrenceKey == occurrenceKey })+      ).first {+      try ProfileAccess.same(existing, routine, context: context)+      return existing+    }+    var definition = try RoutineService(context: context).freeze(routine)+    if let occurrenceKey, let slotID, let scheduledLocalDate, let scheduledTimeZoneID {+      definition.occurrence = .init(+        key: occurrenceKey, slotID: slotID, localDate: scheduledLocalDate,+        timeZoneID: scheduledTimeZoneID, scheduledAt: scheduledAt)+    }+    return try transaction {+      let value = RoutineRun(routine: routine, runID: runID)+      value.profileLifecycleID = try ProfileAccess.lifecycle(routine, context: context)+      value.occurrenceKey = occurrenceKey+      value.scheduledLocalDate = scheduledLocalDate+      value.scheduledTimeZoneID = scheduledTimeZoneID+      value.slotID = slotID+      value.scheduledAt = scheduledAt+      value.definitionSnapshotData = try encode(definition)+      value.stepProgressData = try encode(OrderedCheckpoint(definition: definition))+      if definition.kind == .timedRounds {+        value.timerCheckpointData = try encode(+          TimerCheckpoint(+            rounds: definition.roundCount ?? 0,+            durationSeconds: definition.roundDurationSeconds ?? 0))+      }+      value.processedActionIDsData = try encode([UUID]())+      value.startedAt = now()+      value.updatedAt = now()+      value.sourceRaw = source.rawValue+      value.executionDeviceID = deviceID+      context.insert(value)+      return value+    }+  } -    func importWatchRun(_ cached: CompanionRun, deviceID: String, timestamp: Date) throws -> RoutineRun {-        try CompanionOwnership.validate(cached)-        if let existing = try run(cached.id) {-            try ProfileAccess.action(cached.profileID ?? cached.definition.profileID, version: cached.ownershipVersion, lifecycle: cached.profileLifecycleID, target: existing, context: context)-            return existing-        }-        guard !cached.isDeleted, Set(cached.definition.steps.map(\.id)).count == cached.definition.steps.count,-              cached.definition.steps.allSatisfy({ $0.position >= 0 }) else { throw ExecutionError.invalidSnapshot }-        let routineID = cached.definition.routineID-        guard let routine = try context.fetch(FetchDescriptor<Routine>(predicate: #Predicate { $0.id == routineID })).first else { throw ExecutionError.unknownRun }-        try ProfileAccess.action(cached.profileID ?? cached.definition.profileID, version: cached.ownershipVersion, lifecycle: cached.profileLifecycleID, target: routine, context: context)-        for step in cached.definition.steps {-            let owner: UUID-            switch step.kind {-            case .medication: owner = try ProfileAccess.owner(ProfileAccess.canonical(Medication.self, id: step.targetID, context: context), context: context)-            case .treatment: owner = try ProfileAccess.owner(ProfileAccess.canonical(Treatment.self, id: step.targetID, context: context), context: context)-            case .timedRoutine: owner = try ProfileAccess.owner(ProfileAccess.canonical(Routine.self, id: step.targetID, context: context), context: context)-            }-            guard owner == routine.profileID else { throw ProfileError.conflictingOwnership }-        }-        if let occurrence = cached.definition.occurrence {-            guard cached.id == ScheduleCalendar.identity(occurrence.key) else { throw ExecutionError.invalidSnapshot }-        }-        return try transaction {-            let value = RoutineRun(routine: routine, runID: cached.id)-            value.profileLifecycleID = cached.profileLifecycleID ?? ProfileIdentity.selfLifecycle-            value.definitionSnapshotData = try encode(cached.definition)-            value.stepProgressData = try encode(OrderedCheckpoint(definition: cached.definition))-            value.definitionRevision = cached.definition.revision-            value.occurrenceKey = cached.definition.occurrence?.key-            value.slotID = cached.definition.occurrence?.slotID-            value.scheduledLocalDate = cached.definition.occurrence?.localDate-            value.scheduledTimeZoneID = cached.definition.occurrence?.timeZoneID-            value.scheduledAt = cached.definition.occurrence?.scheduledAt-            value.parentRoutineRunID = cached.parentRunID; value.parentRoutineStepID = cached.parentStepID-            if cached.definition.kind == .timedRounds { value.timerCheckpointData = try encode(TimerCheckpoint(rounds: cached.definition.roundCount ?? 0, durationSeconds: cached.definition.roundDurationSeconds ?? 0)) }-            value.processedActionIDsData = try encode([UUID]())-            value.startedAt = cached.startedAt ?? timestamp; value.sourceRaw = "watch"; value.executionDeviceID = deviceID-            context.insert(value)-            if let parentID = cached.parentRunID, let stepID = cached.parentStepID {-                guard let parent = try self.run(parentID), let step = try definition(parent).steps.first(where: { $0.id == stepID }), step.kind == .timedRoutine,-                      step.targetID == cached.definition.routineID, step.roundCount == cached.definition.roundCount,-                      step.roundDurationSeconds == cached.definition.roundDurationSeconds else { throw ExecutionError.invalidSnapshot }-                var progress = try self.progress(parent)-                guard let index = progress.steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-                if let other = progress.steps[index].canonicalEventID, other != cached.id {-                    try progress.invalidate(stepID: stepID, audit: .init(actionID: cached.id, timestamp: timestamp, reason: "Distinct Watch child timer overlaps the saved child", previousState: progress.steps[index].state, previousEventID: other))-                } else {-                    progress.steps[index].canonicalEventID = cached.id; progress.steps[index].state = .inProgress-                }-                try saveProgress(progress, run: parent)-            }-            return value-        }-    }+  func definition(_ run: RoutineRun) throws -> FrozenRoutineDefinition {+    let owner = try ProfileAccess.owner(run, context: context)+    let value = try decode(FrozenRoutineDefinition.self, run.definitionSnapshotData)+    guard (value.profileID ?? ProfileIdentity.me) == owner,+      value.steps.allSatisfy({ ($0.profileID ?? ProfileIdentity.me) == owner }),+      owner == ProfileIdentity.me+        || value.ownershipVersion == ProfileIdentity.ownershipVersion+          && value.steps.allSatisfy({ $0.ownershipVersion == ProfileIdentity.ownershipVersion })+    else { throw ProfileError.conflictingOwnership }+    return value+  }+  func progress(_ run: RoutineRun) throws -> OrderedCheckpoint {+    _ = try ProfileAccess.owner(run, context: context)+    return try decode(OrderedCheckpoint.self, run.stepProgressData)+  }+  func timer(_ run: RoutineRun) throws -> TimerCheckpoint {+    _ = try ProfileAccess.owner(run, context: context)+    guard let data = run.timerCheckpointData else { throw ExecutionError.invalidTimer }+    return try decode(TimerCheckpoint.self, data)+  } -    func importWatchTimer(_ run: RoutineRun, checkpoint incoming: TimerCheckpoint, actionID: UUID, timestamp: Date, expectedRevision: Int?, deviceID: String) throws {-        var ids = try actionIDs(run)-        guard !ids.contains(actionID) else { return }-        guard !run.isDeleted else { return }-        let frozen = try definition(run)-        guard incoming.roundCount == frozen.roundCount, incoming.durationSeconds == Double(frozen.roundDurationSeconds ?? 0),-              (0...incoming.roundCount).contains(incoming.completedRounds), incoming.accumulatedActiveSeconds >= 0,-              incoming.accumulatedActiveSeconds.isFinite else { throw ExecutionError.invalidTimer }-        let conflict = expectedRevision.map { $0 != run.revision } ?? false-        try transaction {-            var checkpoint = incoming-            if checkpoint.phase == .running { checkpoint.phase = .interrupted; checkpoint.anchor = nil; checkpoint.deadline = nil }-            // Never reverse a phone completion with an older Watch checkpoint.-            if !run.wasCompleted || checkpoint.phase == .completed {-                run.timerCheckpointData = try encode(checkpoint)-                run.completedRounds = checkpoint.completedRounds-                run.wasCompleted = checkpoint.phase == .completed-                run.completedAt = run.wasCompleted ? (run.completedAt ?? timestamp) : nil-                run.statusRaw = run.wasCompleted ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")-                run.endedAt = checkpoint.phase == .ended ? timestamp : nil-            }-            if conflict || timestamp > now() { run.statusRaw = "needsReview" }-            ids.append(actionID); run.processedActionIDsData = try encode(ids)-            run.executionDeviceID = deviceID; run.revision += 1; run.updatedAt = now()-            if incoming.phase == .completed, let parentID = run.parentRoutineRunID, let stepID = run.parentRoutineStepID, let parent = try self.run(parentID) {-                try complete(parent, stepID: stepID, eventID: run.id, actionID: actionID, timestamp: timestamp, allowReportedConflict: true, extraReview: conflict ? "Watch timing overlaps another saved checkpoint" : nil)-            }-        }-    }+  func recordMedication(+    _ action: AdministrationAction, in run: RoutineRun, stepID: UUID, expectedRevision: Int? = nil+  ) throws -> Administration {+    let target = try ProfileAccess.canonical(+      Medication.self, id: action.medicationID, context: context)+    try ProfileAccess.same(target, run, context: context)+    try ProfileAccess.action(+      action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID,+      target: target, context: context)+    let step = try frozenStep(run, stepID: stepID, kind: .medication)+    guard step.targetID == action.medicationID else { throw ExecutionError.ineligibleLog }+    let eventID = action.eventID+    if let existing = try context.fetch(+      FetchDescriptor<Administration>(predicate: #Predicate { $0.id == eventID })+    ).first {+      try ProfileAccess.same(existing, run, context: context)+      guard existing.medicationID == action.medicationID else { throw ExecutionError.ineligibleLog }+      if existing.isDeleted || (existing.routineRunID == run.id && existing.routineStepID == stepID) {+        if existing.routineRunID == run.id { try reconcile(run) }+        return existing+      }+      throw existing.routineRunID == nil ? ExecutionError.ineligibleLog : .linkedElsewhere+    }+    try action.dose.validate()+    guard action.source == .watch || action.timestamp <= now() else {+      throw RecordingError.futureTime+    }+    let targetID = action.medicationID+    guard+      let medication = try context.fetch(+        FetchDescriptor<Medication>(predicate: #Predicate { $0.id == targetID })+      ).first+    else { throw ExecutionError.ineligibleLog }+    return try transaction {+      let event = Administration(action: action, medication: medication)+      event.routineRunID = run.id+      event.routineStepID = stepID+      event.createdAt = now()+      event.updatedAt = now()+      event.hasClockMismatch = action.timestamp > now()+      context.insert(event)+      try complete(+        run, stepID: stepID, eventID: event.id, actionID: action.eventID,+        timestamp: action.timestamp,+        allowReportedConflict: action.source == .watch || action.source == .manualHistory,+        expectedRevision: expectedRevision,+        extraReview: event.hasClockMismatch ? "Reported device clock differs from the phone" : nil)+      return event+    }+  } -    func reviewTimer(_ run: RoutineRun, actionID: UUID) throws {-        var ids = try actionIDs(run)-        if ids.contains(actionID) { return }-        guard run.statusRaw == "needsReview", !run.isDeleted else { throw ExecutionError.invalidTransition }-        let checkpoint = try timer(run)-        try transaction {-            run.statusRaw = checkpoint.phase == .completed ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")-            ids.append(actionID); run.processedActionIDsData = try encode(ids)-            run.revision += 1; run.updatedAt = now()-        }-    }+  func recordTreatment(+    _ action: TreatmentAction, in run: RoutineRun, stepID: UUID, expectedRevision: Int? = nil+  ) throws -> TreatmentCompletion {+    let target = try ProfileAccess.canonical(+      Treatment.self, id: action.treatmentID, context: context)+    try ProfileAccess.same(target, run, context: context)+    try ProfileAccess.action(+      action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID,+      target: target, context: context)+    let step = try frozenStep(run, stepID: stepID, kind: .treatment)+    guard step.targetID == action.treatmentID else { throw ExecutionError.ineligibleLog }+    let eventID = action.eventID+    if let existing = try context.fetch(+      FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == eventID })+    ).first {+      try ProfileAccess.same(existing, run, context: context)+      guard existing.treatmentID == action.treatmentID else { throw ExecutionError.ineligibleLog }+      if existing.isDeleted || (existing.routineRunID == run.id && existing.routineStepID == stepID) {+        if existing.routineRunID == run.id { try reconcile(run) }+        return existing+      }+      throw existing.routineRunID == nil ? ExecutionError.ineligibleLog : .linkedElsewhere+    }+    guard action.source == .watch || action.timestamp <= now() else {+      throw DefinitionError.futureTime+    }+    let targetID = action.treatmentID+    guard+      let treatment = try context.fetch(+        FetchDescriptor<Treatment>(predicate: #Predicate { $0.id == targetID })+      ).first+    else { throw ExecutionError.ineligibleLog }+    return try transaction {+      let event = TreatmentCompletion(+        treatment: treatment, timestamp: action.timestamp, source: action.source,+        eventID: action.eventID)+      event.instructionsSnapshot = action.instructionsSnapshot+      event.routineRunID = run.id+      event.routineStepID = stepID+      event.createdAt = now()+      event.updatedAt = now()+      event.hasClockMismatch = action.timestamp > now()+      context.insert(event)+      try complete(+        run, stepID: stepID, eventID: event.id, actionID: action.eventID,+        timestamp: action.timestamp,+        allowReportedConflict: action.source == .watch || action.source == .manualHistory,+        expectedRevision: expectedRevision,+        extraReview: event.hasClockMismatch ? "Reported device clock differs from the phone" : nil)+      return event+    }+  } -    func handoff(_ run: RoutineRun, toDeviceID deviceID: String, actionID: UUID, expectedRevision: Int?) throws {-        var ids = try actionIDs(run)-        guard !ids.contains(actionID) else { return }-        guard !run.isDeleted, expectedRevision == run.revision else { throw ExecutionError.invalidTransition }-        try transaction {-            if run.timerCheckpointData != nil {-                var checkpoint = try timer(run)-                if checkpoint.phase == .running { try checkpoint.pause(at: ExecutionClock.sample()) }-                run.timerCheckpointData = try encode(checkpoint)-            } else {-                var value = try progress(run)-                try stopChildTimers(in: &value, parent: run, operation: .pause, clock: ExecutionClock.sample())-                if value.phase == .active { try value.pause() }-                run.stepProgressData = try encode(value)-                for child in try context.fetch(FetchDescriptor<RoutineRun>()) where child.parentRoutineRunID == run.id && !child.isDeleted {-                    child.executionDeviceID = deviceID-                    child.revision += 1; child.updatedAt = now()-                }-            }-            run.executionDeviceID = deviceID-            if run.timerCheckpointData != nil {-                let checkpoint = try timer(run)-                run.statusRaw = checkpoint.phase == .completed ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")-            } else { run.statusRaw = try progress(run).phase.rawValue }-            ids.append(actionID); run.processedActionIDsData = try encode(ids)-            run.revision += 1; run.updatedAt = now()-        }-    }+  func link(+    _ event: Administration, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(),+    confirmedMove: Bool = false+  ) throws {+    try ProfileAccess.same(event, run, context: context)+    let step = try frozenStep(run, stepID: stepID, kind: .medication)+    guard !event.isDeleted, event.medicationID == step.targetID,+      ["asNeeded", "routineManaged"].contains(event.scheduleTypeAtRecordingRaw)+    else { throw ExecutionError.ineligibleLog }+    if event.routineRunID == run.id && event.routineStepID == stepID { return }+    if event.routineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }+    try transaction {+      try detachForMove(+        runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id,+        actionID: actionID)+      try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)+      event.routineRunID = run.id+      event.routineStepID = stepID+      event.updatedAt = now()+      try complete(+        run, stepID: stepID, eventID: event.id, actionID: actionID, timestamp: event.timestamp,+        allowReportedConflict: true)+    }+  } -    func definition(_ run: RoutineRun) throws -> FrozenRoutineDefinition {-        let owner = try ProfileAccess.owner(run, context: context)-        let value = try decode(FrozenRoutineDefinition.self, run.definitionSnapshotData)-        guard (value.profileID ?? ProfileIdentity.me) == owner,-              value.steps.allSatisfy({ ($0.profileID ?? ProfileIdentity.me) == owner }),-              owner == ProfileIdentity.me || value.ownershipVersion == ProfileIdentity.ownershipVersion && value.steps.allSatisfy({ $0.ownershipVersion == ProfileIdentity.ownershipVersion }) else { throw ProfileError.conflictingOwnership }-        return value-    }-    func progress(_ run: RoutineRun) throws -> OrderedCheckpoint { _ = try ProfileAccess.owner(run, context: context); return try decode(OrderedCheckpoint.self, run.stepProgressData) }-    func timer(_ run: RoutineRun) throws -> TimerCheckpoint {-        _ = try ProfileAccess.owner(run, context: context)-        guard let data = run.timerCheckpointData else { throw ExecutionError.invalidTimer }-        return try decode(TimerCheckpoint.self, data)-    }+  func link(+    _ event: TreatmentCompletion, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(),+    confirmedMove: Bool = false+  ) throws {+    try ProfileAccess.same(event, run, context: context)+    let step = try frozenStep(run, stepID: stepID, kind: .treatment)+    guard !event.isDeleted, event.treatmentID == step.targetID else {+      throw ExecutionError.ineligibleLog+    }+    if event.routineRunID == run.id && event.routineStepID == stepID { return }+    if event.routineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }+    try transaction {+      try detachForMove(+        runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id,+        actionID: actionID)+      try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)+      event.routineRunID = run.id+      event.routineStepID = stepID+      event.updatedAt = now()+      try complete(+        run, stepID: stepID, eventID: event.id, actionID: actionID, timestamp: event.timestamp,+        allowReportedConflict: true)+    }+  } -    func recordMedication(_ action: AdministrationAction, in run: RoutineRun, stepID: UUID, expectedRevision: Int? = nil) throws -> Administration {-        let target = try ProfileAccess.canonical(Medication.self, id: action.medicationID, context: context)-        try ProfileAccess.same(target, run, context: context)-        try ProfileAccess.action(action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID, target: target, context: context)-        let step = try frozenStep(run, stepID: stepID, kind: .medication)-        guard step.targetID == action.medicationID else { throw ExecutionError.ineligibleLog }-        let eventID = action.eventID-        if let existing = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.id == eventID })).first {-            try ProfileAccess.same(existing, run, context: context)-            guard existing.medicationID == action.medicationID else { throw ExecutionError.ineligibleLog }-            if existing.isDeleted || (existing.routineRunID == run.id && existing.routineStepID == stepID) {-                if existing.routineRunID == run.id { try reconcile(run) }-                return existing-            }-            throw existing.routineRunID == nil ? ExecutionError.ineligibleLog : .linkedElsewhere-        }-        try action.dose.validate()-        guard action.source == .watch || action.timestamp <= now() else { throw RecordingError.futureTime }-        let targetID = action.medicationID-        guard let medication = try context.fetch(FetchDescriptor<Medication>(predicate: #Predicate { $0.id == targetID })).first else { throw ExecutionError.ineligibleLog }-        return try transaction {-            let event = Administration(action: action, medication: medication)-            event.routineRunID = run.id; event.routineStepID = stepID-            event.createdAt = now(); event.updatedAt = now()-            event.hasClockMismatch = action.timestamp > now()-            context.insert(event)-            try complete(run, stepID: stepID, eventID: event.id, actionID: action.eventID, timestamp: action.timestamp,-                         allowReportedConflict: action.source == .watch || action.source == .manualHistory, expectedRevision: expectedRevision,-                         extraReview: event.hasClockMismatch ? "Reported device clock differs from the phone" : nil)-            return event-        }-    }+  func correct(+    _ event: Administration, timestamp: Date, dose: RecordedDoseSnapshot, delete: Bool = false,+    actionID: UUID = UUID()+  ) throws {+    _ = try ProfileAccess.owner(event, context: context)+    if try isCorrectionReplay(runID: event.routineRunID, actionID: actionID) { return }+    guard !event.isDeleted || delete else { throw ExecutionError.ineligibleLog }+    try dose.validate()+    guard timestamp <= now() else { throw RecordingError.futureTime }+    try transaction {+      try invalidateLink(+        runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id,+        actionID: actionID, reason: delete ? "Administration undone" : "Administration corrected",+        previousTimestamp: event.timestamp,+        previousDose: .init(+          description: event.doseDescriptionSnapshot, amount: event.doseAmount, unit: event.doseUnit+        ))+      event.timestamp = timestamp+      event.doseDescriptionSnapshot = dose.description+      event.doseAmount = dose.amount+      event.doseUnit = dose.unit+      event.isDeleted = delete+      event.hasClockMismatch = false+      event.updatedAt = now()+    }+  } -    func recordTreatment(_ action: TreatmentAction, in run: RoutineRun, stepID: UUID, expectedRevision: Int? = nil) throws -> TreatmentCompletion {-        let target = try ProfileAccess.canonical(Treatment.self, id: action.treatmentID, context: context)-        try ProfileAccess.same(target, run, context: context)-        try ProfileAccess.action(action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID, target: target, context: context)-        let step = try frozenStep(run, stepID: stepID, kind: .treatment)-        guard step.targetID == action.treatmentID else { throw ExecutionError.ineligibleLog }-        let eventID = action.eventID-        if let existing = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == eventID })).first {-            try ProfileAccess.same(existing, run, context: context)-            guard existing.treatmentID == action.treatmentID else { throw ExecutionError.ineligibleLog }-            if existing.isDeleted || (existing.routineRunID == run.id && existing.routineStepID == stepID) {-                if existing.routineRunID == run.id { try reconcile(run) }-                return existing-            }-            throw existing.routineRunID == nil ? ExecutionError.ineligibleLog : .linkedElsewhere-        }-        guard action.source == .watch || action.timestamp <= now() else { throw DefinitionError.futureTime }-        let targetID = action.treatmentID-        guard let treatment = try context.fetch(FetchDescriptor<Treatment>(predicate: #Predicate { $0.id == targetID })).first else { throw ExecutionError.ineligibleLog }-        return try transaction {-            let event = TreatmentCompletion(treatment: treatment, timestamp: action.timestamp, source: action.source, eventID: action.eventID)-            event.instructionsSnapshot = action.instructionsSnapshot-            event.routineRunID = run.id; event.routineStepID = stepID-            event.createdAt = now(); event.updatedAt = now(); event.hasClockMismatch = action.timestamp > now()-            context.insert(event)-            try complete(run, stepID: stepID, eventID: event.id, actionID: action.eventID, timestamp: action.timestamp,-                         allowReportedConflict: action.source == .watch || action.source == .manualHistory, expectedRevision: expectedRevision,-                         extraReview: event.hasClockMismatch ? "Reported device clock differs from the phone" : nil)-            return event-        }-    }+  func correct(+    _ event: TreatmentCompletion, timestamp: Date, delete: Bool = false, actionID: UUID = UUID()+  ) throws {+    _ = try ProfileAccess.owner(event, context: context)+    if try isCorrectionReplay(runID: event.routineRunID, actionID: actionID) { return }+    guard !event.isDeleted || delete else { throw ExecutionError.ineligibleLog }+    guard timestamp <= now() else { throw DefinitionError.futureTime }+    try transaction {+      try invalidateLink(+        runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id,+        actionID: actionID,+        reason: delete ? "Treatment completion undone" : "Treatment completion corrected",+        previousTimestamp: event.timestamp)+      event.timestamp = timestamp+      event.isDeleted = delete+      event.hasClockMismatch = false+      event.updatedAt = now()+    }+  } -    func link(_ event: Administration, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(), confirmedMove: Bool = false) throws {-        try ProfileAccess.same(event, run, context: context)-        let step = try frozenStep(run, stepID: stepID, kind: .medication)-        guard !event.isDeleted, event.medicationID == step.targetID,-              ["asNeeded", "routineManaged"].contains(event.scheduleTypeAtRecordingRaw) else { throw ExecutionError.ineligibleLog }-        if event.routineRunID == run.id && event.routineStepID == stepID { return }-        if event.routineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }-        try transaction {-            try detachForMove(runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id, actionID: actionID)-            try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)-            event.routineRunID = run.id; event.routineStepID = stepID; event.updatedAt = now()-            try complete(run, stepID: stepID, eventID: event.id, actionID: actionID, timestamp: event.timestamp, allowReportedConflict: true)-        }-    }+  func skip(_ run: RoutineRun, stepID: UUID, actionID: UUID, reason: String) throws {+    try mutate(run, actionID: actionID) { value in+      try stopChildTimers(+        in: &value, parent: run, operation: .end, clock: ExecutionClock.sample(),+        selectedStepID: stepID)+      try value.skip(stepID: stepID, actionID: actionID, at: now(), reason: reason)+    }+  }+  func continueAfterSkip(_ run: RoutineRun, stepID: UUID, actionID: UUID) throws {+    try mutate(run, actionID: actionID) { value in try value.continueAfterSkip(stepID: stepID) }+  }+  func pause(_ run: RoutineRun, actionID: UUID, clock: ClockSample = ExecutionClock.sample()) throws {+    try mutate(run, actionID: actionID) { value in+      try stopChildTimers(in: &value, parent: run, operation: .pause, clock: clock)+      if value.phase == .active { try value.pause() }+    }+  }+  func resume(_ run: RoutineRun, actionID: UUID) throws {+    try transaction {+      try renewLifecycle(run)+      try mutate(run, actionID: actionID) { try $0.resume() }+    }+  }+  func end(_ run: RoutineRun, actionID: UUID, clock: ClockSample = ExecutionClock.sample()) throws {+    try mutate(run, actionID: actionID) { value in+      try stopChildTimers(in: &value, parent: run, operation: .end, clock: clock)+      if value.phase != .completed && value.phase != .finishedWithSkips { try value.end(at: now()) }+    }+  }+  func reopen(_ run: RoutineRun, actionID: UUID) throws {+    try transaction {+      try renewLifecycle(run)+      try mutate(run, actionID: actionID) { try $0.reopen() }+    }+  } -    func link(_ event: TreatmentCompletion, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(), confirmedMove: Bool = false) throws {-        try ProfileAccess.same(event, run, context: context)-        let step = try frozenStep(run, stepID: stepID, kind: .treatment)-        guard !event.isDeleted, event.treatmentID == step.targetID else { throw ExecutionError.ineligibleLog }-        if event.routineRunID == run.id && event.routineStepID == stepID { return }-        if event.routineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }-        try transaction {-            try detachForMove(runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id, actionID: actionID)-            try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)-            event.routineRunID = run.id; event.routineStepID = stepID; event.updatedAt = now()-            try complete(run, stepID: stepID, eventID: event.id, actionID: actionID, timestamp: event.timestamp, allowReportedConflict: true)-        }-    }+  func resolveReview(_ run: RoutineRun, stepID: UUID, resolution: ReviewResolution, actionID: UUID)+    throws {+    if try actionIDs(run).contains(actionID) { return }+    let state = try progress(run)+    guard let step = state.steps.first(where: { $0.id == stepID }), step.state == .needsReview+    else { throw ExecutionError.invalidTransition }+    if resolution == .acceptCanonical {+      guard let id = step.canonicalEventID else { throw ExecutionError.ineligibleLog }+      switch step.targetKind {+      case .medication:+        guard+          let event = try context.fetch(+            FetchDescriptor<Administration>(predicate: #Predicate { $0.id == id })+          ).first,+          !event.isDeleted, !event.hasClockMismatch, event.medicationID == step.targetID,+          event.routineRunID == run.id, event.routineStepID == step.id+        else { throw ExecutionError.ineligibleLog }+      case .treatment:+        guard+          let event = try context.fetch(+            FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == id })+          ).first,+          !event.isDeleted, !event.hasClockMismatch, event.treatmentID == step.targetID,+          event.routineRunID == run.id, event.routineStepID == step.id+        else { throw ExecutionError.ineligibleLog }+      case .timedRoutine:+        guard let event = try self.run(id), !event.isDeleted, event.wasCompleted,+          event.routineID == step.targetID,+          event.parentRoutineRunID == run.id, event.parentRoutineStepID == step.id+        else { throw ExecutionError.ineligibleLog }+      }+    }+    let runID = run.id+    var reviewedIDs: [UUID] = []+    if resolution == .acceptCanonical {+      switch step.targetKind {+      case .medication:+        reviewedIDs = try context.fetch(+          FetchDescriptor<Administration>(+            predicate: #Predicate {+              $0.routineRunID == runID && $0.routineStepID == stepID && !$0.isDeleted+            })+        ).map(\.id)+      case .treatment:+        reviewedIDs = try context.fetch(+          FetchDescriptor<TreatmentCompletion>(+            predicate: #Predicate {+              $0.routineRunID == runID && $0.routineStepID == stepID && !$0.isDeleted+            })+        ).map(\.id)+      case .timedRoutine: reviewedIDs = step.canonicalEventID.map { [$0] } ?? []+      }+    }+    try mutate(run, actionID: actionID) { value in+      try value.resolveReview(+        stepID: stepID, resolution: resolution, actionID: actionID, at: now(),+        reviewedEventIDs: reviewedIDs)+    }+  } -    func correct(_ event: Administration, timestamp: Date, dose: RecordedDoseSnapshot, delete: Bool = false, actionID: UUID = UUID()) throws {-        _ = try ProfileAccess.owner(event, context: context)-        if try isCorrectionReplay(runID: event.routineRunID, actionID: actionID) { return }-        guard !event.isDeleted || delete else { throw ExecutionError.ineligibleLog }-        try dose.validate()-        guard timestamp <= now() else { throw RecordingError.futureTime }-        try transaction {-            try invalidateLink(runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id, actionID: actionID, reason: delete ? "Administration undone" : "Administration corrected", previousTimestamp: event.timestamp, previousDose: .init(description: event.doseDescriptionSnapshot, amount: event.doseAmount, unit: event.doseUnit))-            event.timestamp = timestamp; event.doseDescriptionSnapshot = dose.description-            event.doseAmount = dose.amount; event.doseUnit = dose.unit-            event.isDeleted = delete; event.hasClockMismatch = false; event.updatedAt = now()-        }-    }+  func link(+    _ event: RoutineRun, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(),+    confirmedMove: Bool = false+  ) throws {+    try ProfileAccess.same(event, run, context: context)+    let step = try frozenStep(run, stepID: stepID, kind: .timedRoutine)+    guard !event.isDeleted, event.wasCompleted, event.routineID == step.targetID else {+      throw ExecutionError.ineligibleLog+    }+    if event.parentRoutineRunID == run.id && event.parentRoutineStepID == stepID { return }+    if event.parentRoutineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }+    try transaction {+      try detachForMove(+        runID: event.parentRoutineRunID, stepID: event.parentRoutineStepID, eventID: event.id,+        actionID: actionID)+      try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)+      event.parentRoutineRunID = run.id+      event.parentRoutineStepID = stepID+      event.updatedAt = now()+      let old = try definition(event)+      let mismatch =+        old.roundCount != step.roundCount || old.roundDurationSeconds != step.roundDurationSeconds+      try complete(+        run, stepID: stepID, eventID: event.id, actionID: actionID,+        timestamp: event.completedAt ?? event.startedAt ?? now(), allowReportedConflict: true,+        extraReview: mismatch ? "The existing timer used different saved round settings" : nil)+    }+  } -    func correct(_ event: TreatmentCompletion, timestamp: Date, delete: Bool = false, actionID: UUID = UUID()) throws {-        _ = try ProfileAccess.owner(event, context: context)-        if try isCorrectionReplay(runID: event.routineRunID, actionID: actionID) { return }-        guard !event.isDeleted || delete else { throw ExecutionError.ineligibleLog }-        guard timestamp <= now() else { throw DefinitionError.futureTime }-        try transaction {-            try invalidateLink(runID: event.routineRunID, stepID: event.routineStepID, eventID: event.id, actionID: actionID, reason: delete ? "Treatment completion undone" : "Treatment completion corrected", previousTimestamp: event.timestamp)-            event.timestamp = timestamp; event.isDeleted = delete; event.hasClockMismatch = false; event.updatedAt = now()-        }-    }+  private func replaceReviewedLink(+    in run: RoutineRun, stepID: UUID, replacementID: UUID, actionID: UUID+  ) throws {+    var value = try progress(run)+    guard let index = value.steps.firstIndex(where: { $0.id == stepID }),+      value.steps[index].state == .needsReview,+      let oldID = value.steps[index].canonicalEventID, oldID != replacementID+    else { return }+    switch value.steps[index].targetKind {+    case .medication:+      if let old = try context.fetch(+        FetchDescriptor<Administration>(predicate: #Predicate { $0.id == oldID })+      ).first {+        try ProfileAccess.same(old, run, context: context)+        guard old.routineRunID == run.id, old.routineStepID == stepID else {+          throw ProfileError.conflictingOwnership+        }+        old.routineRunID = nil+        old.routineStepID = nil+        old.updatedAt = now()+      }+    case .treatment:+      if let old = try context.fetch(+        FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == oldID })+      ).first {+        try ProfileAccess.same(old, run, context: context)+        guard old.routineRunID == run.id, old.routineStepID == stepID else {+          throw ProfileError.conflictingOwnership+        }+        old.routineRunID = nil+        old.routineStepID = nil+        old.updatedAt = now()+      }+    case .timedRoutine:+      if let old = try self.run(oldID) {+        try ProfileAccess.same(old, run, context: context)+        guard old.parentRoutineRunID == run.id, old.parentRoutineStepID == stepID else {+          throw ProfileError.conflictingOwnership+        }+        old.parentRoutineRunID = nil+        old.parentRoutineStepID = nil+        old.updatedAt = now()+      }+    }+    let old = value.steps[index]+    value.steps[index].audit.append(+      .init(+        actionID: actionID, timestamp: now(),+        reason: "Explicitly replaced the reviewed canonical link; original history retained",+        previousState: old.state, previousEventID: oldID))+    value.steps[index].canonicalEventID = nil+    try saveProgress(value, run: run)+  } -    func skip(_ run: RoutineRun, stepID: UUID, actionID: UUID, reason: String) throws {-        try mutate(run, actionID: actionID) { value in-            try stopChildTimers(in: &value, parent: run, operation: .end, clock: ExecutionClock.sample(), selectedStepID: stepID)-            try value.skip(stepID: stepID, actionID: actionID, at: now(), reason: reason)-        }-    }-    func continueAfterSkip(_ run: RoutineRun, stepID: UUID, actionID: UUID) throws {-        try mutate(run, actionID: actionID) { value in try value.continueAfterSkip(stepID: stepID) }-    }-    func pause(_ run: RoutineRun, actionID: UUID, clock: ClockSample = ExecutionClock.sample()) throws {-        try mutate(run, actionID: actionID) { value in-            try stopChildTimers(in: &value, parent: run, operation: .pause, clock: clock)-            if value.phase == .active { try value.pause() }-        }-    }-    func resume(_ run: RoutineRun, actionID: UUID) throws {-        try transaction { try renewLifecycle(run); try mutate(run, actionID: actionID) { try $0.resume() } }-    }-    func end(_ run: RoutineRun, actionID: UUID, clock: ClockSample = ExecutionClock.sample()) throws {-        try mutate(run, actionID: actionID) { value in-            try stopChildTimers(in: &value, parent: run, operation: .end, clock: clock)-            if value.phase != .completed && value.phase != .finishedWithSkips { try value.end(at: now()) }-        }-    }-    func reopen(_ run: RoutineRun, actionID: UUID) throws {-        try transaction { try renewLifecycle(run); try mutate(run, actionID: actionID) { try $0.reopen() } }-    }+  private func isCorrectionReplay(runID: UUID?, actionID: UUID) throws -> Bool {+    guard let runID else { return false }+    guard let run = try self.run(runID) else { throw ExecutionError.unknownRun }+    return try actionIDs(run).contains(actionID)+  } -    func beginTimedStep(_ parent: RoutineRun, stepID: UUID) throws -> RoutineRun {-        let step = try frozenStep(parent, stepID: stepID, kind: .timedRoutine)-        var value = try progress(parent)-        guard value.nextReadyStepID == stepID, let index = value.steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.stepNotReady }-        if let id = value.steps[index].canonicalEventID, let existing = try run(id) { return existing }-        let targetID = step.targetID-        guard let routine = try context.fetch(FetchDescriptor<Routine>(predicate: #Predicate { $0.id == targetID })).first else { throw ExecutionError.ineligibleLog }-        return try transaction {-            let child = RoutineRun(routine: routine)-            try ProfileAccess.same(parent, routine, context: context)-            child.profileLifecycleID = try ProfileAccess.lifecycle(parent, context: context)-            var frozen = FrozenRoutineDefinition(routineID: step.targetID, revision: parent.definitionRevision, kind: .timedRounds, name: step.name, instructions: step.instructions, roundCount: step.roundCount, roundDurationSeconds: step.roundDurationSeconds, betweenRoundInstructions: step.betweenRoundInstructions, steps: [])-            frozen.profileID = parent.profileID; frozen.ownershipVersion = parent.ownershipVersion; frozen.profileLifecycleID = child.profileLifecycleID-            child.definitionSnapshotData = try encode(frozen)-            child.stepProgressData = try encode(OrderedCheckpoint(definition: frozen))-            child.timerCheckpointData = try encode(TimerCheckpoint(rounds: step.roundCount ?? 0, durationSeconds: step.roundDurationSeconds ?? 0))-            child.processedActionIDsData = try encode([UUID]())-            child.parentRoutineRunID = parent.id; child.parentRoutineStepID = stepID-            child.startedAt = now(); child.sourceRaw = parent.sourceRaw-            child.executionDeviceID = parent.executionDeviceID-            context.insert(child)-            value.steps[index].canonicalEventID = child.id-            value.steps[index].state = .inProgress; value.steps[index].startedAt = now()-            try saveProgress(value, run: parent)-            return child-        }-    }+  // Repair a recoverable older/partially saved checkpoint from canonical facts, never create a fact.+  func reconcile(_ run: RoutineRun) throws {+    guard !run.isDeleted, try definition(run).kind == .ordered else { return }+    let runID = run.id+    let medications = try context.fetch(+      FetchDescriptor<Administration>(predicate: #Predicate { $0.routineRunID == runID }))+    let treatments = try context.fetch(+      FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.routineRunID == runID }))+    for event in medications { try ProfileAccess.same(event, run, context: context) }+    for event in treatments { try ProfileAccess.same(event, run, context: context) }+    var value = try progress(run)+    let before = value+    for step in value.steps.sorted(by: { $0.position < $1.position }) {+      let facts: [(UUID, Date, Bool)]+      switch step.targetKind {+      case .medication:+        facts = medications.filter {+          $0.routineStepID == step.id && $0.medicationID == step.targetID+        }.map { ($0.id, $0.timestamp, $0.isDeleted) }+      case .treatment:+        facts = treatments.filter { $0.routineStepID == step.id && $0.treatmentID == step.targetID }+          .map { ($0.id, $0.timestamp, $0.isDeleted) }+      case .timedRoutine: continue+      }+      if step.state == .needsReview || step.state == .skipped { continue }+      let live = facts.filter { !$0.2 }+      if (live.count > 1 && !Set(live.map { $0.0 }).isSubset(of: Set(step.reviewedEventIDs)))+        || facts.contains(where: { $0.0 == step.canonicalEventID && $0.2 }) {+        try value.invalidate(+          stepID: step.id,+          audit: .init(+            actionID: UUID(), timestamp: now(),+            reason: "Canonical history requires checkpoint review", previousState: step.state,+            previousEventID: step.canonicalEventID))+      } else if [.pending, .inProgress, .paused].contains(step.state), step.canonicalEventID == nil,+        let fact = live.first {+        try value.markCompleted(+          stepID: step.id, eventID: fact.0, at: fact.1, actionID: fact.0, reportedOutOfOrder: true)+      }+    }+    if value != before { try transaction { try saveProgress(value, run: run) } }+  } -    @discardableResult func changeTimer(_ run: RoutineRun, actionID: UUID, clock: ClockSample, operation: TimerOperation) throws -> Bool {-        guard !run.isDeleted else { throw ExecutionError.unknownRun }-        if [.start, .resume, .reopen].contains(operation), run.statusRaw == "needsReview" { throw ExecutionError.invalidTransition }-        var ids = try actionIDs(run)-        if ids.contains(actionID) { return false }-        if let parentID = run.parentRoutineRunID, [.start, .resume].contains(operation) {-            guard let parent = try self.run(parentID), try progress(parent).phase == .active else { throw ExecutionError.stepNotReady }-        }-        var checkpoint = try timer(run)-        let before = checkpoint-        switch operation {-        case .start: try checkpoint.start(at: clock)-        case .pause: try checkpoint.pause(at: clock)-        case .resume: try checkpoint.resume(at: clock)-        case .end: try checkpoint.end(at: clock)-        case .reopen: try checkpoint.reopen()-        case .advance: checkpoint.advance(at: clock)-        }-        guard checkpoint != before else { return false }-        return try transaction {-            if [.start, .resume, .reopen].contains(operation) { try renewLifecycle(run) }-            run.timerCheckpointData = try encode(checkpoint)-            run.completedRounds = checkpoint.completedRounds-            run.wasCompleted = checkpoint.phase == .completed-            switch checkpoint.phase {-            case .completed: run.statusRaw = "completed"; run.completedAt = run.completedAt ?? clock.wall-            case .ended: run.statusRaw = "endedIncomplete"; run.endedAt = clock.wall-            case .paused, .interrupted: run.statusRaw = "paused"; run.completedAt = nil-            default: run.statusRaw = "active"; run.endedAt = nil; run.completedAt = nil-            }-            ids.append(actionID); run.processedActionIDsData = try encode(ids)-            run.revision += 1; run.updatedAt = now()-            if let parentID = run.parentRoutineRunID, let stepID = run.parentRoutineStepID {-                guard let parent = try self.run(parentID) else { throw ExecutionError.unknownRun }-                if checkpoint.phase == .completed {-                    try complete(parent, stepID: stepID, eventID: run.id, actionID: actionID, timestamp: clock.wall, allowReportedConflict: true)-                } else {-                    var value = try progress(parent)-                    guard let index = value.steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-                    if value.steps[index].state != .skipped && value.steps[index].state != .needsReview {-                        value.steps[index].state = [.paused, .interrupted, .ended].contains(checkpoint.phase) ? .paused : .inProgress-                    }-                    try saveProgress(value, run: parent)-                }-            }-            return true-        }-    }+  private func mutate(+    _ run: RoutineRun, actionID: UUID, body: (inout OrderedCheckpoint) throws -> Void+  ) throws {+    guard !run.isDeleted else { throw ExecutionError.unknownRun }+    var ids = try actionIDs(run)+    if ids.contains(actionID) { return }+    try transaction {+      var value = try progress(run)+      try body(&value)+      ids.append(actionID)+      run.processedActionIDsData = try encode(ids)+      try saveProgress(value, run: run)+    }+  } -    private func stopChildTimers(in value: inout OrderedCheckpoint, parent: RoutineRun, operation: TimerOperation, clock: ClockSample, selectedStepID: UUID? = nil) throws {-        for index in value.steps.indices {-            let step = value.steps[index]-            guard step.targetKind == .timedRoutine, selectedStepID == nil || selectedStepID == step.id,-                  [.inProgress, .paused].contains(step.state), let id = step.canonicalEventID,-                  let child = try run(id) else { continue }-            try ProfileAccess.same(child, parent, context: context)-            let frozen = try frozenStep(parent, stepID: step.id, kind: .timedRoutine)-            guard child.parentRoutineRunID == parent.id, child.parentRoutineStepID == step.id, child.routineID == frozen.targetID else { throw ProfileError.conflictingOwnership }-            var checkpoint = try timer(child)-            if operation == .pause {-                if checkpoint.phase == .running { try checkpoint.pause(at: clock) } else { continue }-            } else {-                if [.completed, .ended].contains(checkpoint.phase) { continue }-                try checkpoint.end(at: clock)-            }-            child.timerCheckpointData = try encode(checkpoint)-            child.completedRounds = checkpoint.completedRounds-            child.wasCompleted = checkpoint.phase == .completed-            child.statusRaw = checkpoint.phase == .completed ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")-            child.completedAt = checkpoint.phase == .completed ? clock.wall : nil-            child.endedAt = checkpoint.phase == .ended ? clock.wall : nil-            child.revision += 1; child.updatedAt = now()-            if checkpoint.phase == .completed {-                try value.markCompleted(stepID: step.id, eventID: child.id, at: clock.wall, actionID: UUID(), reportedOutOfOrder: true)-            } else { value.steps[index].state = .paused }-        }-    }+  func complete(+    _ run: RoutineRun, stepID: UUID, eventID: UUID, actionID: UUID, timestamp: Date,+    allowReportedConflict: Bool, expectedRevision: Int? = nil, extraReview: String? = nil+  ) throws {+    guard !run.isDeleted else { throw ExecutionError.unknownRun }+    var value = try progress(run)+    try value.markCompleted(+      stepID: stepID, eventID: eventID, at: timestamp, actionID: actionID,+      reportedOutOfOrder: allowReportedConflict)+    let orderMismatch = value.steps.contains {+      $0.id != stepID && $0.position < (value.steps.first { $0.id == stepID }?.position ?? 0)+        && ($0.completedAt ?? .distantPast) > timestamp+    }+    if let reason = extraReview+      ?? ((expectedRevision != nil && expectedRevision != run.revision)+        ? "Reported checkpoint revision differs from the saved session"+        : (orderMismatch ? "Recorded times conflict with step order" : nil)),+      let step = value.steps.first(where: { $0.id == stepID }) {+      try value.invalidate(+        stepID: stepID,+        audit: .init(+          actionID: actionID, timestamp: now(), reason: reason, previousState: step.state,+          previousEventID: step.canonicalEventID))+    }+    var ids = try actionIDs(run)+    if !ids.contains(actionID) { ids.append(actionID) }+    run.processedActionIDsData = try encode(ids)+    try saveProgress(value, run: run)+  } -    func resolveReview(_ run: RoutineRun, stepID: UUID, resolution: ReviewResolution, actionID: UUID) throws {-        if try actionIDs(run).contains(actionID) { return }-        let state = try progress(run)-        guard let step = state.steps.first(where: { $0.id == stepID }), step.state == .needsReview else { throw ExecutionError.invalidTransition }-        if resolution == .acceptCanonical {-            guard let id = step.canonicalEventID else { throw ExecutionError.ineligibleLog }-            switch step.targetKind {-            case .medication:-                guard let event = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.id == id })).first,-                      !event.isDeleted, !event.hasClockMismatch, event.medicationID == step.targetID,-                      event.routineRunID == run.id, event.routineStepID == step.id else { throw ExecutionError.ineligibleLog }-            case .treatment:-                guard let event = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == id })).first,-                      !event.isDeleted, !event.hasClockMismatch, event.treatmentID == step.targetID,-                      event.routineRunID == run.id, event.routineStepID == step.id else { throw ExecutionError.ineligibleLog }-            case .timedRoutine:-                guard let event = try self.run(id), !event.isDeleted, event.wasCompleted, event.routineID == step.targetID,-                      event.parentRoutineRunID == run.id, event.parentRoutineStepID == step.id else { throw ExecutionError.ineligibleLog }-            }-        }-        let runID = run.id-        var reviewedIDs: [UUID] = []-        if resolution == .acceptCanonical {-            switch step.targetKind {-            case .medication: reviewedIDs = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.routineRunID == runID && $0.routineStepID == stepID && !$0.isDeleted })).map(\.id)-            case .treatment: reviewedIDs = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.routineRunID == runID && $0.routineStepID == stepID && !$0.isDeleted })).map(\.id)-            case .timedRoutine: reviewedIDs = step.canonicalEventID.map { [$0] } ?? []-            }-        }-        try mutate(run, actionID: actionID) { value in try value.resolveReview(stepID: stepID, resolution: resolution, actionID: actionID, at: now(), reviewedEventIDs: reviewedIDs) }-    }+  private func detachForMove(runID: UUID?, stepID: UUID?, eventID: UUID, actionID: UUID) throws {+    guard let runID, let stepID else { return }+    guard let oldRun = try run(runID) else { throw ExecutionError.unknownRun }+    var value = try progress(oldRun)+    guard let index = value.steps.firstIndex(where: { $0.id == stepID }) else {+      throw ExecutionError.unknownStep+    }+    let old = value.steps[index]+    try value.invalidate(+      stepID: stepID,+      audit: .init(+        actionID: actionID, timestamp: now(), reason: "Canonical log moved to another saved step",+        previousState: old.state, previousEventID: eventID))+    if value.steps[index].canonicalEventID == eventID { value.steps[index].canonicalEventID = nil }+    try saveProgress(value, run: oldRun)+  } -    func link(_ event: RoutineRun, to run: RoutineRun, stepID: UUID, actionID: UUID = UUID(), confirmedMove: Bool = false) throws {-        try ProfileAccess.same(event, run, context: context)-        let step = try frozenStep(run, stepID: stepID, kind: .timedRoutine)-        guard !event.isDeleted, event.wasCompleted, event.routineID == step.targetID else { throw ExecutionError.ineligibleLog }-        if event.parentRoutineRunID == run.id && event.parentRoutineStepID == stepID { return }-        if event.parentRoutineRunID != nil && !confirmedMove { throw ExecutionError.linkedElsewhere }-        try transaction {-            try detachForMove(runID: event.parentRoutineRunID, stepID: event.parentRoutineStepID, eventID: event.id, actionID: actionID)-            try replaceReviewedLink(in: run, stepID: stepID, replacementID: event.id, actionID: actionID)-            event.parentRoutineRunID = run.id; event.parentRoutineStepID = stepID; event.updatedAt = now()-            let old = try definition(event)-            let mismatch = old.roundCount != step.roundCount || old.roundDurationSeconds != step.roundDurationSeconds-            try complete(run, stepID: stepID, eventID: event.id, actionID: actionID, timestamp: event.completedAt ?? event.startedAt ?? now(), allowReportedConflict: true, extraReview: mismatch ? "The existing timer used different saved round settings" : nil)-        }-    }+  private func invalidateLink(+    runID: UUID?, stepID: UUID?, eventID: UUID, actionID: UUID, reason: String,+    previousTimestamp: Date?, previousDose: RecordedDoseSnapshot? = nil+  ) throws {+    guard let runID, let stepID else { return }+    guard let run = try self.run(runID) else { throw ExecutionError.unknownRun }+    var ids = try actionIDs(run)+    if ids.contains(actionID) { return }+    var value = try progress(run)+    guard let step = value.steps.first(where: { $0.id == stepID }) else {+      throw ExecutionError.unknownStep+    }+    try value.invalidate(+      stepID: stepID,+      audit: .init(+        actionID: actionID, timestamp: now(), reason: reason, previousState: step.state,+        previousEventID: eventID, previousTimestamp: previousTimestamp, previousDose: previousDose))+    ids.append(actionID)+    run.processedActionIDsData = try encode(ids)+    try saveProgress(value, run: run)+  } -    private func replaceReviewedLink(in run: RoutineRun, stepID: UUID, replacementID: UUID, actionID: UUID) throws {-        var value = try progress(run)-        guard let index = value.steps.firstIndex(where: { $0.id == stepID }), value.steps[index].state == .needsReview,-              let oldID = value.steps[index].canonicalEventID, oldID != replacementID else { return }-        switch value.steps[index].targetKind {-        case .medication:-            if let old = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.id == oldID })).first {-                try ProfileAccess.same(old, run, context: context)-                guard old.routineRunID == run.id, old.routineStepID == stepID else { throw ProfileError.conflictingOwnership }-                old.routineRunID = nil; old.routineStepID = nil; old.updatedAt = now()-            }-        case .treatment:-            if let old = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == oldID })).first {-                try ProfileAccess.same(old, run, context: context)-                guard old.routineRunID == run.id, old.routineStepID == stepID else { throw ProfileError.conflictingOwnership }-                old.routineRunID = nil; old.routineStepID = nil; old.updatedAt = now()-            }-        case .timedRoutine:-            if let old = try self.run(oldID) { try ProfileAccess.same(old, run, context: context); guard old.parentRoutineRunID == run.id, old.parentRoutineStepID == stepID else { throw ProfileError.conflictingOwnership }; old.parentRoutineRunID = nil; old.parentRoutineStepID = nil; old.updatedAt = now() }-        }-        let old = value.steps[index]-        value.steps[index].audit.append(.init(actionID: actionID, timestamp: now(), reason: "Explicitly replaced the reviewed canonical link; original history retained", previousState: old.state, previousEventID: oldID))-        value.steps[index].canonicalEventID = nil-        try saveProgress(value, run: run)-    }--    private func isCorrectionReplay(runID: UUID?, actionID: UUID) throws -> Bool {-        guard let runID else { return false }-        guard let run = try self.run(runID) else { throw ExecutionError.unknownRun }-        return try actionIDs(run).contains(actionID)-    }--    // Repair a recoverable older/partially saved checkpoint from canonical facts, never create a fact.-    func reconcile(_ run: RoutineRun) throws {-        guard !run.isDeleted, try definition(run).kind == .ordered else { return }-        let runID = run.id-        let medications = try context.fetch(FetchDescriptor<Administration>(predicate: #Predicate { $0.routineRunID == runID }))-        let treatments = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.routineRunID == runID }))-        for event in medications { try ProfileAccess.same(event, run, context: context) }-        for event in treatments { try ProfileAccess.same(event, run, context: context) }-        var value = try progress(run)-        let before = value-        for step in value.steps.sorted(by: { $0.position < $1.position }) {-            let facts: [(UUID, Date, Bool)]-            switch step.targetKind {-            case .medication:-                facts = medications.filter { $0.routineStepID == step.id && $0.medicationID == step.targetID }.map { ($0.id, $0.timestamp, $0.isDeleted) }-            case .treatment:-                facts = treatments.filter { $0.routineStepID == step.id && $0.treatmentID == step.targetID }.map { ($0.id, $0.timestamp, $0.isDeleted) }-            case .timedRoutine: continue-            }-            if step.state == .needsReview || step.state == .skipped { continue }-            let live = facts.filter { !$0.2 }-            if (live.count > 1 && !Set(live.map { $0.0 }).isSubset(of: Set(step.reviewedEventIDs))) || facts.contains(where: { $0.0 == step.canonicalEventID && $0.2 }) {-                try value.invalidate(stepID: step.id, audit: .init(actionID: UUID(), timestamp: now(), reason: "Canonical history requires checkpoint review", previousState: step.state, previousEventID: step.canonicalEventID))-            } else if [.pending, .inProgress, .paused].contains(step.state), step.canonicalEventID == nil, let fact = live.first {-                try value.markCompleted(stepID: step.id, eventID: fact.0, at: fact.1, actionID: fact.0, reportedOutOfOrder: true)-            }-        }-        if value != before { try transaction { try saveProgress(value, run: run) } }-    }--    private func mutate(_ run: RoutineRun, actionID: UUID, body: (inout OrderedCheckpoint) throws -> Void) throws {-        guard !run.isDeleted else { throw ExecutionError.unknownRun }-        var ids = try actionIDs(run)-        if ids.contains(actionID) { return }-        try transaction {-            var value = try progress(run)-            try body(&value)-            ids.append(actionID); run.processedActionIDsData = try encode(ids)-            try saveProgress(value, run: run)-        }-    }--    private func complete(_ run: RoutineRun, stepID: UUID, eventID: UUID, actionID: UUID, timestamp: Date, allowReportedConflict: Bool, expectedRevision: Int? = nil, extraReview: String? = nil) throws {-        guard !run.isDeleted else { throw ExecutionError.unknownRun }-        var value = try progress(run)-        try value.markCompleted(stepID: stepID, eventID: eventID, at: timestamp, actionID: actionID, reportedOutOfOrder: allowReportedConflict)-        let orderMismatch = value.steps.contains { $0.id != stepID && $0.position < (value.steps.first { $0.id == stepID }?.position ?? 0) && ($0.completedAt ?? .distantPast) > timestamp }-        if let reason = extraReview ?? ((expectedRevision != nil && expectedRevision != run.revision) ? "Reported checkpoint revision differs from the saved session" : (orderMismatch ? "Recorded times conflict with step order" : nil)),-           let step = value.steps.first(where: { $0.id == stepID }) {-            try value.invalidate(stepID: stepID, audit: .init(actionID: actionID, timestamp: now(), reason: reason, previousState: step.state, previousEventID: step.canonicalEventID))-        }-        var ids = try actionIDs(run)-        if !ids.contains(actionID) { ids.append(actionID) }-        run.processedActionIDsData = try encode(ids)-        try saveProgress(value, run: run)-    }--    private func detachForMove(runID: UUID?, stepID: UUID?, eventID: UUID, actionID: UUID) throws {-        guard let runID, let stepID else { return }-        guard let oldRun = try run(runID) else { throw ExecutionError.unknownRun }-        var value = try progress(oldRun)-        guard let index = value.steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-        let old = value.steps[index]-        try value.invalidate(stepID: stepID, audit: .init(actionID: actionID, timestamp: now(), reason: "Canonical log moved to another saved step", previousState: old.state, previousEventID: eventID))-        if value.steps[index].canonicalEventID == eventID { value.steps[index].canonicalEventID = nil }-        try saveProgress(value, run: oldRun)-    }--    private func invalidateLink(runID: UUID?, stepID: UUID?, eventID: UUID, actionID: UUID, reason: String, previousTimestamp: Date?, previousDose: RecordedDoseSnapshot? = nil) throws {-        guard let runID, let stepID else { return }-        guard let run = try self.run(runID) else { throw ExecutionError.unknownRun }-        var ids = try actionIDs(run)-        if ids.contains(actionID) { return }-        var value = try progress(run)-        guard let step = value.steps.first(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-        try value.invalidate(stepID: stepID, audit: .init(actionID: actionID, timestamp: now(), reason: reason, previousState: step.state, previousEventID: eventID, previousTimestamp: previousTimestamp, previousDose: previousDose))-        ids.append(actionID); run.processedActionIDsData = try encode(ids)-        try saveProgress(value, run: run)-    }--    private func saveProgress(_ value: OrderedCheckpoint, run: RoutineRun) throws {-        run.stepProgressData = try encode(value)-        run.statusRaw = value.phase.rawValue-        run.wasCompleted = value.phase == .completed-        run.completedAt = [.completed, .finishedWithSkips].contains(value.phase) ? (run.completedAt ?? now()) : nil-        run.endedAt = value.endedAt-        run.revision += 1; run.updatedAt = now()-    }-    private func frozenStep(_ run: RoutineRun, stepID: UUID, kind: RoutineStepTargetKind) throws -> FrozenRoutineStep {-        guard let step = try definition(run).steps.first(where: { $0.id == stepID }), step.kind == kind else { throw ExecutionError.unknownStep }-        return step-    }-    private func renewLifecycle(_ run: RoutineRun) throws {-        let lifecycle = try ProfileAccess.lifecycle(run, context: context)-        run.profileLifecycleID = lifecycle-        var value = try definition(run); value.profileID = run.profileID; value.ownershipVersion = run.ownershipVersion; value.profileLifecycleID = lifecycle-        for index in value.steps.indices { value.steps[index].profileID = run.profileID; value.steps[index].ownershipVersion = run.ownershipVersion; value.steps[index].profileLifecycleID = lifecycle }-        run.definitionSnapshotData = try encode(value)-    }-    private func actionIDs(_ run: RoutineRun) throws -> [UUID] {-        _ = try ProfileAccess.owner(run, context: context)-        return run.processedActionIDsData.isEmpty ? [] : try decode([UUID].self, run.processedActionIDsData)-    }-    private func run(_ id: UUID) throws -> RoutineRun? {-        try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first-    }-    private func encode<T: Encodable>(_ value: T) throws -> Data { try JSONEncoder().encode(value) }-    private func decode<T: Decodable>(_ type: T.Type, _ data: Data) throws -> T {-        do { return try JSONDecoder().decode(type, from: data) }-        catch { throw ExecutionError.invalidSnapshot }-    }-    private func transaction<T>(_ body: () throws -> T) throws -> T {-        transactionDepth += 1; defer { transactionDepth -= 1 }-        do {-            let value = try body()-            if !deferSave && transactionDepth == 1 {-                do { try context.save() } catch { throw ExecutionError.saveFailed }-                MutationEffects.saved(context); onChange()-            }-            return value-        } catch { context.rollback(); throw error }-    }+  func saveProgress(_ value: OrderedCheckpoint, run: RoutineRun) throws {+    run.stepProgressData = try encode(value)+    run.statusRaw = value.phase.rawValue+    run.wasCompleted = value.phase == .completed+    run.completedAt =+      [.completed, .finishedWithSkips].contains(value.phase) ? (run.completedAt ?? now()) : nil+    run.endedAt = value.endedAt+    run.revision += 1+    run.updatedAt = now()+  }+  func frozenStep(_ run: RoutineRun, stepID: UUID, kind: RoutineStepTargetKind) throws+    -> FrozenRoutineStep {+    guard let step = try definition(run).steps.first(where: { $0.id == stepID }), step.kind == kind+    else { throw ExecutionError.unknownStep }+    return step+  }+  func renewLifecycle(_ run: RoutineRun) throws {+    let lifecycle = try ProfileAccess.lifecycle(run, context: context)+    run.profileLifecycleID = lifecycle+    var value = try definition(run)+    value.profileID = run.profileID+    value.ownershipVersion = run.ownershipVersion+    value.profileLifecycleID = lifecycle+    for index in value.steps.indices {+      value.steps[index].profileID = run.profileID+      value.steps[index].ownershipVersion = run.ownershipVersion+      value.steps[index].profileLifecycleID = lifecycle+    }+    run.definitionSnapshotData = try encode(value)+  }+  func actionIDs(_ run: RoutineRun) throws -> [UUID] {+    _ = try ProfileAccess.owner(run, context: context)+    return run.processedActionIDsData.isEmpty+      ? [] : try decode([UUID].self, run.processedActionIDsData)+  }+  func run(_ id: UUID) throws -> RoutineRun? {+    try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first+  }+  func encode<T: Encodable>(_ value: T) throws -> Data { try JSONEncoder().encode(value) }+  private func decode<T: Decodable>(_ type: T.Type, _ data: Data) throws -> T {+    do { return try JSONDecoder().decode(type, from: data) } catch {+      throw ExecutionError.invalidSnapshot+    }+  }+  func transaction<T>(_ body: () throws -> T) throws -> T {+    transactionDepth += 1+    defer { transactionDepth -= 1 }+    do {+      let value = try body()+      if !deferSave && transactionDepth == 1 {+        do { try context.save() } catch { throw ExecutionError.saveFailed }+        MutationEffects.saved(context)+        onChange()+      }+      return value+    } catch {+      context.rollback()+      throw error+    }+  } }
Meddy/Meddy/Services/RoutineSessionTimerService.swift Added
diff --git a/Meddy/Meddy/Services/RoutineSessionTimerService.swift b/Meddy/Meddy/Services/RoutineSessionTimerService.swiftnew file mode 100644index 0000000..54c807b--- /dev/null+++ b/Meddy/Meddy/Services/RoutineSessionTimerService.swift@@ -0,0 +1,371 @@+import Foundation+import SwiftData++// Timer and Watch operations share RoutineSessionService's transaction and ownership checks.+extension RoutineSessionService {+  func importWatchRun(_ cached: CompanionRun, deviceID: String, timestamp: Date) throws+    -> RoutineRun {+    try CompanionOwnership.validate(cached)+    if let existing = try run(cached.id) {+      try ProfileAccess.action(+        cached.profileID ?? cached.definition.profileID, version: cached.ownershipVersion,+        lifecycle: cached.profileLifecycleID, target: existing, context: context)+      return existing+    }+    guard !cached.isDeleted,+      Set(cached.definition.steps.map(\.id)).count == cached.definition.steps.count,+      cached.definition.steps.allSatisfy({ $0.position >= 0 })+    else { throw ExecutionError.invalidSnapshot }+    let routineID = cached.definition.routineID+    guard+      let routine = try context.fetch(+        FetchDescriptor<Routine>(predicate: #Predicate { $0.id == routineID })+      ).first+    else { throw ExecutionError.unknownRun }+    try ProfileAccess.action(+      cached.profileID ?? cached.definition.profileID, version: cached.ownershipVersion,+      lifecycle: cached.profileLifecycleID, target: routine, context: context)+    for step in cached.definition.steps {+      let owner: UUID+      switch step.kind {+      case .medication:+        owner = try ProfileAccess.owner(+          ProfileAccess.canonical(Medication.self, id: step.targetID, context: context),+          context: context)+      case .treatment:+        owner = try ProfileAccess.owner(+          ProfileAccess.canonical(Treatment.self, id: step.targetID, context: context),+          context: context)+      case .timedRoutine:+        owner = try ProfileAccess.owner(+          ProfileAccess.canonical(Routine.self, id: step.targetID, context: context),+          context: context)+      }+      guard owner == routine.profileID else { throw ProfileError.conflictingOwnership }+    }+    if let occurrence = cached.definition.occurrence {+      guard cached.id == ScheduleCalendar.identity(occurrence.key) else {+        throw ExecutionError.invalidSnapshot+      }+    }+    return try transaction {+      let value = RoutineRun(routine: routine, runID: cached.id)+      value.profileLifecycleID = cached.profileLifecycleID ?? ProfileIdentity.selfLifecycle+      value.definitionSnapshotData = try encode(cached.definition)+      value.stepProgressData = try encode(OrderedCheckpoint(definition: cached.definition))+      value.definitionRevision = cached.definition.revision+      value.occurrenceKey = cached.definition.occurrence?.key+      value.slotID = cached.definition.occurrence?.slotID+      value.scheduledLocalDate = cached.definition.occurrence?.localDate+      value.scheduledTimeZoneID = cached.definition.occurrence?.timeZoneID+      value.scheduledAt = cached.definition.occurrence?.scheduledAt+      value.parentRoutineRunID = cached.parentRunID+      value.parentRoutineStepID = cached.parentStepID+      if cached.definition.kind == .timedRounds {+        value.timerCheckpointData = try encode(+          TimerCheckpoint(+            rounds: cached.definition.roundCount ?? 0,+            durationSeconds: cached.definition.roundDurationSeconds ?? 0))+      }+      value.processedActionIDsData = try encode([UUID]())+      value.startedAt = cached.startedAt ?? timestamp+      value.sourceRaw = "watch"+      value.executionDeviceID = deviceID+      context.insert(value)+      if let parentID = cached.parentRunID, let stepID = cached.parentStepID {+        guard let parent = try self.run(parentID),+          let step = try definition(parent).steps.first(where: { $0.id == stepID }),+          step.kind == .timedRoutine,+          step.targetID == cached.definition.routineID,+          step.roundCount == cached.definition.roundCount,+          step.roundDurationSeconds == cached.definition.roundDurationSeconds+        else { throw ExecutionError.invalidSnapshot }+        var progress = try self.progress(parent)+        guard let index = progress.steps.firstIndex(where: { $0.id == stepID }) else {+          throw ExecutionError.unknownStep+        }+        if let other = progress.steps[index].canonicalEventID, other != cached.id {+          try progress.invalidate(+            stepID: stepID,+            audit: .init(+              actionID: cached.id, timestamp: timestamp,+              reason: "Distinct Watch child timer overlaps the saved child",+              previousState: progress.steps[index].state, previousEventID: other))+        } else {+          progress.steps[index].canonicalEventID = cached.id+          progress.steps[index].state = .inProgress+        }+        try saveProgress(progress, run: parent)+      }+      return value+    }+  }++  func importWatchTimer(+    _ run: RoutineRun, checkpoint incoming: TimerCheckpoint, actionID: UUID, timestamp: Date,+    expectedRevision: Int?, deviceID: String+  ) throws {+    var ids = try actionIDs(run)+    guard !ids.contains(actionID) else { return }+    guard !run.isDeleted else { return }+    let frozen = try definition(run)+    guard incoming.roundCount == frozen.roundCount,+      incoming.durationSeconds == Double(frozen.roundDurationSeconds ?? 0),+      (0...incoming.roundCount).contains(incoming.completedRounds),+      incoming.accumulatedActiveSeconds >= 0,+      incoming.accumulatedActiveSeconds.isFinite+    else { throw ExecutionError.invalidTimer }+    let conflict = expectedRevision.map { $0 != run.revision } ?? false+    try transaction {+      var checkpoint = incoming+      if checkpoint.phase == .running {+        checkpoint.phase = .interrupted+        checkpoint.anchor = nil+        checkpoint.deadline = nil+      }+      // Never reverse a phone completion with an older Watch checkpoint.+      if !run.wasCompleted || checkpoint.phase == .completed {+        run.timerCheckpointData = try encode(checkpoint)+        run.completedRounds = checkpoint.completedRounds+        run.wasCompleted = checkpoint.phase == .completed+        run.completedAt = run.wasCompleted ? (run.completedAt ?? timestamp) : nil+        run.statusRaw =+          run.wasCompleted+          ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")+        run.endedAt = checkpoint.phase == .ended ? timestamp : nil+      }+      if conflict || timestamp > now() { run.statusRaw = "needsReview" }+      ids.append(actionID)+      run.processedActionIDsData = try encode(ids)+      run.executionDeviceID = deviceID+      run.revision += 1+      run.updatedAt = now()+      if incoming.phase == .completed, let parentID = run.parentRoutineRunID,+        let stepID = run.parentRoutineStepID, let parent = try self.run(parentID) {+        try complete(+          parent, stepID: stepID, eventID: run.id, actionID: actionID, timestamp: timestamp,+          allowReportedConflict: true,+          extraReview: conflict ? "Watch timing overlaps another saved checkpoint" : nil)+      }+    }+  }++  func reviewTimer(_ run: RoutineRun, actionID: UUID) throws {+    var ids = try actionIDs(run)+    if ids.contains(actionID) { return }+    guard run.statusRaw == "needsReview", !run.isDeleted else {+      throw ExecutionError.invalidTransition+    }+    let checkpoint = try timer(run)+    try transaction {+      run.statusRaw =+        checkpoint.phase == .completed+        ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")+      ids.append(actionID)+      run.processedActionIDsData = try encode(ids)+      run.revision += 1+      run.updatedAt = now()+    }+  }++  func handoff(+    _ run: RoutineRun, toDeviceID deviceID: String, actionID: UUID, expectedRevision: Int?+  ) throws {+    var ids = try actionIDs(run)+    guard !ids.contains(actionID) else { return }+    guard !run.isDeleted, expectedRevision == run.revision else {+      throw ExecutionError.invalidTransition+    }+    try transaction {+      if run.timerCheckpointData != nil {+        var checkpoint = try timer(run)+        if checkpoint.phase == .running { try checkpoint.pause(at: ExecutionClock.sample()) }+        run.timerCheckpointData = try encode(checkpoint)+      } else {+        var value = try progress(run)+        try stopChildTimers(+          in: &value, parent: run, operation: .pause, clock: ExecutionClock.sample())+        if value.phase == .active { try value.pause() }+        run.stepProgressData = try encode(value)+        for child in try context.fetch(FetchDescriptor<RoutineRun>())+        where child.parentRoutineRunID == run.id && !child.isDeleted {+          child.executionDeviceID = deviceID+          child.revision += 1+          child.updatedAt = now()+        }+      }+      run.executionDeviceID = deviceID+      if run.timerCheckpointData != nil {+        let checkpoint = try timer(run)+        run.statusRaw =+          checkpoint.phase == .completed+          ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")+      } else {+        run.statusRaw = try progress(run).phase.rawValue+      }+      ids.append(actionID)+      run.processedActionIDsData = try encode(ids)+      run.revision += 1+      run.updatedAt = now()+    }+  }++  func beginTimedStep(_ parent: RoutineRun, stepID: UUID) throws -> RoutineRun {+    let step = try frozenStep(parent, stepID: stepID, kind: .timedRoutine)+    var value = try progress(parent)+    guard value.nextReadyStepID == stepID,+      let index = value.steps.firstIndex(where: { $0.id == stepID })+    else { throw ExecutionError.stepNotReady }+    if let id = value.steps[index].canonicalEventID, let existing = try run(id) { return existing }+    let targetID = step.targetID+    guard+      let routine = try context.fetch(+        FetchDescriptor<Routine>(predicate: #Predicate { $0.id == targetID })+      ).first+    else { throw ExecutionError.ineligibleLog }+    return try transaction {+      let child = RoutineRun(routine: routine)+      try ProfileAccess.same(parent, routine, context: context)+      child.profileLifecycleID = try ProfileAccess.lifecycle(parent, context: context)+      var frozen = FrozenRoutineDefinition(+        routineID: step.targetID, revision: parent.definitionRevision, kind: .timedRounds,+        name: step.name, instructions: step.instructions, roundCount: step.roundCount,+        roundDurationSeconds: step.roundDurationSeconds,+        betweenRoundInstructions: step.betweenRoundInstructions, steps: [])+      frozen.profileID = parent.profileID+      frozen.ownershipVersion = parent.ownershipVersion+      frozen.profileLifecycleID = child.profileLifecycleID+      child.definitionSnapshotData = try encode(frozen)+      child.stepProgressData = try encode(OrderedCheckpoint(definition: frozen))+      child.timerCheckpointData = try encode(+        TimerCheckpoint(+          rounds: step.roundCount ?? 0, durationSeconds: step.roundDurationSeconds ?? 0))+      child.processedActionIDsData = try encode([UUID]())+      child.parentRoutineRunID = parent.id+      child.parentRoutineStepID = stepID+      child.startedAt = now()+      child.sourceRaw = parent.sourceRaw+      child.executionDeviceID = parent.executionDeviceID+      context.insert(child)+      value.steps[index].canonicalEventID = child.id+      value.steps[index].state = .inProgress+      value.steps[index].startedAt = now()+      try saveProgress(value, run: parent)+      return child+    }+  }++  @discardableResult func changeTimer(+    _ run: RoutineRun, actionID: UUID, clock: ClockSample, operation: TimerOperation+  ) throws -> Bool {+    guard !run.isDeleted else { throw ExecutionError.unknownRun }+    if [.start, .resume, .reopen].contains(operation), run.statusRaw == "needsReview" {+      throw ExecutionError.invalidTransition+    }+    var ids = try actionIDs(run)+    if ids.contains(actionID) { return false }+    if let parentID = run.parentRoutineRunID, [.start, .resume].contains(operation) {+      guard let parent = try self.run(parentID), try progress(parent).phase == .active else {+        throw ExecutionError.stepNotReady+      }+    }+    var checkpoint = try timer(run)+    let before = checkpoint+    switch operation {+    case .start: try checkpoint.start(at: clock)+    case .pause: try checkpoint.pause(at: clock)+    case .resume: try checkpoint.resume(at: clock)+    case .end: try checkpoint.end(at: clock)+    case .reopen: try checkpoint.reopen()+    case .advance: checkpoint.advance(at: clock)+    }+    guard checkpoint != before else { return false }+    return try transaction {+      if [.start, .resume, .reopen].contains(operation) { try renewLifecycle(run) }+      run.timerCheckpointData = try encode(checkpoint)+      run.completedRounds = checkpoint.completedRounds+      run.wasCompleted = checkpoint.phase == .completed+      switch checkpoint.phase {+      case .completed:+        run.statusRaw = "completed"+        run.completedAt = run.completedAt ?? clock.wall+      case .ended:+        run.statusRaw = "endedIncomplete"+        run.endedAt = clock.wall+      case .paused, .interrupted:+        run.statusRaw = "paused"+        run.completedAt = nil+      default:+        run.statusRaw = "active"+        run.endedAt = nil+        run.completedAt = nil+      }+      ids.append(actionID)+      run.processedActionIDsData = try encode(ids)+      run.revision += 1+      run.updatedAt = now()+      if let parentID = run.parentRoutineRunID, let stepID = run.parentRoutineStepID {+        guard let parent = try self.run(parentID) else { throw ExecutionError.unknownRun }+        if checkpoint.phase == .completed {+          try complete(+            parent, stepID: stepID, eventID: run.id, actionID: actionID, timestamp: clock.wall,+            allowReportedConflict: true)+        } else {+          var value = try progress(parent)+          guard let index = value.steps.firstIndex(where: { $0.id == stepID }) else {+            throw ExecutionError.unknownStep+          }+          if value.steps[index].state != .skipped && value.steps[index].state != .needsReview {+            value.steps[index].state =+              [.paused, .interrupted, .ended].contains(checkpoint.phase) ? .paused : .inProgress+          }+          try saveProgress(value, run: parent)+        }+      }+      return true+    }+  }++  func stopChildTimers(+    in value: inout OrderedCheckpoint, parent: RoutineRun, operation: TimerOperation,+    clock: ClockSample, selectedStepID: UUID? = nil+  ) throws {+    for index in value.steps.indices {+      let step = value.steps[index]+      guard step.targetKind == .timedRoutine, selectedStepID == nil || selectedStepID == step.id,+        [.inProgress, .paused].contains(step.state), let id = step.canonicalEventID,+        let child = try run(id)+      else { continue }+      try ProfileAccess.same(child, parent, context: context)+      let frozen = try frozenStep(parent, stepID: step.id, kind: .timedRoutine)+      guard child.parentRoutineRunID == parent.id, child.parentRoutineStepID == step.id,+        child.routineID == frozen.targetID+      else { throw ProfileError.conflictingOwnership }+      var checkpoint = try timer(child)+      if operation == .pause {+        if checkpoint.phase == .running { try checkpoint.pause(at: clock) } else { continue }+      } else {+        if [.completed, .ended].contains(checkpoint.phase) { continue }+        try checkpoint.end(at: clock)+      }+      child.timerCheckpointData = try encode(checkpoint)+      child.completedRounds = checkpoint.completedRounds+      child.wasCompleted = checkpoint.phase == .completed+      child.statusRaw =+        checkpoint.phase == .completed+        ? "completed" : (checkpoint.phase == .ended ? "endedIncomplete" : "paused")+      child.completedAt = checkpoint.phase == .completed ? clock.wall : nil+      child.endedAt = checkpoint.phase == .ended ? clock.wall : nil+      child.revision += 1+      child.updatedAt = now()+      if checkpoint.phase == .completed {+        try value.markCompleted(+          stepID: step.id, eventID: child.id, at: clock.wall, actionID: UUID(),+          reportedOutOfOrder: true)+      } else {+        value.steps[index].state = .paused+      }+    }+  }++}
Meddy/Meddy/Services/ScheduleService.swift Modified
diff --git a/Meddy/Meddy/Services/ScheduleService.swift b/Meddy/Meddy/Services/ScheduleService.swiftindex 1cad794..3519cd1 100644--- a/Meddy/Meddy/Services/ScheduleService.swift+++ b/Meddy/Meddy/Services/ScheduleService.swift@@ -2,181 +2,286 @@ import Foundation import SwiftData  nonisolated struct MedicationScheduleDraft: Equatable {-    var mode: MedicationScheduleType-    var dosesPerDay: Int? = nil-    var dayStartMinute: Int? = nil-    var dayEndMinute: Int? = nil-    var minimumIntervalMinutes: Int? = nil-    var intervalMinutes: Int? = nil-    var firstReminderMinute: Int? = nil-    var fixedMinutes: [Int] = []-    var wakeOffsetMinutes: Int? = nil+  var mode: MedicationScheduleType+  var dosesPerDay: Int?+  var dayStartMinute: Int?+  var dayEndMinute: Int?+  var minimumIntervalMinutes: Int?+  var intervalMinutes: Int?+  var firstReminderMinute: Int?+  var fixedMinutes: [Int] = []+  var wakeOffsetMinutes: Int? }  @MainActor final class ScheduleService {-    private let context: ModelContext-    private let deferSave: Bool-    private let now: () -> Date-    private let calendar: Calendar-    var onChange: () -> Void = {}+  private let context: ModelContext+  private let deferSave: Bool+  private let now: () -> Date+  private let calendar: Calendar+  var onChange: () -> Void = {} -    init(context: ModelContext, now: @escaping () -> Date = Date.init, calendar: Calendar = .current, deferSave: Bool = false) {-        self.deferSave = deferSave-        self.context = context; self.now = now; self.calendar = calendar-        context.autosaveEnabled = false-    }+  init(+    context: ModelContext, now: @escaping () -> Date = Date.init, calendar: Calendar = .current,+    deferSave: Bool = false+  ) {+    self.deferSave = deferSave+    self.context = context+    self.now = now+    self.calendar = calendar+    context.autosaveEnabled = false+  } -    func configure(_ medication: Medication, draft: MedicationScheduleDraft, reminders: Bool) throws {-        _ = try ProfileAccess.owner(medication, context: context)-        guard medication.managedByRoutineID == nil && draft.mode != .routineManaged else { throw DefinitionError.otherOwner }-        try validate(draft)-        guard draft.mode != .asNeeded || !reminders else { throw DefinitionError.invalidSchedule }-        let current = try snapshot(medication)-        var normalised = draft-        normalised.fixedMinutes = Array(Set(normalised.fixedMinutes)).sorted()-        let oldDraft = MedicationScheduleDraft(mode: current.mode, dosesPerDay: current.dosesPerDay, dayStartMinute: current.dayStartMinute, dayEndMinute: current.dayEndMinute, minimumIntervalMinutes: current.minimumIntervalMinutes, intervalMinutes: current.intervalMinutes, firstReminderMinute: current.firstReminderMinute, fixedMinutes: current.fixedMinutes, wakeOffsetMinutes: current.wakeOffsetMinutes)-        if normalised == oldDraft {-            try transaction {-                if draft.mode == .afterWaking && reminders && !medication.remindersEnabled { medication.scheduleGenerationID = UUID(); medication.scheduleStartedAt = now() }-                medication.remindersEnabled = reminders-            }-            return-        }-        try transaction {-            medication.scheduleTypeRaw = draft.mode.rawValue-            medication.scheduleGenerationID = draft.mode == .asNeeded ? nil : UUID()-            medication.scheduleStartedAt = draft.mode == .asNeeded ? nil : now()-            medication.dosesPerDay = draft.mode == .spreadThroughDay ? draft.dosesPerDay : nil-            medication.dayStartMinuteOfDay = draft.mode == .spreadThroughDay ? draft.dayStartMinute : nil-            medication.dayEndMinuteOfDay = draft.mode == .spreadThroughDay ? draft.dayEndMinute : nil-            medication.minimumIntervalMinutes = draft.mode == .spreadThroughDay ? draft.minimumIntervalMinutes : nil-            medication.intervalMinutes = draft.mode == .interval ? draft.intervalMinutes : nil-            medication.firstReminderMinuteOfDay = draft.mode == .interval ? draft.firstReminderMinute : nil-            medication.fixedTimesData = draft.mode == .fixedTimes ? try JSONEncoder().encode(Array(Set(draft.fixedMinutes)).sorted()) : nil-            medication.wakeOffsetMinutes = draft.mode == .afterWaking ? draft.wakeOffsetMinutes : nil-            medication.remindersEnabled = reminders+  func configure(_ medication: Medication, draft: MedicationScheduleDraft, reminders: Bool) throws {+    _ = try ProfileAccess.owner(medication, context: context)+    guard medication.managedByRoutineID == nil && draft.mode != .routineManaged else {+      throw DefinitionError.otherOwner+    }+    try validate(draft)+    guard draft.mode != .asNeeded || !reminders else { throw DefinitionError.invalidSchedule }+    let current = try snapshot(medication)+    var normalised = draft+    normalised.fixedMinutes = Array(Set(normalised.fixedMinutes)).sorted()+    let oldDraft = MedicationScheduleDraft(+      mode: current.mode, dosesPerDay: current.dosesPerDay, dayStartMinute: current.dayStartMinute,+      dayEndMinute: current.dayEndMinute, minimumIntervalMinutes: current.minimumIntervalMinutes,+      intervalMinutes: current.intervalMinutes, firstReminderMinute: current.firstReminderMinute,+      fixedMinutes: current.fixedMinutes, wakeOffsetMinutes: current.wakeOffsetMinutes)+    if normalised == oldDraft {+      try transaction {+        if draft.mode == .afterWaking && reminders && !medication.remindersEnabled {+          medication.scheduleGenerationID = UUID()+          medication.scheduleStartedAt = now()         }+        medication.remindersEnabled = reminders+      }+      return+    }+    try transaction {+      medication.scheduleTypeRaw = draft.mode.rawValue+      medication.scheduleGenerationID = draft.mode == .asNeeded ? nil : UUID()+      medication.scheduleStartedAt = draft.mode == .asNeeded ? nil : now()+      medication.dosesPerDay = draft.mode == .spreadThroughDay ? draft.dosesPerDay : nil+      medication.dayStartMinuteOfDay = draft.mode == .spreadThroughDay ? draft.dayStartMinute : nil+      medication.dayEndMinuteOfDay = draft.mode == .spreadThroughDay ? draft.dayEndMinute : nil+      medication.minimumIntervalMinutes =+        draft.mode == .spreadThroughDay ? draft.minimumIntervalMinutes : nil+      medication.intervalMinutes = draft.mode == .interval ? draft.intervalMinutes : nil+      medication.firstReminderMinuteOfDay =+        draft.mode == .interval ? draft.firstReminderMinute : nil+      medication.fixedTimesData =+        draft.mode == .fixedTimes+        ? try JSONEncoder().encode(Array(Set(draft.fixedMinutes)).sorted()) : nil+      medication.wakeOffsetMinutes = draft.mode == .afterWaking ? draft.wakeOffsetMinutes : nil+      medication.remindersEnabled = reminders     }+  } -    func snapshot(_ medication: Medication) throws -> MedicationScheduleSnapshot {-        _ = try ProfileAccess.owner(medication, context: context)-        guard let mode = MedicationScheduleType(rawValue: medication.scheduleTypeRaw) else { throw DefinitionError.invalidSchedule }-        let minutes = try medication.fixedTimesData.map { try JSONDecoder().decode([Int].self, from: $0) } ?? []-        return .init(id: medication.id, mode: mode, generationID: medication.scheduleGenerationID, startedAt: medication.scheduleStartedAt, dosesPerDay: medication.dosesPerDay, dayStartMinute: medication.dayStartMinuteOfDay, dayEndMinute: medication.dayEndMinuteOfDay, minimumIntervalMinutes: medication.minimumIntervalMinutes, intervalMinutes: medication.intervalMinutes, firstReminderMinute: medication.firstReminderMinuteOfDay, fixedMinutes: minutes, wakeOffsetMinutes: medication.wakeOffsetMinutes, wakeAnchor: try WakeService(context: context).anchor(profileID: medication.profileID ?? ProfileIdentity.me), wakeAnchors: try WakeService(context: context).anchors(profileID: medication.profileID ?? ProfileIdentity.me))+  func snapshot(_ medication: Medication) throws -> MedicationScheduleSnapshot {+    _ = try ProfileAccess.owner(medication, context: context)+    guard let mode = MedicationScheduleType(rawValue: medication.scheduleTypeRaw) else {+      throw DefinitionError.invalidSchedule     }+    let minutes =+      try medication.fixedTimesData.map { try JSONDecoder().decode([Int].self, from: $0) } ?? []+    return .init(+      id: medication.id, mode: mode, generationID: medication.scheduleGenerationID,+      startedAt: medication.scheduleStartedAt, dosesPerDay: medication.dosesPerDay,+      dayStartMinute: medication.dayStartMinuteOfDay, dayEndMinute: medication.dayEndMinuteOfDay,+      minimumIntervalMinutes: medication.minimumIntervalMinutes,+      intervalMinutes: medication.intervalMinutes,+      firstReminderMinute: medication.firstReminderMinuteOfDay, fixedMinutes: minutes,+      wakeOffsetMinutes: medication.wakeOffsetMinutes,+      wakeAnchor: try WakeService(context: context).anchor(+        profileID: medication.profileID ?? ProfileIdentity.me),+      wakeAnchors: try WakeService(context: context).anchors(+        profileID: medication.profileID ?? ProfileIdentity.me))+  } -    func configure(_ routine: Routine, slots: [DailyRoutineSlot]?, reminders: Bool) throws {-        _ = try ProfileAccess.owner(routine, context: context)-        guard routine.kindRaw == "ordered", routine.isActive else { throw DefinitionError.invalidTarget }-        guard let slots else {-            guard !reminders else { throw DefinitionError.invalidSchedule }-            try transaction { routine.scheduleTypeRaw = "none"; routine.pendingScheduleData = nil; routine.remindersEnabled = false }-            return+  func configure(_ routine: Routine, slots: [DailyRoutineSlot]?, reminders: Bool) throws {+    _ = try ProfileAccess.owner(routine, context: context)+    guard routine.kindRaw == "ordered", routine.isActive else {+      throw DefinitionError.invalidTarget+    }+    guard let slots else {+      guard !reminders else { throw DefinitionError.invalidSchedule }+      try transaction {+        routine.scheduleTypeRaw = "none"+        routine.pendingScheduleData = nil+        routine.remindersEnabled = false+      }+      return+    }+    guard !slots.isEmpty, Set(slots.map(\.id)).count == slots.count,+      slots.allSatisfy({+        ($0.minuteOfDay == nil || $0.wakeOffsetMinutes == nil)+          && ($0.minuteOfDay.map { (0..<1440).contains($0) } ?? true)+          && ($0.wakeOffsetMinutes.map(WakeTiming.valid) ?? true)+      }),+      !reminders || slots.allSatisfy({ $0.minuteOfDay != nil || $0.wakeOffsetMinutes != nil })+    else { throw DefinitionError.invalidSchedule }+    let old = try snapshot(routine)+    let oldSlots = old.current?.slots ?? []+    let pendingMatches =+      old.pending.map { Set($0.configuration.slots.map(\.id)) == Set(slots.map(\.id)) } ?? false+    let sameFrequency = old.current != nil && oldSlots.count == slots.count+    if sameFrequency && Set(oldSlots.map(\.id)) != Set(slots.map(\.id)) && !pendingMatches {+      throw DefinitionError.invalidSchedule+    }+    try transaction {+      if pendingMatches, var pending = old.pending {+        pending.configuration.slots = slots+        routine.pendingScheduleData = try JSONEncoder().encode(pending)+      } else if sameFrequency {+        if oldSlots.map(\.wakeOffsetMinutes) != slots.map(\.wakeOffsetMinutes)+          || (reminders && !routine.remindersEnabled+            && slots.contains { $0.wakeOffsetMinutes != nil }) {+          routine.scheduleGenerationID = UUID()+          routine.scheduleStartedAt = now()         }-        guard !slots.isEmpty, Set(slots.map(\.id)).count == slots.count,-              slots.allSatisfy({ ($0.minuteOfDay == nil || $0.wakeOffsetMinutes == nil) && ($0.minuteOfDay.map { (0..<1440).contains($0) } ?? true) && ($0.wakeOffsetMinutes.map(WakeTiming.valid) ?? true) }),-              !reminders || slots.allSatisfy({ $0.minuteOfDay != nil || $0.wakeOffsetMinutes != nil }) else { throw DefinitionError.invalidSchedule }-        let old = try snapshot(routine)-        let oldSlots = old.current?.slots ?? []-        let pendingMatches = old.pending.map { Set($0.configuration.slots.map(\.id)) == Set(slots.map(\.id)) } ?? false-        let sameFrequency = old.current != nil && oldSlots.count == slots.count-        if sameFrequency && Set(oldSlots.map(\.id)) != Set(slots.map(\.id)) && !pendingMatches { throw DefinitionError.invalidSchedule }-        try transaction {-            if pendingMatches, var pending = old.pending {-                pending.configuration.slots = slots-                routine.pendingScheduleData = try JSONEncoder().encode(pending)-            } else if sameFrequency {-                if oldSlots.map(\.wakeOffsetMinutes) != slots.map(\.wakeOffsetMinutes) || (reminders && !routine.remindersEnabled && slots.contains { $0.wakeOffsetMinutes != nil }) { routine.scheduleGenerationID = UUID(); routine.scheduleStartedAt = now() }-                routine.dailySlotsData = try JSONEncoder().encode(slots)-                routine.pendingScheduleData = nil-            } else if old.current == nil && routine.scheduleGenerationID == nil {-                routine.scheduleTypeRaw = "dailySlots"-                routine.scheduleGenerationID = UUID(); routine.scheduleStartedAt = now()-                routine.dailySlotsData = try JSONEncoder().encode(slots); routine.pendingScheduleData = nil-            } else {-                guard let effective = ScheduleCalendar.nextDayStart(now(), calendar: calendar) else { throw DefinitionError.invalidSchedule }-                let pending = PendingRoutineSchedule(configuration: .init(generationID: UUID(), startedAt: effective, slots: slots), effectiveAt: effective, timeZoneID: calendar.timeZone.identifier)-                routine.pendingScheduleData = try JSONEncoder().encode(pending)-            }-            routine.remindersEnabled = reminders+        routine.dailySlotsData = try JSONEncoder().encode(slots)+        routine.pendingScheduleData = nil+      } else if old.current == nil && routine.scheduleGenerationID == nil {+        routine.scheduleTypeRaw = "dailySlots"+        routine.scheduleGenerationID = UUID()+        routine.scheduleStartedAt = now()+        routine.dailySlotsData = try JSONEncoder().encode(slots)+        routine.pendingScheduleData = nil+      } else {+        guard let effective = ScheduleCalendar.nextDayStart(now(), calendar: calendar) else {+          throw DefinitionError.invalidSchedule         }+        let pending = PendingRoutineSchedule(+          configuration: .init(generationID: UUID(), startedAt: effective, slots: slots),+          effectiveAt: effective, timeZoneID: calendar.timeZone.identifier)+        routine.pendingScheduleData = try JSONEncoder().encode(pending)+      }+      routine.remindersEnabled = reminders     }+  } -    func activatePending(_ routine: Routine) throws -> Bool {-        _ = try ProfileAccess.owner(routine, context: context)-        guard let data = routine.pendingScheduleData else { return false }-        let pending = try JSONDecoder().decode(PendingRoutineSchedule.self, from: data)-        let effective = ScheduleCalendar.activationDate(pending, calendar: calendar)-        guard now() >= effective else { return false }-        try transaction {-            routine.scheduleTypeRaw = "dailySlots"-            routine.scheduleGenerationID = pending.configuration.generationID-            routine.scheduleStartedAt = effective-            routine.dailySlotsData = try JSONEncoder().encode(pending.configuration.slots)-            routine.pendingScheduleData = nil-        }-        return true+  func activatePending(_ routine: Routine) throws -> Bool {+    _ = try ProfileAccess.owner(routine, context: context)+    guard let data = routine.pendingScheduleData else { return false }+    let pending = try JSONDecoder().decode(PendingRoutineSchedule.self, from: data)+    let effective = ScheduleCalendar.activationDate(pending, calendar: calendar)+    guard now() >= effective else { return false }+    try transaction {+      routine.scheduleTypeRaw = "dailySlots"+      routine.scheduleGenerationID = pending.configuration.generationID+      routine.scheduleStartedAt = effective+      routine.dailySlotsData = try JSONEncoder().encode(pending.configuration.slots)+      routine.pendingScheduleData = nil     }+    return true+  } -    func snapshot(_ routine: Routine) throws -> RoutineScheduleSnapshot {-        _ = try ProfileAccess.owner(routine, context: context)-        var current: RoutineScheduleConfiguration?-        if routine.scheduleTypeRaw == "dailySlots" {-            guard let generation = routine.scheduleGenerationID, let started = routine.scheduleStartedAt,-                  let data = routine.dailySlotsData else { throw DefinitionError.invalidSchedule }-            current = .init(generationID: generation, startedAt: started, slots: try JSONDecoder().decode([DailyRoutineSlot].self, from: data))-        }-        let pending = try routine.pendingScheduleData.map { try JSONDecoder().decode(PendingRoutineSchedule.self, from: $0) }-        return .init(routineID: routine.id, current: current, pending: pending, isActive: routine.isActive, remindersEnabled: routine.remindersEnabled, wakeAnchor: try WakeService(context: context).anchor(profileID: routine.profileID ?? ProfileIdentity.me), wakeAnchors: try WakeService(context: context).anchors(profileID: routine.profileID ?? ProfileIdentity.me))+  func snapshot(_ routine: Routine) throws -> RoutineScheduleSnapshot {+    _ = try ProfileAccess.owner(routine, context: context)+    var current: RoutineScheduleConfiguration?+    if routine.scheduleTypeRaw == "dailySlots" {+      guard let generation = routine.scheduleGenerationID, let started = routine.scheduleStartedAt,+        let data = routine.dailySlotsData+      else { throw DefinitionError.invalidSchedule }+      current = .init(+        generationID: generation, startedAt: started,+        slots: try JSONDecoder().decode([DailyRoutineSlot].self, from: data))     }+    let pending = try routine.pendingScheduleData.map {+      try JSONDecoder().decode(PendingRoutineSchedule.self, from: $0)+    }+    return .init(+      routineID: routine.id, current: current, pending: pending, isActive: routine.isActive,+      remindersEnabled: routine.remindersEnabled,+      wakeAnchor: try WakeService(context: context).anchor(+        profileID: routine.profileID ?? ProfileIdentity.me),+      wakeAnchors: try WakeService(context: context).anchors(+        profileID: routine.profileID ?? ProfileIdentity.me))+  } -    func startOccurrence(_ occurrence: RoutineOccurrence, routine: Routine, source: AdministrationSource = .phone, deviceID: String? = nil) throws -> RoutineRun {-        _ = try ProfileAccess.owner(routine, context: context)-        guard occurrence.routineID == routine.id else { throw DefinitionError.invalidTarget }-        let id = occurrence.id-        if let existing = try context.fetch(FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })).first {-            try ProfileAccess.same(existing, routine, context: context)-            guard !existing.isDeleted, existing.routineID == routine.id, existing.occurrenceKey == occurrence.key,-                  existing.slotID == occurrence.slotID, existing.scheduledAt == occurrence.scheduledAt else { throw ExecutionError.unknownRun }-            return existing-        }-        _ = try activatePending(routine)-        let schedule = try snapshot(routine)-        guard schedule.current?.generationID == occurrence.generationID,-              schedule.current?.slots.contains(where: { $0.id == occurrence.slotID }) == true else { throw DefinitionError.invalidSchedule }-        if schedule.current?.slots.first(where: { $0.id == occurrence.slotID })?.wakeOffsetMinutes != nil || occurrence.wakeEventID != nil {-            guard let wakeID = occurrence.wakeEventID else { throw DefinitionError.invalidSchedule }-            try WakeService(context: context).validate(id: wakeID, profileID: routine.profileID ?? ProfileIdentity.me)-            let candidates = RoutineScheduleEngine().occurrences(schedule, runs: [], day: occurrence.scheduledAt ?? now(), now: now(), calendar: calendar)-            guard candidates.contains(where: { $0.id == occurrence.id && $0.key == occurrence.key && $0.wakeEventID == wakeID && $0.slotID == occurrence.slotID && $0.generationID == occurrence.generationID && $0.scheduledAt == occurrence.scheduledAt && $0.localDate == occurrence.localDate && $0.timeZoneID == occurrence.timeZoneID }) else { throw DefinitionError.invalidSchedule }-        }-        let service = RoutineSessionService(context: context, now: now)-        service.onChange = onChange-        return try service.start(routine, runID: occurrence.id, occurrenceKey: occurrence.key, source: source, deviceID: deviceID,-                                 scheduledLocalDate: occurrence.localDate, scheduledTimeZoneID: occurrence.timeZoneID,-                                 slotID: occurrence.slotID, scheduledAt: occurrence.scheduledAt)+  func startOccurrence(+    _ occurrence: RoutineOccurrence, routine: Routine, source: AdministrationSource = .phone,+    deviceID: String? = nil+  ) throws -> RoutineRun {+    _ = try ProfileAccess.owner(routine, context: context)+    guard occurrence.routineID == routine.id else { throw DefinitionError.invalidTarget }+    let id = occurrence.id+    if let existing = try context.fetch(+      FetchDescriptor<RoutineRun>(predicate: #Predicate { $0.id == id })+    ).first {+      try ProfileAccess.same(existing, routine, context: context)+      guard !existing.isDeleted, existing.routineID == routine.id,+        existing.occurrenceKey == occurrence.key,+        existing.slotID == occurrence.slotID, existing.scheduledAt == occurrence.scheduledAt+      else { throw ExecutionError.unknownRun }+      return existing+    }+    _ = try activatePending(routine)+    let schedule = try snapshot(routine)+    guard schedule.current?.generationID == occurrence.generationID,+      schedule.current?.slots.contains(where: { $0.id == occurrence.slotID }) == true+    else { throw DefinitionError.invalidSchedule }+    if schedule.current?.slots.first(where: { $0.id == occurrence.slotID })?.wakeOffsetMinutes+      != nil || occurrence.wakeEventID != nil {+      guard let wakeID = occurrence.wakeEventID else { throw DefinitionError.invalidSchedule }+      try WakeService(context: context).validate(+        id: wakeID, profileID: routine.profileID ?? ProfileIdentity.me)+      let candidates = RoutineScheduleEngine().occurrences(+        schedule, runs: [], day: occurrence.scheduledAt ?? now(), now: now(), calendar: calendar)+      guard+        candidates.contains(where: {+          $0.id == occurrence.id && $0.key == occurrence.key && $0.wakeEventID == wakeID+            && $0.slotID == occurrence.slotID && $0.generationID == occurrence.generationID+            && $0.scheduledAt == occurrence.scheduledAt && $0.localDate == occurrence.localDate+            && $0.timeZoneID == occurrence.timeZoneID+        })+      else { throw DefinitionError.invalidSchedule }     }+    let service = RoutineSessionService(context: context, now: now)+    service.onChange = onChange+    return try service.start(+      routine, runID: occurrence.id, occurrenceKey: occurrence.key, source: source,+      deviceID: deviceID,+      scheduledLocalDate: occurrence.localDate, scheduledTimeZoneID: occurrence.timeZoneID,+      slotID: occurrence.slotID, scheduledAt: occurrence.scheduledAt)+  } -    private func validate(_ draft: MedicationScheduleDraft) throws {-        switch draft.mode {-        case .asNeeded: return-        case .routineManaged: throw DefinitionError.otherOwner-        case .spreadThroughDay:-            guard let doses = draft.dosesPerDay, doses > 0, let start = draft.dayStartMinute,-                  let end = draft.dayEndMinute, (0..<1440).contains(start), (0..<1440).contains(end), ScheduleCalendar.minuteOrder(start) < ScheduleCalendar.minuteOrder(end),-                  draft.minimumIntervalMinutes.map({ $0 > 0 }) ?? true else { throw DefinitionError.invalidSchedule }-        case .interval:-            guard let interval = draft.intervalMinutes, interval > 0, let first = draft.firstReminderMinute,-                  (0..<1440).contains(first) else { throw DefinitionError.invalidSchedule }-        case .afterWaking:-            guard let offset = draft.wakeOffsetMinutes, WakeTiming.valid(offset) else { throw DefinitionError.invalidSchedule }-        case .fixedTimes:-            guard !draft.fixedMinutes.isEmpty, draft.fixedMinutes.allSatisfy({ (0..<1440).contains($0) }) else { throw DefinitionError.invalidSchedule }-        }+  private func validate(_ draft: MedicationScheduleDraft) throws {+    switch draft.mode {+    case .asNeeded: return+    case .routineManaged: throw DefinitionError.otherOwner+    case .spreadThroughDay:+      guard let doses = draft.dosesPerDay, doses > 0, let start = draft.dayStartMinute,+        let end = draft.dayEndMinute, (0..<1440).contains(start), (0..<1440).contains(end),+        ScheduleCalendar.minuteOrder(start) < ScheduleCalendar.minuteOrder(end),+        draft.minimumIntervalMinutes.map({ $0 > 0 }) ?? true+      else { throw DefinitionError.invalidSchedule }+    case .interval:+      guard let interval = draft.intervalMinutes, interval > 0,+        let first = draft.firstReminderMinute,+        (0..<1440).contains(first)+      else { throw DefinitionError.invalidSchedule }+    case .afterWaking:+      guard let offset = draft.wakeOffsetMinutes, WakeTiming.valid(offset) else {+        throw DefinitionError.invalidSchedule+      }+    case .fixedTimes:+      guard !draft.fixedMinutes.isEmpty, draft.fixedMinutes.allSatisfy({ (0..<1440).contains($0) })+      else { throw DefinitionError.invalidSchedule }     }-    private func transaction<T>(_ body: () throws -> T) throws -> T {-        do { let result = try body(); if !deferSave { try context.save(); MutationEffects.saved(context); onChange() }; return result }-        catch { context.rollback(); throw error }+  }+  private func transaction<T>(_ body: () throws -> T) throws -> T {+    do {+      let result = try body()+      if !deferSave {+        try context.save()+        MutationEffects.saved(context)+        onChange()+      }+      return result+    } catch {+      context.rollback()+      throw error     }+  } }
Meddy/Meddy/Services/TreatmentService.swift Modified
diff --git a/Meddy/Meddy/Services/TreatmentService.swift b/Meddy/Meddy/Services/TreatmentService.swiftindex cc46811..39bd285 100644--- a/Meddy/Meddy/Services/TreatmentService.swift+++ b/Meddy/Meddy/Services/TreatmentService.swift@@ -3,98 +3,115 @@ import SwiftData  @MainActor final class TreatmentService {-    private let context: ModelContext-    private let deferSave: Bool-    private let now: () -> Date-    var onChange: () -> Void = {}+  private let context: ModelContext+  private let deferSave: Bool+  private let now: () -> Date+  var onChange: () -> Void = {} -    init(context: ModelContext, now: @escaping () -> Date = Date.init, deferSave: Bool = false) {-        self.context = context-        self.deferSave = deferSave-        self.now = now-        context.autosaveEnabled = false-    }+  init(context: ModelContext, now: @escaping () -> Date = Date.init, deferSave: Bool = false) {+    self.context = context+    self.deferSave = deferSave+    self.now = now+    context.autosaveEnabled = false+  } -    func create(name: String, instructions: String = "", notes: String = "", purpose: Purpose? = nil, profileID: UUID = ProfileIdentity.me) throws -> Treatment {-        let treatment = Treatment(name: try validName(name))-        try ProfileAccess.assign(treatment, to: profileID, context: context)-        if let purpose { try ProfileAccess.same(treatment, purpose, context: context) }-        treatment.instructions = instructions-        treatment.notes = notes-        treatment.purpose = purpose-        context.insert(treatment)-        try save()-        return treatment-    }+  func create(+    name: String, instructions: String = "", notes: String = "", purpose: Purpose? = nil,+    profileID: UUID = ProfileIdentity.me+  ) throws -> Treatment {+    let treatment = Treatment(name: try validName(name))+    try ProfileAccess.assign(treatment, to: profileID, context: context)+    if let purpose { try ProfileAccess.same(treatment, purpose, context: context) }+    treatment.instructions = instructions+    treatment.notes = notes+    treatment.purpose = purpose+    context.insert(treatment)+    try save()+    return treatment+  } -    func update(_ treatment: Treatment, name: String, instructions: String, notes: String, purpose: Purpose?) throws {-        _ = try ProfileAccess.owner(treatment, context: context)-        if let purpose { try ProfileAccess.same(treatment, purpose, context: context) }-        treatment.name = try validName(name)-        treatment.instructions = instructions-        treatment.notes = notes-        treatment.purpose = purpose-        try save()-    }+  func update(+    _ treatment: Treatment, name: String, instructions: String, notes: String, purpose: Purpose?+  ) throws {+    _ = try ProfileAccess.owner(treatment, context: context)+    if let purpose { try ProfileAccess.same(treatment, purpose, context: context) }+    treatment.name = try validName(name)+    treatment.instructions = instructions+    treatment.notes = notes+    treatment.purpose = purpose+    try save()+  } -    func setActive(_ treatment: Treatment, _ active: Bool) throws {-        _ = try ProfileAccess.owner(treatment, context: context)-        treatment.isActive = active-        try save()-    }+  func setActive(_ treatment: Treatment, _ active: Bool) throws {+    _ = try ProfileAccess.owner(treatment, context: context)+    treatment.isActive = active+    try save()+  } -    func record(_ action: TreatmentAction) throws -> TreatmentCompletion {-        let treatment = try ProfileAccess.canonical(Treatment.self, id: action.treatmentID, context: context)-        try ProfileAccess.action(action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID, target: treatment, context: context)-        let eventID = action.eventID-        if let existing = try context.fetch(FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == eventID })).first {-            try ProfileAccess.same(existing, treatment, context: context)-            guard existing.treatmentID == treatment.id else { throw ProfileError.conflictingOwnership }-            return existing-        }-        guard action.source == .watch || action.timestamp <= now() else { throw DefinitionError.futureTime }-        let event = TreatmentCompletion(treatment: treatment, timestamp: action.timestamp, source: action.source, eventID: eventID)-        event.instructionsSnapshot = action.instructionsSnapshot-        event.createdAt = now()-        event.updatedAt = now()-        event.hasClockMismatch = action.timestamp > now()-        context.insert(event)-        try save()-        return event+  func record(_ action: TreatmentAction) throws -> TreatmentCompletion {+    let treatment = try ProfileAccess.canonical(+      Treatment.self, id: action.treatmentID, context: context)+    try ProfileAccess.action(+      action.profileID, version: action.ownershipVersion, lifecycle: action.profileLifecycleID,+      target: treatment, context: context)+    let eventID = action.eventID+    if let existing = try context.fetch(+      FetchDescriptor<TreatmentCompletion>(predicate: #Predicate { $0.id == eventID })+    ).first {+      try ProfileAccess.same(existing, treatment, context: context)+      guard existing.treatmentID == treatment.id else { throw ProfileError.conflictingOwnership }+      return existing     }--    func delete(_ event: TreatmentCompletion) throws {-        // Linked corrections require the canonical session transaction service.-        let target = try ProfileAccess.canonical(Treatment.self, id: event.treatmentID, context: context)-        try ProfileAccess.same(event, target, context: context)-        guard event.routineRunID == nil else { throw DefinitionError.unresolvedFrozenStep }-        event.isDeleted = true-        event.updatedAt = now()-        try save()+    guard action.source == .watch || action.timestamp <= now() else {+      throw DefinitionError.futureTime     }+    let event = TreatmentCompletion(+      treatment: treatment, timestamp: action.timestamp, source: action.source, eventID: eventID)+    event.instructionsSnapshot = action.instructionsSnapshot+    event.createdAt = now()+    event.updatedAt = now()+    event.hasClockMismatch = action.timestamp > now()+    context.insert(event)+    try save()+    return event+  } -    func correct(_ event: TreatmentCompletion, timestamp: Date) throws {-        let target = try ProfileAccess.canonical(Treatment.self, id: event.treatmentID, context: context)-        try ProfileAccess.same(event, target, context: context)-        guard event.routineRunID == nil else { throw DefinitionError.unresolvedFrozenStep }-        guard timestamp <= now() else { throw DefinitionError.futureTime }-        event.timestamp = timestamp-        event.hasClockMismatch = false-        event.updatedAt = now()-        try save()-    }+  func delete(_ event: TreatmentCompletion) throws {+    // Linked corrections require the canonical session transaction service.+    let target = try ProfileAccess.canonical(+      Treatment.self, id: event.treatmentID, context: context)+    try ProfileAccess.same(event, target, context: context)+    guard event.routineRunID == nil else { throw DefinitionError.unresolvedFrozenStep }+    event.isDeleted = true+    event.updatedAt = now()+    try save()+  } -    private func validName(_ value: String) throws -> String {-        let name = value.trimmingCharacters(in: .whitespacesAndNewlines)-        guard !name.isEmpty else { throw DefinitionError.missingName }-        return name-    }+  func correct(_ event: TreatmentCompletion, timestamp: Date) throws {+    let target = try ProfileAccess.canonical(+      Treatment.self, id: event.treatmentID, context: context)+    try ProfileAccess.same(event, target, context: context)+    guard event.routineRunID == nil else { throw DefinitionError.unresolvedFrozenStep }+    guard timestamp <= now() else { throw DefinitionError.futureTime }+    event.timestamp = timestamp+    event.hasClockMismatch = false+    event.updatedAt = now()+    try save()+  }++  private func validName(_ value: String) throws -> String {+    let name = value.trimmingCharacters(in: .whitespacesAndNewlines)+    guard !name.isEmpty else { throw DefinitionError.missingName }+    return name+  } -    private func save() throws {-        if deferSave { return }-        do { try context.save() }-        catch { context.rollback(); throw DefinitionError.saveFailed }-        MutationEffects.saved(context)-        onChange()+  private func save() throws {+    if deferSave { return }+    do { try context.save() } catch {+      context.rollback()+      throw DefinitionError.saveFailed     }+    MutationEffects.saved(context)+    onChange()+  } }
Meddy/Meddy/Services/WakeService.swift Modified
diff --git a/Meddy/Meddy/Services/WakeService.swift b/Meddy/Meddy/Services/WakeService.swiftindex e06ad6c..8e41db7 100644--- a/Meddy/Meddy/Services/WakeService.swift+++ b/Meddy/Meddy/Services/WakeService.swift@@ -2,37 +2,64 @@ import Foundation import SwiftData  @MainActor final class WakeService {-    private let context: ModelContext-    init(context: ModelContext) { self.context = context; context.autosaveEnabled = false }-    @discardableResult func record(profileID: UUID = ProfileIdentity.me, at timestamp: Date = Date(), receivedAt: Date = Date(), calendar: Calendar = .current, save: (() throws -> Void)? = nil) throws -> WakeEvent {-        let profile = try ProfileAccess.profile(profileID, context: context)-        guard timestamp <= receivedAt, timestamp.timeIntervalSince1970.isFinite else { throw RecordingError.futureTime }-        let lifecycle = profile?.lifecycleID ?? ProfileIdentity.selfLifecycle-        let day = ScheduleCalendar.localDate(timestamp, calendar: calendar)-        let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter { $0.profileID == profileID && $0.localDate == day && $0.profileLifecycleID == lifecycle }-        guard events.count <= 1 else { throw ProfileError.conflictingOwnership }-        if let existing = events.first { try validate(existing, profileID: profileID); return existing }-        let value = WakeEvent(profileID: profileID, lifecycleID: profile?.lifecycleID ?? ProfileIdentity.selfLifecycle, timestamp: timestamp, recordedAt: receivedAt, calendar: calendar)-        context.insert(value)-        do { try (save ?? { try self.context.save() })(); MutationEffects.saved(context); return value }-        catch { context.rollback(); throw error }+  private let context: ModelContext+  init(context: ModelContext) {+    self.context = context+    context.autosaveEnabled = false+  }+  @discardableResult func record(+    profileID: UUID = ProfileIdentity.me, at timestamp: Date = Date(), receivedAt: Date = Date(),+    calendar: Calendar = .current, save: (() throws -> Void)? = nil+  ) throws -> WakeEvent {+    let profile = try ProfileAccess.profile(profileID, context: context)+    guard timestamp <= receivedAt, timestamp.timeIntervalSince1970.isFinite else {+      throw RecordingError.futureTime     }-    func validate(_ event: WakeEvent, profileID: UUID) throws {-        let profile = try ProfileAccess.profile(profileID, context: context)-        guard event.profileID == profileID, event.ownershipVersion == 1,-              event.profileLifecycleID == (profile?.lifecycleID ?? ProfileIdentity.selfLifecycle), event.sourceRaw == "shortcut" else { throw ProfileError.conflictingOwnership }+    let lifecycle = profile?.lifecycleID ?? ProfileIdentity.selfLifecycle+    let day = ScheduleCalendar.localDate(timestamp, calendar: calendar)+    let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter {+      $0.profileID == profileID && $0.localDate == day && $0.profileLifecycleID == lifecycle     }-    func anchors(profileID: UUID) throws -> [WakeAnchor] {-        _ = try ProfileAccess.profile(profileID, context: context)-        let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter { $0.profileID == profileID }.sorted { $0.timestamp > $1.timestamp }-        let valid = events.filter { (try? validate($0, profileID: profileID)) != nil }-        guard Set(valid.map(\.id)).count == valid.count, Set(valid.map(\.localDate)).count == valid.count else { throw ProfileError.conflictingOwnership }-        return valid.map(\.anchor)+    guard events.count <= 1 else { throw ProfileError.conflictingOwnership }+    if let existing = events.first {+      try validate(existing, profileID: profileID)+      return existing     }-    func anchor(profileID: UUID) throws -> WakeAnchor? { try anchors(profileID: profileID).first }-    func validate(id: UUID, profileID: UUID) throws {-        let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter { $0.id == id }-        guard events.count == 1, let event = events.first else { throw ProfileError.unknownOwner }-        try validate(event, profileID: profileID)+    let value = WakeEvent(+      profileID: profileID, lifecycleID: profile?.lifecycleID ?? ProfileIdentity.selfLifecycle,+      timestamp: timestamp, recordedAt: receivedAt, calendar: calendar)+    context.insert(value)+    do {+      try (save ?? { try self.context.save() })()+      MutationEffects.saved(context)+      return value+    } catch {+      context.rollback()+      throw error     }+  }+  func validate(_ event: WakeEvent, profileID: UUID) throws {+    let profile = try ProfileAccess.profile(profileID, context: context)+    guard event.profileID == profileID, event.ownershipVersion == 1,+      event.profileLifecycleID == (profile?.lifecycleID ?? ProfileIdentity.selfLifecycle),+      event.sourceRaw == "shortcut"+    else { throw ProfileError.conflictingOwnership }+  }+  func anchors(profileID: UUID) throws -> [WakeAnchor] {+    _ = try ProfileAccess.profile(profileID, context: context)+    let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter {+      $0.profileID == profileID+    }.sorted { $0.timestamp > $1.timestamp }+    let valid = events.filter { (try? validate($0, profileID: profileID)) != nil }+    guard Set(valid.map(\.id)).count == valid.count,+      Set(valid.map(\.localDate)).count == valid.count+    else { throw ProfileError.conflictingOwnership }+    return valid.map(\.anchor)+  }+  func anchor(profileID: UUID) throws -> WakeAnchor? { try anchors(profileID: profileID).first }+  func validate(id: UUID, profileID: UUID) throws {+    let events = try context.fetch(FetchDescriptor<WakeEvent>()).filter { $0.id == id }+    guard events.count == 1, let event = events.first else { throw ProfileError.unknownOwner }+    try validate(event, profileID: profileID)+  } }
Meddy/MeddyTests/MeddyAsNeededLimitTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyAsNeededLimitTests.swift b/Meddy/MeddyTests/MeddyAsNeededLimitTests.swiftindex 8421ebd..5c18fba 100644--- a/Meddy/MeddyTests/MeddyAsNeededLimitTests.swift+++ b/Meddy/MeddyTests/MeddyAsNeededLimitTests.swift@@ -1,240 +1,336 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyAsNeededLimitTests {-    private let id = UUID()-    private let now = Date(timeIntervalSince1970: 1_767_660_000)-    private var dose: RecordedDoseSnapshot { .init(description: "", amount: 1, unit: "measure") }-    private var rules: AsNeededDoseLimits {-        .init(minimumIntervalSeconds: 3 * 3600, maximumAmount: 7, windowSeconds: 12 * 3600, unit: "measure", productStrengthAndForm: "Synthetic strength/form", activeIngredients: "Synthetic ingredient", instructionSource: "Synthetic provided directions", historyConfirmedFrom: now.addingTimeInterval(-24 * 3600))-    }-    private func event(_ secondsAgo: Double, amount: Double? = 1, unit: String? = "measure") -> DoseLimitAdministration {-        .init(id: UUID(), medicationID: id, timestamp: now.addingTimeInterval(-secondsAgo), dose: .init(description: "", amount: amount, unit: unit))-    }-    private func check(_ values: [DoseLimitAdministration], rules: AsNeededDoseLimits? = nil, dose: RecordedDoseSnapshot? = nil, at: Date? = nil) -> DoseLimitCheck {-        AsNeededDoseLimitEngine().evaluate(medicationID: id, limits: rules ?? self.rules, administrations: values, proposedDose: dose ?? self.dose, now: at ?? now)-    }-    @Test func onlyEnteredLimitsAndLoggedQuantitiesAffectTheCheck() {-        let absent = AsNeededDoseLimitEngine().evaluate(medicationID: id, limits: nil, administrations: [], proposedDose: dose, now: now)-        #expect(absent.state == .notConfigured)-        var partial = rules; partial.instructionSource = ""; partial.historyConfirmedFrom = nil-        #expect(check([], rules: partial).state == .withinEnteredLimits)-        #expect(check([], dose: .unknown).state == .needsReview)-        partial = rules; partial.maximumAmount = nil; partial.windowSeconds = nil-        #expect(check([], rules: partial).state == .withinEnteredLimits)-        #expect(check([]).state == .withinEnteredLimits)-    }-    @Test func dailyCapHasNoCompletenessChecklistAndDoesNotResetAt02OrDST() throws {-        let iso = ISO8601DateFormatter()-        let daily = AsNeededDoseLimits(minimumIntervalSeconds: 3 * 3600, maximumAmount: 6, windowSeconds: 86400, unit: "measure")-        for text in ["2026-01-05T02:00:00Z", "2026-03-08T07:00:00Z", "2026-11-01T06:00:00Z"] {-            let boundary = try #require(iso.date(from: text))-            var recorded = event(0, amount: 6)-            recorded.timestamp = boundary.addingTimeInterval(-60)-            let blocked = check([recorded], rules: daily, at: boundary)-            #expect(blocked.state == .wait && blocked.remainingAmount == 0 && blocked.issues.isEmpty)-            #expect(blocked.earliestFromLoggedDoses == recorded.timestamp.addingTimeInterval(86400))-            let expired = check([recorded], rules: daily, at: recorded.timestamp.addingTimeInterval(86400))-            #expect(expired.state == .withinEnteredLimits && expired.remainingAmount == 6)-        }-    }-    @Test func dailyDraftUses24HoursAndPreservesLegacyUntilExplicitConversion() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic", dose: dose)-        let draft = AsNeededLimitDraft(medication: nil)-        draft.enabled = true; draft.intervalHours = "3"; draft.maximum = "6"-        #expect(try draft.rules(now: now)?.windowSeconds == 86400)-        #expect(try draft.rules(now: now)?.unit == "units")-        let service = AsNeededLimitService(context: store.mainContext)-        try service.configure(item, limits: rules, now: now)-        let action = AdministrationAction(eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-60), source: .phone, dose: dose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)-        let recorded = try MedicationService(context: store.mainContext).record(action)-        let legacy = AsNeededLimitDraft(medication: item)-        #expect(legacy.legacyWindowHours == 12)-        #expect(try legacy.rules(now: now) == rules)-        legacy.maximum = "8"-        #expect(try legacy.rules(now: now)?.windowSeconds == 12 * 3600)-        legacy.useDailyWindow = true-        let converted = try #require(try legacy.rules(now: now))-        #expect(converted.windowSeconds == 86400 && legacy.legacyWindowHours == nil)-        #expect(converted.activeIngredients == rules.activeIngredients && converted.productStrengthAndForm == rules.productStrengthAndForm)-        #expect(converted.instructionSource == rules.instructionSource && converted.historyConfirmedFrom == rules.historyConfirmedFrom)-        try EditorTransaction.save(context: store.mainContext) { try legacy.apply(to: item, context: store.mainContext) }-        #expect(try service.limits(item)?.windowSeconds == 86400)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-        #expect(recorded.id == action.eventID && recorded.timestamp == action.timestamp && recorded.recordedDose == dose && !recorded.isDeleted)-    }-    @Test func allowanceUsesQuantitiesAndBothIntervalAndCapDetermineNextDose() {-        let daily = AsNeededDoseLimits(minimumIntervalSeconds: 3 * 3600, maximumAmount: 4, windowSeconds: 86400, unit: "measure")-        let values = [event(23 * 3600, amount: 2), event(3600, amount: 1.5)]-        let result = check(values, rules: daily)-        #expect(result.remainingAmount == 0.5 && result.state == .wait)-        #expect(result.earliestFromLoggedDoses == now.addingTimeInterval(2 * 3600))-        #expect(check(values, rules: daily, at: now.addingTimeInterval(2 * 3600)).remainingAmount == 2.5)-    }-    @Test func minimumIntervalBoundaryUsesActualTimestampToTheSecond() {-        let last = event(3 * 3600 - 1)-        let before = check([last])-        #expect(before.state == .wait && before.earliestFromLoggedDoses == now.addingTimeInterval(1))-        #expect(check([last], at: now.addingTimeInterval(1)).state == .withinEnteredLimits)-        #expect(last.timestamp == now.addingTimeInterval(-3 * 3600 + 1))-    }-    @Test func rollingLimitSumsQuantitiesAndFindsRequiredExpiry() {-        let values = [event(11 * 3600, amount: 3), event(5 * 3600, amount: 2), event(4 * 3600, amount: 1)]-        let result = check(values, dose: .init(description: "", amount: 2, unit: "measure"))-        #expect(result.knownAmount == 6 && result.state == .wait)-        #expect(result.earliestFromLoggedDoses == now.addingTimeInterval(3600))-    }-    @Test func exactWindowExpiryExcludesOldDoseAnd02DoesNotResetIt() throws {-        let old = event(12 * 3600, amount: 7)-        #expect(check([old]).knownAmount == 0 && check([old]).state == .withinEnteredLimits)-        let iso = ISO8601DateFormatter(); let at02 = try #require(iso.date(from: "2026-01-05T02:00:00Z"))-        var late = event(1, amount: 7); late.timestamp = at02.addingTimeInterval(-60)-        let result = check([late], at: at02)-        #expect(result.knownAmount == 7 && result.state == .wait)-        #expect(result.earliestFromLoggedDoses == late.timestamp.addingTimeInterval(12 * 3600))-    }-    @Test func decimalQuantitiesDoNotInventFloatingPointExcess() {-        var limits = rules; limits.minimumIntervalSeconds = 1; limits.maximumAmount = 0.4-        let result = check([event(120, amount: 0.1), event(60, amount: 0.2)], rules: limits, dose: .init(description: "", amount: 0.1, unit: "measure"))-        #expect(result.state == .withinEnteredLimits && result.knownAmount == 0.3)-    }-    @Test func unknownAmountsUnitsAndClocksStayUncertain() {-        #expect(check([event(4 * 3600, amount: nil, unit: nil)]).state == .needsReview)-        #expect(check([event(4 * 3600, unit: "another unit")]).state == .needsReview)-        var future = event(-3600); future.hasClockMismatch = true-        #expect(check([future]).state == .needsReview)-        var oldUncertain = event(13 * 3600); oldUncertain.hasClockMismatch = true-        #expect(check([oldUncertain]).state == .needsReview)-        #expect(check([event(4 * 3600)], dose: .init(description: "", amount: 1, unit: "another unit")).state == .needsReview)-        #expect(check([event(13 * 3600, amount: nil, unit: nil)]).state == .withinEnteredLimits)-    }-    @Test func duplicateIdentityAndTombstonesCannotConsumeTwice() {-        let value = event(4 * 3600, amount: 3)-        #expect(check([value, value]).knownAmount == 3)-        var deleted = value; deleted.isDeleted = true-        #expect(check([value, deleted]).knownAmount == 0)-        var other = value; other.id = UUID(); other.medicationID = UUID()-        #expect(check([other]).knownAmount == 0)-    }-    @Test func amountLargerThanWindowMaximumHasNoFutureEligibleTime() {-        let result = check([], dose: .init(description: "", amount: 8, unit: "measure"))-        #expect(result.state == .wait && result.earliestFromLoggedDoses == nil)-    }-    @Test func DSTWindowsUseElapsedHoursAcrossSkippedAndRepeatedTimes() throws {-        let iso = ISO8601DateFormatter()-        for text in ["2026-03-08T06:30:00Z", "2026-11-01T05:30:00Z"] {-            let stamp = try #require(iso.date(from: text)); var value = event(0); value.timestamp = stamp-            var limits = rules; limits.historyConfirmedFrom = stamp.addingTimeInterval(-24 * 3600)-            let boundary = stamp.addingTimeInterval(3 * 3600)-            #expect(check([value], rules: limits, at: boundary.addingTimeInterval(-1)).state == .wait)-            #expect(check([value], rules: limits, at: boundary).state == .withinEnteredLimits)-        }-    }-    @Test func correctionUndoAndRuleEditRecomputeExistingFactsAcrossModes() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let context = store.mainContext-        let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic", dose: dose)-        let service = AsNeededLimitService(context: context)-        try service.configure(item, limits: rules, now: now)-        let action = AdministrationAction(eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-4 * 3600), source: .phone, dose: .init(description: "", amount: 2, unit: "measure"), scheduleTypeAtRecording: .interval, scheduleGenerationID: UUID())-        let recorded = try MedicationService(context: context).record(action)-        #expect(service.check(item, now: now).knownAmount == 2)-        try RoutineSessionService(context: context).correct(recorded, timestamp: now.addingTimeInterval(-3600), dose: .init(description: "", amount: 3, unit: "measure"))-        #expect(service.check(item, now: now).knownAmount == 3 && service.check(item, now: now).state == .wait)-        var changed = rules; changed.maximumAmount = 3-        try service.configure(item, limits: changed, now: now)-        #expect(service.check(item, now: now).knownAmount == 3)-        try MedicationService(context: context).delete(recorded)-        let fetched = try #require(context.fetch(FetchDescriptor<Administration>()).first)-        #expect(fetched.isDeleted)-        #expect(service.check(item, now: now).knownAmount == 0)-        #expect(recorded.id == action.eventID && recorded.isDeleted)-        // History deletion uses the correction service, including unlinked doses.-        var another = action; another.eventID = UUID()-        let historical = try MedicationService(context: context).record(another)-        let corrections = RoutineSessionService(context: context, now: { self.now })-        try corrections.correct(historical, timestamp: historical.timestamp, dose: historical.recordedDose, delete: true)-        // The checker must refresh canonical rows rather than reading a stale relationship cache.-        #expect(service.check(item, now: now).knownAmount == 0)-        let deletedFlag = historical.isDeleted-        #expect(deletedFlag)-        #expect(historical.timestamp == another.timestamp && historical.recordedDose == another.dose)-    }-    @Test func matchingOldIngredientLabelsDoNotAddWarningsOrCombineOtherMedicationDoses() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let meds = MedicationService(context: store.mainContext)-        let first = try meds.createAsNeededMedication(name: "Synthetic A", dose: dose)-        let other = try meds.createAsNeededMedication(name: "Synthetic B", dose: .init(description: "", amount: 1, unit: "other unit"))-        let service = AsNeededLimitService(context: store.mainContext)-        try service.configure(first, limits: rules, now: now)-        var secondRules = rules; secondRules.unit = "other unit"-        try service.configure(other, limits: secondRules, now: now)-        #expect(service.check(first, now: now).state == .withinEnteredLimits)-        #expect(service.check(first, now: now).knownAmount == 0)-        try meds.setActive(other, false)-        #expect(service.check(first, now: now).state == .withinEnteredLimits)+  private let id = UUID()+  private let now = Date(timeIntervalSince1970: 1_767_660_000)+  private var dose: RecordedDoseSnapshot { .init(description: "", amount: 1, unit: "measure") }+  private var rules: AsNeededDoseLimits {+    .init(+      minimumIntervalSeconds: 3 * 3600, maximumAmount: 7, windowSeconds: 12 * 3600, unit: "measure",+      productStrengthAndForm: "Synthetic strength/form", activeIngredients: "Synthetic ingredient",+      instructionSource: "Synthetic provided directions",+      historyConfirmedFrom: now.addingTimeInterval(-24 * 3600))+  }+  private func event(_ secondsAgo: Double, amount: Double? = 1, unit: String? = "measure")+    -> DoseLimitAdministration {+    .init(+      id: UUID(), medicationID: id, timestamp: now.addingTimeInterval(-secondsAgo),+      dose: .init(description: "", amount: amount, unit: unit))+  }+  private func check(+    _ values: [DoseLimitAdministration], rules: AsNeededDoseLimits? = nil,+    dose: RecordedDoseSnapshot? = nil, at: Date? = nil+  ) -> DoseLimitCheck {+    AsNeededDoseLimitEngine().evaluate(+      medicationID: id, limits: rules ?? self.rules, administrations: values,+      proposedDose: dose ?? self.dose, now: at ?? now)+  }+  @Test func onlyEnteredLimitsAndLoggedQuantitiesAffectTheCheck() {+    let absent = AsNeededDoseLimitEngine().evaluate(+      medicationID: id, limits: nil, administrations: [], proposedDose: dose, now: now)+    #expect(absent.state == .notConfigured)+    var partial = rules+    partial.instructionSource = ""+    partial.historyConfirmedFrom = nil+    #expect(check([], rules: partial).state == .withinEnteredLimits)+    #expect(check([], dose: .unknown).state == .needsReview)+    partial = rules+    partial.maximumAmount = nil+    partial.windowSeconds = nil+    #expect(check([], rules: partial).state == .withinEnteredLimits)+    #expect(check([]).state == .withinEnteredLimits)+  }+  @Test func dailyCapHasNoCompletenessChecklistAndDoesNotResetAt02OrDST() throws {+    let iso = ISO8601DateFormatter()+    let daily = AsNeededDoseLimits(+      minimumIntervalSeconds: 3 * 3600, maximumAmount: 6, windowSeconds: 86400, unit: "measure")+    for text in ["2026-01-05T02:00:00Z", "2026-03-08T07:00:00Z", "2026-11-01T06:00:00Z"] {+      let boundary = try #require(iso.date(from: text))+      var recorded = event(0, amount: 6)+      recorded.timestamp = boundary.addingTimeInterval(-60)+      let blocked = check([recorded], rules: daily, at: boundary)+      #expect(blocked.state == .wait && blocked.remainingAmount == 0 && blocked.issues.isEmpty)+      #expect(blocked.earliestFromLoggedDoses == recorded.timestamp.addingTimeInterval(86400))+      let expired = check(+        [recorded], rules: daily, at: recorded.timestamp.addingTimeInterval(86400))+      #expect(expired.state == .withinEnteredLimits && expired.remainingAmount == 6)     }-    @Test func unrepresentableTotalsAndNonfiniteProposalsNeverBecomePositiveChecks() throws {-        let result = check([event(4 * 3600, amount: 9e127), event(5 * 3600, amount: 9e127)])-        #expect(result.state != .withinEnteredLimits)-        let invalid = check([], dose: .init(description: "", amount: .nan, unit: "measure"))-        #expect(invalid.state == .needsReview && invalid.proposedAmount == nil)-        _ = try JSONEncoder().encode(invalid)+  }+  @Test func dailyDraftUses24HoursAndPreservesLegacyUntilExplicitConversion() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic", dose: dose)+    let draft = AsNeededLimitDraft(medication: nil)+    draft.enabled = true+    draft.intervalHours = "3"+    draft.maximum = "6"+    #expect(try draft.rules(now: now)?.windowSeconds == 86400)+    #expect(try draft.rules(now: now)?.unit == "units")+    let service = AsNeededLimitService(context: store.mainContext)+    try service.configure(item, limits: rules, now: now)+    let action = AdministrationAction(+      eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-60),+      source: .phone, dose: dose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+    let recorded = try MedicationService(context: store.mainContext).record(action)+    let legacy = AsNeededLimitDraft(medication: item)+    #expect(legacy.legacyWindowHours == 12)+    #expect(try legacy.rules(now: now) == rules)+    legacy.maximum = "8"+    #expect(try legacy.rules(now: now)?.windowSeconds == 12 * 3600)+    legacy.useDailyWindow = true+    let converted = try #require(try legacy.rules(now: now))+    #expect(converted.windowSeconds == 86400 && legacy.legacyWindowHours == nil)+    #expect(+      converted.activeIngredients == rules.activeIngredients+        && converted.productStrengthAndForm == rules.productStrengthAndForm)+    #expect(+      converted.instructionSource == rules.instructionSource+        && converted.historyConfirmedFrom == rules.historyConfirmedFrom)+    try EditorTransaction.save(context: store.mainContext) {+      try legacy.apply(to: item, context: store.mainContext)     }-    @Test func statusReadsLeaveContextAutosaveAndStoredFactsUnchanged() throws {-        let container = try AppEnvironment.makeContainer(isolated: true)-        let context = container.mainContext-        let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic", dose: dose)-        try AsNeededLimitService(context: context).configure(item, limits: rules, now: now)-        context.autosaveEnabled = true-        let service = AsNeededLimitService(context: context)-        #expect(service.check(item, now: now).state == .withinEnteredLimits)-        #expect(context.autosaveEnabled && !context.hasChanges)-        #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+    #expect(try service.limits(item)?.windowSeconds == 86400)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+    #expect(+      recorded.id == action.eventID && recorded.timestamp == action.timestamp+        && recorded.recordedDose == dose && !recorded.isDeleted)+  }+  @Test func allowanceUsesQuantitiesAndBothIntervalAndCapDetermineNextDose() {+    let daily = AsNeededDoseLimits(+      minimumIntervalSeconds: 3 * 3600, maximumAmount: 4, windowSeconds: 86400, unit: "measure")+    let values = [event(23 * 3600, amount: 2), event(3600, amount: 1.5)]+    let result = check(values, rules: daily)+    #expect(result.remainingAmount == 0.5 && result.state == .wait)+    #expect(result.earliestFromLoggedDoses == now.addingTimeInterval(2 * 3600))+    #expect(+      check(values, rules: daily, at: now.addingTimeInterval(2 * 3600)).remainingAmount == 2.5)+  }+  @Test func minimumIntervalBoundaryUsesActualTimestampToTheSecond() {+    let last = event(3 * 3600 - 1)+    let before = check([last])+    #expect(before.state == .wait && before.earliestFromLoggedDoses == now.addingTimeInterval(1))+    #expect(check([last], at: now.addingTimeInterval(1)).state == .withinEnteredLimits)+    #expect(last.timestamp == now.addingTimeInterval(-3 * 3600 + 1))+  }+  @Test func rollingLimitSumsQuantitiesAndFindsRequiredExpiry() {+    let values = [+      event(11 * 3600, amount: 3), event(5 * 3600, amount: 2), event(4 * 3600, amount: 1)+    ]+    let result = check(values, dose: .init(description: "", amount: 2, unit: "measure"))+    #expect(result.knownAmount == 6 && result.state == .wait)+    #expect(result.earliestFromLoggedDoses == now.addingTimeInterval(3600))+  }+  @Test func exactWindowExpiryExcludesOldDoseAnd02DoesNotResetIt() throws {+    let old = event(12 * 3600, amount: 7)+    #expect(check([old]).knownAmount == 0 && check([old]).state == .withinEnteredLimits)+    let iso = ISO8601DateFormatter()+    let at02 = try #require(iso.date(from: "2026-01-05T02:00:00Z"))+    var late = event(1, amount: 7)+    late.timestamp = at02.addingTimeInterval(-60)+    let result = check([late], at: at02)+    #expect(result.knownAmount == 7 && result.state == .wait)+    #expect(result.earliestFromLoggedDoses == late.timestamp.addingTimeInterval(12 * 3600))+  }+  @Test func decimalQuantitiesDoNotInventFloatingPointExcess() {+    var limits = rules+    limits.minimumIntervalSeconds = 1+    limits.maximumAmount = 0.4+    let result = check(+      [event(120, amount: 0.1), event(60, amount: 0.2)], rules: limits,+      dose: .init(description: "", amount: 0.1, unit: "measure"))+    #expect(result.state == .withinEnteredLimits && result.knownAmount == 0.3)+  }+  @Test func unknownAmountsUnitsAndClocksStayUncertain() {+    #expect(check([event(4 * 3600, amount: nil, unit: nil)]).state == .needsReview)+    #expect(check([event(4 * 3600, unit: "another unit")]).state == .needsReview)+    var future = event(-3600)+    future.hasClockMismatch = true+    #expect(check([future]).state == .needsReview)+    var oldUncertain = event(13 * 3600)+    oldUncertain.hasClockMismatch = true+    #expect(check([oldUncertain]).state == .needsReview)+    #expect(+      check([event(4 * 3600)], dose: .init(description: "", amount: 1, unit: "another unit")).state+        == .needsReview)+    #expect(check([event(13 * 3600, amount: nil, unit: nil)]).state == .withinEnteredLimits)+  }+  @Test func duplicateIdentityAndTombstonesCannotConsumeTwice() {+    let value = event(4 * 3600, amount: 3)+    #expect(check([value, value]).knownAmount == 3)+    var deleted = value+    deleted.isDeleted = true+    #expect(check([value, deleted]).knownAmount == 0)+    var other = value+    other.id = UUID()+    other.medicationID = UUID()+    #expect(check([other]).knownAmount == 0)+  }+  @Test func amountLargerThanWindowMaximumHasNoFutureEligibleTime() {+    let result = check([], dose: .init(description: "", amount: 8, unit: "measure"))+    #expect(result.state == .wait && result.earliestFromLoggedDoses == nil)+  }+  @Test func DSTWindowsUseElapsedHoursAcrossSkippedAndRepeatedTimes() throws {+    let iso = ISO8601DateFormatter()+    for text in ["2026-03-08T06:30:00Z", "2026-11-01T05:30:00Z"] {+      let stamp = try #require(iso.date(from: text))+      var value = event(0)+      value.timestamp = stamp+      var limits = rules+      limits.historyConfirmedFrom = stamp.addingTimeInterval(-24 * 3600)+      let boundary = stamp.addingTimeInterval(3 * 3600)+      #expect(check([value], rules: limits, at: boundary.addingTimeInterval(-1)).state == .wait)+      #expect(check([value], rules: limits, at: boundary).state == .withinEnteredLimits)     }-    @Test func legacyContextIsPreservedAndUnchangedDraftDoesNotOverwriteNewerRules() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic", dose: dose)-        let service = AsNeededLimitService(context: store.mainContext)-        try service.configure(item, limits: rules, now: now)-        let draft = AsNeededLimitDraft(medication: item)-        var newer = rules; newer.maximumAmount = 9-        try service.configure(item, limits: newer, now: now)-        try EditorTransaction.save(context: store.mainContext) { try draft.apply(to: item, context: store.mainContext) }-        #expect(try service.limits(item)?.maximumAmount == 9)-        newer.productStrengthAndForm = "Synthetic changed formulation"-        try service.configure(item, limits: newer, now: now)-        #expect(try service.limits(item)?.historyConfirmedFrom == rules.historyConfirmedFrom)+  }+  @Test func correctionUndoAndRuleEditRecomputeExistingFactsAcrossModes() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    let item = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", dose: dose)+    let service = AsNeededLimitService(context: context)+    try service.configure(item, limits: rules, now: now)+    let action = AdministrationAction(+      eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-4 * 3600),+      source: .phone, dose: .init(description: "", amount: 2, unit: "measure"),+      scheduleTypeAtRecording: .interval, scheduleGenerationID: UUID())+    let recorded = try MedicationService(context: context).record(action)+    #expect(service.check(item, now: now).knownAmount == 2)+    try RoutineSessionService(context: context).correct(+      recorded, timestamp: now.addingTimeInterval(-3600),+      dose: .init(description: "", amount: 3, unit: "measure"))+    #expect(+      service.check(item, now: now).knownAmount == 3 && service.check(item, now: now).state == .wait+    )+    var changed = rules+    changed.maximumAmount = 3+    try service.configure(item, limits: changed, now: now)+    #expect(service.check(item, now: now).knownAmount == 3)+    try MedicationService(context: context).delete(recorded)+    let fetched = try #require(context.fetch(FetchDescriptor<Administration>()).first)+    #expect(fetched.isDeleted)+    #expect(service.check(item, now: now).knownAmount == 0)+    #expect(recorded.id == action.eventID && recorded.isDeleted)+    // History deletion uses the correction service, including unlinked doses.+    var another = action+    another.eventID = UUID()+    let historical = try MedicationService(context: context).record(another)+    let corrections = RoutineSessionService(context: context, now: { self.now })+    try corrections.correct(+      historical, timestamp: historical.timestamp, dose: historical.recordedDose, delete: true)+    // The checker must refresh canonical rows rather than reading a stale relationship cache.+    #expect(service.check(item, now: now).knownAmount == 0)+    let deletedFlag = historical.isDeleted+    #expect(deletedFlag)+    #expect(historical.timestamp == another.timestamp && historical.recordedDose == another.dose)+  }+  @Test func matchingOldIngredientLabelsDoNotAddWarningsOrCombineOtherMedicationDoses() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let meds = MedicationService(context: store.mainContext)+    let first = try meds.createAsNeededMedication(name: "Synthetic A", dose: dose)+    let other = try meds.createAsNeededMedication(+      name: "Synthetic B", dose: .init(description: "", amount: 1, unit: "other unit"))+    let service = AsNeededLimitService(context: store.mainContext)+    try service.configure(first, limits: rules, now: now)+    var secondRules = rules+    secondRules.unit = "other unit"+    try service.configure(other, limits: secondRules, now: now)+    #expect(service.check(first, now: now).state == .withinEnteredLimits)+    #expect(service.check(first, now: now).knownAmount == 0)+    try meds.setActive(other, false)+    #expect(service.check(first, now: now).state == .withinEnteredLimits)+  }+  @Test func unrepresentableTotalsAndNonfiniteProposalsNeverBecomePositiveChecks() throws {+    let result = check([event(4 * 3600, amount: 9e127), event(5 * 3600, amount: 9e127)])+    #expect(result.state != .withinEnteredLimits)+    let invalid = check([], dose: .init(description: "", amount: .nan, unit: "measure"))+    #expect(invalid.state == .needsReview && invalid.proposedAmount == nil)+    _ = try JSONEncoder().encode(invalid)+  }+  @Test func statusReadsLeaveContextAutosaveAndStoredFactsUnchanged() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    let context = container.mainContext+    let item = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", dose: dose)+    try AsNeededLimitService(context: context).configure(item, limits: rules, now: now)+    context.autosaveEnabled = true+    let service = AsNeededLimitService(context: context)+    #expect(service.check(item, now: now).state == .withinEnteredLimits)+    #expect(context.autosaveEnabled && !context.hasChanges)+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func legacyContextIsPreservedAndUnchangedDraftDoesNotOverwriteNewerRules() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic", dose: dose)+    let service = AsNeededLimitService(context: store.mainContext)+    try service.configure(item, limits: rules, now: now)+    let draft = AsNeededLimitDraft(medication: item)+    var newer = rules+    newer.maximumAmount = 9+    try service.configure(item, limits: newer, now: now)+    try EditorTransaction.save(context: store.mainContext) {+      try draft.apply(to: item, context: store.mainContext)     }-    @Test func invalidAndUnreadableRulesFailExplicitlyAndRollbackEditor() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic")-        var invalid = rules; invalid.windowSeconds = nil-        #expect(throws: AsNeededLimitError.invalidConfiguration) {-            try EditorTransaction.save(context: store.mainContext) { item.name = "Changed"; try AsNeededLimitService(context: store.mainContext, deferSave: true).configure(item, limits: invalid, now: now) }-        }-        #expect(item.name == "Synthetic" && item.asNeededDoseLimitsData == nil)-        item.asNeededDoseLimitsData = Data("broken".utf8); try store.mainContext.save()-        #expect(AsNeededLimitService(context: store.mainContext).check(item, now: now).state == .needsReview)+    #expect(try service.limits(item)?.maximumAmount == 9)+    newer.productStrengthAndForm = "Synthetic changed formulation"+    try service.configure(item, limits: newer, now: now)+    #expect(try service.limits(item)?.historyConfirmedFrom == rules.historyConfirmedFrom)+  }+  @Test func invalidAndUnreadableRulesFailExplicitlyAndRollbackEditor() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic")+    var invalid = rules+    invalid.windowSeconds = nil+    #expect(throws: AsNeededLimitError.invalidConfiguration) {+      try EditorTransaction.save(context: store.mainContext) {+        item.name = "Changed"+        try AsNeededLimitService(context: store.mainContext, deferSave: true).configure(+          item, limits: invalid, now: now)+      }     }-    @Test func optionalRuleAndCachedCheckValuesPersistAcrossReload() throws {-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true); defer { try? FileManager.default.removeItem(at: directory) }-        let schema = AppEnvironment.schema; let config = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("limits.store"), cloudKitDatabase: .none)-        do {-            let container = try ModelContainer(for: schema, configurations: [config])-            let item = try MedicationService(context: container.mainContext).createAsNeededMedication(name: "Synthetic", dose: dose)-            try AsNeededLimitService(context: container.mainContext).configure(item, limits: rules, now: now)-        }-        let reopened = try ModelContainer(for: schema, configurations: [config])-        let item = try #require(reopened.mainContext.fetch(FetchDescriptor<Medication>()).first)-        #expect(try AsNeededLimitService(context: reopened.mainContext).limits(item) == rules)-        let value = CompanionMedication(id: item.id, name: item.name, purpose: nil, requirements: "", dose: dose, schedule: .init(id: item.id, mode: .asNeeded, generationID: nil, startedAt: nil), next: nil, lastTaken: nil, active: true, doseLimitCheck: check([]))-        #expect(try JSONDecoder().decode(CompanionMedication.self, from: JSONEncoder().encode(value)).doseLimitCheck?.state == .withinEnteredLimits)-        var legacy = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(value)) as? [String: Any]); legacy.removeValue(forKey: "doseLimitCheck")-        #expect(try JSONDecoder().decode(CompanionMedication.self, from: JSONSerialization.data(withJSONObject: legacy)).doseLimitCheck == nil)+    #expect(item.name == "Synthetic" && item.asNeededDoseLimitsData == nil)+    item.asNeededDoseLimitsData = Data("broken".utf8)+    try store.mainContext.save()+    #expect(+      AsNeededLimitService(context: store.mainContext).check(item, now: now).state == .needsReview)+  }+  @Test func optionalRuleAndCachedCheckValuesPersistAcrossReload() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let schema = AppEnvironment.schema+    let config = ModelConfiguration(+      schema: schema, url: directory.appendingPathComponent("limits.store"), cloudKitDatabase: .none+    )+    do {+      let container = try ModelContainer(for: schema, configurations: [config])+      let item = try MedicationService(context: container.mainContext).createAsNeededMedication(+        name: "Synthetic", dose: dose)+      try AsNeededLimitService(context: container.mainContext).configure(+        item, limits: rules, now: now)     }+    let reopened = try ModelContainer(for: schema, configurations: [config])+    let item = try #require(reopened.mainContext.fetch(FetchDescriptor<Medication>()).first)+    #expect(try AsNeededLimitService(context: reopened.mainContext).limits(item) == rules)+    let value = CompanionMedication(+      id: item.id, name: item.name, purpose: nil, requirements: "", dose: dose,+      schedule: .init(id: item.id, mode: .asNeeded, generationID: nil, startedAt: nil), next: nil,+      lastTaken: nil, active: true, doseLimitCheck: check([]))+    #expect(+      try JSONDecoder().decode(CompanionMedication.self, from: JSONEncoder().encode(value))+        .doseLimitCheck?.state == .withinEnteredLimits)+    var legacy = try #require(+      JSONSerialization.jsonObject(with: JSONEncoder().encode(value)) as? [String: Any])+    legacy.removeValue(forKey: "doseLimitCheck")+    #expect(+      try JSONDecoder().decode(+        CompanionMedication.self, from: JSONSerialization.data(withJSONObject: legacy)+      ).doseLimitCheck == nil)+  } }
Meddy/MeddyTests/MeddyCompanionStoreTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyCompanionStoreTests.swift b/Meddy/MeddyTests/MeddyCompanionStoreTests.swiftindex 07b216c..f062310 100644--- a/Meddy/MeddyTests/MeddyCompanionStoreTests.swift+++ b/Meddy/MeddyTests/MeddyCompanionStoreTests.swift@@ -1,76 +1,112 @@ import Foundation import Testing+ @testable import Meddy  @MainActor struct MeddyCompanionStoreTests {-    private func fixture() throws -> (URL, CompanionStore) {-        let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathComponent("cache.json")-        return (file, try CompanionStore(file: file))-    }-    private func action(_ id: UUID = UUID()) -> CompanionAction {-        .init(id: id, deviceID: "synthetic-device", timestamp: Date(), operation: .pause(runID: UUID()))-    }-    @Test func actionsAreDurableBeforeSendAndReplayIsOneOutboxEntry() throws {-        let (file, store) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let value = action(); try store.enqueue(value); try store.enqueue(value)-        #expect(store.state.pending.count == 1)-        let relaunched = try CompanionStore(file: file)-        #expect(relaunched.state.pending == [value])-        #expect(relaunched.state.deviceID == store.state.deviceID)-    }-    @Test func rejectedActionIsRetainedAndOnlySuccessfulAckRemovesItDurably() throws {-        let (file, store) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let value = action(); try store.enqueue(value)-        try store.acknowledge(.init(actionID: value.id, accepted: false, message: "Synthetic save failure"))-        #expect(try CompanionStore(file: file).state.pending == [value])-        try store.acknowledge(.init(actionID: value.id, accepted: true))-        #expect(try CompanionStore(file: file).state.pending.isEmpty)-    }-    @Test func unknownAckDoesNotDiscardOtherActualActions() throws {-        let (file, store) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let first = action(); let second = action(); try store.enqueue(first); try store.enqueue(second)-        try store.acknowledge(.init(actionID: UUID(), accepted: true))-        #expect(store.state.pending == [first, second])-        try store.acknowledge(.init(actionID: first.id, accepted: true))-        #expect(store.state.pending == [second])-    }-    @Test func staleAndUnrelatedPhoneSnapshotCannotOverwriteCanonicalCache() throws {-        let (file, store) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        var snapshot = CompanionSnapshot(phoneID: UUID(), revision: 2, generatedAt: Date(), medications: [], routines: [], runs: [], deletedEventIDs: [UUID()], appliedEventIDs: [])-        try store.receive(snapshot)-        snapshot.revision = 1-        #expect(throws: CompanionStoreError.self) { try store.receive(snapshot) }-        snapshot.revision = 3; snapshot.phoneID = UUID()-        #expect(throws: CompanionStoreError.self) { try store.receive(snapshot) }-        #expect(store.state.snapshot?.revision == 2)-    }-    @Test func malformedDiskCacheFailsVisiblyInsteadOfDroppingOutbox() throws {-        let (file, _) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)-        try Data("not-json".utf8).write(to: file)-        #expect(throws: (any Error).self) { _ = try CompanionStore(file: file) }-    }-    @Test func authoritativeTimerRevisionAndDeletedRunOverrideExecutableOverlay() throws {-        let (file, store) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let definition = FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "", roundCount: 1, roundDurationSeconds: 30, betweenRoundInstructions: "", steps: [])-        var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)-        try timer.start(at: ExecutionClock.sample())-        let local = CompanionRun(id: UUID(), definition: definition, progress: .init(definition: definition), timer: timer, status: .active, revision: 2, executionDeviceID: store.state.deviceID, processedActionIDs: [], isDeleted: false)-        try store.saveLocal([local])-        var canonical = local; canonical.timer?.phase = .interrupted; canonical.timer?.anchor = nil; canonical.timer?.deadline = nil-        var snapshot = CompanionSnapshot(phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [], routines: [], runs: [canonical], deletedEventIDs: [], appliedEventIDs: [])-        try store.receive(snapshot)-        #expect(store.state.localRuns[local.id]?.timer?.phase == .running)-        canonical.revision = 3; snapshot.revision = 2; snapshot.runs = [canonical]-        try store.receive(snapshot)-        #expect(store.state.localRuns[local.id] == nil)-        try store.saveLocal([local]); let pending = CompanionAction(id: UUID(), deviceID: store.state.deviceID, timestamp: Date(), operation: .pause(runID: local.id), cachedRun: local)-        try store.enqueue(pending)-        canonical.isDeleted = true; snapshot.revision = 3; snapshot.runs = [canonical]-        try store.receive(snapshot)-        #expect(store.state.localRuns[local.id] == nil)-        #expect(store.state.pending == [pending])-    }+  private func fixture() throws -> (URL, CompanionStore) {+    let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+      .appendingPathComponent("cache.json")+    return (file, try CompanionStore(file: file))+  }+  private func action(_ id: UUID = UUID()) -> CompanionAction {+    .init(id: id, deviceID: "synthetic-device", timestamp: Date(), operation: .pause(runID: UUID()))+  }+  @Test func actionsAreDurableBeforeSendAndReplayIsOneOutboxEntry() throws {+    let (file, store) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let value = action()+    try store.enqueue(value)+    try store.enqueue(value)+    #expect(store.state.pending.count == 1)+    let relaunched = try CompanionStore(file: file)+    #expect(relaunched.state.pending == [value])+    #expect(relaunched.state.deviceID == store.state.deviceID)+  }+  @Test func rejectedActionIsRetainedAndOnlySuccessfulAckRemovesItDurably() throws {+    let (file, store) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let value = action()+    try store.enqueue(value)+    try store.acknowledge(+      .init(actionID: value.id, accepted: false, message: "Synthetic save failure"))+    #expect(try CompanionStore(file: file).state.pending == [value])+    try store.acknowledge(.init(actionID: value.id, accepted: true))+    #expect(try CompanionStore(file: file).state.pending.isEmpty)+  }+  @Test func unknownAckDoesNotDiscardOtherActualActions() throws {+    let (file, store) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let first = action()+    let second = action()+    try store.enqueue(first)+    try store.enqueue(second)+    try store.acknowledge(.init(actionID: UUID(), accepted: true))+    #expect(store.state.pending == [first, second])+    try store.acknowledge(.init(actionID: first.id, accepted: true))+    #expect(store.state.pending == [second])+  }+  @Test func staleAndUnrelatedPhoneSnapshotCannotOverwriteCanonicalCache() throws {+    let (file, store) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    var snapshot = CompanionSnapshot(+      phoneID: UUID(), revision: 2, generatedAt: Date(), medications: [], routines: [], runs: [],+      deletedEventIDs: [UUID()], appliedEventIDs: [])+    try store.receive(snapshot)+    snapshot.revision = 1+    #expect(throws: CompanionStoreError.self) { try store.receive(snapshot) }+    snapshot.revision = 3+    snapshot.phoneID = UUID()+    #expect(throws: CompanionStoreError.self) { try store.receive(snapshot) }+    #expect(store.state.snapshot?.revision == 2)+  }+  @Test func malformedDiskCacheFailsVisiblyInsteadOfDroppingOutbox() throws {+    let (file, _) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    try FileManager.default.createDirectory(+      at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+    try Data("not-json".utf8).write(to: file)+    #expect(throws: (any Error).self) { _ = try CompanionStore(file: file) }+  }+  @Test func authoritativeTimerRevisionAndDeletedRunOverrideExecutableOverlay() throws {+    let (file, store) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let definition = FrozenRoutineDefinition(+      routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "",+      roundCount: 1, roundDurationSeconds: 30, betweenRoundInstructions: "", steps: [])+    var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)+    try timer.start(at: ExecutionClock.sample())+    let local = CompanionRun(+      id: UUID(), definition: definition, progress: .init(definition: definition), timer: timer,+      status: .active, revision: 2, executionDeviceID: store.state.deviceID, processedActionIDs: [],+      isDeleted: false)+    try store.saveLocal([local])+    var canonical = local+    canonical.timer?.phase = .interrupted+    canonical.timer?.anchor = nil+    canonical.timer?.deadline = nil+    var snapshot = CompanionSnapshot(+      phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [], routines: [],+      runs: [canonical], deletedEventIDs: [], appliedEventIDs: [])+    try store.receive(snapshot)+    #expect(store.state.localRuns[local.id]?.timer?.phase == .running)+    canonical.revision = 3+    snapshot.revision = 2+    snapshot.runs = [canonical]+    try store.receive(snapshot)+    #expect(store.state.localRuns[local.id] == nil)+    try store.saveLocal([local])+    let pending = CompanionAction(+      id: UUID(), deviceID: store.state.deviceID, timestamp: Date(),+      operation: .pause(runID: local.id), cachedRun: local)+    try store.enqueue(pending)+    canonical.isDeleted = true+    snapshot.revision = 3+    snapshot.runs = [canonical]+    try store.receive(snapshot)+    #expect(store.state.localRuns[local.id] == nil)+    #expect(store.state.pending == [pending])+  }  }
Meddy/MeddyTests/MeddyDefinitionTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyDefinitionTests.swift b/Meddy/MeddyTests/MeddyDefinitionTests.swiftindex dca9fe4..971ba07 100644--- a/Meddy/MeddyTests/MeddyDefinitionTests.swift+++ b/Meddy/MeddyTests/MeddyDefinitionTests.swift@@ -1,119 +1,190 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyDefinitionTests {-    private func container() throws -> ModelContainer { try AppEnvironment.makeContainer(isolated: true) }+  private func container() throws -> ModelContainer {+    try AppEnvironment.makeContainer(isolated: true)+  } -    @Test func nameOnlyTreatmentAndActualCompletionRemainSeparateFromDose() throws {-        let store = try container()-        let service = TreatmentService(context: store.mainContext)-        let treatment = try service.create(name: " Synthetic care ")-        #expect(treatment.name == "Synthetic care")-        #expect(treatment.purpose == nil)-        let action = TreatmentAction(eventID: UUID(), treatmentID: treatment.id, timestamp: Date(), instructionsSnapshot: "Frozen synthetic instructions", source: .phone)-        let completion = try service.record(action)-        try service.delete(completion)-        let replay = try service.record(action)-        #expect(replay.id == completion.id && replay.isDeleted)-        #expect(replay.instructionsSnapshot == action.instructionsSnapshot)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<TreatmentCompletion>()) == 1)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }+  @Test func nameOnlyTreatmentAndActualCompletionRemainSeparateFromDose() throws {+    let store = try container()+    let service = TreatmentService(context: store.mainContext)+    let treatment = try service.create(name: " Synthetic care ")+    #expect(treatment.name == "Synthetic care")+    #expect(treatment.purpose == nil)+    let action = TreatmentAction(+      eventID: UUID(), treatmentID: treatment.id, timestamp: Date(),+      instructionsSnapshot: "Frozen synthetic instructions", source: .phone)+    let completion = try service.record(action)+    try service.delete(completion)+    let replay = try service.record(action)+    #expect(replay.id == completion.id && replay.isDeleted)+    #expect(replay.instructionsSnapshot == action.instructionsSnapshot)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<TreatmentCompletion>()) == 1)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } -    @Test func futureWatchTreatmentTimeIsRetainedAndFlagged() throws {-        let store = try container()-        let clock = Date(timeIntervalSince1970: 1_000)-        let service = TreatmentService(context: store.mainContext, now: { clock })-        let treatment = try service.create(name: "Synthetic care")-        let action = TreatmentAction(eventID: UUID(), treatmentID: treatment.id, timestamp: clock.addingTimeInterval(300), instructionsSnapshot: "", source: .watch)-        let completion = try service.record(action)-        #expect(completion.timestamp == action.timestamp)-        #expect(completion.hasClockMismatch)-        var manual = action; manual.eventID = UUID(); manual.source = .manualHistory-        #expect(throws: DefinitionError.futureTime) { try service.record(manual) }-    }+  @Test func futureWatchTreatmentTimeIsRetainedAndFlagged() throws {+    let store = try container()+    let clock = Date(timeIntervalSince1970: 1_000)+    let service = TreatmentService(context: store.mainContext, now: { clock })+    let treatment = try service.create(name: "Synthetic care")+    let action = TreatmentAction(+      eventID: UUID(), treatmentID: treatment.id, timestamp: clock.addingTimeInterval(300),+      instructionsSnapshot: "", source: .watch)+    let completion = try service.record(action)+    #expect(completion.timestamp == action.timestamp)+    #expect(completion.hasClockMismatch)+    var manual = action+    manual.eventID = UUID()+    manual.source = .manualHistory+    #expect(throws: DefinitionError.futureTime) { try service.record(manual) }+  } -    @Test func timerSettingsAreUserProvidedPositiveValues() throws {-        let store = try container()-        let service = RoutineService(context: store.mainContext)-        #expect(throws: DefinitionError.invalidTimer) { try service.createTimed(name: "Synthetic timer", rounds: 0, durationSeconds: 20) }-        #expect(throws: DefinitionError.invalidTimer) { try service.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 0) }-        let timer = try service.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 17)-        #expect(timer.roundCount == 2 && timer.roundDurationSeconds == 17)-        #expect(timer.scheduleGenerationID == nil && timer.dailySlotsData == nil)+  @Test func timerSettingsAreUserProvidedPositiveValues() throws {+    let store = try container()+    let service = RoutineService(context: store.mainContext)+    #expect(throws: DefinitionError.invalidTimer) {+      try service.createTimed(name: "Synthetic timer", rounds: 0, durationSeconds: 20)     }--    @Test func reorderingPreservesStepIDsAndFrozenPlanAfterEdits() throws {-        let store = try container()-        let treatments = TreatmentService(context: store.mainContext)-        let a = try treatments.create(name: "Synthetic first")-        let b = try treatments.create(name: "Synthetic second")-        let drafts = [RoutineStepDraft(kind: .treatment, targetID: a.id), RoutineStepDraft(kind: .treatment, targetID: b.id)]-        let service = RoutineService(context: store.mainContext)-        let routine = try service.createOrdered(name: "Synthetic sequence", steps: drafts)-        let snapshot = try service.freeze(routine)-        let run = RoutineRun(routine: routine)-        run.definitionSnapshotData = try JSONEncoder().encode(snapshot)-        store.mainContext.insert(run); try store.mainContext.save()-        try service.updateOrdered(routine, name: "Edited", steps: Array(drafts.reversed()), instructions: "New instructions", purpose: nil)-        #expect((routine.steps ?? []).sorted { $0.position < $1.position }.map(\.id) == drafts.reversed().map(\.id))-        #expect(routine.definitionRevision == 2)-        #expect(try JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData) == snapshot)-        try treatments.setActive(a, false)-        #expect(throws: DefinitionError.invalidTarget) { try service.freeze(routine) }-        #expect(try JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData).steps.first?.name == "Synthetic first")+    #expect(throws: DefinitionError.invalidTimer) {+      try service.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 0)     }+    let timer = try service.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 17)+    #expect(timer.roundCount == 2 && timer.roundDurationSeconds == 17)+    #expect(timer.scheduleGenerationID == nil && timer.dailySlotsData == nil)+  }++  @Test func reorderingPreservesStepIDsAndFrozenPlanAfterEdits() throws {+    let store = try container()+    let treatments = TreatmentService(context: store.mainContext)+    let firstTreatment = try treatments.create(name: "Synthetic first")+    let secondTreatment = try treatments.create(name: "Synthetic second")+    let drafts = [+      RoutineStepDraft(kind: .treatment, targetID: firstTreatment.id),+      RoutineStepDraft(kind: .treatment, targetID: secondTreatment.id)+    ]+    let service = RoutineService(context: store.mainContext)+    let routine = try service.createOrdered(name: "Synthetic sequence", steps: drafts)+    let snapshot = try service.freeze(routine)+    let run = RoutineRun(routine: routine)+    run.definitionSnapshotData = try JSONEncoder().encode(snapshot)+    store.mainContext.insert(run)+    try store.mainContext.save()+    try service.updateOrdered(+      routine, name: "Edited", steps: Array(drafts.reversed()), instructions: "New instructions",+      purpose: nil)+    #expect(+      (routine.steps ?? []).sorted { $0.position < $1.position }.map(\.id)+        == drafts.reversed().map(\.id))+    #expect(routine.definitionRevision == 2)+    #expect(+      try JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData)+        == snapshot)+    try treatments.setActive(firstTreatment, false)+    #expect(throws: DefinitionError.invalidTarget) { try service.freeze(routine) }+    #expect(+      try JSONDecoder().decode(FrozenRoutineDefinition.self, from: run.definitionSnapshotData).steps+        .first?.name == "Synthetic first")+  } -    @Test func builderRejectsMissingNestedAndDuplicateMedicationReferences() throws {-        let store = try container()-        let service = RoutineService(context: store.mainContext)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let group = try service.createOrdered(name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])-        #expect(throws: DefinitionError.nestedRoutine) { try service.createOrdered(name: "Nested", steps: [.init(kind: .timedRoutine, targetID: group.id)]) }-        #expect(throws: DefinitionError.invalidTarget) { try service.createOrdered(name: "Missing", steps: [.init(kind: .treatment, targetID: UUID())]) }-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        let duplicated = [RoutineStepDraft(kind: .medication, targetID: medication.id), RoutineStepDraft(kind: .medication, targetID: medication.id)]-        #expect(throws: DefinitionError.duplicateMedication) { try service.createOrdered(name: "Duplicate", steps: duplicated, confirmedMedicationIDs: [medication.id]) }-        #expect(medication.managedByRoutineID == nil)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Routine>()) == 1)+  @Test func builderRejectsMissingNestedAndDuplicateMedicationReferences() throws {+    let store = try container()+    let service = RoutineService(context: store.mainContext)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let group = try service.createOrdered(+      name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])+    #expect(throws: DefinitionError.nestedRoutine) {+      try service.createOrdered(+        name: "Nested", steps: [.init(kind: .timedRoutine, targetID: group.id)])     }+    #expect(throws: DefinitionError.invalidTarget) {+      try service.createOrdered(name: "Missing", steps: [.init(kind: .treatment, targetID: UUID())])+    }+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    let duplicated = [+      RoutineStepDraft(kind: .medication, targetID: medication.id),+      RoutineStepDraft(kind: .medication, targetID: medication.id)+    ]+    #expect(throws: DefinitionError.duplicateMedication) {+      try service.createOrdered(+        name: "Duplicate", steps: duplicated, confirmedMedicationIDs: [medication.id])+    }+    #expect(medication.managedByRoutineID == nil)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Routine>()) == 1)+  } -    @Test func ownershipRequiresConfirmationAndNeverRewritesHistory() throws {-        let store = try container()-        let medications = MedicationService(context: store.mainContext)-        let medication = try medications.createAsNeededMedication(name: "Synthetic item")-        let event = try medications.record(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        medication.remindersEnabled = true; medication.dosesPerDay = 4; medication.scheduleGenerationID = UUID()-        try store.mainContext.save()-        let service = RoutineService(context: store.mainContext)-        let steps = [RoutineStepDraft(kind: .medication, targetID: medication.id)]-        #expect(throws: DefinitionError.ownershipConfirmationRequired) { try service.createOrdered(name: "Synthetic group", steps: steps) }-        #expect(medication.remindersEnabled)-        let group = try service.createOrdered(name: "Synthetic group", steps: steps, confirmedMedicationIDs: [medication.id])-        #expect(medication.managedByRoutineID == group.id)-        #expect(!medication.remindersEnabled && medication.dosesPerDay == nil && medication.scheduleGenerationID == nil)-        #expect(event.scheduleTypeAtRecordingRaw == MedicationScheduleType.asNeeded.rawValue)-        #expect(!event.isDeleted)-        #expect(throws: DefinitionError.otherOwner) { try service.createOrdered(name: "Other group", steps: steps, confirmedMedicationIDs: [medication.id]) }+  @Test func ownershipRequiresConfirmationAndNeverRewritesHistory() throws {+    let store = try container()+    let medications = MedicationService(context: store.mainContext)+    let medication = try medications.createAsNeededMedication(name: "Synthetic item")+    let event = try medications.record(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    medication.remindersEnabled = true+    medication.dosesPerDay = 4+    medication.scheduleGenerationID = UUID()+    try store.mainContext.save()+    let service = RoutineService(context: store.mainContext)+    let steps = [RoutineStepDraft(kind: .medication, targetID: medication.id)]+    #expect(throws: DefinitionError.ownershipConfirmationRequired) {+      try service.createOrdered(name: "Synthetic group", steps: steps)+    }+    #expect(medication.remindersEnabled)+    let group = try service.createOrdered(+      name: "Synthetic group", steps: steps, confirmedMedicationIDs: [medication.id])+    #expect(medication.managedByRoutineID == group.id)+    #expect(+      !medication.remindersEnabled && medication.dosesPerDay == nil+        && medication.scheduleGenerationID == nil)+    #expect(event.scheduleTypeAtRecordingRaw == MedicationScheduleType.asNeeded.rawValue)+    #expect(!event.isDeleted)+    #expect(throws: DefinitionError.otherOwner) {+      try service.createOrdered(+        name: "Other group", steps: steps, confirmedMedicationIDs: [medication.id])     }+  } -    @Test func releaseRequiresExplicitModeAndBlocksUnresolvedSavedSessions() throws {-        let store = try container()-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        let treatment = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let service = RoutineService(context: store.mainContext)-        let group = try service.createOrdered(name: "Synthetic group", steps: [.init(kind: .medication, targetID: medication.id), .init(kind: .treatment, targetID: treatment.id)], confirmedMedicationIDs: [medication.id])-        let remaining = (group.steps ?? []).filter { $0.targetKindRaw == "treatment" }.map { RoutineStepDraft(id: $0.id, kind: .treatment, targetID: $0.targetID) }-        #expect(throws: DefinitionError.releaseChoiceRequired) { try service.updateOrdered(group, name: group.name, steps: remaining, instructions: "", purpose: nil) }-        let run = RoutineRun(routine: group); run.definitionSnapshotData = try JSONEncoder().encode(service.freeze(group))-        store.mainContext.insert(run); try store.mainContext.save()-        #expect(throws: DefinitionError.unresolvedFrozenStep) { try service.updateOrdered(group, name: group.name, steps: remaining, instructions: "", purpose: nil, releasedAsNeededMedicationIDs: [medication.id]) }-        run.statusRaw = "endedIncomplete"; try store.mainContext.save()-        try service.updateOrdered(group, name: group.name, steps: remaining, instructions: "", purpose: nil, releasedAsNeededMedicationIDs: [medication.id])-        #expect(medication.managedByRoutineID == nil && medication.scheduleTypeRaw == "asNeeded")-        #expect(!medication.remindersEnabled)+  @Test func releaseRequiresExplicitModeAndBlocksUnresolvedSavedSessions() throws {+    let store = try container()+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    let treatment = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let service = RoutineService(context: store.mainContext)+    let group = try service.createOrdered(+      name: "Synthetic group",+      steps: [+        .init(kind: .medication, targetID: medication.id),+        .init(kind: .treatment, targetID: treatment.id)+      ], confirmedMedicationIDs: [medication.id])+    let remaining = (group.steps ?? []).filter { $0.targetKindRaw == "treatment" }.map {+      RoutineStepDraft(id: $0.id, kind: .treatment, targetID: $0.targetID)+    }+    #expect(throws: DefinitionError.releaseChoiceRequired) {+      try service.updateOrdered(+        group, name: group.name, steps: remaining, instructions: "", purpose: nil)+    }+    let run = RoutineRun(routine: group)+    run.definitionSnapshotData = try JSONEncoder().encode(service.freeze(group))+    store.mainContext.insert(run)+    try store.mainContext.save()+    #expect(throws: DefinitionError.unresolvedFrozenStep) {+      try service.updateOrdered(+        group, name: group.name, steps: remaining, instructions: "", purpose: nil,+        releasedAsNeededMedicationIDs: [medication.id])     }+    run.statusRaw = "endedIncomplete"+    try store.mainContext.save()+    try service.updateOrdered(+      group, name: group.name, steps: remaining, instructions: "", purpose: nil,+      releasedAsNeededMedicationIDs: [medication.id])+    #expect(medication.managedByRoutineID == nil && medication.scheduleTypeRaw == "asNeeded")+    #expect(!medication.remindersEnabled)+  } }
Meddy/MeddyTests/MeddyEditorReviewTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyEditorReviewTests.swift b/Meddy/MeddyTests/MeddyEditorReviewTests.swiftindex 720f5e1..22f7149 100644--- a/Meddy/MeddyTests/MeddyEditorReviewTests.swift+++ b/Meddy/MeddyTests/MeddyEditorReviewTests.swift@@ -1,75 +1,110 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyEditorReviewTests {-    @Test func invalidScheduleRollsBackNewDefinitionAndMedicationOwnershipTogether() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        #expect(throws: DefinitionError.invalidSchedule) {-            try EditorTransaction.save(context: store.mainContext) {-                let routine = try RoutineService(context: store.mainContext, deferSave: true).createOrdered(name: "Synthetic sequence", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id])-                try ScheduleService(context: store.mainContext, deferSave: true).configure(routine, slots: [.init()], reminders: true)-            }-        }-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Routine>()) == 0)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineStep>()) == 0)-        #expect(medication.managedByRoutineID == nil && medication.scheduleTypeRaw == "asNeeded")+  @Test func invalidScheduleRollsBackNewDefinitionAndMedicationOwnershipTogether() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    #expect(throws: DefinitionError.invalidSchedule) {+      try EditorTransaction.save(context: store.mainContext) {+        let routine = try RoutineService(context: store.mainContext, deferSave: true).createOrdered(+          name: "Synthetic sequence", steps: [.init(kind: .medication, targetID: medication.id)],+          confirmedMedicationIDs: [medication.id])+        try ScheduleService(context: store.mainContext, deferSave: true).configure(+          routine, slots: [.init()], reminders: true)+      }     }+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Routine>()) == 0)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineStep>()) == 0)+    #expect(medication.managedByRoutineID == nil && medication.scheduleTypeRaw == "asNeeded")+  } -    @Test func explicitReviewedSkipPreservesRealDoseAndRequiresSeparateContinue() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        let routine = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic sequence", steps: [.init(kind: .treatment, targetID: care.id), .init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id])-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(routine), steps = try service.definition(run).steps-        let completion = try service.recordTreatment(.init(eventID: UUID(), treatmentID: care.id, timestamp: Date(), instructionsSnapshot: "", source: .phone), in: run, stepID: steps[0].id)-        let dose = try service.recordMedication(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil), in: run, stepID: steps[1].id)-        try service.correct(completion, timestamp: completion.timestamp.addingTimeInterval(-60))-        try service.resolveReview(run, stepID: steps[0].id, resolution: .skip, actionID: UUID())-        try service.reconcile(run)-        #expect(try service.progress(run).steps[0].state == .skipped)-        #expect(run.statusRaw == "active" && !run.wasCompleted)-        try service.continueAfterSkip(run, stepID: steps[0].id, actionID: UUID())-        #expect(run.statusRaw == "finishedWithSkips" && !run.wasCompleted)-        #expect(!dose.isDeleted && !completion.isDeleted)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-    }+  @Test func explicitReviewedSkipPreservesRealDoseAndRequiresSeparateContinue() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    let routine = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic sequence",+      steps: [+        .init(kind: .treatment, targetID: care.id),+        .init(kind: .medication, targetID: medication.id)+      ], confirmedMedicationIDs: [medication.id])+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(routine)+    let steps = try service.definition(run).steps+    let completion = try service.recordTreatment(+      .init(+        eventID: UUID(), treatmentID: care.id, timestamp: Date(), instructionsSnapshot: "",+        source: .phone), in: run, stepID: steps[0].id)+    let dose = try service.recordMedication(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil),+      in: run, stepID: steps[1].id)+    try service.correct(completion, timestamp: completion.timestamp.addingTimeInterval(-60))+    try service.resolveReview(run, stepID: steps[0].id, resolution: .skip, actionID: UUID())+    try service.reconcile(run)+    #expect(try service.progress(run).steps[0].state == .skipped)+    #expect(run.statusRaw == "active" && !run.wasCompleted)+    try service.continueAfterSkip(run, stepID: steps[0].id, actionID: UUID())+    #expect(run.statusRaw == "finishedWithSkips" && !run.wasCompleted)+    #expect(!dose.isDeleted && !completion.isDeleted)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  } -    @Test func correctionReviewCannotImplicitlyReopenAnEndedSession() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let group = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic sequence", steps: [.init(kind: .treatment, targetID: care.id), .init(kind: .treatment, targetID: care.id)])-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group), step = try service.definition(run).steps[0]-        let completion = try service.recordTreatment(.init(eventID: UUID(), treatmentID: care.id, timestamp: Date(), instructionsSnapshot: "", source: .phone), in: run, stepID: step.id)-        try service.end(run, actionID: UUID())-        try service.correct(completion, timestamp: completion.timestamp.addingTimeInterval(-5))-        let actionID = UUID()-        try service.resolveReview(run, stepID: step.id, resolution: .acceptCanonical, actionID: actionID)-        try service.resolveReview(run, stepID: step.id, resolution: .acceptCanonical, actionID: actionID)-        #expect(run.statusRaw == "endedIncomplete")-        try service.reopen(run, actionID: UUID())-        #expect(run.statusRaw == "active")-    }+  @Test func correctionReviewCannotImplicitlyReopenAnEndedSession() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let group = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic sequence",+      steps: [+        .init(kind: .treatment, targetID: care.id), .init(kind: .treatment, targetID: care.id)+      ])+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let step = try service.definition(run).steps[0]+    let completion = try service.recordTreatment(+      .init(+        eventID: UUID(), treatmentID: care.id, timestamp: Date(), instructionsSnapshot: "",+        source: .phone), in: run, stepID: step.id)+    try service.end(run, actionID: UUID())+    try service.correct(completion, timestamp: completion.timestamp.addingTimeInterval(-5))+    let actionID = UUID()+    try service.resolveReview(+      run, stepID: step.id, resolution: .acceptCanonical, actionID: actionID)+    try service.resolveReview(+      run, stepID: step.id, resolution: .acceptCanonical, actionID: actionID)+    #expect(run.statusRaw == "endedIncomplete")+    try service.reopen(run, actionID: UUID())+    #expect(run.statusRaw == "active")+  } -    @Test func parentPauseStopsChildActiveTimeAndResumeDoesNotAutoStartTimer() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let definitions = RoutineService(context: store.mainContext)-        let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)-        let group = try definitions.createOrdered(name: "Synthetic sequence", steps: [.init(kind: .timedRoutine, targetID: timer.id)])-        let service = RoutineSessionService(context: store.mainContext)-        let parent = try service.start(group), stepID = try service.definition(parent).steps[0].id-        let child = try service.beginTimedStep(parent, stepID: stepID)-        let clock = ClockSample(wall: Date(timeIntervalSince1970: 100), monotonic: 100, continuityID: "synthetic")-        try service.changeTimer(child, actionID: UUID(), clock: clock, operation: .start)-        try service.pause(parent, actionID: UUID(), clock: .init(wall: clock.wall.addingTimeInterval(10), monotonic: 110, continuityID: "synthetic"))-        #expect(try service.timer(child).phase == .paused)-        #expect(try service.timer(child).accumulatedActiveSeconds == 10)-        try service.resume(parent, actionID: UUID())-        #expect(try service.timer(child).phase == .paused)-    }+  @Test func parentPauseStopsChildActiveTimeAndResumeDoesNotAutoStartTimer() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)+    let group = try definitions.createOrdered(+      name: "Synthetic sequence", steps: [.init(kind: .timedRoutine, targetID: timer.id)])+    let service = RoutineSessionService(context: store.mainContext)+    let parent = try service.start(group)+    let stepID = try service.definition(parent).steps[0].id+    let child = try service.beginTimedStep(parent, stepID: stepID)+    let clock = ClockSample(+      wall: Date(timeIntervalSince1970: 100), monotonic: 100, continuityID: "synthetic")+    try service.changeTimer(child, actionID: UUID(), clock: clock, operation: .start)+    try service.pause(+      parent, actionID: UUID(),+      clock: .init(+        wall: clock.wall.addingTimeInterval(10), monotonic: 110, continuityID: "synthetic"))+    #expect(try service.timer(child).phase == .paused)+    #expect(try service.timer(child).accumulatedActiveSeconds == 10)+    try service.resume(parent, actionID: UUID())+    #expect(try service.timer(child).phase == .paused)+  } }
Meddy/MeddyTests/MeddyExecutionTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyExecutionTests.swift b/Meddy/MeddyTests/MeddyExecutionTests.swiftindex 963dd12..ab3f9f2 100644--- a/Meddy/MeddyTests/MeddyExecutionTests.swift+++ b/Meddy/MeddyTests/MeddyExecutionTests.swift@@ -1,111 +1,141 @@ import Foundation import Testing+ @testable import Meddy  struct MeddyExecutionTests {-    private func clock(_ seconds: Double, continuity: String = "synthetic-launch") -> ClockSample {-        ClockSample(wall: Date(timeIntervalSince1970: seconds), monotonic: seconds, continuityID: continuity)-    }-    private func definition() -> FrozenRoutineDefinition {-        FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic sequence", instructions: "", roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "", steps: (0..<3).map {-            FrozenRoutineStep(id: UUID(), position: $0, kind: $0 == 2 ? .medication : .treatment, targetID: UUID(), name: "Synthetic step", instructions: "", requirements: "", dose: .unknown, roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "")-        })-    }+  private func clock(_ seconds: Double, continuity: String = "synthetic-launch") -> ClockSample {+    ClockSample(+      wall: Date(timeIntervalSince1970: seconds), monotonic: seconds, continuityID: continuity)+  }+  private func definition() -> FrozenRoutineDefinition {+    FrozenRoutineDefinition(+      routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic sequence", instructions: "",+      roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "",+      steps: (0..<3).map {+        FrozenRoutineStep(+          id: UUID(), position: $0, kind: $0 == 2 ? .medication : .treatment, targetID: UUID(),+          name: "Synthetic step", instructions: "", requirements: "", dose: .unknown,+          roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "")+      })+  } -    @Test func twoRoundsWaitIndefinitelyAndNeverAutoStart() throws {-        var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 20)-        try timer.start(at: clock(100))-        #expect(timer.remaining(at: clock(110)) == 10)-        let boundary1 = timer.advance(at: clock(110))-        #expect(!boundary1)-        let boundary2 = timer.advance(at: clock(120))-        #expect(boundary2)-        #expect(timer.phase == .waiting && timer.completedRounds == 1)-        let boundary3 = timer.advance(at: clock(900))-        #expect(!boundary3)-        #expect(timer.phase == .waiting)-        try timer.start(at: clock(900))-        let boundary4 = timer.advance(at: clock(920))-        #expect(boundary4)-        #expect(timer.phase == .completed && timer.completedRounds == 2)-        #expect(throws: ExecutionError.invalidTransition) { try timer.start(at: clock(930)) }-    }+  @Test func twoRoundsWaitIndefinitelyAndNeverAutoStart() throws {+    var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 20)+    try timer.start(at: clock(100))+    #expect(timer.remaining(at: clock(110)) == 10)+    let boundary1 = timer.advance(at: clock(110))+    #expect(!boundary1)+    let boundary2 = timer.advance(at: clock(120))+    #expect(boundary2)+    #expect(timer.phase == .waiting && timer.completedRounds == 1)+    let boundary3 = timer.advance(at: clock(900))+    #expect(!boundary3)+    #expect(timer.phase == .waiting)+    try timer.start(at: clock(900))+    let boundary4 = timer.advance(at: clock(920))+    #expect(boundary4)+    #expect(timer.phase == .completed && timer.completedRounds == 2)+    #expect(throws: ExecutionError.invalidTransition) { try timer.start(at: clock(930)) }+  } -    @Test func pauseExcludesWaitingAndRetainsRemainingActiveTime() throws {-        var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)-        try timer.start(at: clock(100))-        try timer.pause(at: clock(111))-        #expect(timer.remaining(at: clock(500)) == 19)-        let data = try JSONEncoder().encode(timer)-        timer = try JSONDecoder().decode(TimerCheckpoint.self, from: data)-        try timer.resume(at: clock(500))-        let boundary5 = timer.advance(at: clock(518))-        #expect(!boundary5)-        let boundary6 = timer.advance(at: clock(519))-        #expect(boundary6)-        #expect(timer.phase == .completed)-    }+  @Test func pauseExcludesWaitingAndRetainsRemainingActiveTime() throws {+    var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)+    try timer.start(at: clock(100))+    try timer.pause(at: clock(111))+    #expect(timer.remaining(at: clock(500)) == 19)+    let data = try JSONEncoder().encode(timer)+    timer = try JSONDecoder().decode(TimerCheckpoint.self, from: data)+    try timer.resume(at: clock(500))+    let boundary5 = timer.advance(at: clock(518))+    #expect(!boundary5)+    let boundary6 = timer.advance(at: clock(519))+    #expect(boundary6)+    #expect(timer.phase == .completed)+  } -    @Test func uncertainRestartAndClockChangeRequireExplicitResume() throws {-        var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)-        try timer.start(at: clock(100))-        let boundary7 = timer.advance(at: clock(150, continuity: "new-launch"))-        #expect(boundary7)-        #expect(timer.phase == .interrupted && timer.completedRounds == 0)-        try timer.resume(at: clock(150, continuity: "new-launch"))-        var jumped = clock(155, continuity: "new-launch"); jumped.wall = jumped.wall.addingTimeInterval(3600)-        let boundary8 = timer.advance(at: jumped)-        #expect(boundary8)-        #expect(timer.phase == .interrupted && timer.completedRounds == 0)-    }+  @Test func uncertainRestartAndClockChangeRequireExplicitResume() throws {+    var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)+    try timer.start(at: clock(100))+    let boundary7 = timer.advance(at: clock(150, continuity: "new-launch"))+    #expect(boundary7)+    #expect(timer.phase == .interrupted && timer.completedRounds == 0)+    try timer.resume(at: clock(150, continuity: "new-launch"))+    var jumped = clock(155, continuity: "new-launch")+    jumped.wall = jumped.wall.addingTimeInterval(3600)+    let boundary8 = timer.advance(at: jumped)+    #expect(boundary8)+    #expect(timer.phase == .interrupted && timer.completedRounds == 0)+  } -    @Test func endIsTerminalUntilExplicitReopenWithoutAutoTiming() throws {-        var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)-        try timer.start(at: clock(100)); try timer.end(at: clock(110))-        #expect(timer.phase == .ended)-        #expect(throws: ExecutionError.invalidTransition) { try timer.resume(at: clock(200)) }-        try timer.reopen()-        #expect(timer.phase == .paused && timer.remaining(at: clock(200)) == 20)-    }+  @Test func endIsTerminalUntilExplicitReopenWithoutAutoTiming() throws {+    var timer = try TimerCheckpoint(rounds: 1, durationSeconds: 30)+    try timer.start(at: clock(100))+    try timer.end(at: clock(110))+    #expect(timer.phase == .ended)+    #expect(throws: ExecutionError.invalidTransition) { try timer.resume(at: clock(200)) }+    try timer.reopen()+    #expect(timer.phase == .paused && timer.remaining(at: clock(200)) == 20)+  } -    @Test func skipRequiresSeparateContinueAndCannotClaimFullCompletion() throws {-        let definition = definition(); var session = OrderedCheckpoint(definition: definition)-        let first = definition.steps[0].id-        try session.skip(stepID: first, actionID: UUID(), at: Date(), reason: "User skipped")-        #expect(session.nextReadyStepID == nil)-        #expect(throws: ExecutionError.stepNotReady) { try session.markCompleted(stepID: definition.steps[1].id, eventID: UUID(), at: Date(), actionID: UUID()) }-        try session.continueAfterSkip(stepID: first)-        #expect(session.nextReadyStepID == definition.steps[1].id)-        for step in definition.steps.dropFirst() { try session.markCompleted(stepID: step.id, eventID: UUID(), at: Date(), actionID: UUID()) }-        #expect(session.phase == .finishedWithSkips)-        #expect(session.steps[0].canonicalEventID == nil)+  @Test func skipRequiresSeparateContinueAndCannotClaimFullCompletion() throws {+    let definition = definition()+    var session = OrderedCheckpoint(definition: definition)+    let first = definition.steps[0].id+    try session.skip(stepID: first, actionID: UUID(), at: Date(), reason: "User skipped")+    #expect(session.nextReadyStepID == nil)+    #expect(throws: ExecutionError.stepNotReady) {+      try session.markCompleted(+        stepID: definition.steps[1].id, eventID: UUID(), at: Date(), actionID: UUID())     }--    @Test func prerequisiteCorrectionPreservesLaterRealMedication() throws {-        let definition = definition(); var session = OrderedCheckpoint(definition: definition)-        let events = definition.steps.map { _ in UUID() }-        for (step, event) in zip(definition.steps, events) { try session.markCompleted(stepID: step.id, eventID: event, at: Date(), actionID: event) }-        #expect(session.phase == .completed)-        try session.invalidate(stepID: definition.steps[0].id, audit: .init(actionID: UUID(), timestamp: Date(), reason: "Undo", previousState: .completed, previousEventID: events[0]))-        #expect(session.phase == .needsReview && session.nextReadyStepID == nil)-        #expect(session.steps[2].canonicalEventID == events[2] && session.steps[2].state == .completed)+    try session.continueAfterSkip(stepID: first)+    #expect(session.nextReadyStepID == definition.steps[1].id)+    for step in definition.steps.dropFirst() {+      try session.markCompleted(stepID: step.id, eventID: UUID(), at: Date(), actionID: UUID())     }+    #expect(session.phase == .finishedWithSkips)+    #expect(session.steps[0].canonicalEventID == nil)+  } -    @Test func outOfOrderReportedActionIsRetainedForReview() throws {-        let definition = definition(); var session = OrderedCheckpoint(definition: definition)-        let event = UUID()-        try session.markCompleted(stepID: definition.steps[2].id, eventID: event, at: Date(), actionID: event, reportedOutOfOrder: true)-        #expect(session.phase == .needsReview)-        #expect(session.steps[2].canonicalEventID == event)-        #expect(session.steps[0].state == .pending)+  @Test func prerequisiteCorrectionPreservesLaterRealMedication() throws {+    let definition = definition()+    var session = OrderedCheckpoint(definition: definition)+    let events = definition.steps.map { _ in UUID() }+    for (step, event) in zip(definition.steps, events) {+      try session.markCompleted(stepID: step.id, eventID: event, at: Date(), actionID: event)     }+    #expect(session.phase == .completed)+    try session.invalidate(+      stepID: definition.steps[0].id,+      audit: .init(+        actionID: UUID(), timestamp: Date(), reason: "Undo", previousState: .completed,+        previousEventID: events[0]))+    #expect(session.phase == .needsReview && session.nextReadyStepID == nil)+    #expect(session.steps[2].canonicalEventID == events[2] && session.steps[2].state == .completed)+  }++  @Test func outOfOrderReportedActionIsRetainedForReview() throws {+    let definition = definition()+    var session = OrderedCheckpoint(definition: definition)+    let event = UUID()+    try session.markCompleted(+      stepID: definition.steps[2].id, eventID: event, at: Date(), actionID: event,+      reportedOutOfOrder: true)+    #expect(session.phase == .needsReview)+    #expect(session.steps[2].canonicalEventID == event)+    #expect(session.steps[0].state == .pending)+  } -    @Test func duplicateCompletionIsIdempotentAfterTraversalCompletes() throws {-        let definition = definition(); var session = OrderedCheckpoint(definition: definition)-        let events = definition.steps.map { _ in UUID() }-        for (step, event) in zip(definition.steps, events) { try session.markCompleted(stepID: step.id, eventID: event, at: Date(), actionID: event) }-        let snapshot = session-        try session.markCompleted(stepID: definition.steps[2].id, eventID: events[2], at: Date(), actionID: events[2])-        #expect(session == snapshot)+  @Test func duplicateCompletionIsIdempotentAfterTraversalCompletes() throws {+    let definition = definition()+    var session = OrderedCheckpoint(definition: definition)+    let events = definition.steps.map { _ in UUID() }+    for (step, event) in zip(definition.steps, events) {+      try session.markCompleted(stepID: step.id, eventID: event, at: Date(), actionID: event)     }+    let snapshot = session+    try session.markCompleted(+      stepID: definition.steps[2].id, eventID: events[2], at: Date(), actionID: events[2])+    #expect(session == snapshot)+  } }
Meddy/MeddyTests/MeddyFirstSliceTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyFirstSliceTests.swift b/Meddy/MeddyTests/MeddyFirstSliceTests.swiftindex efae5ac..4d8d15f 100644--- a/Meddy/MeddyTests/MeddyFirstSliceTests.swift+++ b/Meddy/MeddyTests/MeddyFirstSliceTests.swift@@ -1,159 +1,169 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyFirstSliceTests {-    private func store() throws -> ModelContainer {-        let schema = AppEnvironment.schema-        let configuration = ModelConfiguration(-            schema: schema,-            isStoredInMemoryOnly: true,-            cloudKitDatabase: .none-        )-        return try ModelContainer(for: schema, configurations: [configuration])-    }+  private func store() throws -> ModelContainer {+    let schema = AppEnvironment.schema+    let configuration = ModelConfiguration(+      schema: schema,+      isStoredInMemoryOnly: true,+      cloudKitDatabase: .none+    )+    return try ModelContainer(for: schema, configurations: [configuration])+  } -    @Test func nameOnlyMedicationHasNoScheduleOrDose() throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        #expect(medication.scheduleTypeRaw == MedicationScheduleType.asNeeded.rawValue)-        #expect(medication.defaultDoseAmount == nil)-        #expect(medication.defaultDoseUnit == nil)-        #expect(medication.scheduleGenerationID == nil)-        #expect(medication.scheduleStartedAt == nil)-        #expect(!medication.remindersEnabled)-        #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }+  @Test func nameOnlyMedicationHasNoScheduleOrDose() throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    #expect(medication.scheduleTypeRaw == MedicationScheduleType.asNeeded.rawValue)+    #expect(medication.defaultDoseAmount == nil)+    #expect(medication.defaultDoseUnit == nil)+    #expect(medication.scheduleGenerationID == nil)+    #expect(medication.scheduleStartedAt == nil)+    #expect(!medication.remindersEnabled)+    #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } -    @Test func unknownDoseAndReplayRetainOneEvent() throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        let action = AdministrationAction(-            eventID: UUID(), medicationID: medication.id,-            timestamp: Date(timeIntervalSince1970: 1_700_000_000),-            source: .phone, dose: .unknown,-            scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-        )-        let first = try service.record(action)-        let retry = try service.record(action)-        #expect(first.id == retry.id)-        #expect(first.doseAmount == nil)-        #expect(first.doseDescriptionSnapshot.isEmpty)-        #expect(first.timestamp == action.timestamp)-        #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-    }+  @Test func unknownDoseAndReplayRetainOneEvent() throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id,+      timestamp: Date(timeIntervalSince1970: 1_700_000_000),+      source: .phone, dose: .unknown,+      scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+    )+    let first = try service.record(action)+    let retry = try service.record(action)+    #expect(first.id == retry.id)+    #expect(first.doseAmount == nil)+    #expect(first.doseDescriptionSnapshot.isEmpty)+    #expect(first.timestamp == action.timestamp)+    #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  } -    @Test func correctionAndUndoCannotBeRevertedByReplay() throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        let action = AdministrationAction(-            eventID: UUID(), medicationID: medication.id,-            timestamp: Date(timeIntervalSince1970: 1_700_000_000),-            source: .phone, dose: .unknown,-            scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-        )-        let event = try service.record(action)-        let corrected = action.timestamp.addingTimeInterval(-60)-        try service.correct(event, timestamp: corrected, dose: .unknown)-        #expect(try service.record(action).timestamp == corrected)-        try service.delete(event)-        #expect(try service.record(action).isDeleted)-        #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-    }+  @Test func correctionAndUndoCannotBeRevertedByReplay() throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id,+      timestamp: Date(timeIntervalSince1970: 1_700_000_000),+      source: .phone, dose: .unknown,+      scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+    )+    let event = try service.record(action)+    let corrected = action.timestamp.addingTimeInterval(-60)+    try service.correct(event, timestamp: corrected, dose: .unknown)+    #expect(try service.record(action).timestamp == corrected)+    try service.delete(event)+    #expect(try service.record(action).isDeleted)+    #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  } -    @Test func snapshotsSurviveLaterDefaultsAndDistinctActions() throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        let original = RecordedDoseSnapshot(description: "Synthetic label", amount: 1, unit: "test unit")-        let time = Date(timeIntervalSince1970: 1_700_000_000)-        for _ in 0..<2 {-            _ = try service.record(AdministrationAction(-                eventID: UUID(), medicationID: medication.id, timestamp: time,-                source: .phone, dose: original,-                scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-            ))-        }-        medication.doseDescription = "Changed label"-        try container.mainContext.save()-        let events = try container.mainContext.fetch(FetchDescriptor<Administration>())-        #expect(events.count == 2)-        #expect(events.allSatisfy { $0.doseDescriptionSnapshot == original.description })+  @Test func snapshotsSurviveLaterDefaultsAndDistinctActions() throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    let original = RecordedDoseSnapshot(+      description: "Synthetic label", amount: 1, unit: "test unit")+    let time = Date(timeIntervalSince1970: 1_700_000_000)+    for _ in 0..<2 {+      _ = try service.record(+        AdministrationAction(+          eventID: UUID(), medicationID: medication.id, timestamp: time,+          source: .phone, dose: original,+          scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+        ))     }+    medication.doseDescription = "Changed label"+    try container.mainContext.save()+    let events = try container.mainContext.fetch(FetchDescriptor<Administration>())+    #expect(events.count == 2)+    #expect(events.allSatisfy { $0.doseDescriptionSnapshot == original.description })+  } -    @Test(arguments: [0.0, -1.0, Double.infinity, Double.nan])-    func invalidAmountIsRejected(amount: Double) throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        #expect(throws: RecordingError.self) {-            _ = try service.record(AdministrationAction(-                eventID: UUID(), medicationID: medication.id,-                timestamp: Date(timeIntervalSince1970: 1_700_000_000),-                source: .phone,-                dose: RecordedDoseSnapshot(description: "", amount: amount, unit: "test unit"),-                scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-            ))-        }-        #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  @Test(arguments: [0.0, -1.0, Double.infinity, Double.nan])+  func invalidAmountIsRejected(amount: Double) throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    #expect(throws: RecordingError.self) {+      _ = try service.record(+        AdministrationAction(+          eventID: UUID(), medicationID: medication.id,+          timestamp: Date(timeIntervalSince1970: 1_700_000_000),+          source: .phone,+          dose: RecordedDoseSnapshot(description: "", amount: amount, unit: "test unit"),+          scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+        ))     }+    #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } -    @Test func diskStoreRetainsHistoryAndTombstonesAcrossContainers() throws {-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        defer { try? FileManager.default.removeItem(at: directory) }-        let schema = AppEnvironment.schema-        let configuration = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("isolated.store"), cloudKitDatabase: .none)-        let eventID = UUID()-        do {-            let container = try ModelContainer(for: schema, configurations: [configuration])-            let service = MedicationService(context: container.mainContext)-            let medication = try service.createAsNeededMedication(name: "Synthetic persisted item")-            let event = try service.record(AdministrationAction(-                eventID: eventID, medicationID: medication.id,-                timestamp: Date(timeIntervalSince1970: 1_700_000_000),-                source: .phone, dose: .unknown,-                scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-            ))-            try service.delete(event)-        }-        let reopened = try ModelContainer(for: schema, configurations: [configuration])-        let events = try reopened.mainContext.fetch(FetchDescriptor<Administration>())-        #expect(events.count == 1)-        #expect(events.first?.id == eventID)-        #expect(events.first?.isDeleted == true)-        #expect(try reopened.mainContext.fetchCount(FetchDescriptor<Medication>()) == 1)+  @Test func diskStoreRetainsHistoryAndTombstonesAcrossContainers() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let schema = AppEnvironment.schema+    let configuration = ModelConfiguration(+      schema: schema, url: directory.appendingPathComponent("isolated.store"),+      cloudKitDatabase: .none)+    let eventID = UUID()+    do {+      let container = try ModelContainer(for: schema, configurations: [configuration])+      let service = MedicationService(context: container.mainContext)+      let medication = try service.createAsNeededMedication(name: "Synthetic persisted item")+      let event = try service.record(+        AdministrationAction(+          eventID: eventID, medicationID: medication.id,+          timestamp: Date(timeIntervalSince1970: 1_700_000_000),+          source: .phone, dose: .unknown,+          scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+        ))+      try service.delete(event)     }+    let reopened = try ModelContainer(for: schema, configurations: [configuration])+    let events = try reopened.mainContext.fetch(FetchDescriptor<Administration>())+    #expect(events.count == 1)+    #expect(events.first?.id == eventID)+    #expect(events.first?.isDeleted == true)+    #expect(try reopened.mainContext.fetchCount(FetchDescriptor<Medication>()) == 1)+  } -    @Test func invalidPairsAndFutureManualTimeAreRejected() throws {-        let container = try store()-        let service = MedicationService(context: container.mainContext)-        let medication = try service.createAsNeededMedication(name: "Synthetic item")-        for dose in [-            RecordedDoseSnapshot(description: "", amount: nil, unit: "unit"),-            RecordedDoseSnapshot(description: "", amount: 1, unit: nil),-            RecordedDoseSnapshot(description: "", amount: 1, unit: "  ")-        ] {-            #expect(throws: RecordingError.self) { try dose.validate() }-        }-        #expect(throws: RecordingError.self) {-            _ = try service.record(AdministrationAction(-                eventID: UUID(), medicationID: medication.id,-                timestamp: Date().addingTimeInterval(3600), source: .manualHistory,-                dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil-            ))-        }-        #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  @Test func invalidPairsAndFutureManualTimeAreRejected() throws {+    let container = try store()+    let service = MedicationService(context: container.mainContext)+    let medication = try service.createAsNeededMedication(name: "Synthetic item")+    for dose in [+      RecordedDoseSnapshot(description: "", amount: nil, unit: "unit"),+      RecordedDoseSnapshot(description: "", amount: 1, unit: nil),+      RecordedDoseSnapshot(description: "", amount: 1, unit: "  ")+    ] {+      #expect(throws: RecordingError.self) { try dose.validate() }     }-    @Test func amountOnlyDoseIsNotPresentedAsUnknown() {-        let dose = RecordedDoseSnapshot(description: "", amount: 1, unit: "test unit")-        #expect(dose.displayText == "1.0 test unit")-        #expect(RecordedDoseSnapshot.unknown.displayText == "Dose not recorded")-        #expect(RecordedDoseSnapshot(description: "User label", amount: 1, unit: "unit").displayText == "User label")+    #expect(throws: RecordingError.self) {+      _ = try service.record(+        AdministrationAction(+          eventID: UUID(), medicationID: medication.id,+          timestamp: Date().addingTimeInterval(3600), source: .manualHistory,+          dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil+        ))     }+    #expect(try container.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func amountOnlyDoseIsNotPresentedAsUnknown() {+    let dose = RecordedDoseSnapshot(description: "", amount: 1, unit: "test unit")+    #expect(dose.displayText == "1.0 test unit")+    #expect(RecordedDoseSnapshot.unknown.displayText == "Dose not recorded")+    #expect(+      RecordedDoseSnapshot(description: "User label", amount: 1, unit: "unit").displayText+        == "User label")+  } }
Meddy/MeddyTests/MeddyFollowupTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyFollowupTests.swift b/Meddy/MeddyTests/MeddyFollowupTests.swiftindex a309505..c8427f4 100644--- a/Meddy/MeddyTests/MeddyFollowupTests.swift+++ b/Meddy/MeddyTests/MeddyFollowupTests.swift@@ -1,249 +1,394 @@ import Foundation import SwiftData-import UserNotifications import Testing+import UserNotifications+ @testable import Meddy  @MainActor struct MeddyFollowupTests {-    private let now = Date(timeIntervalSince1970: 1_767_660_000)-    private func setup() throws -> (ModelContainer, Medication, Administration) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let service = MedicationService(context: store.mainContext)-        let item = try service.createAsNeededMedication(name: "Synthetic follow-up")-        try EditorTransaction.save(context: store.mainContext) {-            try MedicationFollowupService.configure(item, value: .init(message: "Synthetic user message", delaySeconds: 600))-        }-        let event = try service.record(.init(eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-60), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        return (store, item, event)-    }-    private func decoded(_ request: UNNotificationRequest) throws -> PlannedReminder {-        try JSONDecoder().decode(PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data))-    }-    @Test func userConfigurationHasNoDefaultsValidatesAndPreservesNewerUntouchedValue() throws {-        let draft = MedicationFollowupDraft(medication: nil)-        #expect(!draft.enabled && draft.message.isEmpty && draft.minutes.isEmpty)-        #expect(try draft.value() == nil)-        draft.enabled = true-        #expect(throws: MedicationFollowupError.self) { try draft.value() }-        draft.message = "  Synthetic message  "; draft.minutes = "1,5"-        #expect(try draft.value(locale: Locale(identifier: "nl_NL")) == .init(message: "Synthetic message", delaySeconds: 90))-        for invalid in ["0", "-1", "nan", "inf", "99999999"] {-            draft.minutes = invalid-            #expect(throws: MedicationFollowupError.self) { try draft.value() }-        }-        let (store, item, _) = try setup()-        try EditorTransaction.save(context: store.mainContext) {-            try MedicationFollowupService.configure(item, value: .init(message: "Synthetic fractional time", delaySeconds: 123.456))-        }-        let untouched = MedicationFollowupDraft(medication: item)-        let newer = MedicationFollowup(message: "Synthetic newer value", delaySeconds: 1200)-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: newer) }-        try untouched.apply(to: item)-        #expect(try MedicationFollowupService.configuration(item) == newer)-    }-    @Test func pendingUsesActualTimestampAndRepeatsKeepOneRequestWithoutRecording() async throws {-        let (store, _, event) = try setup(); let client = FollowupNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh()-        let request = try #require(client.requests.first)-        let reminder = try decoded(request)-        #expect(request.identifier == "meddy.followup.\(event.id)")-        #expect(request.content.body == "Synthetic user message" && request.content.categoryIdentifier == "FOLLOWUP")-        #expect(reminder.deliveryAt == event.timestamp.addingTimeInterval(600))-        #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 540)-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.count == 1 && client.added.count == 1)-        service.handle(reminder, action: "TAKEN"); service.handle(reminder, action: "SNOOZE")-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-        #expect(client.added.count == 1)-    }-    @Test func correctionsRescheduleSameIDAndUndoCancelsCanonicalRow() async throws {-        let (store, item, event) = try setup(); let client = FollowupNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh()-        let originalID = try #require(client.requests.first?.identifier)-        try MedicationService(context: store.mainContext).correct(event, timestamp: now.addingTimeInterval(-120), dose: .unknown)-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.count == 1 && client.requests[0].identifier == originalID)-        #expect(try decoded(client.requests[0]).deliveryAt == now.addingTimeInterval(480))-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: .init(message: "Edited synthetic message", delaySeconds: 900)) }-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests[0].content.body == "Edited synthetic message")-        #expect(try decoded(client.requests[0]).deliveryAt == now.addingTimeInterval(780))-        try MedicationService(context: store.mainContext).delete(event)-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty && client.removed.contains(originalID))-        #expect(try service.plan(now: now).isEmpty)-    }-    @Test func overdueCorrectionDisableAndArchiveCancelWithoutCatchup() async throws {-        let (store, item, event) = try setup(); let client = FollowupNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh()-        try MedicationService(context: store.mainContext).correct(event, timestamp: now.addingTimeInterval(-700), dose: .unknown)-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty && client.added.count == 1)-        try MedicationService(context: store.mainContext).correct(event, timestamp: now, dose: .unknown)-        service.refresh(); await service.waitForRefresh(); #expect(client.requests.count == 1)-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: nil) }-        service.refresh(); await service.waitForRefresh(); #expect(client.requests.isEmpty)-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: .init(message: "Synthetic", delaySeconds: 600)) }-        service.refresh(); await service.waitForRefresh(); #expect(client.requests.count == 1)-        try MedicationService(context: store.mainContext).setActive(item, false)-        service.refresh(); await service.waitForRefresh(); #expect(client.requests.isEmpty)-    }-    @Test func allSourcesModesGenerationsAndRoutineLinksUseElapsedTimeAcrossDayAndDST() throws {-        let (store, item, original) = try setup()-        original.isDeleted = true-        let base = ISO8601DateFormatter().date(from: "2026-03-29T00:59:00Z")!-        for (index, source) in [AdministrationSource.phone, .watch, .notification].enumerated() {-            let event = Administration(action: .init(eventID: UUID(), medicationID: item.id, timestamp: base, source: source, dose: .unknown, scheduleTypeAtRecording: index == 0 ? .asNeeded : .interval, scheduleGenerationID: UUID()), medication: item)-            if index == 2 { event.routineRunID = UUID(); event.routineStepID = UUID() }-            store.mainContext.insert(event)-        }-        try store.mainContext.save()-        let actions = try MedicationFollowupService.actions(context: store.mainContext, now: base.addingTimeInterval(60))-        #expect(actions.count == 3 && actions.allSatisfy { $0.deliveryAt == base.addingTimeInterval(600) })-        var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(identifier: "Europe/Amsterdam")!-        #expect(calendar.component(.hour, from: base) == 1 && calendar.component(.hour, from: actions[0].deliveryAt) == 3)-        let boundary = ISO8601DateFormatter().date(from: "2026-10-06T00:59:00Z")!-        let action = MedicationFollowupAction(eventID: UUID(), medicationID: item.id, takenAt: boundary, configuration: .init(message: "Synthetic", delaySeconds: 600))-        #expect(calendar.component(.hour, from: boundary) == 2 && action.deliveryAt.timeIntervalSince(boundary) == 600)-    }-    @Test func overdueFutureAndClockMismatchNeverBecomeImmediateNotifications() throws {-        let (store, _, event) = try setup()-        let service = ReminderService(context: store.mainContext, now: { now })-        #expect(try service.plan(now: event.timestamp.addingTimeInterval(600)).isEmpty)-        event.hasClockMismatch = true; try store.mainContext.save()-        #expect(try service.plan(now: now).isEmpty)-        event.hasClockMismatch = false; event.timestamp = now.addingTimeInterval(1); try store.mainContext.save()-        #expect(try service.plan(now: now).isEmpty)-    }-    @Test func correctedClockDiscrepancyBecomesEligibleAndLateReconciliationDoesNotCatchUp() async throws {-        let (store, _, event) = try setup(); event.hasClockMismatch = true; try store.mainContext.save()-        try MedicationService(context: store.mainContext).correct(event, timestamp: event.timestamp, dose: .unknown)-        #expect(!event.hasClockMismatch)-        let client = FollowupNotifications(); var clock = now-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        client.onPending = { clock = now.addingTimeInterval(541) }-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty && client.added.isEmpty)-        #expect(try service.plan(now: clock).isEmpty)+  private let now = Date(timeIntervalSince1970: 1_767_660_000)+  private func setup() throws -> (ModelContainer, Medication, Administration) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let service = MedicationService(context: store.mainContext)+    let item = try service.createAsNeededMedication(name: "Synthetic follow-up")+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(+        item, value: .init(message: "Synthetic user message", delaySeconds: 600))+    }+    let event = try service.record(+      .init(+        eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-60),+        source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded,+        scheduleGenerationID: nil))+    return (store, item, event)+  }+  private func decoded(_ request: UNNotificationRequest) throws -> PlannedReminder {+    try JSONDecoder().decode(+      PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data))+  }+  @Test func userConfigurationHasNoDefaultsValidatesAndPreservesNewerUntouchedValue() throws {+    let draft = MedicationFollowupDraft(medication: nil)+    #expect(!draft.enabled && draft.message.isEmpty && draft.minutes.isEmpty)+    #expect(try draft.value() == nil)+    draft.enabled = true+    #expect(throws: MedicationFollowupError.self) { try draft.value() }+    draft.message = "  Synthetic message  "+    draft.minutes = "1,5"+    #expect(+      try draft.value(locale: Locale(identifier: "nl_NL"))+        == .init(message: "Synthetic message", delaySeconds: 90))+    for invalid in ["0", "-1", "nan", "inf", "99999999"] {+      draft.minutes = invalid+      #expect(throws: MedicationFollowupError.self) { try draft.value() }+    }+    let (store, item, _) = try setup()+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(+        item, value: .init(message: "Synthetic fractional time", delaySeconds: 123.456))+    }+    let untouched = MedicationFollowupDraft(medication: item)+    let newer = MedicationFollowup(message: "Synthetic newer value", delaySeconds: 1200)+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(item, value: newer)+    }+    try untouched.apply(to: item)+    #expect(try MedicationFollowupService.configuration(item) == newer)+  }+  @Test func pendingUsesActualTimestampAndRepeatsKeepOneRequestWithoutRecording() async throws {+    let (store, _, event) = try setup()+    let client = FollowupNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    let request = try #require(client.requests.first)+    let reminder = try decoded(request)+    #expect(request.identifier == "meddy.followup.\(event.id)")+    #expect(+      request.content.body == "Synthetic user message"+        && request.content.categoryIdentifier == "FOLLOWUP")+    #expect(reminder.deliveryAt == event.timestamp.addingTimeInterval(600))+    #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 540)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 1 && client.added.count == 1)+    service.handle(reminder, action: "TAKEN")+    service.handle(reminder, action: "SNOOZE")+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+    #expect(client.added.count == 1)+  }+  @Test func correctionsRescheduleSameIDAndUndoCancelsCanonicalRow() async throws {+    let (store, item, event) = try setup()+    let client = FollowupNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    let originalID = try #require(client.requests.first?.identifier)+    try MedicationService(context: store.mainContext).correct(+      event, timestamp: now.addingTimeInterval(-120), dose: .unknown)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 1 && client.requests[0].identifier == originalID)+    #expect(try decoded(client.requests[0]).deliveryAt == now.addingTimeInterval(480))+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(+        item, value: .init(message: "Edited synthetic message", delaySeconds: 900))+    }+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests[0].content.body == "Edited synthetic message")+    #expect(try decoded(client.requests[0]).deliveryAt == now.addingTimeInterval(780))+    try MedicationService(context: store.mainContext).delete(event)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty && client.removed.contains(originalID))+    #expect(try service.plan(now: now).isEmpty)+  }+  @Test func overdueCorrectionDisableAndArchiveCancelWithoutCatchup() async throws {+    let (store, item, event) = try setup()+    let client = FollowupNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    try MedicationService(context: store.mainContext).correct(+      event, timestamp: now.addingTimeInterval(-700), dose: .unknown)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty && client.added.count == 1)+    try MedicationService(context: store.mainContext).correct(event, timestamp: now, dose: .unknown)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 1)+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(item, value: nil)     }+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty)+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(+        item, value: .init(message: "Synthetic", delaySeconds: 600))+    }+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 1)+    try MedicationService(context: store.mainContext).setActive(item, false)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty)+  }+  @Test func allSourcesModesGenerationsAndRoutineLinksUseElapsedTimeAcrossDayAndDST() throws {+    let (store, item, original) = try setup()+    original.isDeleted = true+    let base = ISO8601DateFormatter().date(from: "2026-03-29T00:59:00Z")!+    for (index, source) in [AdministrationSource.phone, .watch, .notification].enumerated() {+      let event = Administration(+        action: .init(+          eventID: UUID(), medicationID: item.id, timestamp: base, source: source, dose: .unknown,+          scheduleTypeAtRecording: index == 0 ? .asNeeded : .interval, scheduleGenerationID: UUID()),+        medication: item)+      if index == 2 {+        event.routineRunID = UUID()+        event.routineStepID = UUID()+      }+      store.mainContext.insert(event)+    }+    try store.mainContext.save()+    let actions = try MedicationFollowupService.actions(+      context: store.mainContext, now: base.addingTimeInterval(60))+    #expect(+      actions.count == 3 && actions.allSatisfy { $0.deliveryAt == base.addingTimeInterval(600) })+    var calendar = Calendar(identifier: .gregorian)+    calendar.timeZone = TimeZone(identifier: "Europe/Amsterdam")!+    #expect(+      calendar.component(.hour, from: base) == 1+        && calendar.component(.hour, from: actions[0].deliveryAt) == 3)+    let boundary = ISO8601DateFormatter().date(from: "2026-10-06T00:59:00Z")!+    let action = MedicationFollowupAction(+      eventID: UUID(), medicationID: item.id, takenAt: boundary,+      configuration: .init(message: "Synthetic", delaySeconds: 600))+    #expect(+      calendar.component(.hour, from: boundary) == 2+        && action.deliveryAt.timeIntervalSince(boundary) == 600)+  }+  @Test func overdueFutureAndClockMismatchNeverBecomeImmediateNotifications() throws {+    let (store, _, event) = try setup()+    let service = ReminderService(context: store.mainContext, now: { now })+    #expect(try service.plan(now: event.timestamp.addingTimeInterval(600)).isEmpty)+    event.hasClockMismatch = true+    try store.mainContext.save()+    #expect(try service.plan(now: now).isEmpty)+    event.hasClockMismatch = false+    event.timestamp = now.addingTimeInterval(1)+    try store.mainContext.save()+    #expect(try service.plan(now: now).isEmpty)+  }+  @Test func correctedClockDiscrepancyBecomesEligibleAndLateReconciliationDoesNotCatchUp()+    async throws {+    let (store, _, event) = try setup()+    event.hasClockMismatch = true+    try store.mainContext.save()+    try MedicationService(context: store.mainContext).correct(+      event, timestamp: event.timestamp, dose: .unknown)+    #expect(!event.hasClockMismatch)+    let client = FollowupNotifications()+    var clock = now+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    client.onPending = { clock = now.addingTimeInterval(541) }+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty && client.added.isEmpty)+    #expect(try service.plan(now: clock).isEmpty)+  } -    @Test func permissionDenialAndRetryRetainSettingsAndDoNotTouchForeignRequests() async throws {-        let (store, item, _) = try setup(); let client = FollowupNotifications(); client.status = .denied-        client.requests = [UNNotificationRequest(identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)]-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.map(\.identifier) == ["foreign"] && service.error == nil)-        #expect(try MedicationFollowupService.configuration(item)?.message == "Synthetic user message")-        client.status = .authorized; client.fail = true-        service.refresh(); await service.waitForRefresh(); #expect(service.error != nil)-        client.fail = false; service.error = nil-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.count == 2 && client.added.count == 1 && service.error == nil)-    }-    @Test func relaunchDoesNotReplayElapsedDeadlineEvenAfterSettingsOrTimestampEdits() async throws {-        let (store, item, event) = try setup(); let client = FollowupNotifications()-        let suite = "meddy.synthetic.followup.\(UUID())"; let defaults = try #require(UserDefaults(suiteName: suite))-        defer { defaults.removePersistentDomain(forName: suite) }-        let initial = ReminderService(context: store.mainContext, notifications: client, receiptDefaults: defaults, now: { now })-        initial.refresh(); await initial.waitForRefresh()-        client.requests.removeAll() // iOS delivery / user dismissal leaves no pending request.-        let later = now.addingTimeInterval(601)-        try MedicationService(context: store.mainContext).correct(event, timestamp: later, dose: .unknown)-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: .init(message: "Synthetic edited after delivery", delaySeconds: 1200)) }-        let relaunched = ReminderService(context: store.mainContext, notifications: client, receiptDefaults: defaults, now: { later })-        relaunched.refresh(); await relaunched.waitForRefresh()-        #expect(client.requests.isEmpty && client.added.count == 1)-    }-    @Test func interruptedAddIsDrainedBeforeUndoCleanup() async throws {-        let (store, _, event) = try setup(); let client = FollowupNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        client.onAdd = {-            try MedicationService(context: store.mainContext).delete(event)-            service.refresh()-        }-        service.refresh(); await service.waitForRefresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty)-    }-    @Test func relaunchKeepsFuturePendingAndCurrentCanonicalFactsInvalidateOldDeliveredPayload() async throws {-        let (store, item, event) = try setup(); let client = FollowupNotifications()-        let initial = ReminderService(context: store.mainContext, notifications: client, now: { now })-        initial.refresh(); await initial.waitForRefresh()-        let old = try decoded(#require(client.requests.first))-        let relaunched = ReminderService(context: store.mainContext, notifications: client, now: { now })-        relaunched.refresh(); await relaunched.waitForRefresh()-        #expect(client.added.count == 1 && client.requests.count == 1)-        guard case .followup(let oldAction) = old.payload else { Issue.record("Expected follow-up"); return }-        #expect(try MedicationFollowupService.actions(context: store.mainContext, now: now.addingTimeInterval(1000)).contains(oldAction))-        try MedicationService(context: store.mainContext).correct(event, timestamp: now, dose: .unknown)-        #expect(try !MedicationFollowupService.actions(context: store.mainContext, now: now).contains(oldAction))-        try EditorTransaction.save(context: store.mainContext) { try MedicationFollowupService.configure(item, value: nil) }-        #expect(try MedicationFollowupService.actions(context: store.mainContext, now: now).isEmpty)-    }-    @Test func duplicateCanonicalIDAndExistingSixtyRequestBudgetRemainStable() throws {-        let (store, item, event) = try setup(); let records = MedicationService(context: store.mainContext)-        _ = try records.record(.init(eventID: event.id, medicationID: item.id, timestamp: now, source: .watch, dose: .unknown, scheduleTypeAtRecording: .interval, scheduleGenerationID: UUID()))-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-        for offset in 1...70 {-            _ = try records.record(.init(eventID: UUID(), medicationID: item.id, timestamp: now.addingTimeInterval(-Double(offset)), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        }-        let service = ReminderService(context: store.mainContext, now: { now })-        let first = try service.plan(now: now), second = try service.plan(now: now)-        #expect(first.count == 60 && Set(first.map(\.id)).count == 60 && first == second)-        #expect(first == first.sorted { $0.deliveryAt == $1.deliveryAt ? $0.id < $1.id : $0.deliveryAt < $1.deliveryAt })+  @Test func permissionDenialAndRetryRetainSettingsAndDoNotTouchForeignRequests() async throws {+    let (store, item, _) = try setup()+    let client = FollowupNotifications()+    client.status = .denied+    client.requests = [+      UNNotificationRequest(+        identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)+    ]+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.map(\.identifier) == ["foreign"] && service.error == nil)+    #expect(try MedicationFollowupService.configuration(item)?.message == "Synthetic user message")+    client.status = .authorized+    client.fail = true+    service.refresh()+    await service.waitForRefresh()+    #expect(service.error != nil)+    client.fail = false+    service.error = nil+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 2 && client.added.count == 1 && service.error == nil)+  }+  @Test func relaunchDoesNotReplayElapsedDeadlineEvenAfterSettingsOrTimestampEdits() async throws {+    let (store, item, event) = try setup()+    let client = FollowupNotifications()+    let suite = "meddy.synthetic.followup.\(UUID())"+    let defaults = try #require(UserDefaults(suiteName: suite))+    defer { defaults.removePersistentDomain(forName: suite) }+    let initial = ReminderService(+      context: store.mainContext, notifications: client, receiptDefaults: defaults, now: { now })+    initial.refresh()+    await initial.waitForRefresh()+    client.requests.removeAll()  // iOS delivery / user dismissal leaves no pending request.+    let later = now.addingTimeInterval(601)+    try MedicationService(context: store.mainContext).correct(+      event, timestamp: later, dose: .unknown)+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(+        item, value: .init(message: "Synthetic edited after delivery", delaySeconds: 1200))+    }+    let relaunched = ReminderService(+      context: store.mainContext, notifications: client, receiptDefaults: defaults, now: { later })+    relaunched.refresh()+    await relaunched.waitForRefresh()+    #expect(client.requests.isEmpty && client.added.count == 1)+  }+  @Test func interruptedAddIsDrainedBeforeUndoCleanup() async throws {+    let (store, _, event) = try setup()+    let client = FollowupNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    client.onAdd = {+      try MedicationService(context: store.mainContext).delete(event)+      service.refresh()+    }+    service.refresh()+    await service.waitForRefresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty)+  }+  @Test func relaunchKeepsFuturePendingAndCurrentCanonicalFactsInvalidateOldDeliveredPayload()+    async throws {+    let (store, item, event) = try setup()+    let client = FollowupNotifications()+    let initial = ReminderService(context: store.mainContext, notifications: client, now: { now })+    initial.refresh()+    await initial.waitForRefresh()+    let old = try decoded(#require(client.requests.first))+    let relaunched = ReminderService(+      context: store.mainContext, notifications: client, now: { now })+    relaunched.refresh()+    await relaunched.waitForRefresh()+    #expect(client.added.count == 1 && client.requests.count == 1)+    guard case .followup(let oldAction) = old.payload else {+      Issue.record("Expected follow-up")+      return     }+    #expect(+      try MedicationFollowupService.actions(+        context: store.mainContext, now: now.addingTimeInterval(1000)+      ).contains(oldAction))+    try MedicationService(context: store.mainContext).correct(event, timestamp: now, dose: .unknown)+    #expect(+      try !MedicationFollowupService.actions(context: store.mainContext, now: now).contains(+        oldAction))+    try EditorTransaction.save(context: store.mainContext) {+      try MedicationFollowupService.configure(item, value: nil)+    }+    #expect(try MedicationFollowupService.actions(context: store.mainContext, now: now).isEmpty)+  }+  @Test func duplicateCanonicalIDAndExistingSixtyRequestBudgetRemainStable() throws {+    let (store, item, event) = try setup()+    let records = MedicationService(context: store.mainContext)+    _ = try records.record(+      .init(+        eventID: event.id, medicationID: item.id, timestamp: now, source: .watch, dose: .unknown,+        scheduleTypeAtRecording: .interval, scheduleGenerationID: UUID()))+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+    for offset in 1...70 {+      _ = try records.record(+        .init(+          eventID: UUID(), medicationID: item.id,+          timestamp: now.addingTimeInterval(-Double(offset)), source: .phone, dose: .unknown,+          scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    }+    let service = ReminderService(context: store.mainContext, now: { now })+    let first = try service.plan(now: now)+    let second = try service.plan(now: now)+    #expect(first.count == 60 && Set(first.map(\.id)).count == 60 && first == second)+    #expect(+      first+        == first.sorted {+          $0.deliveryAt == $1.deliveryAt ? $0.id < $1.id : $0.deliveryAt < $1.deliveryAt+        })+  } -    @Test func corruptConfigurationCancelsItsPendingRequestWithoutBlockingOtherKinds() async throws {-        let (store, item, _) = try setup(); let client = FollowupNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh()-        item.followupNotificationData = Data("corrupt".utf8); try store.mainContext.save()-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty && service.error == nil)-    }-    @Test func nullableConfigurationSurvivesDiskRelaunchAndAtomicRollback() throws {-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent("MeddyFollowup-\(UUID())")-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        defer { try? FileManager.default.removeItem(at: directory) }-        let configuration = ModelConfiguration(schema: AppEnvironment.schema, url: directory.appendingPathComponent("synthetic.store"), cloudKitDatabase: .none)-        let first = try ModelContainer(for: AppEnvironment.schema, configurations: [configuration])-        let item = try MedicationService(context: first.mainContext).createAsNeededMedication(name: "Synthetic disk")-        #expect(item.followupNotificationData == nil)-        let value = MedicationFollowup(message: "Synthetic disk message", delaySeconds: 1200)-        try EditorTransaction.save(context: first.mainContext) { try MedicationFollowupService.configure(item, value: value) }-        enum SyntheticFailure: Error { case failed }-        #expect(throws: SyntheticFailure.self) {-            try EditorTransaction.save(context: first.mainContext) {-                try MedicationFollowupService.configure(item, value: nil)-                throw SyntheticFailure.failed-            }-        }-        let second = try ModelContainer(for: AppEnvironment.schema, configurations: [configuration])-        let loaded = try #require(second.mainContext.fetch(FetchDescriptor<Medication>()).first)-        #expect(try MedicationFollowupService.configuration(loaded) == value)+  @Test func corruptConfigurationCancelsItsPendingRequestWithoutBlockingOtherKinds() async throws {+    let (store, item, _) = try setup()+    let client = FollowupNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    item.followupNotificationData = Data("corrupt".utf8)+    try store.mainContext.save()+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty && service.error == nil)+  }+  @Test func nullableConfigurationSurvivesDiskRelaunchAndAtomicRollback() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(+      "MeddyFollowup-\(UUID())")+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let configuration = ModelConfiguration(+      schema: AppEnvironment.schema, url: directory.appendingPathComponent("synthetic.store"),+      cloudKitDatabase: .none)+    let first = try ModelContainer(for: AppEnvironment.schema, configurations: [configuration])+    let item = try MedicationService(context: first.mainContext).createAsNeededMedication(+      name: "Synthetic disk")+    #expect(item.followupNotificationData == nil)+    let value = MedicationFollowup(message: "Synthetic disk message", delaySeconds: 1200)+    try EditorTransaction.save(context: first.mainContext) {+      try MedicationFollowupService.configure(item, value: value)+    }+    enum SyntheticFailure: Error { case failed }+    #expect(throws: SyntheticFailure.self) {+      try EditorTransaction.save(context: first.mainContext) {+        try MedicationFollowupService.configure(item, value: nil)+        throw SyntheticFailure.failed+      }     }+    let second = try ModelContainer(for: AppEnvironment.schema, configurations: [configuration])+    let loaded = try #require(second.mainContext.fetch(FetchDescriptor<Medication>()).first)+    #expect(try MedicationFollowupService.configuration(loaded) == value)+  } }  @MainActor private final class FollowupNotifications: ReminderNotificationClient {-    var status: UNAuthorizationStatus = .authorized-    var requests: [UNNotificationRequest] = []-    var added: [UNNotificationRequest] = []-    var removed: [String] = []-    var fail = false-    var onAdd: (() throws -> Void)?-    var onPending: (() -> Void)?-    func authorization() async -> UNAuthorizationStatus { status }-    func pending() async -> [UNNotificationRequest] { onPending?(); onPending = nil; return requests }-    func delivered() async -> [UNNotification] { [] }-    func removePending(_ ids: [String]) { removed.append(contentsOf: ids); requests.removeAll { ids.contains($0.identifier) } }-    func removeDelivered(_ ids: [String]) {}-    func add(_ request: UNNotificationRequest) async throws {-        if fail { throw NSError(domain: "SyntheticFollowup", code: 1) }-        if let callback = onAdd { onAdd = nil; try callback(); await Task.yield() }-        added.append(request); requests.removeAll { $0.identifier == request.identifier }; requests.append(request)+  var status: UNAuthorizationStatus = .authorized+  var requests: [UNNotificationRequest] = []+  var added: [UNNotificationRequest] = []+  var removed: [String] = []+  var fail = false+  var onAdd: (() throws -> Void)?+  var onPending: (() -> Void)?+  func authorization() async -> UNAuthorizationStatus { status }+  func pending() async -> [UNNotificationRequest] {+    onPending?()+    onPending = nil+    return requests+  }+  func delivered() async -> [UNNotification] { [] }+  func removePending(_ ids: [String]) {+    removed.append(contentsOf: ids)+    requests.removeAll { ids.contains($0.identifier) }+  }+  func removeDelivered(_ ids: [String]) {}+  func add(_ request: UNNotificationRequest) async throws {+    if fail { throw NSError(domain: "SyntheticFollowup", code: 1) }+    if let callback = onAdd {+      onAdd = nil+      try callback()+      await Task.yield()     }+    added.append(request)+    requests.removeAll { $0.identifier == request.identifier }+    requests.append(request)+  } }
Meddy/MeddyTests/MeddyLogicalDayTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyLogicalDayTests.swift b/Meddy/MeddyTests/MeddyLogicalDayTests.swiftindex 325ccc6..cfbd545 100644--- a/Meddy/MeddyTests/MeddyLogicalDayTests.swift+++ b/Meddy/MeddyTests/MeddyLogicalDayTests.swift@@ -1,119 +1,185 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyLogicalDayTests {-    private var calendar: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(secondsFromGMT: 0)!; return c }-    private func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {-        calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))!-    }-    @Test func boundaryCountsAndHistoryKeepActualTimestamp() throws {-        let c = calendar; let before = date(5, 1, 59); let boundary = date(5, 2)-        #expect(ScheduleCalendar.localDate(before, calendar: c) == "2026-01-04")-        #expect(ScheduleCalendar.localDate(boundary, calendar: c) == "2026-01-05")-        #expect(ScheduleCalendar.sameDay(date(4, 23), before, calendar: c))-        #expect(!ScheduleCalendar.sameDay(before, boundary, calendar: c))-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        let event = try MedicationService(context: store.mainContext).record(.init(eventID: UUID(), medicationID: item.id, timestamp: before, source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        #expect(event.timestamp == before)-        #expect(ScheduleCalendar.localDate(event.timestamp, calendar: c) == "2026-01-04")-    }-    @Test func fixedTimesOrderLateNightAtEndOfLogicalDayAndResetAt02() throws {-        let id = UUID(); let generation = UUID()-        let snapshot = MedicationScheduleSnapshot(id: id, mode: .fixedTimes, generationID: generation, startedAt: date(4, 12), fixedMinutes: [60, 1320])-        let event = ScheduledAdministration(id: UUID(), medicationID: id, timestamp: date(4, 23), mode: .fixedTimes, generationID: generation)-        let engine = MedicationScheduleEngine()-        #expect(engine.evaluate(snapshot, administrations: [], now: date(4, 22), calendar: calendar).next == date(4, 22))-        let late = engine.evaluate(snapshot, administrations: [event], now: date(5, 1, 59), calendar: calendar)-        #expect(late.takenToday == 1 && late.remainingToday == 1 && late.next == date(5, 1))-        let newDay = engine.evaluate(snapshot, administrations: [event], now: date(5, 2), calendar: calendar)-        #expect(newDay.takenToday == 0 && newDay.remainingToday == 2 && newDay.next == date(5, 22))-    }-    @Test func spreadWindowMayCrossMidnightButNotThe02DayBoundary() {-        let id = UUID(); let generation = UUID()-        var snapshot = MedicationScheduleSnapshot(id: id, mode: .spreadThroughDay, generationID: generation, startedAt: date(4, 12), dosesPerDay: 2, dayStartMinute: 1320, dayEndMinute: 60)-        let event = ScheduledAdministration(id: UUID(), medicationID: id, timestamp: date(4, 23), mode: .spreadThroughDay, generationID: generation)-        let result = MedicationScheduleEngine().evaluate(snapshot, administrations: [event], now: date(5, 0), calendar: calendar)-        #expect(result.next == date(5, 1) && result.takenToday == 1)-        snapshot.dayStartMinute = 0; snapshot.dayEndMinute = 240-        let invalid = MedicationScheduleEngine().evaluate(snapshot, administrations: [], now: date(5, 2), calendar: calendar)-        #expect(invalid.next == nil && invalid.cannotFitInWindow && invalid.remainingToday == 2)-    }-    @Test func reminderActionDoesNotRotateAtMidnightAndUntimedCueHasNoReminder() throws {-        let snapshot = MedicationScheduleSnapshot(id: UUID(), mode: .fixedTimes, generationID: UUID(), startedAt: date(4, 12), fixedMinutes: [1320])-        let planner = NotificationPlanner()-        let first = try #require(planner.medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [], now: date(4, 23), calendar: calendar))-        let late = try #require(planner.medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [], now: date(5, 1, 59), calendar: calendar))-        guard case .medication(let a) = first.payload, case .medication(let b) = late.payload else { Issue.record("Wrong payload"); return }-        #expect(a.eventID == b.eventID)-        let requirements = TimingCue.beforeSleeping.adding(to: "Synthetic instruction")-        #expect(TimingCue.beforeSleeping.adding(to: requirements) == requirements)-        var slot = DailyRoutineSlot(label: "Synthetic", minuteOfDay: 1320); let id = slot.id-        TimingCue.beforeSleeping.applying(to: &slot)-        #expect(slot.id == id && slot.minuteOfDay == nil && slot.label == "Before sleeping")-        let schedule = RoutineScheduleSnapshot(routineID: UUID(), current: .init(generationID: UUID(), startedAt: date(4, 12), slots: [slot]))-        let occurrence = try #require(RoutineScheduleEngine().occurrences(schedule, runs: [], day: date(5, 1), now: date(5, 1), calendar: calendar).first)-        #expect(occurrence.localDate == "2026-01-04" && occurrence.scheduledAt == nil)-        #expect(planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: date(5, 1)) == nil)-    }-    @Test func frequencyChangeBefore02ActivatesAt02AndLegacyMidnightPendingDoesNotActivateEarly() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let routine = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])-        let original = ScheduleService(context: store.mainContext, now: { date(4, 12) }, calendar: calendar)-        let slot = DailyRoutineSlot(); try original.configure(routine, slots: [slot], reminders: false)-        let before = ScheduleService(context: store.mainContext, now: { date(5, 1, 59) }, calendar: calendar)-        try before.configure(routine, slots: [slot, .init()], reminders: false)-        #expect(try before.snapshot(routine).pending?.effectiveAt == date(5, 2))-        #expect(try before.activatePending(routine) == false)-        let after = ScheduleService(context: store.mainContext, now: { date(5, 2) }, calendar: calendar)-        #expect(try after.activatePending(routine))-        #expect(try after.snapshot(routine).current?.slots.count == 2)-        let legacy = PendingRoutineSchedule(configuration: .init(generationID: UUID(), startedAt: date(5, 0), slots: [slot]), effectiveAt: date(5, 0), timeZoneID: "Etc/UTC")-        #expect(ScheduleCalendar.activationDate(legacy, calendar: calendar) == date(5, 2))-    }-    @Test func legacyEarlySessionKeepsIdentityWithoutCollidingWithNewDay() throws {-        let routineID = UUID(); let generation = UUID(); let slot = DailyRoutineSlot()-        let schedule = RoutineScheduleSnapshot(routineID: routineID, current: .init(generationID: generation, startedAt: date(4, 12), slots: [slot]))-        let oldKey = "\(routineID)|\(generation)|\(slot.id)|2026-01-05"-        let oldID = ScheduleCalendar.identity(oldKey)-        let old = ScheduledRunSnapshot(id: oldID, routineID: routineID, occurrenceKey: oldKey, slotID: slot.id, localDate: "2026-01-05", startedAt: date(5, 1), timeZoneID: "Etc/UTC", scheduledAt: nil, status: .paused)-        let engine = RoutineScheduleEngine()-        let before = try #require(engine.occurrences(schedule, runs: [old], day: date(5, 1, 59), now: date(5, 1, 59), calendar: calendar).first)-        #expect(before.id == oldID && before.key == oldKey && before.localDate == "2026-01-04")-        let after = engine.occurrences(schedule, runs: [old], day: date(5, 2), now: date(5, 2), calendar: calendar)-        let current = try #require(after.first(where: { !$0.isEarlierUnfinished }))-        #expect(current.id != oldID && current.key.contains("day02@2026-01-05"))-        #expect(after.first(where: { $0.id == oldID })?.isEarlierUnfinished == true)-        #expect(old.localDate == "2026-01-05" && old.startedAt == date(5, 1))-    }-    @Test func DSTSkipped02UsesNextValidBoundaryAndRepeated01DoesNotResetTwice() throws {-        var c = Calendar(identifier: .gregorian); c.timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))-        let iso = ISO8601DateFormatter()-        let springBefore = try #require(iso.date(from: "2026-03-08T09:59:00Z"))-        let springAfter = try #require(iso.date(from: "2026-03-08T10:00:00Z"))-        #expect(ScheduleCalendar.localDate(springBefore, calendar: c) == "2026-03-07")-        #expect(ScheduleCalendar.localDate(springAfter, calendar: c) == "2026-03-08")-        #expect(ScheduleCalendar.nextDayStart(springBefore, calendar: c) == springAfter)-        #expect(c.component(.hour, from: ScheduleCalendar.dayStart(springAfter, calendar: c)) == 3)-        let first = try #require(iso.date(from: "2026-11-01T08:59:00Z"))-        let repeated = try #require(iso.date(from: "2026-11-01T09:59:00Z"))-        let end = try #require(iso.date(from: "2026-11-01T10:00:00Z"))-        #expect(ScheduleCalendar.sameDay(first, repeated, calendar: c))-        #expect(ScheduleCalendar.nextDayStart(first, calendar: c) == end)-        #expect(ScheduleCalendar.nextDayStart(repeated, calendar: c) == end)-        #expect(ScheduleCalendar.localDate(end, calendar: c) == "2026-11-01")-        let minute = 60-        let date = try #require(ScheduleCalendar.time(minute, on: first, calendar: c))-        #expect(date == iso.date(from: "2026-11-01T08:00:00Z"))-        c.timeZone = try #require(TimeZone(identifier: "Europe/Berlin"))-        let first02 = try #require(iso.date(from: "2026-10-25T00:00:00Z"))-        let second02 = try #require(iso.date(from: "2026-10-25T01:00:00Z"))-        #expect(ScheduleCalendar.dayStart(first02, calendar: c) == first02)-        #expect(ScheduleCalendar.dayStart(second02, calendar: c) == first02)-        #expect(ScheduleCalendar.sameDay(first02, second02, calendar: c))+  private var calendar: Calendar {+    var localCalendar = Calendar(identifier: .gregorian)+    localCalendar.timeZone = TimeZone(secondsFromGMT: 0)!+    return localCalendar+  }+  private func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {+    calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))!+  }+  @Test func boundaryCountsAndHistoryKeepActualTimestamp() throws {+    let localCalendar = calendar+    let before = date(5, 1, 59)+    let boundary = date(5, 2)+    #expect(ScheduleCalendar.localDate(before, calendar: localCalendar) == "2026-01-04")+    #expect(ScheduleCalendar.localDate(boundary, calendar: localCalendar) == "2026-01-05")+    #expect(ScheduleCalendar.sameDay(date(4, 23), before, calendar: localCalendar))+    #expect(!ScheduleCalendar.sameDay(before, boundary, calendar: localCalendar))+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    let event = try MedicationService(context: store.mainContext).record(+      .init(+        eventID: UUID(), medicationID: item.id, timestamp: before, source: .phone, dose: .unknown,+        scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    #expect(event.timestamp == before)+    #expect(ScheduleCalendar.localDate(event.timestamp, calendar: localCalendar) == "2026-01-04")+  }+  @Test func fixedTimesOrderLateNightAtEndOfLogicalDayAndResetAt02() throws {+    let id = UUID()+    let generation = UUID()+    let snapshot = MedicationScheduleSnapshot(+      id: id, mode: .fixedTimes, generationID: generation, startedAt: date(4, 12),+      fixedMinutes: [60, 1320])+    let event = ScheduledAdministration(+      id: UUID(), medicationID: id, timestamp: date(4, 23), mode: .fixedTimes,+      generationID: generation)+    let engine = MedicationScheduleEngine()+    #expect(+      engine.evaluate(snapshot, administrations: [], now: date(4, 22), calendar: calendar).next+        == date(4, 22))+    let late = engine.evaluate(+      snapshot, administrations: [event], now: date(5, 1, 59), calendar: calendar)+    #expect(late.takenToday == 1 && late.remainingToday == 1 && late.next == date(5, 1))+    let newDay = engine.evaluate(+      snapshot, administrations: [event], now: date(5, 2), calendar: calendar)+    #expect(newDay.takenToday == 0 && newDay.remainingToday == 2 && newDay.next == date(5, 22))+  }+  @Test func spreadWindowMayCrossMidnightButNotThe02DayBoundary() {+    let id = UUID()+    let generation = UUID()+    var snapshot = MedicationScheduleSnapshot(+      id: id, mode: .spreadThroughDay, generationID: generation, startedAt: date(4, 12),+      dosesPerDay: 2, dayStartMinute: 1320, dayEndMinute: 60)+    let event = ScheduledAdministration(+      id: UUID(), medicationID: id, timestamp: date(4, 23), mode: .spreadThroughDay,+      generationID: generation)+    let result = MedicationScheduleEngine().evaluate(+      snapshot, administrations: [event], now: date(5, 0), calendar: calendar)+    #expect(result.next == date(5, 1) && result.takenToday == 1)+    snapshot.dayStartMinute = 0+    snapshot.dayEndMinute = 240+    let invalid = MedicationScheduleEngine().evaluate(+      snapshot, administrations: [], now: date(5, 2), calendar: calendar)+    #expect(invalid.next == nil && invalid.cannotFitInWindow && invalid.remainingToday == 2)+  }+  @Test func reminderActionDoesNotRotateAtMidnightAndUntimedCueHasNoReminder() throws {+    let snapshot = MedicationScheduleSnapshot(+      id: UUID(), mode: .fixedTimes, generationID: UUID(), startedAt: date(4, 12),+      fixedMinutes: [1320])+    let planner = NotificationPlanner()+    let first = try #require(+      planner.medication(+        snapshot, details: MedicationReminderDetails(name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [], now: date(4, 23), calendar: calendar))+    let late = try #require(+      planner.medication(+        snapshot, details: MedicationReminderDetails(name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [], now: date(5, 1, 59), calendar: calendar))+    guard case .medication(let firstAction) = first.payload, case .medication(let b) = late.payload else {+      Issue.record("Wrong payload")+      return     }+    #expect(firstAction.eventID == b.eventID)+    let requirements = TimingCue.beforeSleeping.adding(to: "Synthetic instruction")+    #expect(TimingCue.beforeSleeping.adding(to: requirements) == requirements)+    var slot = DailyRoutineSlot(label: "Synthetic", minuteOfDay: 1320)+    let id = slot.id+    TimingCue.beforeSleeping.applying(to: &slot)+    #expect(slot.id == id && slot.minuteOfDay == nil && slot.label == "Before sleeping")+    let schedule = RoutineScheduleSnapshot(+      routineID: UUID(), current: .init(generationID: UUID(), startedAt: date(4, 12), slots: [slot])+    )+    let occurrence = try #require(+      RoutineScheduleEngine().occurrences(+        schedule, runs: [], day: date(5, 1), now: date(5, 1), calendar: calendar+      ).first)+    #expect(occurrence.localDate == "2026-01-04" && occurrence.scheduledAt == nil)+    #expect(+      planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: date(5, 1))+        == nil)+  }+  @Test func frequencyChangeBefore02ActivatesAt02AndLegacyMidnightPendingDoesNotActivateEarly()+    throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let routine = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])+    let original = ScheduleService(+      context: store.mainContext, now: { date(4, 12) }, calendar: calendar)+    let slot = DailyRoutineSlot()+    try original.configure(routine, slots: [slot], reminders: false)+    let before = ScheduleService(+      context: store.mainContext, now: { date(5, 1, 59) }, calendar: calendar)+    try before.configure(routine, slots: [slot, .init()], reminders: false)+    #expect(try before.snapshot(routine).pending?.effectiveAt == date(5, 2))+    #expect(try before.activatePending(routine) == false)+    let after = ScheduleService(context: store.mainContext, now: { date(5, 2) }, calendar: calendar)+    #expect(try after.activatePending(routine))+    #expect(try after.snapshot(routine).current?.slots.count == 2)+    let legacy = PendingRoutineSchedule(+      configuration: .init(generationID: UUID(), startedAt: date(5, 0), slots: [slot]),+      effectiveAt: date(5, 0), timeZoneID: "Etc/UTC")+    #expect(ScheduleCalendar.activationDate(legacy, calendar: calendar) == date(5, 2))+  }+  @Test func legacyEarlySessionKeepsIdentityWithoutCollidingWithNewDay() throws {+    let routineID = UUID()+    let generation = UUID()+    let slot = DailyRoutineSlot()+    let schedule = RoutineScheduleSnapshot(+      routineID: routineID,+      current: .init(generationID: generation, startedAt: date(4, 12), slots: [slot]))+    let oldKey = "\(routineID)|\(generation)|\(slot.id)|2026-01-05"+    let oldID = ScheduleCalendar.identity(oldKey)+    let old = ScheduledRunSnapshot(+      id: oldID, routineID: routineID, occurrenceKey: oldKey, slotID: slot.id,+      localDate: "2026-01-05", startedAt: date(5, 1), timeZoneID: "Etc/UTC", scheduledAt: nil,+      status: .paused)+    let engine = RoutineScheduleEngine()+    let before = try #require(+      engine.occurrences(+        schedule, runs: [old], day: date(5, 1, 59), now: date(5, 1, 59), calendar: calendar+      ).first)+    #expect(before.id == oldID && before.key == oldKey && before.localDate == "2026-01-04")+    let after = engine.occurrences(+      schedule, runs: [old], day: date(5, 2), now: date(5, 2), calendar: calendar)+    let current = try #require(after.first(where: { !$0.isEarlierUnfinished }))+    #expect(current.id != oldID && current.key.contains("day02@2026-01-05"))+    #expect(after.first(where: { $0.id == oldID })?.isEarlierUnfinished == true)+    #expect(old.localDate == "2026-01-05" && old.startedAt == date(5, 1))+  }+  @Test func DSTSkipped02UsesNextValidBoundaryAndRepeated01DoesNotResetTwice() throws {+    var localCalendar = Calendar(identifier: .gregorian)+    localCalendar.timeZone = try #require(TimeZone(identifier: "America/Los_Angeles"))+    let iso = ISO8601DateFormatter()+    let springBefore = try #require(iso.date(from: "2026-03-08T09:59:00Z"))+    let springAfter = try #require(iso.date(from: "2026-03-08T10:00:00Z"))+    #expect(ScheduleCalendar.localDate(springBefore, calendar: localCalendar) == "2026-03-07")+    #expect(ScheduleCalendar.localDate(springAfter, calendar: localCalendar) == "2026-03-08")+    #expect(ScheduleCalendar.nextDayStart(springBefore, calendar: localCalendar) == springAfter)+    #expect(localCalendar.component(.hour, from: ScheduleCalendar.dayStart(springAfter, calendar: localCalendar)) == 3)+    let first = try #require(iso.date(from: "2026-11-01T08:59:00Z"))+    let repeated = try #require(iso.date(from: "2026-11-01T09:59:00Z"))+    let end = try #require(iso.date(from: "2026-11-01T10:00:00Z"))+    #expect(ScheduleCalendar.sameDay(first, repeated, calendar: localCalendar))+    #expect(ScheduleCalendar.nextDayStart(first, calendar: localCalendar) == end)+    #expect(ScheduleCalendar.nextDayStart(repeated, calendar: localCalendar) == end)+    #expect(ScheduleCalendar.localDate(end, calendar: localCalendar) == "2026-11-01")+    let minute = 60+    let date = try #require(ScheduleCalendar.time(minute, on: first, calendar: localCalendar))+    #expect(date == iso.date(from: "2026-11-01T08:00:00Z"))+    localCalendar.timeZone = try #require(TimeZone(identifier: "Europe/Berlin"))+    let first02 = try #require(iso.date(from: "2026-10-25T00:00:00Z"))+    let second02 = try #require(iso.date(from: "2026-10-25T01:00:00Z"))+    #expect(ScheduleCalendar.dayStart(first02, calendar: localCalendar) == first02)+    #expect(ScheduleCalendar.dayStart(second02, calendar: localCalendar) == first02)+    #expect(ScheduleCalendar.sameDay(first02, second02, calendar: localCalendar))+  } }
Meddy/MeddyTests/MeddyMarkdownExportTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyMarkdownExportTests.swift b/Meddy/MeddyTests/MeddyMarkdownExportTests.swiftindex 360a9b6..3b96bee 100644--- a/Meddy/MeddyTests/MeddyMarkdownExportTests.swift+++ b/Meddy/MeddyTests/MeddyMarkdownExportTests.swift@@ -1,89 +1,145 @@+import CoreTransferable import Foundation import SwiftData-import CoreTransferable-import UniformTypeIdentifiers import Testing+import UniformTypeIdentifiers+ @testable import Meddy  @MainActor struct MeddyMarkdownExportTests {-    private let preparedAt = Date(timeIntervalSince1970: 1_767_660_000)-    private let utc = TimeZone(secondsFromGMT: 0)!-    private func entry(_ name: String, purpose: String = "Ungrouped", id: UUID = UUID(), dose: String? = nil, method: String = "", requirements: String = "", schedule: String = "As needed") -> ConsultationMedication {-        .init(id: id, purpose: purpose, name: name, dose: dose, method: method, requirements: requirements, schedule: schedule)-    }-    @Test func headingsListsDatedFilenameAndOptionalFieldsPreserveExistingConsultationContent() {-        let values = [entry("Synthetic B", purpose: "Z purpose"), entry("Synthetic A", purpose: "A purpose", dose: "Synthetic dose", method: "Synthetic application", requirements: "Synthetic requirement", schedule: "In Synthetic owner · 2 sessions per day")]-        let export = ConsultationMarkdown.make(values, preparedAt: preparedAt, timeZone: utc)-        #expect(export.markdown.hasPrefix("# Current medications\n\nPrepared: 2026-01-06T00:40:00Z\n\n"))-        #expect(export.filename == "meddy-current-medications-2026-01-06.md")-        #expect(export.markdown.contains("## A purpose\n\n### Synthetic A\n\n- **Dose:** Synthetic dose\n- **How to take / apply:** Synthetic application\n- **Requirements:** Synthetic requirement\n- **Schedule:** In Synthetic owner · 2 sessions per day\n\n## Z purpose"))-        #expect(export.markdown.hasSuffix("### Synthetic B\n\n- **Schedule:** As needed\n"))-        #expect(!export.markdown.contains("Dose not recorded"))-        #expect(String(data: export.data, encoding: .utf8) == export.markdown)-    }-    @Test func markdownAndHTMLInUserContentCannotCreateHeadingsLinksTablesOrMarkup() {-        let text = "# heading *bold* _emphasis_ [link](url) <script>&value | cell `code` \\ end"-        let escaped = ConsultationMarkdown.inline(text)-        #expect(escaped == ##"\# heading \*bold\* \_emphasis\_ \[link\]\(url\) \<script\>\&value \| cell \`code\` \\ end"##)-        let export = ConsultationMarkdown.make([entry(text, purpose: "Purpose | other", requirements: text)], preparedAt: preparedAt, timeZone: utc)-        #expect(export.markdown.contains("### \(escaped)\n"))-        #expect(export.markdown.contains("- **Requirements:** \(escaped)\n"))-        #expect(!export.markdown.contains("<script>"))-    }-    @Test func multilineBlankLinesCRLFUnicodeAndMarkdownLikeLinesRemainInsideTheirField() {-        let text = "Synthetic first\r\n\r\n# heading\n1. numbered\r- nested\nÉén 👁"-        let escaped = ConsultationMarkdown.inline(text)-        #expect(escaped == ##"Synthetic first<br><br>\# heading<br>1\. numbered<br>\- nested<br>Één 👁"##)-        let export = ConsultationMarkdown.make([entry("Synthetic\nname", purpose: "Purpose\nsecond", requirements: text)], preparedAt: preparedAt, timeZone: utc)-        #expect(export.markdown.contains("## Purpose<br>second\n\n### Synthetic<br>name"))-        #expect(export.markdown.contains("- **Requirements:** \(escaped)\n"))-        #expect(export.markdown.components(separatedBy: "\n# ").count == 1)-    }-    @Test func groupingOrderIsDeterministicAndEmptyExportIsReadable() {-        let firstID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!-        let secondID = UUID(uuidString: "00000000-0000-0000-0000-000000000002")!-        let values = [entry("Same", purpose: "One", id: secondID, requirements: "Second"), entry("Same", purpose: "One", id: firstID, requirements: "First"), entry("Other", purpose: "Two")]-        let a = ConsultationMarkdown.make(values, preparedAt: preparedAt, timeZone: utc)-        let b = ConsultationMarkdown.make(values.reversed(), preparedAt: preparedAt, timeZone: utc)-        #expect(a.markdown == b.markdown && a.filename == b.filename)-        #expect(a.markdown.components(separatedBy: "## One\n").count == 2)-        let empty = ConsultationMarkdown.make([], preparedAt: preparedAt, timeZone: utc)-        #expect(empty.markdown == "# Current medications\n\nPrepared: 2026-01-06T00:40:00Z\n\nNo active medications recorded.\n")-    }-    @Test func preparedTimestampAndFilenameUseSameExplicitTimeZone() {-        let date = ISO8601DateFormatter().date(from: "2026-10-05T23:30:00Z")!-        let export = ConsultationMarkdown.make([], preparedAt: date, timeZone: TimeZone(secondsFromGMT: 7200)!)-        #expect(export.markdown.contains("Prepared: 2026-10-06T01:30:00+02:00"))-        #expect(export.filename == "meddy-current-medications-2026-10-06.md")-    }-    @Test func activeMedicationMappingKeepsRoutineOwnerOnceAndOmitsArchivedAndPhotos() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let records = MedicationService(context: store.mainContext)-        let item = try records.createAsNeededMedication(name: "Synthetic active", dose: .init(description: "Synthetic dose", amount: nil, unit: nil), purpose: nil, method: "Synthetic method", requirements: "Synthetic requirements", notes: "Synthetic private note")-        let archived = try records.createAsNeededMedication(name: "Synthetic archived"); try records.setActive(archived, false)-        item.recognitionPhotoData = Data("Synthetic bytes excluded".utf8)-        let owner = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic owner", steps: [.init(kind: .medication, targetID: item.id)], confirmedMedicationIDs: [item.id])-        let export = MedicationPresentation.consultationExport([item, archived], routines: [owner], preparedAt: preparedAt, timeZone: utc)-        #expect(export.markdown.components(separatedBy: item.name).count == 2)-        #expect(export.markdown.contains("- **Schedule:** In Synthetic owner"))-        #expect(export.markdown.contains("- **Dose:** Synthetic dose") && export.markdown.contains("- **Requirements:** Synthetic requirements"))-        #expect(!export.markdown.contains(archived.name) && !export.markdown.contains("Synthetic bytes excluded"))-        #expect(!export.markdown.contains("Synthetic private note")) // Scope stays the existing current-medication summary.-        #expect(export.markdown == MedicationPresentation.consultation([item, archived], routines: [owner], preparedAt: preparedAt, timeZone: utc))-    }-    @Test func transferableSharesUTF8MarkdownTypeRatherThanUnstructuredPlainString() async throws {-        let export = ConsultationMarkdown.make([entry("Synthetic Één 👁")], preparedAt: preparedAt, timeZone: utc)-        let provider = NSItemProvider()-        provider.register(export)-        #expect(provider.hasItemConformingToTypeIdentifier(UTType.markdown.identifier))-        #expect(provider.suggestedName == export.filename)-        let loaded: Data = try await withCheckedThrowingContinuation { continuation in-            provider.loadDataRepresentation(forTypeIdentifier: UTType.markdown.identifier) { data, error in-                if let error { continuation.resume(throwing: error) }-                else if let data { continuation.resume(returning: data) }-                else { continuation.resume(throwing: NSError(domain: "SyntheticMarkdown", code: 1)) }-            }+  private let preparedAt = Date(timeIntervalSince1970: 1_767_660_000)+  private let utc = TimeZone(secondsFromGMT: 0)!+  private func entry(+    _ name: String, purpose: String = "Ungrouped", id: UUID = UUID(), dose: String? = nil,+    method: String = "", requirements: String = "", schedule: String = "As needed"+  ) -> ConsultationMedication {+    .init(+      id: id, purpose: purpose, name: name, dose: dose, method: method, requirements: requirements,+      schedule: schedule)+  }+  @Test func headingsListsDatedFilenameAndOptionalFieldsPreserveExistingConsultationContent() {+    let values = [+      entry("Synthetic B", purpose: "Z purpose"),+      entry(+        "Synthetic A", purpose: "A purpose", dose: "Synthetic dose",+        method: "Synthetic application", requirements: "Synthetic requirement",+        schedule: "In Synthetic owner · 2 sessions per day")+    ]+    let export = ConsultationMarkdown.make(values, preparedAt: preparedAt, timeZone: utc)+    #expect(+      export.markdown.hasPrefix("# Current medications\n\nPrepared: 2026-01-06T00:40:00Z\n\n"))+    #expect(export.filename == "meddy-current-medications-2026-01-06.md")+    #expect(+      export.markdown.contains(+        """+        ## A purpose\n\n### Synthetic A\n\n- **Dose:** Synthetic dose\n- **How to take / apply:** Synthetic \+        application\n- **Requirements:** Synthetic requirement\n- **Schedule:** In Synthetic owner · 2 sessions per \+        day\n\n## Z purpose+        """+      ))+    #expect(export.markdown.hasSuffix("### Synthetic B\n\n- **Schedule:** As needed\n"))+    #expect(!export.markdown.contains("Dose not recorded"))+    #expect(String(data: export.data, encoding: .utf8) == export.markdown)+  }+  @Test func markdownAndHTMLInUserContentCannotCreateHeadingsLinksTablesOrMarkup() {+    let text = "# heading *bold* _emphasis_ [link](url) <script>&value | cell `code` \\ end"+    let escaped = ConsultationMarkdown.inline(text)+    #expect(+      escaped+        == ##"\# heading \*bold\* \_emphasis\_ \[link\]\(url\) \<script\>\&value \| cell \`code\` \\ end"##+    )+    let export = ConsultationMarkdown.make(+      [entry(text, purpose: "Purpose | other", requirements: text)], preparedAt: preparedAt,+      timeZone: utc)+    #expect(export.markdown.contains("### \(escaped)\n"))+    #expect(export.markdown.contains("- **Requirements:** \(escaped)\n"))+    #expect(!export.markdown.contains("<script>"))+  }+  @Test func multilineBlankLinesCRLFUnicodeAndMarkdownLikeLinesRemainInsideTheirField() {+    let text = "Synthetic first\r\n\r\n# heading\n1. numbered\r- nested\nÉén 👁"+    let escaped = ConsultationMarkdown.inline(text)+    #expect(+      escaped == ##"Synthetic first<br><br>\# heading<br>1\. numbered<br>\- nested<br>Één 👁"##)+    let export = ConsultationMarkdown.make(+      [entry("Synthetic\nname", purpose: "Purpose\nsecond", requirements: text)],+      preparedAt: preparedAt, timeZone: utc)+    #expect(export.markdown.contains("## Purpose<br>second\n\n### Synthetic<br>name"))+    #expect(export.markdown.contains("- **Requirements:** \(escaped)\n"))+    #expect(export.markdown.components(separatedBy: "\n# ").count == 1)+  }+  @Test func groupingOrderIsDeterministicAndEmptyExportIsReadable() {+    let firstID = UUID(uuidString: "00000000-0000-0000-0000-000000000001")!+    let secondID = UUID(uuidString: "00000000-0000-0000-0000-000000000002")!+    let values = [+      entry("Same", purpose: "One", id: secondID, requirements: "Second"),+      entry("Same", purpose: "One", id: firstID, requirements: "First"),+      entry("Other", purpose: "Two")+    ]+    let firstExport = ConsultationMarkdown.make(values, preparedAt: preparedAt, timeZone: utc)+    let secondExport = ConsultationMarkdown.make(values.reversed(), preparedAt: preparedAt, timeZone: utc)+    #expect(firstExport.markdown == secondExport.markdown && firstExport.filename == secondExport.filename)+    #expect(firstExport.markdown.components(separatedBy: "## One\n").count == 2)+    let empty = ConsultationMarkdown.make([], preparedAt: preparedAt, timeZone: utc)+    #expect(+      empty.markdown+        == "# Current medications\n\nPrepared: 2026-01-06T00:40:00Z\n\nNo active medications recorded.\n"+    )+  }+  @Test func preparedTimestampAndFilenameUseSameExplicitTimeZone() {+    let date = ISO8601DateFormatter().date(from: "2026-10-05T23:30:00Z")!+    let export = ConsultationMarkdown.make(+      [], preparedAt: date, timeZone: TimeZone(secondsFromGMT: 7200)!)+    #expect(export.markdown.contains("Prepared: 2026-10-06T01:30:00+02:00"))+    #expect(export.filename == "meddy-current-medications-2026-10-06.md")+  }+  @Test func activeMedicationMappingKeepsRoutineOwnerOnceAndOmitsArchivedAndPhotos() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let records = MedicationService(context: store.mainContext)+    let item = try records.createAsNeededMedication(+      name: "Synthetic active", dose: .init(description: "Synthetic dose", amount: nil, unit: nil),+      purpose: nil, method: "Synthetic method", requirements: "Synthetic requirements",+      notes: "Synthetic private note")+    let archived = try records.createAsNeededMedication(name: "Synthetic archived")+    try records.setActive(archived, false)+    item.recognitionPhotoData = Data("Synthetic bytes excluded".utf8)+    let owner = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic owner", steps: [.init(kind: .medication, targetID: item.id)],+      confirmedMedicationIDs: [item.id])+    let export = MedicationPresentation.consultationExport(+      [item, archived], routines: [owner], preparedAt: preparedAt, timeZone: utc)+    #expect(export.markdown.components(separatedBy: item.name).count == 2)+    #expect(export.markdown.contains("- **Schedule:** In Synthetic owner"))+    #expect(+      export.markdown.contains("- **Dose:** Synthetic dose")+        && export.markdown.contains("- **Requirements:** Synthetic requirements"))+    #expect(+      !export.markdown.contains(archived.name)+        && !export.markdown.contains("Synthetic bytes excluded"))+    #expect(!export.markdown.contains("Synthetic private note"))  // Scope stays the existing current-medication summary.+    #expect(+      export.markdown+        == MedicationPresentation.consultation(+          [item, archived], routines: [owner], preparedAt: preparedAt, timeZone: utc))+  }+  @Test func transferableSharesUTF8MarkdownTypeRatherThanUnstructuredPlainString() async throws {+    let export = ConsultationMarkdown.make(+      [entry("Synthetic Één 👁")], preparedAt: preparedAt, timeZone: utc)+    let provider = NSItemProvider()+    provider.register(export)+    #expect(provider.hasItemConformingToTypeIdentifier(UTType.markdown.identifier))+    #expect(provider.suggestedName == export.filename)+    let loaded: Data = try await withCheckedThrowingContinuation { continuation in+      provider.loadDataRepresentation(forTypeIdentifier: UTType.markdown.identifier) { data, error in+        if let error {+          continuation.resume(throwing: error)+        } else if let data {+          continuation.resume(returning: data)+        } else {+          continuation.resume(throwing: NSError(domain: "SyntheticMarkdown", code: 1))         }-        #expect(loaded == export.data && String(data: loaded, encoding: .utf8) == export.markdown)+      }     }+    #expect(loaded == export.data && String(data: loaded, encoding: .utf8) == export.markdown)+  } }
Meddy/MeddyTests/MeddyMedicationPhotoTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyMedicationPhotoTests.swift b/Meddy/MeddyTests/MeddyMedicationPhotoTests.swiftindex 3543b79..dcb73a2 100644--- a/Meddy/MeddyTests/MeddyMedicationPhotoTests.swift+++ b/Meddy/MeddyTests/MeddyMedicationPhotoTests.swift@@ -1,143 +1,207 @@ import Foundation+import ImageIO import SwiftData import Testing-import ImageIO import UniformTypeIdentifiers+ @testable import Meddy  @MainActor struct MeddyMedicationPhotoTests {-    private func image(width: Int = 48, height: Int = 32, orientation: Int = 1) throws -> Data {-        let context = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,-            space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))-        context.setFillColor(CGColor(red: 0.1, green: 0.7, blue: 0.3, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: width, height: height))-        let pixels = try #require(context.makeImage()); let output = NSMutableData()-        let destination = try #require(CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil))-        CGImageDestinationAddImage(destination, pixels, [kCGImagePropertyOrientation: orientation,-            kCGImagePropertyExifDictionary: [kCGImagePropertyExifUserComment: "Synthetic source comment"],-            kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 0, kCGImagePropertyGPSLatitudeRef: "N", kCGImagePropertyGPSLongitude: 0, kCGImagePropertyGPSLongitudeRef: "E"]] as CFDictionary)-        #expect(CGImageDestinationFinalize(destination))-        return output as Data-    }-    private func photo() throws -> Data { try MedicationPhotoProcessor.prepare(image()) }+  private func image(width: Int = 48, height: Int = 32, orientation: Int = 1) throws -> Data {+    let context = try #require(+      CGContext(+        data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,+        space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))+    context.setFillColor(CGColor(red: 0.1, green: 0.7, blue: 0.3, alpha: 1))+    context.fill(CGRect(x: 0, y: 0, width: width, height: height))+    let pixels = try #require(context.makeImage())+    let output = NSMutableData()+    let destination = try #require(+      CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil))+    CGImageDestinationAddImage(+      destination, pixels,+      [+        kCGImagePropertyOrientation: orientation,+        kCGImagePropertyExifDictionary: [+          kCGImagePropertyExifUserComment: "Synthetic source comment"+        ],+        kCGImagePropertyGPSDictionary: [+          kCGImagePropertyGPSLatitude: 0, kCGImagePropertyGPSLatitudeRef: "N",+          kCGImagePropertyGPSLongitude: 0, kCGImagePropertyGPSLongitudeRef: "E"+        ]+      ] as CFDictionary)+    #expect(CGImageDestinationFinalize(destination))+    return output as Data+  }+  private func photo() throws -> Data { try MedicationPhotoProcessor.prepare(image()) } -    @Test func normalizesOrientationBoundsAndRemovesSourceMetadata() throws {-        let input = try image(width: 2560, height: 1280, orientation: 6)-        let originalSource = try #require(CGImageSourceCreateWithData(input as CFData, nil))-        let originalProperties = try #require(CGImageSourceCopyPropertiesAtIndex(originalSource, 0, nil) as? [CFString: Any])-        #expect(originalProperties[kCGImagePropertyGPSDictionary] != nil)-        #expect((originalProperties[kCGImagePropertyExifDictionary] as? [CFString: Any])?[kCGImagePropertyExifUserComment] != nil)-        let output = try MedicationPhotoProcessor.prepare(input)-        #expect(output.count <= MedicationPhotoProcessor.storedLimit)-        let source = try #require(CGImageSourceCreateWithData(output as CFData, nil))-        let properties = try #require(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any])-        try MedicationPhotoProcessor.validate(output)-        #expect(properties[kCGImagePropertyPixelWidth] as? Int == 512)-        #expect(properties[kCGImagePropertyPixelHeight] as? Int == 1024)-        #expect(properties[kCGImagePropertyGPSDictionary] == nil)-        let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] ?? [:]-        #expect(exif[kCGImagePropertyExifUserComment] == nil)-        #expect(Set(exif.keys).isSubset(of: [kCGImagePropertyExifColorSpace, kCGImagePropertyExifPixelXDimension, kCGImagePropertyExifPixelYDimension]))-        #expect(CGImageSourceGetType(source) as String? == UTType.jpeg.identifier)+  @Test func normalizesOrientationBoundsAndRemovesSourceMetadata() throws {+    let input = try image(width: 2560, height: 1280, orientation: 6)+    let originalSource = try #require(CGImageSourceCreateWithData(input as CFData, nil))+    let originalProperties = try #require(+      CGImageSourceCopyPropertiesAtIndex(originalSource, 0, nil) as? [CFString: Any])+    #expect(originalProperties[kCGImagePropertyGPSDictionary] != nil)+    #expect(+      (originalProperties[kCGImagePropertyExifDictionary] as? [CFString: Any])?[+        kCGImagePropertyExifUserComment] != nil)+    let output = try MedicationPhotoProcessor.prepare(input)+    #expect(output.count <= MedicationPhotoProcessor.storedLimit)+    let source = try #require(CGImageSourceCreateWithData(output as CFData, nil))+    let properties = try #require(+      CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any])+    try MedicationPhotoProcessor.validate(output)+    #expect(properties[kCGImagePropertyPixelWidth] as? Int == 512)+    #expect(properties[kCGImagePropertyPixelHeight] as? Int == 1024)+    #expect(properties[kCGImagePropertyGPSDictionary] == nil)+    let exif = properties[kCGImagePropertyExifDictionary] as? [CFString: Any] ?? [:]+    #expect(exif[kCGImagePropertyExifUserComment] == nil)+    #expect(+      Set(exif.keys).isSubset(of: [+        kCGImagePropertyExifColorSpace, kCGImagePropertyExifPixelXDimension,+        kCGImagePropertyExifPixelYDimension+      ]))+    #expect(CGImageSourceGetType(source) as String? == UTType.jpeg.identifier)+  }+  @Test func malformedAndOversizedInputsAreRejectedWithoutStoredData() {+    #expect(throws: MedicationPhotoError.invalidImage) {+      _ = try MedicationPhotoProcessor.prepare(Data("synthetic invalid image".utf8))+    }+    #expect(throws: MedicationPhotoError.inputTooLarge) {+      _ = try MedicationPhotoProcessor.prepare(Data(count: MedicationPhotoProcessor.inputLimit + 1))     }-    @Test func malformedAndOversizedInputsAreRejectedWithoutStoredData() {-        #expect(throws: MedicationPhotoError.invalidImage) { _ = try MedicationPhotoProcessor.prepare(Data("synthetic invalid image".utf8)) }-        #expect(throws: MedicationPhotoError.inputTooLarge) { _ = try MedicationPhotoProcessor.prepare(Data(count: MedicationPhotoProcessor.inputLimit + 1)) }+  }+  @Test func replacingRemovingAndArchivingPhotoPreserveMedicationAndHistory() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    let medication = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic box")+    let event = try MedicationService(context: context).record(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    let id = medication.id+    let eventID = event.id+    let timestamp = event.timestamp+    let service = MedicationPhotoService(context: context)+    let first = try photo()+    try service.setPhoto(first, for: medication)+    #expect(medication.recognitionPhotoData == first)+    try MedicationService(context: context).setActive(medication, false)+    #expect(medication.recognitionPhotoData == first)+    let replacement = try MedicationPhotoProcessor.prepare(image(width: 64))+    try service.setPhoto(replacement, for: medication)+    #expect(medication.recognitionPhotoData == replacement && replacement != first)+    #expect(throws: MedicationPhotoError.invalidImage) {+      try service.setPhoto(Data("broken".utf8), for: medication)     }-    @Test func replacingRemovingAndArchivingPhotoPreserveMedicationAndHistory() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let context = store.mainContext-        let medication = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic box")-        let event = try MedicationService(context: context).record(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        let id = medication.id; let eventID = event.id; let timestamp = event.timestamp-        let service = MedicationPhotoService(context: context); let first = try photo()-        try service.setPhoto(first, for: medication)-        #expect(medication.recognitionPhotoData == first)-        try MedicationService(context: context).setActive(medication, false)-        #expect(medication.recognitionPhotoData == first)-        let replacement = try MedicationPhotoProcessor.prepare(image(width: 64))-        try service.setPhoto(replacement, for: medication)-        #expect(medication.recognitionPhotoData == replacement && replacement != first)-        #expect(throws: MedicationPhotoError.invalidImage) { try service.setPhoto(Data("broken".utf8), for: medication) }-        #expect(medication.recognitionPhotoData == replacement)-        try service.setPhoto(nil, for: medication)-        #expect(medication.recognitionPhotoData == nil && medication.id == id)-        #expect(event.id == eventID && event.timestamp == timestamp && !event.isDeleted)-        #expect(medication.visibleAdministrations.count == 1 && medication.defaultDose == .unknown)+    #expect(medication.recognitionPhotoData == replacement)+    try service.setPhoto(nil, for: medication)+    #expect(medication.recognitionPhotoData == nil && medication.id == id)+    #expect(event.id == eventID && event.timestamp == timestamp && !event.isDeleted)+    #expect(medication.visibleAdministrations.count == 1 && medication.defaultDose == .unknown)+  }+  @Test func saveFailureRollsBackReplacementAndRemoval() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic")+    let original = try photo()+    try MedicationPhotoService(context: store.mainContext).setPhoto(original, for: item)+    let failing = MedicationPhotoService(+      context: store.mainContext, save: { throw RecordingError.saveFailed })+    let next = try MedicationPhotoProcessor.prepare(image(width: 64))+    #expect(throws: RecordingError.saveFailed) { try failing.setPhoto(next, for: item) }+    #expect(item.recognitionPhotoData == original)+    #expect(throws: RecordingError.saveFailed) { try failing.setPhoto(nil, for: item) }+    #expect(item.recognitionPhotoData == original)+  }+  @Test func diskRelaunchRetainsPhotoAndRemoval() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let schema = AppEnvironment.schema+    let configuration = ModelConfiguration(+      schema: schema, url: directory.appendingPathComponent("photo.store"), cloudKitDatabase: .none)+    let bytes = try photo()+    var id: UUID?+    do {+      let container = try ModelContainer(for: schema, configurations: [configuration])+      let item = try MedicationService(context: container.mainContext).createAsNeededMedication(+        name: "Synthetic")+      id = item.id+      try MedicationPhotoService(context: container.mainContext).setPhoto(bytes, for: item)     }-    @Test func saveFailureRollsBackReplacementAndRemoval() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic")-        let original = try photo(); try MedicationPhotoService(context: store.mainContext).setPhoto(original, for: item)-        let failing = MedicationPhotoService(context: store.mainContext, save: { throw RecordingError.saveFailed })-        let next = try MedicationPhotoProcessor.prepare(image(width: 64))-        #expect(throws: RecordingError.saveFailed) { try failing.setPhoto(next, for: item) }-        #expect(item.recognitionPhotoData == original)-        #expect(throws: RecordingError.saveFailed) { try failing.setPhoto(nil, for: item) }-        #expect(item.recognitionPhotoData == original)+    do {+      let container = try ModelContainer(for: schema, configurations: [configuration])+      let item = try #require(container.mainContext.fetch(FetchDescriptor<Medication>()).first)+      #expect(item.id == id && item.recognitionPhotoData == bytes)+      try MedicationPhotoService(context: container.mainContext).setPhoto(nil, for: item)     }-    @Test func diskRelaunchRetainsPhotoAndRemoval() throws {-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        defer { try? FileManager.default.removeItem(at: directory) }-        let schema = AppEnvironment.schema; let configuration = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("photo.store"), cloudKitDatabase: .none)-        let bytes = try photo(); var id: UUID?-        do {-            let container = try ModelContainer(for: schema, configurations: [configuration])-            let item = try MedicationService(context: container.mainContext).createAsNeededMedication(name: "Synthetic")-            id = item.id; try MedicationPhotoService(context: container.mainContext).setPhoto(bytes, for: item)-        }-        do {-            let container = try ModelContainer(for: schema, configurations: [configuration])-            let item = try #require(container.mainContext.fetch(FetchDescriptor<Medication>()).first)-            #expect(item.id == id && item.recognitionPhotoData == bytes)-            try MedicationPhotoService(context: container.mainContext).setPhoto(nil, for: item)-        }-        let container = try ModelContainer(for: schema, configurations: [configuration])-        let item = try #require(container.mainContext.fetch(FetchDescriptor<Medication>()).first)-        #expect(item.id == id && item.recognitionPhotoData == nil)+    let container = try ModelContainer(for: schema, configurations: [configuration])+    let item = try #require(container.mainContext.fetch(FetchDescriptor<Medication>()).first)+    #expect(item.id == id && item.recognitionPhotoData == nil)+  }+  @Test func importFailureAndCancellationKeepPreviousDraftAndLeaveModelUntouched() async throws {+    let original = try photo()+    let draft = MedicationPhotoDraft(data: original)+    await draft.load { throw CancellationError() }+    #expect(draft.data == original && draft.error == nil && !draft.loading)+    await draft.load { nil }+    #expect(draft.data == original && draft.error != nil && !draft.loading)+    await draft.load { Data("invalid".utf8) }+    #expect(draft.data == original && draft.error != nil && !draft.loading)+  }+  @Test func obsoleteImportCannotUndoRemovalOrOverwriteNewerSelection() async throws {+    let original = try photo()+    let input = try image(width: 64)+    let draft = MedicationPhotoDraft(data: original)+    await draft.load {+      draft.remove()+      return input     }-    @Test func importFailureAndCancellationKeepPreviousDraftAndLeaveModelUntouched() async throws {-        let original = try photo(); let draft = MedicationPhotoDraft(data: original)-        await draft.load { throw CancellationError() }-        #expect(draft.data == original && draft.error == nil && !draft.loading)-        await draft.load { nil }-        #expect(draft.data == original && draft.error != nil && !draft.loading)-        await draft.load { Data("invalid".utf8) }-        #expect(draft.data == original && draft.error != nil && !draft.loading)+    #expect(draft.data == nil && !draft.loading)+    let newer = try image(width: 96)+    await draft.load {+      await draft.load { newer }+      return input     }-    @Test func obsoleteImportCannotUndoRemovalOrOverwriteNewerSelection() async throws {-        let original = try photo(); let input = try image(width: 64)-        let draft = MedicationPhotoDraft(data: original)-        await draft.load { draft.remove(); return input }-        #expect(draft.data == nil && !draft.loading)-        let newer = try image(width: 96)-        await draft.load { await draft.load { newer }; return input }-        #expect(draft.data == (try MedicationPhotoProcessor.prepare(newer)) && !draft.loading && draft.error == nil)+    #expect(+      draft.data == (try MedicationPhotoProcessor.prepare(newer)) && !draft.loading+        && draft.error == nil)+  }+  @Test func untouchedDraftPreservesNewerPhotoWhileExplicitRemovalIsSaved() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic")+    let original = try photo()+    try MedicationPhotoService(context: store.mainContext).setPhoto(original, for: item)+    let draft = MedicationPhotoDraft(data: original)+    let newer = try MedicationPhotoProcessor.prepare(image(width: 64))+    try MedicationPhotoService(context: store.mainContext).setPhoto(newer, for: item)+    try EditorTransaction.save(context: store.mainContext) {+      try draft.apply(to: item, context: store.mainContext)     }-    @Test func untouchedDraftPreservesNewerPhotoWhileExplicitRemovalIsSaved() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic")-        let original = try photo(); try MedicationPhotoService(context: store.mainContext).setPhoto(original, for: item)-        let draft = MedicationPhotoDraft(data: original)-        let newer = try MedicationPhotoProcessor.prepare(image(width: 64))-        try MedicationPhotoService(context: store.mainContext).setPhoto(newer, for: item)-        try EditorTransaction.save(context: store.mainContext) { try draft.apply(to: item, context: store.mainContext) }-        #expect(item.recognitionPhotoData == newer)-        draft.remove()-        try EditorTransaction.save(context: store.mainContext) { try draft.apply(to: item, context: store.mainContext) }-        #expect(item.recognitionPhotoData == nil)+    #expect(item.recognitionPhotoData == newer)+    draft.remove()+    try EditorTransaction.save(context: store.mainContext) {+      try draft.apply(to: item, context: store.mainContext)     }+    #expect(item.recognitionPhotoData == nil)+  } -    @Test func photoAndMedicationEditsRollbackTogether() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic original")-        let bytes = try photo(); try MedicationPhotoService(context: store.mainContext).setPhoto(bytes, for: item)-        #expect(throws: MedicationPhotoError.invalidImage) {-            try EditorTransaction.save(context: store.mainContext) {-                item.name = "Synthetic edited"-                try MedicationPhotoService(context: store.mainContext, deferSave: true).setPhoto(Data("broken".utf8), for: item)-            }-        }-        #expect(item.name == "Synthetic original" && item.recognitionPhotoData == bytes)+  @Test func photoAndMedicationEditsRollbackTogether() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic original")+    let bytes = try photo()+    try MedicationPhotoService(context: store.mainContext).setPhoto(bytes, for: item)+    #expect(throws: MedicationPhotoError.invalidImage) {+      try EditorTransaction.save(context: store.mainContext) {+        item.name = "Synthetic edited"+        try MedicationPhotoService(context: store.mainContext, deferSave: true).setPhoto(+          Data("broken".utf8), for: item)+      }     }+    #expect(item.name == "Synthetic original" && item.recognitionPhotoData == bytes)+  } }
Meddy/MeddyTests/MeddyOwnerTransferTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyOwnerTransferTests.swift b/Meddy/MeddyTests/MeddyOwnerTransferTests.swiftindex 40d2b2f..4d05a9d 100644--- a/Meddy/MeddyTests/MeddyOwnerTransferTests.swift+++ b/Meddy/MeddyTests/MeddyOwnerTransferTests.swift@@ -1,52 +1,98 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyOwnerTransferTests {-    @Test func transferEditsBothOwnersAtomicallyAndKeepsRecordedDoseHistory() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let definitions = RoutineService(context: store.mainContext)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic medication")-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let old = try definitions.createOrdered(name: "Synthetic old owner", steps: [.init(kind: .medication, targetID: medication.id), .init(kind: .treatment, targetID: care.id)], confirmedMedicationIDs: [medication.id])-        let event = try MedicationService(context: store.mainContext).record(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil))-        let new = try definitions.createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])-        #expect(medication.managedByRoutineID == new.id)-        #expect(old.steps?.count == 1 && old.steps?.first?.targetID == care.id)-        #expect(old.isActive)-        #expect(!medication.remindersEnabled)-        #expect(event.recordedDose == .unknown && !event.isDeleted)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  @Test func transferEditsBothOwnersAtomicallyAndKeepsRecordedDoseHistory() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic medication")+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let old = try definitions.createOrdered(+      name: "Synthetic old owner",+      steps: [+        .init(kind: .medication, targetID: medication.id),+        .init(kind: .treatment, targetID: care.id)+      ], confirmedMedicationIDs: [medication.id])+    let event = try MedicationService(context: store.mainContext).record(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil))+    let new = try definitions.createOrdered(+      name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+      confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])+    #expect(medication.managedByRoutineID == new.id)+    #expect(old.steps?.count == 1 && old.steps?.first?.targetID == care.id)+    #expect(old.isActive)+    #expect(!medication.remindersEnabled)+    #expect(event.recordedDose == .unknown && !event.isDeleted)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  }+  @Test func emptyPreviousOwnerRequiresExplicitArchiveAndInvalidDestinationRollsBack() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic medication")+    let old = try definitions.createOrdered(+      name: "Synthetic old owner", steps: [.init(kind: .medication, targetID: medication.id)],+      confirmedMedicationIDs: [medication.id])+    #expect(throws: DefinitionError.emptyOwnerConfirmationRequired) {+      _ = try definitions.createOrdered(+        name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+        confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])     }-    @Test func emptyPreviousOwnerRequiresExplicitArchiveAndInvalidDestinationRollsBack() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let definitions = RoutineService(context: store.mainContext)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic medication")-        let old = try definitions.createOrdered(name: "Synthetic old owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id])-        #expect(throws: DefinitionError.emptyOwnerConfirmationRequired) { _ = try definitions.createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id]) }-        #expect(old.isActive && medication.managedByRoutineID == old.id)-        #expect(throws: DefinitionError.invalidSchedule) {-            _ = try EditorTransaction.save(context: store.mainContext) {-                let new = try RoutineService(context: store.mainContext, deferSave: true).createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id], archiveEmptyOwnerIDs: [old.id])-                try ScheduleService(context: store.mainContext, deferSave: true).configure(new, slots: [], reminders: false)-                return new-            }-        }-        #expect(old.isActive && old.steps?.count == 1 && medication.managedByRoutineID == old.id)-        let new = try definitions.createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id], archiveEmptyOwnerIDs: [old.id])-        #expect(!old.isActive && old.steps?.isEmpty == true && medication.managedByRoutineID == new.id)+    #expect(old.isActive && medication.managedByRoutineID == old.id)+    #expect(throws: DefinitionError.invalidSchedule) {+      _ = try EditorTransaction.save(context: store.mainContext) {+        let new = try RoutineService(context: store.mainContext, deferSave: true).createOrdered(+          name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+          confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id],+          archiveEmptyOwnerIDs: [old.id])+        try ScheduleService(context: store.mainContext, deferSave: true).configure(+          new, slots: [], reminders: false)+        return new+      }     }-    @Test func completedMedicationStepDoesNotBlockTransferButPendingStepDoes() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let definitions = RoutineService(context: store.mainContext)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic medication")-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let old = try definitions.createOrdered(name: "Synthetic old owner", steps: [.init(kind: .medication, targetID: medication.id), .init(kind: .treatment, targetID: care.id)], confirmedMedicationIDs: [medication.id])-        let sessions = RoutineSessionService(context: store.mainContext); let run = try sessions.start(old)-        let step = try #require(sessions.definition(run).steps.first)-        #expect(throws: DefinitionError.unresolvedFrozenStep) { _ = try definitions.createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id]) }-        _ = try sessions.recordMedication(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil), in: run, stepID: step.id)-        let new = try definitions.createOrdered(name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])-        #expect(medication.managedByRoutineID == new.id)-        #expect(try sessions.progress(run).steps[0].state == .completed)+    #expect(old.isActive && old.steps?.count == 1 && medication.managedByRoutineID == old.id)+    let new = try definitions.createOrdered(+      name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+      confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id],+      archiveEmptyOwnerIDs: [old.id])+    #expect(!old.isActive && old.steps?.isEmpty == true && medication.managedByRoutineID == new.id)+  }+  @Test func completedMedicationStepDoesNotBlockTransferButPendingStepDoes() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic medication")+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let old = try definitions.createOrdered(+      name: "Synthetic old owner",+      steps: [+        .init(kind: .medication, targetID: medication.id),+        .init(kind: .treatment, targetID: care.id)+      ], confirmedMedicationIDs: [medication.id])+    let sessions = RoutineSessionService(context: store.mainContext)+    let run = try sessions.start(old)+    let step = try #require(sessions.definition(run).steps.first)+    #expect(throws: DefinitionError.unresolvedFrozenStep) {+      _ = try definitions.createOrdered(+        name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+        confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])     }+    _ = try sessions.recordMedication(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil),+      in: run, stepID: step.id)+    let new = try definitions.createOrdered(+      name: "Synthetic new owner", steps: [.init(kind: .medication, targetID: medication.id)],+      confirmedMedicationIDs: [medication.id], transferredMedicationIDs: [medication.id])+    #expect(medication.managedByRoutineID == new.id)+    #expect(try sessions.progress(run).steps[0].state == .completed)+  } }
Meddy/MeddyTests/MeddyPhoneCompanionTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyPhoneCompanionTests.swift b/Meddy/MeddyTests/MeddyPhoneCompanionTests.swiftindex 45cf847..a057e34 100644--- a/Meddy/MeddyTests/MeddyPhoneCompanionTests.swift+++ b/Meddy/MeddyTests/MeddyPhoneCompanionTests.swift@@ -1,91 +1,146 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyPhoneCompanionTests {-    private func cached(_ run: RoutineRun, service: RoutineSessionService) throws -> CompanionRun {-        .init(id: run.id, definition: try service.definition(run), progress: try service.progress(run), timer: try run.timerCheckpointData.map { try JSONDecoder().decode(TimerCheckpoint.self, from: $0) }, status: SessionPhase(rawValue: run.statusRaw)!, startedAt: run.startedAt, revision: run.revision, executionDeviceID: "synthetic-watch", processedActionIDs: [], isDeleted: false)-    }-    @Test func duplicatedWatchDoseAndTombstoneNeverCreateASecondAdministration() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic medication")-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let routine = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic group", steps: [.init(kind: .medication, targetID: medication.id), .init(kind: .treatment, targetID: care.id)], confirmedMedicationIDs: [medication.id])-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(routine); let saved = try cached(run, service: service); let stepID = saved.definition.steps[0].id-        let actionID = UUID()-        let event = AdministrationAction(eventID: actionID, medicationID: medication.id, timestamp: Date(), source: .watch, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)-        let action = CompanionAction(id: actionID, deviceID: "synthetic-watch", timestamp: event.timestamp, expectedRevision: 0, operation: .medication(event, runID: run.id, stepID: stepID), cachedRun: saved)-        let companion = PhoneCompanionService(context: store.mainContext)-        try companion.apply(action); try companion.apply(action)-        let canonical = try #require(store.mainContext.fetch(FetchDescriptor<Administration>()).first)-        try service.correct(canonical, timestamp: canonical.timestamp, dose: canonical.recordedDose, delete: true)-        try companion.apply(action)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-        #expect(canonical.isDeleted)-        #expect(try service.progress(run).steps[0].state == .needsReview)-    }-    @Test func cachedOldPlanImportsWithoutReFreezingCurrentDefinition() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let timer = try RoutineService(context: store.mainContext).createTimed(name: "Synthetic old timer", rounds: 2, durationSeconds: 30)-        let session = RoutineSessionService(context: store.mainContext); let seed = try session.start(timer)-        var saved = try cached(seed, service: session); saved.id = UUID()-        try RoutineService(context: store.mainContext).updateTimed(timer, name: "Synthetic edited timer", rounds: 3, durationSeconds: 60, instructions: "", betweenRounds: "", purpose: nil)-        let imported = try session.importWatchRun(saved, deviceID: "synthetic-watch", timestamp: Date())-        #expect(try session.definition(imported).name == "Synthetic old timer")-        #expect(try session.timer(imported).roundCount == 2)-        #expect(try session.timer(imported).durationSeconds == 30)-    }-    @Test func importedChildBindsParentAndOnlyReportedFinalCompletionFulfilsIt() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let definitions = RoutineService(context: store.mainContext)-        let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)-        let group = try definitions.createOrdered(name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])-        let session = RoutineSessionService(context: store.mainContext); let parent = try session.start(group)-        let step = try #require(session.definition(parent).steps.first)-        let childDefinition = FrozenRoutineDefinition(routineID: timer.id, revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "", roundCount: 1, roundDurationSeconds: 30, betweenRoundInstructions: "", steps: [])-        var checkpoint = try TimerCheckpoint(rounds: 1, durationSeconds: 30)-        let child = CompanionRun(id: UUID(), definition: childDefinition, progress: .init(definition: childDefinition), timer: checkpoint, status: .active, startedAt: Date(), revision: 0, executionDeviceID: "synthetic-watch", parentRunID: parent.id, parentStepID: step.id, processedActionIDs: [], isDeleted: false)-        let imported = try session.importWatchRun(child, deviceID: "synthetic-watch", timestamp: Date())-        #expect(try session.progress(parent).steps[0].state == .inProgress)-        #expect(try session.progress(parent).steps[0].canonicalEventID == child.id)-        let clock = ClockSample(wall: Date().addingTimeInterval(-30), monotonic: 0, continuityID: "synthetic")-        try checkpoint.start(at: clock)-        checkpoint.advance(at: .init(wall: clock.wall.addingTimeInterval(30), monotonic: 30, continuityID: "synthetic"))-        let actionID = UUID()-        try session.importWatchTimer(imported, checkpoint: checkpoint, actionID: actionID, timestamp: Date(), expectedRevision: 0, deviceID: "synthetic-watch")-        try session.importWatchTimer(imported, checkpoint: checkpoint, actionID: actionID, timestamp: Date(), expectedRevision: 0, deviceID: "synthetic-watch")-        #expect(imported.wasCompleted)-        #expect(try session.progress(parent).phase == .completed)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }-    @Test func connectedHandoffPausesBeforeAssigningOwnerAndReplayCannotAdvanceIt() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let timer = try RoutineService(context: store.mainContext).createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 30)-        let service = RoutineSessionService(context: store.mainContext); let run = try service.start(timer)-        try service.changeTimer(run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .start)-        let revision = run.revision; let actionID = UUID()-        try service.handoff(run, toDeviceID: "synthetic-watch", actionID: actionID, expectedRevision: revision)-        #expect(try service.timer(run).phase == .paused)-        #expect(run.executionDeviceID == "synthetic-watch")-        let newRevision = run.revision-        try service.handoff(run, toDeviceID: "synthetic-watch", actionID: actionID, expectedRevision: revision)-        #expect(run.revision == newRevision)-        #expect(throws: ExecutionError.invalidTransition) { try service.handoff(run, toDeviceID: "other", actionID: UUID(), expectedRevision: revision) }-    }-    @Test func groupHandoffTransfersPausedChildOwnershipInSameSave() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let definitions = RoutineService(context: store.mainContext)-        let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 30)-        let group = try definitions.createOrdered(name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])-        let service = RoutineSessionService(context: store.mainContext); let parent = try service.start(group, deviceID: "phone")-        let step = try #require(service.definition(parent).steps.first)-        let child = try service.beginTimedStep(parent, stepID: step.id)-        try service.changeTimer(child, actionID: UUID(), clock: ExecutionClock.sample(), operation: .start)-        try service.handoff(parent, toDeviceID: "watch", actionID: UUID(), expectedRevision: parent.revision)-        #expect(parent.executionDeviceID == "watch" && child.executionDeviceID == "watch")-        #expect(try service.timer(child).phase == .paused)-        #expect(try service.progress(parent).phase == .paused)+  private func cached(_ run: RoutineRun, service: RoutineSessionService) throws -> CompanionRun {+    .init(+      id: run.id, definition: try service.definition(run), progress: try service.progress(run),+      timer: try run.timerCheckpointData.map {+        try JSONDecoder().decode(TimerCheckpoint.self, from: $0)+      }, status: SessionPhase(rawValue: run.statusRaw)!, startedAt: run.startedAt,+      revision: run.revision, executionDeviceID: "synthetic-watch", processedActionIDs: [],+      isDeleted: false)+  }+  @Test func duplicatedWatchDoseAndTombstoneNeverCreateASecondAdministration() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic medication")+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let routine = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic group",+      steps: [+        .init(kind: .medication, targetID: medication.id),+        .init(kind: .treatment, targetID: care.id)+      ], confirmedMedicationIDs: [medication.id])+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(routine)+    let saved = try cached(run, service: service)+    let stepID = saved.definition.steps[0].id+    let actionID = UUID()+    let event = AdministrationAction(+      eventID: actionID, medicationID: medication.id, timestamp: Date(), source: .watch,+      dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)+    let action = CompanionAction(+      id: actionID, deviceID: "synthetic-watch", timestamp: event.timestamp, expectedRevision: 0,+      operation: .medication(event, runID: run.id, stepID: stepID), cachedRun: saved)+    let companion = PhoneCompanionService(context: store.mainContext)+    try companion.apply(action)+    try companion.apply(action)+    let canonical = try #require(store.mainContext.fetch(FetchDescriptor<Administration>()).first)+    try service.correct(+      canonical, timestamp: canonical.timestamp, dose: canonical.recordedDose, delete: true)+    try companion.apply(action)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+    #expect(canonical.isDeleted)+    #expect(try service.progress(run).steps[0].state == .needsReview)+  }+  @Test func cachedOldPlanImportsWithoutReFreezingCurrentDefinition() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let timer = try RoutineService(context: store.mainContext).createTimed(+      name: "Synthetic old timer", rounds: 2, durationSeconds: 30)+    let session = RoutineSessionService(context: store.mainContext)+    let seed = try session.start(timer)+    var saved = try cached(seed, service: session)+    saved.id = UUID()+    try RoutineService(context: store.mainContext).updateTimed(+      timer, edit: TimedRoutineEdit(name: "Synthetic edited timer", rounds: 3, durationSeconds: 60, instructions: "",+      betweenRounds: "", purpose: nil))+    let imported = try session.importWatchRun(saved, deviceID: "synthetic-watch", timestamp: Date())+    #expect(try session.definition(imported).name == "Synthetic old timer")+    #expect(try session.timer(imported).roundCount == 2)+    #expect(try session.timer(imported).durationSeconds == 30)+  }+  @Test func importedChildBindsParentAndOnlyReportedFinalCompletionFulfilsIt() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)+    let group = try definitions.createOrdered(+      name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])+    let session = RoutineSessionService(context: store.mainContext)+    let parent = try session.start(group)+    let step = try #require(session.definition(parent).steps.first)+    let childDefinition = FrozenRoutineDefinition(+      routineID: timer.id, revision: 1, kind: .timedRounds, name: "Synthetic timer",+      instructions: "", roundCount: 1, roundDurationSeconds: 30, betweenRoundInstructions: "",+      steps: [])+    var checkpoint = try TimerCheckpoint(rounds: 1, durationSeconds: 30)+    let child = CompanionRun(+      id: UUID(), definition: childDefinition, progress: .init(definition: childDefinition),+      timer: checkpoint, status: .active, startedAt: Date(), revision: 0,+      executionDeviceID: "synthetic-watch", parentRunID: parent.id, parentStepID: step.id,+      processedActionIDs: [], isDeleted: false)+    let imported = try session.importWatchRun(child, deviceID: "synthetic-watch", timestamp: Date())+    #expect(try session.progress(parent).steps[0].state == .inProgress)+    #expect(try session.progress(parent).steps[0].canonicalEventID == child.id)+    let clock = ClockSample(+      wall: Date().addingTimeInterval(-30), monotonic: 0, continuityID: "synthetic")+    try checkpoint.start(at: clock)+    checkpoint.advance(+      at: .init(wall: clock.wall.addingTimeInterval(30), monotonic: 30, continuityID: "synthetic"))+    let actionID = UUID()+    try session.importWatchTimer(+      imported, checkpoint: checkpoint, actionID: actionID, timestamp: Date(), expectedRevision: 0,+      deviceID: "synthetic-watch")+    try session.importWatchTimer(+      imported, checkpoint: checkpoint, actionID: actionID, timestamp: Date(), expectedRevision: 0,+      deviceID: "synthetic-watch")+    #expect(imported.wasCompleted)+    #expect(try session.progress(parent).phase == .completed)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func connectedHandoffPausesBeforeAssigningOwnerAndReplayCannotAdvanceIt() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let timer = try RoutineService(context: store.mainContext).createTimed(+      name: "Synthetic timer", rounds: 2, durationSeconds: 30)+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(timer)+    try service.changeTimer(+      run, actionID: UUID(), clock: ExecutionClock.sample(), operation: .start)+    let revision = run.revision+    let actionID = UUID()+    try service.handoff(+      run, toDeviceID: "synthetic-watch", actionID: actionID, expectedRevision: revision)+    #expect(try service.timer(run).phase == .paused)+    #expect(run.executionDeviceID == "synthetic-watch")+    let newRevision = run.revision+    try service.handoff(+      run, toDeviceID: "synthetic-watch", actionID: actionID, expectedRevision: revision)+    #expect(run.revision == newRevision)+    #expect(throws: ExecutionError.invalidTransition) {+      try service.handoff(run, toDeviceID: "other", actionID: UUID(), expectedRevision: revision)     }+  }+  @Test func groupHandoffTransfersPausedChildOwnershipInSameSave() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 30)+    let group = try definitions.createOrdered(+      name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])+    let service = RoutineSessionService(context: store.mainContext)+    let parent = try service.start(group, deviceID: "phone")+    let step = try #require(service.definition(parent).steps.first)+    let child = try service.beginTimedStep(parent, stepID: step.id)+    try service.changeTimer(+      child, actionID: UUID(), clock: ExecutionClock.sample(), operation: .start)+    try service.handoff(+      parent, toDeviceID: "watch", actionID: UUID(), expectedRevision: parent.revision)+    #expect(parent.executionDeviceID == "watch" && child.executionDeviceID == "watch")+    #expect(try service.timer(child).phase == .paused)+    #expect(try service.progress(parent).phase == .paused)+  }  }
Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swiftindex bbc4e0d..9d0265b 100644--- a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift+++ b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift@@ -1,109 +1,162 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyPhoneRoundAlertTests {-    private func fixture() throws -> (ModelContainer, RoutineRun, RoutineSessionService) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let routine = try RoutineService(context: store.mainContext).createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 10)-        let service = RoutineSessionService(context: store.mainContext)-        return (store, try service.start(routine), service)-    }-    @Test func deadlineBuzzesEachRoundOnceWithoutAnyTimerViewAndNeverAutoStartsNext() throws {-        let (store, run, service) = try fixture(); let scheduler = SyntheticDeadlineScheduler()-        var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic"); var buzzes = 0; var awake = false-        let alerts = PhoneRoundAlertService(context: store.mainContext, scheduler: scheduler, clock: { sample }, feedback: { buzzes += 1 }, keepAwake: { awake = $0 }, enabled: true)-        alerts.setActive(true)-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        let first = try #require(scheduler.entries.last)-        #expect(awake)-        #expect(first.deadline == sample.wall.addingTimeInterval(10))-        sample.wall = sample.wall.addingTimeInterval(10); sample.monotonic += 10-        first.action(); first.action(); alerts.refresh()-        #expect(buzzes == 1); #expect(try service.timer(run).phase == .waiting)-        #expect(try service.timer(run).completedRounds == 1)-        #expect(scheduler.entries.count == 1 && !awake)-        sample.wall = sample.wall.addingTimeInterval(600); sample.monotonic += 600-        alerts.refresh(); #expect(scheduler.entries.count == 1 && buzzes == 1)-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        let final = try #require(scheduler.entries.last)-        sample.wall = sample.wall.addingTimeInterval(10); sample.monotonic += 10-        final.action(); final.action()-        #expect(buzzes == 2 && run.wasCompleted && !awake)-        #expect(try service.timer(run).phase == .completed)-    }-    @Test func pauseResumeAndEndCancelObsoleteDeadlineCallbacks() throws {-        let (store, run, service) = try fixture(); let scheduler = SyntheticDeadlineScheduler()-        var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic"); var buzzes = 0-        let alerts = PhoneRoundAlertService(context: store.mainContext, scheduler: scheduler, clock: { sample }, feedback: { buzzes += 1 }, enabled: true)-        alerts.setActive(true); try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        let old = try #require(scheduler.entries.last)-        sample.wall = sample.wall.addingTimeInterval(3); sample.monotonic += 3-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .pause)-        #expect(old.cancelled)-        old.action(); #expect(buzzes == 0); #expect(try service.timer(run).phase == .paused)-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .resume)-        let resumed = try #require(scheduler.entries.last)-        #expect(resumed.deadline == sample.wall.addingTimeInterval(7))-        old.action(); #expect(buzzes == 0)-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .end)-        #expect(resumed.cancelled); resumed.action()-        #expect(buzzes == 0 && !run.wasCompleted)-    }-    @Test func backgroundCatchUpDoesNotDuplicateSystemNotificationBuzz() throws {-        let (store, run, service) = try fixture(); let scheduler = SyntheticDeadlineScheduler()-        var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic"); var buzzes = 0-        let alerts = PhoneRoundAlertService(context: store.mainContext, scheduler: scheduler, clock: { sample }, feedback: { buzzes += 1 }, enabled: true)-        alerts.setActive(true); try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        let old = try #require(scheduler.entries.last); alerts.setActive(false)-        sample.wall = sample.wall.addingTimeInterval(20); sample.monotonic += 20-        old.action(); #expect(buzzes == 0); #expect(try service.timer(run).phase == .running)-        alerts.setActive(true)-        #expect(buzzes == 0); #expect(try service.timer(run).phase == .waiting)-        #expect(ReminderService.foregroundPresentation(category: "TIMER").isEmpty)-        #expect(!ReminderService.foregroundPresentation(category: "MEDICATION").isEmpty)-    }-    @Test func uncertainRelaunchCanExplicitlyResumeAndStillBuzzAtNewDeadline() throws {-        let (store, run, service) = try fixture(); let scheduler = SyntheticDeadlineScheduler()-        var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "old")-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        sample.continuityID = "new"; var buzzes = 0-        let alerts = PhoneRoundAlertService(context: store.mainContext, scheduler: scheduler, clock: { sample }, feedback: { buzzes += 1 }, enabled: true)-        alerts.setActive(true)-        #expect(try service.timer(run).phase == .interrupted)-        // Immediate resume can retain the same wall deadline; the new continuity must not-        // collide with the interrupted checkpoint's action ID.-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .resume)-        sample.wall = sample.wall.addingTimeInterval(10); sample.monotonic += 10-        try #require(scheduler.entries.last).action()-        #expect(buzzes == 1); #expect(try service.timer(run).phase == .waiting)-    }-    @Test func ownershipHandoffCancelsPhoneDeadlineAndNeverBuzzesRemoteRound() throws {-        let (store, run, service) = try fixture(); let scheduler = SyntheticDeadlineScheduler()-        let sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic"); var buzzes = 0-        let alerts = PhoneRoundAlertService(context: store.mainContext, scheduler: scheduler, clock: { sample }, feedback: { buzzes += 1 }, enabled: true)-        alerts.deviceID = "phone"; alerts.setActive(true)-        try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)-        let old = try #require(scheduler.entries.last)-        try service.handoff(run, toDeviceID: "watch", actionID: UUID(), expectedRevision: run.revision)-        old.action(); #expect(old.cancelled && buzzes == 0)-    }+  private func fixture() throws -> (ModelContainer, RoutineRun, RoutineSessionService) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let routine = try RoutineService(context: store.mainContext).createTimed(+      name: "Synthetic timer", rounds: 2, durationSeconds: 10)+    let service = RoutineSessionService(context: store.mainContext)+    return (store, try service.start(routine), service)+  }+  @Test func deadlineBuzzesEachRoundOnceWithoutAnyTimerViewAndNeverAutoStartsNext() throws {+    let (store, run, service) = try fixture()+    let scheduler = SyntheticDeadlineScheduler()+    var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    var buzzes = 0+    var awake = false+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, keepAwake: { awake = $0 }, enabled: true)+    alerts.setActive(true)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let first = try #require(scheduler.entries.last)+    #expect(awake)+    #expect(first.deadline == sample.wall.addingTimeInterval(10))+    sample.wall = sample.wall.addingTimeInterval(10)+    sample.monotonic += 10+    first.action()+    first.action()+    alerts.refresh()+    #expect(buzzes == 1)+    #expect(try service.timer(run).phase == .waiting)+    #expect(try service.timer(run).completedRounds == 1)+    #expect(scheduler.entries.count == 1 && !awake)+    sample.wall = sample.wall.addingTimeInterval(600)+    sample.monotonic += 600+    alerts.refresh()+    #expect(scheduler.entries.count == 1 && buzzes == 1)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let final = try #require(scheduler.entries.last)+    sample.wall = sample.wall.addingTimeInterval(10)+    sample.monotonic += 10+    final.action()+    final.action()+    #expect(buzzes == 2 && run.wasCompleted && !awake)+    #expect(try service.timer(run).phase == .completed)+  }+  @Test func pauseResumeAndEndCancelObsoleteDeadlineCallbacks() throws {+    let (store, run, service) = try fixture()+    let scheduler = SyntheticDeadlineScheduler()+    var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    var buzzes = 0+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, enabled: true)+    alerts.setActive(true)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let old = try #require(scheduler.entries.last)+    sample.wall = sample.wall.addingTimeInterval(3)+    sample.monotonic += 3+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .pause)+    #expect(old.cancelled)+    old.action()+    #expect(buzzes == 0)+    #expect(try service.timer(run).phase == .paused)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .resume)+    let resumed = try #require(scheduler.entries.last)+    #expect(resumed.deadline == sample.wall.addingTimeInterval(7))+    old.action()+    #expect(buzzes == 0)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .end)+    #expect(resumed.cancelled)+    resumed.action()+    #expect(buzzes == 0 && !run.wasCompleted)+  }+  @Test func backgroundCatchUpDoesNotDuplicateSystemNotificationBuzz() throws {+    let (store, run, service) = try fixture()+    let scheduler = SyntheticDeadlineScheduler()+    var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    var buzzes = 0+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, enabled: true)+    alerts.setActive(true)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let old = try #require(scheduler.entries.last)+    alerts.setActive(false)+    sample.wall = sample.wall.addingTimeInterval(20)+    sample.monotonic += 20+    old.action()+    #expect(buzzes == 0)+    #expect(try service.timer(run).phase == .running)+    alerts.setActive(true)+    #expect(buzzes == 0)+    #expect(try service.timer(run).phase == .waiting)+    #expect(ReminderService.foregroundPresentation(category: "TIMER").isEmpty)+    #expect(!ReminderService.foregroundPresentation(category: "MEDICATION").isEmpty)+  }+  @Test func uncertainRelaunchCanExplicitlyResumeAndStillBuzzAtNewDeadline() throws {+    let (store, run, service) = try fixture()+    let scheduler = SyntheticDeadlineScheduler()+    var sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "old")+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    sample.continuityID = "new"+    var buzzes = 0+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, enabled: true)+    alerts.setActive(true)+    #expect(try service.timer(run).phase == .interrupted)+    // Immediate resume can retain the same wall deadline; the new continuity must not+    // collide with the interrupted checkpoint's action ID.+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .resume)+    sample.wall = sample.wall.addingTimeInterval(10)+    sample.monotonic += 10+    try #require(scheduler.entries.last).action()+    #expect(buzzes == 1)+    #expect(try service.timer(run).phase == .waiting)+  }+  @Test func ownershipHandoffCancelsPhoneDeadlineAndNeverBuzzesRemoteRound() throws {+    let (store, run, service) = try fixture()+    let scheduler = SyntheticDeadlineScheduler()+    let sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    var buzzes = 0+    let alerts = PhoneRoundAlertService(+      context: store.mainContext, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, enabled: true)+    alerts.deviceID = "phone"+    alerts.setActive(true)+    try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    let old = try #require(scheduler.entries.last)+    try service.handoff(run, toDeviceID: "watch", actionID: UUID(), expectedRevision: run.revision)+    old.action()+    #expect(old.cancelled && buzzes == 0)+  } }  @MainActor private final class SyntheticDeadline: RoundDeadlineCancellation {-    let deadline: Date-    let action: @MainActor () -> Void-    var cancelled = false-    init(deadline: Date, action: @escaping @MainActor () -> Void) { self.deadline = deadline; self.action = action }-    func cancel() { cancelled = true }+  let deadline: Date+  let action: @MainActor () -> Void+  var cancelled = false+  init(deadline: Date, action: @escaping @MainActor () -> Void) {+    self.deadline = deadline+    self.action = action+  }+  func cancel() { cancelled = true } } @MainActor private final class SyntheticDeadlineScheduler: RoundDeadlineScheduling {-    var entries: [SyntheticDeadline] = []-    func schedule(at deadline: Date, action: @escaping @MainActor () -> Void) -> any RoundDeadlineCancellation {-        let entry = SyntheticDeadline(deadline: deadline, action: action); entries.append(entry); return entry-    }+  var entries: [SyntheticDeadline] = []+  func schedule(at deadline: Date, action: @escaping @MainActor () -> Void)+    -> any RoundDeadlineCancellation {+    let entry = SyntheticDeadline(deadline: deadline, action: action)+    entries.append(entry)+    return entry+  } }
Meddy/MeddyTests/MeddyPhoneTimerControlTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyPhoneTimerControlTests.swift b/Meddy/MeddyTests/MeddyPhoneTimerControlTests.swiftindex fc8a958..2b4929f 100644--- a/Meddy/MeddyTests/MeddyPhoneTimerControlTests.swift+++ b/Meddy/MeddyTests/MeddyPhoneTimerControlTests.swift@@ -1,50 +1,59 @@ import Foundation import Testing+ @testable import Meddy  struct MeddyPhoneTimerControlTests {-    private func clock(_ time: Double) -> ClockSample { .init(wall: Date(timeIntervalSince1970: time), monotonic: time, continuityID: "synthetic") }-    @Test func centralTapPausesAndResumesSameRoundWithoutAdvancing() throws {-        var timer = try TimerCheckpoint(rounds: 3, durationSeconds: 30)-        #expect(PhoneTimerControl(checkpoint: timer, clock: clock(100)).operation == .start)-        try timer.start(at: clock(100))-        let running = PhoneTimerControl(checkpoint: timer, clock: clock(107))-        #expect(running.title == "Round 1" && running.countdown == "00:23" && running.operation == .pause)-        try timer.pause(at: clock(107))-        let paused = PhoneTimerControl(checkpoint: timer, clock: clock(500))-        #expect(paused.countdown == "00:23" && paused.operation == .resume)-        try timer.resume(at: clock(500))-        #expect(timer.roundIndex == 0 && timer.completedRounds == 0)-        #expect(PhoneTimerControl(checkpoint: timer, clock: clock(523)).operation == .pause)-        timer.advance(at: clock(523))-        let waiting = PhoneTimerControl(checkpoint: timer, clock: clock(900))-        #expect(waiting.title == "Start round 2" && waiting.operation == .start && waiting.countdown == nil)-        #expect(timer.roundIndex == 0 && timer.completedRounds == 1)-    }-    @Test func latePauseAtDeadlineCannotStartNextRoundAndCompletedControlHasNoAction() throws {-        var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 10)-        try timer.start(at: clock(100)); try timer.pause(at: clock(110))-        #expect(timer.phase == .waiting && timer.completedRounds == 1)-        #expect(PhoneTimerControl(checkpoint: timer, clock: clock(110)).operation == .start)-        try timer.start(at: clock(200)); timer.advance(at: clock(210))-        let completed = PhoneTimerControl(checkpoint: timer, clock: clock(210))-        #expect(completed.operation == nil && completed.accessibilityLabel == "All 2 rounds completed")-    }-    @Test func veryLargeSavedDurationDoesNotOverflowTheDisplayFormatter() throws {-        var timer = try TimerCheckpoint(rounds: 1, durationSeconds: Int.max)-        try timer.start(at: clock(100))-        let display = PhoneTimerControl(checkpoint: timer, clock: clock(100))-        #expect(display.operation == .pause && display.countdown?.contains(":") == true)-    }-    @Test func interruptedAndEndedControlsRequireExplicitResumeOrReopen() throws {-        var timer = try TimerCheckpoint(rounds: 3, durationSeconds: 30)-        timer.roundIndex = 2; timer.phase = .interrupted; timer.accumulatedActiveSeconds = 7-        let interrupted = PhoneTimerControl(checkpoint: timer, clock: clock(100))-        #expect(interrupted.operation == .resume && interrupted.countdown == "00:23")-        #expect(interrupted.accessibilityLabel.contains("remaining time"))-        try timer.end(at: clock(100))-        #expect(PhoneTimerControl(checkpoint: timer, clock: clock(100)).operation == .reopen)-        try timer.reopen()-        #expect(timer.phase == .paused && timer.roundIndex == 2)-    }+  private func clock(_ time: Double) -> ClockSample {+    .init(wall: Date(timeIntervalSince1970: time), monotonic: time, continuityID: "synthetic")+  }+  @Test func centralTapPausesAndResumesSameRoundWithoutAdvancing() throws {+    var timer = try TimerCheckpoint(rounds: 3, durationSeconds: 30)+    #expect(PhoneTimerControl(checkpoint: timer, clock: clock(100)).operation == .start)+    try timer.start(at: clock(100))+    let running = PhoneTimerControl(checkpoint: timer, clock: clock(107))+    #expect(+      running.title == "Round 1" && running.countdown == "00:23" && running.operation == .pause)+    try timer.pause(at: clock(107))+    let paused = PhoneTimerControl(checkpoint: timer, clock: clock(500))+    #expect(paused.countdown == "00:23" && paused.operation == .resume)+    try timer.resume(at: clock(500))+    #expect(timer.roundIndex == 0 && timer.completedRounds == 0)+    #expect(PhoneTimerControl(checkpoint: timer, clock: clock(523)).operation == .pause)+    timer.advance(at: clock(523))+    let waiting = PhoneTimerControl(checkpoint: timer, clock: clock(900))+    #expect(+      waiting.title == "Start round 2" && waiting.operation == .start && waiting.countdown == nil)+    #expect(timer.roundIndex == 0 && timer.completedRounds == 1)+  }+  @Test func latePauseAtDeadlineCannotStartNextRoundAndCompletedControlHasNoAction() throws {+    var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 10)+    try timer.start(at: clock(100))+    try timer.pause(at: clock(110))+    #expect(timer.phase == .waiting && timer.completedRounds == 1)+    #expect(PhoneTimerControl(checkpoint: timer, clock: clock(110)).operation == .start)+    try timer.start(at: clock(200))+    timer.advance(at: clock(210))+    let completed = PhoneTimerControl(checkpoint: timer, clock: clock(210))+    #expect(completed.operation == nil && completed.accessibilityLabel == "All 2 rounds completed")+  }+  @Test func veryLargeSavedDurationDoesNotOverflowTheDisplayFormatter() throws {+    var timer = try TimerCheckpoint(rounds: 1, durationSeconds: Int.max)+    try timer.start(at: clock(100))+    let display = PhoneTimerControl(checkpoint: timer, clock: clock(100))+    #expect(display.operation == .pause && display.countdown?.contains(":") == true)+  }+  @Test func interruptedAndEndedControlsRequireExplicitResumeOrReopen() throws {+    var timer = try TimerCheckpoint(rounds: 3, durationSeconds: 30)+    timer.roundIndex = 2+    timer.phase = .interrupted+    timer.accumulatedActiveSeconds = 7+    let interrupted = PhoneTimerControl(checkpoint: timer, clock: clock(100))+    #expect(interrupted.operation == .resume && interrupted.countdown == "00:23")+    #expect(interrupted.accessibilityLabel.contains("remaining time"))+    try timer.end(at: clock(100))+    #expect(PhoneTimerControl(checkpoint: timer, clock: clock(100)).operation == .reopen)+    try timer.reopen()+    #expect(timer.phase == .paused && timer.roundIndex == 2)+  } }
Meddy/MeddyTests/MeddyProfileIsolationTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyProfileIsolationTests.swift b/Meddy/MeddyTests/MeddyProfileIsolationTests.swiftindex 5c0e1d4..1cc3aa3 100644--- a/Meddy/MeddyTests/MeddyProfileIsolationTests.swift+++ b/Meddy/MeddyTests/MeddyProfileIsolationTests.swift@@ -1,58 +1,97 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyProfileIsolationTests {-    private func setup() throws -> (ModelContainer, CareProfile, CareProfile) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let service = ProfileService(context: store.mainContext)-        return (store, try service.create(displayName: "Same name"), try service.create(displayName: "Same name"))-    }-    @Test func identicalNamesHaveIndependentDoseHistoryAndCapturedActionOwnership() throws {-        let (store, a, b) = try setup(); let c = store.mainContext; let service = MedicationService(context: c)-        let one = try service.createAsNeededMedication(name: "Same synthetic medicine", dose: .init(description: "", amount: 1, unit: "test"), profileID: a.id)-        let two = try service.createAsNeededMedication(name: one.name, dose: .init(description: "", amount: 2, unit: "test"), profileID: b.id)-        var action = AdministrationAction(eventID: UUID(), medicationID: one.id, timestamp: Date().addingTimeInterval(-5), source: .phone, dose: one.defaultDose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)-        action.profileID = a.id; action.ownershipVersion = 1; action.profileLifecycleID = a.lifecycleID-        let event = try service.record(action)-        #expect(event.profileID == a.id && event.doseAmount == 1)-        #expect(two.visibleAdministrations.isEmpty)-        var forged = action; forged.profileID = b.id; forged.profileLifecycleID = b.lifecycleID-        #expect(throws: ProfileError.self) { try service.record(forged) }-        forged = action; forged.medicationID = two.id-        #expect(throws: ProfileError.self) { try service.record(forged) }-        #expect(try c.fetchCount(FetchDescriptor<Administration>()) == 1)+  private func setup() throws -> (ModelContainer, CareProfile, CareProfile) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let service = ProfileService(context: store.mainContext)+    return (+      store, try service.create(displayName: "Same name"),+      try service.create(displayName: "Same name")+    )+  }+  @Test func identicalNamesHaveIndependentDoseHistoryAndCapturedActionOwnership() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let service = MedicationService(context: context)+    let one = try service.createAsNeededMedication(+      name: "Same synthetic medicine", dose: .init(description: "", amount: 1, unit: "test"),+      profileID: firstProfile.id)+    let two = try service.createAsNeededMedication(+      name: one.name, dose: .init(description: "", amount: 2, unit: "test"), profileID: secondProfile.id)+    var action = AdministrationAction(+      eventID: UUID(), medicationID: one.id, timestamp: Date().addingTimeInterval(-5),+      source: .phone, dose: one.defaultDose, scheduleTypeAtRecording: .asNeeded,+      scheduleGenerationID: nil)+    action.profileID = firstProfile.id+    action.ownershipVersion = 1+    action.profileLifecycleID = firstProfile.lifecycleID+    let event = try service.record(action)+    #expect(event.profileID == firstProfile.id && event.doseAmount == 1)+    #expect(two.visibleAdministrations.isEmpty)+    var forged = action+    forged.profileID = secondProfile.id+    forged.profileLifecycleID = secondProfile.lifecycleID+    #expect(throws: ProfileError.self) { try service.record(forged) }+    forged = action+    forged.medicationID = two.id+    #expect(throws: ProfileError.self) { try service.record(forged) }+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 1)+  }+  @Test func crossProfilePurposeRoutineTargetsAndLegacyOwnerlessActionReject() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let purpose = try MedicationService(context: context).createPurpose(+      name: "Synthetic purpose", profileID: firstProfile.id)+    #expect(throws: ProfileError.self) {+      try MedicationService(context: context).createAsNeededMedication(+        name: "Synthetic", purpose: purpose, profileID: secondProfile.id)     }-    @Test func crossProfilePurposeRoutineTargetsAndLegacyOwnerlessActionReject() throws {-        let (store, a, b) = try setup(); let c = store.mainContext-        let purpose = try MedicationService(context: c).createPurpose(name: "Synthetic purpose", profileID: a.id)-        #expect(throws: ProfileError.self) { try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", purpose: purpose, profileID: b.id) }-        let treatment = try TreatmentService(context: c).create(name: "Synthetic", profileID: a.id)-        #expect(throws: ProfileError.self) { try RoutineService(context: c).createOrdered(name: "Synthetic", steps: [.init(kind: .treatment, targetID: treatment.id)], profileID: b.id) }-        let medication = try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", profileID: a.id)-        let legacy = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)-        #expect(throws: ProfileError.self) { try MedicationService(context: c).record(legacy) }+    let treatment = try TreatmentService(context: context).create(name: "Synthetic", profileID: firstProfile.id)+    #expect(throws: ProfileError.self) {+      try RoutineService(context: context).createOrdered(+        name: "Synthetic", steps: [.init(kind: .treatment, targetID: treatment.id)], profileID: secondProfile.id+      )     }-    @Test func archiveRestoreKeepsCareButOldActionsStayStaleAndOtherProfileWorks() throws {-        let (store, a, b) = try setup(); let c = store.mainContext-        let medication = try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", profileID: a.id)-        medication.recognitionPhotoData = Data([1,2,3]); try c.save()-        let originalLifecycle = a.lifecycleID-        let profiles = ProfileService(context: c)-        #expect(throws: RecordingError.self) { try profiles.setArchived(a, true, save: { throw RecordingError.saveFailed }) }-        #expect(a.archivedAt == nil && a.lifecycleID == originalLifecycle)-        try profiles.setArchived(a, true)-        #expect(throws: ProfileError.self) { try ProfileAccess.owner(medication, context: c) }-        let other = try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", profileID: b.id)-        #expect(try ProfileAccess.owner(other, context: c) == b.id)-        try profiles.setArchived(a, false)-        #expect(a.lifecycleID != originalLifecycle)-        #expect(medication.recognitionPhotoData == Data([1,2,3]))-        var stale = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)-        stale.profileID = a.id; stale.ownershipVersion = 1; stale.profileLifecycleID = originalLifecycle-        #expect(throws: ProfileError.self) { try MedicationService(context: c).record(stale) }-        stale.profileLifecycleID = a.lifecycleID-        #expect(try MedicationService(context: c).record(stale).profileID == a.id)+    let medication = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", profileID: firstProfile.id)+    let legacy = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch,+      dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+    #expect(throws: ProfileError.self) { try MedicationService(context: context).record(legacy) }+  }+  @Test func archiveRestoreKeepsCareButOldActionsStayStaleAndOtherProfileWorks() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let medication = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", profileID: firstProfile.id)+    medication.recognitionPhotoData = Data([1, 2, 3])+    try context.save()+    let originalLifecycle = firstProfile.lifecycleID+    let profiles = ProfileService(context: context)+    #expect(throws: RecordingError.self) {+      try profiles.setArchived(firstProfile, true, save: { throw RecordingError.saveFailed })     }+    #expect(firstProfile.archivedAt == nil && firstProfile.lifecycleID == originalLifecycle)+    try profiles.setArchived(firstProfile, true)+    #expect(throws: ProfileError.self) { try ProfileAccess.owner(medication, context: context) }+    let other = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", profileID: secondProfile.id)+    #expect(try ProfileAccess.owner(other, context: context) == secondProfile.id)+    try profiles.setArchived(firstProfile, false)+    #expect(firstProfile.lifecycleID != originalLifecycle)+    #expect(medication.recognitionPhotoData == Data([1, 2, 3]))+    var stale = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch,+      dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+    stale.profileID = firstProfile.id+    stale.ownershipVersion = 1+    stale.profileLifecycleID = originalLifecycle+    #expect(throws: ProfileError.self) { try MedicationService(context: context).record(stale) }+    stale.profileLifecycleID = firstProfile.lifecycleID+    #expect(try MedicationService(context: context).record(stale).profileID == firstProfile.id)+  } }
Meddy/MeddyTests/MeddyProfileMigrationTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyProfileMigrationTests.swift b/Meddy/MeddyTests/MeddyProfileMigrationTests.swiftindex 65a1c0a..1b62f16 100644--- a/Meddy/MeddyTests/MeddyProfileMigrationTests.swift+++ b/Meddy/MeddyTests/MeddyProfileMigrationTests.swift@@ -2,84 +2,116 @@ import Foundation import SwiftData import Testing import XCTest+ @testable import Meddy  private final class ProfileFixtureBundle: NSObject {}  @MainActor struct MeddyProfileMigrationTests {-    private func fixture(_ release: String) throws -> (ModelContainer, URL) {-        let bundle = Bundle(for: ProfileFixtureBundle.self)-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        let source = try #require(bundle.url(forResource: release, withExtension: "store"))-        let target = directory.appendingPathComponent("fixture.store")-        try FileManager.default.copyItem(at: source, to: target)-        let schema = AppEnvironment.schema-        let store = try ModelContainer(for: schema, configurations: [ModelConfiguration(schema: schema, url: target, cloudKitDatabase: .none)])-        return (store, directory)-    }-    @Test(arguments: ["4a9daaa", "0966b4a"])-    func exactReleasedStoreMigrationPreservesBytesAndIdentity(_ release: String) throws {-        let (store, directory) = try fixture(release)-        // Keep this test-owned temporary store until its container/process closes.-        _ = directory-        let context = store.mainContext-        let medication = try #require(context.fetch(FetchDescriptor<Medication>()).first)-        let run = try #require(context.fetch(FetchDescriptor<RoutineRun>()).first)-        let event = try #require(context.fetch(FetchDescriptor<Administration>()).first)-        let before = try ProfileMigration.rows(context).map { ($0.id, $0.persistentModelID) }-        #expect(before.count == 8)-        #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == nil && $0.ownershipVersion == nil })-        try ProfileMigration.bootstrap(context)-        #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == ProfileIdentity.me && $0.ownershipVersion == 1 })-        #expect(medication.recognitionPhotoData == Data([1,2,3,4]))-        #expect(medication.fixedTimesData == Data([9,8,7]))-        #expect(medication.defaultDoseAmount == 2)-        #expect(event.timestamp == Date(timeIntervalSince1970: 1700000000))-        #expect(event.isDeleted)-        #expect(event.routineRunID == run.id)-        #expect(run.definitionSnapshotData == Data("frozen synthetic bytes".utf8))-        #expect(run.stepProgressData == Data([6,5,4]))-        #expect(run.timerCheckpointData == Data([3,2,1]))-        try ProfileMigration.bootstrap(context)-        let after = try ProfileMigration.rows(context)-        #expect(after.count == before.count)-        #expect(after.allSatisfy { row in before.contains { $0.0 == row.id && $0.1 == row.persistentModelID } })-        #expect(try context.fetchCount(FetchDescriptor<CareProfile>()) == 1)-        let reopened = try ModelContainer(for: AppEnvironment.schema, configurations: [ModelConfiguration(schema: AppEnvironment.schema, url: directory.appendingPathComponent("fixture.store"), cloudKitDatabase: .none)])-        #expect(try ProfileMigration.rows(reopened.mainContext).allSatisfy { $0.profileID == ProfileIdentity.me })-    }-    @Test func failedBackfillRollsBackAndCanRetry() throws {-        let (store, _) = try fixture("0966b4a")-        let context = store.mainContext-        #expect(throws: RecordingError.self) { try ProfileMigration.bootstrap(context, save: { throw RecordingError.saveFailed }) }-        #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == nil })-        #expect(try context.fetchCount(FetchDescriptor<CareProfile>()) == 0)-        try ProfileMigration.bootstrap(context)-        #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == ProfileIdentity.me })-    }-    @Test func lateUnknownImportAndMissingCurrentOwnerNeverBecomeMe() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let c = store.mainContext-        let legacy = Medication(name: "Synthetic late import"); legacy.profileID = nil; legacy.ownershipVersion = nil-        let corrupt = Medication(name: "Synthetic malformed new writer"); corrupt.profileID = nil-        c.insert(legacy); c.insert(corrupt); try c.save()-        c.insert(CareProfile(displayName: "Synthetic dependant")); try c.save()-        try ProfileMigration.bootstrap(c)-        #expect(legacy.profileID == nil && corrupt.profileID == nil)-        #expect(throws: ProfileError.self) { try ProfileAccess.owner(legacy, context: c) }-        #expect(throws: ProfileError.self) { try ProfileAccess.action(nil, target: corrupt, context: c) }+  private func fixture(_ release: String) throws -> (ModelContainer, URL) {+    let bundle = Bundle(for: ProfileFixtureBundle.self)+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    let source = try #require(bundle.url(forResource: release, withExtension: "store"))+    let target = directory.appendingPathComponent("fixture.store")+    try FileManager.default.copyItem(at: source, to: target)+    let schema = AppEnvironment.schema+    let store = try ModelContainer(+      for: schema,+      configurations: [ModelConfiguration(schema: schema, url: target, cloudKitDatabase: .none)])+    return (store, directory)+  }+  @Test(arguments: ["4a9daaa", "0966b4a"])+  func exactReleasedStoreMigrationPreservesBytesAndIdentity(_ release: String) throws {+    let (store, directory) = try fixture(release)+    // Keep this test-owned temporary store until its container/process closes.+    _ = directory+    let context = store.mainContext+    let medication = try #require(context.fetch(FetchDescriptor<Medication>()).first)+    let run = try #require(context.fetch(FetchDescriptor<RoutineRun>()).first)+    let event = try #require(context.fetch(FetchDescriptor<Administration>()).first)+    let before = try ProfileMigration.rows(context).map { ($0.id, $0.persistentModelID) }+    #expect(before.count == 8)+    #expect(+      try ProfileMigration.rows(context).allSatisfy {+        $0.profileID == nil && $0.ownershipVersion == nil+      })+    try ProfileMigration.bootstrap(context)+    #expect(+      try ProfileMigration.rows(context).allSatisfy {+        $0.profileID == ProfileIdentity.me && $0.ownershipVersion == 1+      })+    #expect(medication.recognitionPhotoData == Data([1, 2, 3, 4]))+    #expect(medication.fixedTimesData == Data([9, 8, 7]))+    #expect(medication.defaultDoseAmount == 2)+    #expect(event.timestamp == Date(timeIntervalSince1970: 1_700_000_000))+    #expect(event.isDeleted)+    #expect(event.routineRunID == run.id)+    #expect(run.definitionSnapshotData == Data("frozen synthetic bytes".utf8))+    #expect(run.stepProgressData == Data([6, 5, 4]))+    #expect(run.timerCheckpointData == Data([3, 2, 1]))+    try ProfileMigration.bootstrap(context)+    let after = try ProfileMigration.rows(context)+    #expect(after.count == before.count)+    #expect(+      after.allSatisfy { row in before.contains { $0.0 == row.id && $0.1 == row.persistentModelID }+      })+    #expect(try context.fetchCount(FetchDescriptor<CareProfile>()) == 1)+    let reopened = try ModelContainer(+      for: AppEnvironment.schema,+      configurations: [+        ModelConfiguration(+          schema: AppEnvironment.schema, url: directory.appendingPathComponent("fixture.store"),+          cloudKitDatabase: .none)+      ])+    #expect(+      try ProfileMigration.rows(reopened.mainContext).allSatisfy {+        $0.profileID == ProfileIdentity.me+      })+  }+  @Test func failedBackfillRollsBackAndCanRetry() throws {+    let (store, _) = try fixture("0966b4a")+    let context = store.mainContext+    #expect(throws: RecordingError.self) {+      try ProfileMigration.bootstrap(context, save: { throw RecordingError.saveFailed })     }-    @Test func duplicateUUIDOrForeignGraphRejectsBeforeBackfill() throws {-        let (store, directory) = try fixture("0966b4a")-        // Keep this test-owned temporary store until its container/process closes.-        _ = directory-        let c = store.mainContext-        let original = try #require(c.fetch(FetchDescriptor<Medication>()).first)-        let duplicate = Medication(name: "Synthetic replacement"); duplicate.id = original.id-        c.insert(duplicate); try c.save()-        try ProfileMigration.bootstrap(c)-        #expect(throws: ProfileError.self) { try ProfileAccess.owner(original, context: c) }-        #expect(original.profileID == nil)+    #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == nil })+    #expect(try context.fetchCount(FetchDescriptor<CareProfile>()) == 0)+    try ProfileMigration.bootstrap(context)+    #expect(try ProfileMigration.rows(context).allSatisfy { $0.profileID == ProfileIdentity.me })+  }+  @Test func lateUnknownImportAndMissingCurrentOwnerNeverBecomeMe() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    let legacy = Medication(name: "Synthetic late import")+    legacy.profileID = nil+    legacy.ownershipVersion = nil+    let corrupt = Medication(name: "Synthetic malformed new writer")+    corrupt.profileID = nil+    context.insert(legacy)+    context.insert(corrupt)+    try context.save()+    context.insert(CareProfile(displayName: "Synthetic dependant"))+    try context.save()+    try ProfileMigration.bootstrap(context)+    #expect(legacy.profileID == nil && corrupt.profileID == nil)+    #expect(throws: ProfileError.self) { try ProfileAccess.owner(legacy, context: context) }+    #expect(throws: ProfileError.self) {+      try ProfileAccess.action(nil, target: corrupt, context: context)     }+  }+  @Test func duplicateUUIDOrForeignGraphRejectsBeforeBackfill() throws {+    let (store, directory) = try fixture("0966b4a")+    // Keep this test-owned temporary store until its container/process closes.+    _ = directory+    let context = store.mainContext+    let original = try #require(context.fetch(FetchDescriptor<Medication>()).first)+    let duplicate = Medication(name: "Synthetic replacement")+    duplicate.id = original.id+    context.insert(duplicate)+    try context.save()+    try ProfileMigration.bootstrap(context)+    #expect(throws: ProfileError.self) { try ProfileAccess.owner(original, context: context) }+    #expect(original.profileID == nil)+  } }
Meddy/MeddyTests/MeddyProfileRoutingTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyProfileRoutingTests.swift b/Meddy/MeddyTests/MeddyProfileRoutingTests.swiftindex e776510..9e6bd6b 100644--- a/Meddy/MeddyTests/MeddyProfileRoutingTests.swift+++ b/Meddy/MeddyTests/MeddyProfileRoutingTests.swift@@ -2,128 +2,206 @@ import Foundation import SwiftData import Testing import UserNotifications+ @testable import Meddy  @MainActor struct MeddyProfileRoutingTests {-    private func setup() throws -> (ModelContainer, CareProfile, CareProfile) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let profiles = ProfileService(context: store.mainContext)-        return (store, try profiles.create(displayName: "Same label"), try profiles.create(displayName: "Same label"))-    }-    @Test func allProfileRemindersRouteTakenAndSnoozeToCapturedOwner() async throws {-        let (store, a, b) = try setup(); let c = store.mainContext; let now = Date()-        let service = MedicationService(context: c)-        for owner in [ProfileIdentity.me, a.id, b.id] {-            let item = try service.createAsNeededMedication(name: "Same medicine", profileID: owner)-            try ScheduleService(context: c, now: { now }).configure(item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120), reminders: true)-        }-        let client = ProfileNotifications()-        let reminders = ReminderService(context: c, notifications: client, now: { now })-        let plans = try reminders.plan(now: now)-        #expect(Set(plans.compactMap(\.profileID)) == Set([ProfileIdentity.me,a.id,b.id]))-        #expect(Set(plans.map(\.id)).count == 3)-        let captured = try #require(plans.first { $0.profileID == a.id })-        reminders.handle(captured, action: "SNOOZE"); await reminders.waitForRefresh()-        let deferred = try #require(reminders.plan(now: now).first { $0.profileID == a.id })-        #expect(deferred.deliveryAt == now.addingTimeInterval(900))-        #expect(try c.fetchCount(FetchDescriptor<Administration>()) == 0)-        reminders.handle(deferred, action: "TAKEN"); await reminders.waitForRefresh()-        let event = try #require(c.fetch(FetchDescriptor<Administration>()).first)-        #expect(event.profileID == a.id)-        var forged = captured; forged.profileID = b.id; forged.profileLifecycleID = b.lifecycleID-        reminders.handle(forged, action: "TAKEN"); await reminders.waitForRefresh()-        #expect(try c.fetchCount(FetchDescriptor<Administration>()) == 1)+  private func setup() throws -> (ModelContainer, CareProfile, CareProfile) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let profiles = ProfileService(context: store.mainContext)+    return (+      store, try profiles.create(displayName: "Same label"),+      try profiles.create(displayName: "Same label")+    )+  }+  @Test func allProfileRemindersRouteTakenAndSnoozeToCapturedOwner() async throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let now = Date()+    let service = MedicationService(context: context)+    for owner in [ProfileIdentity.me, firstProfile.id, secondProfile.id] {+      let item = try service.createAsNeededMedication(name: "Same medicine", profileID: owner)+      try ScheduleService(context: context, now: { now }).configure(+        item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120),+        reminders: true)     }-    @Test func dailyAllowanceAndExportStayWithOneProfile() throws {-        let (store, a, b) = try setup(); let c = store.mainContext; let now = Date()-        let one = try MedicationService(context: c).createAsNeededMedication(name: "Same medicine", dose: .init(description: "", amount: 1, unit: "measure"), profileID: a.id)-        let two = try MedicationService(context: c).createAsNeededMedication(name: one.name, dose: .init(description: "", amount: 2, unit: "measure"), profileID: b.id)-        let rules = AsNeededDoseLimits(minimumIntervalSeconds: 3600, maximumAmount: 5, windowSeconds: 86400, unit: "measure")-        for item in [one,two] { try AsNeededLimitService(context: c).configure(item, limits: rules, now: now) }-        var action = AdministrationAction(eventID: UUID(), medicationID: two.id, timestamp: now.addingTimeInterval(-30), source: .phone, dose: two.defaultDose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)-        action = try ProfileAccess.stamp(action, target: two, context: c)-        _ = try MedicationService(context: c).record(action)-        let check = AsNeededLimitService(context: c).check(one, now: now)-        #expect(check.state == .withinEnteredLimits && check.remainingAmount == 5)-        #expect(!check.issues.contains { $0.contains("Another active entry") })-        let export = MedicationPresentation.consultationExport([one,two], profileID: a.id, profileLabel: a.label)-        #expect(export.markdown.contains(a.id.uuidString))-        #expect(!export.markdown.contains(b.id.uuidString))-        #expect(export.filename.contains(a.id.uuidString))+    let client = ProfileNotifications()+    let reminders = ReminderService(context: context, notifications: client, now: { now })+    let plans = try reminders.plan(now: now)+    #expect(Set(plans.compactMap(\.profileID)) == Set([ProfileIdentity.me, firstProfile.id, secondProfile.id]))+    #expect(Set(plans.map(\.id)).count == 3)+    let captured = try #require(plans.first { $0.profileID == firstProfile.id })+    reminders.handle(captured, action: "SNOOZE")+    await reminders.waitForRefresh()+    let deferred = try #require(reminders.plan(now: now).first { $0.profileID == firstProfile.id })+    #expect(deferred.deliveryAt == now.addingTimeInterval(900))+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+    reminders.handle(deferred, action: "TAKEN")+    await reminders.waitForRefresh()+    let event = try #require(context.fetch(FetchDescriptor<Administration>()).first)+    #expect(event.profileID == firstProfile.id)+    var forged = captured+    forged.profileID = secondProfile.id+    forged.profileLifecycleID = secondProfile.lifecycleID+    reminders.handle(forged, action: "TAKEN")+    await reminders.waitForRefresh()+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 1)+  }+  @Test func dailyAllowanceAndExportStayWithOneProfile() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let now = Date()+    let one = try MedicationService(context: context).createAsNeededMedication(+      name: "Same medicine", dose: .init(description: "", amount: 1, unit: "measure"),+      profileID: firstProfile.id)+    let two = try MedicationService(context: context).createAsNeededMedication(+      name: one.name, dose: .init(description: "", amount: 2, unit: "measure"), profileID: secondProfile.id)+    let rules = AsNeededDoseLimits(+      minimumIntervalSeconds: 3600, maximumAmount: 5, windowSeconds: 86400, unit: "measure")+    for item in [one, two] {+      try AsNeededLimitService(context: context).configure(item, limits: rules, now: now)     }-    @Test func malformedWatchSnapshotAndAcceptedAckPreserveActualCareOutbox() throws {-        let (store, a, b) = try setup(); let c = store.mainContext-        let medication = try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", profileID: a.id)-        let snapshot = try PhoneCompanionService(context: c).snapshot()-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        defer { try? FileManager.default.removeItem(at: directory) }-        let cache = try CompanionStore(file: directory.appendingPathComponent("outbox.json")); try cache.receive(snapshot)-        let event = try ProfileAccess.stamp(AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil), target: medication, context: c)-        let action = try ProfileAccess.stamp(CompanionAction(version: 2, id: event.eventID, deviceID: "synthetic-watch", timestamp: event.timestamp, operation: .medication(event, runID: nil, stepID: nil)), target: medication, context: c)-        try cache.enqueue(action)-        var malformed = snapshot; malformed.medications[0].profileID = b.id-        #expect(throws: ProfileError.self) { try cache.receive(malformed) }-        #expect(throws: ProfileError.self) { try cache.acknowledge(.init(actionID: action.id, accepted: true, snapshot: malformed)) }-        #expect(cache.state.pending.count == 1 && cache.state.snapshot == snapshot)-        let reopened = try CompanionStore(file: directory.appendingPathComponent("outbox.json"))-        #expect(reopened.state.pending.first == action)-        var legacy = snapshot; legacy.version = 1-        #expect(throws: ProfileError.self) { try cache.receive(legacy) }+    var action = AdministrationAction(+      eventID: UUID(), medicationID: two.id, timestamp: now.addingTimeInterval(-30), source: .phone,+      dose: two.defaultDose, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+    action = try ProfileAccess.stamp(action, target: two, context: context)+    _ = try MedicationService(context: context).record(action)+    let check = AsNeededLimitService(context: context).check(one, now: now)+    #expect(check.state == .withinEnteredLimits && check.remainingAmount == 5)+    #expect(!check.issues.contains { $0.contains("Another active entry") })+    let export = MedicationPresentation.consultationExport(+      [one, two], profileID: firstProfile.id, profileLabel: firstProfile.label)+    #expect(export.markdown.contains(firstProfile.id.uuidString))+    #expect(!export.markdown.contains(secondProfile.id.uuidString))+    #expect(export.filename.contains(firstProfile.id.uuidString))+  }+  @Test func malformedWatchSnapshotAndAcceptedAckPreserveActualCareOutbox() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let medication = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", profileID: firstProfile.id)+    let snapshot = try PhoneCompanionService(context: context).snapshot()+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    defer { try? FileManager.default.removeItem(at: directory) }+    let cache = try CompanionStore(file: directory.appendingPathComponent("outbox.json"))+    try cache.receive(snapshot)+    let event = try ProfileAccess.stamp(+      AdministrationAction(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .watch,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil),+      target: medication, context: context)+    let action = try ProfileAccess.stamp(+      CompanionAction(+        version: 2, id: event.eventID, deviceID: "synthetic-watch", timestamp: event.timestamp,+        operation: .medication(event, runID: nil, stepID: nil)), target: medication, context: context)+    try cache.enqueue(action)+    var malformed = snapshot+    malformed.medications[0].profileID = secondProfile.id+    #expect(throws: ProfileError.self) { try cache.receive(malformed) }+    #expect(throws: ProfileError.self) {+      try cache.acknowledge(.init(actionID: action.id, accepted: true, snapshot: malformed))     }-    @Test func cachedParentChildAndOperationRollbackTogetherOnFinalSaveFailure() throws {-        let (store, a, _) = try setup(); let c = store.mainContext-        let timer = try RoutineService(context: c).createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 60, profileID: a.id)-        let parent = try RoutineService(context: c).createOrdered(name: "Synthetic parent", steps: [.init(kind: .timedRoutine, targetID: timer.id)], profileID: a.id)-        let definition = try RoutineService(context: c).freeze(parent)-        let frozenTimer = try RoutineService(context: c).freeze(timer)-        func cached(_ definition: FrozenRoutineDefinition, parentID: UUID? = nil, stepID: UUID? = nil) -> CompanionRun {-            var value = CompanionRun(id: UUID(), definition: definition, progress: .init(definition: definition), timer: nil, status: .active, startedAt: Date(), revision: 0, executionDeviceID: "synthetic-watch", parentRunID: parentID, parentStepID: stepID, processedActionIDs: [], isDeleted: false)-            value.profileID = a.id; value.ownershipVersion = 1; value.profileLifecycleID = a.lifecycleID; return value-        }-        let root = cached(definition)-        let child = cached(frozenTimer, parentID: root.id, stepID: definition.steps[0].id)-        let action = try ProfileAccess.stamp(CompanionAction(version: 2, id: UUID(), deviceID: "synthetic-watch", timestamp: Date(), operation: .start(child), cachedRun: child, cachedParentRun: root), target: parent, context: c)-        let phone = PhoneCompanionService(context: c)-        #expect(throws: RecordingError.self) { try phone.apply(action, save: { throw RecordingError.saveFailed }) }-        #expect(try c.fetchCount(FetchDescriptor<RoutineRun>()) == 0)-        try phone.apply(action)-        #expect(try c.fetchCount(FetchDescriptor<RoutineRun>()) == 2)-        #expect(try c.fetch(FetchDescriptor<RoutineRun>()).allSatisfy { $0.profileID == a.id })+    #expect(cache.state.pending.count == 1 && cache.state.snapshot == snapshot)+    let reopened = try CompanionStore(file: directory.appendingPathComponent("outbox.json"))+    #expect(reopened.state.pending.first == action)+    var legacy = snapshot+    legacy.version = 1+    #expect(throws: ProfileError.self) { try cache.receive(legacy) }+  }+  @Test func cachedParentChildAndOperationRollbackTogetherOnFinalSaveFailure() throws {+    let (store, firstProfile, _) = try setup()+    let context = store.mainContext+    let timer = try RoutineService(context: context).createTimed(+      name: "Synthetic timer", rounds: 1, durationSeconds: 60, profileID: firstProfile.id)+    let parent = try RoutineService(context: context).createOrdered(+      name: "Synthetic parent", steps: [.init(kind: .timedRoutine, targetID: timer.id)],+      profileID: firstProfile.id)+    let definition = try RoutineService(context: context).freeze(parent)+    let frozenTimer = try RoutineService(context: context).freeze(timer)+    func cached(_ definition: FrozenRoutineDefinition, parentID: UUID? = nil, stepID: UUID? = nil)+      -> CompanionRun {+      var value = CompanionRun(+        id: UUID(), definition: definition, progress: .init(definition: definition), timer: nil,+        status: .active, startedAt: Date(), revision: 0, executionDeviceID: "synthetic-watch",+        parentRunID: parentID, parentStepID: stepID, processedActionIDs: [], isDeleted: false)+      value.profileID = firstProfile.id+      value.ownershipVersion = 1+      value.profileLifecycleID = firstProfile.lifecycleID+      return value     }-    @Test func dependantChildTimerAndExplicitRestoreResumeCarryFreshLifecycle() throws {-        let (store, a, _) = try setup(); let c = store.mainContext-        let timer = try RoutineService(context: c).createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 60, profileID: a.id)-        let parent = try RoutineService(context: c).createOrdered(name: "Synthetic parent", steps: [.init(kind: .timedRoutine, targetID: timer.id)], profileID: a.id)-        let sessions = RoutineSessionService(context: c); let root = try sessions.start(parent)-        let child = try sessions.beginTimedStep(root, stepID: parent.steps![0].id)-        #expect(try sessions.definition(child).profileID == a.id)-        #expect(child.profileLifecycleID == a.lifecycleID)-        let clock = ClockSample(wall: Date(), monotonic: 10, continuityID: "synthetic")-        _ = try sessions.changeTimer(child, actionID: UUID(), clock: clock, operation: .start)-        let profiles = ProfileService(context: c); try profiles.setArchived(a, true); try profiles.setArchived(a, false)-        let old = child.profileLifecycleID-        #expect(try sessions.timer(child).phase != .running)-        try sessions.resume(root, actionID: UUID())-        #expect(root.profileLifecycleID == a.lifecycleID)-        _ = try sessions.changeTimer(child, actionID: UUID(), clock: .init(wall: clock.wall.addingTimeInterval(1), monotonic: 11, continuityID: "synthetic"), operation: .resume)-        #expect(child.profileLifecycleID == a.lifecycleID && child.profileLifecycleID != old)+    let root = cached(definition)+    let child = cached(frozenTimer, parentID: root.id, stepID: definition.steps[0].id)+    let action = try ProfileAccess.stamp(+      CompanionAction(+        version: 2, id: UUID(), deviceID: "synthetic-watch", timestamp: Date(),+        operation: .start(child), cachedRun: child, cachedParentRun: root), target: parent,+      context: context)+    let phone = PhoneCompanionService(context: context)+    #expect(throws: RecordingError.self) {+      try phone.apply(action, save: { throw RecordingError.saveFailed })     }-    @Test func extraForeignTransferCannotDetachAnotherPersonsCare() throws {-        let (store, a, b) = try setup(); let c = store.mainContext-        let foreign = try MedicationService(context: c).createAsNeededMedication(name: "Synthetic", profileID: b.id)-        let source = try RoutineService(context: c).createOrdered(name: "Synthetic source", steps: [.init(kind: .medication, targetID: foreign.id)], confirmedMedicationIDs: [foreign.id], profileID: b.id)-        let target = try TreatmentService(context: c).create(name: "Synthetic treatment", profileID: a.id)-        #expect(throws: ProfileError.self) { try RoutineService(context: c).createOrdered(name: "Synthetic destination", steps: [.init(kind: .treatment, targetID: target.id)], transferredMedicationIDs: [foreign.id], archiveEmptyOwnerIDs: [source.id], profileID: a.id) }-        #expect(source.isActive && source.steps?.count == 1 && foreign.managedByRoutineID == source.id)+    #expect(try context.fetchCount(FetchDescriptor<RoutineRun>()) == 0)+    try phone.apply(action)+    #expect(try context.fetchCount(FetchDescriptor<RoutineRun>()) == 2)+    #expect(try context.fetch(FetchDescriptor<RoutineRun>()).allSatisfy { $0.profileID == firstProfile.id })+  }+  @Test func dependantChildTimerAndExplicitRestoreResumeCarryFreshLifecycle() throws {+    let (store, firstProfile, _) = try setup()+    let context = store.mainContext+    let timer = try RoutineService(context: context).createTimed(+      name: "Synthetic timer", rounds: 1, durationSeconds: 60, profileID: firstProfile.id)+    let parent = try RoutineService(context: context).createOrdered(+      name: "Synthetic parent", steps: [.init(kind: .timedRoutine, targetID: timer.id)],+      profileID: firstProfile.id)+    let sessions = RoutineSessionService(context: context)+    let root = try sessions.start(parent)+    let child = try sessions.beginTimedStep(root, stepID: parent.steps![0].id)+    #expect(try sessions.definition(child).profileID == firstProfile.id)+    #expect(child.profileLifecycleID == firstProfile.lifecycleID)+    let clock = ClockSample(wall: Date(), monotonic: 10, continuityID: "synthetic")+    _ = try sessions.changeTimer(child, actionID: UUID(), clock: clock, operation: .start)+    let profiles = ProfileService(context: context)+    try profiles.setArchived(firstProfile, true)+    try profiles.setArchived(firstProfile, false)+    let old = child.profileLifecycleID+    #expect(try sessions.timer(child).phase != .running)+    try sessions.resume(root, actionID: UUID())+    #expect(root.profileLifecycleID == firstProfile.lifecycleID)+    _ = try sessions.changeTimer(+      child, actionID: UUID(),+      clock: .init(+        wall: clock.wall.addingTimeInterval(1), monotonic: 11, continuityID: "synthetic"),+      operation: .resume)+    #expect(child.profileLifecycleID == firstProfile.lifecycleID && child.profileLifecycleID != old)+  }+  @Test func extraForeignTransferCannotDetachAnotherPersonsCare() throws {+    let (store, firstProfile, secondProfile) = try setup()+    let context = store.mainContext+    let foreign = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic", profileID: secondProfile.id)+    let source = try RoutineService(context: context).createOrdered(+      name: "Synthetic source", steps: [.init(kind: .medication, targetID: foreign.id)],+      confirmedMedicationIDs: [foreign.id], profileID: secondProfile.id)+    let target = try TreatmentService(context: context).create(+      name: "Synthetic treatment", profileID: firstProfile.id)+    #expect(throws: ProfileError.self) {+      try RoutineService(context: context).createOrdered(+        name: "Synthetic destination", steps: [.init(kind: .treatment, targetID: target.id)],+        transferredMedicationIDs: [foreign.id], archiveEmptyOwnerIDs: [source.id], profileID: firstProfile.id)     }+    #expect(source.isActive && source.steps?.count == 1 && foreign.managedByRoutineID == source.id)+  } }  @MainActor private final class ProfileNotifications: ReminderNotificationClient {-    var requests: [UNNotificationRequest] = []-    func authorization() async -> UNAuthorizationStatus { .authorized }-    func pending() async -> [UNNotificationRequest] { requests }-    func delivered() async -> [UNNotification] { [] }-    func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }-    func removeDelivered(_ ids: [String]) {}-    func add(_ request: UNNotificationRequest) async throws { requests.removeAll { $0.identifier == request.identifier }; requests.append(request) }+  var requests: [UNNotificationRequest] = []+  func authorization() async -> UNAuthorizationStatus { .authorized }+  func pending() async -> [UNNotificationRequest] { requests }+  func delivered() async -> [UNNotification] { [] }+  func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }+  func removeDelivered(_ ids: [String]) {}+  func add(_ request: UNNotificationRequest) async throws {+    requests.removeAll { $0.identifier == request.identifier }+    requests.append(request)+  } }
Meddy/MeddyTests/MeddyReminderServiceTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyReminderServiceTests.swift b/Meddy/MeddyTests/MeddyReminderServiceTests.swiftindex 95e771c..c434d53 100644--- a/Meddy/MeddyTests/MeddyReminderServiceTests.swift+++ b/Meddy/MeddyTests/MeddyReminderServiceTests.swift@@ -1,101 +1,148 @@ import Foundation import SwiftData-import UserNotifications import Testing+import UserNotifications+ @testable import Meddy  @MainActor struct MeddyReminderServiceTests {-    @Test func staleTakenKeepsDeliveredDoseAndGenerationWithoutCreditingNewSchedule() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let records = MedicationService(context: store.mainContext)-        let item = try records.createAsNeededMedication(name: "Synthetic item")-        let schedules = ScheduleService(context: store.mainContext)-        try schedules.configure(item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 0), reminders: true)-        let oldGeneration = item.scheduleGenerationID-        let dose = RecordedDoseSnapshot(description: "Synthetic delivered label", amount: nil, unit: nil)-        let event = AdministrationAction(eventID: UUID(), medicationID: item.id, timestamp: Date(), source: .notification, dose: dose, scheduleTypeAtRecording: .interval, scheduleGenerationID: oldGeneration)-        let reminder = PlannedReminder(id: "synthetic", title: "Synthetic", body: "", deliveryAt: Date(), payload: .medication(action: event))-        try schedules.configure(item, draft: .init(mode: .interval, intervalMinutes: 120, firstReminderMinute: 0), reminders: true)-        let service = ReminderService(context: store.mainContext)-        service.handle(reminder, action: "TAKEN"); service.handle(reminder, action: "TAKEN")-        #expect(service.error == nil)-        let actual = try #require(store.mainContext.fetch(FetchDescriptor<Administration>()).first)-        #expect(actual.recordedDose == dose && actual.scheduleGenerationID == oldGeneration)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-        #expect(try MedicationPresentation.result(item, context: store.mainContext).takenToday == 0)-    }-    @Test func notificationOpenReusesExactSavedOccurrenceInsteadOfStartingAnotherSession() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let routine = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])-        let schedules = ScheduleService(context: store.mainContext); try schedules.configure(routine, slots: [.init()], reminders: false)-        let date = Date()-        let occurrence = try #require(RoutineScheduleEngine().occurrences(schedules.snapshot(routine), runs: [], day: date, now: date, calendar: .current).first)-        let original = try schedules.startOccurrence(occurrence, routine: routine)-        let reminder = PlannedReminder(id: "synthetic", title: "Synthetic", body: "", deliveryAt: date, payload: .routine(occurrence: occurrence))-        let service = ReminderService(context: store.mainContext); var opened: UUID?-        service.openRun = { opened = $0.id }; service.handle(reminder, action: "OPEN")-        #expect(opened == original.id && service.error == nil)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 1)-    }-    @Test func consultationIncludesOnlyActiveMedicationOnceAndNamesRoutineOwner() throws {-        let store = try AppEnvironment.makeContainer(isolated: true); let records = MedicationService(context: store.mainContext)-        let item = try records.createAsNeededMedication(name: "Synthetic owned medicine")-        let archived = try records.createAsNeededMedication(name: "Synthetic archived medicine")-        try records.setActive(archived, false)-        let owner = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic owner", steps: [.init(kind: .medication, targetID: item.id)], confirmedMedicationIDs: [item.id])-        let text = MedicationPresentation.consultation([archived, item], routines: [owner])-        #expect(text.components(separatedBy: item.name).count == 2)-        #expect(!text.contains(archived.name) && text.contains("In Synthetic owner"))-        #expect(!text.contains("Dose not recorded"))-    }-    @Test func deniedNotificationPermissionRemovesOnlyMeddyRequestsAndDoesNotBlockRecording() async throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let records = MedicationService(context: store.mainContext); let item = try records.createAsNeededMedication(name: "Synthetic item")-        let client = SyntheticReminderNotifications(); client.status = .denied-        client.requests = [UNNotificationRequest(identifier: "meddy.old", content: UNMutableNotificationContent(), trigger: nil), UNNotificationRequest(identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)]-        let service = ReminderService(context: store.mainContext, notifications: client)-        service.refresh(); await service.waitForRefresh()-        #expect(client.removedPending == ["meddy.old"] && client.added.isEmpty)-        #expect(service.error == nil)-        _ = try records.record(.init(eventID: UUID(), medicationID: item.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-    }-    @Test func schedulingFailureIsVisibleAndRetryKeepsOneSemanticRequest() async throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        try ScheduleService(context: store.mainContext).configure(item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 0), reminders: true)-        let client = SyntheticReminderNotifications(); client.fail = true-        let service = ReminderService(context: store.mainContext, notifications: client)-        service.refresh(); await service.waitForRefresh()-        #expect(service.error != nil && client.added.isEmpty)-        client.fail = false; service.error = nil-        service.refresh(); await service.waitForRefresh()-        #expect(service.error == nil && client.added.count == 1)-        let id = try #require(client.added.first?.identifier)-        service.refresh(); await service.waitForRefresh()-        #expect(Set(client.added.map(\.identifier)) == [id])-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }+  @Test func staleTakenKeepsDeliveredDoseAndGenerationWithoutCreditingNewSchedule() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let records = MedicationService(context: store.mainContext)+    let item = try records.createAsNeededMedication(name: "Synthetic item")+    let schedules = ScheduleService(context: store.mainContext)+    try schedules.configure(+      item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 0),+      reminders: true)+    let oldGeneration = item.scheduleGenerationID+    let dose = RecordedDoseSnapshot(+      description: "Synthetic delivered label", amount: nil, unit: nil)+    let event = AdministrationAction(+      eventID: UUID(), medicationID: item.id, timestamp: Date(), source: .notification, dose: dose,+      scheduleTypeAtRecording: .interval, scheduleGenerationID: oldGeneration)+    let reminder = PlannedReminder(+      id: "synthetic", title: "Synthetic", body: "", deliveryAt: Date(),+      payload: .medication(action: event))+    try schedules.configure(+      item, draft: .init(mode: .interval, intervalMinutes: 120, firstReminderMinute: 0),+      reminders: true)+    let service = ReminderService(context: store.mainContext)+    service.handle(reminder, action: "TAKEN")+    service.handle(reminder, action: "TAKEN")+    #expect(service.error == nil)+    let actual = try #require(store.mainContext.fetch(FetchDescriptor<Administration>()).first)+    #expect(actual.recordedDose == dose && actual.scheduleGenerationID == oldGeneration)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+    #expect(try MedicationPresentation.result(item, context: store.mainContext).takenToday == 0)+  }+  @Test func notificationOpenReusesExactSavedOccurrenceInsteadOfStartingAnotherSession() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let routine = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])+    let schedules = ScheduleService(context: store.mainContext)+    try schedules.configure(routine, slots: [.init()], reminders: false)+    let date = Date()+    let occurrence = try #require(+      RoutineScheduleEngine().occurrences(+        schedules.snapshot(routine), runs: [], day: date, now: date, calendar: .current+      ).first)+    let original = try schedules.startOccurrence(occurrence, routine: routine)+    let reminder = PlannedReminder(+      id: "synthetic", title: "Synthetic", body: "", deliveryAt: date,+      payload: .routine(occurrence: occurrence))+    let service = ReminderService(context: store.mainContext)+    var opened: UUID?+    service.openRun = { opened = $0.id }+    service.handle(reminder, action: "OPEN")+    #expect(opened == original.id && service.error == nil)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 1)+  }+  @Test func consultationIncludesOnlyActiveMedicationOnceAndNamesRoutineOwner() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let records = MedicationService(context: store.mainContext)+    let item = try records.createAsNeededMedication(name: "Synthetic owned medicine")+    let archived = try records.createAsNeededMedication(name: "Synthetic archived medicine")+    try records.setActive(archived, false)+    let owner = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic owner", steps: [.init(kind: .medication, targetID: item.id)],+      confirmedMedicationIDs: [item.id])+    let text = MedicationPresentation.consultation([archived, item], routines: [owner])+    #expect(text.components(separatedBy: item.name).count == 2)+    #expect(!text.contains(archived.name) && text.contains("In Synthetic owner"))+    #expect(!text.contains("Dose not recorded"))+  }+  @Test func deniedNotificationPermissionRemovesOnlyMeddyRequestsAndDoesNotBlockRecording()+    async throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let records = MedicationService(context: store.mainContext)+    let item = try records.createAsNeededMedication(name: "Synthetic item")+    let client = SyntheticReminderNotifications()+    client.status = .denied+    client.requests = [+      UNNotificationRequest(+        identifier: "meddy.old", content: UNMutableNotificationContent(), trigger: nil),+      UNNotificationRequest(+        identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)+    ]+    let service = ReminderService(context: store.mainContext, notifications: client)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.removedPending == ["meddy.old"] && client.added.isEmpty)+    #expect(service.error == nil)+    _ = try records.record(+      .init(+        eventID: UUID(), medicationID: item.id, timestamp: Date(), source: .phone, dose: .unknown,+        scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  }+  @Test func schedulingFailureIsVisibleAndRetryKeepsOneSemanticRequest() async throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    try ScheduleService(context: store.mainContext).configure(+      item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 0),+      reminders: true)+    let client = SyntheticReminderNotifications()+    client.fail = true+    let service = ReminderService(context: store.mainContext, notifications: client)+    service.refresh()+    await service.waitForRefresh()+    #expect(service.error != nil && client.added.isEmpty)+    client.fail = false+    service.error = nil+    service.refresh()+    await service.waitForRefresh()+    #expect(service.error == nil && client.added.count == 1)+    let id = try #require(client.added.first?.identifier)+    service.refresh()+    await service.waitForRefresh()+    #expect(Set(client.added.map(\.identifier)) == [id])+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }  } - @MainActor private final class SyntheticReminderNotifications: ReminderNotificationClient {-    var status: UNAuthorizationStatus = .authorized-    var requests: [UNNotificationRequest] = []-    var added: [UNNotificationRequest] = []-    var removedPending: [String] = []-    var fail = false-    func authorization() async -> UNAuthorizationStatus { status }-    func pending() async -> [UNNotificationRequest] { requests }-    func delivered() async -> [UNNotification] { [] }-    func removePending(_ ids: [String]) { removedPending.append(contentsOf: ids); requests.removeAll { ids.contains($0.identifier) } }-    func removeDelivered(_ ids: [String]) {}-    func add(_ request: UNNotificationRequest) async throws {-        if fail { throw NSError(domain: "SyntheticNotificationFailure", code: 1) }-        added.append(request); requests.removeAll { $0.identifier == request.identifier }; requests.append(request)-    }+  var status: UNAuthorizationStatus = .authorized+  var requests: [UNNotificationRequest] = []+  var added: [UNNotificationRequest] = []+  var removedPending: [String] = []+  var fail = false+  func authorization() async -> UNAuthorizationStatus { status }+  func pending() async -> [UNNotificationRequest] { requests }+  func delivered() async -> [UNNotification] { [] }+  func removePending(_ ids: [String]) {+    removedPending.append(contentsOf: ids)+    requests.removeAll { ids.contains($0.identifier) }+  }+  func removeDelivered(_ ids: [String]) {}+  func add(_ request: UNNotificationRequest) async throws {+    if fail { throw NSError(domain: "SyntheticNotificationFailure", code: 1) }+    added.append(request)+    requests.removeAll { $0.identifier == request.identifier }+    requests.append(request)+  } }
Meddy/MeddyTests/MeddyReminderTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyReminderTests.swift b/Meddy/MeddyTests/MeddyReminderTests.swiftindex 99836ea..35e81f4 100644--- a/Meddy/MeddyTests/MeddyReminderTests.swift+++ b/Meddy/MeddyTests/MeddyReminderTests.swift@@ -1,55 +1,105 @@ import Foundation import Testing+ @testable import Meddy  struct MeddyReminderTests {-    private var calendar: Calendar { var value = Calendar(identifier: .gregorian); value.timeZone = TimeZone(secondsFromGMT: 0)!; return value }-    private let now = Date(timeIntervalSince1970: 1791201600)+  private var calendar: Calendar {+    var value = Calendar(identifier: .gregorian)+    value.timeZone = TimeZone(secondsFromGMT: 0)!+    return value+  }+  private let now = Date(timeIntervalSince1970: 1_791_201_600) -    @Test func noAsNeededOrOwnedMedicationNotificationEvenWithMalformedEnabledFlag() {-        for mode in [MedicationScheduleType.asNeeded, .routineManaged] {-            let snapshot = MedicationScheduleSnapshot(id: UUID(), mode: mode, generationID: UUID(), startedAt: now, intervalMinutes: 60, firstReminderMinute: 0)-            #expect(NotificationPlanner().medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [], now: now, calendar: calendar) == nil)-        }-    }-    @Test func overdueIntervalRetainsSameActionUUIDUntilRealAdministration() throws {-        let snapshot = MedicationScheduleSnapshot(id: UUID(), mode: .interval, generationID: UUID(), startedAt: now, intervalMinutes: 60, firstReminderMinute: 0)-        let planner = NotificationPlanner()-        let first = try #require(planner.medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [], now: now, calendar: calendar))-        let later = try #require(planner.medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [], now: now.addingTimeInterval(60), calendar: calendar))-        guard case .medication(let firstAction) = first.payload, case .medication(let laterAction) = later.payload else { Issue.record("Wrong payload"); return }-        #expect(firstAction.eventID == laterAction.eventID)-        #expect(laterAction.dose == .unknown && laterAction.scheduleGenerationID == snapshot.generationID)-        let actual = ScheduledAdministration(id: firstAction.eventID, medicationID: snapshot.id, timestamp: now, mode: .interval, generationID: snapshot.generationID)-        let next = try #require(planner.medication(snapshot, name: "Synthetic", dose: .unknown, reminders: true, active: true, administrations: [actual], now: now.addingTimeInterval(60), calendar: calendar))-        guard case .medication(let nextAction) = next.payload else { return }-        #expect(nextAction.eventID != firstAction.eventID)-        #expect(next.deliveryAt == now.addingTimeInterval(3600))-    }-    @Test func savedOrUntimedRoutineOccurrenceDoesNotNotify() {-        var occurrence = RoutineOccurrence(id: UUID(), key: "synthetic", routineID: UUID(), generationID: UUID(), slotID: UUID(), label: "Session", localDate: "2026-10-05", timeZoneID: "Etc/UTC")-        let planner = NotificationPlanner()-        #expect(planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) == nil)-        occurrence.scheduledAt = now.addingTimeInterval(60)-        #expect(planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) != nil)-        occurrence.existingRunID = occurrence.id-        #expect(planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) == nil)-    }-    @Test func onlyRunningRoundGetsNotificationNeverBetweenRoundWait() throws {-        var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 60)-        let planner = NotificationPlanner(); let runID = UUID()-        #expect(planner.timer(name: "Synthetic", runID: runID, revision: 0, checkpoint: timer, now: now) == nil)-        let clock = ClockSample(wall: now, monotonic: 10, continuityID: UUID().uuidString)-        try timer.start(at: clock)-        let reminder = try #require(planner.timer(name: "Synthetic", runID: runID, revision: 1, checkpoint: timer, now: now))-        #expect(reminder.deliveryAt == now.addingTimeInterval(60))-        _ = timer.advance(at: .init(wall: now.addingTimeInterval(60), monotonic: 70, continuityID: clock.continuityID))-        #expect(timer.phase == .waiting)-        #expect(planner.timer(name: "Synthetic", runID: runID, revision: 2, checkpoint: timer, now: now.addingTimeInterval(60)) == nil)+  @Test func noAsNeededOrOwnedMedicationNotificationEvenWithMalformedEnabledFlag() {+    for mode in [MedicationScheduleType.asNeeded, .routineManaged] {+      let snapshot = MedicationScheduleSnapshot(+        id: UUID(), mode: mode, generationID: UUID(), startedAt: now, intervalMinutes: 60,+        firstReminderMinute: 0)+      #expect(+        NotificationPlanner().medication(+          snapshot, details: MedicationReminderDetails(+            name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [], now: now, calendar: calendar) == nil)     }-    @Test func frozenReminderRoundTripsWithoutChangingDoseOrOccurrenceIdentity() throws {-        let action = AdministrationAction(eventID: UUID(), medicationID: UUID(), timestamp: now, source: .notification, dose: .init(description: "Synthetic instruction", amount: nil, unit: nil), scheduleTypeAtRecording: .fixedTimes, scheduleGenerationID: UUID())-        let reminder = PlannedReminder(id: "synthetic", title: "Synthetic", body: "", deliveryAt: now, payload: .medication(action: action))-        #expect(try JSONDecoder().decode(PlannedReminder.self, from: JSONEncoder().encode(reminder)) == reminder)+  }+  @Test func overdueIntervalRetainsSameActionUUIDUntilRealAdministration() throws {+    let snapshot = MedicationScheduleSnapshot(+      id: UUID(), mode: .interval, generationID: UUID(), startedAt: now, intervalMinutes: 60,+      firstReminderMinute: 0)+    let planner = NotificationPlanner()+    let first = try #require(+      planner.medication(+        snapshot, details: MedicationReminderDetails(name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [], now: now, calendar: calendar))+    let later = try #require(+      planner.medication(+        snapshot, details: MedicationReminderDetails(name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [], now: now.addingTimeInterval(60), calendar: calendar))+    guard case .medication(let firstAction) = first.payload,+      case .medication(let laterAction) = later.payload+    else {+      Issue.record("Wrong payload")+      return     }+    #expect(firstAction.eventID == laterAction.eventID)+    #expect(+      laterAction.dose == .unknown && laterAction.scheduleGenerationID == snapshot.generationID)+    let actual = ScheduledAdministration(+      id: firstAction.eventID, medicationID: snapshot.id, timestamp: now, mode: .interval,+      generationID: snapshot.generationID)+    let next = try #require(+      planner.medication(+        snapshot, details: MedicationReminderDetails(name: "Synthetic", dose: .unknown, reminders: true, active: true),+          administrations: [actual], now: now.addingTimeInterval(60), calendar: calendar))+    guard case .medication(let nextAction) = next.payload else { return }+    #expect(nextAction.eventID != firstAction.eventID)+    #expect(next.deliveryAt == now.addingTimeInterval(3600))+  }+  @Test func savedOrUntimedRoutineOccurrenceDoesNotNotify() {+    var occurrence = RoutineOccurrence(+      id: UUID(), key: "synthetic", routineID: UUID(), generationID: UUID(), slotID: UUID(),+      label: "Session", localDate: "2026-10-05", timeZoneID: "Etc/UTC")+    let planner = NotificationPlanner()+    #expect(+      planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) == nil)+    occurrence.scheduledAt = now.addingTimeInterval(60)+    #expect(+      planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) != nil)+    occurrence.existingRunID = occurrence.id+    #expect(+      planner.routine(name: "Synthetic", occurrence: occurrence, reminders: true, now: now) == nil)+  }+  @Test func onlyRunningRoundGetsNotificationNeverBetweenRoundWait() throws {+    var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 60)+    let planner = NotificationPlanner()+    let runID = UUID()+    #expect(+      planner.timer(name: "Synthetic", runID: runID, revision: 0, checkpoint: timer, now: now)+        == nil)+    let clock = ClockSample(wall: now, monotonic: 10, continuityID: UUID().uuidString)+    try timer.start(at: clock)+    let reminder = try #require(+      planner.timer(name: "Synthetic", runID: runID, revision: 1, checkpoint: timer, now: now))+    #expect(reminder.deliveryAt == now.addingTimeInterval(60))+    _ = timer.advance(+      at: .init(wall: now.addingTimeInterval(60), monotonic: 70, continuityID: clock.continuityID))+    #expect(timer.phase == .waiting)+    #expect(+      planner.timer(+        name: "Synthetic", runID: runID, revision: 2, checkpoint: timer,+        now: now.addingTimeInterval(60)) == nil)+  }+  @Test func frozenReminderRoundTripsWithoutChangingDoseOrOccurrenceIdentity() throws {+    let action = AdministrationAction(+      eventID: UUID(), medicationID: UUID(), timestamp: now, source: .notification,+      dose: .init(description: "Synthetic instruction", amount: nil, unit: nil),+      scheduleTypeAtRecording: .fixedTimes, scheduleGenerationID: UUID())+    let reminder = PlannedReminder(+      id: "synthetic", title: "Synthetic", body: "", deliveryAt: now,+      payload: .medication(action: action))+    #expect(+      try JSONDecoder().decode(PlannedReminder.self, from: JSONEncoder().encode(reminder))+        == reminder)+  } }
Meddy/MeddyTests/MeddyScheduleServiceTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyScheduleServiceTests.swift b/Meddy/MeddyTests/MeddyScheduleServiceTests.swiftindex 6e0e75d..0f1e6f9 100644--- a/Meddy/MeddyTests/MeddyScheduleServiceTests.swift+++ b/Meddy/MeddyTests/MeddyScheduleServiceTests.swift@@ -1,73 +1,100 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyScheduleServiceTests {-    private var calendar: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(secondsFromGMT: 0)!; return c }-    private func fixture() throws -> (ModelContainer, Routine) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")-        let group = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])-        return (store, group)-    }-    @Test func initialSlotsAreAvailableTodayAndFrequencyEditActivatesExactlyOnceTomorrow() throws {-        let (store, group) = try fixture()-        let now = Date(timeIntervalSince1970: 1791201600)-        let initial = ScheduleService(context: store.mainContext, now: { now }, calendar: calendar)-        let slot = DailyRoutineSlot()-        try initial.configure(group, slots: [slot], reminders: false)-        let oldGeneration = group.scheduleGenerationID-        try initial.configure(group, slots: [slot, .init()], reminders: false)-        #expect(group.scheduleGenerationID == oldGeneration)-        #expect(try initial.snapshot(group).current?.slots.count == 1)-        #expect(try initial.snapshot(group).pending?.configuration.slots.count == 2)-        #expect(try initial.activatePending(group) == false)-        let tomorrow = ScheduleService(context: store.mainContext, now: { now.addingTimeInterval(86400) }, calendar: calendar)-        #expect(try tomorrow.activatePending(group))-        let newGeneration = group.scheduleGenerationID-        #expect(newGeneration != oldGeneration && group.pendingScheduleData == nil)-        #expect(try tomorrow.activatePending(group) == false)-        #expect(group.scheduleGenerationID == newGeneration)-    }+  private var calendar: Calendar {+    var localCalendar = Calendar(identifier: .gregorian)+    localCalendar.timeZone = TimeZone(secondsFromGMT: 0)!+    return localCalendar+  }+  private func fixture() throws -> (ModelContainer, Routine) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic care")+    let group = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic group", steps: [.init(kind: .treatment, targetID: care.id)])+    return (store, group)+  }+  @Test func initialSlotsAreAvailableTodayAndFrequencyEditActivatesExactlyOnceTomorrow() throws {+    let (store, group) = try fixture()+    let now = Date(timeIntervalSince1970: 1_791_201_600)+    let initial = ScheduleService(context: store.mainContext, now: { now }, calendar: calendar)+    let slot = DailyRoutineSlot()+    try initial.configure(group, slots: [slot], reminders: false)+    let oldGeneration = group.scheduleGenerationID+    try initial.configure(group, slots: [slot, .init()], reminders: false)+    #expect(group.scheduleGenerationID == oldGeneration)+    #expect(try initial.snapshot(group).current?.slots.count == 1)+    #expect(try initial.snapshot(group).pending?.configuration.slots.count == 2)+    #expect(try initial.activatePending(group) == false)+    let tomorrow = ScheduleService(+      context: store.mainContext, now: { now.addingTimeInterval(86400) }, calendar: calendar)+    #expect(try tomorrow.activatePending(group))+    let newGeneration = group.scheduleGenerationID+    #expect(newGeneration != oldGeneration && group.pendingScheduleData == nil)+    #expect(try tomorrow.activatePending(group) == false)+    #expect(group.scheduleGenerationID == newGeneration)+  } -    @Test func timeEditKeepsGenerationAndRepresentedUntimedOccurrence() throws {-        let (store, group) = try fixture()-        let now = Date(); let service = ScheduleService(context: store.mainContext, now: { now }, calendar: calendar)-        var slot = DailyRoutineSlot()-        try service.configure(group, slots: [slot], reminders: false)-        let generation = group.scheduleGenerationID-        let occurrence = try #require(RoutineScheduleEngine().occurrences(service.snapshot(group), runs: [], day: now, now: now, calendar: calendar).first)-        let run = try service.startOccurrence(occurrence, routine: group)-        slot.minuteOfDay = 1200; slot.label = "User label"-        try service.configure(group, slots: [slot], reminders: true)-        #expect(group.scheduleGenerationID == generation)-        #expect(run.scheduledAt == nil && run.slotID == slot.id)-        #expect(run.id == occurrence.id)-    }+  @Test func timeEditKeepsGenerationAndRepresentedUntimedOccurrence() throws {+    let (store, group) = try fixture()+    let now = Date()+    let service = ScheduleService(context: store.mainContext, now: { now }, calendar: calendar)+    var slot = DailyRoutineSlot()+    try service.configure(group, slots: [slot], reminders: false)+    let generation = group.scheduleGenerationID+    let occurrence = try #require(+      RoutineScheduleEngine().occurrences(+        service.snapshot(group), runs: [], day: now, now: now, calendar: calendar+      ).first)+    let run = try service.startOccurrence(occurrence, routine: group)+    slot.minuteOfDay = 1200+    slot.label = "User label"+    try service.configure(group, slots: [slot], reminders: true)+    #expect(group.scheduleGenerationID == generation)+    #expect(run.scheduledAt == nil && run.slotID == slot.id)+    #expect(run.id == occurrence.id)+  } -    @Test func untimedReminderAndInvalidFieldsAreRejectedWithoutMutation() throws {-        let (store, group) = try fixture()-        let service = ScheduleService(context: store.mainContext)-        #expect(throws: DefinitionError.invalidSchedule) { try service.configure(group, slots: [.init()], reminders: true) }-        #expect(group.scheduleGenerationID == nil && !group.remindersEnabled)-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        #expect(throws: DefinitionError.invalidSchedule) { try service.configure(medication, draft: .init(mode: .spreadThroughDay, dosesPerDay: 4, dayStartMinute: 1300, dayEndMinute: 420), reminders: false) }-        #expect(medication.scheduleGenerationID == nil)+  @Test func untimedReminderAndInvalidFieldsAreRejectedWithoutMutation() throws {+    let (store, group) = try fixture()+    let service = ScheduleService(context: store.mainContext)+    #expect(throws: DefinitionError.invalidSchedule) {+      try service.configure(group, slots: [.init()], reminders: true)     }--    @Test func medicationConfigStartsNewGenerationAndNeverReclassifiesOldLog() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let records = MedicationService(context: store.mainContext)-        let medication = try records.createAsNeededMedication(name: "Synthetic item")-        let event = try records.record(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        let service = ScheduleService(context: store.mainContext)-        try service.configure(medication, draft: .init(mode: .fixedTimes, fixedMinutes: [480, 1200]), reminders: false)-        let generation = medication.scheduleGenerationID-        try service.configure(medication, draft: .init(mode: .interval, intervalMinutes: 360, firstReminderMinute: 480), reminders: false)-        #expect(medication.scheduleGenerationID != generation && medication.fixedTimesData == nil)-        #expect(event.scheduleTypeAtRecordingRaw == "asNeeded" && event.scheduleGenerationID == nil)-        #expect(!medication.remindersEnabled)+    #expect(group.scheduleGenerationID == nil && !group.remindersEnabled)+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    #expect(throws: DefinitionError.invalidSchedule) {+      try service.configure(+        medication,+        draft: .init(+          mode: .spreadThroughDay, dosesPerDay: 4, dayStartMinute: 1300, dayEndMinute: 420),+        reminders: false)     }+    #expect(medication.scheduleGenerationID == nil)+  }++  @Test func medicationConfigStartsNewGenerationAndNeverReclassifiesOldLog() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let records = MedicationService(context: store.mainContext)+    let medication = try records.createAsNeededMedication(name: "Synthetic item")+    let event = try records.record(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    let service = ScheduleService(context: store.mainContext)+    try service.configure(+      medication, draft: .init(mode: .fixedTimes, fixedMinutes: [480, 1200]), reminders: false)+    let generation = medication.scheduleGenerationID+    try service.configure(+      medication, draft: .init(mode: .interval, intervalMinutes: 360, firstReminderMinute: 480),+      reminders: false)+    #expect(medication.scheduleGenerationID != generation && medication.fixedTimesData == nil)+    #expect(event.scheduleTypeAtRecordingRaw == "asNeeded" && event.scheduleGenerationID == nil)+    #expect(!medication.remindersEnabled)+  } }
Meddy/MeddyTests/MeddyScheduleTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyScheduleTests.swift b/Meddy/MeddyTests/MeddyScheduleTests.swiftindex e7af79e..e93f3a1 100644--- a/Meddy/MeddyTests/MeddyScheduleTests.swift+++ b/Meddy/MeddyTests/MeddyScheduleTests.swift@@ -1,123 +1,191 @@ import Foundation import Testing+ @testable import Meddy  struct MeddyScheduleTests {-    private var calendar: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(secondsFromGMT: 0)!; return c }-    private func date(_ time: String) -> Date { ISO8601DateFormatter().date(from: "2026-10-05T\(time):00Z")! }-    private func medication(_ mode: MedicationScheduleType = .spreadThroughDay) -> MedicationScheduleSnapshot {-        .init(id: UUID(), mode: mode, generationID: UUID(), startedAt: date("00:00"), dosesPerDay: 4, dayStartMinute: 420, dayEndMinute: 1350)-    }-    private func administration(_ medication: MedicationScheduleSnapshot, _ time: String) -> ScheduledAdministration {-        .init(id: UUID(), medicationID: medication.id, timestamp: date(time), mode: medication.mode, generationID: medication.generationID)-    }+  private var calendar: Calendar {+    var localCalendar = Calendar(identifier: .gregorian)+    localCalendar.timeZone = TimeZone(secondsFromGMT: 0)!+    return localCalendar+  }+  private func date(_ time: String) -> Date {+    ISO8601DateFormatter().date(from: "2026-10-05T\(time):00Z")!+  }+  private func medication(_ mode: MedicationScheduleType = .spreadThroughDay)+    -> MedicationScheduleSnapshot {+    .init(+      id: UUID(), mode: mode, generationID: UUID(), startedAt: date("00:00"), dosesPerDay: 4,+      dayStartMinute: 420, dayEndMinute: 1350)+  }+  private func administration(_ medication: MedicationScheduleSnapshot, _ time: String)+    -> ScheduledAdministration {+    .init(+      id: UUID(), medicationID: medication.id, timestamp: date(time), mode: medication.mode,+      generationID: medication.generationID)+  } -    @Test func spreadExamplesUseRemainingActualDoses() {-        let medication = medication(); let engine = MedicationScheduleEngine()-        let first = engine.evaluate(medication, administrations: [administration(medication, "07:30")], now: date("07:30"), calendar: calendar)-        let late = engine.evaluate(medication, administrations: [administration(medication, "09:00")], now: date("09:00"), calendar: calendar)-        #expect(first.next == date("12:30") && first.remainingToday == 3)-        #expect(late.next == date("13:30") && late.remainingToday == 3)-    }+  @Test func spreadExamplesUseRemainingActualDoses() {+    let medication = medication()+    let engine = MedicationScheduleEngine()+    let first = engine.evaluate(+      medication, administrations: [administration(medication, "07:30")], now: date("07:30"),+      calendar: calendar)+    let late = engine.evaluate(+      medication, administrations: [administration(medication, "09:00")], now: date("09:00"),+      calendar: calendar)+    #expect(first.next == date("12:30") && first.remainingToday == 3)+    #expect(late.next == date("13:30") && late.remainingToday == 3)+  } -    @Test func minimumIntervalIsNeverCompressedIntoImpossibleWindow() {-        var medication = medication(); medication.minimumIntervalMinutes = 360-        let result = MedicationScheduleEngine().evaluate(medication, administrations: [administration(medication, "21:00")], now: date("21:00"), calendar: calendar)-        #expect(result.next == nil && result.cannotFitInWindow && result.remainingToday == 3)-    }+  @Test func minimumIntervalIsNeverCompressedIntoImpossibleWindow() {+    var medication = medication()+    medication.minimumIntervalMinutes = 360+    let result = MedicationScheduleEngine().evaluate(+      medication, administrations: [administration(medication, "21:00")], now: date("21:00"),+      calendar: calendar)+    #expect(result.next == nil && result.cannotFitInWindow && result.remainingToday == 3)+  } -    @Test func spreadResetsNextDayAndNoHistoryIsDueNow() {-        let medication = medication(); let engine = MedicationScheduleEngine()-        let initial = engine.evaluate(medication, administrations: [], now: date("09:00"), calendar: calendar)-        #expect(initial.next == date("09:00"))-        let history = ["07:00", "12:00", "17:00", "22:00"].map { administration(medication, $0) }-        let done = engine.evaluate(medication, administrations: history, now: date("22:00"), calendar: calendar)-        #expect(done.remainingToday == 0)-        #expect(done.next == date("07:00").addingTimeInterval(86400))-    }+  @Test func spreadResetsNextDayAndNoHistoryIsDueNow() {+    let medication = medication()+    let engine = MedicationScheduleEngine()+    let initial = engine.evaluate(+      medication, administrations: [], now: date("09:00"), calendar: calendar)+    #expect(initial.next == date("09:00"))+    let history = ["07:00", "12:00", "17:00", "22:00"].map { administration(medication, $0) }+    let done = engine.evaluate(+      medication, administrations: history, now: date("22:00"), calendar: calendar)+    #expect(done.remainingToday == 0)+    #expect(done.next == date("07:00").addingTimeInterval(86400))+  } -    @Test func wrongModeGenerationLinkedDeletedAndFutureClockHistoryCannotConsumeSchedule() {-        let medication = medication(); var values = (0..<6).map { _ in administration(medication, "07:30") }-        values[0].mode = .asNeeded; values[1].mode = .routineManaged; values[2].generationID = UUID()-        values[3].routineRunID = UUID(); values[4].isDeleted = true; values[5].hasClockMismatch = true-        let result = MedicationScheduleEngine().evaluate(medication, administrations: values, now: date("07:30"), calendar: calendar)-        #expect(result.takenToday == 0 && result.remainingToday == 4)-    }+  @Test func wrongModeGenerationLinkedDeletedAndFutureClockHistoryCannotConsumeSchedule() {+    let medication = medication()+    var values = (0..<6).map { _ in administration(medication, "07:30") }+    values[0].mode = .asNeeded+    values[1].mode = .routineManaged+    values[2].generationID = UUID()+    values[3].routineRunID = UUID()+    values[4].isDeleted = true+    values[5].hasClockMismatch = true+    let result = MedicationScheduleEngine().evaluate(+      medication, administrations: values, now: date("07:30"), calendar: calendar)+    #expect(result.takenToday == 0 && result.remainingToday == 4)+  } -    @Test func asNeededAndRoutineManagedHaveNoDueOrDailyTarget() {-        for mode in [MedicationScheduleType.asNeeded, .routineManaged] {-            let medication = medication(mode)-            let result = MedicationScheduleEngine().evaluate(medication, administrations: [administration(medication, "07:30")], now: date("08:00"), calendar: calendar)-            #expect(result.next == nil && result.remainingToday == nil)-        }+  @Test func asNeededAndRoutineManagedHaveNoDueOrDailyTarget() {+    for mode in [MedicationScheduleType.asNeeded, .routineManaged] {+      let medication = medication(mode)+      let result = MedicationScheduleEngine().evaluate(+        medication, administrations: [administration(medication, "07:30")], now: date("08:00"),+        calendar: calendar)+      #expect(result.next == nil && result.remainingToday == nil)     }+  } -    @Test func intervalCrossesMidnightWithoutDayWindow() {-        var medication = medication(.interval); medication.intervalMinutes = 360-        let result = MedicationScheduleEngine().evaluate(medication, administrations: [administration(medication, "23:00")], now: date("23:00"), calendar: calendar)-        #expect(result.next == date("05:00").addingTimeInterval(86400))-    }+  @Test func intervalCrossesMidnightWithoutDayWindow() {+    var medication = medication(.interval)+    medication.intervalMinutes = 360+    let result = MedicationScheduleEngine().evaluate(+      medication, administrations: [administration(medication, "23:00")], now: date("23:00"),+      calendar: calendar)+    #expect(result.next == date("05:00").addingTimeInterval(86400))+  } -    @Test func fixedActivationAt14Excludes08AndDoesNotShift20() {-        var medication = medication(.fixedTimes); medication.startedAt = date("14:00"); medication.fixedMinutes = [480, 1200]-        let engine = MedicationScheduleEngine()-        #expect(engine.evaluate(medication, administrations: [], now: date("14:00"), calendar: calendar).next == date("20:00"))-        let taken = engine.evaluate(medication, administrations: [administration(medication, "16:00")], now: date("16:00"), calendar: calendar)-        #expect(taken.next == date("08:00").addingTimeInterval(86400))-    }+  @Test func fixedActivationAt14Excludes08AndDoesNotShift20() {+    var medication = medication(.fixedTimes)+    medication.startedAt = date("14:00")+    medication.fixedMinutes = [480, 1200]+    let engine = MedicationScheduleEngine()+    #expect(+      engine.evaluate(medication, administrations: [], now: date("14:00"), calendar: calendar).next+        == date("20:00"))+    let taken = engine.evaluate(+      medication, administrations: [administration(medication, "16:00")], now: date("16:00"),+      calendar: calendar)+    #expect(taken.next == date("08:00").addingTimeInterval(86400))+  } -    @Test func fixedLateDoseConsumesEarliestOccurrenceWithoutShiftingNext() {-        var medication = medication(.fixedTimes); medication.fixedMinutes = [480, 1200]-        let result = MedicationScheduleEngine().evaluate(medication, administrations: [administration(medication, "11:00")], now: date("11:00"), calendar: calendar)-        #expect(result.next == date("20:00"))-    }+  @Test func fixedLateDoseConsumesEarliestOccurrenceWithoutShiftingNext() {+    var medication = medication(.fixedTimes)+    medication.fixedMinutes = [480, 1200]+    let result = MedicationScheduleEngine().evaluate(+      medication, administrations: [administration(medication, "11:00")], now: date("11:00"),+      calendar: calendar)+    #expect(result.next == date("20:00"))+  } -    @Test func twoUntimedSlotsAreIndependentStableAndNotDue() {-        let slots = [DailyRoutineSlot(), DailyRoutineSlot()]-        let schedule = RoutineScheduleSnapshot(routineID: UUID(), current: .init(generationID: UUID(), startedAt: date("14:00"), slots: slots), remindersEnabled: false)-        let engine = RoutineScheduleEngine()-        let first = engine.occurrences(schedule, runs: [], day: date("14:00"), now: date("14:00"), calendar: calendar)-        let second = engine.occurrences(schedule, runs: [], day: date("20:00"), now: date("20:00"), calendar: calendar)-        #expect(first.count == 2 && Set(first.map(\.id)).count == 2)-        #expect(first.map(\.id) == second.map(\.id))-        #expect(first.map(\.label) == ["Session 1", "Session 2"])-        #expect(first.allSatisfy { $0.scheduledAt == nil && !$0.canRemind })-    }+  @Test func twoUntimedSlotsAreIndependentStableAndNotDue() {+    let slots = [DailyRoutineSlot(), DailyRoutineSlot()]+    let schedule = RoutineScheduleSnapshot(+      routineID: UUID(),+      current: .init(generationID: UUID(), startedAt: date("14:00"), slots: slots),+      remindersEnabled: false)+    let engine = RoutineScheduleEngine()+    let first = engine.occurrences(+      schedule, runs: [], day: date("14:00"), now: date("14:00"), calendar: calendar)+    let second = engine.occurrences(+      schedule, runs: [], day: date("20:00"), now: date("20:00"), calendar: calendar)+    #expect(first.count == 2 && Set(first.map(\.id)).count == 2)+    #expect(first.map(\.id) == second.map(\.id))+    #expect(first.map(\.label) == ["Session 1", "Session 2"])+    #expect(first.allSatisfy { $0.scheduledAt == nil && !$0.canRemind })+  } -    @Test func timedActivationExcludesPastSlotAndSavedUntimedRunSurvivesTimeEditAndTravel() {-        let slots = [DailyRoutineSlot(minuteOfDay: 480), DailyRoutineSlot()]-        var schedule = RoutineScheduleSnapshot(routineID: UUID(), current: .init(generationID: UUID(), startedAt: date("14:00"), slots: slots))-        let engine = RoutineScheduleEngine()-        let initial = engine.occurrences(schedule, runs: [], day: date("14:00"), now: date("14:00"), calendar: calendar)-        #expect(initial.count == 1)-        let occurrence = initial[0]-        let run = ScheduledRunSnapshot(id: occurrence.id, routineID: schedule.routineID, occurrenceKey: occurrence.key, slotID: occurrence.slotID, localDate: occurrence.localDate, timeZoneID: "UTC", scheduledAt: nil, status: .paused)-        schedule.current?.slots[1].minuteOfDay = 1200-        var travelled = calendar; travelled.timeZone = TimeZone(secondsFromGMT: 3600)!-        let after = engine.occurrences(schedule, runs: [run], day: date("14:00"), now: date("14:00"), calendar: travelled)-        let saved = after.first { $0.id == run.id }-        #expect(saved?.scheduledAt == nil && saved?.timeZoneID == "UTC" && saved?.status == .paused)-    }+  @Test func timedActivationExcludesPastSlotAndSavedUntimedRunSurvivesTimeEditAndTravel() {+    let slots = [DailyRoutineSlot(minuteOfDay: 480), DailyRoutineSlot()]+    var schedule = RoutineScheduleSnapshot(+      routineID: UUID(),+      current: .init(generationID: UUID(), startedAt: date("14:00"), slots: slots))+    let engine = RoutineScheduleEngine()+    let initial = engine.occurrences(+      schedule, runs: [], day: date("14:00"), now: date("14:00"), calendar: calendar)+    #expect(initial.count == 1)+    let occurrence = initial[0]+    let run = ScheduledRunSnapshot(+      id: occurrence.id, routineID: schedule.routineID, occurrenceKey: occurrence.key,+      slotID: occurrence.slotID, localDate: occurrence.localDate, timeZoneID: "UTC",+      scheduledAt: nil, status: .paused)+    schedule.current?.slots[1].minuteOfDay = 1200+    var travelled = calendar+    travelled.timeZone = TimeZone(secondsFromGMT: 3600)!+    let after = engine.occurrences(+      schedule, runs: [run], day: date("14:00"), now: date("14:00"), calendar: travelled)+    let saved = after.first { $0.id == run.id }+    #expect(saved?.scheduledAt == nil && saved?.timeZoneID == "UTC" && saved?.status == .paused)+  } -    @Test func pendingFrequencyStartsOnlyAtNextLocalDayBoundary() {-        let current = RoutineScheduleConfiguration(generationID: UUID(), startedAt: date("00:00"), slots: [.init()])-        let pending = PendingRoutineSchedule(configuration: .init(generationID: UUID(), startedAt: date("00:00").addingTimeInterval(86400), slots: [.init(), .init()]), effectiveAt: date("00:00").addingTimeInterval(86400), timeZoneID: "UTC")-        let schedule = RoutineScheduleSnapshot(routineID: UUID(), current: current, pending: pending)-        let engine = RoutineScheduleEngine()-        #expect(engine.occurrences(schedule, runs: [], day: date("20:00"), now: date("20:00"), calendar: calendar).count == 1)-        let tomorrow = date("10:00").addingTimeInterval(86400)-        #expect(engine.occurrences(schedule, runs: [], day: tomorrow, now: tomorrow, calendar: calendar).count == 2)-    }+  @Test func pendingFrequencyStartsOnlyAtNextLocalDayBoundary() {+    let current = RoutineScheduleConfiguration(+      generationID: UUID(), startedAt: date("00:00"), slots: [.init()])+    let pending = PendingRoutineSchedule(+      configuration: .init(+        generationID: UUID(), startedAt: date("00:00").addingTimeInterval(86400),+        slots: [.init(), .init()]), effectiveAt: date("00:00").addingTimeInterval(86400),+      timeZoneID: "UTC")+    let schedule = RoutineScheduleSnapshot(routineID: UUID(), current: current, pending: pending)+    let engine = RoutineScheduleEngine()+    #expect(+      engine.occurrences(+        schedule, runs: [], day: date("20:00"), now: date("20:00"), calendar: calendar+      ).count == 1)+    let tomorrow = date("10:00").addingTimeInterval(86400)+    #expect(+      engine.occurrences(schedule, runs: [], day: tomorrow, now: tomorrow, calendar: calendar).count+        == 2)+  } -    @Test func daylightSavingSkippedAndRepeatedTimesResolveOneOccurrence() {-        var zoneCalendar = calendar; zoneCalendar.timeZone = TimeZone(identifier: "America/New_York")!-        let formatter = ISO8601DateFormatter()-        let spring = formatter.date(from: "2026-03-08T12:00:00Z")!-        // The repeated 01:30 belongs to the prior logical day, ending at 02:00.-        let fall = formatter.date(from: "2026-11-01T05:59:00Z")!-        let skipped = ScheduleCalendar.time(150, on: spring, calendar: zoneCalendar)-        let repeated = ScheduleCalendar.time(90, on: fall, calendar: zoneCalendar)-        #expect(skipped == formatter.date(from: "2026-03-08T07:00:00Z"))-        #expect(repeated == formatter.date(from: "2026-11-01T05:30:00Z"))-    }+  @Test func daylightSavingSkippedAndRepeatedTimesResolveOneOccurrence() {+    var zoneCalendar = calendar+    zoneCalendar.timeZone = TimeZone(identifier: "America/New_York")!+    let formatter = ISO8601DateFormatter()+    let spring = formatter.date(from: "2026-03-08T12:00:00Z")!+    // The repeated 01:30 belongs to the prior logical day, ending at 02:00.+    let fall = formatter.date(from: "2026-11-01T05:59:00Z")!+    let skipped = ScheduleCalendar.time(150, on: spring, calendar: zoneCalendar)+    let repeated = ScheduleCalendar.time(90, on: fall, calendar: zoneCalendar)+    #expect(skipped == formatter.date(from: "2026-03-08T07:00:00Z"))+    #expect(repeated == formatter.date(from: "2026-11-01T05:30:00Z"))+  } }
Meddy/MeddyTests/MeddySchemaTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddySchemaTests.swift b/Meddy/MeddyTests/MeddySchemaTests.swiftindex 8331f30..9d4bb70 100644--- a/Meddy/MeddyTests/MeddySchemaTests.swift+++ b/Meddy/MeddyTests/MeddySchemaTests.swift@@ -1,78 +1,84 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddySchemaTests {-    private func container() throws -> ModelContainer {-        let schema = AppEnvironment.schema-        return try ModelContainer(for: schema, configurations: [-            ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)-        ])-    }+  private func container() throws -> ModelContainer {+    let schema = AppEnvironment.schema+    return try ModelContainer(+      for: schema,+      configurations: [+        ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+      ])+  } -    @Test func treatmentAndTimedRoutineAreDistinctAndKeepPurpose() throws {-        let store = try container()-        let purpose = Purpose(name: "Synthetic grouping")-        let treatment = Treatment(name: "Synthetic untimed item")-        treatment.purpose = purpose-        let timed = Routine(name: "Synthetic timer", kind: .timedRounds)-        timed.roundCount = 2-        timed.roundDurationSeconds = 15-        timed.purpose = purpose-        store.mainContext.insert(purpose)-        store.mainContext.insert(treatment)-        store.mainContext.insert(timed)-        try store.mainContext.save()-        #expect(treatment.purpose?.id == purpose.id)-        #expect(purpose.treatments?.contains(where: { $0.id == treatment.id }) == true)-        #expect(purpose.routines?.contains(where: { $0.id == timed.id }) == true)-        #expect(timed.kindRaw == RoutineKind.timedRounds.rawValue)-        #expect(timed.dailySlotsData == nil)-        #expect(timed.scheduleGenerationID == nil)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Medication>()) == 0)-    }+  @Test func treatmentAndTimedRoutineAreDistinctAndKeepPurpose() throws {+    let store = try container()+    let purpose = Purpose(name: "Synthetic grouping")+    let treatment = Treatment(name: "Synthetic untimed item")+    treatment.purpose = purpose+    let timed = Routine(name: "Synthetic timer", kind: .timedRounds)+    timed.roundCount = 2+    timed.roundDurationSeconds = 15+    timed.purpose = purpose+    store.mainContext.insert(purpose)+    store.mainContext.insert(treatment)+    store.mainContext.insert(timed)+    try store.mainContext.save()+    #expect(treatment.purpose?.id == purpose.id)+    #expect(purpose.treatments?.contains(where: { $0.id == treatment.id }) == true)+    #expect(purpose.routines?.contains(where: { $0.id == timed.id }) == true)+    #expect(timed.kindRaw == RoutineKind.timedRounds.rawValue)+    #expect(timed.dailySlotsData == nil)+    #expect(timed.scheduleGenerationID == nil)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Medication>()) == 0)+  } -    @Test func canonicalLinksAndCheckpointBytesPersistWithoutExtraDose() throws {-        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-        defer { try? FileManager.default.removeItem(at: directory) }-        let schema = AppEnvironment.schema-        let configuration = ModelConfiguration(schema: schema, url: directory.appendingPathComponent("schema.store"), cloudKitDatabase: .none)-        let routineID = UUID()-        let runID = UUID()-        let stepID = UUID()-        let snapshot = Data("synthetic frozen plan".utf8)-        do {-            let store = try ModelContainer(for: schema, configurations: [configuration])-            let group = Routine(name: "Synthetic group", kind: .ordered)-            group.id = routineID-            let treatment = Treatment(name: "Synthetic untimed item")-            let step = RoutineStep(routine: group, targetKind: .treatment, targetID: treatment.id, position: 0)-            step.id = stepID-            let run = RoutineRun(routine: group, runID: runID)-            run.definitionSnapshotData = snapshot-            run.stepProgressData = Data("synthetic progress".utf8)-            let completion = TreatmentCompletion(treatment: treatment, timestamp: Date(), source: .phone)-            completion.routineRunID = runID-            completion.routineStepID = stepID-            completion.isDeleted = true-            for model in [group as any PersistentModel, treatment, step, run, completion] {-                store.mainContext.insert(model)-            }-            try store.mainContext.save()-        }-        let reopened = try ModelContainer(for: schema, configurations: [configuration])-        let runs = try reopened.mainContext.fetch(FetchDescriptor<RoutineRun>())-        let completions = try reopened.mainContext.fetch(FetchDescriptor<TreatmentCompletion>())-        #expect(runs.count == 1)-        #expect(runs.first?.id == runID)-        #expect(runs.first?.definitionSnapshotData == snapshot)-        #expect(runs.first?.routine?.id == routineID)-        #expect(completions.first?.routineRunID == runID)-        #expect(completions.first?.routineStepID == stepID)-        #expect(completions.first?.isDeleted == true)-        #expect(try reopened.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  @Test func canonicalLinksAndCheckpointBytesPersistWithoutExtraDose() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let schema = AppEnvironment.schema+    let configuration = ModelConfiguration(+      schema: schema, url: directory.appendingPathComponent("schema.store"), cloudKitDatabase: .none+    )+    let routineID = UUID()+    let runID = UUID()+    let stepID = UUID()+    let snapshot = Data("synthetic frozen plan".utf8)+    do {+      let store = try ModelContainer(for: schema, configurations: [configuration])+      let group = Routine(name: "Synthetic group", kind: .ordered)+      group.id = routineID+      let treatment = Treatment(name: "Synthetic untimed item")+      let step = RoutineStep(+        routine: group, targetKind: .treatment, targetID: treatment.id, position: 0)+      step.id = stepID+      let run = RoutineRun(routine: group, runID: runID)+      run.definitionSnapshotData = snapshot+      run.stepProgressData = Data("synthetic progress".utf8)+      let completion = TreatmentCompletion(treatment: treatment, timestamp: Date(), source: .phone)+      completion.routineRunID = runID+      completion.routineStepID = stepID+      completion.isDeleted = true+      for model in [group as any PersistentModel, treatment, step, run, completion] {+        store.mainContext.insert(model)+      }+      try store.mainContext.save()     }+    let reopened = try ModelContainer(for: schema, configurations: [configuration])+    let runs = try reopened.mainContext.fetch(FetchDescriptor<RoutineRun>())+    let completions = try reopened.mainContext.fetch(FetchDescriptor<TreatmentCompletion>())+    #expect(runs.count == 1)+    #expect(runs.first?.id == runID)+    #expect(runs.first?.definitionSnapshotData == snapshot)+    #expect(runs.first?.routine?.id == routineID)+    #expect(completions.first?.routineRunID == runID)+    #expect(completions.first?.routineStepID == stepID)+    #expect(completions.first?.isDeleted == true)+    #expect(try reopened.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } }
Meddy/MeddyTests/MeddySessionTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddySessionTests.swift b/Meddy/MeddyTests/MeddySessionTests.swiftindex dcba711..c8afdb2 100644--- a/Meddy/MeddyTests/MeddySessionTests.swift+++ b/Meddy/MeddyTests/MeddySessionTests.swift@@ -1,139 +1,205 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddySessionTests {-    private func fixture() throws -> (ModelContainer, Treatment, Medication, Routine) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let treatment = try TreatmentService(context: store.mainContext).create(name: "Synthetic care", instructions: "Saved instructions")-        let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic item")-        let group = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic sequence", steps: [.init(kind: .treatment, targetID: treatment.id), .init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id])-        return (store, treatment, medication, group)-    }+  private struct Fixture {+    let store: ModelContainer+    let treatment: Treatment+    let medication: Medication+    let group: Routine+  } -    @Test func canonicalFactsAndProgressDeduplicateThenUndoPreservesLaterDose() throws {-        let (store, treatment, medication, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group)-        let steps = try service.definition(run).steps-        let careAction = TreatmentAction(eventID: UUID(), treatmentID: treatment.id, timestamp: Date(), instructionsSnapshot: "Saved instructions", source: .phone)-        let completion = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)-        _ = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)-        let medicationAction = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)-        let administration = try service.recordMedication(medicationAction, in: run, stepID: steps[1].id)-        #expect(run.wasCompleted)-        try service.correct(completion, timestamp: completion.timestamp, delete: true)-        #expect(run.statusRaw == "needsReview" && !run.wasCompleted)-        #expect(!administration.isDeleted)-        #expect(try service.progress(run).steps[1].canonicalEventID == administration.id)-        _ = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)-        #expect(completion.isDeleted)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<TreatmentCompletion>()) == 1)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)-    }+  private func fixture() throws -> Fixture {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let treatment = try TreatmentService(context: store.mainContext).create(+      name: "Synthetic care", instructions: "Saved instructions")+    let medication = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic item")+    let group = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic sequence",+      steps: [+        .init(kind: .treatment, targetID: treatment.id),+        .init(kind: .medication, targetID: medication.id)+      ], confirmedMedicationIDs: [medication.id])+    return Fixture(store: store, treatment: treatment, medication: medication, group: group)+  } -    @Test func outOfOrderWatchDoseAndFutureClockAreNeverDropped() throws {-        let (store, _, medication, group) = try fixture()-        let now = Date(timeIntervalSince1970: 1_000)-        let service = RoutineSessionService(context: store.mainContext, now: { now })-        let run = try service.start(group)-        let step = try service.definition(run).steps[1]-        let action = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: now.addingTimeInterval(90), source: .watch, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)-        let event = try service.recordMedication(action, in: run, stepID: step.id, expectedRevision: 0)-        #expect(event.timestamp == action.timestamp && event.hasClockMismatch)-        #expect(run.statusRaw == "needsReview")-        #expect(try service.progress(run).steps[0].state == .pending)-    }+  @Test func canonicalFactsAndProgressDeduplicateThenUndoPreservesLaterDose() throws {+    let fixture = try fixture()+    let store = fixture.store+    let treatment = fixture.treatment+    let medication = fixture.medication+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let steps = try service.definition(run).steps+    let careAction = TreatmentAction(+      eventID: UUID(), treatmentID: treatment.id, timestamp: Date(),+      instructionsSnapshot: "Saved instructions", source: .phone)+    let completion = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)+    _ = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)+    let medicationAction = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+      dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)+    let administration = try service.recordMedication(+      medicationAction, in: run, stepID: steps[1].id)+    #expect(run.wasCompleted)+    try service.correct(completion, timestamp: completion.timestamp, delete: true)+    #expect(run.statusRaw == "needsReview" && !run.wasCompleted)+    #expect(!administration.isDeleted)+    #expect(try service.progress(run).steps[1].canonicalEventID == administration.id)+    _ = try service.recordTreatment(careAction, in: run, stepID: steps[0].id)+    #expect(completion.isDeleted)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<TreatmentCompletion>()) == 1)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  } -    @Test func invalidPhoneOrderRollsBackFactAndCheckpointTogether() throws {-        let (store, _, medication, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group)-        let before = run.stepProgressData-        let step = try service.definition(run).steps[1]-        let action = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)-        #expect(throws: ExecutionError.stepNotReady) { try service.recordMedication(action, in: run, stepID: step.id) }-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-        #expect(run.stepProgressData == before && run.revision == 0)-    }+  @Test func outOfOrderWatchDoseAndFutureClockAreNeverDropped() throws {+    let fixture = try fixture()+    let store = fixture.store+    let medication = fixture.medication+    let group = fixture.group+    let now = Date(timeIntervalSince1970: 1_000)+    let service = RoutineSessionService(context: store.mainContext, now: { now })+    let run = try service.start(group)+    let step = try service.definition(run).steps[1]+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: now.addingTimeInterval(90),+      source: .watch, dose: .unknown, scheduleTypeAtRecording: .routineManaged,+      scheduleGenerationID: nil)+    let event = try service.recordMedication(action, in: run, stepID: step.id, expectedRevision: 0)+    #expect(event.timestamp == action.timestamp && event.hasClockMismatch)+    #expect(run.statusRaw == "needsReview")+    #expect(try service.progress(run).steps[0].state == .pending)+  } -    @Test func explicitLinkAndMoveReuseOneActualAdministration() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let medicationService = MedicationService(context: store.mainContext)-        let medication = try medicationService.createAsNeededMedication(name: "Synthetic item")-        let event = try medicationService.record(.init(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))-        let group = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic one-step group", steps: [.init(kind: .medication, targetID: medication.id)], confirmedMedicationIDs: [medication.id])-        let service = RoutineSessionService(context: store.mainContext)-        let a = try service.start(group), b = try service.start(group)-        let step = try service.definition(a).steps[0]-        try service.link(event, to: a, stepID: step.id)-        #expect(throws: ExecutionError.linkedElsewhere) { try service.link(event, to: b, stepID: step.id) }-        try service.link(event, to: b, stepID: step.id, confirmedMove: true)-        #expect(a.statusRaw == "needsReview" && b.wasCompleted)-        #expect(event.routineRunID == b.id && event.scheduleTypeAtRecordingRaw == "asNeeded")-        #expect(try service.progress(a).steps[0].canonicalEventID == nil)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  @Test func invalidPhoneOrderRollsBackFactAndCheckpointTogether() throws {+    let fixture = try fixture()+    let store = fixture.store+    let medication = fixture.medication+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let before = run.stepProgressData+    let step = try service.definition(run).steps[1]+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+      dose: .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)+    #expect(throws: ExecutionError.stepNotReady) {+      try service.recordMedication(action, in: run, stepID: step.id)     }+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+    #expect(run.stepProgressData == before && run.revision == 0)+  } -    @Test func scheduledLogsAreNeverRepurposedForRoutineCompletion() throws {-        let (store, _, medication, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group)-        let action = AdministrationAction(eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone, dose: .unknown, scheduleTypeAtRecording: .fixedTimes, scheduleGenerationID: UUID())-        let event = try MedicationService(context: store.mainContext).record(action)-        let step = try service.definition(run).steps[1]-        #expect(throws: ExecutionError.ineligibleLog) { try service.link(event, to: run, stepID: step.id) }-        #expect(event.routineRunID == nil)+  @Test func explicitLinkAndMoveReuseOneActualAdministration() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let medicationService = MedicationService(context: store.mainContext)+    let medication = try medicationService.createAsNeededMedication(name: "Synthetic item")+    let event = try medicationService.record(+      .init(+        eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+        dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil))+    let group = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic one-step group", steps: [.init(kind: .medication, targetID: medication.id)],+      confirmedMedicationIDs: [medication.id])+    let service = RoutineSessionService(context: store.mainContext)+    let firstRun = try service.start(group)+    let secondRun = try service.start(group)+    let step = try service.definition(firstRun).steps[0]+    try service.link(event, to: firstRun, stepID: step.id)+    #expect(throws: ExecutionError.linkedElsewhere) {+      try service.link(event, to: secondRun, stepID: step.id)     }+    try service.link(event, to: secondRun, stepID: step.id, confirmedMove: true)+    #expect(firstRun.statusRaw == "needsReview" && secondRun.wasCompleted)+    #expect(event.routineRunID == secondRun.id && event.scheduleTypeAtRecordingRaw == "asNeeded")+    #expect(try service.progress(firstRun).steps[0].canonicalEventID == nil)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 1)+  } -    @Test func partialCheckpointRepairUsesSavedCanonicalFactWithoutCreatingDose() throws {-        let (store, treatment, _, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group)-        let step = try service.definition(run).steps[0]-        let completion = TreatmentCompletion(treatment: treatment, timestamp: Date(), source: .phone)-        completion.routineRunID = run.id; completion.routineStepID = step.id-        store.mainContext.insert(completion); try store.mainContext.save()-        try service.reconcile(run)-        let after = run.stepProgressData-        try service.reconcile(run)-        #expect(run.stepProgressData == after)-        #expect(try service.progress(run).steps[0].canonicalEventID == completion.id)-        #expect(try service.progress(run).steps[1].state == .pending)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  @Test func scheduledLogsAreNeverRepurposedForRoutineCompletion() throws {+    let fixture = try fixture()+    let store = fixture.store+    let medication = fixture.medication+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let action = AdministrationAction(+      eventID: UUID(), medicationID: medication.id, timestamp: Date(), source: .phone,+      dose: .unknown, scheduleTypeAtRecording: .fixedTimes, scheduleGenerationID: UUID())+    let event = try MedicationService(context: store.mainContext).record(action)+    let step = try service.definition(run).steps[1]+    #expect(throws: ExecutionError.ineligibleLog) {+      try service.link(event, to: run, stepID: step.id)     }+    #expect(event.routineRunID == nil)+  } -    @Test func correctionReplayCannotRewriteLaterAuthoritativeCorrection() throws {-        let (store, treatment, _, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group)-        let step = try service.definition(run).steps[0]-        let completion = try service.recordTreatment(.init(eventID: UUID(), treatmentID: treatment.id, timestamp: Date(), instructionsSnapshot: "", source: .phone), in: run, stepID: step.id)-        let firstID = UUID()-        let first = Date().addingTimeInterval(-60), second = Date().addingTimeInterval(-30)-        try service.correct(completion, timestamp: first, actionID: firstID)-        try service.correct(completion, timestamp: second)-        try service.correct(completion, timestamp: first, actionID: firstID)-        #expect(completion.timestamp == second)-        #expect(try service.progress(run).steps[0].audit.count == 2)-    }+  @Test func partialCheckpointRepairUsesSavedCanonicalFactWithoutCreatingDose() throws {+    let fixture = try fixture()+    let store = fixture.store+    let treatment = fixture.treatment+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let step = try service.definition(run).steps[0]+    let completion = TreatmentCompletion(treatment: treatment, timestamp: Date(), source: .phone)+    completion.routineRunID = run.id+    completion.routineStepID = step.id+    store.mainContext.insert(completion)+    try store.mainContext.save()+    try service.reconcile(run)+    let after = run.stepProgressData+    try service.reconcile(run)+    #expect(run.stepProgressData == after)+    #expect(try service.progress(run).steps[0].canonicalEventID == completion.id)+    #expect(try service.progress(run).steps[1].state == .pending)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } -    @Test func scheduledOccurrenceAndSkipActionHaveDurableStableIDs() throws {-        let (store, _, _, group) = try fixture()-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(group, occurrenceKey: "synthetic-slot-date")-        let replay = try service.start(group, occurrenceKey: "synthetic-slot-date")-        #expect(run.id == replay.id)-        let step = try service.definition(run).steps[0]-        let actionID = UUID()-        try service.skip(run, stepID: step.id, actionID: actionID, reason: "User choice")-        try service.skip(run, stepID: step.id, actionID: actionID, reason: "Retry")-        #expect(try service.progress(run).steps[0].audit.count == 1)-        #expect(try service.progress(run).nextReadyStepID == nil)-        try service.continueAfterSkip(run, stepID: step.id, actionID: UUID())-        #expect(try service.progress(run).nextReadyStepID != nil)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 1)-    }+  @Test func correctionReplayCannotRewriteLaterAuthoritativeCorrection() throws {+    let fixture = try fixture()+    let store = fixture.store+    let treatment = fixture.treatment+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group)+    let step = try service.definition(run).steps[0]+    let completion = try service.recordTreatment(+      .init(+        eventID: UUID(), treatmentID: treatment.id, timestamp: Date(), instructionsSnapshot: "",+        source: .phone), in: run, stepID: step.id)+    let firstID = UUID()+    let first = Date().addingTimeInterval(-60)+    let second = Date().addingTimeInterval(-30)+    try service.correct(completion, timestamp: first, actionID: firstID)+    try service.correct(completion, timestamp: second)+    try service.correct(completion, timestamp: first, actionID: firstID)+    #expect(completion.timestamp == second)+    #expect(try service.progress(run).steps[0].audit.count == 2)+  }++  @Test func scheduledOccurrenceAndSkipActionHaveDurableStableIDs() throws {+    let fixture = try fixture()+    let store = fixture.store+    let group = fixture.group+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(group, occurrenceKey: "synthetic-slot-date")+    let replay = try service.start(group, occurrenceKey: "synthetic-slot-date")+    #expect(run.id == replay.id)+    let step = try service.definition(run).steps[0]+    let actionID = UUID()+    try service.skip(run, stepID: step.id, actionID: actionID, reason: "User choice")+    try service.skip(run, stepID: step.id, actionID: actionID, reason: "Retry")+    #expect(try service.progress(run).steps[0].audit.count == 1)+    #expect(try service.progress(run).nextReadyStepID == nil)+    try service.continueAfterSkip(run, stepID: step.id, actionID: UUID())+    #expect(try service.progress(run).nextReadyStepID != nil)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 1)+  } }
Meddy/MeddyTests/MeddySnoozeTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddySnoozeTests.swift b/Meddy/MeddyTests/MeddySnoozeTests.swiftindex 803b351..c439576 100644--- a/Meddy/MeddyTests/MeddySnoozeTests.swift+++ b/Meddy/MeddyTests/MeddySnoozeTests.swift@@ -1,207 +1,313 @@ import Foundation import SwiftData-import UserNotifications import Testing+import UserNotifications+ @testable import Meddy  @MainActor struct MeddySnoozeTests {-    private func setup(at now: Date) throws -> (ModelContainer, Medication) {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic snooze")-        try ScheduleService(context: store.mainContext).configure(item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120), reminders: true)-        item.scheduleStartedAt = now.addingTimeInterval(-7200); try store.mainContext.save()-        return (store, item)-    }-    private func decoded(_ request: UNNotificationRequest) throws -> PlannedReminder {-        try JSONDecoder().decode(PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data))-    }-    @Test func snoozeAnchorsToActionClockAndRefreshNeverRecreatesOriginalOverdueRequest() async throws {-        var clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first)-        clock = clock.addingTimeInterval(30)-        let actionAt = clock-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        let request = try #require(client.requests.first)-        #expect(try decoded(request).deliveryAt == actionAt.addingTimeInterval(900))-        #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 900)-        clock = clock.addingTimeInterval(60)-        service.refresh(); await service.waitForRefresh() // Foreground / background lifecycle reconciliation.-        #expect(client.requests.count == 1)-        #expect(try decoded(client.requests[0]).deliveryAt == actionAt.addingTimeInterval(900))-        #expect(client.added.count == 1)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }-    @Test func elapsedDismissedSnoozeIsNotReplayedByLaterRefresh() async throws {-        var clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first)-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        let deliveredAt = try decoded(#require(client.requests.first)).deliveryAt-        clock = deliveredAt-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.count == 1 && client.added.count == 1) // Leave the due request to iOS delivery.-        client.requests.removeAll() // Delivered and dismissed by iOS; no pending or delivered request remains.-        clock = deliveredAt.addingTimeInterval(1)-        service.refresh(); await service.waitForRefresh()-        #expect(client.requests.isEmpty && client.added.count == 1)-    }-    @Test func duplicateCallbackKeepsDeadlineButAnotherDeliveredSnoozeCanBeSnoozedAgain() async throws {-        var clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first)-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        let firstSnooze = try decoded(#require(client.requests.first))-        clock = clock.addingTimeInterval(10)-        let beforeRepeat = try #require(service.plan(now: clock).first)-        #expect(beforeRepeat.deliveryAt == firstSnooze.deliveryAt)-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        let duplicateDeadline = try decoded(#require(client.requests.first)).deliveryAt-        #expect(duplicateDeadline.timeIntervalSince(firstSnooze.deliveryAt) == 0)-        #expect(service.error == nil)-        client.requests.removeAll(); clock = firstSnooze.deliveryAt-        service.handle(firstSnooze, action: "SNOOZE"); await service.waitForRefresh()-        let nextDeadline = try decoded(#require(client.requests.first)).deliveryAt-        #expect(nextDeadline.timeIntervalSince(clock) == 900)-        #expect(service.error == nil)-    }-    @Test func installedRevisionCancelledInFlightAddCanOverwriteFifteenMinuteSnooze() async throws {-        let now = Date(); let (store, _) = try setup(at: now)-        let original = try #require(ReminderService(context: store.mainContext).plan(now: now).first)-        var snoozed = original; snoozed.deliveryAt = now.addingTimeInterval(900)-        let client = SnoozeNotifications(); client.blockNextAdd = true-        // Exact relevant ordering in 4a9daaa: cancel old refresh, start new refresh,-        // and no cancellation check after the old asynchronous notification add.-        let oldRefresh = Task { try await client.add(Self.request(original, interval: 1)) }-        await client.waitUntilBlocked()-        oldRefresh.cancel()-        try await client.add(Self.request(snoozed, interval: 900))-        client.releaseBlockedAdd(); try await oldRefresh.value-        #expect(client.requests.count == 1)-        #expect((client.requests[0].trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 1)-        #expect(try decoded(client.requests[0]) == original)-    }-    @Test func currentReconciliationDrainsOldAddBeforeInstallingSnooze() async throws {-        let clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications(); client.blockNextAdd = true-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first)-        service.refresh(); await client.waitUntilBlocked()-        service.handle(original, action: "SNOOZE")-        client.releaseBlockedAdd(); await service.waitForRefresh()-        let request = try #require(client.requests.first)-        #expect(client.requests.count == 1 && client.added.count == 2)-        #expect(try decoded(request).deliveryAt == clock.addingTimeInterval(900))-        #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 900)-    }-    @Test func persistedFutureAndElapsedSnoozesSurviveRelaunchWithoutEarlyDeliveryOrReplay() async throws {-        var clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let suite = "meddy.synthetic.snooze.\(UUID())"; let defaults = try #require(UserDefaults(suiteName: suite))-        defer { defaults.removePersistentDomain(forName: suite) }-        let initial = ReminderService(context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })-        let original = try #require(initial.plan(now: clock).first)-        initial.handle(original, action: "SNOOZE"); await initial.waitForRefresh()-        let deadline = try decoded(#require(client.requests.first)).deliveryAt-        clock = clock.addingTimeInterval(300)-        let relaunched = ReminderService(context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })-        relaunched.refresh(); await relaunched.waitForRefresh()-        #expect(client.added.count == 1 && client.requests.count == 1)-        #expect(try decoded(client.requests[0]).deliveryAt == deadline)-        client.status = .denied; relaunched.refresh(); await relaunched.waitForRefresh()-        #expect(client.requests.isEmpty)-        client.status = .authorized; clock = clock.addingTimeInterval(60)-        relaunched.refresh(); await relaunched.waitForRefresh()-        #expect(try decoded(#require(client.requests.first)).deliveryAt == deadline)-        #expect((client.requests[0].trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 540)-        client.requests.removeAll(); clock = deadline.addingTimeInterval(1)-        let afterDismissal = ReminderService(context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })-        afterDismissal.refresh(); await afterDismissal.waitForRefresh()-        afterDismissal.handle(original, action: "SNOOZE"); await afterDismissal.waitForRefresh()-        #expect(client.requests.isEmpty && client.added.count == 2)-    }-    @Test func snoozePreservesOtherDueAndForeignRequestsAndStaleDisabledActionCannotRecreateIt() async throws {-        var clock = Date(); let (store, item) = try setup(at: clock); let client = SnoozeNotifications()-        let other = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic other due")-        try ScheduleService(context: store.mainContext).configure(other, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120), reminders: true)-        other.scheduleStartedAt = clock.addingTimeInterval(-7200); try store.mainContext.save()-        client.requests = [.init(identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)]-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first { if case .medication(let action) = $0.payload { return action.medicationID == item.id }; return false })-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        #expect(Set(client.requests.map(\.identifier)) == ["foreign", original.id, "meddy.medication.\(other.id)"])-        let deferred = try decoded(#require(client.requests.first { $0.identifier == original.id }))-        #expect(deferred.deliveryAt == clock.addingTimeInterval(900))-        client.requests.removeAll { $0.identifier == original.id }; clock = deferred.deliveryAt.addingTimeInterval(1)-        service.refresh(); await service.waitForRefresh()-        #expect(Set(client.requests.map(\.identifier)) == ["foreign", "meddy.medication.\(other.id)"])-        try ScheduleService(context: store.mainContext).configure(item, draft: .init(mode: .asNeeded), reminders: false)-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        #expect(!client.requests.contains { $0.identifier == original.id })-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }-    @Test func routineSnoozeKeepsItsOccurrenceAndDoesNotStartOrSuppressAnotherSession() async throws {-        var clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let care = try TreatmentService(context: store.mainContext).create(name: "Synthetic snoozed care")-        let routine = try RoutineService(context: store.mainContext).createOrdered(name: "Synthetic snoozed routine", steps: [.init(kind: .treatment, targetID: care.id)])-        try ScheduleService(context: store.mainContext).configure(routine, slots: [.init(label: "Synthetic slot", minuteOfDay: 120)], reminders: true)-        routine.scheduleStartedAt = clock.addingTimeInterval(-24 * 3600); try store.mainContext.save()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first { if case .routine(let occurrence) = $0.payload { return occurrence.routineID == routine.id && occurrence.scheduledAt! <= clock }; return false })-        service.handle(original, action: "SNOOZE"); await service.waitForRefresh()-        let deferred = try decoded(#require(client.requests.first { $0.identifier == original.id }))-        #expect(deferred.payload == original.payload && deferred.deliveryAt == clock.addingTimeInterval(900))-        let added = client.added.filter { $0.identifier == original.id }.count-        clock = clock.addingTimeInterval(300); service.refresh(); await service.waitForRefresh()-        #expect(client.added.filter { $0.identifier == original.id }.count == added)-        #expect(client.requests.contains { $0.identifier.hasPrefix("meddy.routine.") && $0.identifier != original.id })-        #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 0)-    }+  private func setup(at now: Date) throws -> (ModelContainer, Medication) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic snooze")+    try ScheduleService(context: store.mainContext).configure(+      item, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120),+      reminders: true)+    item.scheduleStartedAt = now.addingTimeInterval(-7200)+    try store.mainContext.save()+    return (store, item)+  }+  private func decoded(_ request: UNNotificationRequest) throws -> PlannedReminder {+    try JSONDecoder().decode(+      PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data))+  }+  @Test func snoozeAnchorsToActionClockAndRefreshNeverRecreatesOriginalOverdueRequest() async throws {+    var clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(service.plan(now: clock).first)+    clock = clock.addingTimeInterval(30)+    let actionAt = clock+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    let request = try #require(client.requests.first)+    #expect(try decoded(request).deliveryAt == actionAt.addingTimeInterval(900))+    #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 900)+    clock = clock.addingTimeInterval(60)+    service.refresh()+    await service.waitForRefresh()  // Foreground / background lifecycle reconciliation.+    #expect(client.requests.count == 1)+    #expect(try decoded(client.requests[0]).deliveryAt == actionAt.addingTimeInterval(900))+    #expect(client.added.count == 1)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func elapsedDismissedSnoozeIsNotReplayedByLaterRefresh() async throws {+    var clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(service.plan(now: clock).first)+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    let deliveredAt = try decoded(#require(client.requests.first)).deliveryAt+    clock = deliveredAt+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.count == 1 && client.added.count == 1)  // Leave the due request to iOS delivery.+    client.requests.removeAll()  // Delivered and dismissed by iOS; no pending or delivered request remains.+    clock = deliveredAt.addingTimeInterval(1)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.requests.isEmpty && client.added.count == 1)+  }+  @Test func duplicateCallbackKeepsDeadlineButAnotherDeliveredSnoozeCanBeSnoozedAgain() async throws {+    var clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(service.plan(now: clock).first)+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    let firstSnooze = try decoded(#require(client.requests.first))+    clock = clock.addingTimeInterval(10)+    let beforeRepeat = try #require(service.plan(now: clock).first)+    #expect(beforeRepeat.deliveryAt == firstSnooze.deliveryAt)+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    let duplicateDeadline = try decoded(#require(client.requests.first)).deliveryAt+    #expect(duplicateDeadline.timeIntervalSince(firstSnooze.deliveryAt) == 0)+    #expect(service.error == nil)+    client.requests.removeAll()+    clock = firstSnooze.deliveryAt+    service.handle(firstSnooze, action: "SNOOZE")+    await service.waitForRefresh()+    let nextDeadline = try decoded(#require(client.requests.first)).deliveryAt+    #expect(nextDeadline.timeIntervalSince(clock) == 900)+    #expect(service.error == nil)+  }+  @Test func installedRevisionCancelledInFlightAddCanOverwriteFifteenMinuteSnooze() async throws {+    let now = Date()+    let (store, _) = try setup(at: now)+    let original = try #require(ReminderService(context: store.mainContext).plan(now: now).first)+    var snoozed = original+    snoozed.deliveryAt = now.addingTimeInterval(900)+    let client = SnoozeNotifications()+    client.blockNextAdd = true+    // Exact relevant ordering in 4a9daaa: cancel old refresh, start new refresh,+    // and no cancellation check after the old asynchronous notification add.+    let oldRefresh = Task { try await client.add(Self.request(original, interval: 1)) }+    await client.waitUntilBlocked()+    oldRefresh.cancel()+    try await client.add(Self.request(snoozed, interval: 900))+    client.releaseBlockedAdd()+    try await oldRefresh.value+    #expect(client.requests.count == 1)+    #expect((client.requests[0].trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 1)+    #expect(try decoded(client.requests[0]) == original)+  }+  @Test func currentReconciliationDrainsOldAddBeforeInstallingSnooze() async throws {+    let clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    client.blockNextAdd = true+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(service.plan(now: clock).first)+    service.refresh()+    await client.waitUntilBlocked()+    service.handle(original, action: "SNOOZE")+    client.releaseBlockedAdd()+    await service.waitForRefresh()+    let request = try #require(client.requests.first)+    #expect(client.requests.count == 1 && client.added.count == 2)+    #expect(try decoded(request).deliveryAt == clock.addingTimeInterval(900))+    #expect((request.trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 900)+  }+  @Test func persistedFutureAndElapsedSnoozesSurviveRelaunchWithoutEarlyDeliveryOrReplay()+    async throws {+    var clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let suite = "meddy.synthetic.snooze.\(UUID())"+    let defaults = try #require(UserDefaults(suiteName: suite))+    defer { defaults.removePersistentDomain(forName: suite) }+    let initial = ReminderService(+      context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })+    let original = try #require(initial.plan(now: clock).first)+    initial.handle(original, action: "SNOOZE")+    await initial.waitForRefresh()+    let deadline = try decoded(#require(client.requests.first)).deliveryAt+    clock = clock.addingTimeInterval(300)+    let relaunched = ReminderService(+      context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })+    relaunched.refresh()+    await relaunched.waitForRefresh()+    #expect(client.added.count == 1 && client.requests.count == 1)+    #expect(try decoded(client.requests[0]).deliveryAt == deadline)+    client.status = .denied+    relaunched.refresh()+    await relaunched.waitForRefresh()+    #expect(client.requests.isEmpty)+    client.status = .authorized+    clock = clock.addingTimeInterval(60)+    relaunched.refresh()+    await relaunched.waitForRefresh()+    #expect(try decoded(#require(client.requests.first)).deliveryAt == deadline)+    #expect((client.requests[0].trigger as? UNTimeIntervalNotificationTrigger)?.timeInterval == 540)+    client.requests.removeAll()+    clock = deadline.addingTimeInterval(1)+    let afterDismissal = ReminderService(+      context: store.mainContext, notifications: client, snoozeDefaults: defaults, now: { clock })+    afterDismissal.refresh()+    await afterDismissal.waitForRefresh()+    afterDismissal.handle(original, action: "SNOOZE")+    await afterDismissal.waitForRefresh()+    #expect(client.requests.isEmpty && client.added.count == 2)+  }+  @Test func snoozePreservesOtherDueAndForeignRequestsAndStaleDisabledActionCannotRecreateIt()+    async throws {+    var clock = Date()+    let (store, item) = try setup(at: clock)+    let client = SnoozeNotifications()+    let other = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic other due")+    try ScheduleService(context: store.mainContext).configure(+      other, draft: .init(mode: .interval, intervalMinutes: 60, firstReminderMinute: 120),+      reminders: true)+    other.scheduleStartedAt = clock.addingTimeInterval(-7200)+    try store.mainContext.save()+    client.requests = [+      .init(identifier: "foreign", content: UNMutableNotificationContent(), trigger: nil)+    ]+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(+      service.plan(now: clock).first {+        if case .medication(let action) = $0.payload { return action.medicationID == item.id }+        return false+      })+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    #expect(+      Set(client.requests.map(\.identifier)) == [+        "foreign", original.id, "meddy.medication.\(other.id)"+      ])+    let deferred = try decoded(#require(client.requests.first { $0.identifier == original.id }))+    #expect(deferred.deliveryAt == clock.addingTimeInterval(900))+    client.requests.removeAll { $0.identifier == original.id }+    clock = deferred.deliveryAt.addingTimeInterval(1)+    service.refresh()+    await service.waitForRefresh()+    #expect(Set(client.requests.map(\.identifier)) == ["foreign", "meddy.medication.\(other.id)"])+    try ScheduleService(context: store.mainContext).configure(+      item, draft: .init(mode: .asNeeded), reminders: false)+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    #expect(!client.requests.contains { $0.identifier == original.id })+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func routineSnoozeKeepsItsOccurrenceAndDoesNotStartOrSuppressAnotherSession() async throws {+    var clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let care = try TreatmentService(context: store.mainContext).create(+      name: "Synthetic snoozed care")+    let routine = try RoutineService(context: store.mainContext).createOrdered(+      name: "Synthetic snoozed routine", steps: [.init(kind: .treatment, targetID: care.id)])+    try ScheduleService(context: store.mainContext).configure(+      routine, slots: [.init(label: "Synthetic slot", minuteOfDay: 120)], reminders: true)+    routine.scheduleStartedAt = clock.addingTimeInterval(-24 * 3600)+    try store.mainContext.save()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(+      service.plan(now: clock).first {+        if case .routine(let occurrence) = $0.payload {+          return occurrence.routineID == routine.id && occurrence.scheduledAt! <= clock+        }+        return false+      })+    service.handle(original, action: "SNOOZE")+    await service.waitForRefresh()+    let deferred = try decoded(#require(client.requests.first { $0.identifier == original.id }))+    #expect(+      deferred.payload == original.payload && deferred.deliveryAt == clock.addingTimeInterval(900))+    let added = client.added.filter { $0.identifier == original.id }.count+    clock = clock.addingTimeInterval(300)+    service.refresh()+    await service.waitForRefresh()+    #expect(client.added.filter { $0.identifier == original.id }.count == added)+    #expect(+      client.requests.contains {+        $0.identifier.hasPrefix("meddy.routine.") && $0.identifier != original.id+      })+    #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 0)+  } -    @Test func backgroundResponseWaitsForLatestReconciliationBeforeReturning() async throws {-        let clock = Date(); let (store, _) = try setup(at: clock); let client = SnoozeNotifications()-        let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })-        let original = try #require(service.plan(now: clock).first)-        service.refresh(); await service.waitForRefresh()-        client.blockNextAdd = true-        var completed = false-        let response = Task { await service.respond(original, action: "SNOOZE"); completed = true }-        await client.waitUntilBlocked()-        #expect(!completed && client.requests.isEmpty) // The queued overdue original is cancelled immediately.-        service.refresh() // A foreground wake-up must not let the older callback return early.-        client.releaseBlockedAdd(); await response.value-        #expect(completed && client.requests.count == 1 && client.added.count == 2)-        #expect(try decoded(client.requests[0]).deliveryAt == clock.addingTimeInterval(900))+  @Test func backgroundResponseWaitsForLatestReconciliationBeforeReturning() async throws {+    let clock = Date()+    let (store, _) = try setup(at: clock)+    let client = SnoozeNotifications()+    let service = ReminderService(context: store.mainContext, notifications: client, now: { clock })+    let original = try #require(service.plan(now: clock).first)+    service.refresh()+    await service.waitForRefresh()+    client.blockNextAdd = true+    var completed = false+    let response = Task {+      await service.respond(original, action: "SNOOZE")+      completed = true     }+    await client.waitUntilBlocked()+    #expect(!completed && client.requests.isEmpty)  // The queued overdue original is cancelled immediately.+    service.refresh()  // A foreground wake-up must not let the older callback return early.+    client.releaseBlockedAdd()+    await response.value+    #expect(completed && client.requests.count == 1 && client.added.count == 2)+    #expect(try decoded(client.requests[0]).deliveryAt == clock.addingTimeInterval(900))+  } -    private static func request(_ reminder: PlannedReminder, interval: TimeInterval) throws -> UNNotificationRequest {-        let content = UNMutableNotificationContent(); content.userInfo = ["meddy.payload": try JSONEncoder().encode(reminder)]-        return .init(identifier: reminder.id, content: content, trigger: UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false))-    }+  private static func request(_ reminder: PlannedReminder, interval: TimeInterval) throws+    -> UNNotificationRequest {+    let content = UNMutableNotificationContent()+    content.userInfo = ["meddy.payload": try JSONEncoder().encode(reminder)]+    return .init(+      identifier: reminder.id, content: content,+      trigger: UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false))+  } }  @MainActor private final class SnoozeNotifications: ReminderNotificationClient {-    var status: UNAuthorizationStatus = .authorized-    var requests: [UNNotificationRequest] = []-    var added: [UNNotificationRequest] = []-    var blockNextAdd = false-    private var blocked: CheckedContinuation<Void, Never>?-    private var started: CheckedContinuation<Void, Never>?-    func waitUntilBlocked() async {-        if blocked != nil { return }-        await withCheckedContinuation { started = $0 }-    }-    func releaseBlockedAdd() { blocked?.resume(); blocked = nil }-    func authorization() async -> UNAuthorizationStatus { status }-    func pending() async -> [UNNotificationRequest] { requests }-    func delivered() async -> [UNNotification] { [] }-    func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }-    func removeDelivered(_ ids: [String]) {}-    func add(_ request: UNNotificationRequest) async throws {-        if blockNextAdd {-            blockNextAdd = false-            await withCheckedContinuation { blocked = $0; started?.resume(); started = nil }-        }-        added.append(request); requests.removeAll { $0.identifier == request.identifier }; requests.append(request)+  var status: UNAuthorizationStatus = .authorized+  var requests: [UNNotificationRequest] = []+  var added: [UNNotificationRequest] = []+  var blockNextAdd = false+  private var blocked: CheckedContinuation<Void, Never>?+  private var started: CheckedContinuation<Void, Never>?+  func waitUntilBlocked() async {+    if blocked != nil { return }+    await withCheckedContinuation { started = $0 }+  }+  func releaseBlockedAdd() {+    blocked?.resume()+    blocked = nil+  }+  func authorization() async -> UNAuthorizationStatus { status }+  func pending() async -> [UNNotificationRequest] { requests }+  func delivered() async -> [UNNotification] { [] }+  func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }+  func removeDelivered(_ ids: [String]) {}+  func add(_ request: UNNotificationRequest) async throws {+    if blockNextAdd {+      blockNextAdd = false+      await withCheckedContinuation {+        blocked = $0+        started?.resume()+        started = nil+      }     }+    added.append(request)+    requests.removeAll { $0.identifier == request.identifier }+    requests.append(request)+  } }
Meddy/MeddyTests/MeddyTimedSessionTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyTimedSessionTests.swift b/Meddy/MeddyTests/MeddyTimedSessionTests.swiftindex 72e961c..a9ba913 100644--- a/Meddy/MeddyTests/MeddyTimedSessionTests.swift+++ b/Meddy/MeddyTests/MeddyTimedSessionTests.swift@@ -1,72 +1,82 @@ import Foundation import SwiftData import Testing+ @testable import Meddy  @MainActor struct MeddyTimedSessionTests {-    private func sample(_ time: Double) -> ClockSample { .init(wall: Date(timeIntervalSince1970: time), monotonic: time, continuityID: "synthetic") }+  private func sample(_ time: Double) -> ClockSample {+    .init(wall: Date(timeIntervalSince1970: time), monotonic: time, continuityID: "synthetic")+  } -    @Test func childTimerUsesFrozenSettingsAndOnlyFinalRoundFulfilsParent() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let definitions = RoutineService(context: store.mainContext)-        let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 10)-        let group = try definitions.createOrdered(name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])-        let service = RoutineSessionService(context: store.mainContext)-        let parent = try service.start(group)-        let step = try service.definition(parent).steps[0]-        try definitions.updateTimed(timer, name: "Edited timer", rounds: 5, durationSeconds: 90, instructions: "", betweenRounds: "", purpose: nil)-        let child = try service.beginTimedStep(parent, stepID: step.id)-        let retry = try service.beginTimedStep(parent, stepID: step.id)-        #expect(child.id == retry.id)-        #expect(try service.timer(child).roundCount == 2)-        try service.changeTimer(child, actionID: UUID(), clock: sample(100), operation: .start)-        try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .advance)-        #expect(!parent.wasCompleted && !child.wasCompleted)-        #expect(try service.timer(child).phase == .waiting)-        try service.changeTimer(child, actionID: UUID(), clock: sample(900), operation: .advance)-        #expect(!parent.wasCompleted)-        try service.changeTimer(child, actionID: UUID(), clock: sample(900), operation: .start)-        try service.changeTimer(child, actionID: UUID(), clock: sample(910), operation: .advance)-        #expect(parent.wasCompleted && child.wasCompleted)-        #expect(try service.progress(parent).steps[0].canonicalEventID == child.id)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 2)-        #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)-    }+  @Test func childTimerUsesFrozenSettingsAndOnlyFinalRoundFulfilsParent() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 2, durationSeconds: 10)+    let group = try definitions.createOrdered(+      name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])+    let service = RoutineSessionService(context: store.mainContext)+    let parent = try service.start(group)+    let step = try service.definition(parent).steps[0]+    try definitions.updateTimed(+      timer, edit: TimedRoutineEdit(name: "Edited timer", rounds: 5, durationSeconds: 90, instructions: "",+      betweenRounds: "", purpose: nil))+    let child = try service.beginTimedStep(parent, stepID: step.id)+    let retry = try service.beginTimedStep(parent, stepID: step.id)+    #expect(child.id == retry.id)+    #expect(try service.timer(child).roundCount == 2)+    try service.changeTimer(child, actionID: UUID(), clock: sample(100), operation: .start)+    try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .advance)+    #expect(!parent.wasCompleted && !child.wasCompleted)+    #expect(try service.timer(child).phase == .waiting)+    try service.changeTimer(child, actionID: UUID(), clock: sample(900), operation: .advance)+    #expect(!parent.wasCompleted)+    try service.changeTimer(child, actionID: UUID(), clock: sample(900), operation: .start)+    try service.changeTimer(child, actionID: UUID(), clock: sample(910), operation: .advance)+    #expect(parent.wasCompleted && child.wasCompleted)+    #expect(try service.progress(parent).steps[0].canonicalEventID == child.id)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<RoutineRun>()) == 2)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  } -    @Test func timerTransitionsAreReplaySafeAndTicksDoNotWrite() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let timer = try RoutineService(context: store.mainContext).createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)-        let service = RoutineSessionService(context: store.mainContext)-        let run = try service.start(timer)-        let action = UUID()-        try service.changeTimer(run, actionID: action, clock: sample(100), operation: .start)-        let revision = run.revision-        try service.changeTimer(run, actionID: action, clock: sample(105), operation: .start)-        try service.changeTimer(run, actionID: UUID(), clock: sample(106), operation: .advance)-        #expect(run.revision == revision)-        try service.changeTimer(run, actionID: UUID(), clock: sample(110), operation: .pause)-        #expect(try service.timer(run).accumulatedActiveSeconds == 10)-        try service.changeTimer(run, actionID: UUID(), clock: sample(500), operation: .resume)-        try service.changeTimer(run, actionID: UUID(), clock: sample(520), operation: .advance)-        #expect(run.wasCompleted && run.completedRounds == 1)-    }+  @Test func timerTransitionsAreReplaySafeAndTicksDoNotWrite() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let timer = try RoutineService(context: store.mainContext).createTimed(+      name: "Synthetic timer", rounds: 1, durationSeconds: 30)+    let service = RoutineSessionService(context: store.mainContext)+    let run = try service.start(timer)+    let action = UUID()+    try service.changeTimer(run, actionID: action, clock: sample(100), operation: .start)+    let revision = run.revision+    try service.changeTimer(run, actionID: action, clock: sample(105), operation: .start)+    try service.changeTimer(run, actionID: UUID(), clock: sample(106), operation: .advance)+    #expect(run.revision == revision)+    try service.changeTimer(run, actionID: UUID(), clock: sample(110), operation: .pause)+    #expect(try service.timer(run).accumulatedActiveSeconds == 10)+    try service.changeTimer(run, actionID: UUID(), clock: sample(500), operation: .resume)+    try service.changeTimer(run, actionID: UUID(), clock: sample(520), operation: .advance)+    #expect(run.wasCompleted && run.completedRounds == 1)+  } -    @Test func endingChildTimerNeverFulfilsParent() throws {-        let store = try AppEnvironment.makeContainer(isolated: true)-        let definitions = RoutineService(context: store.mainContext)-        let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)-        let group = try definitions.createOrdered(name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])-        let service = RoutineSessionService(context: store.mainContext)-        let parent = try service.start(group)-        let stepID = try service.definition(parent).steps[0].id-        let child = try service.beginTimedStep(parent, stepID: stepID)-        try service.changeTimer(child, actionID: UUID(), clock: sample(100), operation: .start)-        try service.changeTimer(child, actionID: UUID(), clock: sample(105), operation: .end)-        #expect(!parent.wasCompleted && !child.wasCompleted)-        #expect(try service.progress(parent).steps[0].state == .paused)-        #expect(throws: ExecutionError.invalidTransition) { try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .resume) }-        try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .reopen)-        #expect(try service.timer(child).phase == .paused)+  @Test func endingChildTimerNeverFulfilsParent() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let definitions = RoutineService(context: store.mainContext)+    let timer = try definitions.createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 30)+    let group = try definitions.createOrdered(+      name: "Synthetic group", steps: [.init(kind: .timedRoutine, targetID: timer.id)])+    let service = RoutineSessionService(context: store.mainContext)+    let parent = try service.start(group)+    let stepID = try service.definition(parent).steps[0].id+    let child = try service.beginTimedStep(parent, stepID: stepID)+    try service.changeTimer(child, actionID: UUID(), clock: sample(100), operation: .start)+    try service.changeTimer(child, actionID: UUID(), clock: sample(105), operation: .end)+    #expect(!parent.wasCompleted && !child.wasCompleted)+    #expect(try service.progress(parent).steps[0].state == .paused)+    #expect(throws: ExecutionError.invalidTransition) {+      try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .resume)     }+    try service.changeTimer(child, actionID: UUID(), clock: sample(110), operation: .reopen)+    #expect(try service.timer(child).phase == .paused)+  } }
Meddy/MeddyTests/MeddyWakeTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyWakeTests.swift b/Meddy/MeddyTests/MeddyWakeTests.swiftindex 7d0c23a..000adcd 100644--- a/Meddy/MeddyTests/MeddyWakeTests.swift+++ b/Meddy/MeddyTests/MeddyWakeTests.swift@@ -3,316 +3,532 @@ import Foundation import SwiftData import Testing import UserNotifications+ @testable import Meddy  @MainActor @Suite(.serialized) struct MeddyWakeTests {-    private var calendar: Calendar { var value = Calendar(identifier: .gregorian); value.timeZone = TimeZone(secondsFromGMT: 0)!; return value }-    private func date(_ day: Int = 5, _ hour: Int = 8, _ minute: Int = 0) -> Date { calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))! }-    private func medication(_ context: ModelContext, minutes: Int, owner: UUID = ProfileIdentity.me, start: Date? = nil) throws -> Medication {-        let medication = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic same medication", profileID: owner)-        try ScheduleService(context: context, now: { start ?? self.date() }, calendar: calendar).configure(medication, draft: .init(mode: .afterWaking, wakeOffsetMinutes: minutes), reminders: true)-        return medication-    }-    private func defaults() -> UserDefaults { UserDefaults(suiteName: "MeddyWakeTest-" + UUID().uuidString)! }-    private func payload(_ request: UNNotificationRequest) throws -> PlannedReminder { try JSONDecoder().decode(PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data)) }+  private var calendar: Calendar {+    var value = Calendar(identifier: .gregorian)+    value.timeZone = TimeZone(secondsFromGMT: 0)!+    return value+  }+  private func date(_ day: Int = 5, _ hour: Int = 8, _ minute: Int = 0) -> Date {+    calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))!+  }+  private func medication(+    _ context: ModelContext, minutes: Int, owner: UUID = ProfileIdentity.me, start: Date? = nil+  ) throws -> Medication {+    let medication = try MedicationService(context: context).createAsNeededMedication(+      name: "Synthetic same medication", profileID: owner)+    try ScheduleService(context: context, now: { start ?? self.date() }, calendar: calendar)+      .configure(+        medication, draft: .init(mode: .afterWaking, wakeOffsetMinutes: minutes), reminders: true)+    return medication+  }+  private func defaults() -> UserDefaults {+    UserDefaults(suiteName: "MeddyWakeTest-" + UUID().uuidString)!+  }+  private func payload(_ request: UNNotificationRequest) throws -> PlannedReminder {+    try JSONDecoder().decode(+      PlannedReminder.self, from: #require(request.content.userInfo["meddy.payload"] as? Data))+  } -    @Test func firstWakePerProfileAndLogicalDayWinsWithoutMovingTimestamp() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let dep = try ProfileService(context: c).create(displayName: "Synthetic")-        let service = WakeService(context: c)-        let first = try service.record(at: date(5, 1, 59), receivedAt: date(5, 1, 59), calendar: calendar)-        let duplicate = try service.record(at: date(5, 1, 59).addingTimeInterval(30), receivedAt: date(5, 1, 59).addingTimeInterval(30), calendar: calendar)-        let next = try service.record(at: date(5, 2), receivedAt: date(5, 2), calendar: calendar)-        let foreign = try service.record(profileID: dep.id, at: date(5, 2), receivedAt: date(5, 2), calendar: calendar)-        #expect(first.id == duplicate.id && first.timestamp == date(5, 1, 59))-        #expect(first.localDate == "2026-01-04" && next.localDate == "2026-01-05")-        #expect(next.id != first.id && foreign.id != next.id)-        #expect(first.sourceRaw == "shortcut" && first.timeZoneID == "GMT")-        #expect(try c.fetchCount(FetchDescriptor<Administration>()) == 0)-    }-    @Test func failedWakeSaveRollsBackAndRetryKeepsOneEvent() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; let service = WakeService(context: c)-        #expect(throws: RecordingError.self) { try service.record(at: date(), receivedAt: date(), calendar: calendar, save: { throw RecordingError.saveFailed }) }-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 0)-        try service.record(at: date(), receivedAt: date(), calendar: calendar)-        try service.record(at: date().addingTimeInterval(10), receivedAt: date().addingTimeInterval(10), calendar: calendar)-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 1)-    }-    @Test func wakingAndElapsedOffsetPersistAcrossDiskReopen() throws {-        let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)-        try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)-        let config = ModelConfiguration(schema: AppEnvironment.schema, url: dir.appendingPathComponent("synthetic.store"), cloudKitDatabase: .none)-        var eventID: UUID?-        do {-            let container = try ModelContainer(for: AppEnvironment.schema, configurations: [config]); try ProfileMigration.bootstrap(container.mainContext)-            _ = try medication(container.mainContext, minutes: 35)-            eventID = try WakeService(context: container.mainContext).record(at: date(), receivedAt: date(), calendar: calendar).id-        }-        let reopened = try ModelContainer(for: AppEnvironment.schema, configurations: [config])-        let event = try #require(reopened.mainContext.fetch(FetchDescriptor<WakeEvent>()).first)-        #expect(event.id == eventID && event.timestamp == date() && event.sourceRaw == "shortcut")-        let med = try #require(reopened.mainContext.fetch(FetchDescriptor<Medication>()).first)-        #expect(med.wakeOffsetMinutes == 35)-    }-    @Test func zeroSchedulesOnceAndRepeatedInvocationCannotCancelPendingOrReplayAfterDismissal() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; _ = try medication(c, minutes: 0)-        let now = date(), client = WakeNotifications(), state = defaults()-        try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: now, context: c, notifications: client, defaults: state, now: { now })-        #expect(client.added.count == 1 && client.requests.count == 1)-        try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: now.addingTimeInterval(2), context: c, notifications: client, defaults: state, now: { now.addingTimeInterval(2) })-        #expect(client.added.count == 1 && client.requests.count == 1)-        client.requests = [] // System delivered/dismissed it; no fabricated replay on relaunch.-        let reopened = ReminderService(context: c, notifications: client, wakeReceiptDefaults: state, now: { now.addingTimeInterval(3) })-        reopened.refresh(); await reopened.waitForRefresh()-        #expect(client.added.count == 1 && client.requests.isEmpty)-    }-    @Test(arguments: [0, 15]) func explicitSnoozeSurvivesElapsedWakeAndRelaunch(minutes: Int) async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; _ = try medication(c, minutes: minutes)-        let client = WakeNotifications(), state = defaults(), snoozes = defaults(); var now = date()-        try WakeService(context: c).record(at: now, receivedAt: now, calendar: calendar)-        let service = ReminderService(context: c, notifications: client, snoozeDefaults: snoozes, wakeReceiptDefaults: state, now: { now })-        service.refresh(); await service.waitForRefresh()-        let original = try payload(#require(client.added.first))-        now = date().addingTimeInterval(Double(minutes) * 60 + 5)-        client.requests = []-        await service.respond(original, action: "SNOOZE")-        let snoozed = try payload(#require(client.requests.first))-        #expect(snoozed.deliveryAt == now.addingTimeInterval(900))-        let additions = client.added.count-        await service.respond(original, action: "SNOOZE")-        let reopened = ReminderService(context: c, notifications: client, snoozeDefaults: snoozes, wakeReceiptDefaults: state, now: { now.addingTimeInterval(10) })-        reopened.refresh(); await reopened.waitForRefresh()-        let persisted = try payload(#require(client.requests.first))-        #expect(client.added.count == additions && persisted == snoozed)-    }-    @Test func missingWakeAndLatePositiveOffsetDoNotGenerateCatchupSpam() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; _ = try medication(c, minutes: 15)-        let client = WakeNotifications(); let now = date().addingTimeInterval(16 * 60)-        let service = ReminderService(context: c, notifications: client, now: { now })-        service.refresh(); await service.waitForRefresh(); #expect(client.added.isEmpty)-        try WakeService(context: c).record(at: date(), receivedAt: now, calendar: calendar)-        service.refresh(); await service.waitForRefresh(); service.refresh(); await service.waitForRefresh()-        #expect(client.added.isEmpty)+  @Test func firstWakePerProfileAndLogicalDayWinsWithoutMovingTimestamp() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let dep = try ProfileService(context: context).create(displayName: "Synthetic")+    let service = WakeService(context: context)+    let first = try service.record(+      at: date(5, 1, 59), receivedAt: date(5, 1, 59), calendar: calendar)+    let duplicate = try service.record(+      at: date(5, 1, 59).addingTimeInterval(30), receivedAt: date(5, 1, 59).addingTimeInterval(30),+      calendar: calendar)+    let next = try service.record(at: date(5, 2), receivedAt: date(5, 2), calendar: calendar)+    let foreign = try service.record(+      profileID: dep.id, at: date(5, 2), receivedAt: date(5, 2), calendar: calendar)+    #expect(first.id == duplicate.id && first.timestamp == date(5, 1, 59))+    #expect(first.localDate == "2026-01-04" && next.localDate == "2026-01-05")+    #expect(next.id != first.id && foreign.id != next.id)+    #expect(first.sourceRaw == "shortcut" && first.timeZoneID == "GMT")+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+  }+  @Test func failedWakeSaveRollsBackAndRetryKeepsOneEvent() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let service = WakeService(context: context)+    #expect(throws: RecordingError.self) {+      try service.record(+        at: date(), receivedAt: date(), calendar: calendar,+        save: { throw RecordingError.saveFailed })     }-    @Test func positiveOffsetKeepsExactElapsedDeadlineAcrossNewDayAndWake() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; let med = try medication(c, minutes: 1440)-        let wakes = WakeService(context: c)-        let first = try wakes.record(at: date(5, 8), receivedAt: date(5, 8), calendar: calendar)-        let second = try wakes.record(at: date(6, 7), receivedAt: date(6, 7), calendar: calendar)-        let plan = try ReminderService(context: c).plan(now: date(6, 7))-        let original = try #require(plan.first { $0.wakeEventID == first.id })-        #expect(original.deliveryAt == first.timestamp.addingTimeInterval(86400))-        #expect(plan.contains { $0.wakeEventID == second.id })-        guard case .medication(var action) = original.payload else { Issue.record("Expected medication action"); return }-        action.timestamp = date(6, 7)-        let event = try MedicationService(context: c).record(action)-        #expect(event.wakeEventID == first.id)-        let snapshot = try ScheduleService(context: c).snapshot(med)-        let actual = ScheduledAdministration(id: event.id, medicationID: med.id, timestamp: event.timestamp, mode: .afterWaking, generationID: event.scheduleGenerationID, wakeEventID: event.wakeEventID)-        let result = MedicationScheduleEngine().evaluate(snapshot, administrations: [actual], now: date(6, 7), calendar: calendar)-        #expect(result.remainingToday == 1 && result.next == second.timestamp.addingTimeInterval(86400))+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 0)+    try service.record(at: date(), receivedAt: date(), calendar: calendar)+    try service.record(+      at: date().addingTimeInterval(10), receivedAt: date().addingTimeInterval(10),+      calendar: calendar)+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 1)+  }+  @Test func wakingAndElapsedOffsetPersistAcrossDiskReopen() throws {+    let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+    let config = ModelConfiguration(+      schema: AppEnvironment.schema, url: dir.appendingPathComponent("synthetic.store"),+      cloudKitDatabase: .none)+    var eventID: UUID?+    do {+      let container = try ModelContainer(for: AppEnvironment.schema, configurations: [config])+      try ProfileMigration.bootstrap(container.mainContext)+      _ = try medication(container.mainContext, minutes: 35)+      eventID = try WakeService(context: container.mainContext).record(+        at: date(), receivedAt: date(), calendar: calendar+      ).id     }-    @Test func editCancellationAndReenableWaitForNextWake() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; let med = try medication(c, minutes: 30)-        let client = WakeNotifications(); var now = date()-        try WakeService(context: c).record(at: now, receivedAt: now, calendar: calendar)-        let reminders = ReminderService(context: c, notifications: client, now: { now })-        reminders.refresh(); await reminders.waitForRefresh(); #expect(client.requests.count == 1)-        now = now.addingTimeInterval(60)-        let schedule = ScheduleService(context: c, now: { now }, calendar: calendar)-        try schedule.configure(med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: true)-        reminders.refresh(); await reminders.waitForRefresh(); #expect(client.requests.isEmpty)-        try schedule.configure(med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: false)-        try schedule.configure(med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: true)-        #expect(try reminders.plan(now: now).isEmpty)-        now = date(6, 8); try WakeService(context: c).record(at: now, receivedAt: now, calendar: calendar)-        reminders.refresh(); await reminders.waitForRefresh(); #expect(client.requests.count == 1)+    let reopened = try ModelContainer(for: AppEnvironment.schema, configurations: [config])+    let event = try #require(reopened.mainContext.fetch(FetchDescriptor<WakeEvent>()).first)+    #expect(event.id == eventID && event.timestamp == date() && event.sourceRaw == "shortcut")+    let med = try #require(reopened.mainContext.fetch(FetchDescriptor<Medication>()).first)+    #expect(med.wakeOffsetMinutes == 35)+  }+  @Test func zeroSchedulesOnceAndRepeatedInvocationCannotCancelPendingOrReplayAfterDismissal()+    async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    _ = try medication(context, minutes: 0)+    let now = date()+    let client = WakeNotifications()+    let state = defaults()+    try await WakeIntentExecution.record(+      profileID: ProfileIdentity.me, at: now, context: context, notifications: client, defaults: state,+      now: { now })+    #expect(client.added.count == 1 && client.requests.count == 1)+    try await WakeIntentExecution.record(+      profileID: ProfileIdentity.me, at: now.addingTimeInterval(2), context: context,+      notifications: client, defaults: state, now: { now.addingTimeInterval(2) })+    #expect(client.added.count == 1 && client.requests.count == 1)+    client.requests = []  // System delivered/dismissed it; no fabricated replay on relaunch.+    let reopened = ReminderService(+      context: context, notifications: client, wakeReceiptDefaults: state,+      now: { now.addingTimeInterval(3) })+    reopened.refresh()+    await reopened.waitForRefresh()+    #expect(client.added.count == 1 && client.requests.isEmpty)+  }+  @Test(arguments: [0, 15]) func explicitSnoozeSurvivesElapsedWakeAndRelaunch(minutes: Int)+    async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    _ = try medication(context, minutes: minutes)+    let client = WakeNotifications()+    let state = defaults()+    let snoozes = defaults()+    var now = date()+    try WakeService(context: context).record(at: now, receivedAt: now, calendar: calendar)+    let service = ReminderService(+      context: context, notifications: client, snoozeDefaults: snoozes, wakeReceiptDefaults: state,+      now: { now })+    service.refresh()+    await service.waitForRefresh()+    let original = try payload(#require(client.added.first))+    now = date().addingTimeInterval(Double(minutes) * 60 + 5)+    client.requests = []+    await service.respond(original, action: "SNOOZE")+    let snoozed = try payload(#require(client.requests.first))+    #expect(snoozed.deliveryAt == now.addingTimeInterval(900))+    let additions = client.added.count+    await service.respond(original, action: "SNOOZE")+    let reopened = ReminderService(+      context: context, notifications: client, snoozeDefaults: snoozes, wakeReceiptDefaults: state,+      now: { now.addingTimeInterval(10) })+    reopened.refresh()+    await reopened.waitForRefresh()+    let persisted = try payload(#require(client.requests.first))+    #expect(client.added.count == additions && persisted == snoozed)+  }+  @Test func missingWakeAndLatePositiveOffsetDoNotGenerateCatchupSpam() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    _ = try medication(context, minutes: 15)+    let client = WakeNotifications()+    let now = date().addingTimeInterval(16 * 60)+    let service = ReminderService(context: context, notifications: client, now: { now })+    service.refresh()+    await service.waitForRefresh()+    #expect(client.added.isEmpty)+    try WakeService(context: context).record(at: date(), receivedAt: now, calendar: calendar)+    service.refresh()+    await service.waitForRefresh()+    service.refresh()+    await service.waitForRefresh()+    #expect(client.added.isEmpty)+  }+  @Test func positiveOffsetKeepsExactElapsedDeadlineAcrossNewDayAndWake() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let med = try medication(context, minutes: 1440)+    let wakes = WakeService(context: context)+    let first = try wakes.record(at: date(5, 8), receivedAt: date(5, 8), calendar: calendar)+    let second = try wakes.record(at: date(6, 7), receivedAt: date(6, 7), calendar: calendar)+    let plan = try ReminderService(context: context).plan(now: date(6, 7))+    let original = try #require(plan.first { $0.wakeEventID == first.id })+    #expect(original.deliveryAt == first.timestamp.addingTimeInterval(86400))+    #expect(plan.contains { $0.wakeEventID == second.id })+    guard case .medication(var action) = original.payload else {+      Issue.record("Expected medication action")+      return     }-    @Test func profileWakeAndCapturedDoseCannotCrossProfilesOrArchive() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let a = try ProfileService(context: c).create(displayName: "Same name"), b = try ProfileService(context: c).create(displayName: "Same name")-        let medA = try medication(c, minutes: 15, owner: a.id), medB = try medication(c, minutes: 15, owner: b.id)-        let wake = try WakeService(context: c).record(profileID: a.id, at: date(), receivedAt: date(), calendar: calendar)-        let plan = try ReminderService(context: c).plan(now: date())-        #expect(plan.count == 1 && plan[0].profileID == a.id && plan[0].wakeEventID == wake.id)-        let snapshot = try PhoneCompanionService(context: c).snapshot()-        #expect(snapshot.medications.first { $0.id == medA.id }?.schedule.wakeAnchor?.profileID == a.id)-        guard case .medication(var event) = plan[0].payload else { Issue.record("Expected medication action"); return }-        event.medicationID = medB.id-        #expect(throws: ProfileError.self) { try MedicationService(context: c).record(event) }-        event.profileID = b.id; event.profileLifecycleID = b.lifecycleID-        #expect(throws: ProfileError.self) { try MedicationService(context: c).record(event) }-        #expect(medA.id != medB.id)-        try ProfileService(context: c).setArchived(a, true)-        #expect(throws: ProfileError.self) { try WakeService(context: c).record(profileID: a.id, at: date(), receivedAt: date(), calendar: calendar) }-        #expect(try ReminderService(context: c).plan(now: date()).isEmpty)+    action.timestamp = date(6, 7)+    let event = try MedicationService(context: context).record(action)+    #expect(event.wakeEventID == first.id)+    let snapshot = try ScheduleService(context: context).snapshot(med)+    let actual = ScheduledAdministration(+      id: event.id, medicationID: med.id, timestamp: event.timestamp, mode: .afterWaking,+      generationID: event.scheduleGenerationID, wakeEventID: event.wakeEventID)+    let result = MedicationScheduleEngine().evaluate(+      snapshot, administrations: [actual], now: date(6, 7), calendar: calendar)+    #expect(result.remainingToday == 1 && result.next == second.timestamp.addingTimeInterval(86400))+  }+  @Test func editCancellationAndReenableWaitForNextWake() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let med = try medication(context, minutes: 30)+    let client = WakeNotifications()+    var now = date()+    try WakeService(context: context).record(at: now, receivedAt: now, calendar: calendar)+    let reminders = ReminderService(context: context, notifications: client, now: { now })+    reminders.refresh()+    await reminders.waitForRefresh()+    #expect(client.requests.count == 1)+    now = now.addingTimeInterval(60)+    let schedule = ScheduleService(context: context, now: { now }, calendar: calendar)+    try schedule.configure(+      med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: true)+    reminders.refresh()+    await reminders.waitForRefresh()+    #expect(client.requests.isEmpty)+    try schedule.configure(+      med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: false)+    try schedule.configure(+      med, draft: .init(mode: .afterWaking, wakeOffsetMinutes: 45), reminders: true)+    #expect(try reminders.plan(now: now).isEmpty)+    now = date(6, 8)+    try WakeService(context: context).record(at: now, receivedAt: now, calendar: calendar)+    reminders.refresh()+    await reminders.waitForRefresh()+    #expect(client.requests.count == 1)+  }+  @Test func profileWakeAndCapturedDoseCannotCrossProfilesOrArchive() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let firstProfile = try ProfileService(context: context).create(displayName: "Same name")+    let secondProfile = try ProfileService(context: context).create(displayName: "Same name")+    let medA = try medication(context, minutes: 15, owner: firstProfile.id)+    let medB = try medication(context, minutes: 15, owner: secondProfile.id)+    let wake = try WakeService(context: context).record(+      profileID: firstProfile.id, at: date(), receivedAt: date(), calendar: calendar)+    let plan = try ReminderService(context: context).plan(now: date())+    #expect(plan.count == 1 && plan[0].profileID == firstProfile.id && plan[0].wakeEventID == wake.id)+    let snapshot = try PhoneCompanionService(context: context).snapshot()+    #expect(snapshot.medications.first { $0.id == medA.id }?.schedule.wakeAnchor?.profileID == firstProfile.id)+    guard case .medication(var event) = plan[0].payload else {+      Issue.record("Expected medication action")+      return     }-    @Test func restoreNeedsExplicitFreshWakeWithoutDeletingPriorAnchor() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let profile = try ProfileService(context: c).create(displayName: "Synthetic dependant")-        let med = try medication(c, minutes: 15, owner: profile.id)-        let wakes = WakeService(context: c), profiles = ProfileService(context: c)-        let old = try wakes.record(profileID: profile.id, at: date(), receivedAt: date(), calendar: calendar)-        try profiles.setArchived(profile, true); try profiles.setArchived(profile, false)-        #expect(try wakes.anchor(profileID: profile.id) == nil)-        #expect(try ReminderService(context: c).plan(now: date()).isEmpty)-        let fresh = try wakes.record(profileID: profile.id, at: date().addingTimeInterval(60), receivedAt: date().addingTimeInterval(60), calendar: calendar)-        #expect(fresh.id != old.id && med.profileID == profile.id)-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 2)-        #expect(try wakes.anchors(profileID: profile.id).map(\.id) == [fresh.id])+    event.medicationID = medB.id+    #expect(throws: ProfileError.self) { try MedicationService(context: context).record(event) }+    event.profileID = secondProfile.id+    event.profileLifecycleID = secondProfile.lifecycleID+    #expect(throws: ProfileError.self) { try MedicationService(context: context).record(event) }+    #expect(medA.id != medB.id)+    try ProfileService(context: context).setArchived(firstProfile, true)+    #expect(throws: ProfileError.self) {+      try WakeService(context: context).record(+        profileID: firstProfile.id, at: date(), receivedAt: date(), calendar: calendar)     }-    @Test func routineWakeSlotUsesCapturedAnchorAndOneCanonicalSavedSession() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let treatment = try TreatmentService(context: c).create(name: "Synthetic care")-        let routine = try RoutineService(context: c).createOrdered(name: "Synthetic routine", steps: [.init(kind: .treatment, targetID: treatment.id)])-        let schedule = ScheduleService(context: c, now: { self.date(5, 1, 58) }, calendar: calendar)-        try schedule.configure(routine, slots: [.init(label: "Synthetic wake cue", wakeOffsetMinutes: 35)], reminders: true)-        let wake = try WakeService(context: c).record(at: date(5, 1, 59), receivedAt: date(5, 1, 59), calendar: calendar)-        let snapshot = try schedule.snapshot(routine)-        let occurrence = try #require(RoutineScheduleEngine().occurrences(snapshot, runs: [], day: date(5, 2, 10), now: date(5, 2, 10), calendar: calendar).first)-        #expect(occurrence.scheduledAt == wake.timestamp.addingTimeInterval(35 * 60) && occurrence.localDate == "2026-01-04")-        #expect(occurrence.wakeEventID == wake.id)-        let run = try schedule.startOccurrence(occurrence, routine: routine)-        #expect(try schedule.startOccurrence(occurrence, routine: routine).id == run.id)-        #expect(run.scheduledAt == occurrence.scheduledAt && run.scheduledLocalDate == occurrence.localDate)+    #expect(try ReminderService(context: context).plan(now: date()).isEmpty)+  }+  @Test func restoreNeedsExplicitFreshWakeWithoutDeletingPriorAnchor() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let profile = try ProfileService(context: context).create(displayName: "Synthetic dependant")+    let med = try medication(context, minutes: 15, owner: profile.id)+    let wakes = WakeService(context: context)+    let profiles = ProfileService(context: context)+    let old = try wakes.record(+      profileID: profile.id, at: date(), receivedAt: date(), calendar: calendar)+    try profiles.setArchived(profile, true)+    try profiles.setArchived(profile, false)+    #expect(try wakes.anchor(profileID: profile.id) == nil)+    #expect(try ReminderService(context: context).plan(now: date()).isEmpty)+    let fresh = try wakes.record(+      profileID: profile.id, at: date().addingTimeInterval(60),+      receivedAt: date().addingTimeInterval(60), calendar: calendar)+    #expect(fresh.id != old.id && med.profileID == profile.id)+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 2)+    #expect(try wakes.anchors(profileID: profile.id).map(\.id) == [fresh.id])+  }+  @Test func routineWakeSlotUsesCapturedAnchorAndOneCanonicalSavedSession() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let treatment = try TreatmentService(context: context).create(name: "Synthetic care")+    let routine = try RoutineService(context: context).createOrdered(+      name: "Synthetic routine", steps: [.init(kind: .treatment, targetID: treatment.id)])+    let schedule = ScheduleService(context: context, now: { self.date(5, 1, 58) }, calendar: calendar)+    try schedule.configure(+      routine, slots: [.init(label: "Synthetic wake cue", wakeOffsetMinutes: 35)], reminders: true)+    let wake = try WakeService(context: context).record(+      at: date(5, 1, 59), receivedAt: date(5, 1, 59), calendar: calendar)+    let snapshot = try schedule.snapshot(routine)+    let occurrence = try #require(+      RoutineScheduleEngine().occurrences(+        snapshot, runs: [], day: date(5, 2, 10), now: date(5, 2, 10), calendar: calendar+      ).first)+    #expect(+      occurrence.scheduledAt == wake.timestamp.addingTimeInterval(35 * 60)+        && occurrence.localDate == "2026-01-04")+    #expect(occurrence.wakeEventID == wake.id)+    let run = try schedule.startOccurrence(occurrence, routine: routine)+    #expect(try schedule.startOccurrence(occurrence, routine: routine).id == run.id)+    #expect(+      run.scheduledAt == occurrence.scheduledAt && run.scheduledLocalDate == occurrence.localDate)+  }+  @Test func intentDefaultsMeAndExplicitStableEntitySurvivesRenameButRejectsUnknownAndArchived()+    async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    let context = container.mainContext+    WakeIntentExecution.testContainer = container+    defer { WakeIntentExecution.testContainer = nil }+    let dep = try ProfileService(context: context).create(displayName: "Synthetic before")+    let intent = RecordWakingUpIntent()+    _ = try await intent.perform()+    #expect(try context.fetch(FetchDescriptor<WakeEvent>()).first?.profileID == ProfileIdentity.me)+    intent.profile = .init(id: dep.id, label: "Synthetic before")+    try ProfileService(context: context).rename(dep, displayName: "Synthetic after")+    _ = try await intent.perform()+    let resolved = try await WakeProfileQuery().entities(for: [dep.id])+    #expect(resolved[0].id == dep.id && resolved[0].label.contains("Synthetic after"))+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 2)+    intent.profile = .init(id: UUID(), label: "Unknown")+    await #expect(throws: ProfileError.self) { try await intent.perform() }+    try ProfileService(context: context).setArchived(dep, true)+    intent.profile = .init(id: dep.id, label: "Synthetic after")+    await #expect(throws: ProfileError.self) { try await intent.perform() }+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 2)+    #expect(+      RecordWakingUpIntent.supportedModes == .background+        && RecordWakingUpIntent.authenticationPolicy == .alwaysAllowed)+  }+  @Test func intentAwaitsSchedulingAndPropagatesAddFailureAfterSavingWake() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    _ = try medication(context, minutes: 15)+    let client = WakeNotifications()+    client.fail = true+    await #expect(throws: WakeIntentFailure.self) {+      try await WakeIntentExecution.record(+        profileID: ProfileIdentity.me, at: date(), context: context, notifications: client,+        now: { self.date() })     }-    @Test func intentDefaultsMeAndExplicitStableEntitySurvivesRenameButRejectsUnknownAndArchived() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true), c = container.mainContext-        WakeIntentExecution.testContainer = container; defer { WakeIntentExecution.testContainer = nil }-        let dep = try ProfileService(context: c).create(displayName: "Synthetic before")-        let intent = RecordWakingUpIntent(); _ = try await intent.perform()-        #expect(try c.fetch(FetchDescriptor<WakeEvent>()).first?.profileID == ProfileIdentity.me)-        intent.profile = .init(id: dep.id, label: "Synthetic before")-        try ProfileService(context: c).rename(dep, displayName: "Synthetic after")-        _ = try await intent.perform()-        let resolved = try await WakeProfileQuery().entities(for: [dep.id])-        #expect(resolved[0].id == dep.id && resolved[0].label.contains("Synthetic after"))-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 2)-        intent.profile = .init(id: UUID(), label: "Unknown")-        await #expect(throws: ProfileError.self) { try await intent.perform() }-        try ProfileService(context: c).setArchived(dep, true); intent.profile = .init(id: dep.id, label: "Synthetic after")-        await #expect(throws: ProfileError.self) { try await intent.perform() }-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 2)-        #expect(RecordWakingUpIntent.supportedModes == .background && RecordWakingUpIntent.authenticationPolicy == .alwaysAllowed)+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 1 && client.added.isEmpty)+    client.fail = false+    try await WakeIntentExecution.record(+      profileID: ProfileIdentity.me, at: date(), context: context, notifications: client,+      now: { self.date() })+    #expect(client.added.count == 1)+    client.status = .denied+    client.requests = []+    try await WakeIntentExecution.record(+      profileID: ProfileIdentity.me, at: date(), context: context, notifications: client,+      now: { self.date() })+    #expect(try context.fetchCount(FetchDescriptor<WakeEvent>()) == 1 && client.requests.isEmpty)+  }+  @Test func offlineNilWakeAndBeforeWakeHistoryRemainActualButDoNotSatisfyNewWake() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let med = try medication(context, minutes: 15)+    let timestamp = date().addingTimeInterval(-60)+    let watch = AdministrationAction(+      eventID: UUID(), medicationID: med.id, timestamp: timestamp, source: .watch, dose: .unknown,+      scheduleTypeAtRecording: .afterWaking, scheduleGenerationID: med.scheduleGenerationID)+    let wake = try WakeService(context: context).record(+      at: date(), receivedAt: date(), calendar: calendar)+    let imported = try MedicationService(context: context).record(watch)+    let history = try MedicationService(context: context).record(+      .init(+        eventID: UUID(), medicationID: med.id, timestamp: timestamp, source: .manualHistory,+        dose: .unknown, scheduleTypeAtRecording: .afterWaking,+        scheduleGenerationID: med.scheduleGenerationID))+    #expect(imported.wakeEventID == nil && history.wakeEventID == nil)+    var explicit = watch+    explicit.eventID = UUID()+    explicit.wakeEventID = wake.id+    let early = try MedicationService(context: context).record(explicit)+    let values = [imported, history, early].map {+      ScheduledAdministration(+        id: $0.id, medicationID: med.id, timestamp: $0.timestamp, mode: .afterWaking,+        generationID: $0.scheduleGenerationID, wakeEventID: $0.wakeEventID)     }-    @Test func intentAwaitsSchedulingAndPropagatesAddFailureAfterSavingWake() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; _ = try medication(c, minutes: 15)-        let client = WakeNotifications(); client.fail = true-        await #expect(throws: WakeIntentFailure.self) { try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: date(), context: c, notifications: client, now: { self.date() }) }-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 1 && client.added.isEmpty)-        client.fail = false-        try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: date(), context: c, notifications: client, now: { self.date() })-        #expect(client.added.count == 1)-        client.status = .denied; client.requests = []-        try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: date(), context: c, notifications: client, now: { self.date() })-        #expect(try c.fetchCount(FetchDescriptor<WakeEvent>()) == 1 && client.requests.isEmpty)+    let snapshot = try ScheduleService(context: context).snapshot(med)+    #expect(+      MedicationScheduleEngine().evaluate(+        snapshot, administrations: values, now: date(), calendar: calendar+      ).remainingToday == 1)+    #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 3)+  }+  @Test func forgedWakeOccurrenceTupleAndForeignExistingRunAreRejected() throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let treatment = try TreatmentService(context: context).create(name: "Synthetic")+    let routine = try RoutineService(context: context).createOrdered(+      name: "Synthetic", steps: [.init(kind: .treatment, targetID: treatment.id)])+    let schedule = ScheduleService(context: context, now: { self.date() }, calendar: calendar)+    try schedule.configure(routine, slots: [.init(wakeOffsetMinutes: 15)], reminders: true)+    try WakeService(context: context).record(at: date(), receivedAt: date(), calendar: calendar)+    let occurrence = try #require(+      RoutineScheduleEngine().occurrences(+        schedule.snapshot(routine), runs: [], day: date(), now: date(), calendar: calendar+      ).first)+    var forged = occurrence+    forged.scheduledAt = occurrence.scheduledAt?.addingTimeInterval(1)+    #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }+    forged = occurrence+    forged.id = UUID()+    #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }+    forged = occurrence+    forged.wakeEventID = nil+    #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }+    let profile = try ProfileService(context: context).create(displayName: "Synthetic other")+    let timer = try RoutineService(context: context).createTimed(+      name: "Synthetic other", rounds: 1, durationSeconds: 30, profileID: profile.id)+    let foreign = try RoutineSessionService(context: context).start(timer)+    forged = occurrence+    forged.id = foreign.id+    #expect(throws: ProfileError.self) { try schedule.startOccurrence(forged, routine: routine) }+    #expect(try context.fetchCount(FetchDescriptor<RoutineRun>()) == 1)+  }+  @Test func coldBackgroundIntentPreservesPhoneOwnedTimerReminder() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let timer = try RoutineService(context: context).createTimed(+      name: "Synthetic timer", rounds: 1, durationSeconds: 600)+    let sessions = RoutineSessionService(context: context, now: { self.date() })+    let run = try sessions.start(timer, deviceID: "synthetic-phone")+    try sessions.changeTimer(+      run, actionID: UUID(), clock: .init(wall: date(), monotonic: 0, continuityID: "synthetic"),+      operation: .start)+    let client = WakeNotifications()+    let old = ReminderService(context: context, notifications: client, now: { self.date() })+    old.localDeviceID = "synthetic-phone"+    old.refresh()+    await old.waitForRefresh()+    let id = try #require(client.requests.first?.identifier)+    try await WakeIntentExecution.record(+      profileID: ProfileIdentity.me, at: date(), context: context, notifications: client,+      localDeviceID: "synthetic-phone", now: { self.date() })+    #expect(client.requests.contains { $0.identifier == id })+    #expect(run.executionDeviceID == "synthetic-phone")+  }+  @Test func intentReturnWaitsUntilNotificationAddCompletes() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    _ = try medication(context, minutes: 15)+    let client = WakeNotifications()+    client.suspendAdd = true+    var finished = false+    let task = Task { @MainActor in+      try await WakeIntentExecution.record(+        profileID: ProfileIdentity.me, at: date(), context: context, notifications: client,+        now: { self.date() })+      finished = true     }-    @Test func offlineNilWakeAndBeforeWakeHistoryRemainActualButDoNotSatisfyNewWake() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; let med = try medication(c, minutes: 15)-        let timestamp = date().addingTimeInterval(-60)-        let watch = AdministrationAction(eventID: UUID(), medicationID: med.id, timestamp: timestamp, source: .watch, dose: .unknown, scheduleTypeAtRecording: .afterWaking, scheduleGenerationID: med.scheduleGenerationID)-        let wake = try WakeService(context: c).record(at: date(), receivedAt: date(), calendar: calendar)-        let imported = try MedicationService(context: c).record(watch)-        let history = try MedicationService(context: c).record(.init(eventID: UUID(), medicationID: med.id, timestamp: timestamp, source: .manualHistory, dose: .unknown, scheduleTypeAtRecording: .afterWaking, scheduleGenerationID: med.scheduleGenerationID))-        #expect(imported.wakeEventID == nil && history.wakeEventID == nil)-        var explicit = watch; explicit.eventID = UUID(); explicit.wakeEventID = wake.id-        let early = try MedicationService(context: c).record(explicit)-        let values = [imported, history, early].map { ScheduledAdministration(id: $0.id, medicationID: med.id, timestamp: $0.timestamp, mode: .afterWaking, generationID: $0.scheduleGenerationID, wakeEventID: $0.wakeEventID) }-        let snapshot = try ScheduleService(context: c).snapshot(med)-        #expect(MedicationScheduleEngine().evaluate(snapshot, administrations: values, now: date(), calendar: calendar).remainingToday == 1)-        #expect(try c.fetchCount(FetchDescriptor<Administration>()) == 3)-    }-    @Test func forgedWakeOccurrenceTupleAndForeignExistingRunAreRejected() throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let treatment = try TreatmentService(context: c).create(name: "Synthetic")-        let routine = try RoutineService(context: c).createOrdered(name: "Synthetic", steps: [.init(kind: .treatment, targetID: treatment.id)])-        let schedule = ScheduleService(context: c, now: { self.date() }, calendar: calendar)-        try schedule.configure(routine, slots: [.init(wakeOffsetMinutes: 15)], reminders: true)-        try WakeService(context: c).record(at: date(), receivedAt: date(), calendar: calendar)-        let occurrence = try #require(RoutineScheduleEngine().occurrences(schedule.snapshot(routine), runs: [], day: date(), now: date(), calendar: calendar).first)-        var forged = occurrence; forged.scheduledAt = occurrence.scheduledAt?.addingTimeInterval(1)-        #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }-        forged = occurrence; forged.id = UUID()-        #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }-        forged = occurrence; forged.wakeEventID = nil-        #expect(throws: DefinitionError.self) { try schedule.startOccurrence(forged, routine: routine) }-        let profile = try ProfileService(context: c).create(displayName: "Synthetic other")-        let timer = try RoutineService(context: c).createTimed(name: "Synthetic other", rounds: 1, durationSeconds: 30, profileID: profile.id)-        let foreign = try RoutineSessionService(context: c).start(timer)-        forged = occurrence; forged.id = foreign.id-        #expect(throws: ProfileError.self) { try schedule.startOccurrence(forged, routine: routine) }-        #expect(try c.fetchCount(FetchDescriptor<RoutineRun>()) == 1)-    }-    @Test func coldBackgroundIntentPreservesPhoneOwnedTimerReminder() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let timer = try RoutineService(context: c).createTimed(name: "Synthetic timer", rounds: 1, durationSeconds: 600)-        let sessions = RoutineSessionService(context: c, now: { self.date() })-        let run = try sessions.start(timer, deviceID: "synthetic-phone")-        try sessions.changeTimer(run, actionID: UUID(), clock: .init(wall: date(), monotonic: 0, continuityID: "synthetic"), operation: .start)-        let client = WakeNotifications()-        let old = ReminderService(context: c, notifications: client, now: { self.date() }); old.localDeviceID = "synthetic-phone"-        old.refresh(); await old.waitForRefresh()-        let id = try #require(client.requests.first?.identifier)-        try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: date(), context: c, notifications: client, localDeviceID: "synthetic-phone", now: { self.date() })-        #expect(client.requests.contains { $0.identifier == id })-        #expect(run.executionDeviceID == "synthetic-phone")-    }-    @Test func intentReturnWaitsUntilNotificationAddCompletes() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext; _ = try medication(c, minutes: 15)-        let client = WakeNotifications(); client.suspendAdd = true; var finished = false-        let task = Task { @MainActor in-            try await WakeIntentExecution.record(profileID: ProfileIdentity.me, at: date(), context: c, notifications: client, now: { self.date() })-            finished = true-        }-        for _ in 0..<1000 { if client.continuation != nil { break }; await Task.yield() }-        #expect(client.continuation != nil && !finished)-        client.continuation?.resume(); client.continuation = nil-        try await task.value-        #expect(finished && client.added.count == 1)-    }-    @Test func snoozedPreviousWakeSurvivesAnotherLogicalDayWake() async throws {-        let container = try AppEnvironment.makeContainer(isolated: true); defer { withExtendedLifetime(container) {} }; let c = container.mainContext-        let firstTime = date(5, 1, 59); _ = try medication(c, minutes: 0, start: firstTime)-        let client = WakeNotifications(); var now = firstTime-        let wake = WakeService(context: c); let first = try wake.record(at: now, receivedAt: now, calendar: calendar)-        let reminders = ReminderService(context: c, notifications: client, now: { now })-        reminders.refresh(); await reminders.waitForRefresh()-        let original = try payload(#require(client.added.first))-        now = now.addingTimeInterval(5); await reminders.respond(original, action: "SNOOZE")-        let deadline = now.addingTimeInterval(900)-        now = date(5, 2, 1); try wake.record(at: now, receivedAt: now, calendar: calendar)-        reminders.refresh(); await reminders.waitForRefresh()-        let saved = try payload(#require(client.requests.first { request in (try? payload(request).wakeEventID) == first.id }))-        #expect(saved.deliveryAt == deadline && saved.wakeEventID == first.id)-        #expect(client.requests.count == 2)-    }-    @Test func offsetBoundsAndDSTUseElapsedSeconds() throws {-        #expect(WakeTiming.valid(0) && WakeTiming.valid(1440) && !WakeTiming.valid(-1) && !WakeTiming.valid(1441))-        var zone = calendar; zone.timeZone = TimeZone(identifier: "America/New_York")!-        let beforeSpringJump = ISO8601DateFormatter().date(from: "2026-03-08T06:30:00Z")!-        let wake = WakeAnchor(id: UUID(), timestamp: beforeSpringJump, recordedAt: beforeSpringJump, localDate: ScheduleCalendar.localDate(beforeSpringJump, calendar: zone), timeZoneID: zone.timeZone.identifier)-        let due = try #require(WakeTiming.date(wake, minutes: 120, startedAt: beforeSpringJump))-        #expect(zone.component(.hour, from: beforeSpringJump) == 1 && zone.component(.hour, from: due) == 4)-        #expect(due.timeIntervalSince(beforeSpringJump) == 7200 && wake.localDate == "2026-03-07")-        #expect(WakeTiming.date(wake, minutes: 15, startedAt: beforeSpringJump.addingTimeInterval(1)) == nil)+    for _ in 0..<1000 {+      if client.continuation != nil { break }+      await Task.yield()     }+    #expect(client.continuation != nil && !finished)+    client.continuation?.resume()+    client.continuation = nil+    try await task.value+    #expect(finished && client.added.count == 1)+  }+  @Test func snoozedPreviousWakeSurvivesAnotherLogicalDayWake() async throws {+    let container = try AppEnvironment.makeContainer(isolated: true)+    defer { withExtendedLifetime(container) {} }+    let context = container.mainContext+    let firstTime = date(5, 1, 59)+    _ = try medication(context, minutes: 0, start: firstTime)+    let client = WakeNotifications()+    var now = firstTime+    let wake = WakeService(context: context)+    let first = try wake.record(at: now, receivedAt: now, calendar: calendar)+    let reminders = ReminderService(context: context, notifications: client, now: { now })+    reminders.refresh()+    await reminders.waitForRefresh()+    let original = try payload(#require(client.added.first))+    now = now.addingTimeInterval(5)+    await reminders.respond(original, action: "SNOOZE")+    let deadline = now.addingTimeInterval(900)+    now = date(5, 2, 1)+    try wake.record(at: now, receivedAt: now, calendar: calendar)+    reminders.refresh()+    await reminders.waitForRefresh()+    let saved = try payload(+      #require(client.requests.first { request in (try? payload(request).wakeEventID) == first.id })+    )+    #expect(saved.deliveryAt == deadline && saved.wakeEventID == first.id)+    #expect(client.requests.count == 2)+  }+  @Test func offsetBoundsAndDSTUseElapsedSeconds() throws {+    #expect(+      WakeTiming.valid(0) && WakeTiming.valid(1440) && !WakeTiming.valid(-1)+        && !WakeTiming.valid(1441))+    var zone = calendar+    zone.timeZone = TimeZone(identifier: "America/New_York")!+    let beforeSpringJump = ISO8601DateFormatter().date(from: "2026-03-08T06:30:00Z")!+    let wake = WakeAnchor(+      id: UUID(), timestamp: beforeSpringJump, recordedAt: beforeSpringJump,+      localDate: ScheduleCalendar.localDate(beforeSpringJump, calendar: zone),+      timeZoneID: zone.timeZone.identifier)+    let due = try #require(WakeTiming.date(wake, minutes: 120, startedAt: beforeSpringJump))+    #expect(+      zone.component(.hour, from: beforeSpringJump) == 1 && zone.component(.hour, from: due) == 4)+    #expect(due.timeIntervalSince(beforeSpringJump) == 7200 && wake.localDate == "2026-03-07")+    #expect(+      WakeTiming.date(wake, minutes: 15, startedAt: beforeSpringJump.addingTimeInterval(1)) == nil)+  } }  @MainActor private final class WakeNotifications: ReminderNotificationClient {-    var status: UNAuthorizationStatus = .authorized-    var requests: [UNNotificationRequest] = [], added: [UNNotificationRequest] = []-    var suspendAdd = false-    var continuation: CheckedContinuation<Void, Never>?-    var fail = false-    func authorization() async -> UNAuthorizationStatus { status }-    func pending() async -> [UNNotificationRequest] { requests }-    func delivered() async -> [UNNotification] { [] }-    func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }-    func removeDelivered(_ ids: [String]) {}-    func add(_ request: UNNotificationRequest) async throws {-        if suspendAdd { await withCheckedContinuation { continuation = $0 } }-        if fail { throw NSError(domain: "SyntheticWakeScheduling", code: 1) }-        added.append(request); requests.removeAll { $0.identifier == request.identifier }; requests.append(request)-    }+  var status: UNAuthorizationStatus = .authorized+  var requests: [UNNotificationRequest] = [], added: [UNNotificationRequest] = []+  var suspendAdd = false+  var continuation: CheckedContinuation<Void, Never>?+  var fail = false+  func authorization() async -> UNAuthorizationStatus { status }+  func pending() async -> [UNNotificationRequest] { requests }+  func delivered() async -> [UNNotification] { [] }+  func removePending(_ ids: [String]) { requests.removeAll { ids.contains($0.identifier) } }+  func removeDelivered(_ ids: [String]) {}+  func add(_ request: UNNotificationRequest) async throws {+    if suspendAdd { await withCheckedContinuation { continuation = $0 } }+    if fail { throw NSError(domain: "SyntheticWakeScheduling", code: 1) }+    added.append(request)+    requests.removeAll { $0.identifier == request.identifier }+    requests.append(request)+  } }
Meddy/MeddyUITests/MeddyEditorUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyEditorUITests.swift b/Meddy/MeddyUITests/MeddyEditorUITests.swiftindex 8c08eac..5e73a55 100644--- a/Meddy/MeddyUITests/MeddyEditorUITests.swift+++ b/Meddy/MeddyUITests/MeddyEditorUITests.swift@@ -2,54 +2,59 @@ import XCTest  @MainActor final class MeddyEditorUITests: XCTestCase {-    func testEditorsDismissKeyboardWithoutSavingAndKeepExplicitSaveAndCancel() {-        continueAfterFailure = false-        let app = XCUIApplication()-        app.launchEnvironment["MEDDY_TESTING"] = "1"-        app.launch()-        XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8))+  func testEditorsDismissKeyboardWithoutSavingAndKeepExplicitSaveAndCancel() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8)) -        for kind in ["Medication", "Treatment item", "Timed routine", "Ordered routine"] {-            if kind == "Medication" {-                app.tabBars.buttons["Today"].tap()-                app.buttons["Add as-needed medication"].tap()-            } else {-                app.tabBars.buttons["Routines"].tap()-                app.buttons["Add care item"].tap()-                app.buttons[kind].tap()-            }-            let name = app.textFields["Name"]-            XCTAssertTrue(name.waitForExistence(timeout: 4))-            name.tap(); name.typeText("Synthetic cancelled " + kind)-            XCTAssertTrue(app.keyboards.firstMatch.exists)-            XCTAssertFalse(app.buttons["Done editing"].exists)-            // Scroll the form, then return to the draft; dismissing the keyboard must not save or close it.-            let form = app.collectionViews.element(boundBy: app.collectionViews.count - 1)-            form.swipeUp()-            form.swipeDown()-            XCTAssertEqual(name.value as? String, "Synthetic cancelled " + kind)-            XCTAssertTrue(app.buttons["Save"].isHittable)-            XCTAssertTrue(app.buttons["Cancel"].isHittable)-            app.buttons["Cancel"].tap()-            XCTAssertFalse(app.staticTexts["Synthetic cancelled " + kind].exists)-        }--        app.buttons["Add care item"].tap(); app.buttons["Treatment item"].tap()-        let name = app.textFields["Name"]-        XCTAssertTrue(name.waitForExistence(timeout: 4))-        name.tap(); name.typeText("Synthetic saved treatment")-        // Save remains usable while text entry is active.-        app.buttons["Save"].tap()-        let treatment = app.buttons["Synthetic saved treatment"]-        XCTAssertTrue(treatment.waitForExistence(timeout: 4))-        treatment.tap(); app.buttons["Edit"].tap()-        XCTAssertTrue(name.waitForExistence(timeout: 4))-        XCTAssertEqual(name.value as? String, "Synthetic saved treatment")-        name.tap(); name.typeText(" discarded")-        app.buttons["Cancel"].tap()-        app.buttons["Edit"].tap()-        XCTAssertTrue(name.waitForExistence(timeout: 4))-        XCTAssertEqual(name.value as? String, "Synthetic saved treatment")-        app.buttons["Cancel"].tap()+    for kind in ["Medication", "Treatment item", "Timed routine", "Ordered routine"] {+      if kind == "Medication" {+        app.tabBars.buttons["Today"].tap()+        app.buttons["Add as-needed medication"].tap()+      } else {+        app.tabBars.buttons["Routines"].tap()+        app.buttons["Add care item"].tap()+        app.buttons[kind].tap()+      }+      let name = app.textFields["Name"]+      XCTAssertTrue(name.waitForExistence(timeout: 4))+      name.tap()+      name.typeText("Synthetic cancelled " + kind)+      XCTAssertTrue(app.keyboards.firstMatch.exists)+      XCTAssertFalse(app.buttons["Done editing"].exists)+      // Scroll the form, then return to the draft; dismissing the keyboard must not save or close it.+      let form = app.collectionViews.element(boundBy: app.collectionViews.count - 1)+      form.swipeUp()+      form.swipeDown()+      XCTAssertEqual(name.value as? String, "Synthetic cancelled " + kind)+      XCTAssertTrue(app.buttons["Save"].isHittable)+      XCTAssertTrue(app.buttons["Cancel"].isHittable)+      app.buttons["Cancel"].tap()+      XCTAssertFalse(app.staticTexts["Synthetic cancelled " + kind].exists)     }++    app.buttons["Add care item"].tap()+    app.buttons["Treatment item"].tap()+    let name = app.textFields["Name"]+    XCTAssertTrue(name.waitForExistence(timeout: 4))+    name.tap()+    name.typeText("Synthetic saved treatment")+    // Save remains usable while text entry is active.+    app.buttons["Save"].tap()+    let treatment = app.buttons["Synthetic saved treatment"]+    XCTAssertTrue(treatment.waitForExistence(timeout: 4))+    treatment.tap()+    app.buttons["Edit"].tap()+    XCTAssertTrue(name.waitForExistence(timeout: 4))+    XCTAssertEqual(name.value as? String, "Synthetic saved treatment")+    name.tap()+    name.typeText(" discarded")+    app.buttons["Cancel"].tap()+    app.buttons["Edit"].tap()+    XCTAssertTrue(name.waitForExistence(timeout: 4))+    XCTAssertEqual(name.value as? String, "Synthetic saved treatment")+    app.buttons["Cancel"].tap()+  } }
Meddy/MeddyUITests/MeddyFirstSliceUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift b/Meddy/MeddyUITests/MeddyFirstSliceUITests.swiftindex ab95e29..371c182 100644--- a/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift+++ b/Meddy/MeddyUITests/MeddyFirstSliceUITests.swift@@ -2,141 +2,182 @@ import XCTest  @MainActor final class MeddyFirstSliceUITests: XCTestCase {-    func testNameOnlyCreationTakenAndUndoWithoutNotificationPermission() {-        let app = XCUIApplication()-        app.launchEnvironment["MEDDY_TESTING"] = "1"-        app.launch()-        XCTAssertTrue(app.tabBars.buttons["Today"].waitForExistence(timeout: 10))-        XCTAssertTrue(app.tabBars.buttons["Medications"].exists)-        XCTAssertTrue(app.tabBars.buttons["Routines"].exists)-        app.buttons["Add as-needed medication"].tap()-        let name = app.textFields["Name"]-        XCTAssertTrue(name.waitForExistence(timeout: 5))-        XCTAssertTrue(app.buttons["Add photo"].exists)-        XCTAssertFalse(app.buttons["Remove photo"].exists)-        name.tap()-        name.typeText("Synthetic UI item")-        if app.keyboards.firstMatch.exists { app.swipeUp() }-        // Tap the menu label; the Form accessibility row extends beyond its control.-        app.staticTexts["Timing option"].tap()-        XCTAssertTrue(app.buttons["Before sleeping"].waitForExistence(timeout: 5))-        app.buttons["Before sleeping"].tap()-        let requirements = app.descendants(matching: .any)["medicationRequirements"]-        XCTAssertEqual(requirements.value as? String, "Before sleeping")-        app.buttons["Save"].tap()-        let taken = app.buttons["Mark Synthetic UI item taken"]-        XCTAssertTrue(taken.waitForExistence(timeout: 5))-        taken.tap()-        let undo = app.buttons["Undo Taken"]-        XCTAssertTrue(undo.waitForExistence(timeout: 5))-        XCTAssertTrue(app.staticTexts["Dose not recorded"].exists)-        undo.tap()-        XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5))-        XCTAssertTrue(taken.exists)-        XCTAssertFalse(app.alerts.firstMatch.exists)-    }-    func testUserFollowupMessageAndDelaySaveWithoutSystemPermissionAndUndoStillWorks() {-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))-        app.buttons["Add as-needed medication"].tap()-        func fill(_ id: String, _ value: String) {-            let field = app.descendants(matching: .any)[id].firstMatch-            for _ in 0..<10 { if field.exists && field.isHittable { break }; app.swipeUp() }-            XCTAssertTrue(field.isHittable, id); field.tap(); field.typeText(value)-            if app.keyboards.firstMatch.exists { app.swipeUp() }-        }-        fill("Name", "Synthetic follow-up UI")-        let toggle = app.switches["followupEnabled"]-        for _ in 0..<10 { if toggle.exists && toggle.isHittable { break }; app.swipeUp() }-        XCTAssertTrue(toggle.isHittable)-        toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()+  func testNameOnlyCreationTakenAndUndoWithoutNotificationPermission() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.tabBars.buttons["Today"].waitForExistence(timeout: 10))+    XCTAssertTrue(app.tabBars.buttons["Medications"].exists)+    XCTAssertTrue(app.tabBars.buttons["Routines"].exists)+    app.buttons["Add as-needed medication"].tap()+    let name = app.textFields["Name"]+    XCTAssertTrue(name.waitForExistence(timeout: 5))+    XCTAssertTrue(app.buttons["Add photo"].exists)+    XCTAssertFalse(app.buttons["Remove photo"].exists)+    name.tap()+    name.typeText("Synthetic UI item")+    if app.keyboards.firstMatch.exists { app.swipeUp() }+    // Tap the menu label; the Form accessibility row extends beyond its control.+    app.staticTexts["Timing option"].tap()+    XCTAssertTrue(app.buttons["Before sleeping"].waitForExistence(timeout: 5))+    app.buttons["Before sleeping"].tap()+    let requirements = app.descendants(matching: .any)["medicationRequirements"]+    XCTAssertEqual(requirements.value as? String, "Before sleeping")+    app.buttons["Save"].tap()+    let taken = app.buttons["Mark Synthetic UI item taken"]+    XCTAssertTrue(taken.waitForExistence(timeout: 5))+    taken.tap()+    let undo = app.buttons["Undo Taken"]+    XCTAssertTrue(undo.waitForExistence(timeout: 5))+    XCTAssertTrue(app.staticTexts["Dose not recorded"].exists)+    undo.tap()+    XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5))+    XCTAssertTrue(taken.exists)+    XCTAssertFalse(app.alerts.firstMatch.exists)+  }+  func testUserFollowupMessageAndDelaySaveWithoutSystemPermissionAndUndoStillWorks() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))+    app.buttons["Add as-needed medication"].tap()+    func fill(_ id: String, _ value: String) {+      let field = app.descendants(matching: .any)[id].firstMatch+      for _ in 0..<10 {+        if field.exists && field.isHittable { break }         app.swipeUp()-        fill("followupMessage", "Synthetic later reminder")-        fill("followupMinutes", "17")-        app.buttons["Save"].tap()-        let taken = app.buttons["Mark Synthetic follow-up UI taken"]-        XCTAssertTrue(taken.waitForExistence(timeout: 5)); taken.tap()-        let undo = app.buttons["Undo Taken"]-        XCTAssertTrue(undo.waitForExistence(timeout: 5)); undo.tap()-        XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5))-        app.tabBars.buttons["Medications"].tap()-        app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic follow-up UI")).firstMatch.tap()-        let message = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@", "Synthetic later reminder")).firstMatch-        for _ in 0..<5 { if message.exists { break }; app.swipeUp() }-        XCTAssertTrue(message.exists)-        XCTAssertFalse(app.alerts.firstMatch.exists)+      }+      XCTAssertTrue(field.isHittable, id)+      field.tap()+      field.typeText(value)+      if app.keyboards.firstMatch.exists { app.swipeUp() }+    }+    fill("Name", "Synthetic follow-up UI")+    let toggle = app.switches["followupEnabled"]+    for _ in 0..<10 {+      if toggle.exists && toggle.isHittable { break }+      app.swipeUp()+    }+    XCTAssertTrue(toggle.isHittable)+    toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()+    app.swipeUp()+    fill("followupMessage", "Synthetic later reminder")+    fill("followupMinutes", "17")+    app.buttons["Save"].tap()+    let taken = app.buttons["Mark Synthetic follow-up UI taken"]+    XCTAssertTrue(taken.waitForExistence(timeout: 5))+    taken.tap()+    let undo = app.buttons["Undo Taken"]+    XCTAssertTrue(undo.waitForExistence(timeout: 5))+    undo.tap()+    XCTAssertTrue(app.staticTexts["Not logged yet"].waitForExistence(timeout: 5))+    app.tabBars.buttons["Medications"].tap()+    app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic follow-up UI"))+      .firstMatch.tap()+    let message = app.descendants(matching: .any).matching(+      NSPredicate(format: "label CONTAINS %@", "Synthetic later reminder")+    ).firstMatch+    for _ in 0..<5 {+      if message.exists { break }+      app.swipeUp()     }+    XCTAssertTrue(message.exists)+    XCTAssertFalse(app.alerts.firstMatch.exists)+  } -    func testSimpleDailyDoseLimitsShowAllowanceThenRefreshAfterTakenAndUndo() {-        continueAfterFailure = false-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))-        app.buttons["Add as-needed medication"].tap()-        func fill(_ id: String, _ value: String) {-            let field = app.textFields[id]-            let form = app.collectionViews.allElementsBoundByIndex.first { $0.textFields[id].exists } ?? app.collectionViews.firstMatch-            let bar = app.buttons["Save"]-            // The simulator can report a clipped field as hittable behind the navigation bar.-            for _ in 0..<10 {-                if field.exists && field.isHittable && field.frame.minY > bar.frame.maxY { break }-                if field.exists && field.frame.minY <= bar.frame.maxY { form.swipeDown() }-                else { form.swipeUp() }-            }-            XCTAssertTrue(field.isHittable && field.frame.minY > bar.frame.maxY, id)-            field.tap(); field.typeText(value)-            if app.keyboards.firstMatch.exists { form.swipeUp() }+  func testSimpleDailyDoseLimitsShowAllowanceThenRefreshAfterTakenAndUndo() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))+    app.buttons["Add as-needed medication"].tap()+    func fill(_ id: String, _ value: String) {+      let field = app.textFields[id]+      let form =+        app.collectionViews.allElementsBoundByIndex.first { $0.textFields[id].exists }+        ?? app.collectionViews.firstMatch+      let bar = app.buttons["Save"]+      // The simulator can report a clipped field as hittable behind the navigation bar.+      for _ in 0..<10 {+        if field.exists && field.isHittable && field.frame.minY > bar.frame.maxY { break }+        if field.exists && field.frame.minY <= bar.frame.maxY {+          form.swipeDown()+        } else {+          form.swipeUp()         }-        func expectStatus(_ text: String) {-            // SwiftUI Form/List can combine status text into one accessibility row.-            let status = app.descendants(matching: .any).matching(NSPredicate(format: "label CONTAINS %@", text)).firstMatch-            XCTAssertTrue(status.waitForExistence(timeout: 5), text)-        }-        fill("Name", "Synthetic interval UI")-        fill("Quantity per dose", "1")-        fill("Unit", "measure")-        let toggle = app.switches["doseLimitsEnabled"]-        for _ in 0..<8 { if toggle.exists && toggle.isHittable { break }; app.swipeUp() }-        XCTAssertTrue(toggle.isHittable)-        toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()-        app.swipeUp() // Form materializes the newly enabled rows as they enter view.-        fill("doseLimitintervalHours", "3")-        fill("doseLimitmaximum", "7.5")-        XCTAssertFalse(app.textFields["doseLimitwindowHours"].exists)-        XCTAssertFalse(app.textFields["doseLimitproduct"].exists)-        XCTAssertFalse(app.textFields["doseLimitingredients"].exists)-        XCTAssertFalse(app.textFields["doseLimitsource"].exists)-        app.buttons["Save"].tap()-        expectStatus("Fits your entered limits")-        expectStatus("Remaining: 7.5 measure in the last 24 hours")-        let taken = app.buttons["Mark Synthetic interval UI taken"]-        for _ in 0..<8 { if taken.isHittable { break }; app.swipeDown() }-        taken.tap()-        expectStatus("Wait before another dose")-        expectStatus("Remaining: 6.5 measure in the last 24 hours")-        expectStatus("Next dose:")-        let undo = app.buttons["Undo Taken"]-        for _ in 0..<8 { if undo.isHittable { break }; app.swipeDown() }-        undo.tap()-        expectStatus("Fits your entered limits")-        XCTAssertFalse(app.alerts.firstMatch.exists)+      }+      XCTAssertTrue(field.isHittable && field.frame.minY > bar.frame.maxY, id)+      field.tap()+      field.typeText(value)+      if app.keyboards.firstMatch.exists { form.swipeUp() }+    }+    func expectStatus(_ text: String) {+      // SwiftUI Form/List can combine status text into one accessibility row.+      let status = app.descendants(matching: .any).matching(+        NSPredicate(format: "label CONTAINS %@", text)+      ).firstMatch+      XCTAssertTrue(status.waitForExistence(timeout: 5), text)+    }+    fill("Name", "Synthetic interval UI")+    fill("Quantity per dose", "1")+    fill("Unit", "measure")+    let toggle = app.switches["doseLimitsEnabled"]+    for _ in 0..<8 {+      if toggle.exists && toggle.isHittable { break }+      app.swipeUp()+    }+    XCTAssertTrue(toggle.isHittable)+    toggle.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()+    app.swipeUp()  // Form materializes the newly enabled rows as they enter view.+    fill("doseLimitintervalHours", "3")+    fill("doseLimitmaximum", "7.5")+    XCTAssertFalse(app.textFields["doseLimitwindowHours"].exists)+    XCTAssertFalse(app.textFields["doseLimitproduct"].exists)+    XCTAssertFalse(app.textFields["doseLimitingredients"].exists)+    XCTAssertFalse(app.textFields["doseLimitsource"].exists)+    app.buttons["Save"].tap()+    expectStatus("Fits your entered limits")+    expectStatus("Remaining: 7.5 measure in the last 24 hours")+    let taken = app.buttons["Mark Synthetic interval UI taken"]+    for _ in 0..<8 {+      if taken.isHittable { break }+      app.swipeDown()     }-    func testPhotoPickerCancellationKeepsOptionalMedicationEditorUsable() {-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))-        app.buttons["Add as-needed medication"].tap()-        XCTAssertTrue(app.staticTexts["Add photo"].waitForExistence(timeout: 5))-        app.staticTexts["Add photo"].tap()-        let cancelButtons = app.buttons.matching(identifier: "Cancel")-        XCTAssertTrue(cancelButtons.firstMatch.waitForExistence(timeout: 5))-        cancelButtons.element(boundBy: cancelButtons.count - 1).tap()-        XCTAssertTrue(app.textFields["Name"].waitForExistence(timeout: 5))-        XCTAssertTrue(app.buttons["Add photo"].exists)-        XCTAssertFalse(app.buttons["Remove photo"].exists)-        let name = app.textFields["Name"]; name.tap(); name.typeText("Synthetic photo-free item")-        if app.keyboards.firstMatch.exists { app.swipeUp() }-        app.buttons["Save"].tap()-        XCTAssertTrue(app.buttons["Mark Synthetic photo-free item taken"].waitForExistence(timeout: 5))-        XCTAssertFalse(app.alerts.firstMatch.exists)+    taken.tap()+    expectStatus("Wait before another dose")+    expectStatus("Remaining: 6.5 measure in the last 24 hours")+    expectStatus("Next dose:")+    let undo = app.buttons["Undo Taken"]+    for _ in 0..<8 {+      if undo.isHittable { break }+      app.swipeDown()     }+    undo.tap()+    expectStatus("Fits your entered limits")+    XCTAssertFalse(app.alerts.firstMatch.exists)+  }+  func testPhotoPickerCancellationKeepsOptionalMedicationEditorUsable() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 10))+    app.buttons["Add as-needed medication"].tap()+    XCTAssertTrue(app.staticTexts["Add photo"].waitForExistence(timeout: 5))+    app.staticTexts["Add photo"].tap()+    let cancelButtons = app.buttons.matching(identifier: "Cancel")+    XCTAssertTrue(cancelButtons.firstMatch.waitForExistence(timeout: 5))+    cancelButtons.element(boundBy: cancelButtons.count - 1).tap()+    XCTAssertTrue(app.textFields["Name"].waitForExistence(timeout: 5))+    XCTAssertTrue(app.buttons["Add photo"].exists)+    XCTAssertFalse(app.buttons["Remove photo"].exists)+    let name = app.textFields["Name"]+    name.tap()+    name.typeText("Synthetic photo-free item")+    if app.keyboards.firstMatch.exists { app.swipeUp() }+    app.buttons["Save"].tap()+    XCTAssertTrue(app.buttons["Mark Synthetic photo-free item taken"].waitForExistence(timeout: 5))+    XCTAssertFalse(app.alerts.firstMatch.exists)+  }  }
Meddy/MeddyUITests/MeddyProfileUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyProfileUITests.swift b/Meddy/MeddyUITests/MeddyProfileUITests.swiftindex 7669a65..3e55a84 100644--- a/Meddy/MeddyUITests/MeddyProfileUITests.swift+++ b/Meddy/MeddyUITests/MeddyProfileUITests.swift@@ -1,39 +1,65 @@ import XCTest  final class MeddyProfileUITests: XCTestCase {-    @MainActor func testAddRenameSwitchKeepsSameNameCareSeparateAndLaunchDefaultsToMe() {-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        let picker = app.buttons["careProfilePicker"]-        XCTAssertTrue(picker.waitForExistence(timeout: 8))-        func manage() { picker.tap(); app.buttons["Manage profiles…"].tap() }-        func add(_ name: String) {-            app.buttons["addDependant"].tap()-            let field = app.textFields["profileDisplayName"]; XCTAssertTrue(field.waitForExistence(timeout: 3)); field.tap(); field.typeText(name)-            app.buttons["Save"].tap()-        }-        manage(); add("Synthetic Alpha"); app.navigationBars["Care profiles"].buttons["Done"].tap()-        app.buttons["Add as-needed medication"].tap()-        let name = app.textFields["Name"]; XCTAssertTrue(name.waitForExistence(timeout: 3)); name.tap(); name.typeText("Synthetic same medicine")-        app.buttons["Save"].tap()-        XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 4))-        manage(); add("Synthetic Beta"); app.navigationBars["Care profiles"].buttons["Done"].tap()-        XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)-        picker.tap(); app.buttons["Synthetic Alpha"].tap()-        XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 3))-        manage()-        let alpha = app.cells.containing(.staticText, identifier: "Synthetic Alpha").firstMatch-        alpha.buttons["Rename"].tap()-        let field = app.textFields["profileDisplayName"]; field.tap()-        field.press(forDuration: 1.1)-        if app.menuItems["Select All"].waitForExistence(timeout: 2) { app.menuItems["Select All"].tap(); field.typeText("Synthetic Renamed") }-        else { field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: "Synthetic Alpha".count) + "Synthetic Renamed") }-        app.buttons["Save"].tap(); app.navigationBars["Care profiles"].buttons["Done"].tap()-        XCTAssertTrue(picker.label.contains("Synthetic Renamed"))-        XCTAssertTrue(app.staticTexts["Synthetic same medicine"].exists)-        picker.tap(); app.buttons["Me"].tap()-        XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)-        app.terminate(); app.launch()-        XCTAssertTrue(app.buttons["careProfilePicker"].waitForExistence(timeout: 8))-        XCTAssertTrue(app.buttons["careProfilePicker"].label.contains("Me"))+  @MainActor func testAddRenameSwitchKeepsSameNameCareSeparateAndLaunchDefaultsToMe() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    let picker = app.buttons["careProfilePicker"]+    XCTAssertTrue(picker.waitForExistence(timeout: 8))+    func manage() {+      picker.tap()+      app.buttons["Manage profiles…"].tap()     }+    func add(_ name: String) {+      app.buttons["addDependant"].tap()+      let field = app.textFields["profileDisplayName"]+      XCTAssertTrue(field.waitForExistence(timeout: 3))+      field.tap()+      field.typeText(name)+      app.buttons["Save"].tap()+    }+    manage()+    add("Synthetic Alpha")+    app.navigationBars["Care profiles"].buttons["Done"].tap()+    app.buttons["Add as-needed medication"].tap()+    let name = app.textFields["Name"]+    XCTAssertTrue(name.waitForExistence(timeout: 3))+    name.tap()+    name.typeText("Synthetic same medicine")+    app.buttons["Save"].tap()+    XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 4))+    manage()+    add("Synthetic Beta")+    app.navigationBars["Care profiles"].buttons["Done"].tap()+    XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)+    picker.tap()+    app.buttons["Synthetic Alpha"].tap()+    XCTAssertTrue(app.staticTexts["Synthetic same medicine"].waitForExistence(timeout: 3))+    manage()+    let alpha = app.cells.containing(.staticText, identifier: "Synthetic Alpha").firstMatch+    alpha.buttons["Rename"].tap()+    let field = app.textFields["profileDisplayName"]+    field.tap()+    field.press(forDuration: 1.1)+    if app.menuItems["Select All"].waitForExistence(timeout: 2) {+      app.menuItems["Select All"].tap()+      field.typeText("Synthetic Renamed")+    } else {+      field.typeText(+        String(repeating: XCUIKeyboardKey.delete.rawValue, count: "Synthetic Alpha".count)+          + "Synthetic Renamed")+    }+    app.buttons["Save"].tap()+    app.navigationBars["Care profiles"].buttons["Done"].tap()+    XCTAssertTrue(picker.label.contains("Synthetic Renamed"))+    XCTAssertTrue(app.staticTexts["Synthetic same medicine"].exists)+    picker.tap()+    app.buttons["Me"].tap()+    XCTAssertFalse(app.staticTexts["Synthetic same medicine"].exists)+    app.terminate()+    app.launch()+    XCTAssertTrue(app.buttons["careProfilePicker"].waitForExistence(timeout: 8))+    XCTAssertTrue(app.buttons["careProfilePicker"].label.contains("Me"))+  } }
Meddy/MeddyUITests/MeddyRoutineUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyRoutineUITests.swift b/Meddy/MeddyUITests/MeddyRoutineUITests.swiftindex ccce1a6..408ccad 100644--- a/Meddy/MeddyUITests/MeddyRoutineUITests.swift+++ b/Meddy/MeddyUITests/MeddyRoutineUITests.swift@@ -2,151 +2,178 @@ import XCTest  @MainActor final class MeddyRoutineUITests: XCTestCase {-    func testTwoUntimedSessionsKeepIndependentProgressThroughWholePhoneSequence() throws {-        continueAfterFailure = false-        let app = XCUIApplication()-        app.launchEnvironment["MEDDY_TESTING"] = "1"-        app.launch()-        app.tabBars.buttons["Routines"].tap()-        addCare("Treatment item", in: app)-        enter("Synthetic care", into: app.textFields["Name"])-        app.buttons["Save"].tap()-        addCare("Timed routine", in: app)-        enter("Synthetic timer", into: app.textFields["Name"])-        enter("1", into: app.textFields["Number of rounds"])-        enter("1", into: app.textFields["Seconds per round"])-        app.buttons["Save"].tap()-        app.tabBars.buttons["Medications"].tap()-        app.buttons["Add medication"].tap()-        enter("Synthetic medication", into: app.textFields["Name"])-        app.buttons["Save"].tap()-        app.tabBars.buttons["Routines"].tap()-        addCare("Ordered routine", in: app)-        enter("Synthetic group", into: app.textFields["Name"])-        for name in ["Synthetic care", "Synthetic timer", "Synthetic medication"] {-            reveal(app.buttons["Add existing step"], in: app)-            app.buttons["Add existing step"].tap()-            let choice = app.buttons.matching(identifier: name).allElementsBoundByIndex.first { $0.isHittable }-            XCTAssertNotNil(choice)-            choice?.tap()-        }-        reveal(app.switches["Confirm ownership change"], in: app)-        app.switches["Confirm ownership change"].coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()-        XCTAssertEqual(app.switches["Confirm ownership change"].value as? String, "1")-        reveal(app.switches["Daily sessions"], in: app)-        app.switches["Daily sessions"].coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()-        XCTAssertEqual(app.switches["Daily sessions"].value as? String, "1")-        reveal(app.textFields["Daily session count"], in: app)-        app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()-        enter("2", into: app.textFields["Daily session count"])-        app.buttons["Save"].tap()-        XCTAssertFalse(app.buttons["Cancel"].waitForExistence(timeout: 2), app.staticTexts.allElementsBoundByIndex.map(\.label).joined(separator: " | "))-        XCTAssertFalse(app.alerts.firstMatch.exists)-        app.buttons["Synthetic group"].tap()-        app.buttons["Start Session 1"].tap()-        XCTAssertTrue(app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)-        app.buttons["Done"].tap()-        app.buttons["Start timer"].tap()-        app.buttons["Open saved timer"].tap()-        app.buttons["phoneTimerCircle"].tap()-        XCTAssertTrue(app.staticTexts["1 rounds completed"].waitForExistence(timeout: 8))-        app.navigationBars.buttons.element(boundBy: 0).tap()-        reveal(app.buttons["Taken / Applied"], in: app)-        app.buttons["Taken / Applied"].tap()-        XCTAssertTrue(app.staticTexts["3 of 3 steps completed"].waitForExistence(timeout: 5))-        app.buttons["Close"].tap()-        XCTAssertTrue(app.buttons["Start Session 2"].exists)-        app.buttons["Start Session 2"].tap()-        XCTAssertTrue(app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)-        app.buttons["Skip step"].firstMatch.tap()-        XCTAssertTrue(app.buttons["Continue with skipped step"].exists)-        XCTAssertFalse(app.buttons["Taken / Applied"].exists)-        app.buttons["Continue with skipped step"].tap()-        XCTAssertTrue(app.buttons["Start timer"].exists)-        app.buttons["Close"].tap()-        XCTAssertTrue(app.buttons["Open Session 1"].exists)-        XCTAssertFalse(app.alerts.firstMatch.exists)+  func testTwoUntimedSessionsKeepIndependentProgressThroughWholePhoneSequence() throws {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    app.tabBars.buttons["Routines"].tap()+    addCare("Treatment item", in: app)+    enter("Synthetic care", into: app.textFields["Name"])+    app.buttons["Save"].tap()+    addCare("Timed routine", in: app)+    enter("Synthetic timer", into: app.textFields["Name"])+    enter("1", into: app.textFields["Number of rounds"])+    enter("1", into: app.textFields["Seconds per round"])+    app.buttons["Save"].tap()+    app.tabBars.buttons["Medications"].tap()+    app.buttons["Add medication"].tap()+    enter("Synthetic medication", into: app.textFields["Name"])+    app.buttons["Save"].tap()+    app.tabBars.buttons["Routines"].tap()+    addCare("Ordered routine", in: app)+    enter("Synthetic group", into: app.textFields["Name"])+    for name in ["Synthetic care", "Synthetic timer", "Synthetic medication"] {+      reveal(app.buttons["Add existing step"], in: app)+      app.buttons["Add existing step"].tap()+      let choice = app.buttons.matching(identifier: name).allElementsBoundByIndex.first {+        $0.isHittable+      }+      XCTAssertNotNil(choice)+      choice?.tap()     }+    reveal(app.switches["Confirm ownership change"], in: app)+    app.switches["Confirm ownership change"].coordinate(+      withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)+    ).tap()+    XCTAssertEqual(app.switches["Confirm ownership change"].value as? String, "1")+    reveal(app.switches["Daily sessions"], in: app)+    app.switches["Daily sessions"].coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5))+      .tap()+    XCTAssertEqual(app.switches["Daily sessions"].value as? String, "1")+    reveal(app.textFields["Daily session count"], in: app)+    app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()+    enter("2", into: app.textFields["Daily session count"])+    app.buttons["Save"].tap()+    XCTAssertFalse(+      app.buttons["Cancel"].waitForExistence(timeout: 2),+      app.staticTexts.allElementsBoundByIndex.map(\.label).joined(separator: " | "))+    XCTAssertFalse(app.alerts.firstMatch.exists)+    app.buttons["Synthetic group"].tap()+    app.buttons["Start Session 1"].tap()+    XCTAssertTrue(+      app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)+    app.buttons["Done"].tap()+    app.buttons["Start timer"].tap()+    app.buttons["Open saved timer"].tap()+    app.buttons["phoneTimerCircle"].tap()+    XCTAssertTrue(app.staticTexts["1 rounds completed"].waitForExistence(timeout: 8))+    app.navigationBars.buttons.element(boundBy: 0).tap()+    reveal(app.buttons["Taken / Applied"], in: app)+    app.buttons["Taken / Applied"].tap()+    XCTAssertTrue(app.staticTexts["3 of 3 steps completed"].waitForExistence(timeout: 5))+    app.buttons["Close"].tap()+    XCTAssertTrue(app.buttons["Start Session 2"].exists)+    app.buttons["Start Session 2"].tap()+    XCTAssertTrue(+      app.staticTexts["0 of 3 steps completed"].waitForExistence(timeout: 5), app.debugDescription)+    app.buttons["Skip step"].firstMatch.tap()+    XCTAssertTrue(app.buttons["Continue with skipped step"].exists)+    XCTAssertFalse(app.buttons["Taken / Applied"].exists)+    app.buttons["Continue with skipped step"].tap()+    XCTAssertTrue(app.buttons["Start timer"].exists)+    app.buttons["Close"].tap()+    XCTAssertTrue(app.buttons["Open Session 1"].exists)+    XCTAssertFalse(app.alerts.firstMatch.exists)+  } -    func testLargeTimerCircleStartsPausesResumesAndWaitsForNextRound() {-        continueAfterFailure = false-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        app.tabBars.buttons["Routines"].tap()-        addCare("Timed routine", in: app)-        enter("Synthetic circle timer", into: app.textFields["Name"])-        enter("2", into: app.textFields["Number of rounds"])-        enter("8", into: app.textFields["Seconds per round"])-        app.buttons["Save"].tap()-        reveal(app.buttons["Start"], in: app)-        app.buttons["Start"].tap()-        let circle = app.buttons["phoneTimerCircle"]-        XCTAssertTrue(circle.waitForExistence(timeout: 5))-        XCTAssertGreaterThanOrEqual(circle.frame.width, 260)-        XCTAssertEqual(circle.frame.width, circle.frame.height, accuracy: 2)-        XCTAssertEqual(circle.frame.midX, app.frame.midX, accuracy: 5)-        XCTAssertLessThan(abs(circle.frame.midY - app.frame.midY), 110)-        XCTAssertEqual(circle.label, "Start round 1 of 2")-        circle.tap()-        XCTAssertEqual(circle.label, "Pause round 1 of 2")-        circle.tap()-        XCTAssertEqual(circle.label, "Resume round 1 of 2")-        XCTAssertFalse(circle.value as? String == "")-        circle.tap()-        let waiting = NSPredicate(format: "label == %@", "Start round 2 of 2")-        expectation(for: waiting, evaluatedWith: circle)-        waitForExpectations(timeout: 15)-        XCTAssertTrue(app.staticTexts["Waiting between rounds. No timer is running."].exists)-        XCTAssertTrue(app.buttons["End timer"].exists)-        circle.tap()-        let complete = NSPredicate(format: "label == %@", "All 2 rounds completed")-        expectation(for: complete, evaluatedWith: circle)-        waitForExpectations(timeout: 15)-        XCTAssertFalse(circle.isEnabled)-    }+  func testLargeTimerCircleStartsPausesResumesAndWaitsForNextRound() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    app.tabBars.buttons["Routines"].tap()+    addCare("Timed routine", in: app)+    enter("Synthetic circle timer", into: app.textFields["Name"])+    enter("2", into: app.textFields["Number of rounds"])+    enter("8", into: app.textFields["Seconds per round"])+    app.buttons["Save"].tap()+    reveal(app.buttons["Start"], in: app)+    app.buttons["Start"].tap()+    let circle = app.buttons["phoneTimerCircle"]+    XCTAssertTrue(circle.waitForExistence(timeout: 5))+    XCTAssertGreaterThanOrEqual(circle.frame.width, 260)+    XCTAssertEqual(circle.frame.width, circle.frame.height, accuracy: 2)+    XCTAssertEqual(circle.frame.midX, app.frame.midX, accuracy: 5)+    XCTAssertLessThan(abs(circle.frame.midY - app.frame.midY), 110)+    XCTAssertEqual(circle.label, "Start round 1 of 2")+    circle.tap()+    XCTAssertEqual(circle.label, "Pause round 1 of 2")+    circle.tap()+    XCTAssertEqual(circle.label, "Resume round 1 of 2")+    XCTAssertFalse(circle.value as? String == "")+    circle.tap()+    let waiting = NSPredicate(format: "label == %@", "Start round 2 of 2")+    expectation(for: waiting, evaluatedWith: circle)+    waitForExpectations(timeout: 15)+    XCTAssertTrue(app.staticTexts["Waiting between rounds. No timer is running."].exists)+    XCTAssertTrue(app.buttons["End timer"].exists)+    circle.tap()+    let complete = NSPredicate(format: "label == %@", "All 2 rounds completed")+    expectation(for: complete, evaluatedWith: circle)+    waitForExpectations(timeout: 15)+    XCTAssertFalse(circle.isEnabled)+  } -    func testLargeTextTimerKeepsCircleAndEndControlReachable() {-        continueAfterFailure = false-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"-        app.launchEnvironment["MEDDY_TEST_TIMER_CIRCLE"] = "1"-        app.launchArguments = ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"]-        app.launch()-        let circle = app.buttons["phoneTimerCircle"]-        XCTAssertTrue(circle.waitForExistence(timeout: 5))-        for _ in 0..<5 { if circle.isHittable { break }; app.scrollViews.firstMatch.swipeUp() }-        XCTAssertTrue(circle.isHittable)-        XCTAssertEqual(circle.label, "Start round 1 of 1")-        XCTAssertGreaterThanOrEqual(circle.frame.width, 260)-        circle.tap()-        XCTAssertEqual(circle.label, "Pause round 1 of 1")-        circle.tap()-        XCTAssertEqual(circle.label, "Resume round 1 of 1")-        XCTAssertTrue((circle.value as? String)?.contains("remaining") == true)-        let attachment = XCTAttachment(screenshot: app.screenshot())-        attachment.lifetime = .keepAlways; add(attachment)-        let end = app.buttons["End timer"]-        for _ in 0..<5 { if end.isHittable { break }; app.scrollViews.firstMatch.swipeUp() }-        XCTAssertTrue(end.isHittable)-        end.tap()-        for _ in 0..<5 { if circle.isHittable { break }; app.scrollViews.firstMatch.swipeDown() }-        XCTAssertEqual(circle.label, "Reopen ended timer without starting a round")-        circle.tap()-        XCTAssertEqual(circle.label, "Resume round 1 of 1")+  func testLargeTextTimerKeepsCircleAndEndControlReachable() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launchEnvironment["MEDDY_TEST_TIMER_CIRCLE"] = "1"+    app.launchArguments = [+      "-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityXXXL"+    ]+    app.launch()+    let circle = app.buttons["phoneTimerCircle"]+    XCTAssertTrue(circle.waitForExistence(timeout: 5))+    for _ in 0..<5 {+      if circle.isHittable { break }+      app.scrollViews.firstMatch.swipeUp()     }--    private func addCare(_ kind: String, in app: XCUIApplication) {-        app.buttons["Add care item"].tap()-        app.buttons[kind].tap()+    XCTAssertTrue(circle.isHittable)+    XCTAssertEqual(circle.label, "Start round 1 of 1")+    XCTAssertGreaterThanOrEqual(circle.frame.width, 260)+    circle.tap()+    XCTAssertEqual(circle.label, "Pause round 1 of 1")+    circle.tap()+    XCTAssertEqual(circle.label, "Resume round 1 of 1")+    XCTAssertTrue((circle.value as? String)?.contains("remaining") == true)+    let attachment = XCTAttachment(screenshot: app.screenshot())+    attachment.lifetime = .keepAlways+    add(attachment)+    let end = app.buttons["End timer"]+    for _ in 0..<5 {+      if end.isHittable { break }+      app.scrollViews.firstMatch.swipeUp()     }-    private func enter(_ text: String, into field: XCUIElement) {-        XCTAssertTrue(field.waitForExistence(timeout: 5))-        field.tap(); field.typeText(text)+    XCTAssertTrue(end.isHittable)+    end.tap()+    for _ in 0..<5 {+      if circle.isHittable { break }+      app.scrollViews.firstMatch.swipeDown()+    }+    XCTAssertEqual(circle.label, "Reopen ended timer without starting a round")+    circle.tap()+    XCTAssertEqual(circle.label, "Resume round 1 of 1")+  }++  private func addCare(_ kind: String, in app: XCUIApplication) {+    app.buttons["Add care item"].tap()+    app.buttons[kind].tap()+  }+  private func enter(_ text: String, into field: XCUIElement) {+    XCTAssertTrue(field.waitForExistence(timeout: 5))+    field.tap()+    field.typeText(text)+  }+  private func reveal(_ element: XCUIElement, in app: XCUIApplication) {+    if app.keyboards.firstMatch.exists {+      app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()     }-    private func reveal(_ element: XCUIElement, in app: XCUIApplication) {-        if app.keyboards.firstMatch.exists { app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp() }-        for _ in 0..<10 {-            if element.exists && element.isHittable { return }-            app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()-        }-        XCTAssertTrue(element.exists && element.isHittable)+    for _ in 0..<10 {+      if element.exists && element.isHittable { return }+      app.collectionViews.element(boundBy: app.collectionViews.count - 1).swipeUp()     }+    XCTAssertTrue(element.exists && element.isHittable)+  } }
Meddy/MeddyUITests/MeddyWakeUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyWakeUITests.swift b/Meddy/MeddyUITests/MeddyWakeUITests.swiftindex 8db6b2d..1f4ce5d 100644--- a/Meddy/MeddyUITests/MeddyWakeUITests.swift+++ b/Meddy/MeddyUITests/MeddyWakeUITests.swift@@ -1,41 +1,55 @@ import XCTest  final class MeddyWakeUITests: XCTestCase {-    @MainActor func testMedicationAfterWakingOffsetPersistsAndRoutineHasSameTimingChoice() {-        let app = XCUIApplication(); app.launchEnvironment["MEDDY_TESTING"] = "1"; app.launch()-        XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8))-        app.buttons["Add as-needed medication"].tap()-        let name = app.textFields["Name"]; XCTAssertTrue(name.waitForExistence(timeout: 3)); name.tap(); name.typeText("Synthetic wake medicine")-        if app.keyboards.firstMatch.exists { app.swipeUp() }-        let schedule = app.buttons["medicationSchedulePicker"]-        for _ in 0..<4 where !schedule.isHittable { app.swipeUp() }-        schedule.tap(); app.buttons["After waking"].tap()-        let offset = app.textFields["wakeOffsetMinutes"]-        for _ in 0..<4 where !offset.isHittable { app.swipeUp() }-        XCTAssertTrue(offset.waitForExistence(timeout: 3)); offset.tap(); offset.typeText(XCUIKeyboardKey.delete.rawValue + "35")-        app.buttons["Save"].tap()-        app.buttons["Medications"].tap()-        XCTAssertTrue(app.staticTexts["Synthetic wake medicine"].waitForExistence(timeout: 4))-        app.staticTexts["Synthetic wake medicine"].tap()-        app.buttons["Edit"].tap()-        for _ in 0..<4 where !app.textFields["wakeOffsetMinutes"].isHittable { app.swipeUp() }-        XCTAssertEqual(app.textFields["wakeOffsetMinutes"].value as? String, "35")-        app.buttons["Cancel"].tap()-        app.buttons["Routines"].tap()-        app.buttons["Add care item"].tap(); app.buttons["Ordered routine"].tap()-        let daily = app.switches["Daily sessions"]-        for _ in 0..<5 where !daily.isHittable { app.swipeUp() }-        daily.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()-        let count = app.textFields["Daily session count"]-        guard count.waitForExistence(timeout: 4) else { XCTFail("Daily schedule fields should open"); return }-        count.tap(); count.typeText("1")-        if app.keyboards.firstMatch.exists { app.swipeUp() }-        let timing = app.buttons["Session timing option"]-        for _ in 0..<4 where !timing.isHittable { app.swipeUp() }-        timing.tap(); app.buttons["After waking"].tap()-        let routineOffset = app.textFields["Minutes after waking (0–1440)"]-        for _ in 0..<3 where !routineOffset.isHittable { app.swipeUp() }-        XCTAssertTrue(routineOffset.waitForExistence(timeout: 3))-        app.buttons["Cancel"].tap()+  @MainActor func testMedicationAfterWakingOffsetPersistsAndRoutineHasSameTimingChoice() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.buttons["Add as-needed medication"].waitForExistence(timeout: 8))+    app.buttons["Add as-needed medication"].tap()+    let name = app.textFields["Name"]+    XCTAssertTrue(name.waitForExistence(timeout: 3))+    name.tap()+    name.typeText("Synthetic wake medicine")+    if app.keyboards.firstMatch.exists { app.swipeUp() }+    let schedule = app.buttons["medicationSchedulePicker"]+    for _ in 0..<4 where !schedule.isHittable { app.swipeUp() }+    schedule.tap()+    app.buttons["After waking"].tap()+    let offset = app.textFields["wakeOffsetMinutes"]+    for _ in 0..<4 where !offset.isHittable { app.swipeUp() }+    XCTAssertTrue(offset.waitForExistence(timeout: 3))+    offset.tap()+    offset.typeText(XCUIKeyboardKey.delete.rawValue + "35")+    app.buttons["Save"].tap()+    app.buttons["Medications"].tap()+    XCTAssertTrue(app.staticTexts["Synthetic wake medicine"].waitForExistence(timeout: 4))+    app.staticTexts["Synthetic wake medicine"].tap()+    app.buttons["Edit"].tap()+    for _ in 0..<4 where !app.textFields["wakeOffsetMinutes"].isHittable { app.swipeUp() }+    XCTAssertEqual(app.textFields["wakeOffsetMinutes"].value as? String, "35")+    app.buttons["Cancel"].tap()+    app.buttons["Routines"].tap()+    app.buttons["Add care item"].tap()+    app.buttons["Ordered routine"].tap()+    let daily = app.switches["Daily sessions"]+    for _ in 0..<5 where !daily.isHittable { app.swipeUp() }+    daily.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.5)).tap()+    let count = app.textFields["Daily session count"]+    guard count.waitForExistence(timeout: 4) else {+      XCTFail("Daily schedule fields should open")+      return     }+    count.tap()+    count.typeText("1")+    if app.keyboards.firstMatch.exists { app.swipeUp() }+    let timing = app.buttons["Session timing option"]+    for _ in 0..<4 where !timing.isHittable { app.swipeUp() }+    timing.tap()+    app.buttons["After waking"].tap()+    let routineOffset = app.textFields["Minutes after waking (0–1440)"]+    for _ in 0..<3 where !routineOffset.isHittable { app.swipeUp() }+    XCTAssertTrue(routineOffset.waitForExistence(timeout: 3))+    app.buttons["Cancel"].tap()+  } }
Meddy/MeddyWatch/ContentView.swift Modified
diff --git a/Meddy/MeddyWatch/ContentView.swift b/Meddy/MeddyWatch/ContentView.swiftindex c7422e3..9af6af3 100644--- a/Meddy/MeddyWatch/ContentView.swift+++ b/Meddy/MeddyWatch/ContentView.swift@@ -1,215 +1,376 @@ import SwiftUI  struct ContentView: View {-    @State private var controller = WatchController()-    var body: some View {-        TimelineView(.everyMinute) { timeline in-            TabView {-                NavigationStack {-                    List {-                        status-                        profilePicker-                        if let snapshot = controller.snapshot {-                            Section("Due / next") {-                                ForEach(snapshot.medications.filter { ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID }.filter { $0.active && ![.asNeeded, .routineManaged].contains($0.schedule.mode) }.sorted { ($0.next ?? .distantFuture) < ($1.next ?? .distantFuture) }) { item in medicationRow(item) }-                            }-                            Section("As needed") {-                                ForEach(snapshot.medications.filter { ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID }.filter { $0.active && $0.schedule.mode == .asNeeded }.sorted { $0.name < $1.name }) { item in medicationRow(item) }-                            }-                            ForEach(snapshot.routines.filter { ($0.definition.profileID ?? ProfileIdentity.me) == controller.selectedProfileID }.filter { !controller.occurrences($0, now: timeline.date).isEmpty }) { routine in-                                NavigationLink(routine.definition.name) { WatchRoutineDetail(routine: routine, controller: controller, now: timeline.date) }-                            }-                        } else { Text("Open Meddy on the paired iPhone to receive your plans. Cached plans will remain available offline.") }-                    }.navigationTitle("Today")-                }.tabItem { Label("Today", systemImage: "sun.max") }-                NavigationStack {-                    List {-                        status-                        ForEach((controller.snapshot?.routines ?? []).filter { ($0.definition.profileID ?? ProfileIdentity.me) == controller.selectedProfileID }) { routine in-                            NavigationLink(routine.definition.name) { WatchRoutineDetail(routine: routine, controller: controller, now: timeline.date) }-                        }-                        Section("Treatment items") {-                            ForEach((controller.snapshot?.treatments ?? []).filter { $0.active && ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID }) { item in-                                VStack(alignment: .leading) {-                                    Text(item.name).font(.headline)-                                    if !item.instructions.isEmpty { Text(item.instructions).font(.caption) }-                                    if let date = item.lastDone { Text("Last done \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption) }-                                    Button("Done") { perform { try controller.markTreatment(item) } }-                                }-                            }-                        }-                        Section("Saved sessions") {-                            ForEach(controller.runs.filter { $0.parentRunID == nil && CompanionOwnership.owner($0) == controller.selectedProfileID }) { run in-                                NavigationLink { WatchRunView(runID: run.id, controller: controller) } label: {-                                    VStack(alignment: .leading) { Text(run.definition.name); Text(run.status.rawValue).font(.caption) }-                                }-                            }-                        }-                    }.navigationTitle("Routines")-                }.tabItem { Label("Routines", systemImage: "list.bullet.clipboard") }+  @State private var controller = WatchController()+  var body: some View {+    TimelineView(.everyMinute) { timeline in+      TabView {+        NavigationStack {+          List {+            status+            profilePicker+            if let snapshot = controller.snapshot {+              Section("Due / next") {+                ForEach(+                  snapshot.medications.filter {+                    ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID+                  }.filter {+                    $0.active && ![.asNeeded, .routineManaged].contains($0.schedule.mode)+                  }.sorted { ($0.next ?? .distantFuture) < ($1.next ?? .distantFuture) }+                ) { item in medicationRow(item) }+              }+              Section("As needed") {+                ForEach(+                  snapshot.medications.filter {+                    ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID+                  }.filter { $0.active && $0.schedule.mode == .asNeeded }.sorted {+                    $0.name < $1.name+                  }+                ) { item in medicationRow(item) }+              }+              ForEach(+                snapshot.routines.filter {+                  ($0.definition.profileID ?? ProfileIdentity.me) == controller.selectedProfileID+                }.filter { !controller.occurrences($0, now: timeline.date).isEmpty }+              ) { routine in+                NavigationLink(routine.definition.name) {+                  WatchRoutineDetail(routine: routine, controller: controller, now: timeline.date)+                }+              }+            } else {+              Text(+                "Open Meddy on the paired iPhone to receive your plans. Cached plans will remain available offline."+              )             }-        }-        .onAppear { controller.refresh() }-        .alert("Meddy needs attention", isPresented: Binding(get: { controller.error != nil }, set: { if !$0 { controller.error = nil } })) { Button("OK") { controller.error = nil } } message: { Text(controller.error ?? "") }-    }-    private var profilePicker: some View {-        Picker("Profile", selection: $controller.selectedProfileID) {-            if let profiles = controller.snapshot?.profiles {-                ForEach(profiles.filter { !$0.archived }.sorted { a,b in a.id != b.id && (a.id == ProfileIdentity.me || b.id != ProfileIdentity.me && a.id.uuidString < b.id.uuidString) }) { Text($0.label).tag($0.id) }-            } else { Text("Me").tag(ProfileIdentity.me) }-        }-    }-    private func medicationRow(_ item: CompanionMedication) -> some View {-        VStack(alignment: .leading) {-            Text(item.name).font(.headline)-            if let next = item.next { Text(next, style: .time).font(.caption) }-            if item.dose != .unknown { Text(item.dose.displayText).font(.caption) }-            if let check = item.doseLimitCheck {-                Text("Last phone check: \(check.title)").font(.caption)-                Text(check.evaluatedAt.formatted(date: .abbreviated, time: .shortened)).font(.caption)-                Text("Cached check excludes later doses. Check the phone before taking another dose.").font(.caption)+          }.navigationTitle("Today")+        }.tabItem { Label("Today", systemImage: "sun.max") }+        NavigationStack {+          List {+            status+            ForEach(+              (controller.snapshot?.routines ?? []).filter {+                ($0.definition.profileID ?? ProfileIdentity.me) == controller.selectedProfileID+              }+            ) { routine in+              NavigationLink(routine.definition.name) {+                WatchRoutineDetail(routine: routine, controller: controller, now: timeline.date)+              }             }-            if let date = controller.lastTaken(item) { Text("Last taken \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption) }-            else { Text("Not logged yet").font(.caption) }-            if !item.requirements.isEmpty { Text(item.requirements).font(.caption) }-            Button("Taken / Applied") { perform { try controller.markMedication(item) } }-        }+            Section("Treatment items") {+              ForEach(+                (controller.snapshot?.treatments ?? []).filter {+                  $0.active && ($0.profileID ?? ProfileIdentity.me) == controller.selectedProfileID+                }+              ) { item in+                VStack(alignment: .leading) {+                  Text(item.name).font(.headline)+                  if !item.instructions.isEmpty { Text(item.instructions).font(.caption) }+                  if let date = item.lastDone {+                    Text("Last done \(date.formatted(date: .abbreviated, time: .shortened))").font(+                      .caption)+                  }+                  Button("Done") { perform { try controller.markTreatment(item) } }+                }+              }+            }+            Section("Saved sessions") {+              ForEach(+                controller.runs.filter {+                  $0.parentRunID == nil+                    && CompanionOwnership.owner($0) == controller.selectedProfileID+                }+              ) { run in+                NavigationLink {+                  WatchRunView(runID: run.id, controller: controller)+                } label: {+                  VStack(alignment: .leading) {+                    Text(run.definition.name)+                    Text(run.status.rawValue).font(.caption)+                  }+                }+              }+            }+          }.navigationTitle("Routines")+        }.tabItem { Label("Routines", systemImage: "list.bullet.clipboard") }+      }     }-    private var status: some View {-        Section {-            Text(controller.reachable ? "Phone connected" : "Cached · Phone offline").font(.caption)-            if let date = controller.snapshot?.generatedAt { Text("Updated \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption) }-            if controller.pendingCount > 0 { Text("\(controller.pendingCount) actions saved on Watch · Awaiting phone confirmation").font(.caption) }-            if let message = controller.runtimeMessage { Text(message).font(.caption) }-            Button("Refresh / retry") { controller.refresh() }-        }+    .onAppear { controller.refresh() }+    .alert(+      "Meddy needs attention",+      isPresented: Binding(+        get: { controller.error != nil }, set: { if !$0 { controller.error = nil } })+    ) {+      Button("OK") { controller.error = nil }+    } message: {+      Text(controller.error ?? "")+    }+  }+  private var profilePicker: some View {+    Picker("Profile", selection: $controller.selectedProfileID) {+      if let profiles = controller.snapshot?.profiles {+        ForEach(+          profiles.filter { !$0.archived }.sorted { left, right in+            left.id != right.id+              && (left.id == ProfileIdentity.me+                || right.id != ProfileIdentity.me && left.id.uuidString < right.id.uuidString)+          }+        ) { Text($0.label).tag($0.id) }+      } else {+        Text("Me").tag(ProfileIdentity.me)+      }     }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { controller.error = error.localizedDescription } }+  }+  private func medicationRow(_ item: CompanionMedication) -> some View {+    VStack(alignment: .leading) {+      Text(item.name).font(.headline)+      if let next = item.next { Text(next, style: .time).font(.caption) }+      if item.dose != .unknown { Text(item.dose.displayText).font(.caption) }+      if let check = item.doseLimitCheck {+        Text("Last phone check: \(check.title)").font(.caption)+        Text(check.evaluatedAt.formatted(date: .abbreviated, time: .shortened)).font(.caption)+        Text("Cached check excludes later doses. Check the phone before taking another dose.").font(+          .caption)+      }+      if let date = controller.lastTaken(item) {+        Text("Last taken \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption)+      } else {+        Text("Not logged yet").font(.caption)+      }+      if !item.requirements.isEmpty { Text(item.requirements).font(.caption) }+      Button("Taken / Applied") { perform { try controller.markMedication(item) } }+    }+  }+  private var status: some View {+    Section {+      Text(controller.reachable ? "Phone connected" : "Cached · Phone offline").font(.caption)+      if let date = controller.snapshot?.generatedAt {+        Text("Updated \(date.formatted(date: .abbreviated, time: .shortened))").font(.caption)+      }+      if controller.pendingCount > 0 {+        Text("\(controller.pendingCount) actions saved on Watch · Awaiting phone confirmation")+          .font(.caption)+      }+      if let message = controller.runtimeMessage { Text(message).font(.caption) }+      Button("Refresh / retry") { controller.refresh() }+    }+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { controller.error = error.localizedDescription }+  } }  struct WatchRoutineDetail: View {-    let routine: CompanionRoutine-    let controller: WatchController-    let now: Date-    @State private var selectedID: UUID?-    @State private var pendingOccurrence: RoutineOccurrence?-    @State private var warning = false-    var body: some View {-        List {-            Text(routine.definition.instructions)-            if controller.occurrences(routine, now: now).isEmpty { Button("Start") { request(nil) } }-            ForEach(controller.occurrences(routine, now: now)) { occurrence in-                Button { request(occurrence) } label: {-                    VStack(alignment: .leading) { Text(occurrence.label); if let date = occurrence.scheduledAt { Text(date, style: .time) }; Text(occurrence.status?.rawValue ?? "Start") }-                }-            }-            ForEach(routine.definition.steps) { Text("\($0.position + 1). \($0.name)").font(.caption) }-        }.navigationTitle(routine.definition.name)-        .navigationDestination(item: $selectedID) { id in WatchRunView(runID: id, controller: controller) }-        .confirmationDialog("Another saved session is incomplete", isPresented: $warning) {-            Button("Start selected session") { start(pendingOccurrence) }-            Button("Cancel", role: .cancel) {}-        } message: { Text("Existing real logs are kept. Offline execution has no global lock; review overlapping actions on the phone.") }-    }-    private func request(_ occurrence: RoutineOccurrence?) {-        if let id = occurrence?.existingRunID { selectedID = id; return }-        if let saved = controller.runs.first(where: { $0.definition.routineID == routine.id && [.active, .paused, .needsReview].contains($0.status) }), occurrence == nil { selectedID = saved.id; return }-        if controller.runs.contains(where: { $0.parentRunID == nil && [.active, .paused, .needsReview].contains($0.status) }) { pendingOccurrence = occurrence; warning = true }-        else { start(occurrence) }-    }-    private func start(_ occurrence: RoutineOccurrence?) {-        do { selectedID = try controller.start(routine, occurrence: occurrence) } catch { controller.error = error.localizedDescription }+  let routine: CompanionRoutine+  let controller: WatchController+  let now: Date+  @State private var selectedID: UUID?+  @State private var pendingOccurrence: RoutineOccurrence?+  @State private var warning = false+  var body: some View {+    List {+      Text(routine.definition.instructions)+      if controller.occurrences(routine, now: now).isEmpty { Button("Start") { request(nil) } }+      ForEach(controller.occurrences(routine, now: now)) { occurrence in+        Button {+          request(occurrence)+        } label: {+          VStack(alignment: .leading) {+            Text(occurrence.label)+            if let date = occurrence.scheduledAt { Text(date, style: .time) }+            Text(occurrence.status?.rawValue ?? "Start")+          }+        }+      }+      ForEach(routine.definition.steps) { Text("\($0.position + 1). \($0.name)").font(.caption) }+    }.navigationTitle(routine.definition.name)+      .navigationDestination(item: $selectedID) { id in+        WatchRunView(runID: id, controller: controller)+      }+      .confirmationDialog("Another saved session is incomplete", isPresented: $warning) {+        Button("Start selected session") { start(pendingOccurrence) }+        Button("Cancel", role: .cancel) {}+      } message: {+        Text(+          "Existing real logs are kept. Offline execution has no global lock; review overlapping actions on the phone."+        )+      }+  }+  private func request(_ occurrence: RoutineOccurrence?) {+    if let id = occurrence?.existingRunID {+      selectedID = id+      return     }+    if let saved = controller.runs.first(where: {+      $0.definition.routineID == routine.id && [.active, .paused, .needsReview].contains($0.status)+    }), occurrence == nil {+      selectedID = saved.id+      return+    }+    if controller.runs.contains(where: {+      $0.parentRunID == nil && [.active, .paused, .needsReview].contains($0.status)+    }) {+      pendingOccurrence = occurrence+      warning = true+    } else {+      start(occurrence)+    }+  }+  private func start(_ occurrence: RoutineOccurrence?) {+    do { selectedID = try controller.start(routine, occurrence: occurrence) } catch {+      controller.error = error.localizedDescription+    }+  } }  struct WatchRunView: View {-    let runID: UUID-    let controller: WatchController-    @State private var childID: UUID?-    @State private var offlineWarning = false-    @State private var ending = false-    private var run: CompanionRun? { controller.value(runID) }-    var body: some View {-        List {-            if let run {-                Text(run.definition.name).font(.headline)-                if controller.requiresPhoneResume(run) {-                    Text("After restore, resume this saved session on iPhone, then refresh the Watch.")-                } else if controller.waitingHandoff.contains(runID) {-                    Text("Waiting for the paused checkpoint to be acknowledged.")-                    if controller.handoffWasRejected(runID) {-                        Button("Retry handoff") { perform { try controller.takeOwnership(runID) } }.disabled(!controller.reachable)-                    }-                }-                else if run.executionDeviceID != controller.deviceID {-                    Button(controller.reachable ? "Continue on Watch" : "Continue offline on Watch") {-                        if controller.reachable { perform { try controller.takeOwnership(runID) } } else { offlineWarning = true }-                    }-                } else if let timer = run.timer { timerControls(timer) }-                else { orderedControls(run) }-                if run.status == .needsReview { Text("Needs review on iPhone. Real logs remain saved; do not repeat medication to repair progress.") }-                if let message = controller.runtimeMessage { Text(message).font(.caption) }-            } else { Text("Saved session unavailable. Refresh from the phone.") }-        }-        .navigationTitle("Saved session")-        .navigationDestination(item: $childID) { id in WatchRunView(runID: id, controller: controller) }-        .confirmationDialog("End this session incomplete?", isPresented: $ending) {-            Button("End session", role: .destructive) { perform { try controller.transitionGroup(runID, operation: .end(runID: runID)) } }-            Button("Cancel", role: .cancel) {}-        } message: { Text("Real logs are kept. Unfinished steps remain unfinished.") }-        .confirmationDialog("Execute this cached session offline?", isPresented: $offlineWarning) {-            Button("Confirm offline execution") { perform { try controller.takeOwnership(runID, offlineConfirmed: true) } }-            Button("Cancel", role: .cancel) {}-        } message: { Text("Another device may still be running. Each actual action will be preserved and conflicting progress will need review on the phone.") }-    }-    @ViewBuilder private func orderedControls(_ run: CompanionRun) -> some View {-        Text("\(run.progress.steps.filter { $0.state == .completed }.count) of \(run.progress.steps.count) steps completed").font(.caption)-        ForEach(run.definition.steps) { step in-            if let saved = run.progress.steps.first(where: { $0.id == step.id }) {-                VStack(alignment: .leading) {-                    Text(step.name)-                    Text(saved.state.rawValue).font(.caption)-                    if !step.instructions.isEmpty { Text(step.instructions).font(.caption) }-                    if !step.requirements.isEmpty { Text(step.requirements).font(.caption) }-                    if run.progress.nextReadyStepID == step.id {-                        switch step.kind {-                        case .treatment: Button("Done") { perform { try controller.record(runID: runID, stepID: step.id) } }-                        case .medication:-                            Text((step.dose ?? .unknown).displayText).font(.caption)-                            Button("Taken / Applied") { perform { try controller.record(runID: runID, stepID: step.id) } }-                        case .timedRoutine: Button("Open timer") { perform { childID = try controller.beginChild(parentID: runID, stepID: step.id) } }-                        }-                        Button("Skip step") { perform { try controller.skip(runID, stepID: step.id, confirm: false) } }-                    }-                    if saved.state == .skipped && !saved.skipConfirmed { Button("Continue with skipped step") { perform { try controller.skip(runID, stepID: step.id, confirm: true) } } }-                }+  let runID: UUID+  let controller: WatchController+  @State private var childID: UUID?+  @State private var offlineWarning = false+  @State private var ending = false+  private var run: CompanionRun? { controller.value(runID) }+  var body: some View {+    List {+      if let run {+        Text(run.definition.name).font(.headline)+        if controller.requiresPhoneResume(run) {+          Text("After restore, resume this saved session on iPhone, then refresh the Watch.")+        } else if controller.waitingHandoff.contains(runID) {+          Text("Waiting for the paused checkpoint to be acknowledged.")+          if controller.handoffWasRejected(runID) {+            Button("Retry handoff") { perform { try controller.takeOwnership(runID) } }.disabled(+              !controller.reachable)+          }+        } else if run.executionDeviceID != controller.deviceID {+          Button(controller.reachable ? "Continue on Watch" : "Continue offline on Watch") {+            if controller.reachable {+              perform { try controller.takeOwnership(runID) }+            } else {+              offlineWarning = true             }+          }+        } else if let timer = run.timer {+          timerControls(timer)+        } else {+          orderedControls(run)         }-        if run.progress.phase == .active { Button("Pause session") { perform { try controller.transitionGroup(runID, operation: .pause(runID: runID)) } } }-        if run.progress.phase == .paused { Button("Resume session") { perform { try controller.transitionGroup(runID, operation: .resume(runID: runID)) } } }-        if [.active, .paused, .needsReview].contains(run.progress.phase) { Button("End session", role: .destructive) { ending = true } }-    }-    @ViewBuilder private func timerControls(_ timer: TimerCheckpoint) -> some View {-        TimelineView(.periodic(from: .now, by: 1)) { tick in-            Text(Duration.seconds(timer.remaining(at: ExecutionClock.sample())).formatted(.time(pattern: .minuteSecond))).font(.title).monospacedDigit()-                .onChange(of: tick.date) { _, _ in controller.tick() }+        if run.status == .needsReview {+          Text(+            "Needs review on iPhone. Real logs remain saved; do not repeat medication to repair progress."+          )         }-        Text("Round \(min(timer.roundIndex + 1, timer.roundCount)) of \(timer.roundCount)")-        switch timer.phase {-        case .ready: Button("Start round") { transition(.start) }-        case .running: Button("Pause") { transition(.pause) }-        case .waiting:-            Text(run?.definition.betweenRoundInstructions ?? "")-            Text("No active timer between rounds").font(.caption)-            Button("Start next round") { transition(.start) }-        case .paused, .interrupted:-            Text("Confirm remaining active time before resuming.").font(.caption)-            Button("Resume remaining time") { transition(.resume) }-        case .completed: Label("\(timer.completedRounds) / \(timer.roundCount) complete", systemImage: "checkmark.circle.fill")-        case .ended: Text("Ended incomplete"); Button("Reopen") { transition(.reopen) }+        if let message = controller.runtimeMessage { Text(message).font(.caption) }+      } else {+        Text("Saved session unavailable. Refresh from the phone.")+      }+    }+    .navigationTitle("Saved session")+    .navigationDestination(item: $childID) { id in WatchRunView(runID: id, controller: controller) }+    .confirmationDialog("End this session incomplete?", isPresented: $ending) {+      Button("End session", role: .destructive) {+        perform { try controller.transitionGroup(runID, operation: .end(runID: runID)) }+      }+      Button("Cancel", role: .cancel) {}+    } message: {+      Text("Real logs are kept. Unfinished steps remain unfinished.")+    }+    .confirmationDialog("Execute this cached session offline?", isPresented: $offlineWarning) {+      Button("Confirm offline execution") {+        perform { try controller.takeOwnership(runID, offlineConfirmed: true) }+      }+      Button("Cancel", role: .cancel) {}+    } message: {+      Text(+        "Another device may still be running. Each actual action will be preserved and conflicting progress will need review on the phone."+      )+    }+  }+  @ViewBuilder private func orderedControls(_ run: CompanionRun) -> some View {+    Text(+      "\(run.progress.steps.filter { $0.state == .completed }.count) of \(run.progress.steps.count) steps completed"+    ).font(.caption)+    ForEach(run.definition.steps) { step in+      if let saved = run.progress.steps.first(where: { $0.id == step.id }) {+        VStack(alignment: .leading) {+          Text(step.name)+          Text(saved.state.rawValue).font(.caption)+          if !step.instructions.isEmpty { Text(step.instructions).font(.caption) }+          if !step.requirements.isEmpty { Text(step.requirements).font(.caption) }+          if run.progress.nextReadyStepID == step.id {+            switch step.kind {+            case .treatment:+              Button("Done") { perform { try controller.record(runID: runID, stepID: step.id) } }+            case .medication:+              Text((step.dose ?? .unknown).displayText).font(.caption)+              Button("Taken / Applied") {+                perform { try controller.record(runID: runID, stepID: step.id) }+              }+            case .timedRoutine:+              Button("Open timer") {+                perform { childID = try controller.beginChild(parentID: runID, stepID: step.id) }+              }+            }+            Button("Skip step") {+              perform { try controller.skip(runID, stepID: step.id, confirm: false) }+            }+          }+          if saved.state == .skipped && !saved.skipConfirmed {+            Button("Continue with skipped step") {+              perform { try controller.skip(runID, stepID: step.id, confirm: true) }+            }+          }         }-        if ![.completed, .ended].contains(timer.phase) { Button("End timer", role: .destructive) { transition(.end) } }+      }+    }+    if run.progress.phase == .active {+      Button("Pause session") {+        perform { try controller.transitionGroup(runID, operation: .pause(runID: runID)) }+      }+    }+    if run.progress.phase == .paused {+      Button("Resume session") {+        perform { try controller.transitionGroup(runID, operation: .resume(runID: runID)) }+      }+    }+    if [.active, .paused, .needsReview].contains(run.progress.phase) {+      Button("End session", role: .destructive) { ending = true }+    }+  }+  @ViewBuilder private func timerControls(_ timer: TimerCheckpoint) -> some View {+    TimelineView(.periodic(from: .now, by: 1)) { tick in+      Text(+        Duration.seconds(timer.remaining(at: ExecutionClock.sample())).formatted(+          .time(pattern: .minuteSecond))+      ).font(.title).monospacedDigit()+        .onChange(of: tick.date) { _, _ in controller.tick() }+    }+    Text("Round \(min(timer.roundIndex + 1, timer.roundCount)) of \(timer.roundCount)")+    switch timer.phase {+    case .ready: Button("Start round") { transition(.start) }+    case .running: Button("Pause") { transition(.pause) }+    case .waiting:+      Text(run?.definition.betweenRoundInstructions ?? "")+      Text("No active timer between rounds").font(.caption)+      Button("Start next round") { transition(.start) }+    case .paused, .interrupted:+      Text("Confirm remaining active time before resuming.").font(.caption)+      Button("Resume remaining time") { transition(.resume) }+    case .completed:+      Label(+        "\(timer.completedRounds) / \(timer.roundCount) complete",+        systemImage: "checkmark.circle.fill")+    case .ended:+      Text("Ended incomplete")+      Button("Reopen") { transition(.reopen) }+    }+    if ![.completed, .ended].contains(timer.phase) {+      Button("End timer", role: .destructive) { transition(.end) }     }-    private func transition(_ operation: TimerOperation) { perform { try controller.transitionTimer(runID, operation) } }-    private func perform(_ action: () throws -> Void) { do { try action() } catch { controller.error = error.localizedDescription } }+  }+  private func transition(_ operation: TimerOperation) {+    perform { try controller.transitionTimer(runID, operation) }+  }+  private func perform(_ action: () throws -> Void) {+    do { try action() } catch { controller.error = error.localizedDescription }+  } }
Meddy/MeddyWatch/MeddyWatchApp.swift Modified
diff --git a/Meddy/MeddyWatch/MeddyWatchApp.swift b/Meddy/MeddyWatch/MeddyWatchApp.swiftindex 8f3f520..12e1917 100644--- a/Meddy/MeddyWatch/MeddyWatchApp.swift+++ b/Meddy/MeddyWatch/MeddyWatchApp.swift@@ -9,9 +9,9 @@ import SwiftUI  @main struct MeddyWatchApp: App {-    var body: some Scene {-        WindowGroup {-            ContentView()-        }+  var body: some Scene {+    WindowGroup {+      ContentView()     }+  } }
Meddy/MeddyWatch/RoundRuntime.swift Modified
diff --git a/Meddy/MeddyWatch/RoundRuntime.swift b/Meddy/MeddyWatch/RoundRuntime.swiftindex a0201c8..5c7680e 100644--- a/Meddy/MeddyWatch/RoundRuntime.swift+++ b/Meddy/MeddyWatch/RoundRuntime.swift@@ -3,50 +3,69 @@ import WatchKit  @MainActor protocol RoundRuntimeManaging: AnyObject {-    var onBoundary: () -> Void { get set }-    var onInterrupted: (String) -> Void { get set }-    func start(deadline: Date)-    func stop()+  var onBoundary: () -> Void { get set }+  var onInterrupted: (String) -> Void { get set }+  func start(deadline: Date)+  func stop() }  @MainActor final class RoundRuntime: NSObject, RoundRuntimeManaging, WKExtendedRuntimeSessionDelegate {-    private var session: WKExtendedRuntimeSession?-    private var boundaryTimer: Timer?-    var onBoundary: () -> Void = {}-    var onInterrupted: (String) -> Void = { _ in }+  private var session: WKExtendedRuntimeSession?+  private var boundaryTimer: Timer?+  var onBoundary: () -> Void = {}+  var onInterrupted: (String) -> Void = { _ in } -    func start(deadline: Date) {-        stop()-        guard WKExtension.shared().applicationState == .active else {-            onInterrupted("Keep Meddy frontmost before starting a round."); return-        }-        let value = WKExtendedRuntimeSession()-        value.delegate = self; session = value-        boundaryTimer = Timer(fire: deadline, interval: 0, repeats: false) { [weak self] _ in Task { @MainActor in self?.onBoundary() } }-        if let boundaryTimer { RunLoop.main.add(boundaryTimer, forMode: .common) }-        value.start()+  func start(deadline: Date) {+    stop()+    guard WKApplication.shared().applicationState == .active else {+      onInterrupted("Keep Meddy frontmost before starting a round.")+      return     }-    func stop() {-        boundaryTimer?.invalidate(); boundaryTimer = nil-        session?.delegate = nil-        if session?.state == .running { session?.invalidate() }-        session = nil+    let value = WKExtendedRuntimeSession()+    value.delegate = self+    session = value+    boundaryTimer = Timer(fire: deadline, interval: 0, repeats: false) { [weak self] _ in+      Task { @MainActor in self?.onBoundary() }     }-    nonisolated func extendedRuntimeSessionDidStart(_ extendedRuntimeSession: WKExtendedRuntimeSession) {}-    nonisolated func extendedRuntimeSessionWillExpire(_ extendedRuntimeSession: WKExtendedRuntimeSession) {-        let identity = ObjectIdentifier(extendedRuntimeSession)-        Task { @MainActor [weak self] in-            guard let self, self.session.map(ObjectIdentifier.init) == identity else { return }-            self.onInterrupted("Self Care runtime is expiring. This round has been paused; confirm the remaining time before resuming.")-        }+    if let boundaryTimer { RunLoop.main.add(boundaryTimer, forMode: .common) }+    value.start()+  }+  func stop() {+    boundaryTimer?.invalidate()+    boundaryTimer = nil+    session?.delegate = nil+    if session?.state == .running { session?.invalidate() }+    session = nil+  }+  nonisolated func extendedRuntimeSessionDidStart(+    _ extendedRuntimeSession: WKExtendedRuntimeSession+  ) {}+  nonisolated func extendedRuntimeSessionWillExpire(+    _ extendedRuntimeSession: WKExtendedRuntimeSession+  ) {+    let identity = ObjectIdentifier(extendedRuntimeSession)+    Task { @MainActor [weak self] in+      guard let self, self.session.map(ObjectIdentifier.init) == identity else { return }+      self.onInterrupted(+        "Self Care runtime is expiring. This round has been paused; confirm the remaining time before resuming."+      )     }-    nonisolated func extendedRuntimeSession(_ extendedRuntimeSession: WKExtendedRuntimeSession, didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?) {-        let message = error?.localizedDescription ?? "Watch runtime ended (\(reason.rawValue)). This round has been paused."-        let identity = ObjectIdentifier(extendedRuntimeSession)-        Task { @MainActor [weak self] in-            guard let self, self.session.map(ObjectIdentifier.init) == identity else { return }-            self.boundaryTimer?.invalidate(); self.boundaryTimer = nil; self.session = nil; self.onInterrupted(message)-        }+  }+  nonisolated func extendedRuntimeSession(+    _ extendedRuntimeSession: WKExtendedRuntimeSession,+    didInvalidateWith reason: WKExtendedRuntimeSessionInvalidationReason, error: Error?+  ) {+    let message =+      error?.localizedDescription+      ?? "Watch runtime ended (\(reason.rawValue)). This round has been paused."+    let identity = ObjectIdentifier(extendedRuntimeSession)+    Task { @MainActor [weak self] in+      guard let self, self.session.map(ObjectIdentifier.init) == identity else { return }+      self.boundaryTimer?.invalidate()+      self.boundaryTimer = nil+      self.session = nil+      self.onInterrupted(message)     }+  } }
Meddy/MeddyWatch/WatchController.swift Modified
diff --git a/Meddy/MeddyWatch/WatchController.swift b/Meddy/MeddyWatch/WatchController.swiftindex 0f96333..21229d4 100644--- a/Meddy/MeddyWatch/WatchController.swift+++ b/Meddy/MeddyWatch/WatchController.swift@@ -4,308 +4,569 @@ import WatchKit  @MainActor @Observable final class WatchController {-    private(set) var snapshot: CompanionSnapshot?-    private(set) var pendingCount = 0-    private(set) var reachable = false-    private(set) var localRuns: [UUID: CompanionRun] = [:]-    private(set) var waitingHandoff: Set<UUID> = []-    var selectedProfileID = ProfileIdentity.me-    var error: String?-    var runtimeMessage: String?-    @ObservationIgnored private var store: CompanionStore?-    @ObservationIgnored private let transportEnabled: Bool-    @ObservationIgnored private let transport = CompanionTransport()-    @ObservationIgnored private let runtime: any RoundRuntimeManaging-    @ObservationIgnored private let runtimeEnabled: Bool-    @ObservationIgnored private let clock: () -> ClockSample-    @ObservationIgnored private let haptic: () -> Void-    @ObservationIgnored private(set) var foregroundRunID: UUID?-    var deviceID: String { store?.state.deviceID ?? "unavailable" }-    var runs: [CompanionRun] {-        var values = Dictionary(uniqueKeysWithValues: (snapshot?.runs ?? []).map { ($0.id, $0) })-        for (id, run) in localRuns { values[id] = run }-        return values.values.filter { !$0.isDeleted }.sorted { ($0.startedAt ?? .distantPast) > ($1.startedAt ?? .distantPast) }+  private(set) var snapshot: CompanionSnapshot?+  private(set) var pendingCount = 0+  private(set) var reachable = false+  private(set) var localRuns: [UUID: CompanionRun] = [:]+  private(set) var waitingHandoff: Set<UUID> = []+  var selectedProfileID = ProfileIdentity.me+  var error: String?+  var runtimeMessage: String?+  @ObservationIgnored private var store: CompanionStore?+  @ObservationIgnored private let transportEnabled: Bool+  @ObservationIgnored private let transport = CompanionTransport()+  @ObservationIgnored private let runtime: any RoundRuntimeManaging+  @ObservationIgnored private let runtimeEnabled: Bool+  @ObservationIgnored private let clock: () -> ClockSample+  @ObservationIgnored private let haptic: () -> Void+  @ObservationIgnored private(set) var foregroundRunID: UUID?+  var deviceID: String { store?.state.deviceID ?? "unavailable" }+  var runs: [CompanionRun] {+    var values = Dictionary(uniqueKeysWithValues: (snapshot?.runs ?? []).map { ($0.id, $0) })+    for (id, run) in localRuns { values[id] = run }+    return values.values.filter { !$0.isDeleted }.sorted {+      ($0.startedAt ?? .distantPast) > ($1.startedAt ?? .distantPast)     }-    init(file: URL? = nil, activate: Bool = true, runtime: (any RoundRuntimeManaging)? = nil, clock: @escaping () -> ClockSample = ExecutionClock.sample, haptic: (() -> Void)? = nil) {-        let testing = ProcessInfo.processInfo.environment["MEDDY_TESTING"] == "1" || ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil-        transportEnabled = activate && !testing-        runtimeEnabled = transportEnabled || runtime != nil-        self.runtime = runtime ?? RoundRuntime(); self.clock = clock-        self.haptic = haptic ?? { if !testing { WKInterfaceDevice.current().play(.success) } }-        do {-            let isolated = FileManager.default.temporaryDirectory.appendingPathComponent("MeddyTest-" + UUID().uuidString).appendingPathComponent("cache.json")-            let path = file ?? (testing ? isolated : FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("MeddyCompanion/cache.json"))-            store = try CompanionStore(file: path)-            reload()-        } catch { self.error = "Watch storage could not be opened: \(error.localizedDescription). Existing actions were not discarded." }-        self.runtime.onInterrupted = { [weak self] reason in self?.interrupt(reason) }-        self.runtime.onBoundary = { [weak self] in self?.tick() }-        transport.onError = { [weak self] in self?.error = $0 }-        transport.onActivation = { [weak self] in self?.refresh() }-        transport.onMessage = { [weak self] message, _ in self?.receive(message) }-        // A relaunch cannot establish continuity with a persisted running timer.-        for run in runs where run.timer?.phase == .running && run.executionDeviceID == deviceID {-            do { try transitionTimer(run.id, .advance) } catch { self.error = error.localizedDescription }-        }-        if transportEnabled { transport.activate() }+  }+  init(+    file: URL? = nil, activate: Bool = true, runtime: (any RoundRuntimeManaging)? = nil,+    clock: @escaping () -> ClockSample = ExecutionClock.sample, haptic: (() -> Void)? = nil+  ) {+    let testing =+      ProcessInfo.processInfo.environment["MEDDY_TESTING"] == "1"+      || ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil+    transportEnabled = activate && !testing+    runtimeEnabled = transportEnabled || runtime != nil+    self.runtime = runtime ?? RoundRuntime()+    self.clock = clock+    self.haptic = haptic ?? { if !testing { WKInterfaceDevice.current().play(.success) } }+    do {+      let isolated = FileManager.default.temporaryDirectory.appendingPathComponent(+        "MeddyTest-" + UUID().uuidString+      ).appendingPathComponent("cache.json")+      let path =+        file+        ?? (testing+          ? isolated+          : FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+            .appendingPathComponent("MeddyCompanion/cache.json"))+      store = try CompanionStore(file: path)+      reload()+    } catch {+      self.error =+        "Watch storage could not be opened: \(error.localizedDescription). Existing actions were not discarded."     }-    func refresh() {-        guard transportEnabled else { return }-        reachable = transport.reachable-        do {-            try transport.send(.requestSnapshot)-            if let action = store?.state.pending.first { try transport.send(.action(action)) }-            processIncomingHandoffs()-        } catch { self.error = error.localizedDescription }+    self.runtime.onInterrupted = { [weak self] reason in self?.interrupt(reason) }+    self.runtime.onBoundary = { [weak self] in self?.tick() }+    transport.onError = { [weak self] in self?.error = $0 }+    transport.onActivation = { [weak self] in self?.refresh() }+    transport.onMessage = { [weak self] message, _ in self?.receive(message) }+    // A relaunch cannot establish continuity with a persisted running timer.+    for run in runs where run.timer?.phase == .running && run.executionDeviceID == deviceID {+      do { try transitionTimer(run.id, .advance) } catch { self.error = error.localizedDescription }     }-    func occurrences(_ routine: CompanionRoutine, now: Date = Date(), calendar: Calendar = .current) -> [RoutineOccurrence] {-        guard let schedule = routine.schedule else { return routine.occurrences }-        let represented = runs.map { run in-            ScheduledRunSnapshot(id: run.id, routineID: run.definition.routineID, occurrenceKey: run.definition.occurrence?.key,-                slotID: run.definition.occurrence?.slotID, localDate: run.definition.occurrence?.localDate, startedAt: run.startedAt,-                timeZoneID: run.definition.occurrence?.timeZoneID, scheduledAt: run.definition.occurrence?.scheduledAt,-                status: run.status, isDeleted: run.isDeleted)-        }-        return RoutineScheduleEngine().occurrences(schedule, runs: represented, day: now, now: now, calendar: calendar)+    if transportEnabled { transport.activate() }+  }+  func refresh() {+    guard transportEnabled else { return }+    reachable = transport.reachable+    do {+      try transport.send(.requestSnapshot)+      if let action = store?.state.pending.first { try transport.send(.action(action)) }+      processIncomingHandoffs()+    } catch { self.error = error.localizedDescription }+  }+  func occurrences(_ routine: CompanionRoutine, now: Date = Date(), calendar: Calendar = .current)+    -> [RoutineOccurrence] {+    guard let schedule = routine.schedule else { return routine.occurrences }+    let represented = runs.map { run in+      ScheduledRunSnapshot(+        id: run.id, routineID: run.definition.routineID,+        occurrenceKey: run.definition.occurrence?.key,+        slotID: run.definition.occurrence?.slotID, localDate: run.definition.occurrence?.localDate,+        startedAt: run.startedAt,+        timeZoneID: run.definition.occurrence?.timeZoneID,+        scheduledAt: run.definition.occurrence?.scheduledAt,+        status: run.status, isDeleted: run.isDeleted)     }-    func value(_ id: UUID) -> CompanionRun? { runs.first { $0.id == id } }-    func start(_ routine: CompanionRoutine, occurrence: RoutineOccurrence?) throws -> UUID {-        if let id = occurrence?.existingRunID { return id }-        var definition = routine.definition-        if let occurrence { definition.occurrence = .init(key: occurrence.key, slotID: occurrence.slotID, localDate: occurrence.localDate, timeZoneID: occurrence.timeZoneID, scheduledAt: occurrence.scheduledAt) }-        if let foregroundRunID, let other = value(foregroundRunID), other.timer?.phase == .running, CompanionOwnership.owner(other) == (routine.definition.profileID ?? ProfileIdentity.me) {-            if let parentID = other.parentRunID { try transitionGroup(parentID, operation: .pause(runID: parentID)) }-            else { try transitionTimer(foregroundRunID, .pause) }-        }-        let id = occurrence?.id ?? UUID()-        if value(id) != nil { return id }-        var run = CompanionRun(id: id, definition: definition, progress: .init(definition: definition), timer: definition.kind == .timedRounds ? try TimerCheckpoint(rounds: definition.roundCount ?? 0, durationSeconds: definition.roundDurationSeconds ?? 0) : nil, status: .active, startedAt: Date(), revision: 0, executionDeviceID: deviceID, processedActionIDs: [], isDeleted: false)-        run = ownedRun(run)-        let action = CompanionAction(id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: nil, operation: .start(run), cachedRun: run)-        try enqueue(action, run: run)-        return id+    return RoutineScheduleEngine().occurrences(+      schedule, runs: represented, day: now, now: now, calendar: calendar)+  }+  func value(_ id: UUID) -> CompanionRun? { runs.first { $0.id == id } }+  func start(_ routine: CompanionRoutine, occurrence: RoutineOccurrence?) throws -> UUID {+    if let id = occurrence?.existingRunID { return id }+    var definition = routine.definition+    if let occurrence {+      definition.occurrence = .init(+        key: occurrence.key, slotID: occurrence.slotID, localDate: occurrence.localDate,+        timeZoneID: occurrence.timeZoneID, scheduledAt: occurrence.scheduledAt)     }-    func markMedication(_ medication: CompanionMedication) throws {-        let id = UUID(); let now = Date()-        let event = AdministrationAction(eventID: id, medicationID: medication.id, timestamp: now, source: .watch, dose: medication.dose, scheduleTypeAtRecording: medication.schedule.mode, scheduleGenerationID: medication.schedule.generationID, wakeEventID: medication.schedule.wakeAnchor?.id)-        try enqueue(.init(id: id, deviceID: deviceID, timestamp: now, operation: .medication(event, runID: nil, stepID: nil)))+    if let foregroundRunID, let other = value(foregroundRunID), other.timer?.phase == .running,+      CompanionOwnership.owner(other) == (routine.definition.profileID ?? ProfileIdentity.me) {+      if let parentID = other.parentRunID {+        try transitionGroup(parentID, operation: .pause(runID: parentID))+      } else {+        try transitionTimer(foregroundRunID, .pause)+      }     }-    func lastTaken(_ medication: CompanionMedication) -> Date? {-        let deleted = Set(snapshot?.deletedEventIDs ?? [])-        let pending = (store?.state.pending ?? []).compactMap { action -> Date? in-            guard case .medication(let event, _, _) = action.operation, event.medicationID == medication.id, !deleted.contains(event.eventID) else { return nil }-            return event.timestamp-        }.max()-        return [medication.lastTaken, pending].compactMap { $0 }.max()+    let id = occurrence?.id ?? UUID()+    if value(id) != nil { return id }+    var run = CompanionRun(+      id: id, definition: definition, progress: .init(definition: definition),+      timer: definition.kind == .timedRounds+        ? try TimerCheckpoint(+          rounds: definition.roundCount ?? 0, durationSeconds: definition.roundDurationSeconds ?? 0)+        : nil, status: .active, startedAt: Date(), revision: 0, executionDeviceID: deviceID,+      processedActionIDs: [], isDeleted: false)+    run = ownedRun(run)+    let action = CompanionAction(+      id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: nil,+      operation: .start(run), cachedRun: run)+    try enqueue(action, run: run)+    return id+  }+  func markMedication(_ medication: CompanionMedication) throws {+    let id = UUID()+    let now = Date()+    let event = AdministrationAction(+      eventID: id, medicationID: medication.id, timestamp: now, source: .watch,+      dose: medication.dose, scheduleTypeAtRecording: medication.schedule.mode,+      scheduleGenerationID: medication.schedule.generationID,+      wakeEventID: medication.schedule.wakeAnchor?.id)+    try enqueue(+      .init(+        id: id, deviceID: deviceID, timestamp: now,+        operation: .medication(event, runID: nil, stepID: nil)))+  }+  func lastTaken(_ medication: CompanionMedication) -> Date? {+    let deleted = Set(snapshot?.deletedEventIDs ?? [])+    let pending = (store?.state.pending ?? []).compactMap { action -> Date? in+      guard case .medication(let event, _, _) = action.operation,+        event.medicationID == medication.id, !deleted.contains(event.eventID)+      else { return nil }+      return event.timestamp+    }.max()+    return [medication.lastTaken, pending].compactMap { $0 }.max()+  }+  func markTreatment(_ treatment: CompanionTreatment) throws {+    let id = UUID()+    let now = Date()+    let event = TreatmentAction(+      eventID: id, treatmentID: treatment.id, timestamp: now,+      instructionsSnapshot: treatment.instructions, source: .watch)+    try enqueue(+      .init(+        id: id, deviceID: deviceID, timestamp: now,+        operation: .treatment(event, runID: nil, stepID: nil)))+  }++  func record(runID: UUID, stepID: UUID) throws {+    guard var run = value(runID), run.executionDeviceID == deviceID, run.status != .needsReview,+      let step = run.definition.steps.first(where: { $0.id == stepID }),+      run.progress.nextReadyStepID == stepID, !waitingHandoff.contains(runID)+    else { throw ExecutionError.stepNotReady }+    let id = UUID()+    let now = Date()+    let operation: CompanionOperation+    switch step.kind {+    case .medication:+      let event = AdministrationAction(+        eventID: id, medicationID: step.targetID, timestamp: now, source: .watch,+        dose: step.dose ?? .unknown, scheduleTypeAtRecording: .routineManaged,+        scheduleGenerationID: nil)+      operation = .medication(event, runID: run.id, stepID: step.id)+    case .treatment:+      operation = .treatment(+        .init(+          eventID: id, treatmentID: step.targetID, timestamp: now,+          instructionsSnapshot: step.instructions, source: .watch), runID: run.id, stepID: step.id)+    case .timedRoutine: throw ExecutionError.invalidTransition     }-    func markTreatment(_ treatment: CompanionTreatment) throws {-        let id = UUID(); let now = Date()-        let event = TreatmentAction(eventID: id, treatmentID: treatment.id, timestamp: now, instructionsSnapshot: treatment.instructions, source: .watch)-        try enqueue(.init(id: id, deviceID: deviceID, timestamp: now, operation: .treatment(event, runID: nil, stepID: nil)))+    let cached = run+    try run.progress.markCompleted(stepID: step.id, eventID: id, at: now, actionID: id)+    run.status = run.progress.phase+    run.revision += 1+    try enqueue(+      .init(+        id: id, deviceID: deviceID, timestamp: now, expectedRevision: cached.revision,+        operation: operation, cachedRun: cached), run: run)+  }+  func beginChild(parentID: UUID, stepID: UUID) throws -> UUID {+    guard var parent = value(parentID),+      let step = parent.definition.steps.first(where: { $0.id == stepID }),+      step.kind == .timedRoutine+    else { throw ExecutionError.unknownStep }+    if let progress = parent.progress.steps.first(where: { $0.id == stepID }),+      let id = progress.canonicalEventID, value(id) != nil {+      return id     }--    func record(runID: UUID, stepID: UUID) throws {-        guard var run = value(runID), run.executionDeviceID == deviceID, run.status != .needsReview, let step = run.definition.steps.first(where: { $0.id == stepID }), run.progress.nextReadyStepID == stepID, !waitingHandoff.contains(runID) else { throw ExecutionError.stepNotReady }-        let id = UUID(); let now = Date(); let operation: CompanionOperation-        switch step.kind {-        case .medication:-            let event = AdministrationAction(eventID: id, medicationID: step.targetID, timestamp: now, source: .watch, dose: step.dose ?? .unknown, scheduleTypeAtRecording: .routineManaged, scheduleGenerationID: nil)-            operation = .medication(event, runID: run.id, stepID: step.id)-        case .treatment:-            operation = .treatment(.init(eventID: id, treatmentID: step.targetID, timestamp: now, instructionsSnapshot: step.instructions, source: .watch), runID: run.id, stepID: step.id)-        case .timedRoutine: throw ExecutionError.invalidTransition+    guard parent.progress.nextReadyStepID == stepID, parent.executionDeviceID == deviceID,+      !waitingHandoff.contains(parentID)+    else { throw ExecutionError.stepNotReady }+    let id = ScheduleCalendar.identity("child|\(parentID)|\(stepID)")+    var definition = FrozenRoutineDefinition(+      routineID: step.targetID, revision: parent.definition.revision, kind: .timedRounds,+      name: step.name, instructions: step.instructions, roundCount: step.roundCount,+      roundDurationSeconds: step.roundDurationSeconds,+      betweenRoundInstructions: step.betweenRoundInstructions, steps: [])+    definition.profileID = parent.definition.profileID+    definition.ownershipVersion = parent.definition.ownershipVersion+    definition.profileLifecycleID =+      parent.profileLifecycleID ?? parent.definition.profileLifecycleID+    let child = CompanionRun(+      id: id, definition: definition, progress: .init(definition: definition),+      timer: try TimerCheckpoint(+        rounds: step.roundCount ?? 0, durationSeconds: step.roundDurationSeconds ?? 0),+      status: .active, startedAt: Date(), revision: 0, executionDeviceID: deviceID,+      parentRunID: parentID, parentStepID: stepID, processedActionIDs: [], isDeleted: false)+    let cached = parent+    guard let index = parent.progress.steps.firstIndex(where: { $0.id == stepID }) else {+      throw ExecutionError.unknownStep+    }+    parent.progress.steps[index].state = .inProgress+    parent.progress.steps[index].canonicalEventID = id+    parent.revision += 1+    try enqueue(+      .init(+        id: UUID(), deviceID: deviceID, timestamp: Date(), operation: .start(child),+        cachedRun: child, cachedParentRun: cached), runs: [child, parent])+    return id+  }+  func takeOwnership(_ id: UUID, offlineConfirmed: Bool = false) throws {+    guard let run = value(id) else { throw ExecutionError.unknownRun }+    if run.executionDeviceID == deviceID { return }+    if reachable {+      if let previous = store?.state.pending.first(where: {+        if case .handoff(let runID, _, _) = $0.operation { return runID == id }+        return false+      }) {+        guard store?.state.rejected[previous.id] != nil else {+          refresh()+          return         }-        let cached = run-        try run.progress.markCompleted(stepID: step.id, eventID: id, at: now, actionID: id)-        run.status = run.progress.phase; run.revision += 1-        try enqueue(.init(id: id, deviceID: deviceID, timestamp: now, expectedRevision: cached.revision, operation: operation, cachedRun: cached), run: run)+        try store?.discardRejectedHandoff(previous.id)+      }+      try enqueue(+        .init(+          id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: run.revision,+          operation: .handoff(runID: id, checkpoint: run, toDeviceID: deviceID), cachedRun: run))+    } else {+      guard offlineConfirmed else { throw ExecutionError.invalidTransition }+      var local = run+      local.executionDeviceID = deviceID+      if var timer = local.timer, timer.phase == .running {+        timer.phase = .interrupted+        timer.anchor = nil+        timer.deadline = nil+        local.timer = timer+      }+      try store?.saveLocal([local])+      reload()     }-    func beginChild(parentID: UUID, stepID: UUID) throws -> UUID {-        guard var parent = value(parentID), let step = parent.definition.steps.first(where: { $0.id == stepID }), step.kind == .timedRoutine else { throw ExecutionError.unknownStep }-        if let progress = parent.progress.steps.first(where: { $0.id == stepID }), let id = progress.canonicalEventID, value(id) != nil { return id }-        guard parent.progress.nextReadyStepID == stepID, parent.executionDeviceID == deviceID, !waitingHandoff.contains(parentID) else { throw ExecutionError.stepNotReady }-        let id = ScheduleCalendar.identity("child|\(parentID)|\(stepID)")-        var definition = FrozenRoutineDefinition(routineID: step.targetID, revision: parent.definition.revision, kind: .timedRounds, name: step.name, instructions: step.instructions, roundCount: step.roundCount, roundDurationSeconds: step.roundDurationSeconds, betweenRoundInstructions: step.betweenRoundInstructions, steps: [])-        definition.profileID = parent.definition.profileID; definition.ownershipVersion = parent.definition.ownershipVersion; definition.profileLifecycleID = parent.profileLifecycleID ?? parent.definition.profileLifecycleID-        let child = CompanionRun(id: id, definition: definition, progress: .init(definition: definition), timer: try TimerCheckpoint(rounds: step.roundCount ?? 0, durationSeconds: step.roundDurationSeconds ?? 0), status: .active, startedAt: Date(), revision: 0, executionDeviceID: deviceID, parentRunID: parentID, parentStepID: stepID, processedActionIDs: [], isDeleted: false)-        let cached = parent-        guard let index = parent.progress.steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-        parent.progress.steps[index].state = .inProgress; parent.progress.steps[index].canonicalEventID = id; parent.revision += 1-        try enqueue(.init(id: UUID(), deviceID: deviceID, timestamp: Date(), operation: .start(child), cachedRun: child, cachedParentRun: cached), runs: [child, parent])-        return id+  }+  func handoffWasRejected(_ id: UUID) -> Bool {+    store?.state.pending.contains {+      $0.operation.runID == id && store?.state.rejected[$0.id] != nil+    } ?? false+  }+  func transitionTimer(_ id: UUID, _ operation: TimerOperation) throws {+    guard var run = value(id), run.status != .needsReview, var timer = run.timer,+      run.executionDeviceID == deviceID+    else { throw ExecutionError.invalidTransition }+    if waitingHandoff.contains(id), operation != .pause && operation != .end {+      throw ExecutionError.invalidTransition     }-    func takeOwnership(_ id: UUID, offlineConfirmed: Bool = false) throws {-        guard let run = value(id) else { throw ExecutionError.unknownRun }-        if run.executionDeviceID == deviceID { return }-        if reachable {-            if let previous = store?.state.pending.first(where: { if case .handoff(let runID, _, _) = $0.operation { return runID == id }; return false }) {-                guard store?.state.rejected[previous.id] != nil else { refresh(); return }-                try store?.discardRejectedHandoff(previous.id)-            }-            try enqueue(.init(id: UUID(), deviceID: deviceID, timestamp: Date(), expectedRevision: run.revision, operation: .handoff(runID: id, checkpoint: run, toDeviceID: deviceID), cachedRun: run))-        } else {-            guard offlineConfirmed else { throw ExecutionError.invalidTransition }-            var local = run; local.executionDeviceID = deviceID-            if var timer = local.timer, timer.phase == .running { timer.phase = .interrupted; timer.anchor = nil; timer.deadline = nil; local.timer = timer }-            try store?.saveLocal([local]); reload()-        }+    if [.start, .resume].contains(operation), let other = foregroundRunID, other != id,+      value(other)?.timer?.phase == .running {+      throw ExecutionError.invalidTransition     }-    func handoffWasRejected(_ id: UUID) -> Bool {-        store?.state.pending.contains { $0.operation.runID == id && store?.state.rejected[$0.id] != nil } ?? false+    let before = run+    let clock = self.clock()+    switch operation {+    case .start: try timer.start(at: clock)+    case .pause: try timer.pause(at: clock)+    case .resume: try timer.resume(at: clock)+    case .end: try timer.end(at: clock)+    case .reopen: try timer.reopen()+    case .advance: timer.advance(at: clock)     }-    func transitionTimer(_ id: UUID, _ operation: TimerOperation) throws {-        guard var run = value(id), run.status != .needsReview, var timer = run.timer, run.executionDeviceID == deviceID else { throw ExecutionError.invalidTransition }-        if waitingHandoff.contains(id), operation != .pause && operation != .end { throw ExecutionError.invalidTransition }-        if [.start, .resume].contains(operation), let other = foregroundRunID, other != id, value(other)?.timer?.phase == .running { throw ExecutionError.invalidTransition }-        let before = run; let clock = self.clock()-        switch operation {-        case .start: try timer.start(at: clock)-        case .pause: try timer.pause(at: clock)-        case .resume: try timer.resume(at: clock)-        case .end: try timer.end(at: clock)-        case .reopen: try timer.reopen()-        case .advance: timer.advance(at: clock)-        }-        guard timer != before.timer else { return }-        run.timer = timer; run.status = timer.phase == .completed ? .completed : (timer.phase == .ended ? .endedIncomplete : ([.paused, .interrupted].contains(timer.phase) ? .paused : .active)); run.completedAt = timer.phase == .completed ? Date() : nil; run.revision += 1-        var changed = [run]-        if timer.phase == .completed, let parentID = run.parentRunID, let stepID = run.parentStepID, var parent = value(parentID) {-            try parent.progress.markCompleted(stepID: stepID, eventID: run.id, at: clock.wall, actionID: UUID(), reportedOutOfOrder: true)-            parent.status = parent.progress.phase; parent.revision += 1; changed.append(parent)-        }-        let action = CompanionAction(id: UUID(), deviceID: deviceID, timestamp: clock.wall, expectedRevision: before.revision, operation: .timer(runID: id, operation: operation, checkpoint: timer), cachedRun: before, cachedParentRun: run.parentRunID.flatMap(value))-        try enqueue(action, runs: changed)-        if timer.phase == .running, let deadline = timer.deadline { foregroundRunID = id; if runtimeEnabled { runtime.start(deadline: deadline) } }-        else {-            if foregroundRunID == id { runtime.stop(); foregroundRunID = nil }-            if timer.completedRounds > (before.timer?.completedRounds ?? 0) { haptic() }-        }+    guard timer != before.timer else { return }+    run.timer = timer+    run.status =+      timer.phase == .completed+      ? .completed+      : (timer.phase == .ended+        ? .endedIncomplete : ([.paused, .interrupted].contains(timer.phase) ? .paused : .active))+    run.completedAt = timer.phase == .completed ? Date() : nil+    run.revision += 1+    var changed = [run]+    if timer.phase == .completed, let parentID = run.parentRunID, let stepID = run.parentStepID,+      var parent = value(parentID) {+      try parent.progress.markCompleted(+        stepID: stepID, eventID: run.id, at: clock.wall, actionID: UUID(), reportedOutOfOrder: true)+      parent.status = parent.progress.phase+      parent.revision += 1+      changed.append(parent)     }-    func skip(_ id: UUID, stepID: UUID, confirm: Bool) throws {-        try transitionGroup(id, operation: confirm ? .continueAfterSkip(runID: id, stepID: stepID) : .skip(runID: id, stepID: stepID))+    let action = CompanionAction(+      id: UUID(), deviceID: deviceID, timestamp: clock.wall, expectedRevision: before.revision,+      operation: .timer(runID: id, operation: operation, checkpoint: timer), cachedRun: before,+      cachedParentRun: run.parentRunID.flatMap(value))+    try enqueue(action, runs: changed)+    if timer.phase == .running, let deadline = timer.deadline {+      foregroundRunID = id+      if runtimeEnabled { runtime.start(deadline: deadline) }+    } else {+      if foregroundRunID == id {+        runtime.stop()+        foregroundRunID = nil+      }+      if timer.completedRounds > (before.timer?.completedRounds ?? 0) { haptic() }     }-    func transitionGroup(_ id: UUID, operation: CompanionOperation) throws {-        guard var run = value(id), run.timer == nil, run.executionDeviceID == deviceID else { throw ExecutionError.invalidTransition }-        if waitingHandoff.contains(id) { switch operation { case .pause, .end: break; default: throw ExecutionError.invalidTransition } }-        let cached = run; let actionID = UUID(); let clock = self.clock()-        var actions: [CompanionAction] = []; var changed: [CompanionRun] = []-        let ending: Bool-        var selectedStepID: UUID?-        switch operation {-        case .pause: try run.progress.pause(); ending = false-        case .resume: try run.progress.resume(); ending = false-        case .end: try run.progress.end(at: clock.wall); ending = true-        case .skip(_, let stepID): try run.progress.skip(stepID: stepID, actionID: actionID, at: clock.wall, reason: "Explicitly skipped on Watch"); ending = true; selectedStepID = stepID-        case .continueAfterSkip(_, let stepID): try run.progress.continueAfterSkip(stepID: stepID); ending = false-        default: throw ExecutionError.invalidTransition-        }-        let stopsTiming: Bool-        switch operation { case .resume, .continueAfterSkip: stopsTiming = false; default: stopsTiming = true }-        if stopsTiming {-            for var child in runs where child.parentRunID == id && (selectedStepID == nil || child.parentStepID == selectedStepID) {-                guard var timer = child.timer, timer.phase == .running || (ending && ![.completed, .ended].contains(timer.phase)) else { continue }-                let before = child-                if ending { try timer.end(at: clock) } else { try timer.pause(at: clock) }-                child.timer = timer; child.status = ending ? .endedIncomplete : .paused; child.revision += 1-                actions.append(.init(id: UUID(), deviceID: deviceID, timestamp: clock.wall, expectedRevision: before.revision, operation: .timer(runID: child.id, operation: ending ? .end : .pause, checkpoint: timer), cachedRun: before, cachedParentRun: cached))-                changed.append(child)-            }-        }-        run.status = run.progress.phase; run.revision += 1; changed.append(run)-        actions.append(.init(id: actionID, deviceID: deviceID, timestamp: clock.wall, expectedRevision: cached.revision, operation: operation, cachedRun: cached))-        guard let store else { throw ExecutionError.saveFailed }-        try store.enqueue(actions: actions.map { try ownedAction($0) }, localRuns: changed.map(ownedRun)); reload()-        if transportEnabled, let first = store.state.pending.first { try? transport.send(.action(first)) }+  }+  func skip(_ id: UUID, stepID: UUID, confirm: Bool) throws {+    try transitionGroup(+      id,+      operation: confirm+        ? .continueAfterSkip(runID: id, stepID: stepID) : .skip(runID: id, stepID: stepID))+  }+  func transitionGroup(_ id: UUID, operation: CompanionOperation) throws {+    guard var run = value(id), run.timer == nil, run.executionDeviceID == deviceID else {+      throw ExecutionError.invalidTransition     }-    func tick() { if let id = foregroundRunID { do { try transitionTimer(id, .advance) } catch { self.error = error.localizedDescription } } }-    private func interrupt(_ reason: String) {-        runtimeMessage = reason-        guard let id = foregroundRunID, value(id)?.timer?.phase == .running else { return }-        do { try transitionTimer(id, .pause) } catch { self.error = error.localizedDescription }+    if waitingHandoff.contains(id) {+      switch operation {+      case .pause, .end: break+      default: throw ExecutionError.invalidTransition+      }     }-    private func ownedRun(_ value: CompanionRun) -> CompanionRun {-        var run = value; run.profileID = run.profileID ?? run.definition.profileID-        run.ownershipVersion = run.ownershipVersion ?? run.definition.ownershipVersion-        run.profileLifecycleID = run.profileLifecycleID ?? run.definition.profileLifecycleID-        return run+    let cached = run+    let actionID = UUID()+    let clock = self.clock()+    var actions: [CompanionAction] = []+    var changed: [CompanionRun] = []+    let ending: Bool+    var selectedStepID: UUID?+    switch operation {+    case .pause:+      try run.progress.pause()+      ending = false+    case .resume:+      try run.progress.resume()+      ending = false+    case .end:+      try run.progress.end(at: clock.wall)+      ending = true+    case .skip(_, let stepID):+      try run.progress.skip(+        stepID: stepID, actionID: actionID, at: clock.wall, reason: "Explicitly skipped on Watch")+      ending = true+      selectedStepID = stepID+    case .continueAfterSkip(_, let stepID):+      try run.progress.continueAfterSkip(stepID: stepID)+      ending = false+    default: throw ExecutionError.invalidTransition     }-    private func ownedAction(_ value: CompanionAction) throws -> CompanionAction {-        var action = value-        var owner = action.cachedRun.map { CompanionOwnership.owner($0) } ?? action.cachedParentRun.map { CompanionOwnership.owner($0) }-        var lifecycle = action.cachedRun?.profileLifecycleID ?? action.cachedRun?.definition.profileLifecycleID-        switch action.operation {-        case .medication(var event, let runID, let stepID):-            let target = snapshot?.medications.first { $0.id == event.medicationID }-            owner = owner ?? target?.profileID ?? ProfileIdentity.me; lifecycle = lifecycle ?? target?.profileLifecycleID-            if snapshot?.version == 2 { event.profileID = owner; event.ownershipVersion = 1; event.profileLifecycleID = lifecycle }; action.operation = .medication(event, runID: runID, stepID: stepID)-        case .treatment(var event, let runID, let stepID):-            let target = snapshot?.treatments?.first { $0.id == event.treatmentID }-            owner = owner ?? target?.profileID ?? ProfileIdentity.me; lifecycle = lifecycle ?? target?.profileLifecycleID-            if snapshot?.version == 2 { event.profileID = owner; event.ownershipVersion = 1; event.profileLifecycleID = lifecycle }; action.operation = .treatment(event, runID: runID, stepID: stepID)-        case .start(let run): let run = ownedRun(run); owner = CompanionOwnership.owner(run); lifecycle = run.profileLifecycleID; action.operation = .start(run)-        case .handoff(let id, let run, let device): let run = ownedRun(run); owner = CompanionOwnership.owner(run); lifecycle = run.profileLifecycleID; action.operation = .handoff(runID: id, checkpoint: run, toDeviceID: device)-        default: if let id = action.operation.runID, let run = self.value(id) { owner = owner ?? CompanionOwnership.owner(run); lifecycle = lifecycle ?? run.profileLifecycleID ?? run.definition.profileLifecycleID }-        }-        action.cachedRun = action.cachedRun.map(ownedRun); action.cachedParentRun = action.cachedParentRun.map(ownedRun)-        if snapshot?.version == 2 { action.version = 2; action.profileID = owner ?? ProfileIdentity.me; action.ownershipVersion = 1; action.profileLifecycleID = lifecycle ?? ProfileIdentity.selfLifecycle }-        return action+    let stopsTiming: Bool+    switch operation {+    case .resume, .continueAfterSkip: stopsTiming = false+    default: stopsTiming = true     }-    private func enqueue(_ action: CompanionAction, run: CompanionRun? = nil) throws { try enqueue(action, runs: run.map { [$0] } ?? []) }-    private func enqueue(_ action: CompanionAction, runs: [CompanionRun]) throws {-        guard let store else { throw ExecutionError.saveFailed }-        let action = try ownedAction(action)-        try store.enqueue(action, localRuns: runs.map(ownedRun)); reload()-        if transportEnabled, store.state.pending.first?.id == action.id { try? transport.send(.action(action)) }+    if stopsTiming {+      for var child in runs+      where child.parentRunID == id+        && (selectedStepID == nil || child.parentStepID == selectedStepID) {+        guard var timer = child.timer,+          timer.phase == .running || (ending && ![.completed, .ended].contains(timer.phase))+        else { continue }+        let before = child+        if ending { try timer.end(at: clock) } else { try timer.pause(at: clock) }+        child.timer = timer+        child.status = ending ? .endedIncomplete : .paused+        child.revision += 1+        actions.append(+          .init(+            id: UUID(), deviceID: deviceID, timestamp: clock.wall,+            expectedRevision: before.revision,+            operation: .timer(+              runID: child.id, operation: ending ? .end : .pause, checkpoint: timer),+            cachedRun: before, cachedParentRun: cached))+        changed.append(child)+      }     }-    private func processIncomingHandoffs() {-        guard transportEnabled, let store, store.state.pending.isEmpty else { return }-        for request in (store.state.incomingHandoffs ?? [:]).values {-            do {-                guard case .handoff(let id, _, let destination) = request.operation, let run = value(id) else { continue }-                guard destination != deviceID else { continue }-                if run.timer?.phase == .running { try transitionTimer(id, .pause); return }-                if run.timer == nil && (run.progress.phase == .active || runs.contains(where: { $0.parentRunID == id && $0.timer?.phase == .running })) { try transitionGroup(id, operation: .pause(runID: id)); return }-                guard run.status != .needsReview else { error = "Review this saved session on iPhone before continuing."; continue }-                try transport.send(.handoffCheckpoint(actionID: request.id, checkpoint: run))-            } catch { self.error = error.localizedDescription }-        }+    run.status = run.progress.phase+    run.revision += 1+    changed.append(run)+    actions.append(+      .init(+        id: actionID, deviceID: deviceID, timestamp: clock.wall, expectedRevision: cached.revision,+        operation: operation, cachedRun: cached))+    guard let store else { throw ExecutionError.saveFailed }+    try store.enqueue(+      actions: actions.map { try ownedAction($0) }, localRuns: changed.map(ownedRun))+    reload()+    if transportEnabled, let first = store.state.pending.first {+      try? transport.send(.action(first))     }--    func receive(_ message: CompanionMessage) {-        // Cache persistence may succeed before a later outbound send fails.-        defer { reload() }-        do {-            switch message {-            case .snapshot(let value): try store?.receive(value)-            case .action(let action):-                if case .handoff = action.operation { try store?.rememberIncomingHandoff(action) }-            case .acknowledgement(let ack):-                let action = store?.state.pending.first { $0.id == ack.actionID }-                try store?.acknowledge(ack)-                if ack.accepted { try store?.finishIncomingHandoff(ack.actionID) }-                if let snapshot = ack.snapshot { try store?.receive(snapshot) }-                if ack.accepted, case .handoff(let id, _, _) = action?.operation { waitingHandoff.remove(id) }-                if !ack.accepted { error = ack.message }-                else if transportEnabled, let next = store?.state.pending.first { try transport.send(.action(next)) }-            default: break-            }-            reload(); processIncomingHandoffs()-        } catch CompanionStoreError.staleSnapshot { /* An older background transfer is harmless. */ }-        catch { self.error = error.localizedDescription }+  }+  func tick() {+    if let id = foregroundRunID {+      do { try transitionTimer(id, .advance) } catch { self.error = error.localizedDescription }     }-    func requiresPhoneResume(_ run: CompanionRun) -> Bool {-        let owner = CompanionOwnership.owner(run)-        guard owner != ProfileIdentity.me else { return false }-        guard let profile = snapshot?.profiles?.first(where: { $0.id == owner }) else { return true }-        return profile.archived || run.profileLifecycleID != profile.lifecycleID+  }+  private func interrupt(_ reason: String) {+    runtimeMessage = reason+    guard let id = foregroundRunID, value(id)?.timer?.phase == .running else { return }+    do { try transitionTimer(id, .pause) } catch { self.error = error.localizedDescription }+  }+  private func ownedRun(_ value: CompanionRun) -> CompanionRun {+    var run = value+    run.profileID = run.profileID ?? run.definition.profileID+    run.ownershipVersion = run.ownershipVersion ?? run.definition.ownershipVersion+    run.profileLifecycleID = run.profileLifecycleID ?? run.definition.profileLifecycleID+    return run+  }+  private func ownedAction(_ value: CompanionAction) throws -> CompanionAction {+    var action = value+    var owner =+      action.cachedRun.map { CompanionOwnership.owner($0) }+      ?? action.cachedParentRun.map { CompanionOwnership.owner($0) }+    var lifecycle =+      action.cachedRun?.profileLifecycleID ?? action.cachedRun?.definition.profileLifecycleID+    switch action.operation {+    case .medication(var event, let runID, let stepID):+      let target = snapshot?.medications.first { $0.id == event.medicationID }+      owner = owner ?? target?.profileID ?? ProfileIdentity.me+      lifecycle = lifecycle ?? target?.profileLifecycleID+      if snapshot?.version == 2 {+        event.profileID = owner+        event.ownershipVersion = 1+        event.profileLifecycleID = lifecycle+      }+      action.operation = .medication(event, runID: runID, stepID: stepID)+    case .treatment(var event, let runID, let stepID):+      let target = snapshot?.treatments?.first { $0.id == event.treatmentID }+      owner = owner ?? target?.profileID ?? ProfileIdentity.me+      lifecycle = lifecycle ?? target?.profileLifecycleID+      if snapshot?.version == 2 {+        event.profileID = owner+        event.ownershipVersion = 1+        event.profileLifecycleID = lifecycle+      }+      action.operation = .treatment(event, runID: runID, stepID: stepID)+    case .start(let run):+      let run = ownedRun(run)+      owner = CompanionOwnership.owner(run)+      lifecycle = run.profileLifecycleID+      action.operation = .start(run)+    case .handoff(let id, let run, let device):+      let run = ownedRun(run)+      owner = CompanionOwnership.owner(run)+      lifecycle = run.profileLifecycleID+      action.operation = .handoff(runID: id, checkpoint: run, toDeviceID: device)+    default:+      if let id = action.operation.runID, let run = self.value(id) {+        owner = owner ?? CompanionOwnership.owner(run)+        lifecycle = lifecycle ?? run.profileLifecycleID ?? run.definition.profileLifecycleID+      }     }-    private func reload() {-        snapshot = store?.state.snapshot; pendingCount = store?.state.pending.count ?? 0; localRuns = store?.state.localRuns ?? [:]-        waitingHandoff = Set((store?.state.pending ?? []).compactMap { if case .handoff(let id, _, _) = $0.operation { return id }; return nil })-        waitingHandoff.formUnion((store?.state.incomingHandoffs ?? [:]).values.compactMap { $0.operation.runID })-        if let id = foregroundRunID,-           value(id).map({ $0.timer?.phase != .running || requiresPhoneResume($0) }) ?? true {-            runtime.stop(); foregroundRunID = nil+    action.cachedRun = action.cachedRun.map(ownedRun)+    action.cachedParentRun = action.cachedParentRun.map(ownedRun)+    if snapshot?.version == 2 {+      action.version = 2+      action.profileID = owner ?? ProfileIdentity.me+      action.ownershipVersion = 1+      action.profileLifecycleID = lifecycle ?? ProfileIdentity.selfLifecycle+    }+    return action+  }+  private func enqueue(_ action: CompanionAction, run: CompanionRun? = nil) throws {+    try enqueue(action, runs: run.map { [$0] } ?? [])+  }+  private func enqueue(_ action: CompanionAction, runs: [CompanionRun]) throws {+    guard let store else { throw ExecutionError.saveFailed }+    let action = try ownedAction(action)+    try store.enqueue(action, localRuns: runs.map(ownedRun))+    reload()+    if transportEnabled, store.state.pending.first?.id == action.id {+      try? transport.send(.action(action))+    }+  }+  private func processIncomingHandoffs() {+    guard transportEnabled, let store, store.state.pending.isEmpty else { return }+    for request in (store.state.incomingHandoffs ?? [:]).values {+      do {+        guard case .handoff(let id, _, let destination) = request.operation, let run = value(id)+        else { continue }+        guard destination != deviceID else { continue }+        if run.timer?.phase == .running {+          try transitionTimer(id, .pause)+          return+        }+        if run.timer == nil+          && (run.progress.phase == .active+            || runs.contains(where: { $0.parentRunID == id && $0.timer?.phase == .running })) {+          try transitionGroup(id, operation: .pause(runID: id))+          return+        }+        guard run.status != .needsReview else {+          error = "Review this saved session on iPhone before continuing."+          continue+        }+        try transport.send(.handoffCheckpoint(actionID: request.id, checkpoint: run))+      } catch { self.error = error.localizedDescription }+    }+  }++  func receive(_ message: CompanionMessage) {+    // Cache persistence may succeed before a later outbound send fails.+    defer { reload() }+    do {+      switch message {+      case .snapshot(let value): try store?.receive(value)+      case .action(let action):+        if case .handoff = action.operation { try store?.rememberIncomingHandoff(action) }+      case .acknowledgement(let ack):+        let action = store?.state.pending.first { $0.id == ack.actionID }+        try store?.acknowledge(ack)+        if ack.accepted { try store?.finishIncomingHandoff(ack.actionID) }+        if let snapshot = ack.snapshot { try store?.receive(snapshot) }+        if ack.accepted, case .handoff(let id, _, _) = action?.operation {+          waitingHandoff.remove(id)+        }+        if !ack.accepted {+          error = ack.message+        } else if transportEnabled, let next = store?.state.pending.first {+          try transport.send(.action(next))         }+      default: break+      }+      reload()+      processIncomingHandoffs()+    } catch CompanionStoreError.staleSnapshot { /* An older background transfer is harmless. */+    } catch { self.error = error.localizedDescription }+  }+  func requiresPhoneResume(_ run: CompanionRun) -> Bool {+    let owner = CompanionOwnership.owner(run)+    guard owner != ProfileIdentity.me else { return false }+    guard let profile = snapshot?.profiles?.first(where: { $0.id == owner }) else { return true }+    return profile.archived || run.profileLifecycleID != profile.lifecycleID+  }+  private func reload() {+    snapshot = store?.state.snapshot+    pendingCount = store?.state.pending.count ?? 0+    localRuns = store?.state.localRuns ?? [:]+    waitingHandoff = Set(+      (store?.state.pending ?? []).compactMap {+        if case .handoff(let id, _, _) = $0.operation { return id }+        return nil+      })+    waitingHandoff.formUnion(+      (store?.state.incomingHandoffs ?? [:]).values.compactMap { $0.operation.runID })+    if let id = foregroundRunID,+      value(id).map({ $0.timer?.phase != .running || requiresPhoneResume($0) }) ?? true {+      runtime.stop()+      foregroundRunID = nil     }+  } }
Meddy/MeddyWatchTests/MeddyWatchProfileTests.swift Modified
diff --git a/Meddy/MeddyWatchTests/MeddyWatchProfileTests.swift b/Meddy/MeddyWatchTests/MeddyWatchProfileTests.swiftindex d503fca..65f54fc 100644--- a/Meddy/MeddyWatchTests/MeddyWatchProfileTests.swift+++ b/Meddy/MeddyWatchTests/MeddyWatchProfileTests.swift@@ -1,134 +1,237 @@ import Foundation import Testing+ @testable import MeddyWatch  @MainActor struct MeddyWatchProfileTests {-    private func fixture() throws -> (URL, WatchController, ProfileRuntime, CompanionSnapshot) {-        let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathComponent("watch.json")-        let runtime = ProfileRuntime()-        let a = CompanionProfile(id: UUID(), label: "Same name", archived: false, lifecycleID: UUID())-        let b = CompanionProfile(id: UUID(), label: "Same name", archived: false, lifecycleID: UUID())-        func timer(_ p: CompanionProfile) -> CompanionRoutine {-            var definition = FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "", roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "", steps: [])-            definition.profileID = p.id; definition.ownershipVersion = 1; definition.profileLifecycleID = p.lifecycleID-            return .init(definition: definition, occurrences: [])-        }-        let ta = timer(a), tb = timer(b)-        var group = FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic group", instructions: "", roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "", steps: [])-        group.profileID = b.id; group.ownershipVersion = 1; group.profileLifecycleID = b.lifecycleID-        var step = FrozenRoutineStep(id: UUID(), position: 0, kind: .timedRoutine, targetID: tb.id, name: "Synthetic timer", instructions: "", requirements: "", dose: nil, roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "")-        step.profileID = b.id; step.ownershipVersion = 1; step.profileLifecycleID = b.lifecycleID; group.steps = [step]-        let snapshot = CompanionSnapshot(version: 2, phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [], routines: [ta, tb, .init(definition: group, occurrences: [])], runs: [], deletedEventIDs: [], appliedEventIDs: [], profiles: [a,b], eventOwners: [:])-        try CompanionStore(file: file).receive(snapshot)-        let sample = ClockSample(wall: Date(), monotonic: 0, continuityID: "synthetic-profile")-        return (file, WatchController(file: file, activate: false, runtime: runtime, clock: { sample }), runtime, snapshot)+  private struct Fixture {+    let file: URL+    let controller: WatchController+    let runtime: ProfileRuntime+    let snapshot: CompanionSnapshot+  }++  private func fixture() throws -> Fixture {+    let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+      .appendingPathComponent("watch.json")+    let runtime = ProfileRuntime()+    let firstProfile = CompanionProfile(id: UUID(), label: "Same name", archived: false, lifecycleID: UUID())+    let secondProfile = CompanionProfile(id: UUID(), label: "Same name", archived: false, lifecycleID: UUID())+    func timer(_ profile: CompanionProfile) -> CompanionRoutine {+      var definition = FrozenRoutineDefinition(+        routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer",+        instructions: "", roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "",+        steps: [])+      definition.profileID = profile.id+      definition.ownershipVersion = 1+      definition.profileLifecycleID = profile.lifecycleID+      return .init(definition: definition, occurrences: [])     }-    @Test func endingOtherPersonsTimerAndGroupKeepsForegroundRoundRunning() throws {-        let (file, controller, runtime, snapshot) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let a = try controller.start(snapshot.routines[0], occurrence: nil)-        try controller.transitionTimer(a, .start)-        let baseline = runtime.stops-        controller.selectedProfileID = snapshot.profiles![1].id-        let b = try controller.start(snapshot.routines[1], occurrence: nil)-        try controller.transitionTimer(b, .end)-        try controller.transitionTimer(b, .reopen)-        let group = try controller.start(snapshot.routines[2], occurrence: nil)-        _ = try controller.beginChild(parentID: group, stepID: snapshot.routines[2].definition.steps[0].id)-        try controller.transitionGroup(group, operation: .end(runID: group))-        #expect(controller.value(a)?.timer?.phase == .running)-        #expect(controller.foregroundRunID == a && runtime.stops == baseline)-        #expect(try CompanionStore(file: file).state.pending.allSatisfy { action in-            guard let run = action.cachedRun else { return true }-            return action.profileID == CompanionOwnership.owner(run)-        })+    let ta = timer(firstProfile)+    let tb = timer(secondProfile)+    var group = FrozenRoutineDefinition(+      routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic group", instructions: "",+      roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "", steps: [])+    group.profileID = secondProfile.id+    group.ownershipVersion = 1+    group.profileLifecycleID = secondProfile.lifecycleID+    var step = FrozenRoutineStep(+      id: UUID(), position: 0, kind: .timedRoutine, targetID: tb.id, name: "Synthetic timer",+      instructions: "", requirements: "", dose: nil, roundCount: 2, roundDurationSeconds: 30,+      betweenRoundInstructions: "")+    step.profileID = secondProfile.id+    step.ownershipVersion = 1+    step.profileLifecycleID = secondProfile.lifecycleID+    group.steps = [step]+    let snapshot = CompanionSnapshot(+      version: 2, phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [],+      routines: [ta, tb, .init(definition: group, occurrences: [])], runs: [], deletedEventIDs: [],+      appliedEventIDs: [], profiles: [firstProfile, secondProfile], eventOwners: [:])+    try CompanionStore(file: file).receive(snapshot)+    let sample = ClockSample(wall: Date(), monotonic: 0, continuityID: "synthetic-profile")+    return Fixture(+      file: file, controller: WatchController(file: file, activate: false, runtime: runtime, clock: { sample }),+      runtime: runtime, snapshot: snapshot+    )+  }+  @Test func endingOtherPersonsTimerAndGroupKeepsForegroundRoundRunning() throws {+    let fixture = try fixture()+    let file = fixture.file+    let controller = fixture.controller+    let runtime = fixture.runtime+    let snapshot = fixture.snapshot+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let firstRun = try controller.start(snapshot.routines[0], occurrence: nil)+    try controller.transitionTimer(firstRun, .start)+    let baseline = runtime.stops+    controller.selectedProfileID = snapshot.profiles![1].id+    let secondProfile = try controller.start(snapshot.routines[1], occurrence: nil)+    try controller.transitionTimer(secondProfile, .end)+    try controller.transitionTimer(secondProfile, .reopen)+    let group = try controller.start(snapshot.routines[2], occurrence: nil)+    _ = try controller.beginChild(+      parentID: group, stepID: snapshot.routines[2].definition.steps[0].id)+    try controller.transitionGroup(group, operation: .end(runID: group))+    #expect(controller.value(firstRun)?.timer?.phase == .running)+    #expect(controller.foregroundRunID == firstRun && runtime.stops == baseline)+    #expect(+      try CompanionStore(file: file).state.pending.allSatisfy { action in+        guard let run = action.cachedRun else { return true }+        return action.profileID == CompanionOwnership.owner(run)+      })+  }+  @Test(arguments: [0, 1, 2])+  func incomingArchiveStopsAffectedRuntimeAndRetainsUnacknowledgedActions(delivery: Int) throws {+    let fixture = try fixture()+    let file = fixture.file+    let controller = fixture.controller+    let runtime = fixture.runtime+    let original = fixture.snapshot+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(original.routines[0], occurrence: nil)+    try controller.transitionTimer(id, .start)+    let before = try CompanionStore(file: file).state.pending+    var archived = original+    archived.revision += 1+    archived.profiles![0].archived = true+    let baseline = runtime.stops+    let viaAcknowledgement = delivery == 1+    if delivery == 2 {+      archived.profiles!.removeFirst()+      archived.routines.removeFirst()     }-    @Test(arguments: [0, 1, 2]) func incomingArchiveStopsAffectedRuntimeAndRetainsUnacknowledgedActions(delivery: Int) throws {-        let (file, controller, runtime, original) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(original.routines[0], occurrence: nil)-        try controller.transitionTimer(id, .start)-        let before = try CompanionStore(file: file).state.pending-        var archived = original; archived.revision += 1; archived.profiles![0].archived = true-        let baseline = runtime.stops-        let viaAcknowledgement = delivery == 1-        if delivery == 2 { archived.profiles!.removeFirst(); archived.routines.removeFirst() }-        if viaAcknowledgement {-            controller.receive(.acknowledgement(.init(actionID: before[0].id, accepted: true, message: nil, snapshot: archived)))-        } else { controller.receive(.snapshot(archived)) }-        #expect(controller.foregroundRunID == nil && runtime.stops > baseline)-        #expect(controller.value(id) == nil)-        let pending = try CompanionStore(file: file).state.pending-        #expect(pending.map(\.id) == (viaAcknowledgement ? Array(before.dropFirst()) : before).map(\.id))-        #expect(controller.error == nil)+    if viaAcknowledgement {+      controller.receive(+        .acknowledgement(+          .init(actionID: before[0].id, accepted: true, message: nil, snapshot: archived)))+    } else {+      controller.receive(.snapshot(archived))     }-    @Test func actualCareKeepsCapturedOwnerAfterSelectionAndArchive() throws {-        let (file, controller, _, original) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let a = original.profiles![0], b = original.profiles![1], medicationID = UUID()-        let medication = CompanionMedication(id: medicationID, name: "Synthetic same name", purpose: nil, requirements: "", dose: .unknown,-            schedule: .init(id: medicationID, mode: .asNeeded, generationID: nil, startedAt: nil), next: nil, lastTaken: nil, active: true,-            profileID: a.id, ownershipVersion: 1, profileLifecycleID: a.lifecycleID)-        var snapshot = original; snapshot.revision += 1; snapshot.medications = [medication]-        controller.receive(.snapshot(snapshot)); controller.selectedProfileID = b.id-        try controller.markMedication(medication)-        let action = try #require(CompanionStore(file: file).state.pending.first)-        #expect(action.profileID == a.id && action.version == 2)-        guard case .medication(let event, _, _) = action.operation else { Issue.record("Expected actual medication event"); return }-        #expect(event.profileID == a.id && event.medicationID == medicationID)-        snapshot.revision += 1; snapshot.profiles![0].archived = true; snapshot.medications = []-        controller.receive(.snapshot(snapshot))-        #expect(try CompanionStore(file: file).state.pending == [action])-        #expect(controller.selectedProfileID == b.id)+    #expect(controller.foregroundRunID == nil && runtime.stops > baseline)+    #expect(controller.value(id) == nil)+    let pending = try CompanionStore(file: file).state.pending+    #expect(+      pending.map(\.id) == (viaAcknowledgement ? Array(before.dropFirst()) : before).map(\.id))+    #expect(controller.error == nil)+  }+  @Test func actualCareKeepsCapturedOwnerAfterSelectionAndArchive() throws {+    let fixture = try fixture()+    let file = fixture.file+    let controller = fixture.controller+    let original = fixture.snapshot+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let firstProfile = original.profiles![0]+    let secondProfile = original.profiles![1]+    let medicationID = UUID()+    let medication = CompanionMedication(+      id: medicationID, name: "Synthetic same name", purpose: nil, requirements: "", dose: .unknown,+      schedule: .init(id: medicationID, mode: .asNeeded, generationID: nil, startedAt: nil),+      next: nil, lastTaken: nil, active: true,+      profileID: firstProfile.id, ownershipVersion: 1, profileLifecycleID: firstProfile.lifecycleID)+    var snapshot = original+    snapshot.revision += 1+    snapshot.medications = [medication]+    controller.receive(.snapshot(snapshot))+    controller.selectedProfileID = secondProfile.id+    try controller.markMedication(medication)+    let action = try #require(CompanionStore(file: file).state.pending.first)+    #expect(action.profileID == firstProfile.id && action.version == 2)+    guard case .medication(let event, _, _) = action.operation else {+      Issue.record("Expected actual medication event")+      return     }-    @Test func wakeTakenPreservesCapturedAnchorAndRejectsForeignWakeSnapshot() throws {-        let (file, controller, _, original) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let a = original.profiles![0], b = original.profiles![1], medicationID = UUID()-        var medication = CompanionMedication(id: medicationID, name: "Synthetic wake medicine", purpose: nil, requirements: "", dose: .unknown,-            schedule: .init(id: medicationID, mode: .afterWaking, generationID: UUID(), startedAt: Date(), wakeOffsetMinutes: 15), next: nil, lastTaken: nil, active: true,-            profileID: a.id, ownershipVersion: 1, profileLifecycleID: a.lifecycleID)-        var snapshot = original; snapshot.revision += 1; snapshot.medications = [medication]-        controller.receive(.snapshot(snapshot)); try controller.markMedication(medication)-        let withoutWake = try #require(CompanionStore(file: file).state.pending.first)-        guard case .medication(let noAnchor, _, _) = withoutWake.operation else { Issue.record("Expected medication action"); return }-        #expect(noAnchor.wakeEventID == nil)-        let wake = WakeAnchor(id: UUID(), timestamp: Date(), recordedAt: Date(), localDate: "2026-01-05", timeZoneID: "GMT", profileID: a.id, ownershipVersion: 1, profileLifecycleID: a.lifecycleID)-        medication.schedule.wakeAnchor = wake; snapshot.revision += 1; snapshot.medications = [medication]-        controller.receive(.snapshot(snapshot)); controller.selectedProfileID = b.id-        try controller.markMedication(medication)-        let pending = try CompanionStore(file: file).state.pending-        guard case .medication(let captured, _, _) = pending[1].operation else { Issue.record("Expected medication action"); return }-        #expect(pending[0] == withoutWake && captured.wakeEventID == wake.id && pending[1].profileID == a.id)-        var forged = snapshot; forged.revision += 1; forged.medications[0].schedule.wakeAnchor?.profileID = b.id-        controller.receive(.snapshot(forged))-        #expect(controller.error != nil && controller.snapshot == snapshot)-        #expect(try CompanionStore(file: file).state.pending == pending)+    #expect(event.profileID == firstProfile.id && event.medicationID == medicationID)+    snapshot.revision += 1+    snapshot.profiles![0].archived = true+    snapshot.medications = []+    controller.receive(.snapshot(snapshot))+    #expect(try CompanionStore(file: file).state.pending == [action])+    #expect(controller.selectedProfileID == secondProfile.id)+  }+  @Test func wakeTakenPreservesCapturedAnchorAndRejectsForeignWakeSnapshot() throws {+    let fixture = try fixture()+    let file = fixture.file+    let controller = fixture.controller+    let original = fixture.snapshot+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let firstProfile = original.profiles![0]+    let secondProfile = original.profiles![1]+    let medicationID = UUID()+    var medication = CompanionMedication(+      id: medicationID, name: "Synthetic wake medicine", purpose: nil, requirements: "",+      dose: .unknown,+      schedule: .init(+        id: medicationID, mode: .afterWaking, generationID: UUID(), startedAt: Date(),+        wakeOffsetMinutes: 15), next: nil, lastTaken: nil, active: true,+      profileID: firstProfile.id, ownershipVersion: 1, profileLifecycleID: firstProfile.lifecycleID)+    var snapshot = original+    snapshot.revision += 1+    snapshot.medications = [medication]+    controller.receive(.snapshot(snapshot))+    try controller.markMedication(medication)+    let withoutWake = try #require(CompanionStore(file: file).state.pending.first)+    guard case .medication(let noAnchor, _, _) = withoutWake.operation else {+      Issue.record("Expected medication action")+      return     }-    @Test func restoredSnapshotRequiresPhoneResumeAndKeepsOldActionsCaptured() throws {-        let (file, controller, runtime, original) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(original.routines[0], occurrence: nil)-        try controller.transitionTimer(id, .start)-        let old = try #require(controller.value(id))-        let pending = try CompanionStore(file: file).state.pending-        var restored = original; restored.revision += 1; restored.profiles![0].lifecycleID = UUID()-        restored.routines[0].definition.profileLifecycleID = restored.profiles![0].lifecycleID-        var saved = old; saved.status = .paused; saved.timer?.phase = .interrupted; saved.timer?.anchor = nil; saved.timer?.deadline = nil-        restored.runs = [saved]-        controller.receive(.snapshot(restored))-        #expect(controller.requiresPhoneResume(try #require(controller.value(id))))-        #expect(controller.foregroundRunID == nil && runtime.stops > 0)-        #expect(throws: ProfileError.self) { try controller.transitionTimer(id, .resume) }-        #expect(try CompanionStore(file: file).state.pending == pending)+    #expect(noAnchor.wakeEventID == nil)+    let wake = WakeAnchor(+      id: UUID(), timestamp: Date(), recordedAt: Date(), localDate: "2026-01-05", timeZoneID: "GMT",+      profileID: firstProfile.id, ownershipVersion: 1, profileLifecycleID: firstProfile.lifecycleID)+    medication.schedule.wakeAnchor = wake+    snapshot.revision += 1+    snapshot.medications = [medication]+    controller.receive(.snapshot(snapshot))+    controller.selectedProfileID = secondProfile.id+    try controller.markMedication(medication)+    let pending = try CompanionStore(file: file).state.pending+    guard case .medication(let captured, _, _) = pending[1].operation else {+      Issue.record("Expected medication action")+      return     }+    #expect(+      pending[0] == withoutWake && captured.wakeEventID == wake.id && pending[1].profileID == firstProfile.id)+    var forged = snapshot+    forged.revision += 1+    forged.medications[0].schedule.wakeAnchor?.profileID = secondProfile.id+    controller.receive(.snapshot(forged))+    #expect(controller.error != nil && controller.snapshot == snapshot)+    #expect(try CompanionStore(file: file).state.pending == pending)+  }+  @Test func restoredSnapshotRequiresPhoneResumeAndKeepsOldActionsCaptured() throws {+    let fixture = try fixture()+    let file = fixture.file+    let controller = fixture.controller+    let runtime = fixture.runtime+    let original = fixture.snapshot+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(original.routines[0], occurrence: nil)+    try controller.transitionTimer(id, .start)+    let old = try #require(controller.value(id))+    let pending = try CompanionStore(file: file).state.pending+    var restored = original+    restored.revision += 1+    restored.profiles![0].lifecycleID = UUID()+    restored.routines[0].definition.profileLifecycleID = restored.profiles![0].lifecycleID+    var saved = old+    saved.status = .paused+    saved.timer?.phase = .interrupted+    saved.timer?.anchor = nil+    saved.timer?.deadline = nil+    restored.runs = [saved]+    controller.receive(.snapshot(restored))+    #expect(controller.requiresPhoneResume(try #require(controller.value(id))))+    #expect(controller.foregroundRunID == nil && runtime.stops > 0)+    #expect(throws: ProfileError.self) { try controller.transitionTimer(id, .resume) }+    #expect(try CompanionStore(file: file).state.pending == pending)+  } }  @MainActor private final class ProfileRuntime: RoundRuntimeManaging {-    var onBoundary: () -> Void = {}-    var onInterrupted: (String) -> Void = { _ in }-    var stops = 0-    func start(deadline: Date) {}-    func stop() { stops += 1 }+  var onBoundary: () -> Void = {}+  var onInterrupted: (String) -> Void = { _ in }+  var stops = 0+  func start(deadline: Date) {}+  func stop() { stops += 1 } }
Meddy/MeddyWatchTests/MeddyWatchTests.swift Modified
diff --git a/Meddy/MeddyWatchTests/MeddyWatchTests.swift b/Meddy/MeddyWatchTests/MeddyWatchTests.swiftindex a1edad1..d4ff70e 100644--- a/Meddy/MeddyWatchTests/MeddyWatchTests.swift+++ b/Meddy/MeddyWatchTests/MeddyWatchTests.swift@@ -1,143 +1,190 @@ import Foundation import Testing+ @testable import MeddyWatch  @MainActor struct MeddyWatchTests {-    private func fixture() throws -> (URL, WatchController, CompanionRoutine) {-        let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathComponent("watch.json")-        let step = FrozenRoutineStep(id: UUID(), position: 0, kind: .timedRoutine, targetID: UUID(), name: "Synthetic timer", instructions: "", requirements: "", dose: nil, roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "Synthetic wait")-        let definition = FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic group", instructions: "", roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "", steps: [step])-        let routine = CompanionRoutine(definition: definition, occurrences: [])-        let store = try CompanionStore(file: file)-        try store.receive(.init(phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [], routines: [routine], runs: [], deletedEventIDs: [], appliedEventIDs: []))-        return (file, WatchController(file: file, activate: false), routine)-    }-    @Test func offlineStartKeepsFrozenPlanAndOutboxAcrossRelaunch() throws {-        let (file, controller, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(routine, occurrence: nil)-        let reopened = WatchController(file: file, activate: false)-        #expect(reopened.value(id)?.definition == routine.definition)-        #expect(reopened.pendingCount == 1)-        #expect(reopened.value(id)?.progress.steps.first?.state == .pending)-    }-    @Test func openingChildIsOneCanonicalChildAndParentCannotAdvanceEarly() throws {-        let (file, controller, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let parent = try controller.start(routine, occurrence: nil)-        let stepID = routine.definition.steps[0].id-        let child = try controller.beginChild(parentID: parent, stepID: stepID)-        #expect(try controller.beginChild(parentID: parent, stepID: stepID) == child)-        #expect(controller.value(child)?.timer?.roundCount == 2)-        #expect(controller.value(parent)?.progress.steps.first?.state == .inProgress)-        #expect(controller.value(parent)?.progress.steps.first?.canonicalEventID == child)-        #expect(controller.pendingCount == 2)-        #expect(throws: ExecutionError.self) { try controller.record(runID: parent, stepID: stepID) }-    }-    @Test func skipNeedsSeparateContinueAndNeitherCreatesCompletion() throws {-        let (file, controller, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(routine, occurrence: nil); let stepID = routine.definition.steps[0].id-        try controller.skip(id, stepID: stepID, confirm: false)-        #expect(controller.value(id)?.progress.steps.first?.skipConfirmed == false)-        #expect(controller.value(id)?.status == .active)-        try controller.skip(id, stepID: stepID, confirm: true)-        #expect(controller.value(id)?.status == .finishedWithSkips)-        #expect(controller.value(id)?.progress.steps.first?.completedAt == nil)+  private func fixture() throws -> (URL, WatchController, CompanionRoutine) {+    let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+      .appendingPathComponent("watch.json")+    let step = FrozenRoutineStep(+      id: UUID(), position: 0, kind: .timedRoutine, targetID: UUID(), name: "Synthetic timer",+      instructions: "", requirements: "", dose: nil, roundCount: 2, roundDurationSeconds: 30,+      betweenRoundInstructions: "Synthetic wait")+    let definition = FrozenRoutineDefinition(+      routineID: UUID(), revision: 1, kind: .ordered, name: "Synthetic group", instructions: "",+      roundCount: nil, roundDurationSeconds: nil, betweenRoundInstructions: "", steps: [step])+    let routine = CompanionRoutine(definition: definition, occurrences: [])+    let store = try CompanionStore(file: file)+    try store.receive(+      .init(+        phoneID: UUID(), revision: 1, generatedAt: Date(), medications: [], routines: [routine],+        runs: [], deletedEventIDs: [], appliedEventIDs: []))+    return (file, WatchController(file: file, activate: false), routine)+  }+  @Test func offlineStartKeepsFrozenPlanAndOutboxAcrossRelaunch() throws {+    let (file, controller, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(routine, occurrence: nil)+    let reopened = WatchController(file: file, activate: false)+    #expect(reopened.value(id)?.definition == routine.definition)+    #expect(reopened.pendingCount == 1)+    #expect(reopened.value(id)?.progress.steps.first?.state == .pending)+  }+  @Test func openingChildIsOneCanonicalChildAndParentCannotAdvanceEarly() throws {+    let (file, controller, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let parent = try controller.start(routine, occurrence: nil)+    let stepID = routine.definition.steps[0].id+    let child = try controller.beginChild(parentID: parent, stepID: stepID)+    #expect(try controller.beginChild(parentID: parent, stepID: stepID) == child)+    #expect(controller.value(child)?.timer?.roundCount == 2)+    #expect(controller.value(parent)?.progress.steps.first?.state == .inProgress)+    #expect(controller.value(parent)?.progress.steps.first?.canonicalEventID == child)+    #expect(controller.pendingCount == 2)+    #expect(throws: ExecutionError.self) { try controller.record(runID: parent, stepID: stepID) }+  }+  @Test func skipNeedsSeparateContinueAndNeitherCreatesCompletion() throws {+    let (file, controller, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(routine, occurrence: nil)+    let stepID = routine.definition.steps[0].id+    try controller.skip(id, stepID: stepID, confirm: false)+    #expect(controller.value(id)?.progress.steps.first?.skipConfirmed == false)+    #expect(controller.value(id)?.status == .active)+    try controller.skip(id, stepID: stepID, confirm: true)+    #expect(controller.value(id)?.status == .finishedWithSkips)+    #expect(controller.value(id)?.progress.steps.first?.completedAt == nil)+  }+  @Test func invalidStorageBlocksActionsWithoutPretendingSaved() throws {+    let (file, _, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    try Data("broken".utf8).write(to: file)+    let controller = WatchController(file: file, activate: false)+    #expect(controller.error != nil)+    #expect(throws: ExecutionError.saveFailed) {+      _ = try controller.start(routine, occurrence: nil)     }-    @Test func invalidStorageBlocksActionsWithoutPretendingSaved() throws {-        let (file, _, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        try Data("broken".utf8).write(to: file)-        let controller = WatchController(file: file, activate: false)-        #expect(controller.error != nil)-        #expect(throws: ExecutionError.saveFailed) { _ = try controller.start(routine, occurrence: nil) }-        #expect(controller.pendingCount == 0)-    }-    @Test func incomingOwnershipRequestSurvivesRelaunchAndBlocksAdvancement() throws {-        let (file, controller, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(routine, occurrence: nil)-        let run = try #require(controller.value(id))-        let store = try CompanionStore(file: file)-        try store.rememberIncomingHandoff(.init(id: UUID(), deviceID: "phone", timestamp: Date(), expectedRevision: run.revision, operation: .handoff(runID: id, checkpoint: run, toDeviceID: "phone"), cachedRun: run))-        let reopened = WatchController(file: file, activate: false)-        #expect(reopened.waitingHandoff.contains(id))-        #expect(throws: ExecutionError.self) { _ = try reopened.beginChild(parentID: id, stepID: routine.definition.steps[0].id) }-        try reopened.transitionGroup(id, operation: .pause(runID: id))-        #expect(reopened.value(id)?.status == .paused)-    }-    @Test func rejectedHandshakeCanBeReplacedButActualActionCannotBeDiscarded() throws {-        let (file, controller, routine) = try fixture(); defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let id = try controller.start(routine, occurrence: nil)-        let run = try #require(controller.value(id)); let store = try CompanionStore(file: file)-        let actual = try #require(store.state.pending.first)-        try store.acknowledge(.init(actionID: actual.id, accepted: false, message: "Synthetic failure", snapshot: nil))-        #expect(throws: CompanionStoreError.self) { try store.discardRejectedHandoff(actual.id) }-        let handshake = CompanionAction(id: UUID(), deviceID: store.state.deviceID, timestamp: Date(), expectedRevision: run.revision, operation: .handoff(runID: id, checkpoint: run, toDeviceID: store.state.deviceID), cachedRun: run)-        try store.enqueue(handshake)-        try store.acknowledge(.init(actionID: handshake.id, accepted: false, message: "Synthetic stale revision", snapshot: nil))-        try store.discardRejectedHandoff(handshake.id)-        let reopened = try CompanionStore(file: file)-        #expect(reopened.state.pending.map(\.id) == [actual.id])-        #expect(reopened.state.rejected[actual.id] != nil)-        #expect(reopened.state.rejected[handshake.id] == nil)+    #expect(controller.pendingCount == 0)+  }+  @Test func incomingOwnershipRequestSurvivesRelaunchAndBlocksAdvancement() throws {+    let (file, controller, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(routine, occurrence: nil)+    let run = try #require(controller.value(id))+    let store = try CompanionStore(file: file)+    try store.rememberIncomingHandoff(+      .init(+        id: UUID(), deviceID: "phone", timestamp: Date(), expectedRevision: run.revision,+        operation: .handoff(runID: id, checkpoint: run, toDeviceID: "phone"), cachedRun: run))+    let reopened = WatchController(file: file, activate: false)+    #expect(reopened.waitingHandoff.contains(id))+    #expect(throws: ExecutionError.self) {+      _ = try reopened.beginChild(parentID: id, stepID: routine.definition.steps[0].id)     }+    try reopened.transitionGroup(id, operation: .pause(runID: id))+    #expect(reopened.value(id)?.status == .paused)+  }+  @Test func rejectedHandshakeCanBeReplacedButActualActionCannotBeDiscarded() throws {+    let (file, controller, routine) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let id = try controller.start(routine, occurrence: nil)+    let run = try #require(controller.value(id))+    let store = try CompanionStore(file: file)+    let actual = try #require(store.state.pending.first)+    try store.acknowledge(+      .init(actionID: actual.id, accepted: false, message: "Synthetic failure", snapshot: nil))+    #expect(throws: CompanionStoreError.self) { try store.discardRejectedHandoff(actual.id) }+    let handshake = CompanionAction(+      id: UUID(), deviceID: store.state.deviceID, timestamp: Date(), expectedRevision: run.revision,+      operation: .handoff(runID: id, checkpoint: run, toDeviceID: store.state.deviceID),+      cachedRun: run)+    try store.enqueue(handshake)+    try store.acknowledge(+      .init(+        actionID: handshake.id, accepted: false, message: "Synthetic stale revision", snapshot: nil)+    )+    try store.discardRejectedHandoff(handshake.id)+    let reopened = try CompanionStore(file: file)+    #expect(reopened.state.pending.map(\.id) == [actual.id])+    #expect(reopened.state.rejected[actual.id] != nil)+    #expect(reopened.state.rejected[handshake.id] == nil)+  } -    @Test func cachedRoutineDayRollsAt02WithoutPhoneOrRewritingSavedSession() throws {-        let (file, controller, base) = try fixture()-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(secondsFromGMT: 0)!-        func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {-            calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))!-        }-        var routine = base-        routine.schedule = .init(routineID: base.id, current: .init(generationID: UUID(), startedAt: date(4, 12), slots: [.init(label: "Before sleeping")]))-        // The Codable cache includes the plan, rather than only yesterday's occurrence list.-        let cached = try JSONDecoder().decode(CompanionRoutine.self, from: JSONEncoder().encode(routine))-        let before = try #require(controller.occurrences(cached, now: date(5, 1, 59), calendar: calendar).first)-        #expect(before.localDate == "2026-01-04" && before.scheduledAt == nil)-        let id = try controller.start(cached, occurrence: before)-        let after = controller.occurrences(cached, now: date(5, 2), calendar: calendar)-        #expect(after.first(where: { !$0.isEarlierUnfinished })?.localDate == "2026-01-05")-        #expect(after.first(where: { !$0.isEarlierUnfinished })?.id != id)-        #expect(after.first(where: { $0.id == id })?.isEarlierUnfinished == true)-        #expect(controller.value(id)?.definition.occurrence?.localDate == "2026-01-04")-        #expect(controller.pendingCount == 1)+  @Test func cachedRoutineDayRollsAt02WithoutPhoneOrRewritingSavedSession() throws {+    let (file, controller, base) = try fixture()+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    var calendar = Calendar(identifier: .gregorian)+    calendar.timeZone = TimeZone(secondsFromGMT: 0)!+    func date(_ day: Int, _ hour: Int, _ minute: Int = 0) -> Date {+      calendar.date(from: .init(year: 2026, month: 1, day: day, hour: hour, minute: minute))!     }+    var routine = base+    routine.schedule = .init(+      routineID: base.id,+      current: .init(+        generationID: UUID(), startedAt: date(4, 12), slots: [.init(label: "Before sleeping")]))+    // The Codable cache includes the plan, rather than only yesterday's occurrence list.+    let cached = try JSONDecoder().decode(+      CompanionRoutine.self, from: JSONEncoder().encode(routine))+    let before = try #require(+      controller.occurrences(cached, now: date(5, 1, 59), calendar: calendar).first)+    #expect(before.localDate == "2026-01-04" && before.scheduledAt == nil)+    let id = try controller.start(cached, occurrence: before)+    let after = controller.occurrences(cached, now: date(5, 2), calendar: calendar)+    #expect(after.first(where: { !$0.isEarlierUnfinished })?.localDate == "2026-01-05")+    #expect(after.first(where: { !$0.isEarlierUnfinished })?.id != id)+    #expect(after.first(where: { $0.id == id })?.isEarlierUnfinished == true)+    #expect(controller.value(id)?.definition.occurrence?.localDate == "2026-01-04")+    #expect(controller.pendingCount == 1)+  } -    @Test func perRoundRuntimeStopsWhileWaitingAndRequiresExplicitNextRound() throws {-        let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathComponent("watch.json")-        defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }-        let runtime = SyntheticRoundRuntime(); var sample = ClockSample(wall: Date(), monotonic: 0, continuityID: "synthetic")-        var signals = 0-        let controller = WatchController(file: file, activate: false, runtime: runtime, clock: { sample }, haptic: { signals += 1 })-        let definition = FrozenRoutineDefinition(routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "", roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "Synthetic wait", steps: [])-        let id = try controller.start(.init(definition: definition, occurrences: []), occurrence: nil)-        try controller.transitionTimer(id, .start)-        #expect(runtime.deadlines.count == 1)-        sample.wall = sample.wall.addingTimeInterval(30); sample.monotonic = 30; runtime.onBoundary()-        #expect(controller.value(id)?.timer?.phase == .waiting && signals == 1)-        #expect(runtime.stops > 0 && runtime.deadlines.count == 1)-        sample.wall = sample.wall.addingTimeInterval(600); sample.monotonic = 630; controller.tick()-        #expect(controller.value(id)?.timer?.completedRounds == 1 && runtime.deadlines.count == 1)-        try controller.transitionTimer(id, .start)-        #expect(runtime.deadlines.count == 2)-        runtime.onInterrupted("Synthetic startup/invalidation failure")-        #expect(controller.value(id)?.timer?.phase == .paused)-        #expect(controller.runtimeMessage == "Synthetic startup/invalidation failure")-        #expect(controller.value(id)?.timer?.completedRounds == 1)-        try controller.transitionTimer(id, .resume)-        #expect(runtime.deadlines.count == 3)-        try controller.transitionTimer(id, .end)-        #expect(controller.value(id)?.timer?.phase == .ended && signals == 1)-    }+  @Test func perRoundRuntimeStopsWhileWaitingAndRequiresExplicitNextRound() throws {+    let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+      .appendingPathComponent("watch.json")+    defer { try? FileManager.default.removeItem(at: file.deletingLastPathComponent()) }+    let runtime = SyntheticRoundRuntime()+    var sample = ClockSample(wall: Date(), monotonic: 0, continuityID: "synthetic")+    var signals = 0+    let controller = WatchController(+      file: file, activate: false, runtime: runtime, clock: { sample }, haptic: { signals += 1 })+    let definition = FrozenRoutineDefinition(+      routineID: UUID(), revision: 1, kind: .timedRounds, name: "Synthetic timer", instructions: "",+      roundCount: 2, roundDurationSeconds: 30, betweenRoundInstructions: "Synthetic wait", steps: []+    )+    let id = try controller.start(.init(definition: definition, occurrences: []), occurrence: nil)+    try controller.transitionTimer(id, .start)+    #expect(runtime.deadlines.count == 1)+    sample.wall = sample.wall.addingTimeInterval(30)+    sample.monotonic = 30+    runtime.onBoundary()+    #expect(controller.value(id)?.timer?.phase == .waiting && signals == 1)+    #expect(runtime.stops > 0 && runtime.deadlines.count == 1)+    sample.wall = sample.wall.addingTimeInterval(600)+    sample.monotonic = 630+    controller.tick()+    #expect(controller.value(id)?.timer?.completedRounds == 1 && runtime.deadlines.count == 1)+    try controller.transitionTimer(id, .start)+    #expect(runtime.deadlines.count == 2)+    runtime.onInterrupted("Synthetic startup/invalidation failure")+    #expect(controller.value(id)?.timer?.phase == .paused)+    #expect(controller.runtimeMessage == "Synthetic startup/invalidation failure")+    #expect(controller.value(id)?.timer?.completedRounds == 1)+    try controller.transitionTimer(id, .resume)+    #expect(runtime.deadlines.count == 3)+    try controller.transitionTimer(id, .end)+    #expect(controller.value(id)?.timer?.phase == .ended && signals == 1)+  }  } - @MainActor private final class SyntheticRoundRuntime: RoundRuntimeManaging {-    var onBoundary: () -> Void = {}-    var onInterrupted: (String) -> Void = { _ in }-    var deadlines: [Date] = []-    var stops = 0-    func start(deadline: Date) { deadlines.append(deadline) }-    func stop() { stops += 1 }+  var onBoundary: () -> Void = {}+  var onInterrupted: (String) -> Void = { _ in }+  var deadlines: [Date] = []+  var stops = 0+  func start(deadline: Date) { deadlines.append(deadline) }+  func stop() { stops += 1 } }
Meddy/Shared/Companion/CompanionOwnership.swift Modified
diff --git a/Meddy/Shared/Companion/CompanionOwnership.swift b/Meddy/Shared/Companion/CompanionOwnership.swiftindex 2a7de13..d039d28 100644--- a/Meddy/Shared/Companion/CompanionOwnership.swift+++ b/Meddy/Shared/Companion/CompanionOwnership.swift@@ -1,104 +1,225 @@ import Foundation  nonisolated enum CompanionOwnership {-    static func owner(_ run: CompanionRun) -> UUID { run.profileID ?? run.definition.profileID ?? ProfileIdentity.me }-    static func validate(_ snapshot: CompanionSnapshot) throws {-        guard [1,2].contains(snapshot.version) else { throw CompanionStoreError.unsupportedVersion }-        let profiles = snapshot.profiles ?? [CompanionProfile(id: ProfileIdentity.me, label: "Me", archived: false, lifecycleID: ProfileIdentity.selfLifecycle)]-        guard Set(profiles.map(\.id)).count == profiles.count else { throw ProfileError.conflictingOwnership }-        func check(_ id: UUID?, version: Int?, lifecycle: UUID?) throws {-            let owner = id ?? ProfileIdentity.me-            guard let profile = profiles.first(where: { $0.id == owner }) else { throw ProfileError.unknownOwner }-            if snapshot.version == 1 { guard owner == ProfileIdentity.me else { throw ProfileError.conflictingOwnership } }-            else { guard id != nil, version == ProfileIdentity.ownershipVersion, lifecycle == profile.lifecycleID else { throw ProfileError.conflictingOwnership } }-        }-        func checkWake(_ anchors: [WakeAnchor], owner: UUID) throws {-            for wake in anchors {-                guard wake.profileID == owner, wake.ownershipVersion == 1,-                      profiles.first(where: { $0.id == owner })?.lifecycleID == wake.profileLifecycleID else { throw ProfileError.conflictingOwnership }-            }-        }-        for medication in snapshot.medications {-            try checkWake(medication.schedule.wakeAnchors ?? medication.schedule.wakeAnchor.map { [$0] } ?? [], owner: medication.profileID ?? ProfileIdentity.me)-            if let anchor = medication.schedule.wakeAnchor { try checkWake([anchor], owner: medication.profileID ?? ProfileIdentity.me) }-        }-        for routine in snapshot.routines {-            if let schedule = routine.schedule {-                try checkWake(schedule.wakeAnchors ?? schedule.wakeAnchor.map { [$0] } ?? [], owner: routine.definition.profileID ?? ProfileIdentity.me)-                if let anchor = schedule.wakeAnchor { try checkWake([anchor], owner: routine.definition.profileID ?? ProfileIdentity.me) }-            }-        }-        var entities: [UUID: UUID] = [:]-        func entity(_ id: UUID, owner: UUID) throws { guard entities[id] == nil else { throw ProfileError.conflictingOwnership }; entities[id] = owner }-        for value in snapshot.medications { try check(value.profileID, version: value.ownershipVersion, lifecycle: value.profileLifecycleID); try entity(value.id, owner: value.profileID ?? ProfileIdentity.me) }-        for value in snapshot.treatments ?? [] { try check(value.profileID, version: value.ownershipVersion, lifecycle: value.profileLifecycleID); try entity(value.id, owner: value.profileID ?? ProfileIdentity.me) }-        for value in snapshot.routines { try check(value.definition.profileID, version: value.definition.ownershipVersion, lifecycle: value.definition.profileLifecycleID); try entity(value.id, owner: value.definition.profileID ?? ProfileIdentity.me) }-        for value in snapshot.runs {-            let id = owner(value)-            guard profiles.contains(where: { $0.id == id }) else { throw ProfileError.unknownOwner }-            if snapshot.version == 1 { guard id == ProfileIdentity.me else { throw ProfileError.conflictingOwnership } }-            else { guard value.profileID != nil, value.ownershipVersion == 1 else { throw ProfileError.unknownOwner } }-            try validate(value); try entity(value.id, owner: id)-        }-        for routine in snapshot.routines {-            let owner = routine.definition.profileID ?? ProfileIdentity.me-            for step in routine.definition.steps {-                guard (step.profileID ?? ProfileIdentity.me) == owner else { throw ProfileError.conflictingOwnership }-                if let target = entities[step.targetID] { guard target == owner else { throw ProfileError.conflictingOwnership } }-                else if snapshot.version == 2 { throw ProfileError.unknownOwner }-                if snapshot.version == 2 { guard step.profileID == owner, step.ownershipVersion == 1 else { throw ProfileError.unknownOwner } }-            }-        }-        if snapshot.version == 2 {-            guard let owners = snapshot.eventOwners, (snapshot.appliedEventIDs + snapshot.deletedEventIDs).allSatisfy({ owners[$0].map { id in profiles.contains { $0.id == id } } == true }) else { throw ProfileError.unknownOwner }-        } else {-            guard profiles.allSatisfy({ $0.id == ProfileIdentity.me }), (snapshot.eventOwners ?? [:]).values.allSatisfy({ $0 == ProfileIdentity.me }) else { throw ProfileError.conflictingOwnership }+  static func owner(_ run: CompanionRun) -> UUID {+    run.profileID ?? run.definition.profileID ?? ProfileIdentity.me+  }+  static func validate(_ snapshot: CompanionSnapshot) throws {+    guard [1, 2].contains(snapshot.version) else { throw CompanionStoreError.unsupportedVersion }+    let profiles =+      snapshot.profiles ?? [+        CompanionProfile(+          id: ProfileIdentity.me, label: "Me", archived: false,+          lifecycleID: ProfileIdentity.selfLifecycle)+      ]+    guard Set(profiles.map(\.id)).count == profiles.count else {+      throw ProfileError.conflictingOwnership+    }+    func check(_ id: UUID?, version: Int?, lifecycle: UUID?) throws {+      let owner = id ?? ProfileIdentity.me+      guard let profile = profiles.first(where: { $0.id == owner }) else {+        throw ProfileError.unknownOwner+      }+      if snapshot.version == 1 {+        guard owner == ProfileIdentity.me else { throw ProfileError.conflictingOwnership }+      } else {+        guard id != nil, version == ProfileIdentity.ownershipVersion,+          lifecycle == profile.lifecycleID+        else { throw ProfileError.conflictingOwnership }+      }+    }+    try validateWakeAnchors(snapshot, profiles: profiles)+    var entities: [UUID: UUID] = [:]+    func entity(_ id: UUID, owner: UUID) throws {+      guard entities[id] == nil else { throw ProfileError.conflictingOwnership }+      entities[id] = owner+    }+    for value in snapshot.medications {+      try check(+        value.profileID, version: value.ownershipVersion, lifecycle: value.profileLifecycleID)+      try entity(value.id, owner: value.profileID ?? ProfileIdentity.me)+    }+    for value in snapshot.treatments ?? [] {+      try check(+        value.profileID, version: value.ownershipVersion, lifecycle: value.profileLifecycleID)+      try entity(value.id, owner: value.profileID ?? ProfileIdentity.me)+    }+    for value in snapshot.routines {+      try check(+        value.definition.profileID, version: value.definition.ownershipVersion,+        lifecycle: value.definition.profileLifecycleID)+      try entity(value.id, owner: value.definition.profileID ?? ProfileIdentity.me)+    }+    for value in snapshot.runs {+      let id = owner(value)+      guard profiles.contains(where: { $0.id == id }) else { throw ProfileError.unknownOwner }+      if snapshot.version == 1 {+        guard id == ProfileIdentity.me else { throw ProfileError.conflictingOwnership }+      } else {+        guard value.profileID != nil, value.ownershipVersion == 1 else {+          throw ProfileError.unknownOwner         }+      }+      try validate(value)+      try entity(value.id, owner: id)+    }+    try validateRoutineSteps(snapshot, entities: entities)+    try validateEventOwners(snapshot, profiles: profiles)+  }+  static func validate(_ run: CompanionRun) throws {+    let owner = owner(run)+    guard !(run.profileID == nil && run.ownershipVersion != nil),+      !(run.definition.profileID == nil && run.definition.ownershipVersion != nil),+      run.definition.steps.allSatisfy({ !($0.profileID == nil && $0.ownershipVersion != nil) })+    else { throw ProfileError.unknownOwner }+    guard (run.definition.profileID ?? ProfileIdentity.me) == owner,+      run.definition.steps.allSatisfy({ ($0.profileID ?? ProfileIdentity.me) == owner })+    else { throw ProfileError.conflictingOwnership }+    if owner != ProfileIdentity.me {+      guard run.profileID != nil, run.ownershipVersion == ProfileIdentity.ownershipVersion,+        run.definition.ownershipVersion == ProfileIdentity.ownershipVersion,+        run.definition.steps.allSatisfy({ $0.ownershipVersion == ProfileIdentity.ownershipVersion }+        ), run.profileLifecycleID != nil+      else { throw ProfileError.unknownOwner }     }-    static func validate(_ run: CompanionRun) throws {-        let owner = owner(run)-        guard !(run.profileID == nil && run.ownershipVersion != nil), !(run.definition.profileID == nil && run.definition.ownershipVersion != nil),-              run.definition.steps.allSatisfy({ !($0.profileID == nil && $0.ownershipVersion != nil) }) else { throw ProfileError.unknownOwner }-        guard (run.definition.profileID ?? ProfileIdentity.me) == owner,-              run.definition.steps.allSatisfy({ ($0.profileID ?? ProfileIdentity.me) == owner }) else { throw ProfileError.conflictingOwnership }-        if owner != ProfileIdentity.me {-            guard run.profileID != nil, run.ownershipVersion == ProfileIdentity.ownershipVersion,-                  run.definition.ownershipVersion == ProfileIdentity.ownershipVersion,-                  run.definition.steps.allSatisfy({ $0.ownershipVersion == ProfileIdentity.ownershipVersion }), run.profileLifecycleID != nil else { throw ProfileError.unknownOwner }+  }+  static func validate(_ action: CompanionAction, snapshot: CompanionSnapshot?) throws {+    guard [1, 2].contains(action.version) else { throw CompanionStoreError.unsupportedVersion }+    let owner = action.profileID ?? ProfileIdentity.me+    if action.version == 1 {+      guard owner == ProfileIdentity.me else { throw ProfileError.conflictingOwnership }+    }+    if action.version == 2 {+      guard action.profileID != nil, action.ownershipVersion == ProfileIdentity.ownershipVersion+      else { throw ProfileError.unknownOwner }+      guard let profile = snapshot?.profiles?.first(where: { $0.id == owner }), !profile.archived+      else { throw ProfileError.archived }+      guard profile.lifecycleID == action.profileLifecycleID else {+        throw ProfileError.staleLifecycle+      }+    }+    let runs = try cachedRuns(for: action, owner: owner)+    for run in runs {+      try validate(run)+      guard self.owner(run) == owner else { throw ProfileError.conflictingOwnership }+    }+    if let runID = action.operation.runID,+      let target = snapshot?.runs.first(where: { $0.id == runID }) {+      guard self.owner(target) == owner else { throw ProfileError.conflictingOwnership }+    }+  }+  @MainActor static func validate(+    _ runs: [CompanionRun], against state: CompanionStore.State, owner: UUID? = nil+  ) throws {+    var seen: [UUID: UUID] = [:]+    for run in runs {+      try validate(run)+      let id = self.owner(run)+      if let owner { guard id == owner else { throw ProfileError.conflictingOwnership } }+      if let previous = seen[run.id] {+        guard previous == id else { throw ProfileError.conflictingOwnership }+      }+      seen[run.id] = id+      if let existing = state.localRuns[run.id]+        ?? state.snapshot?.runs.first(where: { $0.id == run.id }) {+        guard self.owner(existing) == id else { throw ProfileError.conflictingOwnership }+      }+    }+  }++  private static func validateWakeAnchors(+    _ snapshot: CompanionSnapshot, profiles: [CompanionProfile]+  ) throws {+    func checkWake(_ anchors: [WakeAnchor], owner: UUID) throws {+      for wake in anchors {+        guard wake.profileID == owner, wake.ownershipVersion == 1,+          profiles.first(where: { $0.id == owner })?.lifecycleID == wake.profileLifecycleID+        else { throw ProfileError.conflictingOwnership }+      }+    }+    for medication in snapshot.medications {+      try checkWake(+        medication.schedule.wakeAnchors ?? medication.schedule.wakeAnchor.map { [$0] } ?? [],+        owner: medication.profileID ?? ProfileIdentity.me)+      if let anchor = medication.schedule.wakeAnchor {+        try checkWake([anchor], owner: medication.profileID ?? ProfileIdentity.me)+      }+    }+    for routine in snapshot.routines {+      if let schedule = routine.schedule {+        try checkWake(+          schedule.wakeAnchors ?? schedule.wakeAnchor.map { [$0] } ?? [],+          owner: routine.definition.profileID ?? ProfileIdentity.me)+        if let anchor = schedule.wakeAnchor {+          try checkWake([anchor], owner: routine.definition.profileID ?? ProfileIdentity.me)         }+      }     }-    static func validate(_ action: CompanionAction, snapshot: CompanionSnapshot?) throws {-        guard [1,2].contains(action.version) else { throw CompanionStoreError.unsupportedVersion }-        let owner = action.profileID ?? ProfileIdentity.me-        if action.version == 1 { guard owner == ProfileIdentity.me else { throw ProfileError.conflictingOwnership } }-        if action.version == 2 {-            guard action.profileID != nil, action.ownershipVersion == ProfileIdentity.ownershipVersion else { throw ProfileError.unknownOwner }-            guard let profile = snapshot?.profiles?.first(where: { $0.id == owner }), !profile.archived else { throw ProfileError.archived }-            guard profile.lifecycleID == action.profileLifecycleID else { throw ProfileError.staleLifecycle }+  }++  private static func validateRoutineSteps(+    _ snapshot: CompanionSnapshot, entities: [UUID: UUID]+  ) throws {+    for routine in snapshot.routines {+      let owner = routine.definition.profileID ?? ProfileIdentity.me+      for step in routine.definition.steps {+        guard (step.profileID ?? ProfileIdentity.me) == owner else {+          throw ProfileError.conflictingOwnership         }-        var runs = [action.cachedRun, action.cachedParentRun].compactMap { $0 }-        switch action.operation {-        case .start(let run), .handoff(_, let run, _): runs.append(run)-        case .medication(let event, _, _):-            guard (event.profileID ?? ProfileIdentity.me) == owner else { throw ProfileError.conflictingOwnership }-            if owner != ProfileIdentity.me { guard event.ownershipVersion == 1, event.profileLifecycleID == action.profileLifecycleID else { throw ProfileError.staleLifecycle } }-        case .treatment(let event, _, _):-            guard (event.profileID ?? ProfileIdentity.me) == owner else { throw ProfileError.conflictingOwnership }-            if owner != ProfileIdentity.me { guard event.ownershipVersion == 1, event.profileLifecycleID == action.profileLifecycleID else { throw ProfileError.staleLifecycle } }-        default: break+        if let target = entities[step.targetID] {+          guard target == owner else { throw ProfileError.conflictingOwnership }+        } else if snapshot.version == 2 {+          throw ProfileError.unknownOwner         }-        for run in runs { try validate(run); guard self.owner(run) == owner else { throw ProfileError.conflictingOwnership } }-        if let runID = action.operation.runID, let target = snapshot?.runs.first(where: { $0.id == runID }) {-            guard self.owner(target) == owner else { throw ProfileError.conflictingOwnership }+        if snapshot.version == 2 {+          guard step.profileID == owner, step.ownershipVersion == 1 else {+            throw ProfileError.unknownOwner+          }         }+      }     }-    @MainActor static func validate(_ runs: [CompanionRun], against state: CompanionStore.State, owner: UUID? = nil) throws {-        var seen: [UUID: UUID] = [:]-        for run in runs {-            try validate(run); let id = self.owner(run)-            if let owner { guard id == owner else { throw ProfileError.conflictingOwnership } }-            if let previous = seen[run.id] { guard previous == id else { throw ProfileError.conflictingOwnership } }; seen[run.id] = id-            if let existing = state.localRuns[run.id] ?? state.snapshot?.runs.first(where: { $0.id == run.id }) { guard self.owner(existing) == id else { throw ProfileError.conflictingOwnership } }-        }+  }++  private static func validateEventOwners(+    _ snapshot: CompanionSnapshot, profiles: [CompanionProfile]+  ) throws {+    if snapshot.version == 2 {+      guard let owners = snapshot.eventOwners,+        (snapshot.appliedEventIDs + snapshot.deletedEventIDs).allSatisfy({+          owners[$0].map { id in profiles.contains { $0.id == id } } == true+        })+      else { throw ProfileError.unknownOwner }+    } else {+      guard profiles.allSatisfy({ $0.id == ProfileIdentity.me }),+        (snapshot.eventOwners ?? [:]).values.allSatisfy({ $0 == ProfileIdentity.me })+      else { throw ProfileError.conflictingOwnership }+    }+  }++  private static func cachedRuns(+    for action: CompanionAction, owner: UUID+  ) throws -> [CompanionRun] {+    var runs = [action.cachedRun, action.cachedParentRun].compactMap { $0 }+    switch action.operation {+    case .start(let run), .handoff(_, let run, _): runs.append(run)+    case .medication(let event, _, _):+      guard (event.profileID ?? ProfileIdentity.me) == owner else {+        throw ProfileError.conflictingOwnership+      }+      if owner != ProfileIdentity.me {+        guard event.ownershipVersion == 1, event.profileLifecycleID == action.profileLifecycleID+        else { throw ProfileError.staleLifecycle }+      }+    case .treatment(let event, _, _):+      guard (event.profileID ?? ProfileIdentity.me) == owner else {+        throw ProfileError.conflictingOwnership+      }+      if owner != ProfileIdentity.me {+        guard event.ownershipVersion == 1, event.profileLifecycleID == action.profileLifecycleID+        else { throw ProfileError.staleLifecycle }+      }+    default: break     }+    return runs+  } }
Meddy/Shared/Companion/CompanionTransport.swift Modified
diff --git a/Meddy/Shared/Companion/CompanionTransport.swift b/Meddy/Shared/Companion/CompanionTransport.swiftindex beb3ca6..ad8cafd 100644--- a/Meddy/Shared/Companion/CompanionTransport.swift+++ b/Meddy/Shared/Companion/CompanionTransport.swift@@ -3,80 +3,119 @@ import WatchConnectivity  @MainActor final class CompanionTransport: NSObject, WCSessionDelegate {-    private let session: WCSession-    var onMessage: (CompanionMessage, ((Data) -> Void)?) -> Void = { _, _ in }-    var onActivation: () -> Void = {}-    var onError: (String) -> Void = { _ in }-    var reachable: Bool { session.isReachable }-    var available: Bool {-        #if os(iOS)-        session.isPaired && session.isWatchAppInstalled-        #else-        session.isCompanionAppInstalled-        #endif-    }-    init(session: WCSession = .default) {-        self.session = session-        super.init()-    }-    func activate() { guard WCSession.isSupported() else { return }; session.delegate = self; session.activate() }-    func send(_ message: CompanionMessage) throws {-        let data = try JSONEncoder().encode(message)-        guard session.activationState == .activated else { return }-        if session.isReachable {-            session.sendMessageData(data, replyHandler: { [weak self] reply in-                guard let message = try? JSONDecoder().decode(CompanionMessage.self, from: reply) else { return }-                Task { @MainActor in self?.onMessage(message, nil) }-            }, errorHandler: { [weak self] error in Task { @MainActor in self?.onError(error.localizedDescription) } })-        }-        // Background delivery may duplicate immediate delivery. Action UUIDs make both safe.-        session.transferUserInfo(["meddy.message": data])-    }-    func publish(_ snapshot: CompanionSnapshot) throws {-        guard session.activationState == .activated else { return }-        let data = try JSONEncoder().encode(CompanionMessage.snapshot(snapshot))-        if data.count < 60_000 { try session.updateApplicationContext(["meddy.message": data]) }-        else {-            let directory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("MeddyTransfers")-            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)-            let file = directory.appendingPathComponent(UUID().uuidString + ".json")-            try data.write(to: file, options: .atomic)-            session.transferFile(file, metadata: ["meddy.snapshot": true])-        }-    }-    nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {-        let message = error?.localizedDescription-        Task { @MainActor [weak self] in if let message { self?.onError(message) }; self?.onActivation() }+  private let session: WCSession+  var onMessage: (CompanionMessage, ((Data) -> Void)?) -> Void = { _, _ in }+  var onActivation: () -> Void = {}+  var onError: (String) -> Void = { _ in }+  var reachable: Bool { session.isReachable }+  var available: Bool {+    #if os(iOS)+      session.isPaired && session.isWatchAppInstalled+    #else+      session.isCompanionAppInstalled+    #endif+  }+  init(session: WCSession = .default) {+    self.session = session+    super.init()+  }+  func activate() {+    guard WCSession.isSupported() else { return }+    session.delegate = self+    session.activate()+  }+  func send(_ message: CompanionMessage) throws {+    let data = try JSONEncoder().encode(message)+    guard session.activationState == .activated else { return }+    if session.isReachable {+      session.sendMessageData(+        data,+        replyHandler: { [weak self] reply in+          guard let message = try? JSONDecoder().decode(CompanionMessage.self, from: reply) else {+            return+          }+          Task { @MainActor in self?.onMessage(message, nil) }+        },+        errorHandler: { [weak self] error in+          Task { @MainActor in self?.onError(error.localizedDescription) }+        })     }-    nonisolated func sessionReachabilityDidChange(_ session: WCSession) { Task { @MainActor [weak self] in self?.onActivation() } }-    nonisolated func session(_ session: WCSession, didReceiveMessageData messageData: Data, replyHandler: @escaping (Data) -> Void) {-        guard let message = try? JSONDecoder().decode(CompanionMessage.self, from: messageData) else { return }-        let reply = CompanionReply(replyHandler)-        Task { @MainActor [weak self] in self?.onMessage(message, { reply.send($0) }) }+    // Background delivery may duplicate immediate delivery. Action UUIDs make both safe.+    session.transferUserInfo(["meddy.message": data])+  }+  func publish(_ snapshot: CompanionSnapshot) throws {+    guard session.activationState == .activated else { return }+    let data = try JSONEncoder().encode(CompanionMessage.snapshot(snapshot))+    if data.count < 60_000 {+      try session.updateApplicationContext(["meddy.message": data])+    } else {+      let directory = FileManager.default.urls(+        for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent(+          "MeddyTransfers")+      try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+      let file = directory.appendingPathComponent(UUID().uuidString + ".json")+      try data.write(to: file, options: .atomic)+      session.transferFile(file, metadata: ["meddy.snapshot": true])     }-    nonisolated func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) { receive(userInfo) }-    nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { receive(applicationContext) }-    nonisolated private func receive(_ values: [String: Any]) {-        guard let data = values["meddy.message"] as? Data, let message = try? JSONDecoder().decode(CompanionMessage.self, from: data) else { return }-        Task { @MainActor [weak self] in self?.onMessage(message, nil) }+  }+  nonisolated func session(+    _ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState,+    error: Error?+  ) {+    let message = error?.localizedDescription+    Task { @MainActor [weak self] in+      if let message { self?.onError(message) }+      self?.onActivation()     }-    nonisolated func session(_ session: WCSession, didReceive file: WCSessionFile) {-        guard let data = try? Data(contentsOf: file.fileURL), let message = try? JSONDecoder().decode(CompanionMessage.self, from: data) else { return }-        Task { @MainActor [weak self] in self?.onMessage(message, nil) }+  }+  nonisolated func sessionReachabilityDidChange(_ session: WCSession) {+    Task { @MainActor [weak self] in self?.onActivation() }+  }+  nonisolated func session(+    _ session: WCSession, didReceiveMessageData messageData: Data,+    replyHandler: @escaping (Data) -> Void+  ) {+    guard let message = try? JSONDecoder().decode(CompanionMessage.self, from: messageData) else {+      return     }-    nonisolated func session(_ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?) {-        guard error == nil, fileTransfer.file.metadata?["meddy.snapshot"] as? Bool == true else { return }-        try? FileManager.default.removeItem(at: fileTransfer.file.fileURL)+    let reply = CompanionReply(replyHandler)+    Task { @MainActor [weak self] in self?.onMessage(message, { reply.send($0) }) }+  }+  nonisolated func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {+    receive(userInfo)+  }+  nonisolated func session(+    _ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]+  ) { receive(applicationContext) }+  nonisolated private func receive(_ values: [String: Any]) {+    guard let data = values["meddy.message"] as? Data,+      let message = try? JSONDecoder().decode(CompanionMessage.self, from: data)+    else { return }+    Task { @MainActor [weak self] in self?.onMessage(message, nil) }+  }+  nonisolated func session(_ session: WCSession, didReceive file: WCSessionFile) {+    guard let data = try? Data(contentsOf: file.fileURL),+      let message = try? JSONDecoder().decode(CompanionMessage.self, from: data)+    else { return }+    Task { @MainActor [weak self] in self?.onMessage(message, nil) }+  }+  nonisolated func session(+    _ session: WCSession, didFinish fileTransfer: WCSessionFileTransfer, error: Error?+  ) {+    guard error == nil, fileTransfer.file.metadata?["meddy.snapshot"] as? Bool == true else {+      return     }-    #if os(iOS)+    try? FileManager.default.removeItem(at: fileTransfer.file.fileURL)+  }+  #if os(iOS)     nonisolated func sessionDidBecomeInactive(_ session: WCSession) {}     nonisolated func sessionDidDeactivate(_ session: WCSession) { session.activate() }-    #endif+  #endif }  // WCSession owns this escaping reply callback; wrapping it transfers that ownership once to the actor.-private nonisolated final class CompanionReply: @unchecked Sendable {-    private let callback: (Data) -> Void-    init(_ callback: @escaping (Data) -> Void) { self.callback = callback }-    func send(_ data: Data) { callback(data) }+nonisolated private final class CompanionReply: @unchecked Sendable {+  private let callback: (Data) -> Void+  init(_ callback: @escaping (Data) -> Void) { self.callback = callback }+  func send(_ data: Data) { callback(data) } }
Meddy/Shared/Companion/CompanionValues.swift Modified
diff --git a/Meddy/Shared/Companion/CompanionValues.swift b/Meddy/Shared/Companion/CompanionValues.swiftindex 2cdbecb..f0aada1 100644--- a/Meddy/Shared/Companion/CompanionValues.swift+++ b/Meddy/Shared/Companion/CompanionValues.swift@@ -1,258 +1,312 @@ import Foundation  nonisolated struct CompanionProfile: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var label: String-    var archived: Bool-    var lifecycleID: UUID+  var id: UUID+  var label: String+  var archived: Bool+  var lifecycleID: UUID }  nonisolated struct CompanionMedication: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var name: String-    var purpose: String?-    var requirements: String-    var dose: RecordedDoseSnapshot-    var schedule: MedicationScheduleSnapshot-    var next: Date?-    var lastTaken: Date?-    var active: Bool-    var doseLimitCheck: DoseLimitCheck? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: UUID+  var name: String+  var purpose: String?+  var requirements: String+  var dose: RecordedDoseSnapshot+  var schedule: MedicationScheduleSnapshot+  var next: Date?+  var lastTaken: Date?+  var active: Bool+  var doseLimitCheck: DoseLimitCheck?+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct CompanionTreatment: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var name: String-    var instructions: String-    var lastDone: Date?-    var active: Bool-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: UUID+  var name: String+  var instructions: String+  var lastDone: Date?+  var active: Bool+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct CompanionRoutine: Codable, Equatable, Identifiable, Sendable {-    var id: UUID { definition.routineID }-    var definition: FrozenRoutineDefinition-    var occurrences: [RoutineOccurrence]-    var schedule: RoutineScheduleSnapshot? = nil+  var id: UUID { definition.routineID }+  var definition: FrozenRoutineDefinition+  var occurrences: [RoutineOccurrence]+  var schedule: RoutineScheduleSnapshot? }  nonisolated struct CompanionRun: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var definition: FrozenRoutineDefinition-    var progress: OrderedCheckpoint-    var timer: TimerCheckpoint?-    var status: SessionPhase-    var startedAt: Date?-    var completedAt: Date?-    var revision: Int-    var executionDeviceID: String?-    var parentRunID: UUID?-    var parentStepID: UUID?-    var processedActionIDs: [UUID]-    var isDeleted: Bool-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: UUID+  var definition: FrozenRoutineDefinition+  var progress: OrderedCheckpoint+  var timer: TimerCheckpoint?+  var status: SessionPhase+  var startedAt: Date?+  var completedAt: Date?+  var revision: Int+  var executionDeviceID: String?+  var parentRunID: UUID?+  var parentStepID: UUID?+  var processedActionIDs: [UUID]+  var isDeleted: Bool+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct CompanionSnapshot: Codable, Equatable, Sendable {-    var version: Int = 1-    var phoneID: UUID-    var revision: Int-    var generatedAt: Date-    var medications: [CompanionMedication]-    var routines: [CompanionRoutine]-    var runs: [CompanionRun]-    var deletedEventIDs: [UUID]-    var appliedEventIDs: [UUID]-    var treatments: [CompanionTreatment]? = nil-    var profiles: [CompanionProfile]? = nil-    var eventOwners: [UUID: UUID]? = nil+  var version: Int = 1+  var phoneID: UUID+  var revision: Int+  var generatedAt: Date+  var medications: [CompanionMedication]+  var routines: [CompanionRoutine]+  var runs: [CompanionRun]+  var deletedEventIDs: [UUID]+  var appliedEventIDs: [UUID]+  var treatments: [CompanionTreatment]?+  var profiles: [CompanionProfile]?+  var eventOwners: [UUID: UUID]? }  nonisolated enum CompanionOperation: Codable, Equatable, Sendable {-    case medication(AdministrationAction, runID: UUID?, stepID: UUID?)-    case treatment(TreatmentAction, runID: UUID?, stepID: UUID?)-    case start(CompanionRun)-    case timer(runID: UUID, operation: TimerOperation, checkpoint: TimerCheckpoint)-    case skip(runID: UUID, stepID: UUID)-    case continueAfterSkip(runID: UUID, stepID: UUID)-    case pause(runID: UUID)-    case resume(runID: UUID)-    case end(runID: UUID)-    case handoff(runID: UUID, checkpoint: CompanionRun, toDeviceID: String)+  case medication(AdministrationAction, runID: UUID?, stepID: UUID?)+  case treatment(TreatmentAction, runID: UUID?, stepID: UUID?)+  case start(CompanionRun)+  case timer(runID: UUID, operation: TimerOperation, checkpoint: TimerCheckpoint)+  case skip(runID: UUID, stepID: UUID)+  case continueAfterSkip(runID: UUID, stepID: UUID)+  case pause(runID: UUID)+  case resume(runID: UUID)+  case end(runID: UUID)+  case handoff(runID: UUID, checkpoint: CompanionRun, toDeviceID: String) }  nonisolated struct CompanionAction: Codable, Equatable, Identifiable, Sendable {-    var version: Int = 1-    var id: UUID-    var deviceID: String-    var timestamp: Date-    var expectedRevision: Int?-    var operation: CompanionOperation-    var cachedRun: CompanionRun? = nil-    var cachedParentRun: CompanionRun? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var version: Int = 1+  var id: UUID+  var deviceID: String+  var timestamp: Date+  var expectedRevision: Int?+  var operation: CompanionOperation+  var cachedRun: CompanionRun?+  var cachedParentRun: CompanionRun?+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct CompanionAcknowledgement: Codable, Equatable, Sendable {-    var actionID: UUID-    var accepted: Bool-    var message: String?-    var snapshot: CompanionSnapshot?+  var actionID: UUID+  var accepted: Bool+  var message: String?+  var snapshot: CompanionSnapshot? }  nonisolated enum CompanionMessage: Codable, Sendable {-    case snapshot(CompanionSnapshot)-    case action(CompanionAction)-    case acknowledgement(CompanionAcknowledgement)-    case requestSnapshot-    case handoffCheckpoint(actionID: UUID, checkpoint: CompanionRun)+  case snapshot(CompanionSnapshot)+  case action(CompanionAction)+  case acknowledgement(CompanionAcknowledgement)+  case requestSnapshot+  case handoffCheckpoint(actionID: UUID, checkpoint: CompanionRun) } -nonisolated enum CompanionStoreError: Error { case unsupportedVersion, unrelatedPhone, staleSnapshot }+nonisolated enum CompanionStoreError: Error {+  case unsupportedVersion, unrelatedPhone, staleSnapshot+}  /// Commit the entire cache/outbox atomically before changing memory or transmitting an action. @MainActor final class CompanionStore {-    struct State: Codable {-        var deviceID: String = UUID().uuidString-        var snapshot: CompanionSnapshot?-        var pending: [CompanionAction] = []-        var rejected: [UUID: String] = [:]-        var localRuns: [UUID: CompanionRun] = [:]-        var incomingHandoffs: [UUID: CompanionAction]? = nil-    }-    private let file: URL-    private(set) var state: State-    init(file: URL) throws {-        self.file = file-        if FileManager.default.fileExists(atPath: file.path) { state = try JSONDecoder().decode(State.self, from: Data(contentsOf: file)) }-        else { state = State() }-        if let snapshot = state.snapshot { try CompanionOwnership.validate(snapshot) }-        for run in state.localRuns.values { try CompanionOwnership.validate(run) }+  struct State: Codable {+    var deviceID: String = UUID().uuidString+    var snapshot: CompanionSnapshot?+    var pending: [CompanionAction] = []+    var rejected: [UUID: String] = [:]+    var localRuns: [UUID: CompanionRun] = [:]+    var incomingHandoffs: [UUID: CompanionAction]?+  }+  private let file: URL+  private(set) var state: State+  init(file: URL) throws {+    self.file = file+    if FileManager.default.fileExists(atPath: file.path) {+      state = try JSONDecoder().decode(State.self, from: Data(contentsOf: file))+    } else {+      state = State()     }-    func enqueue(_ action: CompanionAction, localRun: CompanionRun? = nil) throws {-        try CompanionOwnership.validate(action, snapshot: state.snapshot)-        try CompanionOwnership.validate(localRun.map { [$0] } ?? [], against: state, owner: action.profileID ?? ProfileIdentity.me)-        var next = state-        if !next.pending.contains(where: { $0.id == action.id }) { next.pending.append(action) }-        if let localRun { next.localRuns[localRun.id] = localRun }-        try commit(next)+    if let snapshot = state.snapshot { try CompanionOwnership.validate(snapshot) }+    for run in state.localRuns.values { try CompanionOwnership.validate(run) }+  }+  func enqueue(_ action: CompanionAction, localRun: CompanionRun? = nil) throws {+    try CompanionOwnership.validate(action, snapshot: state.snapshot)+    try CompanionOwnership.validate(+      localRun.map { [$0] } ?? [], against: state, owner: action.profileID ?? ProfileIdentity.me)+    var next = state+    if !next.pending.contains(where: { $0.id == action.id }) { next.pending.append(action) }+    if let localRun { next.localRuns[localRun.id] = localRun }+    try commit(next)+  }+  func enqueue(_ action: CompanionAction, localRuns: [CompanionRun]) throws {+    try CompanionOwnership.validate(action, snapshot: state.snapshot)+    try CompanionOwnership.validate(+      localRuns, against: state, owner: action.profileID ?? ProfileIdentity.me)+    var next = state+    if !next.pending.contains(where: { $0.id == action.id }) { next.pending.append(action) }+    for run in localRuns { next.localRuns[run.id] = run }+    try commit(next)+  }+  func enqueue(actions: [CompanionAction], localRuns: [CompanionRun]) throws {+    for action in actions { try CompanionOwnership.validate(action, snapshot: state.snapshot) }+    try CompanionOwnership.validate(localRuns, against: state)+    var next = state+    for action in actions where !next.pending.contains(where: { $0.id == action.id }) {+      next.pending.append(action)     }-    func enqueue(_ action: CompanionAction, localRuns: [CompanionRun]) throws {-        try CompanionOwnership.validate(action, snapshot: state.snapshot)-        try CompanionOwnership.validate(localRuns, against: state, owner: action.profileID ?? ProfileIdentity.me)-        var next = state-        if !next.pending.contains(where: { $0.id == action.id }) { next.pending.append(action) }-        for run in localRuns { next.localRuns[run.id] = run }-        try commit(next)+    for run in localRuns { next.localRuns[run.id] = run }+    try commit(next)+  }+  func saveLocal(_ runs: [CompanionRun]) throws {+    try CompanionOwnership.validate(runs, against: state)+    var next = state+    for run in runs { next.localRuns[run.id] = run }+    try commit(next)+  }+  private func mayContinueLocalTimer(_ local: CompanionRun?, canonical: CompanionRun?) -> Bool {+    guard let local, let canonical else { return false }+    return local.timer?.phase == .running && !canonical.isDeleted+      && canonical.executionDeviceID == state.deviceID && canonical.revision <= local.revision+      && canonical.status != .needsReview+      && ![TimerPhase.ended, .completed].contains(canonical.timer?.phase ?? .ended)+  }+  func receive(_ snapshot: CompanionSnapshot) throws {+    try CompanionOwnership.validate(snapshot)+    try CompanionOwnership.validate(snapshot.runs, against: state)+    if let old = state.snapshot {+      guard old.phoneID == snapshot.phoneID else { throw CompanionStoreError.unrelatedPhone }+      guard snapshot.revision >= old.revision else { throw CompanionStoreError.staleSnapshot }     }-    func enqueue(actions: [CompanionAction], localRuns: [CompanionRun]) throws {-        for action in actions { try CompanionOwnership.validate(action, snapshot: state.snapshot) }-        try CompanionOwnership.validate(localRuns, against: state)-        var next = state-        for action in actions where !next.pending.contains(where: { $0.id == action.id }) { next.pending.append(action) }-        for run in localRuns { next.localRuns[run.id] = run }-        try commit(next)+    var next = state+    next.snapshot = snapshot+    for (id, run) in next.localRuns {+      let owner = run.profileID ?? run.definition.profileID ?? ProfileIdentity.me+      if let profile = snapshot.profiles?.first(where: { $0.id == owner }) {+        if profile.archived+          || (owner != ProfileIdentity.me && run.profileLifecycleID != profile.lifecycleID) {+          next.localRuns.removeValue(forKey: id)+        }+      } else if owner != ProfileIdentity.me {+        next.localRuns.removeValue(forKey: id)+      }     }-    func saveLocal(_ runs: [CompanionRun]) throws {-        try CompanionOwnership.validate(runs, against: state)-        var next = state-        for run in runs { next.localRuns[run.id] = run }-        try commit(next)+    // Deleted runs never remain executable, even while distinct actual actions await acknowledgement.+    for run in snapshot.runs where run.isDeleted { next.localRuns.removeValue(forKey: run.id) }+    // Authoritative phone correction wins after every pending action is acknowledged.+    for run in snapshot.runs+    where !next.pending.contains(where: {+      $0.cachedRun?.id == run.id || $0.operation.runID == run.id+    }) {+      if !mayContinueLocalTimer(next.localRuns[run.id], canonical: run) {+        next.localRuns.removeValue(forKey: run.id)+      }     }-    private func mayContinueLocalTimer(_ local: CompanionRun?, canonical: CompanionRun?) -> Bool {-        guard let local, let canonical else { return false }-        return local.timer?.phase == .running && !canonical.isDeleted && canonical.executionDeviceID == state.deviceID && canonical.revision <= local.revision && canonical.status != .needsReview && ![TimerPhase.ended, .completed].contains(canonical.timer?.phase ?? .ended)+    try commit(next)+  }+  func acknowledge(_ acknowledgement: CompanionAcknowledgement) throws {+    guard state.pending.contains(where: { $0.id == acknowledgement.actionID }) else { return }+    if let snapshot = acknowledgement.snapshot {+      try CompanionOwnership.validate(snapshot)+      try CompanionOwnership.validate(snapshot.runs, against: state)+      if let old = state.snapshot {+        guard old.phoneID == snapshot.phoneID else { throw CompanionStoreError.unrelatedPhone }+        guard snapshot.revision >= old.revision else { throw CompanionStoreError.staleSnapshot }+      }     }-    func receive(_ snapshot: CompanionSnapshot) throws {-        try CompanionOwnership.validate(snapshot)-        try CompanionOwnership.validate(snapshot.runs, against: state)-        if let old = state.snapshot {-            guard old.phoneID == snapshot.phoneID else { throw CompanionStoreError.unrelatedPhone }-            guard snapshot.revision >= old.revision else { throw CompanionStoreError.staleSnapshot }-        }-        var next = state; next.snapshot = snapshot-        for (id, run) in next.localRuns {-            let owner = run.profileID ?? run.definition.profileID ?? ProfileIdentity.me-            if let profile = snapshot.profiles?.first(where: { $0.id == owner }) {-                if profile.archived || (owner != ProfileIdentity.me && run.profileLifecycleID != profile.lifecycleID) { next.localRuns.removeValue(forKey: id) }-            } else if owner != ProfileIdentity.me { next.localRuns.removeValue(forKey: id) }+    var next = state+    if acknowledgement.accepted {+      let runID = next.pending.first { $0.id == acknowledgement.actionID }?.operation.runID+      next.pending.removeAll { $0.id == acknowledgement.actionID }+      next.rejected.removeValue(forKey: acknowledgement.actionID)+      if let runID, !next.pending.contains(where: { $0.operation.runID == runID }) {+        if !mayContinueLocalTimer(+          next.localRuns[runID], canonical: acknowledgement.snapshot?.runs.first { $0.id == runID }) {+          next.localRuns.removeValue(forKey: runID)         }-        // Deleted runs never remain executable, even while distinct actual actions await acknowledgement.-        for run in snapshot.runs where run.isDeleted { next.localRuns.removeValue(forKey: run.id) }-        // Authoritative phone correction wins after every pending action is acknowledged.-        for run in snapshot.runs where !next.pending.contains(where: { $0.cachedRun?.id == run.id || $0.operation.runID == run.id }) { if !mayContinueLocalTimer(next.localRuns[run.id], canonical: run) { next.localRuns.removeValue(forKey: run.id) } }-        try commit(next)+      }+    } else {+      next.rejected[acknowledgement.actionID] =+        acknowledgement.message ?? "Phone could not save this action. It remains on this Watch."     }-    func acknowledge(_ acknowledgement: CompanionAcknowledgement) throws {-        guard state.pending.contains(where: { $0.id == acknowledgement.actionID }) else { return }-        if let snapshot = acknowledgement.snapshot {-            try CompanionOwnership.validate(snapshot)-            try CompanionOwnership.validate(snapshot.runs, against: state)-            if let old = state.snapshot { guard old.phoneID == snapshot.phoneID else { throw CompanionStoreError.unrelatedPhone }; guard snapshot.revision >= old.revision else { throw CompanionStoreError.staleSnapshot } }+    if let snapshot = acknowledgement.snapshot, [1, 2].contains(snapshot.version),+      next.snapshot == nil+        || (next.snapshot?.phoneID == snapshot.phoneID+          && snapshot.revision >= (next.snapshot?.revision ?? 0)) {+      next.snapshot = snapshot+      for (id, run) in next.localRuns {+        let owner = CompanionOwnership.owner(run)+        if let profile = snapshot.profiles?.first(where: { $0.id == owner }) {+          if profile.archived+            || (owner != ProfileIdentity.me && run.profileLifecycleID != profile.lifecycleID) {+            next.localRuns.removeValue(forKey: id)+          }+        } else if owner != ProfileIdentity.me {+          next.localRuns.removeValue(forKey: id)         }-        var next = state-        if acknowledgement.accepted {-            let runID = next.pending.first { $0.id == acknowledgement.actionID }?.operation.runID-            next.pending.removeAll { $0.id == acknowledgement.actionID }; next.rejected.removeValue(forKey: acknowledgement.actionID)-            if let runID, !next.pending.contains(where: { $0.operation.runID == runID }) { if !mayContinueLocalTimer(next.localRuns[runID], canonical: acknowledgement.snapshot?.runs.first { $0.id == runID }) { next.localRuns.removeValue(forKey: runID) } }-        } else { next.rejected[acknowledgement.actionID] = acknowledgement.message ?? "Phone could not save this action. It remains on this Watch." }-        if let snapshot = acknowledgement.snapshot, [1,2].contains(snapshot.version), (next.snapshot == nil || (next.snapshot?.phoneID == snapshot.phoneID && snapshot.revision >= (next.snapshot?.revision ?? 0))) { next.snapshot = snapshot-            for (id, run) in next.localRuns {-                let owner = CompanionOwnership.owner(run)-                if let profile = snapshot.profiles?.first(where: { $0.id == owner }) {-                    if profile.archived || (owner != ProfileIdentity.me && run.profileLifecycleID != profile.lifecycleID) { next.localRuns.removeValue(forKey: id) }-                } else if owner != ProfileIdentity.me { next.localRuns.removeValue(forKey: id) }-            }-            for run in snapshot.runs where run.isDeleted { next.localRuns.removeValue(forKey: run.id) }-        }-        try commit(next)-    }-    // Only a rejected ownership request may be replaced. Actual care events remain durable.-    func discardRejectedHandoff(_ id: UUID) throws {-        guard state.rejected[id] != nil,-              let action = state.pending.first(where: { $0.id == id }),-              case .handoff = action.operation else { throw CompanionStoreError.unsupportedVersion }-        var next = state-        next.pending.removeAll { $0.id == id }; next.rejected.removeValue(forKey: id)-        try commit(next)-    }-    func rememberIncomingHandoff(_ action: CompanionAction) throws {-        try CompanionOwnership.validate(action, snapshot: state.snapshot)-        guard case .handoff = action.operation else { throw CompanionStoreError.unsupportedVersion }-        var next = state-        var requests = next.incomingHandoffs ?? [:]; requests[action.id] = action-        next.incomingHandoffs = requests-        try commit(next)-    }-    func finishIncomingHandoff(_ id: UUID) throws {-        var next = state; next.incomingHandoffs?.removeValue(forKey: id); try commit(next)+      }+      for run in snapshot.runs where run.isDeleted { next.localRuns.removeValue(forKey: run.id) }     }+    try commit(next)+  }+  // Only a rejected ownership request may be replaced. Actual care events remain durable.+  func discardRejectedHandoff(_ id: UUID) throws {+    guard state.rejected[id] != nil,+      let action = state.pending.first(where: { $0.id == id }),+      case .handoff = action.operation+    else { throw CompanionStoreError.unsupportedVersion }+    var next = state+    next.pending.removeAll { $0.id == id }+    next.rejected.removeValue(forKey: id)+    try commit(next)+  }+  func rememberIncomingHandoff(_ action: CompanionAction) throws {+    try CompanionOwnership.validate(action, snapshot: state.snapshot)+    guard case .handoff = action.operation else { throw CompanionStoreError.unsupportedVersion }+    var next = state+    var requests = next.incomingHandoffs ?? [:]+    requests[action.id] = action+    next.incomingHandoffs = requests+    try commit(next)+  }+  func finishIncomingHandoff(_ id: UUID) throws {+    var next = state+    next.incomingHandoffs?.removeValue(forKey: id)+    try commit(next)+  } -    private func commit(_ next: State) throws {-        let data = try JSONEncoder().encode(next)-        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)-        try data.write(to: file, options: .atomic)-        state = next-    }+  private func commit(_ next: State) throws {+    let data = try JSONEncoder().encode(next)+    try FileManager.default.createDirectory(+      at: file.deletingLastPathComponent(), withIntermediateDirectories: true)+    try data.write(to: file, options: .atomic)+    state = next+  } }  nonisolated extension CompanionOperation {-    var runID: UUID? {-        switch self {-        case .medication(_, let id, _): id-        case .treatment(_, let id, _): id-        case .timer(let id, _, _), .skip(let id, _), .continueAfterSkip(let id, _), .pause(let id), .resume(let id), .end(let id), .handoff(let id, _, _): id-        case .start(let run): run.id-        }+  var runID: UUID? {+    switch self {+    case .medication(_, let id, _): id+    case .treatment(_, let id, _): id+    case .timer(let id, _, _), .skip(let id, _), .continueAfterSkip(let id, _), .pause(let id),+      .resume(let id), .end(let id), .handoff(let id, _, _):+      id+    case .start(let run): run.id     }+  } }
Meddy/Shared/RoutineExecution/ExecutionValues.swift Modified
diff --git a/Meddy/Shared/RoutineExecution/ExecutionValues.swift b/Meddy/Shared/RoutineExecution/ExecutionValues.swiftindex 7a99eab..b3d8484 100644--- a/Meddy/Shared/RoutineExecution/ExecutionValues.swift+++ b/Meddy/Shared/RoutineExecution/ExecutionValues.swift@@ -1,259 +1,326 @@ import Foundation  nonisolated enum ExecutionError: Error, LocalizedError, Equatable, Sendable {-    case invalidTransition, stepNotReady, unknownStep, unknownRun, invalidSnapshot, linkedElsewhere, ineligibleLog, invalidTimer, saveFailed-    var errorDescription: String? {-        switch self {-        case .invalidTransition: "This action is unavailable in the current session state."-        case .stepNotReady: "Finish the preceding step or explicitly continue after its skip."-        case .unknownStep: "The saved step is unavailable. Keep this action for review."-        case .unknownRun: "The saved session is unavailable. Keep this action for review."-        case .invalidSnapshot: "The saved plan could not be read. It needs review."-        case .linkedElsewhere: "This log already belongs to another step. Use an explicit move."-        case .ineligibleLog: "This log cannot fulfil this step."-        case .invalidTimer: "The saved timer settings are invalid."-        case .saveFailed: "The session could not be saved. Please try again."-        }+  case invalidTransition, stepNotReady, unknownStep, unknownRun, invalidSnapshot, linkedElsewhere,+    ineligibleLog, invalidTimer, saveFailed+  var errorDescription: String? {+    switch self {+    case .invalidTransition: "This action is unavailable in the current session state."+    case .stepNotReady: "Finish the preceding step or explicitly continue after its skip."+    case .unknownStep: "The saved step is unavailable. Keep this action for review."+    case .unknownRun: "The saved session is unavailable. Keep this action for review."+    case .invalidSnapshot: "The saved plan could not be read. It needs review."+    case .linkedElsewhere: "This log already belongs to another step. Use an explicit move."+    case .ineligibleLog: "This log cannot fulfil this step."+    case .invalidTimer: "The saved timer settings are invalid."+    case .saveFailed: "The session could not be saved. Please try again."     }+  } }  nonisolated struct ClockSample: Codable, Equatable, Sendable {-    var wall: Date-    var monotonic: TimeInterval-    // A new token on process relaunch is conservative: an uncertain checkpoint requires explicit resume.-    var continuityID: String+  var wall: Date+  var monotonic: TimeInterval+  // A new token on process relaunch is conservative: an uncertain checkpoint requires explicit resume.+  var continuityID: String }  nonisolated enum TimerPhase: String, Codable, Sendable {-    case ready, running, paused, interrupted, waiting, completed, ended+  case ready, running, paused, interrupted, waiting, completed, ended }  nonisolated struct TimerCheckpoint: Codable, Equatable, Sendable {-    var phase: TimerPhase = .ready-    var roundCount: Int-    var durationSeconds: TimeInterval-    var roundIndex: Int = 0-    var completedRounds: Int = 0-    var accumulatedActiveSeconds: TimeInterval = 0-    var anchor: ClockSample?-    var deadline: Date?-    var phaseBeforeEnd: TimerPhase?+  var phase: TimerPhase = .ready+  var roundCount: Int+  var durationSeconds: TimeInterval+  var roundIndex: Int = 0+  var completedRounds: Int = 0+  var accumulatedActiveSeconds: TimeInterval = 0+  var anchor: ClockSample?+  var deadline: Date?+  var phaseBeforeEnd: TimerPhase? -    init(rounds: Int, durationSeconds: Int) throws {-        guard rounds > 0, durationSeconds > 0 else { throw ExecutionError.invalidTimer }-        roundCount = rounds-        self.durationSeconds = TimeInterval(durationSeconds)-    }+  init(rounds: Int, durationSeconds: Int) throws {+    guard rounds > 0, durationSeconds > 0 else { throw ExecutionError.invalidTimer }+    roundCount = rounds+    self.durationSeconds = TimeInterval(durationSeconds)+  } -    func remaining(at clock: ClockSample) -> TimeInterval {-        let additional: TimeInterval-        if phase == .running, let anchor, anchor.continuityID == clock.continuityID {-            additional = max(0, clock.monotonic - anchor.monotonic)-        } else { additional = 0 }-        return max(0, durationSeconds - accumulatedActiveSeconds - additional)+  func remaining(at clock: ClockSample) -> TimeInterval {+    let additional: TimeInterval+    if phase == .running, let anchor, anchor.continuityID == clock.continuityID {+      additional = max(0, clock.monotonic - anchor.monotonic)+    } else {+      additional = 0     }+    return max(0, durationSeconds - accumulatedActiveSeconds - additional)+  } -    mutating func start(at clock: ClockSample) throws {-        guard phase == .ready || phase == .waiting else { throw ExecutionError.invalidTransition }-        if phase == .ready { roundIndex = 0 } else { roundIndex += 1 }-        accumulatedActiveSeconds = 0-        phase = .running-        anchor = clock-        deadline = clock.wall.addingTimeInterval(durationSeconds)-    }+  mutating func start(at clock: ClockSample) throws {+    guard phase == .ready || phase == .waiting else { throw ExecutionError.invalidTransition }+    if phase == .ready { roundIndex = 0 } else { roundIndex += 1 }+    accumulatedActiveSeconds = 0+    phase = .running+    anchor = clock+    deadline = clock.wall.addingTimeInterval(durationSeconds)+  } -    // Returns true only at a state boundary; callers do not persist every display tick.-    @discardableResult mutating func advance(at clock: ClockSample) -> Bool {-        guard phase == .running, let anchor else { return false }-        let elapsed = clock.monotonic - anchor.monotonic-        let wallElapsed = clock.wall.timeIntervalSince(anchor.wall)-        guard anchor.continuityID == clock.continuityID, elapsed >= 0,-              abs(elapsed - wallElapsed) < 5 else {-            phase = .interrupted; self.anchor = nil; deadline = nil-            return true-        }-        guard elapsed + accumulatedActiveSeconds >= durationSeconds else { return false }-        accumulatedActiveSeconds = durationSeconds-        completedRounds = roundIndex + 1-        phase = completedRounds == roundCount ? .completed : .waiting-        self.anchor = nil; deadline = nil-        return true+  // Returns true only at a state boundary; callers do not persist every display tick.+  @discardableResult mutating func advance(at clock: ClockSample) -> Bool {+    guard phase == .running, let anchor else { return false }+    let elapsed = clock.monotonic - anchor.monotonic+    let wallElapsed = clock.wall.timeIntervalSince(anchor.wall)+    guard anchor.continuityID == clock.continuityID, elapsed >= 0,+      abs(elapsed - wallElapsed) < 5+    else {+      phase = .interrupted+      self.anchor = nil+      deadline = nil+      return true     }+    guard elapsed + accumulatedActiveSeconds >= durationSeconds else { return false }+    accumulatedActiveSeconds = durationSeconds+    completedRounds = roundIndex + 1+    phase = completedRounds == roundCount ? .completed : .waiting+    self.anchor = nil+    deadline = nil+    return true+  } -    mutating func pause(at clock: ClockSample) throws {-        guard phase == .running else { throw ExecutionError.invalidTransition }-        if advance(at: clock) { return }-        if let anchor { accumulatedActiveSeconds += max(0, clock.monotonic - anchor.monotonic) }-        phase = .paused; anchor = nil; deadline = nil-    }+  mutating func pause(at clock: ClockSample) throws {+    guard phase == .running else { throw ExecutionError.invalidTransition }+    if advance(at: clock) { return }+    if let anchor { accumulatedActiveSeconds += max(0, clock.monotonic - anchor.monotonic) }+    phase = .paused+    anchor = nil+    deadline = nil+  } -    mutating func resume(at clock: ClockSample) throws {-        guard phase == .paused || phase == .interrupted else { throw ExecutionError.invalidTransition }-        phase = .running; anchor = clock-        deadline = clock.wall.addingTimeInterval(max(0, durationSeconds - accumulatedActiveSeconds))-    }+  mutating func resume(at clock: ClockSample) throws {+    guard phase == .paused || phase == .interrupted else { throw ExecutionError.invalidTransition }+    phase = .running+    anchor = clock+    deadline = clock.wall.addingTimeInterval(max(0, durationSeconds - accumulatedActiveSeconds))+  } -    mutating func end(at clock: ClockSample) throws {-        guard phase != .completed && phase != .ended else { throw ExecutionError.invalidTransition }-        if phase == .running { try pause(at: clock) }-        if phase == .completed { return }-        phaseBeforeEnd = phase-        phase = .ended; anchor = nil; deadline = nil-    }+  mutating func end(at clock: ClockSample) throws {+    guard phase != .completed && phase != .ended else { throw ExecutionError.invalidTransition }+    if phase == .running { try pause(at: clock) }+    if phase == .completed { return }+    phaseBeforeEnd = phase+    phase = .ended+    anchor = nil+    deadline = nil+  } -    mutating func reopen() throws {-        guard phase == .ended else { throw ExecutionError.invalidTransition }-        phase = phaseBeforeEnd == .waiting ? .waiting : (phaseBeforeEnd == .ready ? .ready : .paused)-        phaseBeforeEnd = nil-    }+  mutating func reopen() throws {+    guard phase == .ended else { throw ExecutionError.invalidTransition }+    phase = phaseBeforeEnd == .waiting ? .waiting : (phaseBeforeEnd == .ready ? .ready : .paused)+    phaseBeforeEnd = nil+  } }  nonisolated enum StepPhase: String, Codable, Sendable {-    case pending, inProgress, paused, completed, skipped, needsReview+  case pending, inProgress, paused, completed, skipped, needsReview }  nonisolated struct StepAudit: Codable, Equatable, Sendable {-    var actionID: UUID-    var timestamp: Date-    var reason: String-    var previousState: StepPhase-    var previousEventID: UUID?-    var previousTimestamp: Date? = nil-    var previousDose: RecordedDoseSnapshot? = nil+  var actionID: UUID+  var timestamp: Date+  var reason: String+  var previousState: StepPhase+  var previousEventID: UUID?+  var previousTimestamp: Date?+  var previousDose: RecordedDoseSnapshot? }  nonisolated struct StepProgress: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var position: Int-    var targetKind: RoutineStepTargetKind-    var targetID: UUID-    var state: StepPhase = .pending-    var startedAt: Date?-    var completedAt: Date?-    var canonicalEventID: UUID?-    var skipConfirmed: Bool = false-    var reviewedEventIDs: [UUID] = []-    var audit: [StepAudit] = []+  var id: UUID+  var position: Int+  var targetKind: RoutineStepTargetKind+  var targetID: UUID+  var state: StepPhase = .pending+  var startedAt: Date?+  var completedAt: Date?+  var canonicalEventID: UUID?+  var skipConfirmed: Bool = false+  var reviewedEventIDs: [UUID] = []+  var audit: [StepAudit] = [] }  nonisolated extension StepProgress {-    private enum CodingKeys: String, CodingKey { case id, position, targetKind, targetID, state, startedAt, completedAt, canonicalEventID, skipConfirmed, reviewedEventIDs, audit }-    init(from decoder: Decoder) throws {-        let values = try decoder.container(keyedBy: CodingKeys.self)-        id = try values.decode(UUID.self, forKey: .id)-        position = try values.decode(Int.self, forKey: .position)-        targetKind = try values.decode(RoutineStepTargetKind.self, forKey: .targetKind)-        targetID = try values.decode(UUID.self, forKey: .targetID)-        state = try values.decode(StepPhase.self, forKey: .state)-        startedAt = try values.decodeIfPresent(Date.self, forKey: .startedAt)-        completedAt = try values.decodeIfPresent(Date.self, forKey: .completedAt)-        canonicalEventID = try values.decodeIfPresent(UUID.self, forKey: .canonicalEventID)-        skipConfirmed = try values.decodeIfPresent(Bool.self, forKey: .skipConfirmed) ?? false-        reviewedEventIDs = try values.decodeIfPresent([UUID].self, forKey: .reviewedEventIDs) ?? []-        audit = try values.decodeIfPresent([StepAudit].self, forKey: .audit) ?? []-    }+  private enum CodingKeys: String, CodingKey {+    case id, position, targetKind, targetID, state, startedAt, completedAt, canonicalEventID,+      skipConfirmed, reviewedEventIDs, audit+  }+  init(from decoder: Decoder) throws {+    let values = try decoder.container(keyedBy: CodingKeys.self)+    id = try values.decode(UUID.self, forKey: .id)+    position = try values.decode(Int.self, forKey: .position)+    targetKind = try values.decode(RoutineStepTargetKind.self, forKey: .targetKind)+    targetID = try values.decode(UUID.self, forKey: .targetID)+    state = try values.decode(StepPhase.self, forKey: .state)+    startedAt = try values.decodeIfPresent(Date.self, forKey: .startedAt)+    completedAt = try values.decodeIfPresent(Date.self, forKey: .completedAt)+    canonicalEventID = try values.decodeIfPresent(UUID.self, forKey: .canonicalEventID)+    skipConfirmed = try values.decodeIfPresent(Bool.self, forKey: .skipConfirmed) ?? false+    reviewedEventIDs = try values.decodeIfPresent([UUID].self, forKey: .reviewedEventIDs) ?? []+    audit = try values.decodeIfPresent([StepAudit].self, forKey: .audit) ?? []+  } }  nonisolated enum SessionPhase: String, Codable, Sendable {-    case active, paused, completed, finishedWithSkips, endedIncomplete, needsReview+  case active, paused, completed, finishedWithSkips, endedIncomplete, needsReview }  nonisolated struct OrderedCheckpoint: Codable, Equatable, Sendable {-    var steps: [StepProgress]-    var phase: SessionPhase = .active-    var endedAt: Date?+  var steps: [StepProgress]+  var phase: SessionPhase = .active+  var endedAt: Date? -    init(definition: FrozenRoutineDefinition) {-        steps = definition.steps.map { StepProgress(id: $0.id, position: $0.position, targetKind: $0.kind, targetID: $0.targetID) }+  init(definition: FrozenRoutineDefinition) {+    steps = definition.steps.map {+      StepProgress(id: $0.id, position: $0.position, targetKind: $0.kind, targetID: $0.targetID)     }+  } -    var nextReadyStepID: UUID? {-        guard phase == .active else { return nil }-        for step in steps.sorted(by: { $0.position < $1.position }) {-            switch step.state {-            case .completed: continue-            case .skipped: if step.skipConfirmed { continue } else { return nil }-            case .needsReview: return nil-            default: return step.id-            }-        }-        return nil+  var nextReadyStepID: UUID? {+    guard phase == .active else { return nil }+    for step in steps.sorted(by: { $0.position < $1.position }) {+      switch step.state {+      case .completed: continue+      case .skipped: if step.skipConfirmed { continue } else { return nil }+      case .needsReview: return nil+      default: return step.id+      }     }+    return nil+  } -    mutating func markCompleted(stepID: UUID, eventID: UUID, at timestamp: Date, actionID: UUID, reportedOutOfOrder: Bool = false) throws {-        guard let index = steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-        let old = steps[index]-        if old.canonicalEventID == eventID && old.state == .completed { return }-        let ready = nextReadyStepID == stepID-        guard ready || reportedOutOfOrder else { throw ExecutionError.stepNotReady }-        let timeConflict = steps.contains { $0.id != stepID && (($0.position < old.position && ($0.completedAt ?? .distantPast) > timestamp) || ($0.position > old.position && $0.completedAt != nil && ($0.completedAt ?? .distantFuture) < timestamp)) }-        if !ready || timeConflict || (old.canonicalEventID != nil && old.canonicalEventID != eventID) {-            steps[index].reviewedEventIDs = []-            steps[index].state = .needsReview-            phase = .needsReview-            steps[index].audit.append(.init(actionID: actionID, timestamp: timestamp, reason: "Reported action conflicts with saved step order or completion", previousState: old.state, previousEventID: old.canonicalEventID))-        } else { steps[index].state = .completed }-        // Preserve the earlier canonical event when a distinct real action conflicts.-        if steps[index].canonicalEventID == nil { steps[index].canonicalEventID = eventID }-        steps[index].startedAt = steps[index].startedAt ?? timestamp-        steps[index].completedAt = timestamp-        finishTraversalIfReady()+  mutating func markCompleted(+    stepID: UUID, eventID: UUID, at timestamp: Date, actionID: UUID,+    reportedOutOfOrder: Bool = false+  ) throws {+    guard let index = steps.firstIndex(where: { $0.id == stepID }) else {+      throw ExecutionError.unknownStep     }--    mutating func skip(stepID: UUID, actionID: UUID, at timestamp: Date, reason: String) throws {-        guard nextReadyStepID == stepID, let index = steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.stepNotReady }-        let old = steps[index]-        steps[index].audit.append(.init(actionID: actionID, timestamp: timestamp, reason: reason, previousState: old.state, previousEventID: old.canonicalEventID))-        steps[index].state = .skipped; steps[index].skipConfirmed = false+    let old = steps[index]+    if old.canonicalEventID == eventID && old.state == .completed { return }+    let ready = nextReadyStepID == stepID+    guard ready || reportedOutOfOrder else { throw ExecutionError.stepNotReady }+    let timeConflict = steps.contains {+      $0.id != stepID+        && (($0.position < old.position && ($0.completedAt ?? .distantPast) > timestamp)+          || ($0.position > old.position && $0.completedAt != nil+            && ($0.completedAt ?? .distantFuture) < timestamp))     }--    mutating func continueAfterSkip(stepID: UUID) throws {-        guard phase == .active, let index = steps.firstIndex(where: { $0.id == stepID }), steps[index].state == .skipped,-              !steps[index].skipConfirmed else { throw ExecutionError.invalidTransition }-        steps[index].skipConfirmed = true-        finishTraversalIfReady()+    if !ready || timeConflict || (old.canonicalEventID != nil && old.canonicalEventID != eventID) {+      steps[index].reviewedEventIDs = []+      steps[index].state = .needsReview+      phase = .needsReview+      steps[index].audit.append(+        .init(+          actionID: actionID, timestamp: timestamp,+          reason: "Reported action conflicts with saved step order or completion",+          previousState: old.state, previousEventID: old.canonicalEventID))+    } else {+      steps[index].state = .completed     }+    // Preserve the earlier canonical event when a distinct real action conflicts.+    if steps[index].canonicalEventID == nil { steps[index].canonicalEventID = eventID }+    steps[index].startedAt = steps[index].startedAt ?? timestamp+    steps[index].completedAt = timestamp+    finishTraversalIfReady()+  } -    mutating func invalidate(stepID: UUID, audit: StepAudit) throws {-        guard let index = steps.firstIndex(where: { $0.id == stepID }) else { throw ExecutionError.unknownStep }-        steps[index].audit.append(audit)-        steps[index].state = .needsReview-        steps[index].reviewedEventIDs = []-        phase = .needsReview-        // Later actual events stay untouched. This is never a request to repeat medication.+  mutating func skip(stepID: UUID, actionID: UUID, at timestamp: Date, reason: String) throws {+    guard nextReadyStepID == stepID, let index = steps.firstIndex(where: { $0.id == stepID }) else {+      throw ExecutionError.stepNotReady     }+    let old = steps[index]+    steps[index].audit.append(+      .init(+        actionID: actionID, timestamp: timestamp, reason: reason, previousState: old.state,+        previousEventID: old.canonicalEventID))+    steps[index].state = .skipped+    steps[index].skipConfirmed = false+  } -    mutating func resolveReview(stepID: UUID, resolution: ReviewResolution, actionID: UUID, at timestamp: Date, reviewedEventIDs: [UUID] = []) throws {-        guard let index = steps.firstIndex(where: { $0.id == stepID }), steps[index].state == .needsReview else { throw ExecutionError.invalidTransition }-        let old = steps[index]-        steps[index].audit.append(.init(actionID: actionID, timestamp: timestamp, reason: resolution == .acceptCanonical ? "User reviewed and accepted the original log and order conflict" : "User explicitly skipped the unresolved step", previousState: old.state, previousEventID: old.canonicalEventID))-        if resolution == .acceptCanonical { steps[index].state = .completed; steps[index].reviewedEventIDs = reviewedEventIDs }-        else { steps[index].state = .skipped; steps[index].skipConfirmed = false; steps[index].canonicalEventID = nil }-        phase = steps.contains(where: { $0.state == .needsReview }) ? .needsReview : (endedAt != nil ? .endedIncomplete : .active)-        finishTraversalIfReady()-    }+  mutating func continueAfterSkip(stepID: UUID) throws {+    guard phase == .active, let index = steps.firstIndex(where: { $0.id == stepID }),+      steps[index].state == .skipped,+      !steps[index].skipConfirmed+    else { throw ExecutionError.invalidTransition }+    steps[index].skipConfirmed = true+    finishTraversalIfReady()+  } -    mutating func pause() throws {-        guard phase == .active else { throw ExecutionError.invalidTransition }-        phase = .paused-    }-    mutating func resume() throws {-        guard phase == .paused else { throw ExecutionError.invalidTransition }-        phase = .active+  mutating func invalidate(stepID: UUID, audit: StepAudit) throws {+    guard let index = steps.firstIndex(where: { $0.id == stepID }) else {+      throw ExecutionError.unknownStep     }-    mutating func end(at timestamp: Date) throws {-        guard phase != .completed && phase != .finishedWithSkips && phase != .endedIncomplete else { throw ExecutionError.invalidTransition }-        phase = .endedIncomplete; endedAt = timestamp-    }-    mutating func reopen() throws {-        guard phase == .endedIncomplete else { throw ExecutionError.invalidTransition }-        phase = steps.contains(where: { $0.state == .needsReview }) ? .needsReview : .active-        endedAt = nil+    steps[index].audit.append(audit)+    steps[index].state = .needsReview+    steps[index].reviewedEventIDs = []+    phase = .needsReview+    // Later actual events stay untouched. This is never a request to repeat medication.+  }++  mutating func resolveReview(+    stepID: UUID, resolution: ReviewResolution, actionID: UUID, at timestamp: Date,+    reviewedEventIDs: [UUID] = []+  ) throws {+    guard let index = steps.firstIndex(where: { $0.id == stepID }),+      steps[index].state == .needsReview+    else { throw ExecutionError.invalidTransition }+    let old = steps[index]+    steps[index].audit.append(+      .init(+        actionID: actionID, timestamp: timestamp,+        reason: resolution == .acceptCanonical+          ? "User reviewed and accepted the original log and order conflict"+          : "User explicitly skipped the unresolved step", previousState: old.state,+        previousEventID: old.canonicalEventID))+    if resolution == .acceptCanonical {+      steps[index].state = .completed+      steps[index].reviewedEventIDs = reviewedEventIDs+    } else {+      steps[index].state = .skipped+      steps[index].skipConfirmed = false+      steps[index].canonicalEventID = nil     }-    private mutating func finishTraversalIfReady() {-        guard phase == .active, steps.allSatisfy({ $0.state == .completed || ($0.state == .skipped && $0.skipConfirmed) }) else { return }-        phase = steps.contains(where: { $0.state == .skipped }) ? .finishedWithSkips : .completed+    phase =+      steps.contains(where: { $0.state == .needsReview })+      ? .needsReview : (endedAt != nil ? .endedIncomplete : .active)+    finishTraversalIfReady()+  }++  mutating func pause() throws {+    guard phase == .active else { throw ExecutionError.invalidTransition }+    phase = .paused+  }+  mutating func resume() throws {+    guard phase == .paused else { throw ExecutionError.invalidTransition }+    phase = .active+  }+  mutating func end(at timestamp: Date) throws {+    guard phase != .completed && phase != .finishedWithSkips && phase != .endedIncomplete else {+      throw ExecutionError.invalidTransition     }+    phase = .endedIncomplete+    endedAt = timestamp+  }+  mutating func reopen() throws {+    guard phase == .endedIncomplete else { throw ExecutionError.invalidTransition }+    phase = steps.contains(where: { $0.state == .needsReview }) ? .needsReview : .active+    endedAt = nil+  }+  private mutating func finishTraversalIfReady() {+    guard phase == .active,+      steps.allSatisfy({ $0.state == .completed || ($0.state == .skipped && $0.skipConfirmed) })+    else { return }+    phase = steps.contains(where: { $0.state == .skipped }) ? .finishedWithSkips : .completed+  } }  nonisolated enum ReviewResolution: String, Codable, Sendable { case acceptCanonical, skip }
Meddy/Shared/RoutineExecution/TimerOperation.swift Modified
diff --git a/Meddy/Shared/RoutineExecution/TimerOperation.swift b/Meddy/Shared/RoutineExecution/TimerOperation.swiftindex 52b45d3..6ac95d5 100644--- a/Meddy/Shared/RoutineExecution/TimerOperation.swift+++ b/Meddy/Shared/RoutineExecution/TimerOperation.swift@@ -1,12 +1,13 @@ import Foundation  nonisolated enum TimerOperation: String, Codable, Sendable {-    case start, pause, resume, end, reopen, advance+  case start, pause, resume, end, reopen, advance }  nonisolated enum ExecutionClock: Sendable {-    static let continuityID = UUID().uuidString-    static func sample() -> ClockSample {-        ClockSample(wall: Date(), monotonic: ProcessInfo.processInfo.systemUptime, continuityID: continuityID)-    }+  static let continuityID = UUID().uuidString+  static func sample() -> ClockSample {+    ClockSample(+      wall: Date(), monotonic: ProcessInfo.processInfo.systemUptime, continuityID: continuityID)+  } }
Meddy/Shared/Scheduling/AsNeededDoseLimits.swift Modified
diff --git a/Meddy/Shared/Scheduling/AsNeededDoseLimits.swift b/Meddy/Shared/Scheduling/AsNeededDoseLimits.swiftindex 668ec3c..c4e883a 100644--- a/Meddy/Shared/Scheduling/AsNeededDoseLimits.swift+++ b/Meddy/Shared/Scheduling/AsNeededDoseLimits.swift@@ -1,127 +1,189 @@ import Foundation  nonisolated struct AsNeededDoseLimits: Codable, Equatable, Sendable {-    var minimumIntervalSeconds: TimeInterval?-    var maximumAmount: Double?-    var windowSeconds: TimeInterval?-    var unit: String = ""-    var productStrengthAndForm: String = ""-    var activeIngredients: String = ""-    var instructionSource: String = ""-    var historyConfirmedFrom: Date?+  var minimumIntervalSeconds: TimeInterval?+  var maximumAmount: Double?+  var windowSeconds: TimeInterval?+  var unit: String = ""+  var productStrengthAndForm: String = ""+  var activeIngredients: String = ""+  var instructionSource: String = ""+  var historyConfirmedFrom: Date? -    func validate(now: Date) throws {-        func duration(_ value: TimeInterval?) -> Bool { value.map { $0.isFinite && $0 > 0 && $0 <= 366 * 86400 } ?? true }-        guard minimumIntervalSeconds != nil || maximumAmount != nil,-              duration(minimumIntervalSeconds), duration(windowSeconds),-              (maximumAmount == nil) == (windowSeconds == nil),-              maximumAmount.map({ $0.isFinite && $0 > 0 && AsNeededDoseLimitEngine.decimal($0) != nil && !unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) ?? true else { throw AsNeededLimitError.invalidConfiguration }+  func validate(now: Date) throws {+    func duration(_ value: TimeInterval?) -> Bool {+      value.map { $0.isFinite && $0 > 0 && $0 <= 366 * 86400 } ?? true     }-    var lookback: TimeInterval { max(minimumIntervalSeconds ?? 0, windowSeconds ?? 0) }-    var contextKey: String { [unit.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), productStrengthAndForm, activeIngredients].joined(separator: "|") }+    guard minimumIntervalSeconds != nil || maximumAmount != nil,+      duration(minimumIntervalSeconds), duration(windowSeconds),+      (maximumAmount == nil) == (windowSeconds == nil),+      maximumAmount.map({+        $0.isFinite && $0 > 0 && AsNeededDoseLimitEngine.decimal($0) != nil+          && !unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+      }) ?? true+    else { throw AsNeededLimitError.invalidConfiguration }+  }+  var lookback: TimeInterval { max(minimumIntervalSeconds ?? 0, windowSeconds ?? 0) }+  var contextKey: String {+    [+      unit.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), productStrengthAndForm,+      activeIngredients+    ].joined(separator: "|")+  } }  nonisolated enum AsNeededLimitError: Error, LocalizedError, Sendable {-    case invalidConfiguration, unreadableConfiguration-    var errorDescription: String? {-        switch self {-        case .invalidConfiguration: "Enter a positive minimum interval or maximum quantity."-        case .unreadableConfiguration: "Saved limits could not be read. Edit the limits to check another dose."-        }+  case invalidConfiguration, unreadableConfiguration+  var errorDescription: String? {+    switch self {+    case .invalidConfiguration: "Enter a positive minimum interval or maximum quantity."+    case .unreadableConfiguration:+      "Saved limits could not be read. Edit the limits to check another dose."     }+  } }  nonisolated struct DoseLimitAdministration: Codable, Equatable, Sendable {-    var id: UUID-    var medicationID: UUID-    var timestamp: Date-    var dose: RecordedDoseSnapshot-    var isDeleted: Bool = false-    var hasClockMismatch: Bool = false+  var id: UUID+  var medicationID: UUID+  var timestamp: Date+  var dose: RecordedDoseSnapshot+  var isDeleted: Bool = false+  var hasClockMismatch: Bool = false } -nonisolated enum DoseLimitCheckState: String, Codable, Sendable { case notConfigured, needsReview, wait, withinEnteredLimits }+nonisolated enum DoseLimitCheckState: String, Codable, Sendable {+  case notConfigured, needsReview, wait, withinEnteredLimits+}  nonisolated struct DoseLimitCheck: Codable, Equatable, Sendable {-    var state: DoseLimitCheckState-    var evaluatedAt: Date-    var knownAmount: Double? = nil-    var maximumAmount: Double? = nil-    var unit: String = ""-    var windowSeconds: TimeInterval? = nil-    var proposedAmount: Double? = nil-    var earliestFromLoggedDoses: Date? = nil-    var issues: [String] = []-    var remainingAmount: Double? {-        guard let maximum = maximumAmount.flatMap(AsNeededDoseLimitEngine.decimal),-              let known = knownAmount.flatMap(AsNeededDoseLimitEngine.decimal) else { return nil }-        return NSDecimalNumber(decimal: max(Decimal.zero, maximum - known)).doubleValue-    }-    var title: String {-        switch state {-        case .notConfigured: "No dose limits set"-        case .needsReview: "Check logged quantities"-        case .wait: "Wait before another dose"-        case .withinEnteredLimits: "Fits your entered limits"-        }+  var state: DoseLimitCheckState+  var evaluatedAt: Date+  var knownAmount: Double?+  var maximumAmount: Double?+  var unit: String = ""+  var windowSeconds: TimeInterval?+  var proposedAmount: Double?+  var earliestFromLoggedDoses: Date?+  var issues: [String] = []+  var remainingAmount: Double? {+    guard let maximum = maximumAmount.flatMap(AsNeededDoseLimitEngine.decimal),+      let known = knownAmount.flatMap(AsNeededDoseLimitEngine.decimal)+    else { return nil }+    return NSDecimalNumber(decimal: max(Decimal.zero, maximum - known)).doubleValue+  }+  var title: String {+    switch state {+    case .notConfigured: "No dose limits set"+    case .needsReview: "Check logged quantities"+    case .wait: "Wait before another dose"+    case .withinEnteredLimits: "Fits your entered limits"     }+  } }  nonisolated struct AsNeededDoseLimitEngine: Sendable {-    static func decimal(_ value: Double) -> Decimal? {-        guard value.isFinite, let result = Decimal(string: String(value), locale: Locale(identifier: "en_US_POSIX")), !result.isNaN else { return nil }-        return result-    }-    private func unit(_ value: String?) -> String { (value ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }+  static func decimal(_ value: Double) -> Decimal? {+    guard value.isFinite,+      let result = Decimal(string: String(value), locale: Locale(identifier: "en_US_POSIX")),+      !result.isNaN+    else { return nil }+    return result+  }+  private func unit(_ value: String?) -> String {+    (value ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+  } -    func evaluate(medicationID: UUID, limits: AsNeededDoseLimits?, administrations: [DoseLimitAdministration], proposedDose: RecordedDoseSnapshot, now: Date) -> DoseLimitCheck {-        guard let limits else { return .init(state: .notConfigured, evaluatedAt: now) }-        do { try limits.validate(now: now) }-        catch { return .init(state: .needsReview, evaluatedAt: now, issues: [AsNeededLimitError.invalidConfiguration.localizedDescription]) }-        var result = DoseLimitCheck(state: .needsReview, evaluatedAt: now, maximumAmount: limits.maximumAmount, unit: limits.unit, windowSeconds: limits.windowSeconds, proposedAmount: proposedDose.amount.flatMap { $0.isFinite ? $0 : nil })-        func issue(_ text: String) { if !result.issues.contains(text) { result.issues.append(text) } }-        let grouped = Dictionary(grouping: administrations.filter { $0.medicationID == medicationID }, by: \.id)-        var alive: [DoseLimitAdministration] = []-        for group in grouped.values {-            if group.contains(where: \.isDeleted) { continue }-            if group.count > 1 && !group.dropFirst().allSatisfy({ $0 == group.first }) { issue("Conflicting duplicate logs need review.") }-            if let first = group.sorted(by: { $0.timestamp > $1.timestamp }).first { alive.append(first) }+  func evaluate(+    medicationID: UUID, limits: AsNeededDoseLimits?, administrations: [DoseLimitAdministration],+    proposedDose: RecordedDoseSnapshot, now: Date+  ) -> DoseLimitCheck {+    guard let limits else { return .init(state: .notConfigured, evaluatedAt: now) }+    do { try limits.validate(now: now) } catch {+      return .init(+        state: .needsReview, evaluatedAt: now,+        issues: [AsNeededLimitError.invalidConfiguration.localizedDescription])+    }+    var result = DoseLimitCheck(+      state: .needsReview, evaluatedAt: now, maximumAmount: limits.maximumAmount, unit: limits.unit,+      windowSeconds: limits.windowSeconds,+      proposedAmount: proposedDose.amount.flatMap { $0.isFinite ? $0 : nil })+    func issue(_ text: String) { if !result.issues.contains(text) { result.issues.append(text) } }+    let alive = canonicalAdministrations(+      administrations.filter { $0.medicationID == medicationID }, result: &result)+    if alive.contains(where: { $0.hasClockMismatch || $0.timestamp > now }) {+      issue("A relevant recorded clock time needs review.")+    }+    let past = alive.filter { $0.timestamp <= now && !$0.hasClockMismatch }.sorted {+      $0.timestamp < $1.timestamp+    }+    var earliest = now+    if let interval = limits.minimumIntervalSeconds, let latest = past.last {+      earliest = max(earliest, latest.timestamp.addingTimeInterval(interval))+    }+    var doseImpossible = false+    if let maximum = limits.maximumAmount.flatMap(Self.decimal), let window = limits.windowSeconds {+      let windowEvents = past.filter { $0.timestamp > now.addingTimeInterval(-window) }+      var comparable: [(Date, Decimal)] = []+      for event in windowEvents {+        guard let amount = event.dose.amount, amount > 0, let quantity = Self.decimal(amount),+          unit(event.dose.unit) == unit(limits.unit)+        else {+          issue("A logged dose needs a quantity in the same unit.")+          continue         }-        if alive.contains(where: { $0.hasClockMismatch || $0.timestamp > now }) { issue("A relevant recorded clock time needs review.") }-        let past = alive.filter { $0.timestamp <= now && !$0.hasClockMismatch }.sorted { $0.timestamp < $1.timestamp }-        var earliest = now-        if let interval = limits.minimumIntervalSeconds, let latest = past.last { earliest = max(earliest, latest.timestamp.addingTimeInterval(interval)) }-        var doseImpossible = false-        if let maximum = limits.maximumAmount.flatMap(Self.decimal), let window = limits.windowSeconds {-            let windowEvents = past.filter { $0.timestamp > now.addingTimeInterval(-window) }-            var comparable: [(Date, Decimal)] = []-            for event in windowEvents {-                guard let amount = event.dose.amount, amount > 0, let quantity = Self.decimal(amount), unit(event.dose.unit) == unit(limits.unit) else { issue("A logged dose needs a quantity in the same unit."); continue }-                comparable.append((event.timestamp, quantity))-            }-            var total = comparable.reduce(Decimal.zero) { $0 + $1.1 }-            guard !total.isNaN, NSDecimalNumber(decimal: total).doubleValue.isFinite else {-                issue("Recorded amounts are too large to compare reliably.")-                return result+        comparable.append((event.timestamp, quantity))+      }+      var total = comparable.reduce(Decimal.zero) { $0 + $1.1 }+      guard !total.isNaN, NSDecimalNumber(decimal: total).doubleValue.isFinite else {+        issue("Recorded amounts are too large to compare reliably.")+        return result+      }+      result.knownAmount = NSDecimalNumber(decimal: total).doubleValue+      if let amount = proposedDose.amount, amount > 0, let proposed = Self.decimal(amount),+        unit(proposedDose.unit) == unit(limits.unit) {+        if proposed > maximum {+          doseImpossible = true+          issue("This dose is larger than your maximum quantity.")+        } else if (total + proposed).isNaN {+          issue("Recorded amounts are too large to compare reliably.")+          return result+        } else if total + proposed > maximum {+          for (date, quantity) in comparable {+            total -= quantity+            if total + proposed <= maximum {+              earliest = max(earliest, date.addingTimeInterval(window))+              break             }-            result.knownAmount = NSDecimalNumber(decimal: total).doubleValue-            if let amount = proposedDose.amount, amount > 0, let proposed = Self.decimal(amount), unit(proposedDose.unit) == unit(limits.unit) {-                if proposed > maximum { doseImpossible = true; issue("This dose is larger than your maximum quantity.") }-                else if (total + proposed).isNaN {-                    issue("Recorded amounts are too large to compare reliably.")-                    return result-                }-                else if total + proposed > maximum {-                    for (date, quantity) in comparable {-                        total -= quantity-                        if total + proposed <= maximum { earliest = max(earliest, date.addingTimeInterval(window)); break }-                    }-                }-            } else { issue("Enter a quantity per dose in the same unit as your limit.") }+          }         }-        result.earliestFromLoggedDoses = doseImpossible ? nil : earliest-        if doseImpossible || earliest > now { result.state = .wait }-        else { result.state = result.issues.isEmpty ? .withinEnteredLimits : .needsReview }-        return result+      } else {+        issue("Enter a quantity per dose in the same unit as your limit.")+      }+    }+    result.earliestFromLoggedDoses = doseImpossible ? nil : earliest+    if doseImpossible || earliest > now {+      result.state = .wait+    } else {+      result.state = result.issues.isEmpty ? .withinEnteredLimits : .needsReview+    }+    return result+  }++  private func canonicalAdministrations(+    _ administrations: [DoseLimitAdministration], result: inout DoseLimitCheck+  ) -> [DoseLimitAdministration] {+    let grouped = Dictionary(+      grouping: administrations, by: \.id)+    var alive: [DoseLimitAdministration] = []+    for group in grouped.values {+      if group.contains(where: \.isDeleted) { continue }+      if group.count > 1 && !group.dropFirst().allSatisfy({ $0 == group.first }) {+        let text = "Conflicting duplicate logs need review."+        if !result.issues.contains(text) { result.issues.append(text) }+      }+      if let first = group.min(by: { $0.timestamp > $1.timestamp }) { alive.append(first) }     }+    return alive+  } }
Meddy/Shared/Scheduling/MedicationFollowup.swift Modified
diff --git a/Meddy/Shared/Scheduling/MedicationFollowup.swift b/Meddy/Shared/Scheduling/MedicationFollowup.swiftindex 40326f4..3c1c39e 100644--- a/Meddy/Shared/Scheduling/MedicationFollowup.swift+++ b/Meddy/Shared/Scheduling/MedicationFollowup.swift@@ -1,31 +1,38 @@ import Foundation  nonisolated struct MedicationFollowup: Codable, Equatable, Sendable {-    var message: String-    var delaySeconds: TimeInterval-    func validate() throws {-        guard !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,-              delaySeconds.isFinite, delaySeconds > 0, delaySeconds <= 366 * 24 * 3600 else {-            throw MedicationFollowupError.invalidConfiguration-        }+  var message: String+  var delaySeconds: TimeInterval+  func validate() throws {+    guard !message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,+      delaySeconds.isFinite, delaySeconds > 0, delaySeconds <= 366 * 24 * 3600+    else {+      throw MedicationFollowupError.invalidConfiguration     }+  } }  nonisolated enum MedicationFollowupError: LocalizedError {-    case invalidConfiguration-    var errorDescription: String? { "Enter your follow-up message and a positive delay of at most 366 days." }+  case invalidConfiguration+  var errorDescription: String? {+    "Enter your follow-up message and a positive delay of at most 366 days."+  } }  nonisolated struct MedicationFollowupAction: Codable, Equatable, Sendable {-    var eventID: UUID-    var medicationID: UUID-    var takenAt: Date-    var configuration: MedicationFollowup-    var profileID: UUID? = nil-    var requestID: String { (profileID.map { $0 == ProfileIdentity.me ? "" : "meddy.profile.\($0)." } ?? "") + "meddy.followup.\(eventID)" }-    var deliveryAt: Date { takenAt.addingTimeInterval(configuration.delaySeconds) }-    func reminder(name: String) -> PlannedReminder {-        .init(id: requestID, title: "Follow-up · \(name)", body: configuration.message,-              deliveryAt: deliveryAt, payload: .followup(action: self))-    }+  var eventID: UUID+  var medicationID: UUID+  var takenAt: Date+  var configuration: MedicationFollowup+  var profileID: UUID?+  var requestID: String {+    (profileID.map { $0 == ProfileIdentity.me ? "" : "meddy.profile.\($0)." } ?? "")+      + "meddy.followup.\(eventID)"+  }+  var deliveryAt: Date { takenAt.addingTimeInterval(configuration.delaySeconds) }+  func reminder(name: String) -> PlannedReminder {+    .init(+      id: requestID, title: "Follow-up · \(name)", body: configuration.message,+      deliveryAt: deliveryAt, payload: .followup(action: self))+  } }
Meddy/Shared/Scheduling/MedicationScheduleEngine.swift Modified
diff --git a/Meddy/Shared/Scheduling/MedicationScheduleEngine.swift b/Meddy/Shared/Scheduling/MedicationScheduleEngine.swiftindex 650a119..1b2eb5e 100644--- a/Meddy/Shared/Scheduling/MedicationScheduleEngine.swift+++ b/Meddy/Shared/Scheduling/MedicationScheduleEngine.swift@@ -1,51 +1,85 @@ import Foundation  nonisolated struct MedicationScheduleEngine: Sendable {-    func evaluate(_ medication: MedicationScheduleSnapshot, administrations: [ScheduledAdministration], now: Date, calendar: Calendar) -> MedicationScheduleResult {-        guard medication.mode != .asNeeded && medication.mode != .routineManaged,-              let generation = medication.generationID, let startedAt = medication.startedAt else { return .init(next: nil) }-        let eligible = administrations.filter {-            $0.medicationID == medication.id && !$0.isDeleted && !$0.hasClockMismatch && $0.routineRunID == nil-                && $0.mode == medication.mode && $0.generationID == generation && $0.timestamp >= startedAt && $0.timestamp <= now-        }.sorted { $0.timestamp < $1.timestamp }-        let today = eligible.filter { ScheduleCalendar.sameDay($0.timestamp, now, calendar: calendar) }-        let tomorrow = ScheduleCalendar.nextDayStart(now, calendar: calendar)-        switch medication.mode {-        case .asNeeded, .routineManaged: return .init(next: nil)-        case .afterWaking:-            guard let wake = medication.wakeAnchor, let due = WakeTiming.date(wake, minutes: medication.wakeOffsetMinutes, startedAt: startedAt) else { return .init(next: nil) }-            let taken = eligible.filter { $0.wakeEventID == wake.id && $0.timestamp >= wake.timestamp }.count-            return .init(next: taken == 0 ? due : nil, takenToday: taken, remainingToday: max(0, 1 - taken))-        case .spreadThroughDay:-            guard let target = medication.dosesPerDay, target > 0,-                  let startMinute = medication.dayStartMinute, let endMinute = medication.dayEndMinute,-                  let dayStart = ScheduleCalendar.time(startMinute, on: now, calendar: calendar),-                  let dayEnd = ScheduleCalendar.time(endMinute, on: now, calendar: calendar) else { return .init(next: nil) }-            let remaining = max(0, target - today.count)-            guard ScheduleCalendar.minuteOrder(startMinute) < ScheduleCalendar.minuteOrder(endMinute) else {-                return .init(next: nil, takenToday: today.count, remainingToday: remaining, cannotFitInWindow: true)-            }-            if remaining == 0 {-                return .init(next: tomorrow.flatMap { ScheduleCalendar.time(startMinute, on: $0, calendar: calendar) }, takenToday: today.count, remainingToday: 0)-            }-            let next: Date-            if let latest = today.last {-                let spacing = dayEnd.timeIntervalSince(latest.timestamp) / Double(remaining)-                let minimum = TimeInterval(max(0, medication.minimumIntervalMinutes ?? 0)) * 60-                next = max(now, latest.timestamp.addingTimeInterval(max(spacing, minimum)))-            } else { next = max(now, dayStart, startedAt) }-            guard next <= dayEnd else { return .init(next: nil, takenToday: today.count, remainingToday: remaining, cannotFitInWindow: true) }-            return .init(next: next, takenToday: today.count, remainingToday: remaining)-        case .interval:-            guard let minutes = medication.intervalMinutes, minutes > 0 else { return .init(next: nil) }-            if let latest = eligible.last { return .init(next: latest.timestamp.addingTimeInterval(TimeInterval(minutes) * 60), takenToday: today.count) }-            guard let first = medication.firstReminderMinute, let date = ScheduleCalendar.time(first, on: now, calendar: calendar) else { return .init(next: nil) }-            return .init(next: max(now, date, startedAt))-        case .fixedTimes:-            let times = Array(Set(medication.fixedMinutes)).sorted()-            let occurrences = times.compactMap { ScheduleCalendar.time($0, on: now, calendar: calendar) }.filter { $0 >= startedAt }.sorted()-            if today.count < occurrences.count { return .init(next: occurrences[today.count], takenToday: today.count, remainingToday: occurrences.count - today.count) }-            return .init(next: tomorrow.flatMap { day in times.compactMap { ScheduleCalendar.time($0, on: day, calendar: calendar) }.sorted().first }, takenToday: today.count, remainingToday: 0)-        }+  func evaluate(+    _ medication: MedicationScheduleSnapshot, administrations: [ScheduledAdministration], now: Date,+    calendar: Calendar+  ) -> MedicationScheduleResult {+    guard medication.mode != .asNeeded && medication.mode != .routineManaged,+      let generation = medication.generationID, let startedAt = medication.startedAt+    else { return .init(next: nil) }+    let eligible = administrations.filter {+      $0.medicationID == medication.id && !$0.isDeleted && !$0.hasClockMismatch+        && $0.routineRunID == nil+        && $0.mode == medication.mode && $0.generationID == generation && $0.timestamp >= startedAt+        && $0.timestamp <= now+    }.sorted { $0.timestamp < $1.timestamp }+    let today = eligible.filter { ScheduleCalendar.sameDay($0.timestamp, now, calendar: calendar) }+    let tomorrow = ScheduleCalendar.nextDayStart(now, calendar: calendar)+    switch medication.mode {+    case .asNeeded, .routineManaged: return .init(next: nil)+    case .afterWaking:+      guard let wake = medication.wakeAnchor,+        let due = WakeTiming.date(wake, minutes: medication.wakeOffsetMinutes, startedAt: startedAt)+      else { return .init(next: nil) }+      let taken = eligible.filter { $0.wakeEventID == wake.id && $0.timestamp >= wake.timestamp }+        .count+      return .init(+        next: taken == 0 ? due : nil, takenToday: taken, remainingToday: max(0, 1 - taken))+    case .spreadThroughDay:+      guard let target = medication.dosesPerDay, target > 0,+        let startMinute = medication.dayStartMinute, let endMinute = medication.dayEndMinute,+        let dayStart = ScheduleCalendar.time(startMinute, on: now, calendar: calendar),+        let dayEnd = ScheduleCalendar.time(endMinute, on: now, calendar: calendar)+      else { return .init(next: nil) }+      let remaining = max(0, target - today.count)+      guard ScheduleCalendar.minuteOrder(startMinute) < ScheduleCalendar.minuteOrder(endMinute)+      else {+        return .init(+          next: nil, takenToday: today.count, remainingToday: remaining, cannotFitInWindow: true)+      }+      if remaining == 0 {+        return .init(+          next: tomorrow.flatMap { ScheduleCalendar.time(startMinute, on: $0, calendar: calendar) },+          takenToday: today.count, remainingToday: 0)+      }+      let next: Date+      if let latest = today.last {+        let spacing = dayEnd.timeIntervalSince(latest.timestamp) / Double(remaining)+        let minimum = TimeInterval(max(0, medication.minimumIntervalMinutes ?? 0)) * 60+        next = max(now, latest.timestamp.addingTimeInterval(max(spacing, minimum)))+      } else {+        next = max(now, dayStart, startedAt)+      }+      guard next <= dayEnd else {+        return .init(+          next: nil, takenToday: today.count, remainingToday: remaining, cannotFitInWindow: true)+      }+      return .init(next: next, takenToday: today.count, remainingToday: remaining)+    case .interval:+      guard let minutes = medication.intervalMinutes, minutes > 0 else { return .init(next: nil) }+      if let latest = eligible.last {+        return .init(+          next: latest.timestamp.addingTimeInterval(TimeInterval(minutes) * 60),+          takenToday: today.count)+      }+      guard let first = medication.firstReminderMinute,+        let date = ScheduleCalendar.time(first, on: now, calendar: calendar)+      else { return .init(next: nil) }+      return .init(next: max(now, date, startedAt))+    case .fixedTimes:+      let times = Array(Set(medication.fixedMinutes)).sorted()+      let occurrences = times.compactMap { ScheduleCalendar.time($0, on: now, calendar: calendar) }+        .filter { $0 >= startedAt }.sorted()+      if today.count < occurrences.count {+        return .init(+          next: occurrences[today.count], takenToday: today.count,+          remainingToday: occurrences.count - today.count)+      }+      return .init(+        next: tomorrow.flatMap { day in+          times.compactMap { ScheduleCalendar.time($0, on: day, calendar: calendar) }.min()+        }, takenToday: today.count, remainingToday: 0)     }+  } }
Meddy/Shared/Scheduling/NotificationPlanner.swift Modified
diff --git a/Meddy/Shared/Scheduling/NotificationPlanner.swift b/Meddy/Shared/Scheduling/NotificationPlanner.swiftindex 8b5d447..cd6815b 100644--- a/Meddy/Shared/Scheduling/NotificationPlanner.swift+++ b/Meddy/Shared/Scheduling/NotificationPlanner.swift@@ -1,51 +1,98 @@ import Foundation  nonisolated enum ReminderPayload: Codable, Equatable, Sendable {-    case medication(action: AdministrationAction)-    case routine(occurrence: RoutineOccurrence)-    case timer(runID: UUID, roundIndex: Int, revision: Int)-    case followup(action: MedicationFollowupAction)+  case medication(action: AdministrationAction)+  case routine(occurrence: RoutineOccurrence)+  case timer(runID: UUID, roundIndex: Int, revision: Int)+  case followup(action: MedicationFollowupAction) }  nonisolated struct PlannedReminder: Codable, Equatable, Identifiable, Sendable {-    var id: String-    var title: String-    var body: String-    var deliveryAt: Date-    var payload: ReminderPayload-    var wakeEventID: UUID? = nil-    var wakeImmediateUntil: Date? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: String+  var title: String+  var body: String+  var deliveryAt: Date+  var payload: ReminderPayload+  var wakeEventID: UUID?+  var wakeImmediateUntil: Date?+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID?+}++nonisolated struct MedicationReminderDetails: Sendable {+  var name: String+  var dose: RecordedDoseSnapshot+  var reminders: Bool+  var active: Bool }  nonisolated struct NotificationPlanner: Sendable {-    func medication(_ snapshot: MedicationScheduleSnapshot, name: String, dose: RecordedDoseSnapshot, reminders: Bool, active: Bool, administrations: [ScheduledAdministration], now: Date, calendar: Calendar) -> PlannedReminder? {-        guard active, reminders, let generation = snapshot.generationID,-              let next = MedicationScheduleEngine().evaluate(snapshot, administrations: administrations, now: now, calendar: calendar).next else { return nil }-        let eligible = administrations.filter { $0.medicationID == snapshot.id && !$0.isDeleted && !$0.hasClockMismatch && $0.routineRunID == nil && $0.mode == snapshot.mode && $0.generationID == generation && $0.timestamp >= (snapshot.startedAt ?? .distantFuture) && $0.timestamp <= now }-        // Stable while the same administration is due, even when an overdue delivery is moved to now.-        let basis: String-        if snapshot.mode == .afterWaking, let wake = snapshot.wakeAnchor {-            let key = "meddy.wake.medication|\(snapshot.id)|\(generation)|\(wake.id)"-            let action = AdministrationAction(eventID: ScheduleCalendar.identity(key), medicationID: snapshot.id, timestamp: next, source: .notification, dose: dose, scheduleTypeAtRecording: snapshot.mode, scheduleGenerationID: generation, wakeEventID: wake.id)-            return .init(id: key, title: name, body: dose.displayText, deliveryAt: next, payload: .medication(action: action), wakeEventID: wake.id, wakeImmediateUntil: snapshot.wakeOffsetMinutes == 0 ? wake.recordedAt.addingTimeInterval(60) : nil)-        }-        if snapshot.mode == .interval { basis = eligible.max(by: { $0.timestamp < $1.timestamp })?.id.uuidString ?? "initial" }-        else { basis = "\(ScheduleCalendar.localDate(next, calendar: calendar))|\(eligible.filter { ScheduleCalendar.sameDay($0.timestamp, next, calendar: calendar) }.count)" }-        let key = "meddy.medication|\(snapshot.id)|\(generation)|\(basis)"-        let action = AdministrationAction(eventID: ScheduleCalendar.identity(key), medicationID: snapshot.id, timestamp: next, source: .notification, dose: dose, scheduleTypeAtRecording: snapshot.mode, scheduleGenerationID: generation)-        return .init(id: "meddy.medication.\(snapshot.id)", title: name, body: dose.displayText, deliveryAt: max(now.addingTimeInterval(1), next), payload: .medication(action: action))+  func medication(+    _ snapshot: MedicationScheduleSnapshot, details: MedicationReminderDetails,+    administrations: [ScheduledAdministration], now: Date, calendar: Calendar+  ) -> PlannedReminder? {+    guard details.active, details.reminders, let generation = snapshot.generationID,+      let next = MedicationScheduleEngine().evaluate(+        snapshot, administrations: administrations, now: now, calendar: calendar+      ).next+    else { return nil }+    let eligible = administrations.filter {+      $0.medicationID == snapshot.id && !$0.isDeleted && !$0.hasClockMismatch+        && $0.routineRunID == nil && $0.mode == snapshot.mode && $0.generationID == generation+        && $0.timestamp >= (snapshot.startedAt ?? .distantFuture) && $0.timestamp <= now     }--    func routine(name: String, occurrence: RoutineOccurrence, reminders: Bool, now: Date) -> PlannedReminder? {-        guard reminders, occurrence.canRemind, !occurrence.isEarlierUnfinished, let scheduled = occurrence.scheduledAt else { return nil }-        return .init(id: "meddy.routine.\(occurrence.id)", title: name, body: occurrence.label, deliveryAt: occurrence.wakeEventID == nil ? max(now.addingTimeInterval(1), scheduled) : scheduled, payload: .routine(occurrence: occurrence), wakeEventID: occurrence.wakeEventID, wakeImmediateUntil: occurrence.wakeImmediateUntil)+    // Stable while the same administration is due, even when an overdue delivery is moved to now.+    let basis: String+    if snapshot.mode == .afterWaking, let wake = snapshot.wakeAnchor {+      let key = "meddy.wake.medication|\(snapshot.id)|\(generation)|\(wake.id)"+      let action = AdministrationAction(+        eventID: ScheduleCalendar.identity(key), medicationID: snapshot.id, timestamp: next,+        source: .notification, dose: details.dose, scheduleTypeAtRecording: snapshot.mode,+        scheduleGenerationID: generation, wakeEventID: wake.id)+      return .init(+        id: key, title: details.name, body: details.dose.displayText, deliveryAt: next,+        payload: .medication(action: action), wakeEventID: wake.id,+        wakeImmediateUntil: snapshot.wakeOffsetMinutes == 0+          ? wake.recordedAt.addingTimeInterval(60) : nil)     }+    if snapshot.mode == .interval {+      basis = eligible.max(by: { $0.timestamp < $1.timestamp })?.id.uuidString ?? "initial"+    } else {+      basis =+        "\(ScheduleCalendar.localDate(next, calendar: calendar))|\(eligible.filter { ScheduleCalendar.sameDay($0.timestamp, next, calendar: calendar) }.count)"+    }+    let key = "meddy.medication|\(snapshot.id)|\(generation)|\(basis)"+    let action = AdministrationAction(+      eventID: ScheduleCalendar.identity(key), medicationID: snapshot.id, timestamp: next,+      source: .notification, dose: details.dose, scheduleTypeAtRecording: snapshot.mode,+      scheduleGenerationID: generation)+    return .init(+      id: "meddy.medication.\(snapshot.id)", title: details.name, body: details.dose.displayText,+      deliveryAt: max(now.addingTimeInterval(1), next), payload: .medication(action: action))+  }++  func routine(name: String, occurrence: RoutineOccurrence, reminders: Bool, now: Date)+    -> PlannedReminder? {+    guard reminders, occurrence.canRemind, !occurrence.isEarlierUnfinished,+      let scheduled = occurrence.scheduledAt+    else { return nil }+    return .init(+      id: "meddy.routine.\(occurrence.id)", title: name, body: occurrence.label,+      deliveryAt: occurrence.wakeEventID == nil+        ? max(now.addingTimeInterval(1), scheduled) : scheduled,+      payload: .routine(occurrence: occurrence), wakeEventID: occurrence.wakeEventID,+      wakeImmediateUntil: occurrence.wakeImmediateUntil)+  } -    func timer(name: String, runID: UUID, revision: Int, checkpoint: TimerCheckpoint, now: Date) -> PlannedReminder? {-        guard checkpoint.phase == .running, let deadline = checkpoint.deadline, deadline > now else { return nil }-        return .init(id: "meddy.timer.\(runID)", title: name, body: "Round complete. Open Meddy to continue.", deliveryAt: deadline, payload: .timer(runID: runID, roundIndex: checkpoint.roundIndex, revision: revision))+  func timer(name: String, runID: UUID, revision: Int, checkpoint: TimerCheckpoint, now: Date)+    -> PlannedReminder? {+    guard checkpoint.phase == .running, let deadline = checkpoint.deadline, deadline > now else {+      return nil     }+    return .init(+      id: "meddy.timer.\(runID)", title: name, body: "Round complete. Open Meddy to continue.",+      deliveryAt: deadline,+      payload: .timer(runID: runID, roundIndex: checkpoint.roundIndex, revision: revision))+  } }
Meddy/Shared/Scheduling/RoutineScheduleEngine.swift Modified
diff --git a/Meddy/Shared/Scheduling/RoutineScheduleEngine.swift b/Meddy/Shared/Scheduling/RoutineScheduleEngine.swiftindex d849b5f..a4dd609 100644--- a/Meddy/Shared/Scheduling/RoutineScheduleEngine.swift+++ b/Meddy/Shared/Scheduling/RoutineScheduleEngine.swift@@ -1,57 +1,116 @@ import Foundation  nonisolated struct RoutineScheduleEngine: Sendable {-    func occurrences(_ schedule: RoutineScheduleSnapshot, runs: [ScheduledRunSnapshot], day: Date, now: Date, calendar: Calendar) -> [RoutineOccurrence] {-        let localDate = ScheduleCalendar.localDate(day, calendar: calendar)-        let start = ScheduleCalendar.dayStart(day, calendar: calendar)-        let configuration: RoutineScheduleConfiguration?-        if let pending = schedule.pending {-            let effective = ScheduleCalendar.activationDate(pending, calendar: calendar)-            if start >= effective || (ScheduleCalendar.sameDay(day, now, calendar: calendar) && now >= effective) {-                var next = pending.configuration; next.startedAt = effective; configuration = next-            } else { configuration = schedule.current }-        } else { configuration = schedule.current }-        var result: [RoutineOccurrence] = []-        if schedule.isActive, let configuration {-            for (index, slot) in configuration.slots.enumerated() {-                if let minutes = slot.wakeOffsetMinutes {-                    for wake in schedule.wakeAnchors ?? schedule.wakeAnchor.map({ [$0] }) ?? [] {-                        guard let date = WakeTiming.date(wake, minutes: minutes, startedAt: configuration.startedAt) else { continue }-                        let inRequestedDay = date >= start && date < (ScheduleCalendar.nextDayStart(day, calendar: calendar) ?? .distantFuture)-                        guard wake.localDate == localDate || inRequestedDay else { continue }-                        let key = "\(schedule.routineID)|\(configuration.generationID)|\(slot.id)|wake@\(wake.id)"-                        let existing = runs.first { $0.routineID == schedule.routineID && $0.occurrenceKey == key }-                        result.append(.init(id: existing?.id ?? ScheduleCalendar.identity(key), key: key, routineID: schedule.routineID, generationID: configuration.generationID, slotID: slot.id, label: slot.label.isEmpty ? "After waking" : slot.label, localDate: wake.localDate, timeZoneID: wake.timeZoneID, scheduledAt: existing?.scheduledAt ?? date, existingRunID: existing?.id, status: existing?.status, wakeEventID: wake.id, wakeImmediateUntil: minutes == 0 ? wake.recordedAt.addingTimeInterval(60) : nil))-                    }-                    continue-                }-                let key = "\(schedule.routineID.uuidString)|\(configuration.generationID.uuidString)|\(slot.id.uuidString)|day02@\(localDate)"-                let existing = runs.first { $0.routineID == schedule.routineID && $0.slotID == slot.id && ScheduleCalendar.runDate($0, calendar: calendar) == localDate }-                let date = slot.minuteOfDay.flatMap { ScheduleCalendar.time($0, on: day, calendar: calendar) }-                if existing == nil {-                    if ScheduleCalendar.dayStart(day, calendar: calendar) < ScheduleCalendar.dayStart(configuration.startedAt, calendar: calendar) { continue }-                    if let date, date < configuration.startedAt { continue }-                }-                let storedDate: Date?-                if let existing { storedDate = existing.scheduledAt } else { storedDate = date }-                let storedKey = existing?.occurrenceKey ?? key-                let storedGeneration = storedKey.split(separator: "|").dropFirst().first.flatMap { UUID(uuidString: String($0)) } ?? configuration.generationID-                result.append(.init(id: existing?.id ?? ScheduleCalendar.identity(key), key: storedKey, routineID: schedule.routineID, generationID: storedGeneration, slotID: slot.id, label: slot.label.isEmpty ? "Session \(index + 1)" : slot.label, localDate: existing.flatMap { ScheduleCalendar.runDate($0, calendar: calendar) } ?? localDate, timeZoneID: existing?.timeZoneID ?? calendar.timeZone.identifier, scheduledAt: storedDate, existingRunID: existing?.id, status: existing?.isDeleted == true ? .endedIncomplete : existing?.status))+  func occurrences(+    _ schedule: RoutineScheduleSnapshot, runs: [ScheduledRunSnapshot], day: Date, now: Date,+    calendar: Calendar+  ) -> [RoutineOccurrence] {+    let localDate = ScheduleCalendar.localDate(day, calendar: calendar)+    let start = ScheduleCalendar.dayStart(day, calendar: calendar)+    let configuration: RoutineScheduleConfiguration?+    if let pending = schedule.pending {+      let effective = ScheduleCalendar.activationDate(pending, calendar: calendar)+      if start >= effective+        || (ScheduleCalendar.sameDay(day, now, calendar: calendar) && now >= effective) {+        var next = pending.configuration+        next.startedAt = effective+        configuration = next+      } else {+        configuration = schedule.current+      }+    } else {+      configuration = schedule.current+    }+    var result: [RoutineOccurrence] = []+    if schedule.isActive, let configuration {+      for (index, slot) in configuration.slots.enumerated() {+        if let minutes = slot.wakeOffsetMinutes {+          for wake in schedule.wakeAnchors ?? schedule.wakeAnchor.map({ [$0] }) ?? [] {+            guard+              let date = WakeTiming.date(wake, minutes: minutes, startedAt: configuration.startedAt)+            else { continue }+            let inRequestedDay =+              date >= start+              && date < (ScheduleCalendar.nextDayStart(day, calendar: calendar) ?? .distantFuture)+            guard wake.localDate == localDate || inRequestedDay else { continue }+            let key =+              "\(schedule.routineID)|\(configuration.generationID)|\(slot.id)|wake@\(wake.id)"+            let existing = runs.first {+              $0.routineID == schedule.routineID && $0.occurrenceKey == key             }+            result.append(+              .init(+                id: existing?.id ?? ScheduleCalendar.identity(key), key: key,+                routineID: schedule.routineID, generationID: configuration.generationID,+                slotID: slot.id, label: slot.label.isEmpty ? "After waking" : slot.label,+                localDate: wake.localDate, timeZoneID: wake.timeZoneID,+                scheduledAt: existing?.scheduledAt ?? date, existingRunID: existing?.id,+                status: existing?.status, wakeEventID: wake.id,+                wakeImmediateUntil: minutes == 0 ? wake.recordedAt.addingTimeInterval(60) : nil))+          }+          continue+        }+        let key =+          "\(schedule.routineID.uuidString)|\(configuration.generationID.uuidString)|\(slot.id.uuidString)|day02@\(localDate)"+        let existing = runs.first {+          $0.routineID == schedule.routineID && $0.slotID == slot.id+            && ScheduleCalendar.runDate($0, calendar: calendar) == localDate         }-        // Saved sessions retain their original slot/date/zone, including after archive or travel.-        for run in runs where !run.isDeleted && run.routineID == schedule.routineID && !result.contains(where: { $0.existingRunID == run.id }) {-            guard let key = run.occurrenceKey, let slotID = run.slotID, let date = ScheduleCalendar.runDate(run, calendar: calendar),-                  [.active, .paused, .needsReview].contains(run.status) else { continue }-            let pieces = key.split(separator: "|")-            guard pieces.count == 4, let generation = UUID(uuidString: String(pieces[1])) else { continue }-            result.append(.init(id: run.id, key: key, routineID: schedule.routineID, generationID: generation, slotID: slotID, label: "Saved session", localDate: date, timeZoneID: run.timeZoneID ?? calendar.timeZone.identifier, scheduledAt: run.scheduledAt, existingRunID: run.id, status: run.status, isEarlierUnfinished: date != localDate))+        let date = slot.minuteOfDay.flatMap {+          ScheduleCalendar.time($0, on: day, calendar: calendar)         }-        return result+        if existing == nil {+          if ScheduleCalendar.dayStart(day, calendar: calendar)+            < ScheduleCalendar.dayStart(configuration.startedAt, calendar: calendar) {+            continue+          }+          if let date, date < configuration.startedAt { continue }+        }+        let storedDate: Date?+        if let existing { storedDate = existing.scheduledAt } else { storedDate = date }+        let storedKey = existing?.occurrenceKey ?? key+        let storedGeneration =+          storedKey.split(separator: "|").dropFirst().first.flatMap { UUID(uuidString: String($0)) }+          ?? configuration.generationID+        result.append(+          .init(+            id: existing?.id ?? ScheduleCalendar.identity(key), key: storedKey,+            routineID: schedule.routineID, generationID: storedGeneration, slotID: slot.id,+            label: slot.label.isEmpty ? "Session \(index + 1)" : slot.label,+            localDate: existing.flatMap { ScheduleCalendar.runDate($0, calendar: calendar) }+              ?? localDate, timeZoneID: existing?.timeZoneID ?? calendar.timeZone.identifier,+            scheduledAt: storedDate, existingRunID: existing?.id,+            status: existing?.isDeleted == true ? .endedIncomplete : existing?.status))+      }+    }+    // Saved sessions retain their original slot/date/zone, including after archive or travel.+    for run in runs+    where !run.isDeleted && run.routineID == schedule.routineID+      && !result.contains(where: { $0.existingRunID == run.id }) {+      guard let key = run.occurrenceKey, let slotID = run.slotID,+        let date = ScheduleCalendar.runDate(run, calendar: calendar),+        [.active, .paused, .needsReview].contains(run.status)+      else { continue }+      let pieces = key.split(separator: "|")+      guard pieces.count == 4, let generation = UUID(uuidString: String(pieces[1])) else {+        continue+      }+      result.append(+        .init(+          id: run.id, key: key, routineID: schedule.routineID, generationID: generation,+          slotID: slotID, label: "Saved session", localDate: date,+          timeZoneID: run.timeZoneID ?? calendar.timeZone.identifier, scheduledAt: run.scheduledAt,+          existingRunID: run.id, status: run.status, isEarlierUnfinished: date != localDate))     }+    return result+  } -    func nextReminder(_ schedule: RoutineScheduleSnapshot, occurrences: [RoutineOccurrence], now: Date) -> RoutineOccurrence? {-        guard schedule.isActive && schedule.remindersEnabled else { return nil }-        return occurrences.filter { $0.canRemind && !$0.isEarlierUnfinished }.sorted { ($0.scheduledAt ?? .distantFuture) < ($1.scheduledAt ?? .distantFuture) }.first+  func nextReminder(+    _ schedule: RoutineScheduleSnapshot, occurrences: [RoutineOccurrence], now: Date+  ) -> RoutineOccurrence? {+    guard schedule.isActive && schedule.remindersEnabled else { return nil }+    return occurrences.filter { $0.canRemind && !$0.isEarlierUnfinished }.min {+      ($0.scheduledAt ?? .distantFuture) < ($1.scheduledAt ?? .distantFuture)     }+  } }
Meddy/Shared/Scheduling/ScheduleValues.swift Modified
diff --git a/Meddy/Shared/Scheduling/ScheduleValues.swift b/Meddy/Shared/Scheduling/ScheduleValues.swiftindex c85667f..18a81c6 100644--- a/Meddy/Shared/Scheduling/ScheduleValues.swift+++ b/Meddy/Shared/Scheduling/ScheduleValues.swift@@ -1,171 +1,186 @@-import Foundation import CryptoKit+import Foundation  nonisolated struct MedicationScheduleSnapshot: Codable, Equatable, Sendable {-    var id: UUID-    var mode: MedicationScheduleType-    var generationID: UUID?-    var startedAt: Date?-    var dosesPerDay: Int? = nil-    var dayStartMinute: Int? = nil-    var dayEndMinute: Int? = nil-    var minimumIntervalMinutes: Int? = nil-    var intervalMinutes: Int? = nil-    var firstReminderMinute: Int? = nil-    var fixedMinutes: [Int] = []-    var wakeOffsetMinutes: Int? = nil-    var wakeAnchor: WakeAnchor? = nil-    var wakeAnchors: [WakeAnchor]? = nil+  var id: UUID+  var mode: MedicationScheduleType+  var generationID: UUID?+  var startedAt: Date?+  var dosesPerDay: Int?+  var dayStartMinute: Int?+  var dayEndMinute: Int?+  var minimumIntervalMinutes: Int?+  var intervalMinutes: Int?+  var firstReminderMinute: Int?+  var fixedMinutes: [Int] = []+  var wakeOffsetMinutes: Int?+  var wakeAnchor: WakeAnchor?+  var wakeAnchors: [WakeAnchor]? }  nonisolated struct ScheduledAdministration: Codable, Sendable {-    var id: UUID-    var medicationID: UUID-    var timestamp: Date-    var mode: MedicationScheduleType-    var generationID: UUID?-    var routineRunID: UUID? = nil-    var isDeleted: Bool = false-    var hasClockMismatch: Bool = false-    var wakeEventID: UUID? = nil+  var id: UUID+  var medicationID: UUID+  var timestamp: Date+  var mode: MedicationScheduleType+  var generationID: UUID?+  var routineRunID: UUID?+  var isDeleted: Bool = false+  var hasClockMismatch: Bool = false+  var wakeEventID: UUID? }  nonisolated struct MedicationScheduleResult: Equatable, Sendable {-    var next: Date?-    var takenToday: Int = 0-    var remainingToday: Int? = nil-    var cannotFitInWindow: Bool = false+  var next: Date?+  var takenToday: Int = 0+  var remainingToday: Int?+  var cannotFitInWindow: Bool = false }  nonisolated struct DailyRoutineSlot: Codable, Equatable, Identifiable, Sendable {-    var id: UUID = UUID()-    var label: String = ""-    var minuteOfDay: Int? = nil-    var wakeOffsetMinutes: Int? = nil+  var id: UUID = UUID()+  var label: String = ""+  var minuteOfDay: Int?+  var wakeOffsetMinutes: Int? }  nonisolated struct RoutineScheduleConfiguration: Codable, Equatable, Sendable {-    var generationID: UUID-    var startedAt: Date-    var slots: [DailyRoutineSlot]+  var generationID: UUID+  var startedAt: Date+  var slots: [DailyRoutineSlot] }  nonisolated struct PendingRoutineSchedule: Codable, Equatable, Sendable {-    var configuration: RoutineScheduleConfiguration-    var effectiveAt: Date-    var timeZoneID: String+  var configuration: RoutineScheduleConfiguration+  var effectiveAt: Date+  var timeZoneID: String }  nonisolated struct RoutineScheduleSnapshot: Codable, Equatable, Sendable {-    var routineID: UUID-    var current: RoutineScheduleConfiguration?-    var pending: PendingRoutineSchedule? = nil-    var isActive: Bool = true-    var remindersEnabled: Bool = false-    var wakeAnchor: WakeAnchor? = nil-    var wakeAnchors: [WakeAnchor]? = nil+  var routineID: UUID+  var current: RoutineScheduleConfiguration?+  var pending: PendingRoutineSchedule?+  var isActive: Bool = true+  var remindersEnabled: Bool = false+  var wakeAnchor: WakeAnchor?+  var wakeAnchors: [WakeAnchor]? }  nonisolated struct ScheduledRunSnapshot: Codable, Sendable {-    var id: UUID-    var routineID: UUID-    var occurrenceKey: String?-    var slotID: UUID?-    var localDate: String?-    var startedAt: Date? = nil-    var timeZoneID: String?-    var scheduledAt: Date?-    var status: SessionPhase-    var isDeleted: Bool = false+  var id: UUID+  var routineID: UUID+  var occurrenceKey: String?+  var slotID: UUID?+  var localDate: String?+  var startedAt: Date?+  var timeZoneID: String?+  var scheduledAt: Date?+  var status: SessionPhase+  var isDeleted: Bool = false }  nonisolated struct RoutineOccurrence: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var key: String-    var routineID: UUID-    var generationID: UUID-    var slotID: UUID-    var label: String-    var localDate: String-    var timeZoneID: String-    var scheduledAt: Date?-    var existingRunID: UUID?-    var status: SessionPhase?-    var isEarlierUnfinished: Bool = false-    var wakeEventID: UUID? = nil-    var wakeImmediateUntil: Date? = nil+  var id: UUID+  var key: String+  var routineID: UUID+  var generationID: UUID+  var slotID: UUID+  var label: String+  var localDate: String+  var timeZoneID: String+  var scheduledAt: Date?+  var existingRunID: UUID?+  var status: SessionPhase?+  var isEarlierUnfinished: Bool = false+  var wakeEventID: UUID?+  var wakeImmediateUntil: Date? -    var canRemind: Bool { scheduledAt != nil && existingRunID == nil }+  var canRemind: Bool { scheduledAt != nil && existingRunID == nil } }  nonisolated enum ScheduleCalendar: Sendable {-    static let dayBoundaryMinute = 120+  static let dayBoundaryMinute = 120 -    // Use wall-clock components, not a two-hour elapsed-time subtraction across DST.-    static func dayDate(_ instant: Date, calendar: Calendar) -> Date {-        let civil = calendar.startOfDay(for: instant)-        return calendar.component(.hour, from: instant) < 2-            ? (calendar.date(byAdding: .day, value: -1, to: civil) ?? civil) : civil-    }-    static func dayStart(_ instant: Date, calendar: Calendar) -> Date {-        civilTime(dayBoundaryMinute, on: dayDate(instant, calendar: calendar), calendar: calendar) ?? calendar.startOfDay(for: instant)-    }-    static func nextDayStart(_ instant: Date, calendar: Calendar) -> Date? {-        calendar.date(byAdding: .day, value: 1, to: dayDate(instant, calendar: calendar))-            .flatMap { civilTime(dayBoundaryMinute, on: $0, calendar: calendar) }-    }-    static func activationDate(_ pending: PendingRoutineSchedule, calendar: Calendar) -> Date {-        var saved = calendar-        if let zone = TimeZone(identifier: pending.timeZoneID) { saved.timeZone = zone }-        // Pending schedules created by the earlier midnight policy take effect at the-        // new boundary on that civil date; actual event timestamps are never changed.-        if saved.component(.hour, from: pending.effectiveAt) == 0,-           saved.component(.minute, from: pending.effectiveAt) == 0 {-            return civilTime(dayBoundaryMinute, on: pending.effectiveAt, calendar: saved) ?? pending.effectiveAt-        }-        return pending.effectiveAt-    }-    static func sameDay(_ left: Date, _ right: Date, calendar: Calendar) -> Bool {-        calendar.isDate(dayDate(left, calendar: calendar), inSameDayAs: dayDate(right, calendar: calendar))-    }-    static func minuteOrder(_ minute: Int) -> Int { (minute + 1440 - dayBoundaryMinute) % 1440 }-    static func time(_ minute: Int, on day: Date, calendar: Calendar) -> Date? {-        guard (0..<1440).contains(minute) else { return nil }-        var civil = dayDate(day, calendar: calendar)-        if minute < dayBoundaryMinute {-            guard let following = calendar.date(byAdding: .day, value: 1, to: civil) else { return nil }-            civil = following-        }-        return civilTime(minute, on: civil, calendar: calendar)-    }-    private static func civilTime(_ minute: Int, on civil: Date, calendar: Calendar) -> Date? {-        let start = calendar.startOfDay(for: civil)-        let components = DateComponents(hour: minute / 60, minute: minute % 60, second: 0)-        guard let date = calendar.nextDate(after: start.addingTimeInterval(-1), matching: components,-            matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward),-            calendar.isDate(date, inSameDayAs: civil) else { return nil }-        return date-    }-    static func localDate(_ instant: Date, calendar: Calendar) -> String {-        civilDate(dayDate(instant, calendar: calendar), calendar: calendar)+  // Use wall-clock components, not a two-hour elapsed-time subtraction across DST.+  static func dayDate(_ instant: Date, calendar: Calendar) -> Date {+    let civil = calendar.startOfDay(for: instant)+    return calendar.component(.hour, from: instant) < 2+      ? (calendar.date(byAdding: .day, value: -1, to: civil) ?? civil) : civil+  }+  static func dayStart(_ instant: Date, calendar: Calendar) -> Date {+    civilTime(dayBoundaryMinute, on: dayDate(instant, calendar: calendar), calendar: calendar)+      ?? calendar.startOfDay(for: instant)+  }+  static func nextDayStart(_ instant: Date, calendar: Calendar) -> Date? {+    calendar.date(byAdding: .day, value: 1, to: dayDate(instant, calendar: calendar))+      .flatMap { civilTime(dayBoundaryMinute, on: $0, calendar: calendar) }+  }+  static func activationDate(_ pending: PendingRoutineSchedule, calendar: Calendar) -> Date {+    var saved = calendar+    if let zone = TimeZone(identifier: pending.timeZoneID) { saved.timeZone = zone }+    // Pending schedules created by the earlier midnight policy take effect at the+    // new boundary on that civil date; actual event timestamps are never changed.+    if saved.component(.hour, from: pending.effectiveAt) == 0,+      saved.component(.minute, from: pending.effectiveAt) == 0 {+      return civilTime(dayBoundaryMinute, on: pending.effectiveAt, calendar: saved)+        ?? pending.effectiveAt     }-    static func civilDate(_ instant: Date, calendar: Calendar) -> String {-        let parts = calendar.dateComponents([.year, .month, .day], from: instant)-        return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)+    return pending.effectiveAt+  }+  static func sameDay(_ left: Date, _ right: Date, calendar: Calendar) -> Bool {+    calendar.isDate(+      dayDate(left, calendar: calendar), inSameDayAs: dayDate(right, calendar: calendar))+  }+  static func minuteOrder(_ minute: Int) -> Int { (minute + 1440 - dayBoundaryMinute) % 1440 }+  static func time(_ minute: Int, on day: Date, calendar: Calendar) -> Date? {+    guard (0..<1440).contains(minute) else { return nil }+    var civil = dayDate(day, calendar: calendar)+    if minute < dayBoundaryMinute {+      guard let following = calendar.date(byAdding: .day, value: 1, to: civil) else { return nil }+      civil = following     }-    static func runDate(_ run: ScheduledRunSnapshot, calendar: Calendar) -> String? {-        guard let stored = run.localDate else { return nil }-        var savedCalendar = calendar-        if let zone = run.timeZoneID.flatMap(TimeZone.init(identifier:)) { savedCalendar.timeZone = zone }-        // Only reinterpret legacy early-hour civil labels; never rewrite the saved identity.-        if let stamp = run.scheduledAt ?? run.startedAt, stored == civilDate(stamp, calendar: savedCalendar),-           savedCalendar.component(.hour, from: stamp) < 2 { return localDate(stamp, calendar: savedCalendar) }-        return stored+    return civilTime(minute, on: civil, calendar: calendar)+  }+  private static func civilTime(_ minute: Int, on civil: Date, calendar: Calendar) -> Date? {+    let start = calendar.startOfDay(for: civil)+    let components = DateComponents(hour: minute / 60, minute: minute % 60, second: 0)+    guard+      let date = calendar.nextDate(+        after: start.addingTimeInterval(-1), matching: components,+        matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .forward),+      calendar.isDate(date, inSameDayAs: civil)+    else { return nil }+    return date+  }+  static func localDate(_ instant: Date, calendar: Calendar) -> String {+    civilDate(dayDate(instant, calendar: calendar), calendar: calendar)+  }+  static func civilDate(_ instant: Date, calendar: Calendar) -> String {+    let parts = calendar.dateComponents([.year, .month, .day], from: instant)+    return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)+  }+  static func runDate(_ run: ScheduledRunSnapshot, calendar: Calendar) -> String? {+    guard let stored = run.localDate else { return nil }+    var savedCalendar = calendar+    if let zone = run.timeZoneID.flatMap(TimeZone.init(identifier:)) {+      savedCalendar.timeZone = zone     }-    static func identity(_ key: String) -> UUID {-        var bytes = Array(SHA256.hash(data: Data(key.utf8)).prefix(16))-        bytes[6] = (bytes[6] & 0x0f) | 0x50-        bytes[8] = (bytes[8] & 0x3f) | 0x80-        return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))+    // Only reinterpret legacy early-hour civil labels; never rewrite the saved identity.+    if let stamp = run.scheduledAt ?? run.startedAt,+      stored == civilDate(stamp, calendar: savedCalendar),+      savedCalendar.component(.hour, from: stamp) < 2 {+      return localDate(stamp, calendar: savedCalendar)     }+    return stored+  }+  static func identity(_ key: String) -> UUID {+    var bytes = Array(SHA256.hash(data: Data(key.utf8)).prefix(16))+    bytes[6] = (bytes[6] & 0x0f) | 0x50+    bytes[8] = (bytes[8] & 0x3f) | 0x80+    return UUID(+      uuid: (+        bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8],+        bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]+      ))+  } }
Meddy/Shared/Scheduling/TimingCue.swift Modified
diff --git a/Meddy/Shared/Scheduling/TimingCue.swift b/Meddy/Shared/Scheduling/TimingCue.swiftindex 3031450..d786604 100644--- a/Meddy/Shared/Scheduling/TimingCue.swift+++ b/Meddy/Shared/Scheduling/TimingCue.swift@@ -1,14 +1,22 @@ import Foundation  nonisolated enum TimingCue: String, CaseIterable, Sendable {-    case beforeSleeping = "Before sleeping"+  case beforeSleeping = "Before sleeping" -    func adding(to requirements: String) -> String {-        let lines = requirements.components(separatedBy: .newlines)-        guard !lines.contains(where: { $0.trimmingCharacters(in: .whitespaces).localizedCaseInsensitiveCompare(rawValue) == .orderedSame }) else { return requirements }-        return requirements.isEmpty ? rawValue : requirements + (requirements.hasSuffix("\n") ? "" : "\n") + rawValue-    }-    func applying(to slot: inout DailyRoutineSlot) {-        slot.label = rawValue; slot.minuteOfDay = nil; slot.wakeOffsetMinutes = nil-    }+  func adding(to requirements: String) -> String {+    let lines = requirements.components(separatedBy: .newlines)+    guard+      !lines.contains(where: {+        $0.trimmingCharacters(in: .whitespaces).localizedCaseInsensitiveCompare(rawValue)+          == .orderedSame+      })+    else { return requirements }+    return requirements.isEmpty+      ? rawValue : requirements + (requirements.hasSuffix("\n") ? "" : "\n") + rawValue+  }+  func applying(to slot: inout DailyRoutineSlot) {+    slot.label = rawValue+    slot.minuteOfDay = nil+    slot.wakeOffsetMinutes = nil+  } }
Meddy/Shared/Scheduling/WakeAnchor.swift Modified
diff --git a/Meddy/Shared/Scheduling/WakeAnchor.swift b/Meddy/Shared/Scheduling/WakeAnchor.swiftindex bda276f..0cbc901 100644--- a/Meddy/Shared/Scheduling/WakeAnchor.swift+++ b/Meddy/Shared/Scheduling/WakeAnchor.swift@@ -1,21 +1,23 @@ import Foundation  nonisolated struct WakeAnchor: Codable, Equatable, Sendable {-    var id: UUID-    var timestamp: Date-    var recordedAt: Date-    var localDate: String-    var timeZoneID: String-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: UUID+  var timestamp: Date+  var recordedAt: Date+  var localDate: String+  var timeZoneID: String+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated enum WakeTiming {-    // A UI range for one daily cue, not a clinical interval recommendation.-    static func valid(_ minutes: Int) -> Bool { (0...1440).contains(minutes) }-    static func date(_ wake: WakeAnchor?, minutes: Int?, startedAt: Date?) -> Date? {-        guard let wake, let minutes, valid(minutes), let startedAt, wake.timestamp >= startedAt else { return nil }-        return wake.timestamp.addingTimeInterval(Double(minutes) * 60)+  // A UI range for one daily cue, not a clinical interval recommendation.+  static func valid(_ minutes: Int) -> Bool { (0...1440).contains(minutes) }+  static func date(_ wake: WakeAnchor?, minutes: Int?, startedAt: Date?) -> Date? {+    guard let wake, let minutes, valid(minutes), let startedAt, wake.timestamp >= startedAt else {+      return nil     }+    return wake.timestamp.addingTimeInterval(Double(minutes) * 60)+  } }
Meddy/Shared/Snapshots/DefinitionEnums.swift Modified
diff --git a/Meddy/Shared/Snapshots/DefinitionEnums.swift b/Meddy/Shared/Snapshots/DefinitionEnums.swiftindex e1e42e1..6fa8b8c 100644--- a/Meddy/Shared/Snapshots/DefinitionEnums.swift+++ b/Meddy/Shared/Snapshots/DefinitionEnums.swift@@ -1,10 +1,9 @@ import Foundation  nonisolated enum RoutineKind: String, Codable, Sendable {-    case timedRounds, ordered+  case timedRounds, ordered }  nonisolated enum RoutineStepTargetKind: String, Codable, Sendable {-    case treatment, timedRoutine, medication+  case treatment, timedRoutine, medication }-
Meddy/Shared/Snapshots/DefinitionValues.swift Modified
diff --git a/Meddy/Shared/Snapshots/DefinitionValues.swift b/Meddy/Shared/Snapshots/DefinitionValues.swiftindex 4f8c3fd..959444d 100644--- a/Meddy/Shared/Snapshots/DefinitionValues.swift+++ b/Meddy/Shared/Snapshots/DefinitionValues.swift@@ -1,85 +1,94 @@ import Foundation  nonisolated enum DefinitionError: Error, LocalizedError, Equatable, Sendable {-    case missingName, invalidTimer, emptySteps, duplicateStepID, duplicateMedication-    case invalidTarget, invalidSchedule, nestedRoutine, ownershipConfirmationRequired, otherOwner-    case emptyOwnerConfirmationRequired, releaseChoiceRequired, unresolvedFrozenStep, futureTime, saveFailed+  case missingName, invalidTimer, emptySteps, duplicateStepID, duplicateMedication+  case invalidTarget, invalidSchedule, nestedRoutine, ownershipConfirmationRequired, otherOwner+  case emptyOwnerConfirmationRequired, releaseChoiceRequired, unresolvedFrozenStep, futureTime,+    saveFailed -    var errorDescription: String? {-        switch self {-        case .missingName: "Enter a name."-        case .invalidTimer: "Enter at least one round and a positive duration."-        case .emptySteps: "Add at least one step."-        case .duplicateStepID: "Each step needs its own identity."-        case .duplicateMedication: "A medication can appear only once in this routine."-        case .invalidTarget: "An item is missing or archived. Repair the plan before starting a new session."-        case .invalidSchedule: "Enter valid schedule settings. Reminders require a time for every daily slot."-        case .nestedRoutine: "Select a timed routine. Ordered routines cannot contain other ordered routines."-        case .ownershipConfirmationRequired: "Confirm that medication reminders will belong to this routine."-        case .otherOwner: "This medication already belongs to another routine. Resolve that ownership first."-        case .emptyOwnerConfirmationRequired: "Confirm archiving the earlier routine if transferring its medications leaves it empty."-        case .releaseChoiceRequired: "Choose a standalone mode for each medication removed from this routine."-        case .unresolvedFrozenStep: "Resolve the medication's unfinished saved session before changing its owner."-        case .futureTime: "Completion time must be now or in the past."-        case .saveFailed: "The change could not be saved. Please try again."-        }+  var errorDescription: String? {+    switch self {+    case .missingName: "Enter a name."+    case .invalidTimer: "Enter at least one round and a positive duration."+    case .emptySteps: "Add at least one step."+    case .duplicateStepID: "Each step needs its own identity."+    case .duplicateMedication: "A medication can appear only once in this routine."+    case .invalidTarget:+      "An item is missing or archived. Repair the plan before starting a new session."+    case .invalidSchedule:+      "Enter valid schedule settings. Reminders require a time for every daily slot."+    case .nestedRoutine:+      "Select a timed routine. Ordered routines cannot contain other ordered routines."+    case .ownershipConfirmationRequired:+      "Confirm that medication reminders will belong to this routine."+    case .otherOwner:+      "This medication already belongs to another routine. Resolve that ownership first."+    case .emptyOwnerConfirmationRequired:+      "Confirm archiving the earlier routine if transferring its medications leaves it empty."+    case .releaseChoiceRequired:+      "Choose a standalone mode for each medication removed from this routine."+    case .unresolvedFrozenStep:+      "Resolve the medication's unfinished saved session before changing its owner."+    case .futureTime: "Completion time must be now or in the past."+    case .saveFailed: "The change could not be saved. Please try again."     }+  } }  nonisolated struct RoutineStepDraft: Codable, Equatable, Identifiable, Sendable {-    var id: UUID = UUID()-    var kind: RoutineStepTargetKind-    var targetID: UUID+  var id: UUID = UUID()+  var kind: RoutineStepTargetKind+  var targetID: UUID }  nonisolated struct FrozenRoutineStep: Codable, Equatable, Identifiable, Sendable {-    var id: UUID-    var position: Int-    var kind: RoutineStepTargetKind-    var targetID: UUID-    var name: String-    var instructions: String-    var requirements: String-    var dose: RecordedDoseSnapshot?-    var roundCount: Int?-    var roundDurationSeconds: Int?-    var betweenRoundInstructions: String-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var id: UUID+  var position: Int+  var kind: RoutineStepTargetKind+  var targetID: UUID+  var name: String+  var instructions: String+  var requirements: String+  var dose: RecordedDoseSnapshot?+  var roundCount: Int?+  var roundDurationSeconds: Int?+  var betweenRoundInstructions: String+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct FrozenRoutineDefinition: Codable, Equatable, Sendable {-    var routineID: UUID-    var revision: Int-    var kind: RoutineKind-    var name: String-    var instructions: String-    var roundCount: Int?-    var roundDurationSeconds: Int?-    var betweenRoundInstructions: String-    var steps: [FrozenRoutineStep]-    var occurrence: FrozenOccurrenceContext? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var routineID: UUID+  var revision: Int+  var kind: RoutineKind+  var name: String+  var instructions: String+  var roundCount: Int?+  var roundDurationSeconds: Int?+  var betweenRoundInstructions: String+  var steps: [FrozenRoutineStep]+  var occurrence: FrozenOccurrenceContext?+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct TreatmentAction: Codable, Equatable, Sendable {-    var eventID: UUID-    var treatmentID: UUID-    var timestamp: Date-    var instructionsSnapshot: String-    var source: AdministrationSource-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var eventID: UUID+  var treatmentID: UUID+  var timestamp: Date+  var instructionsSnapshot: String+  var source: AdministrationSource+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated struct FrozenOccurrenceContext: Codable, Equatable, Sendable {-    var key: String-    var slotID: UUID-    var localDate: String-    var timeZoneID: String-    var scheduledAt: Date?+  var key: String+  var slotID: UUID+  var localDate: String+  var timeZoneID: String+  var scheduledAt: Date? }
Meddy/Shared/Snapshots/ProfileIdentity.swift Modified
diff --git a/Meddy/Shared/Snapshots/ProfileIdentity.swift b/Meddy/Shared/Snapshots/ProfileIdentity.swiftindex bd0965f..d926e86 100644--- a/Meddy/Shared/Snapshots/ProfileIdentity.swift+++ b/Meddy/Shared/Snapshots/ProfileIdentity.swift@@ -1,27 +1,28 @@ import Foundation  nonisolated enum ProfileIdentity {-    static let me = UUID(uuidString: "91DD5C33-E76A-4A93-982A-A2E71DB1B773")!-    static let selfLifecycle = UUID(uuidString: "0F84D76D-3333-4A94-8450-BF9851769761")!-    static let ownershipVersion = 1+  static let me = UUID(uuidString: "91DD5C33-E76A-4A93-982A-A2E71DB1B773")!+  static let selfLifecycle = UUID(uuidString: "0F84D76D-3333-4A94-8450-BF9851769761")!+  static let ownershipVersion = 1 }  nonisolated enum ProfileError: Error, LocalizedError, Equatable, Sendable {-    case unknownOwner, conflictingOwnership, archived, staleLifecycle-    var errorDescription: String? {-        switch self {-        case .unknownOwner: "This care entry's profile is unavailable. Keep it for review."-        case .conflictingOwnership: "Care entries belong to different or conflicting profiles. Nothing was recorded."-        case .archived: "This profile is archived. Restore it before recording care."-        case .staleLifecycle: "This action predates a profile archive or restore. Keep it for review."-        }+  case unknownOwner, conflictingOwnership, archived, staleLifecycle+  var errorDescription: String? {+    switch self {+    case .unknownOwner: "This care entry's profile is unavailable. Keep it for review."+    case .conflictingOwnership:+      "Care entries belong to different or conflicting profiles. Nothing was recorded."+    case .archived: "This profile is archived. Restore it before recording care."+    case .staleLifecycle: "This action predates a profile archive or restore. Keep it for review."     }+  } }  nonisolated protocol ProfilePayload {-    var profileID: UUID? { get set }-    var ownershipVersion: Int? { get set }-    var profileLifecycleID: UUID? { get set }+  var profileID: UUID? { get set }+  var ownershipVersion: Int? { get set }+  var profileLifecycleID: UUID? { get set } } extension AdministrationAction: ProfilePayload {} extension TreatmentAction: ProfilePayload {}
Meddy/Shared/Snapshots/RecordingValues.swift Modified
diff --git a/Meddy/Shared/Snapshots/RecordingValues.swift b/Meddy/Shared/Snapshots/RecordingValues.swiftindex 3485b70..575398b 100644--- a/Meddy/Shared/Snapshots/RecordingValues.swift+++ b/Meddy/Shared/Snapshots/RecordingValues.swift@@ -1,62 +1,63 @@ import Foundation  nonisolated enum MedicationScheduleType: String, Codable, CaseIterable, Sendable {-    case asNeeded, spreadThroughDay, interval, fixedTimes, afterWaking, routineManaged+  case asNeeded, spreadThroughDay, interval, fixedTimes, afterWaking, routineManaged }  nonisolated enum AdministrationSource: String, Codable, Sendable {-    case phone, watch, notification, manualHistory+  case phone, watch, notification, manualHistory }  nonisolated struct RecordedDoseSnapshot: Codable, Equatable, Sendable {-    var description: String-    var amount: Double?-    var unit: String?--    static let unknown = RecordedDoseSnapshot(description: "", amount: nil, unit: nil)--    var displayText: String {-        if !description.isEmpty { return description }-        if let amount, let unit { return "\(amount) \(unit)" }-        return "Dose not recorded"-    }--    func validate() throws {-        switch (amount, unit) {-        case (nil, nil): break-        case let (amount?, unit?) where amount.isFinite && amount > 0-            && !unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty: break-        default: throw RecordingError.invalidDose-        }+  var description: String+  var amount: Double?+  var unit: String?++  static let unknown = RecordedDoseSnapshot(description: "", amount: nil, unit: nil)++  var displayText: String {+    if !description.isEmpty { return description }+    if let amount, let unit { return "\(amount) \(unit)" }+    return "Dose not recorded"+  }++  func validate() throws {+    switch (amount, unit) {+    case (nil, nil): break+    case (let amount?, let unit?)+    where amount.isFinite && amount > 0+      && !unit.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty:+      break+    default: throw RecordingError.invalidDose     }+  } }  nonisolated struct AdministrationAction: Codable, Equatable, Sendable {-    var eventID: UUID-    var medicationID: UUID-    var timestamp: Date-    var source: AdministrationSource-    var dose: RecordedDoseSnapshot-    var scheduleTypeAtRecording: MedicationScheduleType-    var scheduleGenerationID: UUID?-    var wakeEventID: UUID? = nil-    var profileID: UUID? = nil-    var ownershipVersion: Int? = nil-    var profileLifecycleID: UUID? = nil+  var eventID: UUID+  var medicationID: UUID+  var timestamp: Date+  var source: AdministrationSource+  var dose: RecordedDoseSnapshot+  var scheduleTypeAtRecording: MedicationScheduleType+  var scheduleGenerationID: UUID?+  var wakeEventID: UUID?+  var profileID: UUID?+  var ownershipVersion: Int?+  var profileLifecycleID: UUID? }  nonisolated enum RecordingError: Error, LocalizedError, Sendable {-    case missingName, invalidDose, futureTime, unknownMedication, linkedCorrectionRequired, saveFailed--    var errorDescription: String? {-        switch self {-        case .missingName: "Enter a name."-        case .invalidDose: "Enter a positive amount with a unit, or leave both empty."-        case .futureTime: "Taken time must be now or in the past."-        case .unknownMedication: "The medication is unavailable. Keep the action for review."-        case .linkedCorrectionRequired: "Correct this linked action from its saved routine session."-        case .saveFailed: "The entry could not be saved. Please try again."-        }+  case missingName, invalidDose, futureTime, unknownMedication, linkedCorrectionRequired, saveFailed++  var errorDescription: String? {+    switch self {+    case .missingName: "Enter a name."+    case .invalidDose: "Enter a positive amount with a unit, or leave both empty."+    case .futureTime: "Taken time must be now or in the past."+    case .unknownMedication: "The medication is unavailable. Keep the action for review."+    case .linkedCorrectionRequired: "Correct this linked action from its saved routine session."+    case .saveFailed: "The entry could not be saved. Please try again."     }+  } }-

Docs (3)

AGENTS.md Added
diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..5132623--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,47 @@+# Meddy agent guide++## Project and sources++This guide was authored from the inspected repository. The installed `project-init` skill only configures Claude tool permissions, and no AGENTS-generating init command was available; no init/setup command was invoked.++Meddy is a personal SwiftUI iPhone app with a Watch companion. The Xcode project is `Meddy/Meddy.xcodeproj`; shared schemes are `Meddy` and `MeddyWatch`. Read relevant sections of `docs/meddy-design.md`, `docs/meddy-implementation-plan.md` and `docs/meddy-implementation-preflight.md` before changing care behavior. Profile ownership rules are also in `docs/meddy-dependant-profile-design.md`.++- `Meddy/Meddy/`: iPhone app, SwiftData models, feature views and services.+- `Meddy/Shared/`: scheduling, snapshots, execution and companion protocol values used by both platforms.+- `Meddy/MeddyWatch/`: Watch views/controller/runtime.+- `Meddy/MeddyTests/`, `Meddy/MeddyUITests/`, `Meddy/MeddyWatchTests/`: isolated domain/service tests and UI journeys.++## Commands++Use the root Makefile for development tooling; `make` shows help. GNU Make 4.4.1 is installed as `gmake` on this Mac. See `docs/development.md` for destination/cache/result overrides.++- `make build` / `make build-watch`: unsigned simulator builds.+- `make test-quick`: phone domain tests with no UI; `make test-domain DOMAIN_TEST=MeddyTests/Suite` narrows the affected suite.+- `make test-watch`: Watch domain tests on the Watch simulator.+- `make test-ui UI_TEST=MeddyUITests/Class/Method`: explicit affected UI scenario; omit the method only when the whole class is relevant.+- `make test-ui-smoke`: just the first recording/navigation and whole-phone-routine journeys.+- `make lint`: strict SwiftLint check; `make lint-fix`: explicit corrections followed by diff inspection and another lint run.+- `make check`: whitespace validation; `make simulators`: read-only discovery.+- `make pre-push` (or `make test`): whitespace/lint checks, then full phone domain, Watch domain and full phone UI gates, serially. This is the phase-boundary gate, not the inner loop.++Coordinate the shared heavy-work slot with the parent before builds/tests. Use targeted checks after fixes; do not repeatedly run a full UI suite or duplicate another agent's test monitoring. Keep full logs on disk, report exit status/counts and relevant failure excerpts, and drain only owned processes when a run stalls. Failed/interrupted runs are not passing evidence. Makefile caches are isolated under ignored `DerivedData/`; each invocation retains logs/results under ignored `build/results/`. Never remove another project's cache or stop its processes.++## Swift style++The checked-in `.swiftlint.yml` uses strict warnings, default rules, and Prism's opt-in rules and practical SwiftUI size conventions. It excludes generated caches; it does not globally disable rules. Use descriptive names and focused helpers while preserving validation, action identity and transaction order. Keep care text and encoded/persisted fields unchanged during mechanical cleanup.++`AsNeededLimitViews` deliberately uses `let _ =` inside its SwiftUI result builder to establish observation. The adjacent one-line `redundant_discardable_let` exception preserves that declaration; replacing it with a bare assignment can cause expensive result-builder type checking. Do not apply that exception elsewhere without the same concrete reason.++## Data and behavior++Tests/previews must use isolated synthetic stores and fake clients. The shared test schemes set `MEDDY_TESTING=1`; `AppEnvironment` uses no CloudKit for isolated stores. Never let a failed test-store path fall back to the live container. Do not read, seed, edit, export or reset real personal health records for tests, or send health data to external tools/services.++Preserve captured profile ownership, historical dose snapshots, correction/Undo tombstones, timer/checkpoint state and offline action identity. Do not infer drug limits, doses, medical safety, wake detection or clinical content. As-needed limits use recorded quantities and entered limits; new daily caps use the preceding 24 elapsed hours and older non-24-hour rules require explicit conversion. Medication timing and care actions follow the authoritative design.++The active bundle identifier is `me.nore.ig.meddy`; the Watch companion is `me.nore.ig.meddy.watchkitapp` and private container is `iCloud.me.nore.ig.meddy`. Do not change signing, entitlements, team/account/container configuration as incidental tooling work. Actual live resets/deletes require concrete approval. Physical Watch installs/testing remain deferred; use Watch simulators only. Phone installation requires an explicit request and an in-place update, never an unsolicited uninstall/reset.++## Git and review++Start ticket work on a feature branch from current `main`; preserve user changes and avoid unrelated fixes. Keep commits coherent and update existing design/plan/changelog when behavior changes. Use the existing `recall-knowledge` skill at natural new-task and problem boundaries for applicable captured cross-project patterns, including freshly captured test, notification and editor lessons. Follow the existing `pre-push-review` workflow before publication; full required gates must pass and unresolved/inherited failures must be reported honestly. Publish the ticket branch through a draft PR after review. Do not push directly to `main`, merge a PR, or deploy without the relevant authorization. Remote configuration belongs to the user.++Keep changes proportionate to a personal app. Do not introduce approval stages, enterprise migration machinery, dependencies or exhaustive test infrastructure without a concrete need. No `CLAUDE.md` currently exists; do not create or duplicate one just to mirror this file.
CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 167510a..54d6ddd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,11 +3,14 @@ ## Unreleased  ### Fixed+- Apply strict Swift lint cleanup and focused helpers while preserving care/state semantics; replace the deprecated Watch foreground-state API with WKApplication. - T2419: Remove redundant Done editing keyboard buttons from care editors, retaining scrolling and explicit Save/Cancel. - T2420: Simplify as-needed limits to quantity, interval and a 24-hour daily cap, with next-dose time and remaining allowance; retain older windows until explicitly converted. - T2413: Keep notification snoozes at their chosen 15-minute deadline, cancel queued originals, suppress elapsed replay and await background scheduling completion.  ### Added+- T2423: Repository agent guide covering simulator tooling, recalled knowledge, synthetic stores, captured care/profile ownership and truthful initialization provenance.+- T2421: Help-first simulator Makefile with isolated caches/results, fast targeted checks, strict lint and unchanged full serial publication gates. - T2415: Background-callable Record Waking Up shortcut with stable profile selection and first-wake daily anchors; medication and ordered-session elapsed wake offsets with persistent no-replay reminder receipts. - T2414: Me and optional dependant profiles with separate care/history/PRN/export views, captured notification and Watch ownership, reversible archive/restore and a small additive startup transition. Restored saved sessions resume explicitly on iPhone before continuing on Watch. - Structured UTF-8 Markdown Current Medications export with purpose/medication headings, labelled fields, escaped multiline content and a dated .md share filename.
docs/development.md Added
diff --git a/docs/development.md b/docs/development.mdnew file mode 100644index 0000000..a0cb1c6--- /dev/null+++ b/docs/development.md@@ -0,0 +1,34 @@+# Meddy development commands++Run `make` for help (`gmake` is also available on this Mac). All build/test targets use simulators, disable signing, retain full logs and write a unique `.xcresult` under ignored `build/results/`. Phone and Watch caches are separate under ignored `DerivedData/`. No target installs, launches against live data, resets a device/store, changes accounts or pushes Git branches. Coordinate the shared heavy-work slot before running builds or tests.++For day-to-day work, use `make build`, `make test-quick`, or narrow the domain bundle with `make test-domain DOMAIN_TEST=MeddyTests/MeddyAsNeededLimitTests`. These phone tests depend on iOS APIs, so the fast target uses the iOS simulator rather than inventing a macOS test destination. The shared schemes set `MEDDY_TESTING=1`; tests use isolated synthetic stores and fake clients.++Keep automated UI work minimal during development: `make test-ui-smoke` runs only recording/navigation and the whole phone routine journey. For a changed editor or flow, select its exact test with `make test-ui UI_TEST=MeddyUITests/MeddyEditorUITests/testEditorsDismissKeyboardWithoutSavingAndKeepExplicitSaveAndCancel`. A missing selector fails before Xcode runs. Do not run the full UI bundle repeatedly in the inner loop.++Before publishing a ticket branch, `make pre-push` (also `make test`) runs whitespace and strict SwiftLint checks, then full phone domain tests, full Watch domain tests and the full phone UI bundle serially. A narrowed `DOMAIN_TEST` from the calling shell does not narrow this gate. Any failed command stops the gate; `tee` cannot turn a failed build/test green. Use the existing `pre-push-review` skill before pushing a feature branch and creating its draft PR; never push directly to main. This Makefile does not install a Git hook or publish anything automatically.++Defaults match this Mac's current simulator models. Override destinations with exact simulator IDs when coordinating resources, for example:++```sh+make test-domain 'PHONE_DESTINATION=platform=iOS Simulator,id=YOUR_SIMULATOR_ID'+make test-watch 'WATCH_DESTINATION=platform=watchOS Simulator,id=YOUR_WATCH_SIMULATOR_ID'+```++Override `DERIVED_DATA`, `WATCH_DERIVED_DATA` or `RESULTS_DIR` to reuse an isolated agent cache or keep logs outside the checkout. Each run reports its result directory; inspect its `xcodebuild.log` and `Results.xcresult`. Keep destination overrides on their simulator platforms. `make simulators` lists available devices without booting them; `make check` validates whitespace.++This workflow applies the recalled Swift Makefile pattern: help as the default, fast domain versus pre-push gates, serial testing, explicit targeted UI filters, separate caches and honest pipeline failures. SwiftLint is already installed on this Mac; no package installation was needed.++Run `make lint` for strict checks and `make lint-fix` for explicit corrections, then inspect the diff and run `make lint` again. The policy follows Transit's strict Make integration and Prism's opt-in rules and practical SwiftUI size conventions; Asterism does not use a style linter. The config excludes generated caches and keeps default rules enabled. Lint cache output is ignored under `build/swiftlint-cache`; override `SWIFTLINT_CACHE` when using an agent workspace.++Avoid a blanket suppression to pass lint. Prefer descriptive names, named edit/fixture values and focused helpers. The one-line `redundant_discardable_let` exception in `AsNeededLimitViews` protects its SwiftUI observation declaration from an autofix known to produce expensive result-builder type checking.++## UI runner diagnostics++The first full gate passed 186 phone domain tests and 13 Watch tests, but UI cases repeatedly completed their assertions then exceeded their teardown deadlines. A saved runner sample showed `XCTCrashLogTracker.waitForPendingCrashlogs()` during one inspected teardown wait. The same background-publication runtime warning appears in a prior passing editor log, so its presence alone does not establish a cleanup regression or the cause of the wait. No relevant Meddy crash report was found in the inspected Mac diagnostic-report location.++`UI_TEST_TIMEOUTS=NO` is a UI-only diagnostic override for the supported `xcodebuild -test-timeouts-enabled` option. Its default remains `YES`. One bounded probe selected only `MeddyUITests/MeddyFirstSliceUITests/testNameOnlyCreationTakenAndUndoWithoutNotificationPermission` with `NO`. The case logged a pass after 145.004 seconds, and its retained native result reports one passed, zero failed and zero skipped. However, the overall command exceeded the separate 300-second deadline and was terminated without `TEST SUCCEEDED`. This is incomplete gate evidence: disabling XCTest timeouts did not produce a completed passing command, and it is not an established remedy. Cleanup initially encountered a process-permission error; separate verification confirmed the owned process group and UI runner were gone and the assigned phone simulator was shut down. No equivalent retry or full UI run follows that stall without coordinated authorization. A successful command must execute its selected cases, finish teardown and exit successfully; a stall or interrupted command remains incomplete evidence. After a successful remedy, run the complete UI bundle before publication. Keep all assertions and warning checks, and preserve the already passing domain results unless production code changes. Do not use private XCTest environment switches, suppress runtime warnings or change macOS privacy settings to hide the wait.++The installed `project-init` skill was inspected, not run: it configures `.claude/settings.json` permissions and does not generate AGENTS.md. No available AGENTS-generating init command was found; the guide was authored from this repository's actual layout, commands and data rules.++Reviewed source is preserved in local feature-branch commits. The repository commit workflow requires checks to run but has no passing pre-commit condition, and no active pre-commit hook exists. Local preservation does not waive the unchanged pre-push requirement: full UI verification must complete successfully before push or draft PR publication. No new heavy checks or deployment were run to make these local commits.

Things to double-check

Evidence provenance

Existing native evidence is reused; no new builds or simulator tests ran. The Swift ecosystem registry has no runner for this Xcode project. Native test trees were converted to JUnit; no coverage was collected.