Scoped medication projections and schedule-count wording; signed Release preparation without installation.
Ready for review
Required native project gates passed. Four independent reviews found no unresolved source issues after the attention-section correction. No deployment or merge performed.
ffd63ff T-2503: Add T2504 appointment schedule counts 767388e T-2503: Reuse scoped medication projections after Taken 73b80c4 T-2503: Add residual Taken latency regression checkpoint Meddy now reuses checks while preparing notifications, Watch information and Today. Previously each medication could cause another scan of the same store. A projection is temporary display information; saving a dose still requires fresh checks and a successful save.
The synthetic 25-medication notification benchmark fell from 2.82 seconds to 82 milliseconds. Actual phone responsiveness remains unmeasured.
Appointment sharing now includes how many scheduled times are configured, with singular/plural wording. The same text appears on screen and in the Markdown export.
ReadScope supplies one inventory for a synchronous operation. Schedule snapshots are evaluated once per medication; Today shares a complete render projection including nil-next attention states. Take recomputes current due targets.
Medication reminder projection ends before pending routine activation can save. This avoids a persistent cache and its invalidation requirements while leaving existing delivery and mutation behavior intact.
A consultation-only formatter delegates the existing schedule label, adding a positive dosesPerDay target for spread schedules or a unique valid clock-minute count for fixed schedules. Other modes and the general list label stay unchanged.
Scoped reads preserve pending-object and cross-entity ambiguity, owner, lifecycle and link checks. Static mutation authorization remains fresh. Scoped payload stamping copies existing fields and retains Me/dependant handling. No scope crosses await or mutation.
Deterministic row-bound assertions establish reduced amplification independently of wall-clock load. Wake fetching, routine work, transport, CloudKit and actual frame latency remain outside the measured improvement.
The additional formatter performs no model writes or store reads. It ignores irrelevant fields, preserves routine ownership precedence and wake offsets, and omits a count for missing/malformed values. The Release artifact source manifest is checked against the final commit; temporary packaging only omits embedded Watch content.
Meddy/Meddy/Services/ReminderService.swift
Why it matters. Removes repeated store reads without keeping stale authorization.
What to look at. medicationReminders / medicationPlans / owned
Meddy/Meddy/Services/PhoneCompanionService.swift
Why it matters. Avoids repeated ownership inventory and schedule construction.
What to look at. snapshot
Meddy/Meddy/ContentView.swift
Why it matters. Retains attention entries without a next date and refreshes action targets.
What to look at. today / scheduleAttention / dueHero
Meddy/MeddyTests/MeddyMedicationProjectionPerformanceTests.swift
Why it matters. Detects repeated scans deterministically while checking output and no writes.
What to look at. five test declarations
Meddy/Meddy/Features/MedicationScheduleFields.swift
Why it matters. Makes configured frequency visible without changing schedules or other labels.
What to look at. consultationScheduleLabel and consultationExport
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Today attention projection | Attention rendering still repeated single-medication ownership scans. | Share the full render projection, including nil-next entries, and cover wake refresh. |
Source: local run at 2026-10-29T05:09:33.357626+00:00 · snapshot ffd63ffc0559070b6705f4f655258b5ac3accd2f
Baseline: none
Execution: passed · JUnit: 3 files · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 424 passed · 0 failed · 0 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
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 1d6790d.
20 files: 13 code · 7 docs. Click to expand.
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex b4a3b9a..1459340 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -40,12 +40,7 @@ struct ContentView: View { return ProfileAccess.visible(current, for: selectedProfileID, context: context) } private var scheduled: [(Medication, Date)] {- active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }.compactMap { medication in- guard- let next = try? MedicationPresentation.result(medication, now: now, context: context).next- else { return nil }- return (medication, next)- }.sorted { $0.1 == $1.1 ? $0.0.name < $1.0.name : $0.1 < $1.1 }+ MedicationPresentation.scheduled(active, now: now, context: context) } private var due: [Medication] { scheduled.filter { $0.1 <= now.addingTimeInterval(1800) }.map(\.0)@@ -88,7 +83,11 @@ struct ContentView: View { } private var today: some View {- ScrollView {+ 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)+ return ScrollView { VStack(alignment: .leading, spacing: 12) { MeddyScreenHeader( title: "Today",@@ -104,8 +103,8 @@ struct ContentView: View { } .foregroundStyle(MeddyStyle.warning).meddyCard(radius: 20, padding: 16) }- dueHero- scheduleAttention+ dueHero(scheduled: scheduled, due: due, now: now)+ scheduleAttention(projection) TodayRoutineSections() if scheduled.contains(where: { $0.1 > now.addingTimeInterval(1800) }) { MeddySectionLabel(text: "Later").padding(.horizontal, 8)@@ -167,10 +166,11 @@ struct ContentView: View { .overlay(alignment: .bottom) { undoToast } } - private var scheduleAttention: some View {- ForEach(active.filter { !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw) }) { medication in- if let result = try? MedicationPresentation.result(medication, now: now, context: context),- result.next == nil {+ 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 { if result.cannotFitInWindow || medication.scheduleTypeRaw == "afterWaking" && result.takenToday == 0 { NavigationLink {@@ -194,7 +194,7 @@ struct ContentView: View { } } - private var dueHero: some View {+ private func dueHero(scheduled: [(Medication, Date)], due: [Medication], now: Date) -> some View { VStack(alignment: .leading, spacing: 16) { if due.isEmpty { Text("All caught up").font(.system(.title2, weight: .bold))@@ -242,7 +242,7 @@ struct ContentView: View { .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(due, at: Date(), context: context)) } catch {+ do { showUndo(try TodayMedicationAction.take(self.due, at: Date(), context: context)) } catch { self.error = error.localizedDescription } }.buttonStyle(MeddyPrimaryButtonStyle()).accessibilityIdentifier("takeDueMedications")
diff --git a/Meddy/Meddy/Features/MedicationScheduleFields.swift b/Meddy/Meddy/Features/MedicationScheduleFields.swiftindex 875a051..c661c17 100644--- a/Meddy/Meddy/Features/MedicationScheduleFields.swift+++ b/Meddy/Meddy/Features/MedicationScheduleFields.swift@@ -134,7 +134,11 @@ 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(+ return result(medication, snapshot: snapshot, now: now)+ }++ static func result(_ medication: Medication, snapshot: MedicationScheduleSnapshot, now: Date) -> MedicationScheduleResult {+ MedicationScheduleEngine().evaluate( snapshot, administrations: (medication.administrations ?? []).map { .init(@@ -146,6 +150,32 @@ enum MedicationPresentation { }, now: now, calendar: .current) } + struct ScheduleProjection {+ let results: [(medication: Medication, result: MedicationScheduleResult)]+ var scheduled: [(Medication, Date)] {+ results.compactMap { entry in entry.result.next.map { (entry.medication, $0) } }+ .sorted { $0.1 == $1.1 ? $0.0.name < $1.0.name : $0.1 < $1.1 }+ }+ }++ static func projection(_ medications: [Medication], now: Date, context: ModelContext) -> ScheduleProjection {+ guard !medications.isEmpty, let scope = try? ProfileAccess.ReadScope(context: context) else {+ return ScheduleProjection(results: [])+ }+ let schedules = ScheduleService(context: context)+ let results: [(Medication, MedicationScheduleResult)] = medications.filter {+ $0.isActive && !["asNeeded", "routineManaged"].contains($0.scheduleTypeRaw)+ }.compactMap { medication in+ guard let snapshot = try? schedules.snapshot(medication, scope: scope) else { return nil }+ return (medication, result(medication, snapshot: snapshot, now: now))+ }+ return ScheduleProjection(results: results)+ }++ static func scheduled(_ medications: [Medication], now: Date, context: ModelContext) -> [(Medication, Date)] {+ projection(medications, now: now, context: context).scheduled+ }+ static func scheduleLabel(_ medication: Medication, routines: [Routine]) -> String { guard let id = medication.managedByRoutineID else { if medication.scheduleTypeRaw == "afterWaking", let minutes = medication.wakeOffsetMinutes {@@ -163,6 +193,23 @@ enum MedicationPresentation { return label } + static func consultationScheduleLabel(_ medication: Medication, routines: [Routine]) -> String {+ let label = scheduleLabel(medication, routines: routines)+ guard medication.managedByRoutineID == nil else { return label }+ let count: Int?+ switch MedicationScheduleType(rawValue: medication.scheduleTypeRaw) {+ case .spreadThroughDay:+ count = medication.dosesPerDay+ case .fixedTimes:+ let minutes = medication.fixedTimesData.flatMap { try? JSONDecoder().decode([Int].self, from: $0) } ?? []+ count = Set(minutes.filter { (0..<1440).contains($0) }).count+ default:+ count = nil+ }+ guard let count, count > 0 else { return label }+ return label + " · \(count) " + (count == 1 ? "time" : "times")+ }+ static func consultation( _ medications: [Medication], routines: [Routine] = [], preparedAt: Date = Date(), timeZone: TimeZone = .current@@ -184,7 +231,7 @@ enum MedicationPresentation { 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), prescription: PrescriptionService.details(item))+ schedule: consultationScheduleLabel(item, routines: routines), prescription: PrescriptionService.details(item)) } return ConsultationMarkdown.make( active, preparedAt: preparedAt, timeZone: timeZone, profileID: profileID,
diff --git a/Meddy/Meddy/Features/TodayRoutineSections.swift b/Meddy/Meddy/Features/TodayRoutineSections.swiftindex e7fe0bc..f2340de 100644--- a/Meddy/Meddy/Features/TodayRoutineSections.swift+++ b/Meddy/Meddy/Features/TodayRoutineSections.swift@@ -181,7 +181,7 @@ struct CurrentMedicationsView: View { Text("Requirements").font(.caption) Text(item.requirements) }- Text(MedicationPresentation.scheduleLabel(item, routines: routines)).foregroundStyle(+ Text(MedicationPresentation.consultationScheduleLabel(item, routines: routines)).foregroundStyle( .secondary) if let repeats = item.repeatsLeft, repeats > 0 { Text("Repeats left: \(repeats)")
diff --git a/Meddy/Meddy/Services/AsNeededLimitService.swift b/Meddy/Meddy/Services/AsNeededLimitService.swiftindex 2c7f7ca..89da1bd 100644--- a/Meddy/Meddy/Services/AsNeededLimitService.swift+++ b/Meddy/Meddy/Services/AsNeededLimitService.swift@@ -31,10 +31,11 @@ final class AsNeededLimitService { MutationEffects.saved(context) } func check(- _ medication: Medication, proposedDose: RecordedDoseSnapshot? = nil, now: Date = Date()+ _ medication: Medication, proposedDose: RecordedDoseSnapshot? = nil, now: Date = Date(),+ readScope: ProfileAccess.ReadScope? = nil ) -> DoseLimitCheck { do {- let scope = try ProfileAccess.ReadScope(context: context)+ let scope = try readScope ?? ProfileAccess.ReadScope(context: context) let owner = try scope.owner(medication) let rules = try limits(medication) // Fetch canonical rows: relationship caches can retain pre-save tombstone values.
diff --git a/Meddy/Meddy/Services/MedicationFollowupService.swift b/Meddy/Meddy/Services/MedicationFollowupService.swiftindex 9991b04..d252470 100644--- a/Meddy/Meddy/Services/MedicationFollowupService.swift+++ b/Meddy/Meddy/Services/MedicationFollowupService.swift@@ -20,15 +20,19 @@ enum MedicationFollowupService { } // Canonical rows cover phone, Watch, notifications and routines, without schedule/day filtering. static func actions(context: ModelContext, now: Date) throws -> [MedicationFollowupAction] {+ try actions(context: context, now: now, scope: ProfileAccess.ReadScope(context: context))+ }+ static func actions(context: ModelContext, now: Date, scope: ProfileAccess.ReadScope) 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 {+ 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? ProfileAccess.owner(event, context: context)) != nil && !event.isDeleted+ && (try? scope.owner(event)) != nil && !event.isDeleted && !event.hasClockMismatch && event.timestamp <= now { var action = MedicationFollowupAction( eventID: event.id, medicationID: medication.id, takenAt: event.timestamp,
diff --git a/Meddy/Meddy/Services/PhoneCompanionService.swift b/Meddy/Meddy/Services/PhoneCompanionService.swiftindex c9780a3..5d0b424 100644--- a/Meddy/Meddy/Services/PhoneCompanionService.swift+++ b/Meddy/Meddy/Services/PhoneCompanionService.swift@@ -140,14 +140,15 @@ final class PhoneCompanionService { do { try transport.publish(snapshot()) } catch { onError(error.localizedDescription) } } func snapshot() throws -> CompanionSnapshot {+ let scope = try ProfileAccess.ReadScope(context: context) let service = RoutineSessionService(context: context) let schedules = ScheduleService(context: context)- let medications = ProfileAccess.validated(try context.fetch(FetchDescriptor<Medication>()), context: context)- let routines = ProfileAccess.validated(try context.fetch(FetchDescriptor<Routine>()), context: context)- let runs = ProfileAccess.validated(try context.fetch(FetchDescriptor<RoutineRun>()), context: context)- let events = ProfileAccess.validated(try context.fetch(FetchDescriptor<Administration>()), context: context)- let treatments = ProfileAccess.validated(try context.fetch(FetchDescriptor<Treatment>()), context: context)- let completions = ProfileAccess.validated(try context.fetch(FetchDescriptor<TreatmentCompletion>()), context: context)+ let medications = scope.validated(try context.fetch(FetchDescriptor<Medication>()))+ let routines = scope.validated(try context.fetch(FetchDescriptor<Routine>()))+ let runs = scope.validated(try context.fetch(FetchDescriptor<RoutineRun>()))+ 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>())) let represented = runs.map { ScheduledRunSnapshot( id: $0.id, routineID: $0.routineID, occurrenceKey: $0.occurrenceKey, slotID: $0.slotID,@@ -156,16 +157,17 @@ 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) 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,+ dose: item.defaultDose, schedule: schedule,+ next: MedicationPresentation.result(item, snapshot: schedule, now: Date()).next, lastTaken: item.visibleAdministrations.first?.timestamp, active: item.isActive, doseLimitCheck: item.scheduleTypeRaw == "asNeeded"- ? AsNeededLimitService(context: context).check(item) : nil)+ ? AsNeededLimitService(context: context).check(item, readScope: scope) : nil) value.profileID = item.profileID value.ownershipVersion = item.ownershipVersion- value.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context)+ value.profileLifecycleID = try scope.lifecycle(item) return value } let definitions = try routines.filter(\.isActive).map { item in@@ -178,8 +180,7 @@ final class PhoneCompanionService { schedule: item.kindRaw == "ordered" ? try schedules.snapshot(item) : nil) } // One synchronous projection; never reuse this ownership index for a later action.- let runScope = try ProfileAccess.ReadScope(context: context)- let runValues = try runs.map { try companionRun($0, service: service, scope: runScope) }+ let runValues = try runs.map { try companionRun($0, service: service, scope: scope) } let revision = AppEnvironment.isTesting ? 1 : UserDefaults.standard.integer(forKey: "meddy.phone.snapshot-revision") + 1@@ -200,7 +201,7 @@ final class PhoneCompanionService { }.map(\.timestamp).max(), active: item.isActive) result.profileID = item.profileID result.ownershipVersion = item.ownershipVersion- result.profileLifecycleID = try ProfileAccess.lifecycle(item, context: context)+ result.profileLifecycleID = try scope.lifecycle(item) return result }) value.profiles = try context.fetch(FetchDescriptor<CareProfile>()).compactMap { profile in
diff --git a/Meddy/Meddy/Services/ProfileAccess.swift b/Meddy/Meddy/Services/ProfileAccess.swiftindex e7c0561..9af5382 100644--- a/Meddy/Meddy/Services/ProfileAccess.swift+++ b/Meddy/Meddy/Services/ProfileAccess.swift@@ -104,6 +104,19 @@ import SwiftData return try ProfileAccess.profile(id, profiles: profiles)?.lifecycleID ?? ProfileIdentity.selfLifecycle }+ func profile(_ id: UUID) throws -> CareProfile? {+ try ProfileAccess.profile(id, profiles: profiles)+ }+ func validated<T: ProfileOwned>(_ values: [T]) -> [T] {+ values.filter { (try? owner($0)) != nil }+ }+ func stamp<T: ProfilePayload>(_ value: T, target: any ProfileOwned) throws -> T {+ var result = value+ result.profileID = try owner(target)+ result.ownershipVersion = ProfileIdentity.ownershipVersion+ result.profileLifecycleID = try lifecycle(target)+ return result+ } func visible(_ value: any ProfileOwned, for id: UUID) -> Bool { (try? owner(value)) == id }@@ -114,7 +127,7 @@ import SwiftData } static func validated<T: ProfileOwned>(_ values: [T], context: ModelContext) -> [T] { guard !values.isEmpty, let scope = try? ReadScope(context: context) else { return [] }- return values.filter { (try? scope.owner($0)) != nil }+ return scope.validated(values) } static func canonical<T: ProfileOwned>(_ type: T.Type, id: UUID, context: ModelContext) throws -> T {
diff --git a/Meddy/Meddy/Services/ReminderService.swift b/Meddy/Meddy/Services/ReminderService.swiftindex 9fa17a6..c216836 100644--- a/Meddy/Meddy/Services/ReminderService.swift+++ b/Meddy/Meddy/Services/ReminderService.swift@@ -301,13 +301,7 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate { 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))+ result.append(contentsOf: try medicationReminders(medications, now: now)) for routine in routines where routine.kindRaw == "ordered" && routine.isActive { _ = try schedules.activatePending(routine) let snapshot = try schedules.snapshot(routine)@@ -390,8 +384,22 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate { } } + // Scope ends before plan activates any pending routine schedule (which can save).+ private func medicationReminders(_ medications: [Medication], now: Date) throws -> [PlannedReminder] {+ let scope = try ProfileAccess.ReadScope(context: context)+ var result: [PlannedReminder] = []+ for action in try MedicationFollowupService.actions(context: context, now: now, scope: scope)+ 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, scope: scope))+ }+ }+ result.append(contentsOf: try medicationPlans(medications, now: now, scope: scope))+ return result+ }+ private func medicationPlans(- _ medications: [Medication], now: Date+ _ medications: [Medication], now: Date, scope: ProfileAccess.ReadScope ) throws -> [PlannedReminder] { let planner = NotificationPlanner() let schedules = ScheduleService(context: context)@@ -405,7 +413,7 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate { isDeleted: $0.isDeleted, hasClockMismatch: $0.hasClockMismatch, wakeEventID: $0.wakeEventID) }- let base = try schedules.snapshot(medication)+ let base = try schedules.snapshot(medication, scope: scope) let variants: [MedicationScheduleSnapshot] = base.mode == .afterWaking ? (base.wakeAnchors ?? []).map { anchor in@@ -418,7 +426,7 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate { 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))+ result.append(try owned(reminder, target: medication, scope: scope)) } } }@@ -553,15 +561,18 @@ final class ReminderService: NSObject, UNUserNotificationCenterDelegate { } catch { self.error = error.localizedDescription } } - private func owned(_ reminder: PlannedReminder, target: any ProfileOwned) throws+ private func owned(_ reminder: PlannedReminder, target: any ProfileOwned, scope: ProfileAccess.ReadScope? = nil) throws -> PlannedReminder {- var result = try ProfileAccess.stamp(reminder, target: target, context: context)+ var result = try scope.map { try $0.stamp(reminder, target: target) }+ ?? 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))+ action: try scope.map { try $0.stamp(event, target: target) }+ ?? 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"+ let owner = try scope.map { try $0.owner(target) } ?? ProfileAccess.owner(target, context: context)+ let profile = try scope.map { try $0.profile(owner) } ?? ProfileAccess.profile(owner, context: context)+ let label = profile?.label ?? "Me" result.title = label + " · " + result.title if owner != ProfileIdentity.me && !result.id.hasPrefix("meddy.profile.") { result.id = "meddy.profile.\(owner)." + result.id
diff --git a/Meddy/Meddy/Services/ScheduleService.swift b/Meddy/Meddy/Services/ScheduleService.swiftindex 1bdc4a1..63474fc 100644--- a/Meddy/Meddy/Services/ScheduleService.swift+++ b/Meddy/Meddy/Services/ScheduleService.swift@@ -87,6 +87,12 @@ final class ScheduleService { profileID: medication.profileID ?? ProfileIdentity.me)) } + func snapshot(_ medication: Medication, scope: ProfileAccess.ReadScope) throws -> MedicationScheduleSnapshot {+ _ = try scope.owner(medication)+ return try snapshot(medication, wakeAnchors: WakeService(context: context).anchors(+ profileID: medication.profileID ?? ProfileIdentity.me))+ }+ func snapshot( _ medication: Medication, scope: ProfileAccess.ReadScope, wakeAnchors: [WakeAnchor]
diff --git a/Meddy/MeddyTests/MeddyMarkdownExportTests.swift b/Meddy/MeddyTests/MeddyMarkdownExportTests.swiftindex 6a73d3c..432ce28 100644--- a/Meddy/MeddyTests/MeddyMarkdownExportTests.swift+++ b/Meddy/MeddyTests/MeddyMarkdownExportTests.swift@@ -23,6 +23,60 @@ struct MeddyMarkdownExportTests { #expect(String(data: export.data, encoding: .utf8) == export.markdown) #expect(medication.prescription?.repeatsLeft == repeats) }+ @Test(arguments: [1, 4])+ func appointmentScheduleCountsUseModeSemanticsAndMatchMarkdown(count: Int) throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let item = try MedicationService(context: store.mainContext).createAsNeededMedication(name: "Synthetic count")+ let schedules = ScheduleService(context: store.mainContext)+ let suffix = " · \(count) " + (count == 1 ? "time" : "times")+ for mode in [MedicationScheduleType.spreadThroughDay, .fixedTimes] {+ let times = (0..<count).map { 480 + $0 * 120 }+ let draft = mode == .spreadThroughDay+ ? MedicationScheduleDraft(mode: mode, dosesPerDay: count, dayStartMinute: 480, dayEndMinute: 1200)+ : MedicationScheduleDraft(mode: mode, fixedMinutes: times + times)+ try schedules.configure(item, draft: draft, reminders: false)+ // Irrelevant fields must not determine the displayed count.+ if mode == .spreadThroughDay {+ item.fixedTimesData = try JSONEncoder().encode([480, 600, 720])+ } else {+ item.dosesPerDay = 99+ item.fixedTimesData = try JSONEncoder().encode(times + times + [-1, 1440])+ }+ try store.mainContext.save()+ let expected = mode.title + suffix+ #expect(MedicationPresentation.consultationScheduleLabel(item, routines: []) == expected)+ #expect(MedicationPresentation.scheduleLabel(item, routines: []) == mode.title)+ let export = MedicationPresentation.consultationExport([item], preparedAt: preparedAt, timeZone: utc)+ #expect(export.markdown.contains("- **Schedule:** \(expected)\n"))+ #expect(!store.mainContext.hasChanges)+ }+ }++ @Test func appointmentScheduleCountsOmitMissingInvalidAndUnrelatedValues() throws {+ let item = Medication(name: "Synthetic formatting")+ item.scheduleTypeRaw = "spreadThroughDay"+ for count in [nil, 0, -1] as [Int?] {+ item.dosesPerDay = count+ #expect(MedicationPresentation.consultationScheduleLabel(item, routines: []) == "Spread through day")+ }+ item.scheduleTypeRaw = "fixedTimes"+ for data in [nil, Data("invalid".utf8), try JSONEncoder().encode([-1, 1440])] as [Data?] {+ item.fixedTimesData = data+ #expect(MedicationPresentation.consultationScheduleLabel(item, routines: []) == "Fixed times")+ }+ item.dosesPerDay = 4+ item.fixedTimesData = try JSONEncoder().encode([480, 720])+ item.wakeOffsetMinutes = 25+ for mode in [MedicationScheduleType.asNeeded, .interval, .afterWaking, .routineManaged] {+ item.scheduleTypeRaw = mode.rawValue+ #expect(MedicationPresentation.consultationScheduleLabel(item, routines: [])+ == MedicationPresentation.scheduleLabel(item, routines: []))+ }+ item.scheduleTypeRaw = "fixedTimes"+ item.managedByRoutineID = UUID()+ #expect(MedicationPresentation.consultationScheduleLabel(item, routines: []) == "In saved routine")+ }+ private func entry( _ name: String, purpose: String = "Ungrouped", id: UUID = UUID(), dose: String? = nil, method: String = "", requirements: String = "", schedule: String = "As needed"
diff --git a/Meddy/MeddyTests/MeddyMedicationProjectionPerformanceTests.swift b/Meddy/MeddyTests/MeddyMedicationProjectionPerformanceTests.swiftnew file mode 100644index 0000000..2dd8271--- /dev/null+++ b/Meddy/MeddyTests/MeddyMedicationProjectionPerformanceTests.swift@@ -0,0 +1,166 @@+import Foundation+import SwiftData+import Testing+@testable import Meddy++@MainActor+struct MeddyMedicationProjectionPerformanceTests {+ @Test(arguments: [1, 10, 25])+ func medicationProjectionsDoNotRescanHistoryPerMedication(count: Int) throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ defer { MutationEffects.remove(context); ProfileAccess.inspectedRows = nil }+ var items: [Medication] = []+ for index in 0..<count {+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic \(index)")+ try ScheduleService(context: context).configure(item,+ draft: .init(mode: .interval, intervalMinutes: 1440, firstReminderMinute: 0), reminders: true)+ items.append(item)+ }+ for index in 0..<100 {+ let item = items[index % count]+ let action = AdministrationAction(eventID: UUID(), medicationID: item.id,+ timestamp: Date().addingTimeInterval(-Double(index + 1) * 86400), source: .phone,+ dose: .unknown, scheduleTypeAtRecording: .interval, scheduleGenerationID: item.scheduleGenerationID)+ context.insert(Administration(action: action, medication: item))+ }+ try context.save()+ let inventory = count + 100+ var rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ let snapshot = try PhoneCompanionService(context: context).snapshot()+ #expect(snapshot.medications.count == count && snapshot.appliedEventIDs.count == 100)+ #expect(rows <= 4 * inventory, "Watch projection must share read-only ownership lookups")+ rows = 0+ let reminders = ReminderService(context: context, registerDelegate: false)+ let plan = try reminders.plan(now: Date())+ #expect(plan.count == count)+ #expect(rows <= 8 * inventory, "Notification planning must share read-only ownership lookups")+ #expect(!context.hasChanges)+ #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 100)+ }++ @Test func projectionsRecheckLifecycleArchiveAndPendingDuplicates() 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 item = try MedicationService(context: context).createAsNeededMedication(+ name: "Synthetic medication", profileID: profile.id)+ try ScheduleService(context: context).configure(item,+ draft: .init(mode: .interval, intervalMinutes: 1440, firstReminderMinute: 0), reminders: true)+ let now = Date()+ let companion = PhoneCompanionService(context: context)+ let reminders = ReminderService(context: context, registerDelegate: false)+ let projected = try #require(companion.snapshot().medications.first)+ #expect(try projected.schedule == ScheduleService(context: context).snapshot(item))+ let planned = try #require(reminders.plan(now: now).first)+ #expect(planned.profileID == profile.id && planned.profileLifecycleID == profile.lifecycleID)+ if case .medication(let action) = planned.payload {+ #expect(try action == ProfileAccess.stamp(action, target: item, context: context))+ } else { Issue.record("Expected medication reminder") }+ let scheduled = MedicationPresentation.scheduled([item], now: now, context: context)+ #expect(try scheduled.first?.1 == MedicationPresentation.result(item, now: now, context: context).next)+ profile.lifecycleID = UUID()+ try context.save()+ #expect(try companion.snapshot().medications.first?.profileLifecycleID == profile.lifecycleID)+ #expect(try reminders.plan(now: now).first?.profileLifecycleID == profile.lifecycleID)+ let duplicate = Treatment(name: "Synthetic collision")+ duplicate.id = item.id+ context.insert(duplicate)+ #expect(MedicationPresentation.scheduled([item], now: now, context: context).isEmpty)+ #expect(try companion.snapshot().medications.isEmpty)+ #expect(try reminders.plan(now: now).isEmpty)+ context.delete(duplicate)+ try context.save()+ profile.archivedAt = now+ try context.save()+ #expect(MedicationPresentation.scheduled([item], now: now, context: context).isEmpty)+ #expect(try companion.snapshot().medications.isEmpty)+ #expect(try reminders.plan(now: now).isEmpty)+ #expect(throws: ProfileError.self) { try TodayMedicationAction.take([item], at: now, context: context) }+ #expect(try context.fetchCount(FetchDescriptor<Administration>()) == 0)+ }++ @Test func followupProjectionKeepsValidEventsWithoutPerEventStoreScans() throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ defer { MutationEffects.remove(context); ProfileAccess.inspectedRows = nil }+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic followup")+ try MedicationFollowupService.configure(item, value: .init(message: "Synthetic followup", delaySeconds: 3600))+ let now = Date()+ var valid = Set<UUID>()+ for index in 0..<50 {+ let action = AdministrationAction(eventID: UUID(), medicationID: item.id,+ timestamp: now.addingTimeInterval(-Double(index)), source: .phone,+ dose: .unknown, scheduleTypeAtRecording: .asNeeded, scheduleGenerationID: nil)+ let event = Administration(action: action, medication: item)+ context.insert(event)+ if index == 0 { event.isDeleted = true } else if index == 1 {+ event.profileID = UUID()+ } else { valid.insert(event.id) }+ }+ try context.save()+ var rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ let actions = try MedicationFollowupService.actions(context: context, now: now)+ #expect(Set(actions.map(\.eventID)) == valid)+ #expect(rows <= 51)+ #expect(!context.hasChanges)+ }++ @Test func batchedTodayAndAsNeededWatchReadsHaveBoundedWork() throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ defer { MutationEffects.remove(context); ProfileAccess.inspectedRows = nil }+ var items: [Medication] = []+ for index in 0..<20 {+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic \(index)")+ items.append(item)+ try ScheduleService(context: context).configure(item,+ draft: .init(mode: .interval, intervalMinutes: 1440, firstReminderMinute: 0), reminders: false)+ }+ let now = Date()+ let expected = try items.compactMap { item -> Date? in+ try MedicationPresentation.result(item, now: now, context: context).next+ }.sorted()+ var rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ #expect(MedicationPresentation.scheduled(items, now: now, context: context).map(\.1) == expected)+ #expect(rows == 20)+ ProfileAccess.inspectedRows = nil+ for item in items {+ try ScheduleService(context: context).configure(item, draft: .init(mode: .asNeeded), reminders: false)+ }+ rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ let snapshot = try PhoneCompanionService(context: context).snapshot()+ #expect(snapshot.medications.count == 20 && snapshot.medications.allSatisfy { $0.doseLimitCheck != nil })+ #expect(rows <= 80)+ #expect(!context.hasChanges)+ }+++ @Test func todayProjectionRetainsAttentionResultsAndRefreshesAfterWake() throws {+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ defer { MutationEffects.remove(context); ProfileAccess.inspectedRows = nil }+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic waiting")+ try ScheduleService(context: context).configure(item,+ draft: .init(mode: .afterWaking, wakeOffsetMinutes: 10), reminders: false)+ let now = Date()+ var rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ let waiting = MedicationPresentation.projection([item], now: now, context: context)+ #expect(waiting.results.count == 1 && waiting.scheduled.isEmpty)+ #expect(waiting.results.first?.result.takenToday == 0)+ #expect(rows == 1)+ ProfileAccess.inspectedRows = nil+ _ = try WakeService(context: context).record(at: now, receivedAt: now)+ let awake = MedicationPresentation.projection([item], now: now, context: context)+ #expect(awake.results.count == 1 && awake.scheduled.count == 1)+ #expect(awake.scheduled.first?.1 == now.addingTimeInterval(600))+ }++}
diff --git a/specs/bugfixes/residual-taken-latency/benchmark.json b/specs/bugfixes/residual-taken-latency/benchmark.jsonnew file mode 100644index 0000000..c1b9fca--- /dev/null+++ b/specs/bugfixes/residual-taken-latency/benchmark.json@@ -0,0 +1,151 @@+{+ "fixture": "500 initial synthetic administrations; 1/10/25 medications; 3 visits; unchanged diagnostic; optimized simulator",+ "beforeSource": "b746a6d",+ "afterBase": "1d6790d",+ "results": [+ {+ "medications": 1,+ "stage": "bare-taken",+ "beforeMs": 49.621,+ "afterMs": 47.824,+ "beforeRows": 2008,+ "afterRows": 2008+ },+ {+ "medications": 1,+ "stage": "reminder-two-plans",+ "beforeMs": 295.974,+ "afterMs": 66.565,+ "beforeRows": 6036,+ "afterRows": 2012+ },+ {+ "medications": 1,+ "stage": "view-schedule-pass",+ "beforeMs": 75.558,+ "afterMs": 76.418,+ "beforeRows": 503,+ "afterRows": 503+ },+ {+ "medications": 1,+ "stage": "watch-encode",+ "beforeMs": 0.969,+ "afterMs": 0.729,+ "beforeRows": 0,+ "afterRows": 0+ },+ {+ "medications": 1,+ "stage": "watch-snapshot",+ "beforeMs": 88.288,+ "afterMs": 36.806,+ "beforeRows": 3018,+ "afterRows": 503+ },+ {+ "medications": 1,+ "stage": "widget-capture",+ "beforeMs": 21.046,+ "afterMs": 21.37,+ "beforeRows": 503,+ "afterRows": 503+ },+ {+ "medications": 10,+ "stage": "bare-taken",+ "beforeMs": 49.296,+ "afterMs": 45.437,+ "beforeRows": 2044,+ "afterRows": 2044+ },+ {+ "medications": 10,+ "stage": "reminder-two-plans",+ "beforeMs": 1252.074,+ "afterMs": 72.336,+ "beforeRows": 52224,+ "afterRows": 2048+ },+ {+ "medications": 10,+ "stage": "view-schedule-pass",+ "beforeMs": 183.349,+ "afterMs": 172.926,+ "beforeRows": 5120,+ "afterRows": 5120+ },+ {+ "medications": 10,+ "stage": "watch-encode",+ "beforeMs": 0.829,+ "afterMs": 0.848,+ "beforeRows": 0,+ "afterRows": 0+ },+ {+ "medications": 10,+ "stage": "watch-snapshot",+ "beforeMs": 342.384,+ "afterMs": 35.38,+ "beforeRows": 16896,+ "afterRows": 512+ },+ {+ "medications": 10,+ "stage": "widget-capture",+ "beforeMs": 23.507,+ "afterMs": 22.326,+ "beforeRows": 512,+ "afterRows": 512+ },+ {+ "medications": 25,+ "stage": "bare-taken",+ "beforeMs": 46.738,+ "afterMs": 47.046,+ "beforeRows": 2104,+ "afterRows": 2104+ },+ {+ "medications": 25,+ "stage": "reminder-two-plans",+ "beforeMs": 2823.498,+ "afterMs": 82.065,+ "beforeRows": 132804,+ "afterRows": 2108+ },+ {+ "medications": 25,+ "stage": "view-schedule-pass",+ "beforeMs": 341.508,+ "afterMs": 347.719,+ "beforeRows": 13175,+ "afterRows": 13175+ },+ {+ "medications": 25,+ "stage": "watch-encode",+ "beforeMs": 0.983,+ "afterMs": 1.007,+ "beforeRows": 0,+ "afterRows": 0+ },+ {+ "medications": 25,+ "stage": "watch-snapshot",+ "beforeMs": 738.315,+ "afterMs": 35.675,+ "beforeRows": 41106,+ "afterRows": 527+ },+ {+ "medications": 25,+ "stage": "widget-capture",+ "beforeMs": 22.378,+ "afterMs": 22.736,+ "beforeRows": 527,+ "afterRows": 527+ }+ ]+}
diff --git a/specs/bugfixes/residual-taken-latency/diagnostic.swift.txt b/specs/bugfixes/residual-taken-latency/diagnostic.swift.txtnew file mode 100644index 0000000..d452783--- /dev/null+++ b/specs/bugfixes/residual-taken-latency/diagnostic.swift.txt@@ -0,0 +1,58 @@+import Foundation+import SwiftData+import Testing+@testable import Meddy++@MainActor struct MeddyResidualLatencyDiagnostics {+ func measure<T>(_ stage: String, count: Int, visit: Int, _ body: () throws -> T) rethrows -> T {+ var rows = 0+ ProfileAccess.inspectedRows = { rows += $0 }+ let start = ProcessInfo.processInfo.systemUptime+ defer {+ print("RESIDUAL_DIAG meds=\(count) visit=\(visit) stage=\(stage) ms=\((ProcessInfo.processInfo.systemUptime-start)*1000) rows=\(rows)")+ ProfileAccess.inspectedRows = nil+ }+ return try body()+ }+ @Test(arguments: [1, 10, 25]) func stages(count: Int) throws {+ #expect(AppEnvironment.isTesting)+ let store = try AppEnvironment.makeContainer(isolated: true)+ let context = store.mainContext+ defer { MutationEffects.remove(context) }+ let now = Date()+ var medications: [Medication] = []+ for i in 0..<count {+ let item = try MedicationService(context: context).createAsNeededMedication(name: "Synthetic \(i)")+ try ScheduleService(context: context).configure(item,+ draft: .init(mode: .interval, intervalMinutes: 1440, firstReminderMinute: 0), reminders: true)+ medications.append(item)+ }+ for i in 0..<500 {+ let item = medications[i % count]+ let action = AdministrationAction(eventID: UUID(), medicationID: item.id,+ timestamp: now.addingTimeInterval(-Double(i+1)*86400), source: .phone,+ dose: .unknown, scheduleTypeAtRecording: .interval, scheduleGenerationID: item.scheduleGenerationID)+ context.insert(Administration(action: action, medication: item))+ }+ try context.save()+ MutationEffects.remove(context)+ let companion = PhoneCompanionService(context: context)+ let reminders = ReminderService(context: context, registerDelegate: false)+ for visit in 0..<3 {+ _ = try measure("bare-taken", count: count, visit: visit) {+ try TodayMedicationAction.take([medications[0]], at: now, context: context)+ }+ let snapshot = try measure("watch-snapshot", count: count, visit: visit) { try companion.snapshot() }+ let bytes = try measure("watch-encode", count: count, visit: visit) { try JSONEncoder().encode(CompanionMessage.snapshot(snapshot)) }+ print("RESIDUAL_BYTES meds=\(count) bytes=\(bytes.count)")+ _ = try measure("reminder-two-plans", count: count, visit: visit) {+ (try reminders.plan(now: now), try reminders.plan(now: now, includeElapsedWake: true))+ }+ _ = try measure("widget-capture", count: count, visit: visit) { try WidgetProjectionService(context: context).capture() }+ _ = try measure("view-schedule-pass", count: count, visit: visit) {+ try medications.map { try MedicationPresentation.result($0, now: now, context: context) }+ }+ #expect(!context.hasChanges)+ }+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dd89444..bc0269a 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+- 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. - Prepare the developer-account migration with the `me.nore.ig.apps.meddy` phone/Watch/test identifier family and matching private CloudKit selectors; provisioning and data migration remain separate.@@ -16,6 +17,7 @@ - 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+- 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. - Offer explicitly confirmed import recovery for two unused starter Me profiles in a cold session with managed CloudKit sync paused; validate the archive and exact destination, preserve edited/nonempty destinations, and support rollback and crash recovery.
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex 3c22ff9..cd55199 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -1673,6 +1673,8 @@ API basis: [Apple local notification scheduling and cancellation](https://develo The existing Current Medications Share action now supplies a UTF-8 Markdown transfer rather than an unstructured shared string. Its suggested filename is `meddy-current-medications-YYYY-MM-DD.md`, using the preparation timestamp's time zone. The Markdown document has an H1 title, an ISO 8601 preparation timestamp with offset, H2 purpose groups, H3 medication names and labelled list fields for optional dose, how to take/apply, requirements and schedule. Active medications appear once, including the existing routine-owner/frequency and As needed labels. Missing optional fields stay omitted, and an empty export says no active medications are recorded. Purpose/name/UUID ordering is deterministic. +Appointment schedule-count addition (29 October 2026): the Current Medications appointment screen and Markdown schedule field append ` · 1 time` / ` · N times` for standalone fixed-times and spread-through-day schedules. Fixed-times uses distinct valid clock-minute entries; spread-through-day uses the positive configured daily target. Missing/invalid counts are omitted. Preserve existing labels, wake timing and routine session details, and leave the general medication-list schedule label unchanged. This is display-only and does not infer or change care instructions.+ Escape user-entered Markdown/HTML punctuation so names and instructions cannot change the heading/list structure or inject markup. Normalize CRLF/CR newlines and preserve intentional multiline/blank-line content with generated `<br>` within the field. Keep Unicode intact. Scope remains the existing current-medication consultation summary: no history dump, photos, private notes, inferred instructions, follow-up settings, PDF generation or automatic external sending is added. The user chooses a destination through the system share sheet. Formatting and file/content-type metadata are verified with deterministic synthetic inputs and the real system transfer provider; no personal health file is exported for tests.
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex 99a84dc..e3c2af1 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -8,6 +8,16 @@ > they do not establish provisioning or data migration for the new identity. +## 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.++The unchanged optimized synthetic benchmark (500 history entries, three samples) reduces two notification plans at 25 medications from 2,823 ms to 82 ms and Watch snapshot construction from 738 ms to 36 ms. These are simulator service timings, not actual phone responsiveness. Work-bound regressions cover lifecycle/archive/duplicate refresh, captured reminder ownership, follow-ups and wake attention. See [the T2503 report](../specs/bugfixes/residual-taken-latency/report.md) for final gate evidence and limits. No phone installation or merge is part of this change.++## Appointment schedule counts (T2504)++The appointment screen and Markdown export share a consultation-only schedule label that appends `1 time` / `N times` for fixed-times and spread-through-day schedules. Counts use distinct valid configured clock times or the positive daily target; other modes, wake details, routine ownership and general medication-list labels remain unchanged. Two new synthetic export test declarations cover these semantics and read-only formatting. The addition is included with T2503 in draft PR18; [verification](../specs/appointment-schedule-counts/verification.md) records the combined native gate and signed Release preparation. No merge or phone installation is part of implementation; installation waits for the user's home confirmation.+ ## Recurring medication detail slowness Bug-fix investigation on merged c486485 reproduced growing main-actor ownership-read costs in an optimized synthetic test: 10/100/500 logs caused 121/10,201/251,001 materialized records per limit check, approximately 10 ms/225 ms/4.4 s. Short-lived read indexes share the existing duplicate/profile/link validation within a limit/display operation; writes retain fresh context authorization. Optimized green median at 500 logs is 27.7 ms/501 records versus 4.38 s/251,001 records before, approximately 158× faster. All 50 focused domain declarations and one six-cycle synthetic navigation scenario passed at 85c5071; strict lint passed 116 files/zero violations. Four source reviews clear; assigned simulators restored and lane released. UI automation times include XCTest overhead and are not phone tap-to-open measures; live observer/CloudKit paths and physical acceptance remain unverified. See specs/bugfixes/recurring-medication-detail-slowness/report.md for build-hook qualifications, raw evidence and physical-device limits. No live-store inspection, reset, deployment, cloud/account change or merge. Transit ticket for app Meddy pending unavailable tools; deduplicate the saved local draft before creation.
diff --git a/specs/appointment-schedule-counts/implementation.md b/specs/appointment-schedule-counts/implementation.mdnew file mode 100644index 0000000..29e99ce--- /dev/null+++ b/specs/appointment-schedule-counts/implementation.md@@ -0,0 +1,17 @@+# T2504 implementation explanation++## Beginner++Appointment sharing now states how many times a medication is scheduled, such as `Fixed times · 1 time` or `Spread through day · 4 times`. The screen and exported Markdown use the same wording. This describes the saved schedule; it does not change it.++## Intermediate++A consultation-only formatter delegates the existing schedule label and appends the count for two standalone modes. Spread-through-day reads the positive daily target. Fixed-times decodes the configured clock minutes, ignores invalid minutes and counts distinct values. Missing counts and other modes retain their existing labels. The general medication-list label is unchanged.++## Expert++Routine ownership takes precedence over stale standalone fields. The helper performs no context fetches or mutations and does not evaluate today's remaining doses. This keeps the configured frequency independent of history and avoids adding ownership-scan work to the preserved T2503 paths. Tests verify singular/plural, mode-specific fields, duplicates/invalid data, export parity and no writes.++## Completeness++The display-only change, focused tests and independent reviews are complete. The companion verification document records the combined native gate and Release artifact provenance. Actual phone responsiveness is unmeasured; physical installation awaits home confirmation, and merge is not authorized.
diff --git a/specs/appointment-schedule-counts/verification.md b/specs/appointment-schedule-counts/verification.mdnew file mode 100644index 0000000..156da83--- /dev/null+++ b/specs/appointment-schedule-counts/verification.md@@ -0,0 +1,11 @@+# Appointment schedule counts (T2504)++User-approved addition to draft PR18, preserving T2503. The appointment screen and Markdown export append ` · 1 time` or ` · N times` to fixed-times and spread-through-day labels. Existing labels and time details remain intact. Examples: `Fixed times · 2 times`, `Spread through day · 4 times`.++The formatter derives spread frequency from positive dosesPerDay and fixed frequency from distinct valid clock minutes, matching scheduling semantics. It ignores unrelated fields and omits a count when no valid count is available. Routine-owned medications keep their routine label, including session frequency and archive details; wake offsets and other schedule modes remain unchanged. No model writes, schedule changes, migrations or new store reads occur.++Ten focused export test declarations passed, including two new declarations covering singular/plural, duplicate/invalid clock minutes, missing counts, irrelevant fields, Markdown parity, other modes and no writes. Four independent read-only reviews (reuse, correctness, efficiency and specification) found no issues. Strict lint passed. The full combined `make pre-push` gate completed with exit 0: strict lint (200 files, zero violations), widget build, 375 phone domain declarations, 17 Watch declarations and 32 phone UI journeys all passed. Existing synthetic-startup background-publication warnings remain; no clean-runtime claim is made.++The T2503 optimized benchmark remains evidence for its unchanged projection paths, not a new phone measurement. The combined gate reruns its deterministic work-bound regressions. No real medication data was accessed or exported. A signed Release `-O` build succeeded with the existing phone/widget identity and entitlements; deep/strict signatures verify and the normal temporary packaging omits embedded Watch content. Both existing provisioning profiles include the previously verified phone, checked against the saved deployment record without device contact. All 277 app/test input hashes remained unchanged during validation and match the staged Release candidate. The local artifact receipt binds those hashes to the final published commit; the build began from the reviewed working candidate, and only the standard temporary Watch-packaging omission changes the staged project. Physical installation awaits the user's home confirmation. No merge is authorized.++Evidence: `share-count/focused.log`, `share-count/pre-push.log`, `share-count/source-hashes.json`, and `share-count/release/` under the task workspace. Final native results: `/tmp/meddy-share-final-results/test-domain.BRfqTd/Results.xcresult`, `test-watch.bBTgbg/Results.xcresult` and `test-ui-all.StbbaR/Results.xcresult`. The signed app is preserved separately at `share-count/release/Meddy.app`; its receipt records configuration, identity, signatures, provisioning coverage and file hashes. No install or launch ran.
diff --git a/specs/bugfixes/residual-taken-latency/implementation.md b/specs/bugfixes/residual-taken-latency/implementation.mdnew file mode 100644index 0000000..add95c1--- /dev/null+++ b/specs/bugfixes/residual-taken-latency/implementation.md@@ -0,0 +1,40 @@+# T2503 implementation explanation++## Beginner++### What changed+Meddy prepares notification, Watch and Today information after care changes. These readers repeatedly checked the same store once per medication. They now share those checks during each read operation.++### Why it matters+Less repeated work gives the app more time to update the screen. A synthetic test with 25 medications reduced notification planning from 2.82 seconds to 82 milliseconds. This does not measure actual phone responsiveness.++### Key concepts+A projection is a temporary description prepared for display or delivery. It is discarded after the operation; it is not an enduring cache or permission to record care later.++## Intermediate++### Changes overview+ProfileAccess.ReadScope supplies shared validation, lifecycle and stamping to medication notification plans and PhoneCompanionService. ScheduleService creates one snapshot per medication and MedicationPresentation evaluates that snapshot. Today shares one ScheduleProjection across due, later and attention sections.++### Implementation approach+Medication reminder projection finishes before pending routine activation can mutate or save. Watch passes its scope to as-needed checks and existing run projection. Today retains all eligible results, including entries without a next date, so wake-related attention stays visible. The Take closure recomputes current due targets and the existing mutation service authorizes and saves them.++### Trade-offs+This reuses existing validation with explicit operation lifetime rather than introducing invalidation machinery. Wake-anchor fetches, routine work, synchronous transport and actual disk/CloudKit performance remain outside the measured improvement.++## Expert++### Technical details+ReadScope is immutable for one synchronous operation and includes pending context objects. It retains cross-entity duplicate, owner, lifecycle and link validation. Scoped stamping copies the same payload fields as fresh stamping; nil-profile Me handling and dependant labels remain intact. No scope crosses a suspension or mutation. Static mutation authorization remains fresh.++### Architecture impact+The change adds scoped read overloads and a render-local projection without altering persisted schema, notification identifiers, receipts, ordering, payload format, configuration or delivery. Regression assertions bound ownership inventory visits rather than wall-clock performance, avoiding timing thresholds sensitive to simulator load.++### Potential issues+It is still possible for unmeasured observer, transport or persistence work to delay a frame. The benchmark's unchanged single-item view loop remains a control. Native synthetic startup reports existing background-publication warnings. Actual phone tap-to-paint latency requires a separately authorized installation and observation.++## Decisions and completeness++Operation-local reuse was chosen because the measured amplification comes from repeated read inventories, while care writes require fresh authorization. Save-before-success is preserved because perceived responsiveness must not claim an unsaved dose. The full Today projection includes nil-next entries because they carry waiting-for-wake and cannot-fit attention states.++The focused source change, deterministic regressions, unchanged before/after benchmark and independent reviews are complete. The report records the aggregate gate's current outcome. Physical phone responsiveness and real delivery are unmeasured; no installation or merge belongs to this change.
diff --git a/specs/bugfixes/residual-taken-latency/report.md b/specs/bugfixes/residual-taken-latency/report.mdnew file mode 100644index 0000000..0babced--- /dev/null+++ b/specs/bugfixes/residual-taken-latency/report.md@@ -0,0 +1,60 @@+# Bugfix Report: Residual Taken latency++Date: 2026-10-29. Status: Implemented and verified; ready for review. Transit: T-2503.++## Description and investigation++The user still notices delay after Taken in the installed Release -O build b746a6d. The prior PR17 fix removed retained-timer amplification, but standalone medication projection still calls fresh ownership scans per item. No actual phone records were inspected or changed.++With 500 synthetic history rows and 10/25 medications, the unchanged installed-source benchmark measured two reminder plans at 1,252/2,823 ms, Watch projection at 342/738 ms and one view schedule pass at 183/342 ms. Bare Taken plus in-memory save was 49/47 ms. These are simulator service timings, not phone tap-to-paint measurements.++## Root cause++1. Visible feedback waits for synchronous save observers, and main-actor tasks can delay subsequent frames.+2. Those observers and UI consumers project medication schedules repeatedly.+3. Each ordinary schedule/lifecycle read rebuilds the entire ownership inventory.+4. Batch consumers invoke single-item helpers, despite an existing operation-local ReadScope.+5. Previous optimisation covered routine runs, leaving medication projection consumers unbatched.++This is repeated read work, not evidence that persistence can safely be skipped or success shown early. Watch encoding/widget capture were small in the measured fixture; actual disk/CloudKit/transport costs remain unmeasured.++## Implemented resolution++Use scoped read-only ownership and schedule projections within a synchronous operation. Preserve every ambiguity/owner/lifecycle check, archive filtering, pending schedule activation, notification reconciliation and save-before-feedback. Do not retain projections across mutations, suspension or remote changes. Reuse Today’s schedule projection within a single render while actions recompute authoritative targets.++## Regression and verification++MeddyMedicationProjectionPerformanceTests varies medication count with fixed history, asserting unchanged outputs/no writes and bounded ownership-row work for Watch and reminder planning. Run red before changing production code; compare the exact saved synthetic benchmark before/after; follow with full native/lint/UI gates and independent review.++## Measured comparison++The exact unchanged diagnostic ran before on installed source b746a6d and after on the final production delta based on main 1d6790d. The intervening midnight-header fix does not change these service stages. Both runs used optimized Swift (`-O`) with DEBUG work counters, the same simulator and an isolated in-memory no-CloudKit store. There were 500 initial synthetic administrations, 1/10/25 medications and three visits per stage. Each visit adds one synthetic administration. Medians are milliseconds:++| Stage | 1 medication before → after | 10 medications before → after | 25 medications before → after |+| --- | ---: | ---: | ---: |+| Two notification plans | 295.974 → 66.565 | 1252.074 → 72.336 | 2823.498 → 82.065 |+| Watch snapshot construction | 88.288 → 36.806 | 342.384 → 35.380 | 738.315 → 35.675 |+| Bare Taken and in-memory save | 49.621 → 47.824 | 49.296 → 45.437 | 46.738 → 47.046 |+| Legacy single-item view loop (control) | 75.558 → 76.418 | 183.349 → 172.926 | 341.508 → 347.719 |++At 25 medications, notification ownership-row visits fall from 132,804 to 2,108 and Watch visits from 41,106 to 527. These deterministic work counts support the timing attribution. The unchanged legacy view loop is a control, not a benchmark of the new Today batch. A separate regression verifies 20 scheduled medications use 20 inventory rows, with date parity; all waiting-for-wake results are retained and refresh after a synthetic wake. Watch encoding (about 1 ms) and widget capture (about 23 ms) remain controls. Full values and work counts are in benchmark.json.++These are service measurements, not end-to-end phone latency. Actual disk persistence, CloudKit, notification delivery, Watch transport, and frame timing were not measured. Native synthetic startup emits existing background-publication warnings in both benchmark runs. No clean-runtime claim or claim that all remaining costs are eliminated is made. Wake-anchor fetches, routine projections and transport costs remain outside this focused change.++## Reproducing the diagnostic++`diagnostic.swift.txt` is the exact 58-line diagnostic used in both runs (SHA-256 `e570ea6b1821a70d4b3598adec3d50ffcd8472ea94f7357fdb0744e700ebb3fb`). In a separate disposable source copy, copy it to `Meddy/MeddyTests/MeddyResidualLatencyDiagnostics.swift`. Use a wrapper that executes `/usr/bin/xcodebuild "$@" SWIFT_OPTIMIZATION_LEVEL=-O`, then run `make test-domain DOMAIN_TEST=MeddyTests/MeddyResidualLatencyDiagnostics` with `XCODEBUILD` pointing to that wrapper and isolated destination, derived-data and results overrides. Retain the normal Debug configuration to enable existing work counters and the shared scheme's `MEDDY_TESTING=1`. Do not run against a live store. The archived text is outside the app/test targets and is not a new permanent test declaration.++## Verification and independent review++- Red: the unmodified production baseline failed the new work-bound assertions (five expected issues), while output/no-write checks passed. The native command completed with xcodebuild 65 / make 2; its failure-diagnostic collection was not counted as success.+- Final focused green: five test declarations (one has three parameter cases), exit 0. Covers work bounds, output/date/stamp parity, lifecycle changes, pending cross-entity duplicate IDs, archived targets, deleted/foreign follow-up events, as-needed projections, waiting-for-wake refresh and no writes. Fresh action validation rejects archived targets.+- Unchanged optimized diagnostic: exit 0, one declaration with three parameter cases, both before and after.+- Full `make pre-push` gate completed exit 0: whitespace, strict lint (200 files, zero violations), widget build, 373 phone domain declarations, 17 Watch declarations and all 32 phone UI journeys passed. Source hashes confirm all 277 tracked app/test inputs stayed unchanged through the final benchmark and gate.+- Four independent reviews covered reuse, correctness, efficiency and specification alignment. Correctness review identified an unbatched attention section; it now shares the render projection while retaining no-next-date entries, with a new regression. Rereview accepted the correction. No unresolved source finding remains.++Evidence is retained outside the repository under `/Users/arjen/Documents/Codex/2026-10-28/task-2/residual-latency/`: red.log, green-final.log, run.log, after.log, metrics.json, after-metrics.json, pre-push.log and final-source-hashes.json. Native results are under `/tmp/meddy-residual-final-results/`; the exact diagnostic is retained as diagnostic.swift alongside the logs.++## Resolution++A ReadScope now lives only for one synchronous read operation. Notification medication projection returns values before any pending routine activation can save. Watch uses one ownership inventory and one medication schedule snapshot per medication. Today shares one render projection; Take recomputes current targets, and mutation authorization/save-before-success remain unchanged. No schema, signing, entitlement, deployment or merge change is included.