Meddy files 16 reviewed head db6e969

Pre-push review: All-profile Today

All-profile medication overview and bounded startup read improvements.

At a glance

  • Today shows medication for every valid, unarchived profile, with owner labels and per-owner Take.
  • Medications, Routines and Today routine sections retain their selected-profile scope.
  • Current main is integrated, preserving Tomorrow labels, timer restart and existing projection safeguards.

Verdict

Ready for draft PR

Three independent source reviews covered integration commit 5b63019. Supplemental independent review covered subsequent UI-test-only repairs at db6e969, with no actionable findings. Full phone UI gate passed 32/32 on 16 November; unchanged production retains domain 379/379, Watch 17/17 and widget-build passes from 13 November. Strict lint and whitespace checks passed.

Review findings

2 raised · 0 fixed · 2 skipped

Jump to findings →

Tests

Pass rate: 100% (428 of 428)

New tests: 4

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

Today brings every profile’s medications together so switching profiles is unnecessary. Labels show who each medication belongs to, and each Take button applies to one person.

Why it matters

The screen does less repeated work. Routine-managed medication appears as a reference without adding a second way to record it.

Key concepts

A temporary snapshot gathers the information needed for one screen update. It is not permission to change records later.

Implementation

TodayMedicationSnapshot batches owner validation, schedule evaluation and today’s history. ContentView groups due actions by captured owner; the button recomputes due targets before the existing transactional write service.

Trade-offs

Per-owner wake reads remain synchronous and local. The existing pure schedule evaluator is reused. Routine and library filtering stay unchanged.

Completeness

Requested feature and scoped performance changes are implemented. Extra identical-owner-label UI journeys are recommended but not blocking source-review findings. Required simulator gates have passed; physical-device acceptance is separate.

Ownership and lifetime

ReadScope retains all duplicate-ID candidates and uses the existing link/lifecycle rules. Indexes are discarded before mutation or suspension. Notification planning retains main’s projection boundary before pending routine activation.

Historical state

Grouped follow-up reads preserve elapsed actions for delivered-notification validity. Pending timer reconciliation remains separate from running-only discovery. No clinical rules, schemas, signing identities or persistence formats change.

Limits

The prior phone trace informed the fixes but does not quantify this integrated head. Residual first-scroll stutter is outside this PR’s requested scope.

Important changes — detailed

Today: gather one all-owner snapshot

Meddy/Meddy/Features/TodayMedicationSnapshot.swift

Why it matters. Avoids repeating whole-store validation and schedule work for every card.

What to look at. TodayMedicationSnapshot.init

Takeaway. Reuse a synchronous read index, never a stale write authority.
Rationale. The user requested all profiles without repeated switching; profiling exposed repeated ownership work.

Take: retain captured owner and fresh targets

Meddy/Meddy/ContentView.swift

Why it matters. One profile’s Take must not record another profile’s medication or use obsolete rendered targets.

What to look at. dueCard

Rationale. Preserve profile isolation while widening display scope.

Follow-ups: group history by medication

Meddy/Meddy/Services/MedicationFollowupService.swift

Why it matters. Avoids traversing every event for every medication while retaining historical notification validation.

What to look at. actions(context:now:scope:)

Takeaway. Optimise lookup structure without trimming semantically required history.
Rationale. Measured startup stacks showed repeated history/ownership reads.

Review findings

SeverityAreaFindingResolution
minorTodayMedicationSnapshot reuseThe snapshot duplicates projection assembly already present in MedicationPresentation.Deferred optional consolidation; both continue using the same schedule evaluator and owner validation.
minorAdditional UI and wake-cache casesSame-name owners with grouped Take/Undo and distinct per-owner wake anchors could use direct additional coverage.Not an observed bug or blocking review finding. Existing domain and full UI gates remain required.

Tests

Source: local run at 2026-11-16T08:52:28.597960+00:00 · snapshot db6e9692bb9171f0b2245815327978acc9e0bbe6

Baseline: none

Execution: passed · JUnit: 3 files · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

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

New and removed tests

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

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 HEAD against base 968f0c6dd4488389184b01e6314d5b1b563db71c.

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

16 files: 12 code · 4 docs. Click to expand.

Code (12)

