Meddy native tests 259 passed, aggregate new declarations 7 strict lint 121 files / 0 violations

Pre-push review: Meddy T-2453 medication classification

Optional owner-entered medication label, retaining accepted PR #11 as the dependency.

At a glance

  • Optional type: Not set, Over the counter, Prescription. Existing entries stay unset.
  • Normal editor uses the shared transaction; detail only displays a known label.
  • Prescription revision, repeat accounting, schedules, reminders and accepted performance changes retain their existing behavior.

Verdict

Ready for draft PR

Four read-only review perspectives found no blocking issues. Final gate coverage completed under the targeted retry policy: 224 phone domain, 14 Watch and 19 retained UI passes + 2 affected UI retry passes; strict lint and whitespace passed. The initial full UI attempt failed two test assumptions; both failed results remain retained. This is aggregate coverage, not a fresh full pre-push pass. Synthetic prior-store migration and same-context retry were exercised. No live CloudKit, merge or installation.

Review findings

4 raised · 4 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: 100% (259 of 259)

New tests: 7

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What Changed The existing medication editor offers Not set, Over the counter and Prescription. A selected label appears beneath the medication name on detail. Existing medications remain unset.

Why It Matters The owner can record this distinction without changing doses, reminders or prescription repeat accounting. Save stores the selection; Cancel leaves the stored medication unchanged.

Key Concepts An optional field can hold a label or no value. The editor keeps a draft until Save, so selecting an option does not immediately change stored records.

Changes Overview Medication adds nullable classificationRaw. MedicationClassification maps stable raw values to display titles. MedicationClassificationDraft integrates with the existing EditorTransaction. ContentView adds the native picker; MedicationDetailView displays a known value read-only.

Implementation Approach The draft captures medication identity, owner, lifecycle and original raw value. Apply validates current ownership, preserves newer untouched values and rejects conflicting edited values. The shared editor transaction retains combined Save/rollback behavior. Classification never advances prescriptionRevision.

Trade-offs A scalar fits the existing additive metadata model and avoids coupling this informational label to prescription dates or repeat rules. Unknown values remain intact in an untouched draft; this version displays only its two known labels.

Technical Deep Dive Apply resolves current ownership before writing, checks captured identity and profile lifecycle, then compares the edited selection with the original known value. Untouched drafts return without overwriting concurrent or unrecognized values. Changed drafts accept the original raw value or an already-applied identical value; other current values produce a reopen-editor error. Profile archive/restore invalidates a stale draft.

Architecture Impact The field is additive and optional, with no relationship, uniqueness or encoded schedule/Watch payload changes. Compatibility is exercised against a synthetic SQLite store generated from unchanged production source 011be8c. Tests retain containers and disable CloudKit. CloudKit schema changes remain additive; no live schema promotion, live sync or old-binary downgrade guarantee is claimed.

Potential Issues Unknown labels cannot be selected here and remain hidden on detail until understood by a later version. Replacing one with a supported label requires an explicit edited selection. Conflicting edits ask the owner to reopen the editor. The feature PR depends on unmerged PR #11 and must keep that dependency explicit.

Important changes — detailed

Persist one nullable raw label

Meddy/Meddy/Models/Models.swift

Why it matters. Existing rows need no inferred/default classification.

What to look at. Medication.classificationRaw and classification

Takeaway. Keep optional metadata additive.
Rationale. A label must not derive from prescription accounting.

Validate and apply the editor draft

Meddy/Meddy/Features/MedicationClassification.swift

Why it matters. Cancel, stale ownership and conflicting edits must preserve stored state.

What to look at. MedicationClassificationDraft.apply

Takeaway. Reuse current ownership and transaction guards; preserve untouched newer values.
Rationale. The label is informational metadata independent of prescription revision.

Use the existing editor and detail

Meddy/Meddy/ContentView.swift

Why it matters. The owner needs normal Save/Cancel/clear behavior.

What to look at. MedicationEditor picker and EditorTransaction

Takeaway. A native optional picker fits the existing form.
Rationale. Requested normal editor scope, with read-only detail.

Verify actual prior-source store compatibility

Meddy/MeddyTests/MeddyMedicationClassificationTests.swift

Why it matters. An optional declaration alone does not demonstrate SwiftData migration.

What to look at. exactPreClassificationStoreUpgradesWithoutInferringLabelsAndReopens

Takeaway. Exercise retained synthetic old-source bytes with CloudKit disabled.
Rationale. Exact 011be8c production-source fixture preserves prior records and checks reopen.

Key decisions

Stable nullable scalar

Known values map through an enum. Unknown raw values survive untouched drafts; no guessed label is displayed.

Separate prescription revision

The classification label does not alter dates, repeats or prescriptionRevision, preserving existing Undo semantics.

Stack on accepted performance work

PR #11 remains open at 011be8c. The feature draft targets its branch so the review contains only this addition.

Review findings