Meddy/Meddy/ContentView.swift Changed +134 / -77
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex 1459340..1e1b77f 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -6,6 +6,7 @@ struct ContentView: View {   @Environment(\.modelContext) private var context   @Environment(\.logicalDayNow) private var logicalTick   @Query(sort: \Medication.name) private var allMedications: [Medication]+  @Query private var profiles: [CareProfile]   @Query(sort: \Administration.timestamp, order: .reverse) private var allEvents: [Administration]   @Binding var profileSelection: UUID   var cloud: CloudSyncMonitor?@@ -32,20 +33,21 @@ struct ContentView: View {   private var medications: [Medication] {     ProfileAccess.visible(allMedications, for: selectedProfileID, context: context)   }-  private var active: [Medication] { medications.filter(\.isActive) }-  private var todayEvents: [Administration] {-    let current = allEvents.filter {-      !$0.isDeleted && ScheduleCalendar.sameDay($0.timestamp, now, calendar: .current)-    }-    return ProfileAccess.visible(current, for: selectedProfileID, context: context)-  }-  private var scheduled: [(Medication, Date)] {-    MedicationPresentation.scheduled(active, now: now, context: context)+  private func profileLabel(_ id: UUID?) -> String {+    guard let id else { return "Unknown profile" }+    let fallback = id == ProfileIdentity.me ? "Me" : "Profile \(id.uuidString.prefix(6))"+    let label = profiles.first { $0.id == id }?.label ?? fallback+    let matchingIDs = Set(profiles.filter { $0.archivedAt == nil && $0.label == label }.map(\.id))+    return matchingIDs.count > 1 ? "\(label) · \(id.uuidString.prefix(6))" : label   }-  private var due: [Medication] {-    scheduled.filter { $0.1 <= now.addingTimeInterval(1800) }.map(\.0)+  private func dueProfileIDs(_ medications: [Medication]) -> [UUID] {+    let ids = Set(medications.compactMap(\.profileID))+    return ids.sorted {+      $0 == ProfileIdentity.me && $1 != ProfileIdentity.me+        || $0 != ProfileIdentity.me && $1 != ProfileIdentity.me+          && (profileLabel($0), $0.uuidString) < (profileLabel($1), $1.uuidString)+    }   }-   var body: some View {     TabView {       NavigationStack { today }.tabItem { Label("Today", systemImage: "sun.max") }@@ -84,15 +86,14 @@ struct ContentView: View {    private var today: some View {     let now = now-    let projection = MedicationPresentation.projection(active, now: now, context: context)-    let scheduled = projection.scheduled-    let due = scheduled.filter { $0.1 <= now.addingTimeInterval(1800) }.map(\.0)+    let snapshot = TodayMedicationSnapshot(+      medications: allMedications, events: allEvents, now: now, context: context)     return ScrollView {       VStack(alignment: .leading, spacing: 12) {         MeddyScreenHeader(           title: "Today",           subtitle:-            "\(now.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))) · \(todayEvents.count) recorded"+            "\(now.formatted(.dateTime.weekday(.abbreviated).day().month(.abbreviated))) · \(snapshot.events.count) recorded across profiles"         ) {           ProfilePicker(selection: $profileSelection, cloud: cloud)         }@@ -103,23 +104,28 @@ struct ContentView: View {           }           .foregroundStyle(MeddyStyle.warning).meddyCard(radius: 20, padding: 16)         }-        dueHero(scheduled: scheduled, due: due, now: now)-        scheduleAttention(projection)+        dueHero(snapshot)+        scheduleAttention(snapshot)         TodayRoutineSections()-        if scheduled.contains(where: { $0.1 > now.addingTimeInterval(1800) }) {+        if !snapshot.later.isEmpty {           MeddySectionLabel(text: "Later").padding(.horizontal, 8)-          ForEach(scheduled.filter { $0.1 > now.addingTimeInterval(1800) }, id: \.0.id) { medication, date in+          ForEach(snapshot.later, id: \.0.id) { medication, date in             NavigationLink {               MedicationDetailView(medication: medication)+                .environment(\.careProfileID, medication.profileID ?? ProfileIdentity.me)             } label: {               HStack(spacing: 12) {-                let presentation = NextDosePresentation(next: date, now: now)+                let presentation = NextDosePresentation(next: date, now: snapshot.now)                 Text(presentation.title).monospacedDigit()                   .frame(minWidth: 66, alignment: .leading).fixedSize(horizontal: false, vertical: true)                   .accessibilityLabel(presentation.accessibilityLabel)                   .accessibilityIdentifier("laterNextDose")                 MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name, size: 32)-                Text(medication.name).fontWeight(.semibold)+                VStack(alignment: .leading, spacing: 3) {+                  Text(medication.name).fontWeight(.semibold)+                  Text(profileLabel(medication.profileID)).font(.caption)+                    .foregroundStyle(MeddyStyle.secondary)+                }                 Spacer(minLength: 4)                 Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)                   .font(.subheadline).foregroundStyle(MeddyStyle.secondary)@@ -130,23 +136,24 @@ struct ContentView: View {         }         TodayRoutineSections(           later: true,-          hasMedicationLater: scheduled.contains { $0.1 > now.addingTimeInterval(1800) })+          hasMedicationLater: !snapshot.later.isEmpty)+        routineMedications(snapshot.medications)         MeddySectionLabel(text: "As needed").padding(.horizontal, 8)         LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 12)], spacing: 12) {-          ForEach(active.filter { $0.scheduleTypeRaw == "asNeeded" }) { medication in+          ForEach(snapshot.medications.filter { $0.scheduleTypeRaw == "asNeeded" }) { medication in             Button {               loggingMedication = medication             } label: {-              AsNeededTile(medication: medication)+              AsNeededTile(medication: medication, profileLabel: profileLabel(medication.profileID))             }-            .buttonStyle(.plain).accessibilityLabel("Log dose for \(medication.name)")+            .buttonStyle(.plain).accessibilityLabel("Log dose for \(medication.name), \(profileLabel(medication.profileID))")             .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached")           }         }-        if !todayEvents.isEmpty {+        if !snapshot.events.isEmpty {           MeddySectionLabel(text: "Taken").padding(.horizontal, 8)           MeddyWrap {-            ForEach(todayEvents) { event in+            ForEach(snapshot.events) { event in               Button {                 editingTodayEvent = event               } label: {@@ -154,6 +161,7 @@ struct ContentView: View {                   Image(systemName: "checkmark").foregroundStyle(MeddyStyle.success)                   MedicationPhotoView(data: event.medication?.recognitionPhotoData, name: event.medication?.name ?? "Medication", size: 24)                   Text(event.medication?.name ?? "Medication")+                  Text("· " + profileLabel(event.profileID))                   Text("· " + event.timestamp.formatted(date: .omitted, time: .shortened))                 }.font(.caption).padding(.horizontal, 12).padding(.vertical, 9)                   .background(MeddyStyle.surface, in: Capsule())@@ -166,20 +174,22 @@ struct ContentView: View {       .overlay(alignment: .bottom) { undoToast }   } -  private func scheduleAttention(_ projection: MedicationPresentation.ScheduleProjection) -> some View {-    ForEach(projection.results, id: \.medication.id) { entry in-      let medication = entry.medication-      let result = entry.result-      if result.next == nil {+  private func scheduleAttention(_ snapshot: TodayMedicationSnapshot) -> some View {+    ForEach(snapshot.medications) { medication in+      if let result = snapshot.results[medication.id],+        result.next == nil {         if result.cannotFitInWindow           || medication.scheduleTypeRaw == "afterWaking" && result.takenToday == 0 {           NavigationLink {             MedicationDetailView(medication: medication)+              .environment(\.careProfileID, medication.profileID ?? ProfileIdentity.me)           } label: {             HStack(spacing: 12) {               MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)               VStack(alignment: .leading, spacing: 5) {                 Text(medication.name).font(.headline)+                Text(profileLabel(medication.profileID)).font(.caption)+                  .foregroundStyle(MeddyStyle.secondary)                 Text(                   result.cannotFitInWindow                     ? "Remaining doses cannot fit in today's window" : "Waiting for recorded wake"@@ -194,59 +204,102 @@ struct ContentView: View {     }   } -  private func dueHero(scheduled: [(Medication, Date)], due: [Medication], now: Date) -> some View {-    VStack(alignment: .leading, spacing: 16) {-      if due.isEmpty {+  @ViewBuilder private func routineMedications(_ active: [Medication]) -> some View {+    let medications = active.filter { $0.scheduleTypeRaw == "routineManaged" }+    if !medications.isEmpty {+      MeddySectionLabel(text: "In routines").padding(.horizontal, 8)+      ForEach(medications) { medication in+        NavigationLink {+          MedicationDetailView(medication: medication)+            .environment(\.careProfileID, medication.profileID ?? ProfileIdentity.me)+        } label: {+          HStack(spacing: 12) {+            MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+            VStack(alignment: .leading, spacing: 5) {+              Text(medication.name).font(.headline)+              Text(profileLabel(medication.profileID)).font(.caption)+                .foregroundStyle(MeddyStyle.secondary)+            }+            Spacer(minLength: 4)+            Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)+              .font(.subheadline).foregroundStyle(MeddyStyle.secondary)+          }.meddyCard(radius: 22, padding: 16)+        }.buttonStyle(.plain)+          .accessibilityLabel("\(medication.name), \(profileLabel(medication.profileID)), in a routine")+      }+    }+  }++  @ViewBuilder private func dueHero(_ snapshot: TodayMedicationSnapshot) -> some View {+    if snapshot.due.isEmpty {+      VStack(alignment: .leading, spacing: 16) {         Text("All caught up").font(.system(.title2, weight: .bold))-        if let next = scheduled.first {-          let presentation = NextDosePresentation(next: next.1, now: now)-          Text("Next \(next.0.name) · \(presentation.title)")+        if let next = snapshot.scheduled.first {+          let presentation = NextDosePresentation(next: next.1, now: snapshot.now)+          Text("Next \(next.0.name) for \(profileLabel(next.0.profileID)) · \(presentation.title)")             .font(.subheadline).foregroundStyle(MeddyStyle.secondary)-            .accessibilityLabel("\(next.0.name), \(presentation.accessibilityLabel)")+            .accessibilityLabel("\(next.0.name), \(profileLabel(next.0.profileID)), \(presentation.accessibilityLabel)")         } else {           Text("Your next care will appear here.").font(.subheadline).foregroundStyle(             MeddyStyle.secondary)         }-      } else {-        if let next = scheduled.first {-          let presentation = NextDosePresentation(next: next.1, now: now)-          Text(presentation.dueHeroTitle)-            .font(.system(.caption, weight: .bold)).tracking(1.44).foregroundStyle(MeddyStyle.accent)-            .accessibilityLabel(presentation.accessibilityLabel)-        }-        ForEach(due) { medication in-          NavigationLink {-            MedicationDetailView(medication: medication)-          } label: {-            HStack(alignment: .top, spacing: 12) {-              MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)-              VStack(alignment: .leading, spacing: 5) {-                HStack(alignment: .firstTextBaseline) {-                  Text(medication.name).font(.system(.title2, weight: .bold))-                  Spacer(minLength: 8)-                  Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)-                    .font(.subheadline).foregroundStyle(MeddyStyle.secondary)-                }-                if !medication.requirements.isEmpty {-                  Text(medication.requirements).font(.subheadline).foregroundStyle(-                    MeddyStyle.secondary-                  ).lineLimit(1)-                } else if !medication.administrationMethod.isEmpty {-                  Text(medication.administrationMethod).font(.subheadline).foregroundStyle(-                    MeddyStyle.secondary-                  ).lineLimit(1)-                }+      }.meddyCard()+    } else {+      ForEach(dueProfileIDs(snapshot.due), id: \.self) { profileID in+        dueCard(for: profileID, snapshot: snapshot)+      }+    }+  }++  private func dueCard(for profileID: UUID, snapshot: TodayMedicationSnapshot) -> some View {+    let medications = snapshot.due.filter { $0.profileID == profileID }+    let firstDate = snapshot.scheduled.first { $0.0.profileID == profileID }?.1+    return VStack(alignment: .leading, spacing: 16) {+      Text(profileLabel(profileID)).font(.headline)+      if let firstDate {+        let presentation = NextDosePresentation(next: firstDate, now: snapshot.now)+        Text(presentation.dueHeroTitle)+          .font(.system(.caption, weight: .bold)).tracking(1.44).foregroundStyle(MeddyStyle.accent)+          .accessibilityLabel(presentation.accessibilityLabel)+      }+      ForEach(medications) { medication in+        NavigationLink {+          MedicationDetailView(medication: medication)+            .environment(\.careProfileID, profileID)+        } label: {+          HStack(alignment: .top, spacing: 12) {+            MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+            VStack(alignment: .leading, spacing: 5) {+              HStack(alignment: .firstTextBaseline) {+                Text(medication.name).font(.system(.title2, weight: .bold))+                Spacer(minLength: 8)+                Text(medication.defaultDose == .unknown ? "" : medication.defaultDose.displayText)+                  .font(.subheadline).foregroundStyle(MeddyStyle.secondary)+              }+              if !medication.requirements.isEmpty {+                Text(medication.requirements).font(.subheadline).foregroundStyle(+                  MeddyStyle.secondary+                ).lineLimit(1)+              } else if !medication.administrationMethod.isEmpty {+                Text(medication.administrationMethod).font(.subheadline).foregroundStyle(+                  MeddyStyle.secondary+                ).lineLimit(1)               }             }-          }.buttonStyle(.plain)-            .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached")-        }-        Button(due.count == 1 ? "Take" : due.count == 2 ? "Take both" : "Take all \(due.count)") {-          do { showUndo(try TodayMedicationAction.take(self.due, at: Date(), context: context)) } catch {-            self.error = error.localizedDescription           }-        }.buttonStyle(MeddyPrimaryButtonStyle()).accessibilityIdentifier("takeDueMedications")+        }.buttonStyle(.plain)+          .accessibilityLabel("\(medication.name), \(profileLabel(profileID))")+          .accessibilityValue(medication.recognitionPhotoData == nil ? "" : "Recognition photo attached")       }+      Button(medications.count == 1 ? "Take" : medications.count == 2 ? "Take both" : "Take all \(medications.count)") {+        let current = TodayMedicationSnapshot(+          medications: allMedications, events: allEvents, now: Date(), context: context)+        let targets = current.due.filter { $0.profileID == profileID }+        do { showUndo(try TodayMedicationAction.take(targets, at: current.now, context: context)) } catch {+          self.error = error.localizedDescription+        }+      }.buttonStyle(MeddyPrimaryButtonStyle()).accessibilityIdentifier("takeDueMedications")+        .accessibilityLabel("Take \(medications.count) medications for \(profileLabel(profileID))")     }.meddyCard()   } @@ -310,7 +363,7 @@ struct ContentView: View {     if !undoEvents.isEmpty {       HStack {         Text(-          "\(undoEvents.count == 1 ? undoEvents[0].medication?.name ?? "Medication" : "\(undoEvents.count) medications") taken"+          "\(undoEvents.count == 1 ? undoEvents[0].medication?.name ?? "Medication" : "\(undoEvents.count) medications") taken for \(profileLabel(undoEvents[0].profileID))"         )         .font(.subheadline.weight(.semibold))         Spacer()@@ -373,11 +426,15 @@ struct MedicationRow: View { struct AsNeededTile: View {   @Environment(\.modelContext) private var context   let medication: Medication+  var profileLabel: String?   private var check: DoseLimitCheck? { AsNeededLimitService(context: context).check(medication) }   var body: some View {     let check = self.check     VStack(alignment: .leading, spacing: 10) {       MedicationPhotoView(data: medication.recognitionPhotoData, name: medication.name)+      if let profileLabel {+        Text(profileLabel).font(.caption).foregroundStyle(MeddyStyle.secondary)+      }       HStack(alignment: .top) {         Text(medication.name).font(.system(.body, weight: .bold))         Spacer(minLength: 2)
Meddy/Meddy/Features/TodayMedicationSnapshot.swift Changed +43 / -0
diff --git a/Meddy/Meddy/Features/TodayMedicationSnapshot.swift b/Meddy/Meddy/Features/TodayMedicationSnapshot.swiftnew file mode 100644index 0000000..876a9b0--- /dev/null+++ b/Meddy/Meddy/Features/TodayMedicationSnapshot.swift@@ -0,0 +1,43 @@+import Foundation+import SwiftData++/// One synchronous presentation read. Never cache its ownership scope across mutations.+@MainActor+struct TodayMedicationSnapshot {+  private(set) var medications: [Medication] = []+  private(set) var events: [Administration] = []+  private(set) var results: [UUID: MedicationScheduleResult] = [:]+  private(set) var scheduled: [(Medication, Date)] = []+  private(set) var due: [Medication] = []+  private(set) var later: [(Medication, Date)] = []+  let now: Date++  init(medications: [Medication], events: [Administration], now: Date, context: ModelContext) {+    self.now = now+    guard let scope = try? ProfileAccess.ReadScope(context: context) else { return }+    self.medications = medications.filter { $0.isActive && (try? scope.owner($0)) != nil }+    self.events = events.filter {+      !$0.isDeleted && ScheduleCalendar.sameDay($0.timestamp, now, calendar: .current)+        && (try? scope.owner($0)) != nil+    }+    let schedules = ScheduleService(context: context)+    let wakes = WakeService(context: context)+    var anchorsByOwner: [UUID: Result<[WakeAnchor], Error>] = [:]+    for medication in self.medications where !["asNeeded", "routineManaged"].contains(medication.scheduleTypeRaw) {+      guard let owner = medication.profileID else { continue }+      if anchorsByOwner[owner] == nil {+        anchorsByOwner[owner] = Result { try wakes.anchors(profileID: owner) }+      }+      guard let anchors = try? anchorsByOwner[owner]?.get(),+        let snapshot = try? schedules.snapshot(medication, scope: scope, wakeAnchors: anchors)+      else { continue }+      let result = MedicationPresentation.result(medication, snapshot: snapshot, now: now)+      results[medication.id] = result+      if let next = result.next { scheduled.append((medication, next)) }+    }+    scheduled.sort { $0.1 == $1.1 ? $0.0.name < $1.0.name : $0.1 < $1.1 }+    let threshold = now.addingTimeInterval(1800)+    due = scheduled.filter { $0.1 <= threshold }.map(\.0)+    later = scheduled.filter { $0.1 > threshold }+  }+}
Meddy/Meddy/Services/MedicationFollowupService.swift Changed +6 / -4
diff --git a/Meddy/Meddy/Services/MedicationFollowupService.swift b/Meddy/Meddy/Services/MedicationFollowupService.swiftindex d252470..f29c6c1 100644--- a/Meddy/Meddy/Services/MedicationFollowupService.swift+++ b/Meddy/Meddy/Services/MedicationFollowupService.swift@@ -26,14 +26,16 @@ enum MedicationFollowupService {     -> [MedicationFollowupAction] {     let medications = try context.fetch(FetchDescriptor<Medication>())     let events = try context.fetch(FetchDescriptor<Administration>())+    // This synchronous read must not reload the ownership graph for every historical dose.+    let eventsByMedication = Dictionary(grouping: events, by: \.medicationID)     var result: [MedicationFollowupAction] = []     for medication in medications     where medication.isActive && (try? scope.owner(medication)) != nil {       guard let value = try? configuration(medication) else { continue }-      for event in events-      where event.medicationID == medication.id && event.profileID == medication.profileID-        && (try? scope.owner(event)) != nil && !event.isDeleted-        && !event.hasClockMismatch && event.timestamp <= now {+      for event in eventsByMedication[medication.id] ?? []+      where event.profileID == medication.profileID && !event.isDeleted+        && !event.hasClockMismatch && event.timestamp <= now+        && (try? scope.owner(event)) != nil {         var action = MedicationFollowupAction(           eventID: event.id, medicationID: medication.id, takenAt: event.timestamp,           configuration: value)
Meddy/Meddy/Services/PhoneCompanionService.swift Changed +7 / -1
diff --git a/Meddy/Meddy/Services/PhoneCompanionService.swift b/Meddy/Meddy/Services/PhoneCompanionService.swiftindex 5d0b424..bf4c125 100644--- a/Meddy/Meddy/Services/PhoneCompanionService.swift+++ b/Meddy/Meddy/Services/PhoneCompanionService.swift@@ -140,6 +140,7 @@ final class PhoneCompanionService {     do { try transport.publish(snapshot()) } catch { onError(error.localizedDescription) }   }   func snapshot() throws -> CompanionSnapshot {+    // Keep the index within this synchronous snapshot, never across a care mutation.     let scope = try ProfileAccess.ReadScope(context: context)     let service = RoutineSessionService(context: context)     let schedules = ScheduleService(context: context)@@ -149,6 +150,7 @@ final class PhoneCompanionService {     let events = scope.validated(try context.fetch(FetchDescriptor<Administration>()))     let treatments = scope.validated(try context.fetch(FetchDescriptor<Treatment>()))     let completions = scope.validated(try context.fetch(FetchDescriptor<TreatmentCompletion>()))+    var anchorsByOwner: [UUID: [WakeAnchor]] = [:]     let represented = runs.map {       ScheduledRunSnapshot(         id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,@@ -157,7 +159,11 @@ final class PhoneCompanionService {         status: SessionPhase(rawValue: $0.statusRaw) ?? .needsReview, isDeleted: $0.isDeleted)     }     let medicationValues = try medications.map { item in-      let schedule = try schedules.snapshot(item, scope: scope)+      let owner = try scope.owner(item)+      if anchorsByOwner[owner] == nil {+        anchorsByOwner[owner] = try WakeService(context: context).anchors(profileID: owner)+      }+      let schedule = try schedules.snapshot(item, scope: scope, wakeAnchors: anchorsByOwner[owner] ?? [])       var value = CompanionMedication(         id: item.id, name: item.name, purpose: item.purpose?.name, requirements: item.requirements,         dose: item.defaultDose, schedule: schedule,
Meddy/Meddy/Services/PhoneRoundAlertService.swift Changed +4 / -3
diff --git a/Meddy/Meddy/Services/PhoneRoundAlertService.swift b/Meddy/Meddy/Services/PhoneRoundAlertService.swiftindex 46ae8b7..71d372b 100644--- a/Meddy/Meddy/Services/PhoneRoundAlertService.swift+++ b/Meddy/Meddy/Services/PhoneRoundAlertService.swift@@ -145,6 +145,7 @@ final class PhoneRoundAlertService {   }    private func runningTimer(_ run: RoutineRun) -> TimerCheckpoint? {+    // Discovery only: this decode never authorizes an action or changes a saved checkpoint.     guard let data = run.timerCheckpointData,       let timer = try? JSONDecoder().decode(TimerCheckpoint.self, from: data),       timer.phase == .running@@ -197,11 +198,11 @@ final class PhoneRoundAlertService {     } catch { onError(error.localizedDescription) }   }   private func owns(_ run: RoutineRun) -> Bool {-    (try? ProfileAccess.owner(run, context: context)) != nil+    !run.isDeleted && run.statusRaw != "needsReview"+      && (run.executionDeviceID == nil || run.executionDeviceID == deviceID)+      && (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 {
Meddy/Meddy/Services/ReminderService.swift Changed +8 / -2
diff --git a/Meddy/Meddy/Services/ReminderService.swift b/Meddy/Meddy/Services/ReminderService.swiftindex c216836..3c22a0a 100644--- a/Meddy/Meddy/Services/ReminderService.swift+++ b/Meddy/Meddy/Services/ReminderService.swift@@ -401,8 +401,10 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate {   private func medicationPlans(     _ medications: [Medication], now: Date, scope: ProfileAccess.ReadScope   ) throws -> [PlannedReminder] {+    guard !medications.isEmpty else { return [] }     let planner = NotificationPlanner()     let schedules = ScheduleService(context: context)+    let wakes = WakeService(context: context)     var result: [PlannedReminder] = []     for medication in medications {       let administrations = (medication.administrations ?? []).map {@@ -413,7 +415,9 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate {           isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch,           wakeEventID: $0.wakeEventID)       }-      let base = try schedules.snapshot(medication, scope: scope)+      let owner = try scope.owner(medication)+      let base = try schedules.snapshot(+        medication, scope: scope, wakeAnchors: wakes.anchors(profileID: owner))       let variants: [MedicationScheduleSnapshot] =         base.mode == .afterWaking         ? (base.wakeAnchors ?? []).map { anchor in@@ -561,7 +565,9 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate {     } catch { self.error = error.localizedDescription }   } -  private func owned(_ reminder: PlannedReminder, target: any ProfileOwned, scope: ProfileAccess.ReadScope? = nil) throws+  private func owned(+    _ reminder: PlannedReminder, target: any ProfileOwned, scope: ProfileAccess.ReadScope? = nil+  ) throws     -> PlannedReminder {     var result = try scope.map { try $0.stamp(reminder, target: target) }       ?? ProfileAccess.stamp(reminder, target: target, context: context)
Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift Changed +47 / -0
diff --git a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swiftindex 41af6ee..bfd15d6 100644--- a/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift+++ b/Meddy/MeddyTests/MeddyPhoneRoundAlertTests.swift@@ -291,6 +291,53 @@ struct MeddyPhoneRoundAlertTests {     old.action()     #expect(old.cancelled && buzzes == 0 && scheduler.entries.count == 1)   }++  #if DEBUG || MEDDY_PERFORMANCE_TESTING+  @Test(arguments: [25, 100], [false, true])+  func nonRunningTimerHistoryDoesNotMultiplyOwnershipReads(history: Int, running: Bool) throws {+    let (store, run, service) = try fixture()+    let context = store.mainContext+    defer { MutationEffects.remove(context) }+    let routine = try #require(run.routine)+    let sample = ClockSample(wall: Date(), monotonic: 100, continuityID: "synthetic")+    let phases: [TimerPhase] = [.ready, .paused, .interrupted, .waiting, .completed, .ended]+    for index in 0..<history {+      let saved = RoutineRun(routine: routine)+      var timer = try TimerCheckpoint(rounds: 2, durationSeconds: 10)+      timer.phase = phases[index % phases.count]+      saved.timerCheckpointData = try JSONEncoder().encode(timer)+      context.insert(saved)+    }+    let corrupt = RoutineRun(routine: routine)+    corrupt.timerCheckpointData = Data()+    context.insert(corrupt)+    context.insert(RoutineRun(routine: routine))+    try context.save()+    if running {+      try service.changeTimer(run, actionID: UUID(), clock: sample, operation: .start)+    }+    let scheduler = SyntheticDeadlineScheduler()+    var buzzes = 0+    var awake = false+    let alerts = PhoneRoundAlertService(+      context: context, scheduler: scheduler, clock: { sample },+      feedback: { buzzes += 1 }, keepAwake: { awake = $0 })+    let rowCount = try ProfileMigration.rows(context).count+    var scans = 0+    var inspected = 0+    ProfileAccess.inspectedRows = { scans += 1; inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    alerts.setActive(true)+    alerts.refresh()+    // Only the running candidate/pending deadline may require fresh authorization.+    #expect(running ? (scans > 0 && scans <= 8) : scans == 0)+    #expect(inspected <= 8 * rowCount)+    #expect(scheduler.entries.count == (running ? 1 : 0))+    #expect(awake == running && buzzes == 0)+    #expect(!context.hasChanges)+    alerts.setActive(false)+  }+  #endif }  @MainActor
Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift Changed +4 / -0
diff --git a/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift b/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swiftindex 1bbe725..f81c581 100644--- a/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift+++ b/Meddy/MeddyTests/MeddyProfileAccessPerformanceTests.swift@@ -36,11 +36,15 @@ struct MeddyProfileAccessPerformanceTests {     let values: [any ProfileOwned] = [purpose, medication, administration, treatment, completion, routine, step, run]     for value in values {       #expect(try ProfileAccess.ReadScope(context: context).owner(value) == ProfileAccess.owner(value, context: context))+      #expect(try ProfileAccess.ReadScope(context: context).lifecycle(value) == ProfileAccess.lifecycle(value, context: context))+      #expect(try ProfileAccess.ReadScope(context: context).stamp(action, target: value)+        == ProfileAccess.stamp(action, target: value, context: context))       let collision = Medication(name: "Synthetic duplicate")       collision.id = value.id       context.insert(collision)       // Pending and saved duplicates must both remain unavailable, including cross-type IDs.       #expect(throws: ProfileError.self) { try ProfileAccess.ReadScope(context: context).owner(value) }+      #expect(throws: ProfileError.self) { try ProfileAccess.ReadScope(context: context).stamp(action, target: value) }       try context.save()       #expect(throws: ProfileError.self) { try ProfileAccess.owner(value, context: context) }       #expect(throws: ProfileError.self) { try ProfileAccess.ReadScope(context: context).owner(value) }
Meddy/MeddyTests/MeddyTakenLatencyTests.swift Changed +115 / -5
diff --git a/Meddy/MeddyTests/MeddyTakenLatencyTests.swift b/Meddy/MeddyTests/MeddyTakenLatencyTests.swiftindex 9c276e1..5da53ea 100644--- a/Meddy/MeddyTests/MeddyTakenLatencyTests.swift+++ b/Meddy/MeddyTests/MeddyTakenLatencyTests.swift@@ -109,20 +109,130 @@ struct MeddyTakenLatencyTests {     #expect(inspected <= 532)   } -  @Test func companionSnapshotDoesNotRevalidateWholeStoreForEveryHistoricalEvent() throws {-    let (store, _, _) = try fixture(history: 500, runs: 25)+  @Test(arguments: [25, 100])+  func companionSnapshotDoesNotRevalidateWholeStoreForEveryHistoricalEvent(runs: Int) throws {+    let (store, _, _) = try fixture(history: 500, runs: runs)     let context = store.mainContext     let companion = PhoneCompanionService(context: context)+    let rowCount = try ProfileMigration.rows(context).count     var inspected = 0-    ProfileAccess.inspectedRows = { inspected += $0 }+    var scans = 0+    ProfileAccess.inspectedRows = { inspected += $0; scans += 1 }     defer { ProfileAccess.inspectedRows = nil }     let start = ProcessInfo.processInfo.systemUptime     let snapshot = try companion.snapshot()     print("Synthetic conditional Watch snapshotMS=\((ProcessInfo.processInfo.systemUptime - start) * 1000) rows=\(inspected)")-    #expect(snapshot.appliedEventIDs.count == 500 && snapshot.runs.count == 26)+    #expect(snapshot.appliedEventIDs.count == 500 && snapshot.runs.count == runs + 1)     #expect(snapshot.eventOwners?.count == 500)-    #expect(inspected <= 120 * 532)+    // More saved runs may grow the rows, but must not add whole-store scans per run.+    #expect(scans <= 30 && inspected <= 30 * rowCount)+    #expect(!context.hasChanges)+  }++  @Test(arguments: [100, 500])+  func followupHistoryUsesOneFreshOwnershipScan(history: Int) throws {+    let (store, medication, _) = try fixture(history: history, runs: 0)+    let context = store.mainContext+    let now = Date()+    let configuration = MedicationFollowup(message: "Synthetic follow-up", delaySeconds: 600)+    try MedicationFollowupService.configure(medication, value: configuration)+    try context.save()+    let events = try context.fetch(FetchDescriptor<Administration>())+    let rowCount = try ProfileMigration.rows(context).count+    var scans = 0+    var inspected = 0+    ProfileAccess.inspectedRows = { scans += 1; inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    let actions = try MedicationFollowupService.actions(context: context, now: now)+    #expect(scans == 1 && inspected == rowCount)+    // Even elapsed historical actions remain available to validate delivered notifications.+    #expect(actions.count == history)+    for event in events {+      var expected = MedicationFollowupAction(+        eventID: event.id, medicationID: medication.id, takenAt: event.timestamp,+        configuration: configuration)+      expected.profileID = medication.profileID+      #expect(actions.contains(expected))+    }     #expect(!context.hasChanges)++    events[0].isDeleted = true+    events[1].hasClockMismatch = true+    events[2].timestamp = now.addingTimeInterval(60)+    events[3].profileID = UUID()+    try context.save()+    scans = 0+    let refreshed = try MedicationFollowupService.actions(context: context, now: now)+    #expect(scans == 1 && refreshed.count == history - 4)+    medication.isActive = false+    try context.save()+    #expect(try MedicationFollowupService.actions(context: context, now: now).isEmpty)+  }++  @Test(arguments: [2, 12])+  func medicationReminderPlanningSharesOwnershipReadsAndPreservesCapturedProfiles(count: Int) throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    defer { MutationEffects.remove(context) }+    let profile = CareProfile(displayName: "Synthetic owner")+    context.insert(profile)+    let now = try #require(Calendar.current.date(from: DateComponents(+      year: 2026, month: 11, day: 13, hour: 12)))+    var medications: [Medication] = []+    for index in 0..<count {+      let medication = Medication(name: "Synthetic reminder \(index)")+      medication.profileID = index.isMultiple(of: 2) ? ProfileIdentity.me : profile.id+      medication.scheduleTypeRaw = MedicationScheduleType.fixedTimes.rawValue+      medication.scheduleGenerationID = UUID()+      medication.scheduleStartedAt = now.addingTimeInterval(-86400)+      medication.fixedTimesData = try JSONEncoder().encode([13 * 60])+      medication.remindersEnabled = true+      context.insert(medication)+      medications.append(medication)+      for day in 3...22 {+        let action = AdministrationAction(+          eventID: UUID(), medicationID: medication.id,+          timestamp: now.addingTimeInterval(-Double(day) * 86400), source: .phone,+          dose: .unknown, scheduleTypeAtRecording: .fixedTimes,+          scheduleGenerationID: medication.scheduleGenerationID)+        context.insert(Administration(action: action, medication: medication))+      }+    }+    try context.save()+    let expected = try medications.map { try freshMedicationReminder($0, now: now, context: context) }+    let rowCount = try ProfileMigration.rows(context).count+    let reminders = ReminderService(context: context, registerDelegate: false)+    var scans = 0+    var inspected = 0+    ProfileAccess.inspectedRows = { scans += 1; inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    let plans = try reminders.plan(now: now)+    #expect(plans.count == count && expected.allSatisfy { plans.contains($0) })+    // List validation owns one index; follow-ups and medication planning now share another.+    #expect(scans == 2 && inspected == 2 * rowCount)+    #expect(!context.hasChanges)+    profile.archivedAt = now+    try context.save()+    let afterArchive = try reminders.plan(now: now)+    #expect(afterArchive.count == count / 2)+    #expect(afterArchive.allSatisfy { $0.profileID == ProfileIdentity.me })+  }++  private func freshMedicationReminder(_ medication: Medication, now: Date, context: ModelContext)+    throws -> PlannedReminder {+    let snapshot = try ScheduleService(context: context).snapshot(medication)+    let base = try #require(NotificationPlanner().medication(+      snapshot, details: .init(name: medication.name, dose: medication.defaultDose,+        reminders: medication.remindersEnabled, active: medication.isActive),+      administrations: [], now: now, calendar: .current))+    var result = try ProfileAccess.stamp(base, target: medication, context: context)+    if case .medication(let action) = result.payload, medication.profileID != ProfileIdentity.me {+      result.payload = .medication(action: try ProfileAccess.stamp(action, target: medication, context: context))+    }+    let owner = try ProfileAccess.owner(medication, context: context)+    result.title = (try ProfileAccess.profile(owner, context: context)?.label ?? "Me") + " · " + result.title+    if owner != ProfileIdentity.me { result.id = "meddy.profile.\(owner)." + result.id }+    return result   } } #endif
Meddy/MeddyTests/MeddyTodaySnapshotTests.swift Changed +79 / -0
diff --git a/Meddy/MeddyTests/MeddyTodaySnapshotTests.swift b/Meddy/MeddyTests/MeddyTodaySnapshotTests.swiftnew file mode 100644index 0000000..9129de4--- /dev/null+++ b/Meddy/MeddyTests/MeddyTodaySnapshotTests.swift@@ -0,0 +1,79 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++#if DEBUG || MEDDY_PERFORMANCE_TESTING+@MainActor+struct MeddyTodaySnapshotTests {+  @Test func allProfilePresentationUsesOneOwnershipScanAndRefreshesAfterCareChanges() throws {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let context = store.mainContext+    let now = try #require(Calendar.current.date(from: DateComponents(+      year: 2026, month: 11, day: 13, hour: 12)))+    var profiles: [CareProfile] = []+    var medications: [Medication] = []+    for index in 0..<3 {+      let profile = CareProfile(displayName: "Synthetic owner")+      let medication = Medication(name: "Synthetic medicine \(index)")+      medication.profileID = profile.id+      medication.scheduleTypeRaw = MedicationScheduleType.fixedTimes.rawValue+      medication.scheduleGenerationID = UUID()+      medication.scheduleStartedAt = now.addingTimeInterval(-86400)+      medication.fixedTimesData = try JSONEncoder().encode([11 * 60])+      context.insert(profile)+      context.insert(medication)+      profiles.append(profile)+      medications.append(medication)+      for day in 1...100 {+        var action = AdministrationAction(+          eventID: UUID(), medicationID: medication.id,+          timestamp: now.addingTimeInterval(-Double(day) * 86400), source: .phone,+          dose: .unknown, scheduleTypeAtRecording: .fixedTimes,+          scheduleGenerationID: medication.scheduleGenerationID)+        action.profileID = profile.id+        action.ownershipVersion = ProfileIdentity.ownershipVersion+        action.profileLifecycleID = profile.lifecycleID+        context.insert(Administration(action: action, medication: medication))+      }+    }+    try context.save()+    let events = try context.fetch(FetchDescriptor<Administration>())+    let expectedRows = try ProfileMigration.rows(context).count+    let expectedResults = try medications.map {+      try MedicationPresentation.result($0, now: now, context: context)+    }+    var scans = 0+    var inspected = 0+    ProfileAccess.inspectedRows = { scans += 1; inspected += $0 }+    defer { ProfileAccess.inspectedRows = nil }+    let snapshot = TodayMedicationSnapshot(+      medications: medications, events: events, now: now, context: context)+    #expect(scans == 1 && inspected == expectedRows)+    #expect(snapshot.medications.count == 3 && snapshot.due.count == 3)+    #expect(snapshot.events.isEmpty)+    for (index, medication) in medications.enumerated() {+      #expect(snapshot.results[medication.id] == expectedResults[index])+    }+    #expect(!context.hasChanges)+    ProfileAccess.inspectedRows = nil++    let recorded = try TodayMedicationAction.take([medications[0]], at: now, context: context)+    let afterTake = TodayMedicationSnapshot(+      medications: medications, events: try context.fetch(FetchDescriptor<Administration>()),+      now: now, context: context)+    #expect(afterTake.events.map(\.id) == recorded.map(\.id))+    #expect(afterTake.results[medications[0].id]?.takenToday == 1)+    try TodayMedicationAction.undo(recorded, context: context)+    try ProfileService(context: context).setArchived(profiles[1], true)+    let afterUndoAndArchive = TodayMedicationSnapshot(+      medications: medications, events: try context.fetch(FetchDescriptor<Administration>()),+      now: now, context: context)+    #expect(afterUndoAndArchive.events.isEmpty)+    #expect(afterUndoAndArchive.results[medications[0].id]?.takenToday == 0)+    #expect(!afterUndoAndArchive.medications.contains { $0.id == medications[1].id })+    #expect(afterUndoAndArchive.due.count == 2)+  }+}+#endif
Meddy/MeddyUITests/MeddyPhotoUITests.swift Changed +11 / -3
diff --git a/Meddy/MeddyUITests/MeddyPhotoUITests.swift b/Meddy/MeddyUITests/MeddyPhotoUITests.swiftindex 653f67b..314d376 100644--- a/Meddy/MeddyUITests/MeddyPhotoUITests.swift+++ b/Meddy/MeddyUITests/MeddyPhotoUITests.swift@@ -99,7 +99,7 @@ final class MeddyPhotoUITests: XCTestCase {     let dueVitamin = app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Vitamin D3")).firstMatch     XCTAssertEqual(dueVitamin.value as? String, "Recognition photo attached")     capture("today-photos-" + appearance, app: app)-    let tile = app.buttons["Log dose for Paracetamol"]+    let tile = app.buttons["Log dose for Paracetamol, Me"]     reveal(tile, app: app)     XCTAssertEqual(tile.value as? String, "Recognition photo attached")     capture("as-needed-photos-" + appearance, app: app)@@ -146,9 +146,17 @@ final class MeddyPhotoUITests: XCTestCase {     XCTAssertTrue(photo.waitForExistence(timeout: 3))     reveal(app.buttons["Log dose"], app: app)     app.buttons["Log dose"].tap()-    XCTAssertTrue(photo.waitForExistence(timeout: 3))-    XCTAssertEqual(photo.frame.width, 160, accuracy: 1)+    XCTAssertTrue(app.navigationBars["Log Paracetamol"].waitForExistence(timeout: 3))+    // The detail photo is a button behind this sheet; assert the sheet's image instead.+    let dosePhoto = app.images.matching(NSPredicate(+      format: "identifier == %@ AND label == %@",+      "medicationRecognitionPhoto", "Recognition photo for Paracetamol")).firstMatch+    XCTAssertTrue(dosePhoto.waitForExistence(timeout: 3))+    XCTAssertTrue(dosePhoto.isHittable)     capture("dose-photo-" + appearance, app: app)+    // Accessibility reports the scaled 4:3 bitmap width, not the circular clipping width.+    // Height remains the requested diameter and distinguishes the 220-point detail image.+    XCTAssertEqual(dosePhoto.frame.height, 160, accuracy: 1)     app.buttons["Cancel"].tap()     XCTAssertFalse(app.buttons["Change recognition photo"].exists)     XCTAssertFalse(app.buttons["Add recognition photo"].exists)
Meddy/MeddyUITests/MeddyProfileUITests.swift Changed +13 / -1
diff --git a/Meddy/MeddyUITests/MeddyProfileUITests.swift b/Meddy/MeddyUITests/MeddyProfileUITests.swiftindex 681db3f..9a45bd6 100644--- a/Meddy/MeddyUITests/MeddyProfileUITests.swift+++ b/Meddy/MeddyUITests/MeddyProfileUITests.swift@@ -38,7 +38,11 @@ final class MeddyProfileUITests: XCTestCase {     add("Synthetic Beta")     app.navigationBars["Care profiles"].buttons["Done"].tap()     app.navigationBars["Profiles"].buttons["Done"].tap()+    XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine"))+      .firstMatch.waitForExistence(timeout: 3))+    app.tabBars.buttons["Medications"].tap()     XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists)+    app.tabBars.buttons["Today"].tap()     picker.tap()     app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Synthetic Alpha")).firstMatch.tap()     XCTAssertTrue(@@ -62,15 +66,23 @@ final class MeddyProfileUITests: XCTestCase {     app.navigationBars["Care profiles"].buttons["Done"].tap()     app.navigationBars["Profiles"].buttons["Done"].tap()     XCTAssertTrue(picker.label.contains("Synthetic Renamed"))-    XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists)+    XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine"))+      .firstMatch.waitForExistence(timeout: 3))     picker.tap()     app.buttons.matching(NSPredicate(       format: "identifier BEGINSWITH %@ AND label == %@", "careProfile_", "Me")     ).firstMatch.tap()+    XCTAssertTrue(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine"))+      .firstMatch.waitForExistence(timeout: 3))+    app.tabBars.buttons["Medications"].tap()     XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists)+    app.tabBars.buttons["Today"].tap()     app.terminate()     app.launch()     XCTAssertTrue(app.buttons["careProfilePicker"].waitForExistence(timeout: 8))     XCTAssertTrue(app.buttons["careProfilePicker"].label.contains("Me"))+    // MEDDY_TESTING uses a new in-memory store on launch; this checks the default profile,+    // not persistence. Cross-profile Today visibility is verified before termination above.+    XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic same medicine")).firstMatch.exists)   } }

Docs (4)

CHANGELOG.md Changed +5 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc0269a..582a947 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ - T2460: Record approved requirements/design and implementation tasks for small and medium next-medication widgets across all care profiles, including privacy, expiry and read-only navigation.  ### Changed+- Show all unarchived profiles’ medications and Taken history on iPhone Today, with owner labels and per-profile Take buttons; keep Medications and Routines scoped to the selected profile. - T2504: Show singular/plural schedule counts for fixed-times and spread-through-day in Share for Appointment and its Markdown export, using actual schedule frequency and preserving other labels. - T2496: Add an iPhone Restart routine action that starts a fresh full timer attempt while retaining history and completed care. - Rebase account migration onto current `origin/main`, retaining backup/restore, widgets, medication classification and prescription URLs; migrate widget bundle/App Group identifiers to the new family.@@ -17,6 +18,10 @@ - Restore medication recognition photos throughout the redesigned iPhone care screens, bring the detail image and Add/Replace/Remove editor controls forward, and retain existing photo storage and Save/Cancel behavior.  ### Fixed+- Reuse one synchronous ownership index for medication reminder schedules and captured-profile notification stamps, ending the scope before routine schedule activation or asynchronous delivery.+- Share one ownership index per medication follow-up read and skip non-running timer history before foreground deadline validation, avoiding repeated whole-store scans during startup while preserving notification history and active-timer checks.+- Reuse one ownership index and medication schedule per Watch snapshot, removing repeated whole-store reads for each saved routine during startup synchronization.+- Build one fresh Today medication snapshot per render and share its ownership index, schedule results and history across profile cards and sections instead of repeating whole-store reads. - T2503: Reduce residual Taken work by sharing operation-local medication ownership/schedule reads in notification planning, Watch snapshots and Today rendering, preserving fresh action checks and save-before-success. - Reduce routine-action latency from retained timers by skipping inactive alert discovery and sharing read-only ownership lookups during companion projection, preserving pending alerts and save-before-feedback ordering. - T2495: Show Tomorrow instead of a clock-only next dose across phone and Watch, including Today’s 30-minute due window across midnight, retaining the exact accessible due time and existing schedules.
docs/meddy-dependant-profile-design.md Changed +1 / -1
diff --git a/docs/meddy-dependant-profile-design.md b/docs/meddy-dependant-profile-design.mdindex 1537a2b..9135dfc 100644--- a/docs/meddy-dependant-profile-design.md+++ b/docs/meddy-dependant-profile-design.md@@ -8,7 +8,7 @@ The user has clarified that Meddy has one user, has been used only since last ni  **Me** is the fixed self identity, first in the list and selected on each phone/Watch launch. Dependants have immutable UUIDs and optional display names. Rename never changes ownership. Repeated or absent names are allowed; unnamed profiles get a neutral short-ID label. No DOB, age, dosing inference, clinical guidance or additional Apple account is introduced. These are care groups inside this user's private app, not accounts or sharing permissions. -Add, rename, select and reversibly archive/restore profiles. Switching changes the visible lists, editors, history, PRN comparisons, photos and consultation export. Notifications continue for all unarchived profiles. A notification or offline Watch action always records for its captured owner, regardless of current selection. Show that owner in notifications, session context and exports. Do not transfer an existing medication, treatment, routine or actual history between people.+Add, rename, select and reversibly archive/restore profiles. Switching scopes the Medications and Routines tabs, editors, history details, PRN comparisons, photos and consultation export. The iPhone Today medication overview always includes all unarchived profiles, independently of selection, with owner labels and separate per-owner Take buttons; its Taken history includes those profiles too. Today routine sections remain scoped to the selected profile. Notifications continue for all unarchived profiles. A notification or offline Watch action always records for its captured owner, regardless of current selection. Show that owner in notifications, session context and exports. Do not transfer an existing medication, treatment, routine or actual history between people.  ## Small persistence change 
docs/meddy-design.md Changed +2 / -0
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex cd55199..cc9b614 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -796,6 +796,8 @@ These rows have no due label, progress target, completion checkmark, or snooze c  Include as-needed events in a **Taken today** chronological history alongside scheduled administrations, showing each actual timestamp and the recorded dose when present. This is an event list, not an adherence score. Tapping an event opens its history details for correction. Include routine-linked administrations once with their session/step context. Show treatment completions and timed runs in routine activity, not as drug doses; the group summary is a navigation/aggregation view, not an additional counted action. +The iPhone Today medication overview includes all unarchived care profiles regardless of the selected profile. Due/next, schedule-attention, As needed and Taken entries identify their owner, and batch Take actions stay within one owner. An In routines list also shows active routine-managed medications for every profile, linking to existing details without adding standalone due/Take actions. Medication detail/edit actions retain the target owner. Routine sections and the separate Medications/Routines tabs remain selected-profile views. Archived or invalid ownership stays excluded by existing validation.+ ### 10.2 Medications tab  Group active medications into collapsible sections by `Purpose`.
docs/meddy-implementation-plan.md Changed +36 / -0
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex e3c2af1..e262d6c 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -8,6 +8,42 @@ > they do not establish provisioning or data migration for the new identity.  +## PR integration (13 November 2026)++The owner requested a PR and the pr-pilot review workflow, ending the earlier test deferral. Integrated current main (968f0c6), which already contains overlapping operation-local projections, next-day dose labels and timer restart. Reused main's ownership APIs and notification read scope, retained all-profile Today and grouped follow-up history, and preserved next-day labels/accessibility. Today Take recalculates current due targets for the captured owner rather than relying on a rendered snapshot. Updated the exact scan-count regression to reflect main sharing follow-up and medication planning in one scope. The installed bc29799 build is unchanged; this integration is not installed. Residual first-scroll stutter is explicitly out of scope. Required publication gates and independent review are pending.++## Remaining medication reminder planning (13 November 2026)++After installing fe6e5dd, the owner reports a clear improvement but one to two seconds before interactions respond and another one to two seconds of lag. The earlier trace attributed approximately 1.09 seconds of sampled main-thread weight to medication reminder planning, including 1.01 seconds in ownership reads; these overlapping samples are not a measurement of the newly installed build. That path still used fresh whole-store validation for each medication schedule and each captured-profile notification stamp.++Medication reminder planning now shares one synchronous read index across those schedule and stamp reads. The index is created and discarded entirely within the medication helper, before subsequent routine planning can activate pending schedules and save. Other reminder types and mutation authorization retain their existing fresh context validation. Regression source compares generated reminders against fresh-context planning/stamping across Me and a dependant, checks a fixed scan count with 2/12 medications and accumulated history, and checks fresh exclusion after archive. Source review, strict lint (195 files, zero violations) and whitespace checks pass. Tests remain deferred; no new profile, build or installation was performed. Actual improvement from this additional change remains unmeasured.++## Profiled startup follow-up (13 November 2026)++A user-authorized 15-second Time Profiler capture of the installed e28edc9 Release build reproduced four main-thread hangs (3.29, 2.68, 0.67 and 2.97 seconds). Only timing and call stacks were inspected; the trace remains local. Reminder reconciliation dominated two intervals, with follow-up generation repeatedly fetching the full ownership graph per historical administration. Foreground timer discovery dominated another interval, validating saved non-running timers before checking their phase. Today rendering was comparatively small; the conditional Watch publication path was not the observed hotspot. Instrumented timings are not uninstrumented launch latency.++Follow-up generation now builds one fresh synchronous ownership index and groups events by medication without dropping elapsed history needed for delivered-notification validation. Timer discovery checks the decoded running phase before full authorization; pending-deadline reconciliation, running-candidate validation, boundary writes and feedback ordering remain unchanged. No index survives a mutation or suspension.++Synthetic regression source checks one scan across 100/500 follow-up events, fresh filtering after corrections, and bounded timer-discovery work across 25/100 saved runs with/without an active timer. Source review, strict lint (195 files, zero violations) and whitespace checks pass. Tests remain unrun by instruction. Runtime improvement is not yet measured, and this fix has not been built or installed.++## Startup Watch snapshot follow-up (13 November 2026)++The owner reports improved interactions after loading but at least five seconds of unresponsive startup. Source inspection found synchronous Watch publication on activation: each saved run's definition/progress loaded the entire ownership graph again, with another scan for dependant lifecycle checks. Snapshot construction now shares one fresh synchronous read index across its row filters, medication schedule/lifecycle reads and saved-run serialization. Medication next-time evaluation reuses the same schedule snapshot. Existing per-action mutation validation, archived-owner handling, transport behavior and startup reminder timing are unchanged.++This removes a source-confirmed startup cost, but no trace establishes that it accounts for the full reported pause. Other startup work, including reminder planning, remains. The existing synthetic snapshot regression now checks 25 and 100 saved runs with a fixed scan-count bound; indexed lifecycle parity is also covered in source. Tests remain unrun by instruction. Strict lint and whitespace pass; no new build, profiling, installation or live-data access was performed.++## Today responsiveness follow-up (13 November 2026)++After installing the all-profile change, the owner reported slow interactions. Source inspection found that each profile's due card recomputed the full all-profile schedule twice, while other Today sections repeated the same calculation and ownership reads. Today now constructs one fresh synchronous presentation snapshot and reuses its validated medication/history arrays, schedule results and due/later partitions. One operation-local ownership index is shared across that snapshot; wake anchors are read once per owner. Mutation services still perform their existing fresh validation, and no scope is cached between renders or mutations.++Added an isolated regression test for a single whole-store ownership scan across three profiles and 300 historical events, matching schedule results and fresh Take/Undo/archive reads. It has not been run: the owner's instruction to defer tests remains in force. Static lint and whitespace checks pass; runtime performance improvement remains unmeasured. No replacement build has been installed.++## All-profile Today medications (13 November 2026)++The phone Today medication overview now reads all valid, unarchived profiles rather than the selected profile. Owner labels distinguish due/next, schedule-attention, As needed and Taken entries; Take buttons batch only one owner's medications. An In routines list covers active routine-managed medications across profiles without changing routine scheduling or adding standalone Take buttons. Detail navigation keeps the medication owner's context. Medications/Routines tabs and Today routines remain selected-profile views. The existing profile UI journey now expects medication visibility on Today across profile switches while preserving isolation on Medications.++Validation: strict SwiftLint and whitespace checks passed. Builds, automated tests and simulator/manual UI checks were deliberately left for later at the owner's request. No installation, live-data access, publication or merge.+ ## Residual Taken latency (T2503)  Share operation-local read-only ownership/schedule projections in medication notification planning, Watch snapshots and Today rendering. Keep projections within one synchronous operation; finish medication notification projection before pending routine activation can save. Today retains waiting-for-wake attention results and recomputes current targets at Take. Fresh mutation authorization and save-before-success remain unchanged.

Things to double-check

Not merged or installed

This review does not authorise merge. The integrated branch has not been installed on the phone.