SeverityAreaFindingResolution
minorExisting editor UI testSingle swipe-down did not return to Name after keyboard viewport changesBounded return-to-field scroll and explicit hittability assertion; all original value/Save/Cancel checks retained. Affected native retry passed.
minorExisting prescription UI testUnnecessary positioning requirement continued dragging a reachable field without a keyboard and exhausted120sUse actual hittability when keyboard is absent; preserve keyboard-safe positioning, attempt bound,120s budget and all assertions. Affected retry passed.
minorSynthetic fixtureUnused shm and empty wal sidecarsRemoved exact owned files after verifying WAL was empty and primary fixture SHA unchanged.
minorEvidence wordingTask wording implied clearing was verified after reopenNarrowed wording: saved label reopen and separate clearing verification.

Tests

Source: local run at 2026-10-14T05:34:11.700039+00:00 · snapshot 52c4d32919a150e1cfccf54a69c22119654e135c

Baseline: none

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

Coverage scope: as the project configures it

Totals: 259 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 working-tree against base 011be8c1f0256fd18654909c93aa94750283b477.

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

Per-file diffs

18 files: 9 code · 9 docs. Click to expand.

Code (9)

Meddy/Meddy/ContentView.swift Modified
diff --git a/Meddy/Meddy/ContentView.swift b/Meddy/Meddy/ContentView.swiftindex 2ee2700..28a2b1a 100644--- a/Meddy/Meddy/ContentView.swift+++ b/Meddy/Meddy/ContentView.swift@@ -404,6 +404,7 @@ struct MedicationEditor: View {   @State private var limits: AsNeededLimitDraft   @State private var followup: MedicationFollowupDraft   @State private var prescription: PrescriptionDraft+  @State private var classification: MedicationClassificationDraft   @State private var name: String   @State private var description: String   @State private var amount: String@@ -433,6 +434,7 @@ struct MedicationEditor: View {     _limits = State(initialValue: AsNeededLimitDraft(medication: medication))     _followup = State(initialValue: MedicationFollowupDraft(medication: medication))     _prescription = State(initialValue: PrescriptionDraft(medication: medication))+    _classification = State(initialValue: MedicationClassificationDraft(medication: medication))     _name = State(initialValue: medication?.name ?? "")     _description = State(initialValue: medication?.doseDescription ?? "")     _amount = State(initialValue: medication?.defaultDoseAmount.map { String($0) } ?? "")@@ -466,6 +468,12 @@ struct MedicationEditor: View {       Form {         MeddySection("Medication") {           TextField("Name", text: $name)+          Picker("Medication type", selection: $classification.selection) {+            Text("Not set").tag(nil as MedicationClassification?)+            ForEach(MedicationClassification.allCases, id: \.self) { option in+              Text(option.title).tag(Optional(option))+            }+          }.accessibilityIdentifier("medicationClassificationPicker")           Picker("Purpose", selection: $purpose) {             Text("None").tag(nil as Purpose?)             ForEach(purposes.filter { !$0.isArchived || $0 == purpose }) { item in@@ -585,6 +593,7 @@ struct MedicationEditor: View {             saved, draft: draft, reminders: reminders)         }         try prescription.apply(to: saved, context: context)+        try classification.apply(to: saved, context: context)         try photo.apply(to: saved, context: context)         try followup.apply(to: saved)         if scheduleMode == .asNeeded {
Meddy/Meddy/Features/MedicationClassification.swift Modified
diff --git a/Meddy/Meddy/Features/MedicationClassification.swift b/Meddy/Meddy/Features/MedicationClassification.swiftnew file mode 100644index 0000000..ee075c2--- /dev/null+++ b/Meddy/Meddy/Features/MedicationClassification.swift@@ -0,0 +1,56 @@+import Foundation+import SwiftData+import SwiftUI++nonisolated enum MedicationClassification: String, CaseIterable, Sendable {+  case overTheCounter, prescription++  var title: String {+    switch self {+    case .overTheCounter: "Over the counter"+    case .prescription: "Prescription"+    }+  }+}++nonisolated enum MedicationClassificationError: LocalizedError {+  case changed+  var errorDescription: String? {+    "Medication type changed. Reopen the editor to use its current value."+  }+}++@MainActor @Observable final class MedicationClassificationDraft {+  var selection: MedicationClassification?+  private let original: String?+  private let medicationID: UUID?+  private let profileID: UUID?+  private let lifecycleID: UUID?++  init(medication: Medication?) {+    original = medication?.classificationRaw+    selection = medication?.classification+    medicationID = medication?.id+    profileID = medication?.profileID+    lifecycleID = medication.flatMap { item in+      item.modelContext.flatMap { try? ProfileAccess.lifecycle(item, context: $0) }+    }+  }++  func apply(to medication: Medication, context: ModelContext) throws {+    _ = try ProfileAccess.owner(medication, context: context)+    if let medicationID {+      guard medicationID == medication.id else { throw ProfileError.conflictingOwnership }+      try ProfileAccess.action(+        profileID, version: ProfileIdentity.ownershipVersion, lifecycle: lifecycleID,+        target: medication, context: context)+    }+    // Untouched drafts preserve newer values, including labels not understood by this version.+    guard selection != original.flatMap(MedicationClassification.init(rawValue:)) else { return }+    let entered = selection?.rawValue+    guard medication.classificationRaw == original || medication.classificationRaw == entered else {+      throw MedicationClassificationError.changed+    }+    medication.classificationRaw = entered+  }+}
Meddy/Meddy/Features/MedicationDetailView.swift Modified
diff --git a/Meddy/Meddy/Features/MedicationDetailView.swift b/Meddy/Meddy/Features/MedicationDetailView.swiftindex 0678eb7..03303a5 100644--- a/Meddy/Meddy/Features/MedicationDetailView.swift+++ b/Meddy/Meddy/Features/MedicationDetailView.swift@@ -23,6 +23,10 @@ struct MedicationDetailView: View {     List {       VStack(alignment: .leading, spacing: 10) {         Text(medication.name).font(.system(size: titleSize, weight: .bold))+        if let classification = medication.classification {+          Text(classification.title).font(.subheadline).foregroundStyle(MeddyStyle.secondary)+            .accessibilityIdentifier("medicationClassificationValue")+        }         HStack {           Text(medication.defaultDose.displayText).font(.subheadline).foregroundStyle(             MeddyStyle.secondary)
Meddy/Meddy/Models/Models.swift Modified
diff --git a/Meddy/Meddy/Models/Models.swift b/Meddy/Meddy/Models/Models.swiftindex dfd172c..fc8f7eb 100644--- a/Meddy/Meddy/Models/Models.swift+++ b/Meddy/Meddy/Models/Models.swift@@ -37,6 +37,7 @@ final class Medication {   var asNeededDoseLimitsData: Data?   var followupNotificationData: Data?   var recognitionPhotoData: Data?+  var classificationRaw: String?   var prescribedOn: String?   var prescribedBy: String?   var supplyDurationDays: Int?@@ -76,6 +77,10 @@ final class Medication {       description: doseDescription, amount: defaultDoseAmount, unit: defaultDoseUnit)   } +  var classification: MedicationClassification? {+    classificationRaw.flatMap(MedicationClassification.init(rawValue:))+  }+   var visibleAdministrations: [Administration] {     (administrations ?? []).filter { !$0.isDeleted }.sorted { $0.timestamp > $1.timestamp }   }
Meddy/MeddyTests/ClassificationFixtures/011be8c.store Modified
diff --git a/Meddy/MeddyTests/ClassificationFixtures/011be8c.store b/Meddy/MeddyTests/ClassificationFixtures/011be8c.storenew file mode 100644index 0000000..80fbc20Binary files /dev/null and b/Meddy/MeddyTests/ClassificationFixtures/011be8c.store differ
Meddy/MeddyTests/MeddyMedicationClassificationTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyMedicationClassificationTests.swift b/Meddy/MeddyTests/MeddyMedicationClassificationTests.swiftnew file mode 100644index 0000000..4a30bc6--- /dev/null+++ b/Meddy/MeddyTests/MeddyMedicationClassificationTests.swift@@ -0,0 +1,148 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++@MainActor struct MeddyMedicationClassificationTests {+  private func fixture() throws -> (ModelContainer, Medication) {+    let store = try AppEnvironment.makeContainer(isolated: true)+    let item = try MedicationService(context: store.mainContext).createAsNeededMedication(+      name: "Synthetic classification medicine")+    return (store, item)+  }++  private func save(_ value: MedicationClassification?, item: Medication, context: ModelContext) throws {+    let draft = MedicationClassificationDraft(medication: item)+    draft.selection = value+    try EditorTransaction.save(context: context) { try draft.apply(to: item, context: context) }+  }++  @Test func defaultsStayUnsetAndPrescriptionDetailsNeverInferClassification() throws {+    let (store, item) = try fixture()+    #expect(item.classification == nil && item.classificationRaw == nil)+    item.prescribedOn = "2026-10-08"+    item.prescribedBy = "Synthetic clinic"+    item.repeatsLeft = 3+    try store.mainContext.save()+    let draft = MedicationClassificationDraft(medication: item)+    #expect(draft.selection == nil && !store.mainContext.hasChanges)+    try EditorTransaction.save(context: store.mainContext) {+      try draft.apply(to: item, context: store.mainContext)+    }+    #expect(item.classification == nil && item.prescriptionRevision == nil)+  }++  @Test func bothLabelsAndClearingPersistWithoutChangingCareOrPrescription() throws {+    let (store, item) = try fixture()+    item.repeatsLeft = 2+    let revision = UUID()+    item.prescriptionRevision = revision+    try store.mainContext.save()+    let schedule = try ScheduleService(context: store.mainContext).snapshot(item)+    for choice in [MedicationClassification.overTheCounter, .prescription] {+      try save(choice, item: item, context: store.mainContext)+      let reloaded = try #require(try ModelContext(store).fetch(FetchDescriptor<Medication>()).first)+      #expect(reloaded.classification == choice && reloaded.classificationRaw == choice.rawValue)+      #expect(reloaded.repeatsLeft == 2 && reloaded.prescriptionRevision == revision)+      #expect(try ScheduleService(context: store.mainContext).snapshot(item) == schedule)+      #expect(!item.remindersEnabled)+    }+    try save(nil, item: item, context: store.mainContext)+    #expect(item.classificationRaw == nil && item.repeatsLeft == 2)+    #expect(try store.mainContext.fetchCount(FetchDescriptor<Administration>()) == 0)+  }++  @Test func cancelledDraftAndFailedTransactionLeaveStoredLabelUnchangedAndRetryWorks() throws {+    let (store, item) = try fixture()+    try save(.overTheCounter, item: item, context: store.mainContext)+    let draft = MedicationClassificationDraft(medication: item)+    draft.selection = .prescription+    #expect(item.classification == .overTheCounter && !store.mainContext.hasChanges)+    #expect(throws: RecordingError.self) {+      try EditorTransaction.save(context: store.mainContext) {+        try draft.apply(to: item, context: store.mainContext)+        throw RecordingError.saveFailed+      }+    }+    let context = ModelContext(store)+    let reloaded = try #require(try context.fetch(FetchDescriptor<Medication>()).first)+    #expect(reloaded.classification == .overTheCounter)+    try EditorTransaction.save(context: store.mainContext) {+      try draft.apply(to: item, context: store.mainContext)+    }+    let retried = try #require(try ModelContext(store).fetch(FetchDescriptor<Medication>()).first)+    #expect(retried.classification == .prescription)+  }++  @Test func untouchedDraftPreservesNewerAndUnrecognizedValuesWhileConflictingEditFails() throws {+    let (store, item) = try fixture()+    let untouched = MedicationClassificationDraft(medication: item)+    let conflicting = MedicationClassificationDraft(medication: item)+    try save(.prescription, item: item, context: store.mainContext)+    try untouched.apply(to: item, context: store.mainContext)+    #expect(item.classification == .prescription)+    conflicting.selection = .overTheCounter+    #expect(throws: MedicationClassificationError.self) {+      try conflicting.apply(to: item, context: store.mainContext)+    }+    #expect(item.classification == .prescription)+    item.classificationRaw = "synthetic-future-label"+    try store.mainContext.save()+    try MedicationClassificationDraft(medication: item).apply(to: item, context: store.mainContext)+    #expect(item.classification == nil && item.classificationRaw == "synthetic-future-label")+  }++  @Test func capturedOwnerAndLifecyclePreventRetargetingOrStaleProfileEdits() throws {+    let (store, item) = try fixture()+    let context = store.mainContext+    let profiles = ProfileService(context: context)+    let profile = try profiles.create(displayName: "Synthetic classification owner")+    let other = try MedicationService(context: context).createAsNeededMedication(+      name: item.name, profileID: profile.id)+    let wrongTarget = MedicationClassificationDraft(medication: item)+    wrongTarget.selection = .prescription+    #expect(throws: ProfileError.self) { try wrongTarget.apply(to: other, context: context) }+    let stale = MedicationClassificationDraft(medication: other)+    stale.selection = .overTheCounter+    try profiles.setArchived(profile, true)+    #expect(throws: ProfileError.self) { try stale.apply(to: other, context: context) }+    try profiles.setArchived(profile, false)+    #expect(throws: ProfileError.self) { try stale.apply(to: other, context: context) }+    #expect(item.classification == nil && other.classification == nil)+    try save(.overTheCounter, item: other, context: context)+    #expect(other.classification == .overTheCounter && item.classification == nil)+  }++  @Test func exactPreClassificationStoreUpgradesWithoutInferringLabelsAndReopens() throws {+    let bundle = Bundle(for: ClassificationFixtureMarker.self)+    let source = try #require(bundle.url(forResource: "011be8c", withExtension: "store"))+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+    defer { try? FileManager.default.removeItem(at: directory) }+    let file = directory.appendingPathComponent("synthetic-classification.store")+    try FileManager.default.copyItem(at: source, to: file)+    let schema = AppEnvironment.schema+    func open() throws -> ModelContainer {+      try ModelContainer(for: schema, configurations: [+        ModelConfiguration(schema: schema, url: file, cloudKitDatabase: .none)])+    }+    let store = try open()+    let items = try store.mainContext.fetch(FetchDescriptor<Medication>())+    #expect(items.count == 2 && items.allSatisfy { $0.classificationRaw == nil })+    let item = try #require(items.first { $0.id.uuidString == "71F91A0F-35B8-4750-B08A-5E7387AAC407" })+    #expect(item.prescribedOn == "2026-10-08" && item.prescribedBy == "Synthetic clinic")+    #expect(item.repeatsLeft == 3 && item.defaultDoseAmount == 2)+    #expect(try store.mainContext.fetch(FetchDescriptor<Administration>()).first?.isDeleted == true)+    #expect(try store.mainContext.fetch(FetchDescriptor<RoutineRun>()).first?.definitionSnapshotData+      == Data("Synthetic unchanged frozen bytes".utf8))+    try save(.overTheCounter, item: item, context: store.mainContext)+    let reopened = try open()+    let reloaded = try #require(try reopened.mainContext.fetch(FetchDescriptor<Medication>()).first { $0.id == item.id })+    #expect(reloaded.classification == .overTheCounter && reloaded.repeatsLeft == 3)+    #expect(reloaded.prescribedOn == item.prescribedOn && reloaded.purpose?.id == item.purpose?.id)+    #expect(try reopened.mainContext.fetch(FetchDescriptor<Administration>()).first?.isDeleted == true)+  }+}++private final class ClassificationFixtureMarker: NSObject {}
Meddy/MeddyUITests/MeddyEditorUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyEditorUITests.swift b/Meddy/MeddyUITests/MeddyEditorUITests.swiftindex 14a873f..a5c9a65 100644--- a/Meddy/MeddyUITests/MeddyEditorUITests.swift+++ b/Meddy/MeddyUITests/MeddyEditorUITests.swift@@ -28,6 +28,9 @@ final class MeddyEditorUITests: XCTestCase {       let form = app.collectionViews.element(boundBy: app.collectionViews.count - 1)       form.swipeUp()       form.swipeDown()+      // Keyboard dismissal changes the viewport; return to the field before checking its draft.+      for _ in 0..<4 where !name.isHittable { form.swipeDown() }+      XCTAssertTrue(name.isHittable)       XCTAssertEqual(name.value as? String, "Synthetic cancelled " + kind)       XCTAssertTrue(app.buttons["Save"].isHittable)       XCTAssertTrue(app.buttons["Cancel"].isHittable)
Meddy/MeddyUITests/MeddyMedicationClassificationUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyMedicationClassificationUITests.swift b/Meddy/MeddyUITests/MeddyMedicationClassificationUITests.swiftnew file mode 100644index 0000000..585b9b8--- /dev/null+++ b/Meddy/MeddyUITests/MeddyMedicationClassificationUITests.swift@@ -0,0 +1,48 @@+import XCTest++@MainActor final class MeddyMedicationClassificationUITests: XCTestCase {+  func testOptionalTypeSavesCancelsAndClearsInNormalEditor() {+    continueAfterFailure = false+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launch()+    XCTAssertTrue(app.tabBars.buttons["Medications"].waitForExistence(timeout: 10))+    app.tabBars.buttons["Medications"].tap()+    app.buttons["Add medication"].tap()+    let name = app.textFields["Name"]+    XCTAssertTrue(name.waitForExistence(timeout: 5))+    name.tap()+    name.typeText("Synthetic labelled medicine")+    choose("Prescription", app: app)+    app.buttons["Save"].tap()+    app.buttons["Synthetic labelled medicine"].tap()+    let label = app.staticTexts["medicationClassificationValue"]+    XCTAssertTrue(label.waitForExistence(timeout: 5))+    XCTAssertEqual(label.label, "Prescription")+    app.buttons["Edit"].tap()+    choose("Over the counter", app: app)+    app.buttons["Cancel"].tap()+    XCTAssertEqual(label.label, "Prescription")+    app.buttons["Edit"].tap()+    choose("Over the counter", app: app)+    app.buttons["Save"].tap()+    XCTAssertEqual(label.label, "Over the counter")+    app.buttons["Edit"].tap()+    choose("Not set", app: app)+    app.buttons["Save"].tap()+    XCTAssertFalse(label.exists)+    XCTAssertFalse(app.alerts.firstMatch.exists)+    let shot = XCTAttachment(screenshot: app.screenshot())+    shot.name = "synthetic-classification-cleared-detail"+    shot.lifetime = .keepAlways+    add(shot)+  }++  private func choose(_ title: String, app: XCUIApplication) {+    let picker = app.buttons["medicationClassificationPicker"]+    XCTAssertTrue(picker.waitForExistence(timeout: 5))+    if app.keyboards.firstMatch.exists { app.collectionViews.firstMatch.swipeDown() }+    picker.tap()+    app.buttons[title].tap()+  }+}
Meddy/MeddyUITests/MeddyPrescriptionUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyPrescriptionUITests.swift b/Meddy/MeddyUITests/MeddyPrescriptionUITests.swiftindex 39a896e..134551d 100644--- a/Meddy/MeddyUITests/MeddyPrescriptionUITests.swift+++ b/Meddy/MeddyUITests/MeddyPrescriptionUITests.swift@@ -25,7 +25,10 @@ import XCTest       for attempt in 0..<16 {         if element.exists {           let vertical = element.frame.midY-          if element.isHittable && vertical > 160 && vertical < app.frame.height * 0.55 { return }+          // Without a keyboard, a reachable field needs no extra positioning near the top.+          let keyboardSafe = !app.keyboards.firstMatch.exists+            || (vertical > 160 && vertical < app.frame.height * 0.55)+          if element.isHittable && keyboardSafe { return }           scroll(vertical < 160, app: app)         } else {           scroll(attempt >= 8, app: app)

Docs (9)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8d630f1..6a929d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ - T2413: Keep notification snoozes at their chosen 15-minute deadline, cancel queued originals, suppress elapsed replay and await background scheduling completion.  ### Added+- T2453: Optional Over the counter / Prescription medication type in the normal editor and read-only detail, with existing entries unset and no prescription inference or scheduling changes. - Tap a medication detail recognition photo to view its full stored image uncropped, with pinch/pan, accessible zoom controls and Done; keep the inline photo circular and stored bytes unchanged. - Short single-tone feedback for saved iPhone timer start/resume, and the same tone plus a short haptic for pause/end. Round completion retains its distinct two-tone/two-pulse feedback. - `make install` and `make install-release` for signed, in-place Debug/Release iPhone updates, with explicit device overrides and phone-only packaging.
Meddy/MeddyTests/ClassificationFixtures/classification-fixture-provenance.md Modified
diff --git a/Meddy/MeddyTests/ClassificationFixtures/classification-fixture-provenance.md b/Meddy/MeddyTests/ClassificationFixtures/classification-fixture-provenance.mdnew file mode 100644index 0000000..34d746b--- /dev/null+++ b/Meddy/MeddyTests/ClassificationFixtures/classification-fixture-provenance.md@@ -0,0 +1,5 @@+# Synthetic pre-classification fixture++`011be8c.store` was generated by a single isolated test-only writer against archived, unchanged PR #11 production source 011be8c1f0256fd18654909c93aa94750283b477. The native writer passed; CloudKit was disabled. SQLite backup copied the synthetic committed store after the runner exited.++It contains two synthetic medication rows, existing prescription fields, a purpose link, one tombstoned administration and retained routine bytes. The schema has prescription columns and no classification column. No personal data or live store was read. Provenance and full writer receipt are retained in `/Users/arjen/Documents/Codex/2026-10-05/task/meddy-medication-classification-evidence/fixture-provenance.json` and `baseline-writer.json`.
docs/meddy-design.md Modified
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex 322fa60..22cfff6 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -90,6 +90,8 @@ A `Medication` is a user-defined entry for either a configured regimen/course or  A medication contains practical information needed when taking/administering it. +A medication may also carry an optional user-entered **Medication type**: **Over the counter** or **Prescription**. Existing and name-only entries stay unset. Set or clear it in the normal editor and show the known label read-only on detail. Prescription dates, prescribers and repeats do not infer or constrain this label; changing it does not change schedules, reminders or care history.+ Examples:  - Name: `Doxycycline`
docs/meddy-implementation-plan.md Modified
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex a236266..a06ffa6 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -362,3 +362,12 @@ The fixture predates profile/wake additions; exact installed-store and live Clou ## Circular recognition-photo presentation  Following owner-tested feedback, the shared `MedicationPhotoView` uses aspect-fill inside a circular mask at the existing 24/32/48/160/220-point sizes. Its circular background also covers the unreadable-photo fallback. This applies to all current iPhone call sites, including Today/library, detail, photo editor, detailed dose logging and routine medication selection/steps. There is no stored image crop, model/import/cache change, new permission, photo-control change or Watch deployment. Both existing targeted dark/light photo UI journeys passed at clean `299076a`, command exit 0 in 176.033 seconds. They retain every profile/draft/Save/Cancel/220-point detail/160-point dose assertion. All 12 native captures were viewed: Today/PRN, library, detail, editor and dose logging in each appearance; circle edges and centered aspect-fill are visible, with readable names and reachable photo controls. Routine call sites use the same shared component and were source-reviewed; no separate routine-photo screenshot acceptance is claimed. Three earlier two-appearance attempts failed because SwiftUI exposed the uncropped 80:60 image buffer’s 293.3-point width for a 220-point circle. The final component uses Apple’s [accessibility representation API](https://developer.apple.com/documentation/swiftui/view/accessibilityrepresentation%28representation%3A%29) to expose the actual circular size, existing loaded/unavailable name, image trait and identifier; source review confirms that this is appropriate for the noninteractive photo. The existing detail capture moved before its unchanged frame assertion to retain direct diagnostics. Earlier failed runs remain recorded separately, and none counts as acceptance. Strict SwiftLint passed 111 files with zero violations; whitespace passed. Four source-review perspectives and the accessibility follow-up are clean. Stored data/import/cache and ownership source are unchanged. No broad suite, real-photo/store operation, signing/account change, merge, physical Watch work or installation ran. Assigned simulators were restored to Shutdown, owned groups drained and the heavy lane released.+++## T2453 — Optional medication classification++User-authorized small addition: normal medication editor offers Not set, Over the counter and Prescription; detail shows a known label read-only. A nullable raw-string attribute leaves old/new entries unset until explicitly labelled. Draft save/clear is atomic with existing metadata and guarded by current owner/lifecycle and concurrent-value checks. Prescription values and repeat revision, dose/schedule/reminder behavior, Watch payloads and export remain unchanged.++The feature branch depends on accepted installed PR #11 source 011be8c; no merge or additional installation is authorized. Requirements/design/tasks are in `specs/medication-classification/`. An exact pre-classification synthetic store was generated by archived unchanged PR #11 production source plus one test-only writer. It contains current prescription fields, a tombstoned administration, purpose link and retained routine bytes; its schema has no classification column.++Focused checks: 24 native tests across five suites and one editor Save/Cancel/clear UI journey passed. The fixture upgrades with both labels unset, preserves records and persists an explicit label across reopen. Strict lint: 121 files, zero violations. An initial build-only resource filename collision was corrected by uniquely naming the new fixture provenance file; its failed receipt is retained and not passing evidence. Final gate coverage is 224 phone domain tests, 14 Watch tests and 21 UI cases in aggregate. The initial full UI attempt passed 19 and failed two visibility assumptions; both affected retries passed after reviewed test corrections under the original 120-second budgets and assertions. Initial failures are retained; no fresh complete pre-push pass is claimed. Four pre-push review perspectives found no blocking issues. No live CloudKit/schema publication, real records, account/signing/entitlement changes, merge or deployment occurred.
specs/medication-classification/decision_log.md Modified
diff --git a/specs/medication-classification/decision_log.md b/specs/medication-classification/decision_log.mdnew file mode 100644index 0000000..20d577a--- /dev/null+++ b/specs/medication-classification/decision_log.md@@ -0,0 +1,8 @@+# Quick decisions++| ID | Decision | Reason |+| --- | --- | --- |+| D1 | Store a nullable raw string with two known display values. | Match existing additive optional metadata; old rows stay unset and unknown raw values are preserved by untouched drafts. |+| D2 | Keep classification separate from prescription details and repeat revision. | The user supplies the type explicitly; changing a label must not infer or alter prescription information or repeat Undo. |+| D3 | Base the new branch and draft PR on accepted PR #11 while it is unmerged. | Retain the installed speed-up without merging or accidentally working from older main. |+| D4 | Verify actual prior-schema migration with a synthetic store from exact 011be8c source. | Core Data guidance is not proof of this SwiftData schema; no live-store inspection is needed. |
specs/medication-classification/design.md Modified
diff --git a/specs/medication-classification/design.md b/specs/medication-classification/design.mdnew file mode 100644index 0000000..654e811--- /dev/null+++ b/specs/medication-classification/design.md@@ -0,0 +1,23 @@+# Medication classification design++## Data and draft++Add nullable `Medication.classificationRaw: String?`, matching existing optional prescription metadata. Stable known values are `overTheCounter` and `prescription`; nil remains unset. A small enum provides display titles without changing encoded care/schedule/Watch payloads. Unknown raw labels are not guessed and remain intact when a draft is untouched.++`MedicationClassificationDraft` follows the existing editor draft pattern: capture the original value, medication ID, owner and lifecycle; keep changes separate until Save. Its synchronous apply validates current ownership, preserves newer untouched values and rejects conflicting edits. The existing `EditorTransaction` owns the combined save and rollback. Classification does not modify `prescriptionRevision`, so repeat Undo retains its existing semantics.++## Presentation++Place a native Medication type picker in the existing Medication editor section. Show the known label beneath the medication name on detail. Keep it informational and read-only there. No classification is inferred from medicine names or prescription data.++## Compatibility and verification++One nullable scalar attribute adds no required value, uniqueness constraint, relationship or migration side effect. This follows the existing additive SwiftData metadata pattern. Apple describes simple attribute additions as candidates for inferred lightweight migration; exact SwiftData compatibility is established by opening a synthetic store made from unchanged PR #11 production source, not assumed from Core Data guidance. [Apple lightweight migration](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreDataVersioning/Articles/vmLightweightMigration.html).++The synthetic fixture includes existing prescription fields, a tombstoned administration, purpose link and opaque retained-run bytes. Domain checks cover nil/no inference, both labels/clear, persistence/reopen, cancel/failed transaction/retry, current-value conflicts and owner/lifecycle fences. One UI journey covers normal editor Save/Cancel/clear and read-only detail. Model container lifetimes remain retained; every fixture uses CloudKit.none.++Apple documents additive-only CloudKit schemas: adding a field does not authorize deleting production fields or changing their types. The optional scalar introduces no uniqueness or relationship constraint. [Apple SwiftData/CloudKit guidance](https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices). No live CloudKit schema publication, sync test or downgrade-to-old-binary guarantee is claimed. Existing app/team/container entitlements remain unchanged. Required final gates run once after focused development checks, with inherited failures reported rather than hidden.++## Dependency++Base this feature on PR #11 at 011be8c, with its branch as the draft PR base while unmerged. Do not merge the dependency or deploy this addition automatically. Retargeting to main belongs to a later authorized merge/rebase action.
specs/medication-classification/implementation.md Modified
diff --git a/specs/medication-classification/implementation.md b/specs/medication-classification/implementation.mdnew file mode 100644index 0000000..2a88fcb--- /dev/null+++ b/specs/medication-classification/implementation.md@@ -0,0 +1,38 @@+# Medication classification implementation++## Beginner Level++### What Changed+The existing medication editor offers Not set, Over the counter and Prescription. A selected label appears beneath the medication name on detail. Existing medications remain unset.++### Why It Matters+The owner can record this distinction without changing doses, reminders or prescription repeat accounting. Save stores the selection; Cancel leaves the stored medication unchanged.++### Key Concepts+An optional field can hold a label or no value. The editor keeps a draft until Save, so selecting an option does not immediately change stored records.++## Intermediate Level++### Changes Overview+Medication adds nullable classificationRaw. MedicationClassification maps stable raw values to display titles. MedicationClassificationDraft integrates with the existing EditorTransaction. ContentView adds the native picker; MedicationDetailView displays a known value read-only.++### Implementation Approach+The draft captures medication identity, owner, lifecycle and original raw value. Apply validates current ownership, preserves newer untouched values and rejects conflicting edited values. The shared editor transaction retains combined Save/rollback behavior. Classification never advances prescriptionRevision.++### Trade-offs+A scalar fits the existing additive metadata model and avoids coupling this informational label to prescription dates or repeat rules. Unknown values remain intact in an untouched draft; this version displays only its two known labels.++## Expert Level++### Technical Deep Dive+Apply resolves current ownership before writing, checks captured identity and profile lifecycle, then compares the edited selection with the original known value. Untouched drafts return without overwriting concurrent or unrecognized values. Changed drafts accept the original raw value or an already-applied identical value; other current values produce a reopen-editor error. Profile archive/restore invalidates a stale draft.++### Architecture Impact+The field is additive and optional, with no relationship, uniqueness or encoded schedule/Watch payload changes. Compatibility is exercised against a synthetic SQLite store generated from unchanged production source 011be8c. Tests retain containers and disable CloudKit. CloudKit schema changes remain additive; no live schema promotion, live sync or old-binary downgrade guarantee is claimed.++### Potential Issues+Unknown labels cannot be selected here and remain hidden on detail until understood by a later version. Replacing one with a supported label requires an explicit edited selection. Conflicting edits ask the owner to reopen the editor. The feature PR depends on unmerged PR #11 and must keep that dependency explicit.++## Completeness Assessment++The requested optional label, normal editor Save/Cancel/clear, read-only detail, no inference, captured ownership/lifecycle checks and prior-store compatibility are implemented. Focused checks passed. Final coverage comprises 224 phone domain tests, 14 Watch tests and 21 UI cases in aggregate:19 retained passes from the initial full UI run and 2 passing affected retries after reviewed visibility corrections. The initial full UI attempt failed those 2 cases and remains retained; a fresh complete pre-push pass is not claimed. No further product behavior is required by this scope.
specs/medication-classification/requirements.md Modified
diff --git a/specs/medication-classification/requirements.md b/specs/medication-classification/requirements.mdnew file mode 100644index 0000000..54b8949--- /dev/null+++ b/specs/medication-classification/requirements.md@@ -0,0 +1,27 @@+# Medication classification — T-2453++Medication entries can carry an explicit user-entered type. This label helps distinguish prescription medication from over-the-counter medication without changing recorded care.++## 1. Optional label++As the owner, I want to label a medication so I can see which type I entered.++1. WHEN a medication has no entered type, Meddy SHALL leave it unset, including existing entries with prescription dates, prescribers or repeats.+2. WHEN editing or adding a medication, the normal editor SHALL offer Not set, Over the counter and Prescription.+3. WHEN Save succeeds, detail SHALL display the selected known label read-only; clearing it SHALL remove that label.+4. WHEN Cancel is used or the transaction fails, the persisted label SHALL remain unchanged.+5. WHEN a newer label was saved after the editor opened, an untouched draft SHALL preserve it and a conflicting edited draft SHALL report an error.++## 2. Existing data and ownership++As the owner, I want this addition to preserve my existing medication records.++1. WHEN an old store is opened, its medication identities, prescription fields, dose history and routine bytes SHALL be preserved, with the new label unset.+2. WHEN editing a dependant’s medication, the update SHALL remain scoped to the captured medication, owner and profile lifecycle.+3. WHEN changing a label, existing schedules, reminders, prescription repeat accounting and actual-care history SHALL remain unchanged.++## Non-goals++Automatic classification; new Watch/export fields; sorting/filtering; clinical guidance; schema publication; account changes; merge or installation.++The feature depends on accepted installed PR #11 source 011be8c. New work is isolated on T-2453/feature-medication-classification and must retain that performance fix.
specs/medication-classification/tasks.md Modified
diff --git a/specs/medication-classification/tasks.md b/specs/medication-classification/tasks.mdnew file mode 100644index 0000000..d4700f6--- /dev/null+++ b/specs/medication-classification/tasks.md@@ -0,0 +1,6 @@+# Medication classification tasks++1. [x] Optional type is editable and displayed read-only without changing care or prescription metadata. Verify requirements.md 1–2 through targeted domain/editor checks.+2. [x] Existing PR #11 synthetic data opens with unset type and retains old records; a saved label survives reopen and clearing is verified separately. Verify requirements.md 2.1 through the exact old-source fixture.+3. [x] Normal editor Save/Cancel/clear produces the expected detail label. Verify requirements.md 1.2–1.4 with the affected UI journey.+4. [x] Required final gate coverage and lint/whitespace checks complete, and documented evidence matches the source. Phone 224 / Watch 14 pass; UI 21 in aggregate (initial 19 pass / 2 fail, reviewed corrections and 2 affected retries pass). Original failures retained; no fresh full pre-push pass claimed. Verify requirements.md 1–2 without merging or installing.

Things to double-check

CloudKit boundary

Optional additive model reviewed; no live CloudKit publication/sync or old-binary downgrade guarantee. Existing entitlements and account remain unchanged.

Source preservation

The targeted retry source manifests match before/after. Production source matches the prior phone/Watch/full-UI run; only two reviewed UI visibility corrections changed afterward.