Meddy baseline 9197303 files 25 review 4 independent scopes

Pre-push review: Meddy developer-account migration

Final identity migration and explicitly confirmed starter-profile import recovery, preserving current upstream features and restored data.

At a glance

  • Phone, Watch, tests, widget and CloudKit selectors align with the selected account. Final App Group and widget use singular widget.

  • A cold local-only recovery session validates the backup and exact two starter rows before explicit in-app consent and a single receipt-bearing save.

  • The restored phone display name is Meddy. Original untracked handoff files are excluded; no clinical data is included in this review.

  • Native xcresult/log evidence: 352 phone domain, 14 Watch, 31 UI cases; no unresolved test failure. The ecosystem catalog has no Xcode/JUnit runner, so the generic Tests card reports runner not detected rather than inventing JUnit or coverage data.

Verdict

Ready to push

Four independent review scopes completed. UI-thread verification was fixed and independently re-reviewed. Widget build, 352 phone domain tests, 14 Watch tests and all 31 UI cases are verified on unchanged source. The initial UI wrapper failed during ENOSPC; four photo cases and the truncated navigation record have clean targeted reruns, with failed evidence retained rather than counted as a passing full command.

Review findings

1 raised · 1 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 19

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

Meddy now uses the new developer account. The app keeps backup/restore, widgets and prescription features from current main. A user-confirmed recovery can replace only two unused starter profiles with a validated backup, preserving other data.

The recovery launch reopens the normal persistent URL without managed CloudKit mirroring and omits care/bootstrap producers. Consent binds persistent row identities and canonical values to the archive hash. Existing gate, journal, insertion and receipt logic provide rollback and crash completion.

A local file lock cannot exclude independent CloudKit writes; synthetic probes demonstrate selected-row data-loss risk under ordinary save races. The cold configuration removes that managed writer for this bounded session, followed by exact pre-save revalidation. It is local admission, not distributed atomicity or a claim of remote emptiness. Async input verification avoids decoding large archives on MainActor.

Important changes — detailed

Identity: align all live selectors

Meddy/Meddy.xcodeproj/project.pbxproj

Why it matters. Prevents app, widget and container mismatches under the selected developer team.

What to look at. Debug/Release bundle settings and companion references

Takeaway. Inventory both entitlements and runtime selectors, not only the phone bundle.
Rationale. User-selected destination identity; historical provisioning records remain historical.

Startup: bound recovery to a cold local-only session

Meddy/Meddy/App/AppEnvironment.swift

Why it matters. Prevents managed CloudKit writers during the scoped restore commit.

What to look at. makeContainer and DefaultProfileRecovery.configuration

Takeaway. Preserve the exact persistent URL while selecting the supported local-only configuration.
Rationale. Independent-writer probes showed why a UI check or post-save comparison alone was insufficient.

Importer: bind consent to rows and archive

Meddy/Meddy/Services/Backups/PhoneBackupImporter.swift

Why it matters. Refuses changed/nonempty destinations and preserves atomic rollback/recovery.

What to look at. defaultProfileProof, restorationBaseline, commit and typed journal proof

Takeaway. Consent is a one-archive snapshot, not a reusable empty-store boolean.
Rationale. User approved only an explicit replacement of unused starter profiles.

UI: confirm, cancel and finish explicitly

Meddy/Meddy/Features/BackupRestoreView.swift

Why it matters. The user selects the real backup and confirms replacement; the agent never performs the import.

What to look at. reviewDefaultProfiles, confirmation alert and completion lifecycle

Takeaway. Move heavy revalidation off the main actor, then recheck admission after suspension.
Rationale. Independent efficiency review found synchronous full archive decoding on the confirmation path.

Key decisions

No broad reset or silent legacy fingerprint

Only the two exact default-shaped rows can be confirmed; care/history, reminder semantics, receipts, changed values and other profiles remain protected.

Preserve existing team choices

The Watch UI-test target retains its pre-existing old team. Physical Watch deployment and runtime CloudKit reconciliation remain outside the verified scope.

Review findings

SeverityAreaFindingResolution
majorRecovery review UI responsivenessFull archive read/hash/decode ran synchronously on MainActor.Run verifiedInput in Task.detached, return only archive ID, recheck destination under the held permit; show progress. Independent reviewer confirmed resolution.

Tests

Source: local run at 2026-10-26T23:39:13.555947+00:00 · snapshot acfd17fc8275c102009741f7d6f9ab66d54ecaf1 (dirty working tree)

Baseline: none

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

Coverage scope: as the project configures it

No test results

The test runner could not be detected.

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 9197303fe3ddd49a9d398a7498fb1e71bebefcd9.

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

Per-file diffs

25 files: 15 code · 10 docs. Click to expand.

Code (15)

Meddy/Meddy.xcodeproj/project.pbxproj Modified
diff --git a/Meddy/Meddy.xcodeproj/project.pbxproj b/Meddy/Meddy.xcodeproj/project.pbxprojindex fe74333..b2aaf81 100644--- a/Meddy/Meddy.xcodeproj/project.pbxproj+++ b/Meddy/Meddy.xcodeproj/project.pbxproj@@ -695,7 +695,7 @@ 				CODE_SIGN_ENTITLEMENTS = Meddy/Meddy.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES; 				ENABLE_USER_SELECTED_FILES = readonly;@@ -714,7 +714,7 @@ 				LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; 				"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				REGISTER_APP_GROUPS = YES; 				SDKROOT = auto;@@ -737,7 +737,7 @@ 				CODE_SIGN_ENTITLEMENTS = Meddy/Meddy.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES; 				ENABLE_USER_SELECTED_FILES = readonly;@@ -756,7 +756,7 @@ 				LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks"; 				"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks"; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				REGISTER_APP_GROUPS = YES; 				SDKROOT = auto;@@ -777,9 +777,10 @@ 			buildSettings = { 				BUNDLE_LOADER = "$(TEST_HOST)"; 				CODE_SIGN_STYLE = Automatic;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.tests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.tests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";@@ -796,9 +797,10 @@ 			buildSettings = { 				BUNDLE_LOADER = "$(TEST_HOST)"; 				CODE_SIGN_STYLE = Automatic;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.tests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.tests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";@@ -814,9 +816,10 @@ 			isa = XCBuildConfiguration; 			buildSettings = { 				CODE_SIGN_STYLE = Automatic;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.uitests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.uitests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";@@ -832,9 +835,10 @@ 			isa = XCBuildConfiguration; 			buildSettings = { 				CODE_SIGN_STYLE = Automatic;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.uitests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.uitests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";@@ -854,19 +858,19 @@ 				CODE_SIGN_ENTITLEMENTS = MeddyWatch/MeddyWatch.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				ENABLE_PREVIEWS = YES; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = MeddyWatch/Info.plist; 				INFOPLIST_KEY_CFBundleDisplayName = Meddy; 				INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";-				INFOPLIST_KEY_WKCompanionAppBundleIdentifier = me.nore.ig.meddy;+				INFOPLIST_KEY_WKCompanionAppBundleIdentifier = me.nore.ig.apps.meddy; 				LD_RUNPATH_SEARCH_PATHS = ( 					"$(inherited)", 					"@executable_path/Frameworks", 				); 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				SKIP_INSTALL = YES;@@ -888,19 +892,19 @@ 				CODE_SIGN_ENTITLEMENTS = MeddyWatch/MeddyWatch.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				ENABLE_PREVIEWS = YES; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = MeddyWatch/Info.plist; 				INFOPLIST_KEY_CFBundleDisplayName = Meddy; 				INFOPLIST_KEY_UISupportedInterfaceOrientations = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";-				INFOPLIST_KEY_WKCompanionAppBundleIdentifier = me.nore.ig.meddy;+				INFOPLIST_KEY_WKCompanionAppBundleIdentifier = me.nore.ig.apps.meddy; 				LD_RUNPATH_SEARCH_PATHS = ( 					"$(inherited)", 					"@executable_path/Frameworks", 				); 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				SKIP_INSTALL = YES;@@ -921,10 +925,10 @@ 				BUNDLE_LOADER = "$(TEST_HOST)"; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp.tests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp.tests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -944,10 +948,10 @@ 				BUNDLE_LOADER = "$(TEST_HOST)"; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp.tests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp.tests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -970,7 +974,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				GENERATE_INFOPLIST_FILE = YES; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp.uitests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp.uitests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -991,7 +995,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				GENERATE_INFOPLIST_FILE = YES; 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.watchkitapp.uitests;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.watchkitapp.uitests; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = watchos; 				STRING_CATALOG_GENERATE_SYMBOLS = NO;@@ -1012,7 +1016,7 @@ 				CODE_SIGN_ENTITLEMENTS = MeddyWidgets/MeddyWidgets.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = MeddyWidgets/Info.plist; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;@@ -1022,7 +1026,7 @@ 					"@executable_path/../../Frameworks", 				); 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.widgets;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.widget; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SKIP_INSTALL = YES;@@ -1041,7 +1045,7 @@ 				CODE_SIGN_ENTITLEMENTS = MeddyWidgets/MeddyWidgets.entitlements; 				CODE_SIGN_STYLE = Automatic; 				CURRENT_PROJECT_VERSION = 1;-				DEVELOPMENT_TEAM = V24684SCZN;+				DEVELOPMENT_TEAM = 4PJS97G236; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = MeddyWidgets/Info.plist; 				IPHONEOS_DEPLOYMENT_TARGET = 27.0;@@ -1051,7 +1055,7 @@ 					"@executable_path/../../Frameworks", 				); 				MARKETING_VERSION = 1.0;-				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.meddy.widgets;+				PRODUCT_BUNDLE_IDENTIFIER = me.nore.ig.apps.meddy.widget; 				PRODUCT_NAME = "$(TARGET_NAME)"; 				SDKROOT = iphoneos; 				SKIP_INSTALL = YES;
Meddy/Meddy/App/AppEnvironment.swift Modified
diff --git a/Meddy/Meddy/App/AppEnvironment.swift b/Meddy/Meddy/App/AppEnvironment.swiftindex fbc40ec..d8dff7f 100644--- a/Meddy/Meddy/App/AppEnvironment.swift+++ b/Meddy/Meddy/App/AppEnvironment.swift@@ -4,6 +4,7 @@ import SwiftData @MainActor enum AppEnvironment {   private static var liveContainer: ModelContainer?+  private(set) static var defaultProfileRecoveryActive = false   private static var widgetServices: [ObjectIdentifier: WidgetSnapshotService] = [:]   static func widgets(for context: ModelContext) -> WidgetSnapshotService? {     widgetServices[ObjectIdentifier(context)]@@ -26,7 +27,8 @@ enum AppEnvironment {   static func backupImporter(container: ModelContainer) -> PhoneBackupImporter {     PhoneBackupImporter(       container: container, directory: backupDirectory,-      reminderStore: backupReminderStore())+      reminderStore: backupReminderStore(),+      allowsDefaultProfileRecovery: defaultProfileRecoveryActive)   }    static var schema: Schema {@@ -43,13 +45,23 @@ enum AppEnvironment {     let configuration = ModelConfiguration(       schema: schema,       isStoredInMemoryOnly: isolated,-      cloudKitDatabase: isolated ? .none : .private("iCloud.me.nore.ig.meddy")+      cloudKitDatabase: isolated ? .none : .private("iCloud.me.nore.ig.apps.meddy")     )-    let container = try ModelContainer(for: schema, configurations: [configuration])+    var recoveryMode = !isolated && DefaultProfileRecoveryMode.requested+    #if DEBUG+      if isolated && ProcessInfo.processInfo.environment["MEDDY_TEST_DEFAULT_RECOVERY"] == "1" {+        recoveryMode = true+      }+    #endif+    if recoveryMode { try DefaultProfileRecoveryMode.persist() }+    let selected = recoveryMode && !isolated+      ? DefaultProfileRecovery.configuration(matching: configuration, schema: schema) : configuration+    let container = try ModelContainer(for: schema, configurations: [selected])+    defaultProfileRecoveryActive = recoveryMode     // A pending operation owns the store before bootstrap or any care services run.     let importer = backupImporter(container: container)     let recovery = try? importer.recoveryStatus()-    if recovery == BackupRecoveryStatus.none {+    if recovery == BackupRecoveryStatus.none && !recoveryMode {       let hadProfiles = try container.mainContext.fetchCount(FetchDescriptor<CareProfile>()) > 0       try ProfileMigration.bootstrap(container.mainContext)       if !hadProfiles,@@ -62,7 +74,7 @@ enum AppEnvironment {     #endif     if !isolated {       liveContainer = container-      if let directory = FileManager.default.containerURL(+      if !recoveryMode, let directory = FileManager.default.containerURL(         forSecurityApplicationGroupIdentifier: WidgetSnapshotStore.groupID) {         let publisher = WidgetSnapshotService(           context: container.mainContext,
Meddy/Meddy/Features/BackupRestoreView.swift Modified
diff --git a/Meddy/Meddy/Features/BackupRestoreView.swift b/Meddy/Meddy/Features/BackupRestoreView.swiftindex 9d38b4c..98c426d 100644--- a/Meddy/Meddy/Features/BackupRestoreView.swift+++ b/Meddy/Meddy/Features/BackupRestoreView.swift@@ -15,12 +15,25 @@ struct BackupRestoreView: View {   @State private var message: String?   @State private var error: String?   @State private var validationIssue: BackupValidationIssue?+  @State private var defaultProfileProof: DefaultProfileRecoveryProof?+  @State private var confirmingDefaultProfiles = false    private var importer: PhoneBackupImporter {     AppEnvironment.backupImporter(container: context.container)   }   var body: some View {     List {+      if AppEnvironment.defaultProfileRecoveryActive {+        Section {+          Text("Starter-profile import recovery. Sync is paused until you close and reopen Meddy.")+          Button("Leave import recovery") {+            do {+              try DefaultProfileRecoveryMode.end()+              message = "Close and reopen Meddy to return to normal sync."+            } catch { showError(error) }+          }.disabled(busy)+        }+      }       Section {         Text(           "This file contains unencrypted health information. It includes data stored on this iPhone."@@ -34,8 +47,10 @@ struct BackupRestoreView: View {         previewSection(preview)       } else {         Section {-          Button("Export backup", systemImage: "square.and.arrow.up") { prepareExport() }-            .accessibilityIdentifier("exportPhoneBackup")+          if !AppEnvironment.defaultProfileRecoveryActive {+            Button("Export backup", systemImage: "square.and.arrow.up") { prepareExport() }+              .accessibilityIdentifier("exportPhoneBackup")+          }           Button("Import backup", systemImage: "square.and.arrow.down") { importing = true }             .accessibilityIdentifier("importPhoneBackup")         }.disabled(busy)@@ -70,6 +85,17 @@ struct BackupRestoreView: View {       }     }     .task { prepareSyntheticPreviewIfRequested() }+    .alert("Replace the two unused starter profiles?", isPresented: $confirmingDefaultProfiles) {+      Button("Replace starter profiles and restore", role: .destructive) {+        if let preview, let proof = defaultProfileProof { apply(preview, confirmedDefaults: proof) }+        defaultProfileProof = nil+      }+      Button("Cancel", role: .cancel) { defaultProfileProof = nil }+    } message: {+      Text("Only the two unused Me profiles in this new app will be replaced by the verified backup. "+        + "Their removal will sync to this new app’s iCloud container when normal Meddy resumes. "+        + "Your old Meddy app is unchanged. Continue only if you have not added or edited anything here.")+    }   }    private func showError(_ failure: Error) {@@ -89,7 +115,15 @@ struct BackupRestoreView: View {         LabeledContent(countLabel(name), value: String(count))       }       LabeledContent("Photos", value: String(preview.payload.records.photoCount))-      Button("Import") { apply(preview) }.accessibilityIdentifier("confirmBackupImport")+      if AppEnvironment.defaultProfileRecoveryActive {+        Text("Import recovery: sync is paused for this session. Close and reopen Meddy after restoring.")+        Button("Review starter-profile recovery") { reviewDefaultProfiles(preview) }+          .accessibilityIdentifier("reviewDefaultProfileRecovery")+      } else {+        Button("Import") { apply(preview) }+          .accessibilityIdentifier("confirmBackupImport")+      }+       Button("Cancel", role: .cancel) {         do {           try importer.discard(preview)@@ -101,6 +135,17 @@ struct BackupRestoreView: View {       .accessibilityIdentifier("cancelBackupImport")     }.disabled(busy)   }+  private func reviewDefaultProfiles(_ preview: BackupImportPreview) {+    busy = true+    activity = "Checking starter profiles…"+    Task {+      defer { busy = false }+      do {+        defaultProfileProof = try await importer.defaultProfileProof(for: preview)+        confirmingDefaultProfiles = true+      } catch { showError(error) }+    }+  }   private func countLabel(_ key: String) -> String {     [       "careProfiles": "Profiles", "purposes": "Purposes", "medications": "Medications",@@ -124,7 +169,9 @@ struct BackupRestoreView: View {       }     }   }-  private func apply(_ preview: BackupImportPreview) {+  private func apply(+    _ preview: BackupImportPreview, confirmedDefaults: DefaultProfileRecoveryProof? = nil+  ) {     busy = true     activity = "Restoring backup…"     error = nil@@ -133,9 +180,10 @@ struct BackupRestoreView: View {       await Task.yield()       defer { busy = false }       do {-        try await importer.applyPrepared(preview)+        try await importer.applyPrepared(preview, confirmedDefaultProfiles: confirmedDefaults)         self.preview = nil-        message = "Backup restored"+        message = AppEnvironment.defaultProfileRecoveryActive+          ? "Backup restored. Close and reopen Meddy to resume normal sync." : "Backup restored"         NotificationCenter.default.post(name: .backupRestoreStateChanged, object: true)       } catch {         showError(error)@@ -227,9 +275,17 @@ struct BackupRestoreView: View {   }   private func prepareSyntheticPreviewIfRequested() {     #if DEBUG-      guard AppEnvironment.isTesting,-        ProcessInfo.processInfo.environment["MEDDY_TEST_BACKUP_PREVIEW"] == "1"-      else { return }+      guard AppEnvironment.isTesting else { return }+      if ProcessInfo.processInfo.environment["MEDDY_TEST_DEFAULT_RECOVERY"] == "1" {+        do {+          let profile = CareProfile(id: ProfileIdentity.me, displayName: "Synthetic restored owner")+          let payload = PhoneBackupPayload(capturedClock: ExecutionClock.sample(),+            records: BackupRecords(careProfiles: [BackupCareProfile(profile)]))+          preview = try importer.preview(data: PhoneBackupCodec.encode(payload))+        } catch { showError(error) }+        return+      }+      guard ProcessInfo.processInfo.environment["MEDDY_TEST_BACKUP_PREVIEW"] == "1" else { return }       do {         let payload = try PhoneBackupService.capture(           context: context,@@ -254,7 +310,11 @@ struct BackupStartupView: View {   var body: some View {     Group {       if status == BackupRecoveryStatus.none, error == nil {-        AppRootView(container: container).id(revision)+        if AppEnvironment.defaultProfileRecoveryActive {+          NavigationStack { BackupRestoreView() }.id(revision)+        } else {+          AppRootView(container: container).id(revision)+        }       } else if status == nil, error == nil {         ProgressView("Opening Meddy…")       } else {@@ -293,7 +353,9 @@ struct BackupStartupView: View {     .alert("Backup restored", isPresented: $restored) {       Button("Done", role: .cancel) { }     } message: {-      Text("Your data is saved. Future reminders use this iPhone's notification permissions.")+      Text(AppEnvironment.defaultProfileRecoveryActive+        ? "Backup restored. Close and reopen Meddy to resume normal sync."+        : "Your data is saved. Future reminders use this iPhone's notification permissions.")     }   }   private func check() {@@ -302,8 +364,10 @@ struct BackupStartupView: View {     do {       status = try importer.recoveryStatus()       if status == BackupRecoveryStatus.none {-        try ProfileMigration.bootstrap(container.mainContext)-        revision = UUID()+        if !AppEnvironment.defaultProfileRecoveryActive {+          try ProfileMigration.bootstrap(container.mainContext)+          revision = UUID()+        }       }       error = nil     } catch { self.error = error.localizedDescription }@@ -336,6 +400,15 @@ struct BackupStartupView: View {         && ProcessInfo.processInfo.environment["MEDDY_TEST_BACKUP_REMINDER_FAILURE"] == "1"     }     static func prepare(container: ModelContainer) throws {+      if AppEnvironment.isTesting,+        ProcessInfo.processInfo.environment["MEDDY_TEST_DEFAULT_RECOVERY"] == "1" {+        let first = CareProfile(id: ProfileIdentity.me)+        container.mainContext.insert(first)+        container.mainContext.insert(CareProfile(id: ProfileIdentity.me))+        try container.mainContext.save()+        try PhoneBackupImporter.recordBootstrapProfile(first, directory: AppEnvironment.backupDirectory)+        return+      }       guard requestedRecovery else { return }       BackupOperationGate.testingGate = BackupOperationGate(directory: AppEnvironment.backupDirectory)       let profile = CareProfile(id: ProfileIdentity.me)
Meddy/Meddy/Info.plist Modified
diff --git a/Meddy/Meddy/Info.plist b/Meddy/Meddy/Info.plistindex 7ffb12f..ed0266f 100644--- a/Meddy/Meddy/Info.plist+++ b/Meddy/Meddy/Info.plist@@ -6,7 +6,7 @@ 	<array> 		<dict> 			<key>CFBundleURLName</key>-			<string>me.nore.ig.meddy.widget</string>+			<string>me.nore.ig.apps.meddy.widget</string> 			<key>CFBundleURLSchemes</key> 			<array> 				<string>meddy</string>
Meddy/Meddy/Meddy.entitlements Modified
diff --git a/Meddy/Meddy/Meddy.entitlements b/Meddy/Meddy/Meddy.entitlementsindex 16dc6fa..19d3647 100644--- a/Meddy/Meddy/Meddy.entitlements+++ b/Meddy/Meddy/Meddy.entitlements@@ -6,7 +6,7 @@ 	<string>development</string> 	<key>com.apple.developer.icloud-container-identifiers</key> 	<array>-		<string>iCloud.me.nore.ig.meddy</string>+		<string>iCloud.me.nore.ig.apps.meddy</string> 	</array> 	<key>com.apple.developer.icloud-services</key> 	<array>@@ -14,7 +14,7 @@ 	</array> 	<key>com.apple.security.application-groups</key> 	<array>-		<string>group.me.nore.ig.meddy.widgets</string>+		<string>group.me.nore.ig.apps.meddy.widget</string> 	</array> </dict> </plist>
Meddy/Meddy/Services/Backups/BackupRecovery.swift Modified
diff --git a/Meddy/Meddy/Services/Backups/BackupRecovery.swift b/Meddy/Meddy/Services/Backups/BackupRecovery.swiftindex 751817e..c50f662 100644--- a/Meddy/Meddy/Services/Backups/BackupRecovery.swift+++ b/Meddy/Meddy/Services/Backups/BackupRecovery.swift@@ -6,6 +6,7 @@ nonisolated struct BackupRecoveryJournal: Codable, Equatable, Sendable {   let payloadHash: String   let baselineFingerprint: String   let inputName: String+  var defaultProfileProof: DefaultProfileRecoveryProof?    static func read(directory: URL) throws -> Self {     do {@@ -15,12 +16,19 @@ nonisolated struct BackupRecoveryJournal: Codable, Equatable, Sendable {       var dataBytes = 0       try BackupJSONShape.object([         "importID": .uuid, "archiveID": .uuid, "payloadHash": .text,-        "baselineFingerprint": .text, "inputName": .text+        "baselineFingerprint": .text, "inputName": .text,+        "defaultProfileProof": .optional(DefaultProfileRecoveryProof.shape)       ]).check(value, limits: .standard, dataBytes: &dataBytes)       let journal = try JSONDecoder().decode(Self.self, from: data)       guard journal.inputName.hasPrefix("input-"), journal.inputName.hasSuffix(".json"),         !journal.inputName.contains("/"), journal.payloadHash.count == 64,         journal.baselineFingerprint.count == 64 else { throw BackupImportError.invalidJournal }+      if let proof = journal.defaultProfileProof {+        try proof.validate()+        guard proof.archiveID == journal.archiveID, proof.payloadHash == journal.payloadHash else {+          throw BackupImportError.invalidJournal+        }+      }       return journal     } catch { throw BackupImportError.invalidJournal }   }
Meddy/Meddy/Services/Backups/DefaultProfileRecovery.swift Added
diff --git a/Meddy/Meddy/Services/Backups/DefaultProfileRecovery.swift b/Meddy/Meddy/Services/Backups/DefaultProfileRecovery.swiftnew file mode 100644index 0000000..b898fc0--- /dev/null+++ b/Meddy/Meddy/Services/Backups/DefaultProfileRecovery.swift@@ -0,0 +1,102 @@+import Foundation+import SwiftData++nonisolated struct DefaultProfileRecoveryProof: Codable, Equatable, Sendable {+  let rowIDs: [String]+  let profiles: [BackupCareProfile]+  let archiveID: UUID+  let payloadHash: String++  static let shape: BackupJSONShape = .object([+    "rowIDs": .array(.text), "profiles": .array(BackupCareProfile.shape),+    "archiveID": .uuid, "payloadHash": .text+  ])++  func validate() throws {+    guard rowIDs.count == 2, Set(rowIDs).count == 2,+      rowIDs.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 2048 }), profiles.count == 2,+      payloadHash.count == 64,+      profiles.allSatisfy({ profile in+        profile.id == ProfileIdentity.me && profile.lifecycleID == ProfileIdentity.selfLifecycle+          && profile.displayName == nil && profile.archivedAt == nil+          && profile.createdAt.timeIntervalSince1970.isFinite+          && profile.updatedAt.timeIntervalSince1970.isFinite+          && profile.updatedAt >= profile.createdAt+      }) else { throw BackupImportError.nonemptyDestination }+  }+}++@MainActor enum DefaultProfileRecovery {+  static func configuration(matching normal: ModelConfiguration, schema: Schema) -> ModelConfiguration {+    ModelConfiguration(normal.name, schema: schema, url: normal.url, cloudKitDatabase: .none)+  }++  static func capture(+    context: ModelContext, reminders: ReminderStateStore, directory: URL,+    archiveID: UUID, payloadHash: String+  ) throws -> DefaultProfileRecoveryProof {+    let records = try BackupRecords.capture(context)+    guard records.isEmpty, records.careProfiles.count == 2,+      try context.fetchCount(FetchDescriptor<BackupImportReceipt>()) == 0,+      try reminders.snapshotForRestore().isEmpty() else { throw BackupImportError.nonemptyDestination }+    let baseline = directory.appendingPathComponent("bootstrap-profile.json")+    if FileManager.default.fileExists(atPath: baseline.path) {+      let expected = try BackupStorage.read(baseline)+      let encoder = JSONEncoder()+      encoder.outputFormatting = [.sortedKeys]+      guard try records.careProfiles.contains(where: { try encoder.encode($0) == expected }) else {+        throw BackupImportError.nonemptyDestination+      }+    }+    let rows = try context.fetch(FetchDescriptor<CareProfile>()).map { profile in+      (try rowID(profile), BackupCareProfile(profile))+    }.sorted { $0.0 < $1.0 }+    let proof = DefaultProfileRecoveryProof(+      rowIDs: rows.map { $0.0 }, profiles: rows.map { $0.1 },+      archiveID: archiveID, payloadHash: payloadHash)+    try proof.validate()+    return proof+  }++  static func removeConfirmed(_ proof: DefaultProfileRecoveryProof, context: ModelContext) throws {+    let profiles = try context.fetch(FetchDescriptor<CareProfile>())+    guard profiles.count == 2,+      try profiles.map({ try rowID($0) }).sorted() == proof.rowIDs else {+      throw BackupImportError.changedPreview+    }+    for profile in profiles { context.delete(profile) }+  }++  private static func rowID(_ profile: CareProfile) throws -> String {+    let encoder = JSONEncoder()+    encoder.outputFormatting = [.sortedKeys]+    return try encoder.encode(profile.persistentModelID).base64EncodedString()+  }+}++@MainActor enum DefaultProfileRecoveryMode {+  private static func url(_ directory: URL) -> URL {+    directory.appendingPathComponent("default-profile-recovery-mode")+  }+  static var requested: Bool {+    requested(directory: AppEnvironment.backupDirectory, arguments: ProcessInfo.processInfo.arguments)+  }+  static func requested(directory: URL, arguments: [String]) -> Bool {+    arguments.contains("--meddy-default-profile-recovery")+      || FileManager.default.fileExists(atPath: url(directory).path)+  }+  static func persist(directory: URL = AppEnvironment.backupDirectory) throws {+    let url = url(directory)+    if FileManager.default.fileExists(atPath: url.path) {+      guard try BackupStorage.read(url, maximumBytes: 16) == Data("1".utf8) else {+        throw BackupImportError.invalidJournal+      }+    } else {+      try BackupStorage.write(Data("1".utf8), to: url)+    }+  }+  static func end(directory: URL = AppEnvironment.backupDirectory) throws {+    let url = url(directory)+    if FileManager.default.fileExists(atPath: url.path) { try BackupStorage.remove(url) }+  }+}
Meddy/Meddy/Services/Backups/PhoneBackupImporter.swift Modified
diff --git a/Meddy/Meddy/Services/Backups/PhoneBackupImporter.swift b/Meddy/Meddy/Services/Backups/PhoneBackupImporter.swiftindex 0ecd711..80a0ed6 100644--- a/Meddy/Meddy/Services/Backups/PhoneBackupImporter.swift+++ b/Meddy/Meddy/Services/Backups/PhoneBackupImporter.swift@@ -36,14 +36,17 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {   let directory: URL   private let reminderStore: ReminderStateStore   private let gate: BackupOperationGate+  let allowsDefaultProfileRecovery: Bool   var fault: ((BackupImportBoundary) throws -> Void)?   private var journalURL: URL { directory.appendingPathComponent("pending.json") }   private var baselineURL: URL { directory.appendingPathComponent("bootstrap-profile.json") }    init(container: ModelContainer, directory: URL = BackupPaths.directory,-       reminderStore: ReminderStateStore? = nil) {+       reminderStore: ReminderStateStore? = nil, allowsDefaultProfileRecovery: Bool = false) {     self.container = container     self.directory = directory+    self.allowsDefaultProfileRecovery = allowsDefaultProfileRecovery+      && container.configurations.allSatisfy { $0.cloudKitContainerIdentifier == nil }     gate = BackupOperationGate(directory: directory)     self.reminderStore = reminderStore ?? ReminderStateStore(directory: directory)   }@@ -150,7 +153,28 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {     try applyVerified(payload, preview: preview)   } -  func applyPrepared(_ preview: BackupImportPreview) async throws {+  func defaultProfileProof(for preview: BackupImportPreview) async throws -> DefaultProfileRecoveryProof {+    guard allowsDefaultProfileRecovery else { throw BackupImportError.nonemptyDestination }+    let permit = try gate.restorePermit()+    defer { permit.release() }+    guard !container.mainContext.hasChanges,+      !FileManager.default.fileExists(atPath: journalURL.path) else { throw BackupImportError.pendingEdits }+    let directory = directory+    let archiveID = try await Task.detached(priority: .userInitiated) {+      try Self.verifiedInput(preview.inputName, hash: preview.payloadHash, directory: directory).archiveID+    }.value+    try Task.checkCancellation()+    guard archiveID == preview.payload.archiveID,+      !container.mainContext.hasChanges,+      !FileManager.default.fileExists(atPath: journalURL.path) else { throw BackupImportError.changedPreview }+    return try DefaultProfileRecovery.capture(+      context: freshContext(), reminders: reminderStore, directory: directory,+      archiveID: preview.payload.archiveID, payloadHash: preview.payloadHash)+  }++  func applyPrepared(+    _ preview: BackupImportPreview, confirmedDefaultProfiles: DefaultProfileRecoveryProof? = nil+  ) async throws {     let permit = try gate.restorePermit()     defer { permit.release() }     guard !FileManager.default.fileExists(atPath: journalURL.path) else {@@ -168,15 +192,24 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {       throw BackupOperationGate.Failure.recoveryPending     }     guard !container.mainContext.hasChanges else { throw BackupImportError.pendingEdits }-    try applyVerified(payload, preview: preview)+    try applyVerified(payload, preview: preview, defaultProfileProof: confirmedDefaultProfiles)   } -  private func applyVerified(_ payload: PhoneBackupPayload, preview: BackupImportPreview) throws {+  private func applyVerified(+    _ payload: PhoneBackupPayload, preview: BackupImportPreview,+    defaultProfileProof: DefaultProfileRecoveryProof? = nil+  ) throws {     let context = freshContext()-    let baseline = try emptyBaseline(context)+    if let proof = defaultProfileProof {+      guard proof.archiveID == payload.archiveID, proof.payloadHash == preview.payloadHash else {+        throw BackupImportError.changedPreview+      }+    }+    let baseline = try restorationBaseline(context, proof: defaultProfileProof)+    if defaultProfileProof != nil { try DefaultProfileRecoveryMode.persist(directory: directory) }     let journal = BackupRecoveryJournal(       importID: UUID(), archiveID: payload.archiveID, payloadHash: preview.payloadHash,-      baselineFingerprint: baseline, inputName: preview.inputName)+      baselineFingerprint: baseline, inputName: preview.inputName, defaultProfileProof: defaultProfileProof)     try BackupStorage.write(try Self.canonical(journal), to: journalURL)     AppEnvironment.widgets(for: container.mainContext)?.invalidate()     try commit(payload, journal: journal)@@ -243,7 +276,7 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {         receipt.payloadHash == journal.payloadHash else { throw BackupImportError.inconsistentRecovery }       return .finishing     }-    guard receipts.isEmpty, try emptyBaseline(context) == journal.baselineFingerprint else {+    guard receipts.isEmpty, try restorationBaseline(context, proof: journal.defaultProfileProof) == journal.baselineFingerprint else {       throw BackupImportError.inconsistentRecovery     }     return .resumable@@ -251,20 +284,32 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {    private func commit(_ payload: PhoneBackupPayload, journal: BackupRecoveryJournal) throws {     let context = freshContext()-    guard try emptyBaseline(context) == journal.baselineFingerprint else {+    guard try restorationBaseline(context, proof: journal.defaultProfileProof) == journal.baselineFingerprint else {       throw BackupImportError.inconsistentRecovery     }-    // Raw insertion updates the sole permitted generated Me within the same save.-    try payload.records.insertValidated(into: context)-    for run in try context.fetch(FetchDescriptor<RoutineRun>()) {-      try BackupExecutionRestore.pause(run, archiveID: payload.archiveID, clock: payload.capturedClock)+    do {+      if let proof = journal.defaultProfileProof {+        try DefaultProfileRecovery.removeConfirmed(proof, context: context)+      }+      try payload.records.insertValidated(into: context)+      for run in try context.fetch(FetchDescriptor<RoutineRun>()) {+        try BackupExecutionRestore.pause(run, archiveID: payload.archiveID, clock: payload.capturedClock)+      }+      context.insert(BackupImportReceipt(+        id: journal.importID, archiveID: journal.archiveID,+        payloadHash: journal.payloadHash, committedAt: Date()))+      try fault?(.beforeSave)+      if let proof = journal.defaultProfileProof {+        guard try restorationBaseline(freshContext(), proof: proof) == journal.baselineFingerprint else {+          throw BackupImportError.changedPreview+        }+      }+      try context.save()+      try fault?(.afterSave)+    } catch {+      context.rollback()+      throw error     }-    context.insert(BackupImportReceipt(-      id: journal.importID, archiveID: journal.archiveID,-      payloadHash: journal.payloadHash, committedAt: Date()))-    try fault?(.beforeSave)-    try context.save()-    try fault?(.afterSave)   }    private func finish(_ payload: PhoneBackupPayload, journal: BackupRecoveryJournal) throws {@@ -284,6 +329,18 @@ nonisolated enum BackupImportBoundary: Equatable, Sendable {     MutationEffects.saved(container.mainContext)     try fault?(.afterJournalRemoval)     try? BackupStorage.remove(directory.appendingPathComponent(journal.inputName))+    if journal.defaultProfileProof != nil { try? DefaultProfileRecoveryMode.end(directory: directory) }+  }++  private func restorationBaseline(+    _ context: ModelContext, proof: DefaultProfileRecoveryProof?+  ) throws -> String {+    guard let proof else { return try emptyBaseline(context) }+    guard allowsDefaultProfileRecovery else { throw BackupImportError.nonemptyDestination }+    let current = try DefaultProfileRecovery.capture(+      context: context, reminders: reminderStore, directory: directory, archiveID: proof.archiveID, payloadHash: proof.payloadHash)+    guard current == proof else { throw BackupImportError.changedPreview }+    return try Self.hash(Self.canonical(current))   }    private func emptyBaseline(_ context: ModelContext) throws -> String {
Meddy/Meddy/Services/CloudSyncMonitor.swift Modified
diff --git a/Meddy/Meddy/Services/CloudSyncMonitor.swift b/Meddy/Meddy/Services/CloudSyncMonitor.swiftindex b48ffed..458e5e5 100644--- a/Meddy/Meddy/Services/CloudSyncMonitor.swift+++ b/Meddy/Meddy/Services/CloudSyncMonitor.swift@@ -53,7 +53,7 @@ final class CloudSyncMonitor {     accountTask?.cancel()     accountTask = Task {       do {-        let status = try await CKContainer(identifier: "iCloud.me.nore.ig.meddy").accountStatus()+        let status = try await CKContainer(identifier: "iCloud.me.nore.ig.apps.meddy").accountStatus()         guard !Task.isCancelled else { return }         switch status {         case .available:
Meddy/MeddyTests/MeddyBackupImportTests.swift Modified
diff --git a/Meddy/MeddyTests/MeddyBackupImportTests.swift b/Meddy/MeddyTests/MeddyBackupImportTests.swiftindex 1d73084..103354e 100644--- a/Meddy/MeddyTests/MeddyBackupImportTests.swift+++ b/Meddy/MeddyTests/MeddyBackupImportTests.swift@@ -82,6 +82,143 @@ import Testing     #expect(throws: BackupImportError.self) { try target.importer.apply(preview) }   } +  @Test func legacyAutomaticMeWithoutFingerprintIsPreserved() throws {+    let target = try destination()+    try ProfileMigration.bootstrap(target.container.mainContext)+    let before = try BackupRecords.capture(target.container.mainContext)+    #expect(before.careProfiles.count == 1)+    #expect(before.careProfiles[0].displayName == nil)+    #expect(!FileManager.default.fileExists(+      atPath: target.directory.appendingPathComponent("bootstrap-profile.json").path))+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    #expect(throws: BackupImportError.self) { try target.importer.apply(preview) }+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+    #expect(try target.importer.recoveryStatus() == .none)+  }++  @Test func newlyBootstrappedAndFingerprintedMeAcceptsVerifiedImport() throws {+    let target = try destination()+    try ProfileMigration.bootstrap(target.container.mainContext)+    let me = try #require(target.container.mainContext.fetch(FetchDescriptor<CareProfile>()).first)+    try PhoneBackupImporter.recordBootstrapProfile(me, directory: target.directory)+    let original = try payload()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(original))+    try target.importer.apply(preview)+    #expect(try BackupRecords.capture(ModelContext(target.container)) == original.records)+  }++  // Synthetic design probe: the local permit does not cover a CloudKit-style writer.+  @Test func independentWriterCanArriveAfterFinalBaselineCheck() throws {+    let target = try destination(placeholder: true)+    let original = try payload()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(original))+    let lateID = UUID()+    target.importer.fault = { boundary in+      guard boundary == .beforeSave else { return }+      let other = ModelContext(target.container)+      other.autosaveEnabled = false+      let medication = Medication(name: "Synthetic independent arrival")+      medication.id = lateID+      other.insert(medication)+      try other.save()+    }+    try target.importer.apply(preview)+    let records = try BackupRecords.capture(ModelContext(target.container))+    #expect(records.medications.count == original.records.medications.count + 1)+    #expect(records.medications.contains { $0.id == lateID })+    #expect(try target.importer.recoveryStatus() == .none)+  }++  @Test func independentSecondMeReproducesDuplicateRefusalWithoutMutation() throws {+    let target = try destination(placeholder: true)+    let other = ModelContext(target.container)+    other.insert(CareProfile(id: ProfileIdentity.me))+    try other.save()+    let before = try BackupRecords.capture(ModelContext(target.container))+    #expect(before.careProfiles.count == 2)+    #expect(before.careProfiles.allSatisfy {+      $0.id == ProfileIdentity.me && $0.displayName == nil && $0.lifecycleID == ProfileIdentity.selfLifecycle+    })+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    #expect(throws: BackupImportError.self) { try target.importer.apply(preview) }+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+    #expect(try target.importer.recoveryStatus() == .none)+  }++  // Proposal mechanics only: this manually owned synthetic context is not an import bypass.+  @Test func syntheticDuplicateReplacementCanRollbackOrCommitInOneSave() throws {+    let target = try destination(placeholder: true)+    let other = ModelContext(target.container)+    other.insert(CareProfile(id: ProfileIdentity.me))+    try other.save()+    let before = try BackupRecords.capture(ModelContext(target.container))+    let original = try payload()+    let work = ModelContext(target.container)+    work.autosaveEnabled = false+    for profile in try work.fetch(FetchDescriptor<CareProfile>()) { work.delete(profile) }+    try original.records.insert(into: work)+    work.rollback()+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+    for profile in try work.fetch(FetchDescriptor<CareProfile>()) { work.delete(profile) }+    try original.records.insert(into: work)+    work.insert(BackupImportReceipt(id: UUID(), archiveID: original.archiveID, payloadHash: "synthetic"))+    try work.save()+    #expect(try BackupRecords.capture(ModelContext(target.container)) == original.records)+    #expect(try ModelContext(target.container).fetchCount(FetchDescriptor<BackupImportReceipt>()) == 1)+  }++  @Test func scopedSyntheticReplacementPreservesIndependentCareArrival() throws {+    let target = try destination(placeholder: true)+    let other = ModelContext(target.container)+    other.insert(CareProfile(id: ProfileIdentity.me))+    try other.save()+    let work = ModelContext(target.container)+    work.autosaveEnabled = false+    for profile in try work.fetch(FetchDescriptor<CareProfile>()) { work.delete(profile) }+    let original = try payload()+    try original.records.insert(into: work)+    let late = Medication(name: "Synthetic concurrent care preserved")+    other.insert(late)+    try other.save()+    try work.save()+    let actual = try BackupRecords.capture(ModelContext(target.container))+    #expect(actual.medications.contains { $0.id == late.id })+    #expect(actual.medications.count == original.records.medications.count + 1)+    #expect(actual != original.records)+  }++  @Test func scopedSyntheticReplacementProbesConcurrentProfileEdit() throws {+    let target = try destination(placeholder: true)+    let other = ModelContext(target.container)+    other.insert(CareProfile(id: ProfileIdentity.me))+    try other.save()+    let work = ModelContext(target.container)+    work.autosaveEnabled = false+    let selected = try work.fetch(FetchDescriptor<CareProfile>())+    let selectedID = try #require(selected.first).persistentModelID+    for profile in selected { work.delete(profile) }+    let original = try payload()+    try original.records.insert(into: work)+    let changed = try #require(other.fetch(FetchDescriptor<CareProfile>()).first {+      $0.persistentModelID == selectedID+    })+    changed.displayName = "Synthetic concurrent profile edit"+    changed.updatedAt = Date()+    try other.save()+    do {+      try work.save()+      let actual = try BackupRecords.capture(ModelContext(target.container))+      let retained = actual.careProfiles.contains { $0.displayName == "Synthetic concurrent profile edit" }+      print("PROFILE_RACE_PROBE saved=true concurrentEditRetained=\(retained)")+      #expect(actual == original.records || retained)+    } catch {+      work.rollback()+      let actual = try BackupRecords.capture(ModelContext(target.container))+      print("PROFILE_RACE_PROBE saved=false concurrentEditRetained=true")+      #expect(actual.careProfiles.contains { $0.displayName == "Synthetic concurrent profile edit" })+    }+  }+   @Test func changedDestinationAfterPreviewIsUntouched() throws {     let target = try destination()     let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))
Meddy/MeddyTests/MeddyDefaultProfileRecoveryTests.swift Added
diff --git a/Meddy/MeddyTests/MeddyDefaultProfileRecoveryTests.swift b/Meddy/MeddyTests/MeddyDefaultProfileRecoveryTests.swiftnew file mode 100644index 0000000..2c2ea53--- /dev/null+++ b/Meddy/MeddyTests/MeddyDefaultProfileRecoveryTests.swift@@ -0,0 +1,249 @@+import Foundation+import SwiftData+import Testing++@testable import Meddy++@MainActor struct MeddyDefaultProfileRecoveryTests {+  private struct Fixture {+    let directory: URL+    let container: ModelContainer+    let reminders: ReminderStateStore+    let importer: PhoneBackupImporter+  }+  private func fixture(allowed: Bool = true) throws -> Fixture {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    try BackupStorage.ensureDirectory(directory)+    let container = try ModelContainer(for: AppEnvironment.schema, configurations: [+      ModelConfiguration(schema: AppEnvironment.schema, url: directory.appendingPathComponent("care.store"),+        cloudKitDatabase: .none)+    ])+    let context = container.mainContext+    context.autosaveEnabled = false+    let first = CareProfile(id: ProfileIdentity.me)+    context.insert(first)+    context.insert(CareProfile(id: ProfileIdentity.me))+    try context.save()+    try PhoneBackupImporter.recordBootstrapProfile(first, directory: directory)+    let reminders = ReminderStateStore(directory: directory, legacyDefaults: nil)+    return Fixture(directory: directory, container: container, reminders: reminders,+      importer: PhoneBackupImporter(container: container, directory: directory, reminderStore: reminders,+        allowsDefaultProfileRecovery: allowed))+  }+  private func payload() throws -> PhoneBackupPayload {+    let container = try ModelContainer(for: AppEnvironment.schema, configurations: [+      ModelConfiguration(schema: AppEnvironment.schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+    ])+    let context = container.mainContext+    context.insert(CareProfile(id: ProfileIdentity.me, displayName: "Synthetic restored owner"))+    context.insert(Medication(name: "Synthetic restored medication"))+    try context.save()+    return PhoneBackupPayload(capturedClock: ClockSample(+      wall: Date(timeIntervalSince1970: 1_700_000_000), monotonic: 100, continuityID: "synthetic"),+      records: try BackupRecords.capture(context))+  }+  private func reopened(_ fixture: Fixture) throws -> PhoneBackupImporter {+    let container = try ModelContainer(for: AppEnvironment.schema, configurations: [+      ModelConfiguration(schema: AppEnvironment.schema, url: fixture.directory.appendingPathComponent("care.store"),+        cloudKitDatabase: .none)+    ])+    return PhoneBackupImporter(container: container, directory: fixture.directory,+      reminderStore: ReminderStateStore(directory: fixture.directory, legacyDefaults: nil),+      allowsDefaultProfileRecovery: true)+  }++  @Test func recoveryConfigurationPreservesExactStoreURLWithoutCloudMirroring() {+    let normal = ModelConfiguration(schema: AppEnvironment.schema,+      url: URL(fileURLWithPath: "/tmp/synthetic-existing-meddy.store"),+      cloudKitDatabase: .private("iCloud.invalid.synthetic"))+    let recovery = DefaultProfileRecovery.configuration(matching: normal, schema: AppEnvironment.schema)+    #expect(recovery.url == normal.url)+    #expect(recovery.name == normal.name)+    #expect(recovery.cloudKitContainerIdentifier == nil)+    #expect(normal.cloudKitContainerIdentifier == "iCloud.invalid.synthetic")+  }++  @Test func modeSurvivesRelaunchAndCorruptionFailsClosed() throws {+    let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+    #expect(!DefaultProfileRecoveryMode.requested(directory: directory, arguments: []))+    #expect(DefaultProfileRecoveryMode.requested(directory: directory,+      arguments: ["--meddy-default-profile-recovery"]))+    try DefaultProfileRecoveryMode.persist(directory: directory)+    #expect(DefaultProfileRecoveryMode.requested(directory: directory, arguments: []))+    let marker = directory.appendingPathComponent("default-profile-recovery-mode")+    try BackupStorage.write(Data("invalid".utf8), to: marker)+    #expect(throws: BackupImportError.self) { try DefaultProfileRecoveryMode.persist(directory: directory) }+    #expect(DefaultProfileRecoveryMode.requested(directory: directory, arguments: []))+    try DefaultProfileRecoveryMode.end(directory: directory)+    #expect(!DefaultProfileRecoveryMode.requested(directory: directory, arguments: []))+  }++  @Test func normalImporterCannotOfferExceptionalRecovery() async throws {+    let target = try fixture(allowed: false)+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    await #expect(throws: BackupImportError.self) { try await target.importer.defaultProfileProof(for: preview) }+  }++  @Test func confirmedRecoveryCommitsExactArchiveAndOneReceipt() async throws {+    let target = try fixture()+    let original = try payload()+    let preview = try await target.importer.preparePreview(data: PhoneBackupCodec.encode(original))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    #expect(proof.rowIDs.count == 2)+    try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    #expect(try BackupRecords.capture(ModelContext(target.container)) == original.records)+    #expect(try ModelContext(target.container).fetchCount(FetchDescriptor<BackupImportReceipt>()) == 1)+    #expect(try target.importer.recoveryStatus() == .none)+    #expect(!DefaultProfileRecoveryMode.requested(directory: target.directory, arguments: []))+    await #expect(throws: BackupImportError.self) { try await target.importer.defaultProfileProof(for: preview) }+  }++  enum Rejection: CaseIterable { case name, archive, lifecycle, thirdProfile, care, receipt, reminder, edits }+  @Test(arguments: Rejection.allCases)+  func nonemptyOrAmbiguousDestinationsAreNeverOffered(_ reason: Rejection) async throws {+    let target = try fixture()+    let context = target.container.mainContext+    let me = try #require(context.fetch(FetchDescriptor<CareProfile>()).first)+    switch reason {+    case .name: me.displayName = "Synthetic edited owner"+    case .archive: me.archivedAt = Date()+    case .lifecycle: me.lifecycleID = UUID()+    case .thirdProfile: context.insert(CareProfile(id: ProfileIdentity.me))+    case .care: context.insert(Medication(name: "Synthetic retained care"))+    case .receipt: context.insert(BackupImportReceipt(id: UUID(), archiveID: UUID(), payloadHash: "synthetic"))+    case .reminder:+      let receipts = FollowupReceipts.State(scheduled: ["synthetic": Date()], elapsed: [])+      try target.reminders.install(BackupReminderState(followupReceipts: JSONEncoder().encode(receipts)))+    case .edits: break+    }+    if reason != .edits { try context.save() }+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    if reason == .edits { me.displayName = "Synthetic pending edit" }+    await #expect(throws: (any Error).self) { try await target.importer.defaultProfileProof(for: preview) }+    #expect(!FileManager.default.fileExists(atPath: target.directory.appendingPathComponent("pending.json").path))+  }++  @Test func changedConfirmationAndDifferentArchiveAreRefusedWithoutMutation() async throws {+    let target = try fixture()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    let different = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    await #expect(throws: BackupImportError.self) {+      try await target.importer.applyPrepared(different, confirmedDefaultProfiles: proof)+    }+    let me = try #require(target.container.mainContext.fetch(FetchDescriptor<CareProfile>()).first)+    me.updatedAt = me.updatedAt.addingTimeInterval(10)+    try target.container.mainContext.save()+    let before = try BackupRecords.capture(ModelContext(target.container))+    await #expect(throws: BackupImportError.self) {+      try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    }+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+    #expect(try target.importer.recoveryStatus() == .none)+  }++  enum Arrival: CaseIterable { case care, profileEdit, duplicate }+  @Test(arguments: Arrival.allCases)+  func independentArrivalBeforeSaveRollsBackOnlyOurStagedWork(_ arrival: Arrival) async throws {+    let target = try fixture()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    let lateID = UUID()+    target.importer.fault = { boundary in+      guard boundary == .beforeSave else { return }+      let other = ModelContext(target.container)+      switch arrival {+      case .care:+        let medication = Medication(name: "Synthetic independent preserved row")+        medication.id = lateID+        other.insert(medication)+      case .profileEdit:+        let profile = try #require(other.fetch(FetchDescriptor<CareProfile>()).first)+        profile.displayName = "Synthetic independent profile edit"+        profile.updatedAt = Date()+      case .duplicate: other.insert(CareProfile(id: ProfileIdentity.me))+      }+      try other.save()+    }+    await #expect(throws: (any Error).self) {+      try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    }+    let actual = try BackupRecords.capture(ModelContext(target.container))+    #expect(actual.careProfiles.count == (arrival == .duplicate ? 3 : 2))+    if arrival == .care { #expect(actual.medications.map(\.id) == [lateID]) }+    if arrival == .profileEdit {+      #expect(actual.careProfiles.contains { $0.displayName == "Synthetic independent profile edit" })+    }+    #expect(try ModelContext(target.container).fetchCount(FetchDescriptor<BackupImportReceipt>()) == 0)+  }++  @Test func mismatchingFingerprintAndDamagedBackupDoNotOfferRecovery() async throws {+    let target = try fixture()+    let before = try BackupRecords.capture(ModelContext(target.container))+    await #expect(throws: (any Error).self) {+      _ = try await target.importer.preparePreview(data: Data("invalid synthetic backup".utf8))+    }+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    let encoder = JSONEncoder()+    encoder.outputFormatting = [.sortedKeys]+    let unrelated = BackupCareProfile(CareProfile(id: ProfileIdentity.me))+    try BackupStorage.write(encoder.encode(unrelated),+      to: target.directory.appendingPathComponent("bootstrap-profile.json"))+    await #expect(throws: BackupImportError.self) { try await target.importer.defaultProfileProof(for: preview) }+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+  }++  enum Stop: Error { case injected }+  @Test func confirmedUncommittedRecoveryCanCancelWithoutChangingProfiles() async throws {+    let target = try fixture()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(payload()))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    let before = try BackupRecords.capture(ModelContext(target.container))+    target.importer.fault = { if $0 == .beforeSave { throw Stop.injected } }+    await #expect(throws: Stop.self) {+      try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    }+    let recovered = try reopened(target)+    #expect(try recovered.canCancelRecovery())+    try recovered.cancel()+    #expect(try recovered.recoveryStatus() == .none)+    #expect(try BackupRecords.capture(ModelContext(recovered.container)) == before)+    #expect(try ModelContext(recovered.container).fetchCount(FetchDescriptor<BackupImportReceipt>()) == 0)+  }++  @Test func confirmedCommittedInterruptionFinishesWithoutDuplicateRows() async throws {+    let target = try fixture()+    let original = try payload()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(original))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    target.importer.fault = { if $0 == .afterSave { throw Stop.injected } }+    await #expect(throws: Stop.self) {+      try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    }+    let recovered = try reopened(target)+    #expect(try recovered.recoveryStatus() == .finishing)+    #expect(try !recovered.canCancelRecovery())+    try recovered.resume()+    #expect(try recovered.recoveryStatus() == .none)+    #expect(try BackupRecords.capture(ModelContext(recovered.container)) == original.records)+    #expect(try ModelContext(recovered.container).fetchCount(FetchDescriptor<BackupImportReceipt>()) == 1)+  }++  @Test func preSaveFailureResumesFromDurableExactProofAfterReopen() async throws {+    let target = try fixture()+    let original = try payload()+    let preview = try target.importer.preview(data: PhoneBackupCodec.encode(original))+    let proof = try await target.importer.defaultProfileProof(for: preview)+    let before = try BackupRecords.capture(ModelContext(target.container))+    target.importer.fault = { if $0 == .beforeSave { throw Stop.injected } }+    await #expect(throws: Stop.self) {+      try await target.importer.applyPrepared(preview, confirmedDefaultProfiles: proof)+    }+    #expect(try BackupRecords.capture(ModelContext(target.container)) == before)+    let resumed = try reopened(target)+    #expect(try resumed.recoveryStatus() == .resumable)+    try resumed.resume()+    #expect(try BackupRecords.capture(ModelContext(resumed.container)) == original.records)+    #expect(try resumed.recoveryStatus() == .none)+  }+}
Meddy/MeddyUITests/MeddyBackupUITests.swift Modified
diff --git a/Meddy/MeddyUITests/MeddyBackupUITests.swift b/Meddy/MeddyUITests/MeddyBackupUITests.swiftindex 0d926df..f860042 100644--- a/Meddy/MeddyUITests/MeddyBackupUITests.swift+++ b/Meddy/MeddyUITests/MeddyBackupUITests.swift@@ -104,6 +104,30 @@ final class MeddyBackupUITests: XCTestCase {     XCTAssertTrue(app.buttons["exportPhoneBackup"].exists)   } +  func testDefaultProfileRecoveryRequiresExplicitConfirmationAndCanCancel() {+    let app = XCUIApplication()+    app.launchEnvironment["MEDDY_TESTING"] = "1"+    app.launchEnvironment["MEDDY_TEST_DEFAULT_RECOVERY"] = "1"+    app.launch()+    let review = app.buttons["reviewDefaultProfileRecovery"]+    XCTAssertTrue(app.navigationBars["Backup & restore"].waitForExistence(timeout: 10))+    reveal(review, in: app)+    review.tap()+    let alert = app.alerts["Replace the two unused starter profiles?"]+    XCTAssertTrue(alert.waitForExistence(timeout: 5))+    XCTAssertTrue(alert.staticTexts.containing(NSPredicate(format: "label CONTAINS %@", "iCloud")).firstMatch.exists)+    alert.buttons["Cancel"].tap()+    XCTAssertFalse(app.staticTexts["Backup restored"].exists)+    review.tap()+    XCTAssertTrue(alert.waitForExistence(timeout: 5))+    alert.buttons["Replace starter profiles and restore"].tap()+    let completed = app.alerts["Backup restored"]+    XCTAssertTrue(completed.waitForExistence(timeout: 10))+    XCTAssertTrue(completed.staticTexts["Backup restored. Close and reopen Meddy to resume normal sync."].exists)+    completed.buttons["Done"].tap()+    XCTAssertFalse(app.buttons["reviewDefaultProfileRecovery"].exists)+  }+   private func reveal(_ element: XCUIElement, in app: XCUIApplication, swipeDown: Bool = false) {     for _ in 0..<8 {       if element.exists && element.isHittable { return }
Meddy/MeddyWidgets/MeddyWidgets.entitlements Modified
diff --git a/Meddy/MeddyWidgets/MeddyWidgets.entitlements b/Meddy/MeddyWidgets/MeddyWidgets.entitlementsindex e084b07..2e54f70 100644--- a/Meddy/MeddyWidgets/MeddyWidgets.entitlements+++ b/Meddy/MeddyWidgets/MeddyWidgets.entitlements@@ -6,7 +6,7 @@ 	<string>NSFileProtectionComplete</string> 	<key>com.apple.security.application-groups</key> 	<array>-		<string>group.me.nore.ig.meddy.widgets</string>+		<string>group.me.nore.ig.apps.meddy.widget</string> 	</array> </dict> </plist>
Meddy/Shared/Widgets/WidgetSnapshotStore.swift Modified
diff --git a/Meddy/Shared/Widgets/WidgetSnapshotStore.swift b/Meddy/Shared/Widgets/WidgetSnapshotStore.swiftindex a057e37..c1b4776 100644--- a/Meddy/Shared/Widgets/WidgetSnapshotStore.swift+++ b/Meddy/Shared/Widgets/WidgetSnapshotStore.swift@@ -3,7 +3,7 @@ import Foundation  // The phone is the sole writer. Hooks are injected only by synthetic tests. nonisolated final class WidgetSnapshotStore {-  static let groupID = "group.me.nore.ig.meddy.widgets"+  static let groupID = "group.me.nore.ig.apps.meddy.widget"   private let directory: URL   var beforeReplace: ((String) throws -> Void)?   var beforeRemove: ((String) throws -> Void)?
scripts/install-phone.py Modified
diff --git a/scripts/install-phone.py b/scripts/install-phone.pyindex df401e0..5250e3a 100644--- a/scripts/install-phone.py+++ b/scripts/install-phone.py@@ -106,8 +106,8 @@ def main():     build(command, run_dir / 'xcodebuild.log')     with (app / 'Info.plist').open('rb') as handle:         identity = plistlib.load(handle)['CFBundleIdentifier']-    if identity != 'me.nore.ig.meddy' or (app / 'Watch').exists():-        raise ValueError('Expected existing Meddy phone identity with no embedded Watch content.')+    if identity != 'me.nore.ig.apps.meddy' or (app / 'Watch').exists():+        raise ValueError('Expected configured Meddy phone identity with no embedded Watch content.')     subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True)     if args.build_only:         print('Signed phone build verified; installation skipped.')

Docs (10)

AGENTS.md Modified
diff --git a/AGENTS.md b/AGENTS.mdindex ae9d44b..aba8cda 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -25,7 +25,7 @@ Use the root Makefile for development tooling; `make` shows help. GNU Make 4.4.1 - `make check`: whitespace validation; `make simulators`: read-only discovery. - `make pre-push` (or `make test`): whitespace/lint checks, then full phone domain, Watch domain and full phone UI gates, serially. This is the phase-boundary gate, not the inner loop. -Coordinate the shared heavy-work slot with the parent before builds/tests. Use targeted checks after fixes; do not repeatedly run a full UI suite or duplicate another agent's test monitoring. Keep full logs on disk, report exit status/counts and relevant failure excerpts, and drain only owned processes when a run stalls. Failed/interrupted runs are not passing evidence. Makefile caches are isolated under ignored `DerivedData/`; each invocation retains logs/results under ignored `build/results/`. Never remove another project's cache or stop its processes.+Independent builds may run in parallel. Coordinate only conflicting simulator runs and Mac UI tests that take over the screen. Use targeted checks after fixes; do not repeatedly run a full UI suite or duplicate another agent's test monitoring. Keep full logs on disk, report exit status/counts and relevant failure excerpts, and drain only owned processes when a run stalls. Failed/interrupted runs are not passing evidence. Makefile caches are isolated under ignored `DerivedData/`; each invocation retains logs/results under ignored `build/results/`. Never remove another project's cache or stop its processes.  ## Swift style @@ -39,7 +39,7 @@ Tests/previews must use isolated synthetic stores and fake clients. The shared t  Preserve captured profile ownership, historical dose snapshots, correction/Undo tombstones, timer/checkpoint state and offline action identity. Do not infer drug limits, doses, medical safety, wake detection or clinical content. As-needed limits use recorded quantities and entered limits; new daily caps use the preceding 24 elapsed hours and older non-24-hour rules require explicit conversion. Medication timing and care actions follow the authoritative design. -The active bundle identifier is `me.nore.ig.meddy`; the Watch companion is `me.nore.ig.meddy.watchkitapp` and private container is `iCloud.me.nore.ig.meddy`. Do not change signing, entitlements, team/account/container configuration as incidental tooling work. Actual live resets/deletes require concrete approval. Physical Watch installs/testing remain deferred; use Watch simulators only. Phone installation requires an explicit request and an in-place update, never an unsolicited uninstall/reset.+The active bundle identifier is `me.nore.ig.apps.meddy`; the Watch companion is `me.nore.ig.apps.meddy.watchkitapp` and private container is `iCloud.me.nore.ig.apps.meddy`. Widgets use `me.nore.ig.apps.meddy.widget` and shared App Group `group.me.nore.ig.apps.meddy.widget`. Do not change signing, entitlements, team/account/container configuration as incidental tooling work. Actual live resets/deletes require concrete approval. Physical Watch installs/testing remain deferred; use Watch simulators only. Phone installation requires an explicit request and an in-place update, never an unsolicited uninstall/reset.  ## Git and review 
CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e4c10a2..b27bc01 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,8 @@ - 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+- 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. - Keep medication photo Add/Change and Archive/Reactivate controls in Edit; remove their redundant detail shortcuts while retaining photo viewing, repeats-counter changes and care actions. - Show “Repeats left: x” in Share for appointment and its Markdown output only when the remaining count is positive; omit zero and unset counts without changing repeat accounting. - Present medication recognition images consistently as circles, using a display-only aspect-fill crop without changing stored photos or photo controls.@@ -13,6 +15,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+- 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. - T2471: Preserve immutable restored execution provenance when a completed child timer is explicitly moved, while retaining strict current-link, owner and target validation. - T2471: Allow safe cancellation of an uncommitted restore with missing or damaged retained input; clean orphaned private stages at cold launch while preserving recovery evidence and durable reminder state. - T2471: Preserve legitimate nested timer revision pairs and moved-timer audit history in backups without rewriting saved values; identify each frozen identity rule with private diagnostics.
docs/account-migration.md Modified
diff --git a/docs/account-migration.md b/docs/account-migration.mdnew file mode 100644index 0000000..9b34b4a--- /dev/null+++ b/docs/account-migration.md@@ -0,0 +1,323 @@+# Meddy developer-account migration++Current candidate: rebased onto `origin/main` `9197303fe3ddd49a9d398a7498fb1e71bebefcd9`.+The final widget bundle and App Group use singular `widget`. The user reports+successful restore and removal of the old app. The temporary “Meddy New” display+label has been reverted to Meddy in source for publication and an in-place phone+update. Earlier receipts below retain their original baselines and intermediate+failures; they are historical rather than current account or sync acceptance.++Local configuration prepared on 26 October 2026 on `migration/developer-account`.++| Purpose | Previous | Current |+| --- | --- | --- |+| iPhone / Watch companion reference | `me.nore.ig.meddy` | `me.nore.ig.apps.meddy` |+| iPhone unit tests | `me.nore.ig.meddy.tests` | `me.nore.ig.apps.meddy.tests` |+| iPhone UI tests | `me.nore.ig.meddy.uitests` | `me.nore.ig.apps.meddy.uitests` |+| Watch app | `me.nore.ig.meddy.watchkitapp` | `me.nore.ig.apps.meddy.watchkitapp` |+| Watch unit tests | `me.nore.ig.meddy.watchkitapp.tests` | `me.nore.ig.apps.meddy.watchkitapp.tests` |+| Watch UI tests | `me.nore.ig.meddy.watchkitapp.uitests` | `me.nore.ig.apps.meddy.watchkitapp.uitests` |+| Widget extension | `me.nore.ig.meddy.widgets` | `me.nore.ig.apps.meddy.widget` |+| Widget App Group | `group.me.nore.ig.meddy.widgets` | `group.me.nore.ig.apps.meddy.widget` |+| Widget URL registration name | `me.nore.ig.meddy.widget` | `me.nore.ig.apps.meddy.widget` |+| Private CloudKit container | `iCloud.me.nore.ig.meddy` | `iCloud.me.nore.ig.apps.meddy` |++Both Debug and Release use the new identifiers. The SwiftData configuration,+CloudKit account-status probe, phone entitlement, and phone-install identity guard+agree. After rebasing onto `origin/main` at `9197303`, widgets use bundle+`me.nore.ig.apps.meddy.widget`, App Group `group.me.nore.ig.apps.meddy.widget`,+and URL registration name `me.nore.ig.apps.meddy.widget`. The existing `meddy`+URL scheme and widget link payload format remain unchanged for compatibility.+Both installed identities may register that scheme; routing with both installed+is not established by build verification. Notification IDs and persisted model fields retain their existing values.++## Prerequisites before signed use++The user's Debug/Release team changes to `4PJS97G236` are preserved for the+phone app, phone unit/UI tests, Watch app and Watch unit tests. Watch UI tests+still explicitly select `V24684SCZN` in both configurations; the user must+select/confirm the intended destination team for that remaining target in Xcode.+This change does not modify team/account access or signing settings.++Under the intended team, the user must confirm/register the new app identifiers,+CloudKit container association, required iCloud/CloudKit and push capabilities,+and matching provisioning profiles. Existing local profiles subsequently supported+a signed Debug phone/embedded Watch build and the phone installation recorded below.+No portal provisioning, credentials, cloud schema deployment or live container+inspection was performed.++Changing bundle identity creates a separate application sandbox/defaults identity;+changing the CloudKit selector does not copy the old private database. Preserve+the old app/container and arrange a separately authorized data migration before+relying on the new identity. No live records were read, exported, modified or reset.+The install helper now checks the new identity; it does not migrate data or replace+the old-identifier app in place. The user subsequently explicitly requested phone deployment; see the receipt below.++## Validation++Static checks cover project/plist syntax, identifier consistency across all six+Debug/Release target pairs, companion linkage, entitlement/runtime agreement,+unchanged team settings, Python script syntax and synthetic install-helper tests.+Debug unsigned simulator builds now pass for both `Meddy` (including embedded+Watch) and `MeddyWatch`, with `CODE_SIGNING_ALLOWED=NO`, one build job, isolated+DerivedData, and no simulator launch. Generated phone/embedded Watch Info.plists+confirm the new bundle IDs and companion linkage.++Receipts:+- `/tmp/meddy-account-migration-results/build.iwkwno/xcodebuild.log`+- `/tmp/meddy-account-migration-results/build-watch.79QUen/xcodebuild.log`+- Each directory also contains `Results.xcresult`.++The phone build reports an existing actor-isolation warning in+`MedicationPhoto.swift:123`; Watch reports skipped App Intents metadata extraction+because it has no AppIntents dependency. Neither failed compilation. Tests,+Release compilation and CloudKit runtime access remain unverified. Existing-profile+signing and phone deployment subsequently passed as recorded below.++A separate signed build can use existing local profiles without portal updates:++```sh+xcodebuild -jobs 1 build -project Meddy/Meddy.xcodeproj -scheme Meddy \+  -configuration Debug -destination 'generic/platform=iOS' \+  -derivedDataPath /tmp/meddy-account-migration-signing \+  CODE_SIGNING_ALLOWED=YES+```++Do not add provisioning-update or device-registration flags. This command subsequently passed using existing profiles; it may fail elsewhere+if destination profiles/certificates are unavailable.+It does not install, launch, migrate data or establish CloudKit runtime access.+Historical design/preflight/provisioning records retain their original identifiers;+the current identity notices and this document supersede their setup instructions.+++## Signed build and phone deployment receipt++On 26 October 2026 the user explicitly requested deployment to their phone.+The signed Debug `Meddy` scheme build passed using existing profiles without+provisioning-update/device-registration flags. Both phone and embedded Watch+signatures verified with `codesign --verify --deep --strict`; application IDs+and team entitlements use `4PJS97G236`. The phone's signed CloudKit entitlement+is `iCloud.me.nore.ig.apps.meddy`, and its APS environment is development.+Build log: `/tmp/meddy-account-migration-results/signing.kbazPd/xcodebuild.log`.++The repository phone-install helper built a phone-only staged copy successfully.+Its guard initially stopped before installation because reused temporary build+products retained an empty `Watch` directory. Only that empty temporary directory+was removed, the signature was reverified, and the helper's supported `devicectl`+installation operation was completed. No source or user cache was removed.+Staged build log: `/tmp/meddy-account-migration-results/install-phone.0xym5etj/xcodebuild.log`.++Device: The Dark Side. Installed bundle: `me.nore.ig.apps.meddy`, version 1.0,+build 1. Device tooling confirmed installation and successful normal launch.+The old `me.nore.ig.meddy` app remains installed as version 1.0, build 1.+No uninstall/reset, physical Watch installation or data migration was performed.+Launch acceptance and signed entitlements do not establish CloudKit runtime sync.+Local receipts: `/tmp/meddy-install-result.json`, `/tmp/meddy-new-app-installed.json`,+`/tmp/meddy-old-app-after-install.json`, `/tmp/meddy-launch-result.json`.+++## Rebase onto current remote baseline++The user's missing import/export report identified the stale initial baseline:+`82ff4d97e20f4e76d59f628a00c5b4d45b86f5ba`. A fresh fetch confirmed current+`origin/main` as `9197303fe3ddd49a9d398a7498fb1e71bebefcd9` (prescription URLs).+Migration checkpoint `f15291b` was preserved as branch+`backup/meddy-migration-before-rebase-20261026`, then rebased cleanly as `dffda99`.+Exact pre-rebase diffs, refs and untracked archive are retained locally at+`/tmp/meddy-pre-rebase-20261026`.++The baseline includes portable backup/empty-destination restore (`4518e43`),+next-medication widgets (`cfcebc9`), medication type labels and prescription URLs.+Backup & restore is reachable from Profiles; export/import services and synthetic+regression suites are present. No live backup/export/import is performed here.+The imported widget target now uses selected team `4PJS97G236` in Debug/Release,+with matching new-family App Group entitlements and runtime snapshot selector.+Previously selected target teams are preserved, including Watch UI tests still+using `V24684SCZN`. New App Group/profile acceptance requires separate validation;+no portal registrations or grants are authorised by the rebase.++Earlier build/install receipts above refer to the stale baseline, not this+rebased candidate. No new installation is performed for this rebase request.+++### Historical signing blocker before singular-group correction++Signed Debug compilation was attempted with existing profiles and no provisioning+updates. It exited 65 before compilation. The phone profile+`iOS Team Provisioning Profile: me.nore.ig.apps.meddy` lacks the App Groups+capability, `group.me.nore.ig.apps.meddy.widgets`, and+`com.apple.security.application-groups`. The widget selected fallback profile+`iOS Team Provisioning Profile: *` lacks App Groups and Data Protection,+including `com.apple.developer.default-data-protection` and group entitlements.+The widget target is configured to `4PJS97G236`; no team fallback is requested.+Log: `/tmp/meddy-rebase-results/signed-correct-widget-team.log`;+result: `/tmp/meddy-rebase-results/signed-correct-widget-team.xcresult`.++The user must register/associate the new App Group with the phone and widget+App IDs under the destination team and obtain profiles admitting the existing+widget Complete Data Protection entitlement. Those are account/capability actions,+not completed or attempted here. Rebased-device readiness remains blocked until+existing-profile signing passes. No fresh installation was attempted.+++### Historical verification before singular-group correction++Unsigned Debug compilation of phone, embedded Watch and widget extension passed+as part of the full phone domain test action. All 334 logical tests passed, with+353 device executions including dynamic parameters, zero failures and zero skips.+This includes backup/archive/import/restore, widget and prescription/classification+regressions. Tests used only isolated synthetic stores on the dedicated+`Meddy-Migration-Rebase-20261026` simulator; no real phone data or cloud access.+UI journeys were compiled but not executed. Receipts:+`/tmp/meddy-rebase-results/domain.log`, `domain.xcresult`, `domain-summary.json`.+Strict lint passed all 191 Swift files with zero violations; four synthetic+install-helper tests, project/plist syntax and whitespace checks passed.+The pre-existing MedicationPhoto actor-isolation warning and skipped App Intents+metadata extraction remain non-fatal compiler warnings.++Generated phone/Watch/widget Info.plists confirm the new identifier family and+companion linkage. Phone/widget entitlements and runtime snapshot selector agree+on `group.me.nore.ig.apps.meddy.widgets`. Every pre-existing target team selection+was compared to the pre-rebase checkpoint and preserved exactly. Original+untracked design-handoff files retain their snapshot hashes. No portal changes,+push/merge or new installation were performed during rebase verification.+++## Singular App Group correction++The user requested `group.me.nore.ig.apps.meddy.widget` (singular) after reporting+that the plural identifier had been created under the wrong account. The phone+and widget entitlements and runtime snapshot selector now use the singular group.+The widget bundle stays `me.nore.ig.apps.meddy.widgets`. No team settings,+capability grants, portal identifiers or credentials were modified. Earlier+receipts above using the plural group describe their original tested configuration,+not acceptance of the singular group. Existing-profile signing is rechecked separately.+++Singular-group validation: project/team/bundle settings compared unchanged against+the fresh pre-edit project snapshot. Phone and widget entitlement arrays and the+runtime selector agree exactly; no plural App Group remains in live source.+Both entitlement plists and whitespace checks pass. Unsigned Debug phone build+(including Watch and widget dependencies) passed with no launch or data access:+`/tmp/meddy-rebase-results/unsigned-singular-group.log` and `.xcresult`.+Existing-profile signed validation exited 65: the phone profile lacks App Groups+and the singular group; the widget wildcard profile lacks App Groups, the singular+group and Data Protection. No registration, profile update or installation followed.+Exact log: `/tmp/meddy-rebase-results/signed-singular-group.log`; result bundle:+`/tmp/meddy-rebase-results/signed-singular-group.xcresult`.+++## Singular widget bundle: signed build and installation retry++The user subsequently changed the widget bundle to `me.nore.ig.apps.meddy.widget`+in Debug and Release and explicitly requested installation. That exact choice was+preserved. Current phone/widget team is `4PJS97G236`; App Group remains+`group.me.nore.ig.apps.meddy.widget`. All source/user settings were hash-compared+unchanged during build; only this documentation and the current agent-guide bundle+reference were updated afterward. Original untracked handoff files remain untouched.++The supported phone-only staged build passed using existing profiles, without+provisioning-update/device-registration flags. Both signed packages passed strict+signature checks. The phone has `iCloud.me.nore.ig.apps.meddy`; both phone and+widget signed entitlements contain the singular App Group. The widget signed+entitlement is `com.apple.developer.default-data-protection = NSFileProtectionComplete`.+Profiles are exact `iOS Team Provisioning Profile: me.nore.ig.apps.meddy` and+`iOS Team Provisioning Profile: me.nore.ig.apps.meddy.widget`.+Build log: `/tmp/meddy-current-install-build.log`; staged source/log:+`/tmp/meddy-rebase-results/install-phone.u7_47n4q`.++Installation on The Dark Side succeeded as an in-place update of+`me.nore.ig.apps.meddy`, version 1.0/build 1, from the rebased `9197303` baseline+plus migration commits and current singular identifiers. This includes the restored+backup/restore and widget feature source. The old `me.nore.ig.meddy` remains+installed. No uninstall/reset, data migration, physical Watch installation,+credential generation, capability grants or portal changes were performed.++Normal launch was requested but denied because the phone is locked:+CoreDevice error 10002, FBSOpenApplicationErrorDomain 7 (`Locked`). No unlock+or retry without fresh user evidence was attempted. Unlock the phone before normal+launch verification. Installation is confirmed; normal launch and CloudKit runtime+acceptance are not confirmed for this candidate.+Receipts: `/tmp/meddy-current-install-result.json`,+`/tmp/meddy-current-installed-app.json`, `/tmp/meddy-current-old-app.json`,+`/tmp/meddy-current-launch.json`.+++## Import destination bootstrap investigation++User reported the empty-destination refusal despite the automatically generated Me.+Source inspection of the initially installed `82ff4d9` confirms bootstrap existed+before backup fingerprint recording. Current startup records `bootstrap-profile.json`+only when it creates Me in a previously profile-free destination. Upgrading an+existing Me does not retroactively claim that it is untouched.++The importer deliberately permits a sole unchanged fingerprinted Me, but refuses+an unfingerprinted profile even when its visible name is the default. Synthetic+regressions reproduce both paths using real ProfileMigration bootstrap: legacy Me+without a baseline is rejected with all records unchanged; newly bootstrapped Me+with its recorded baseline accepts the fully validated synthetic archive.+Existing edited/nonempty/reminder-state guard tests also pass. Receipt:+`/tmp/meddy-rebase-results/bootstrap-import-reproduction.xcresult` and matching log.+Strict lint and whitespace checks pass.++This matches the stale-build-to-current-build upgrade sequence, but the phone's+private store was not inspected, so other nonempty destination conditions are not+excluded for the actual device. There is no supported nondestructive UI path to+certify an already existing unfingerprinted Me as untouched. No production guard+was weakened, fingerprint retroactively issued, profile/data deleted, real backup+opened/imported, or new build installed. A recovery path requires a deliberate+policy/user confirmation rather than inferring provenance from the displayed name.+++## Approved starter-profile recovery installation++The user approved the narrowly scoped recovery implementation and installation.+The current build was installed and cold-launched with the explicit recovery flag;+the actual backup selection, review and profile replacement remain user actions+inside the app. No real import or further agent deletion was performed.+See [the recovery report](../specs/bugfixes/legacy-bootstrap-import/report.md)+for implementation boundaries, tests, deployment receipts and the user steps.+++## Temporary visible app label++The user approved temporarily labelling the migrated phone app `Meddy New` and+updating it in place. Only `CFBundleDisplayName` in `Meddy/Meddy/Info.plist` was+changed; source/configuration hash comparison confirms all other files unchanged+during build. Bundle, teams, App Group and CloudKit configuration are unchanged.+Signed build, strict signature and entitlement checks passed. The in-place install+succeeded; device metadata now distinguishes `Meddy New` (`me.nore.ig.apps.meddy`)+from unchanged `Meddy` (`me.nore.ig.meddy`), both version 1.0/build 1.+No uninstall/reset, data import or health-data inspection was performed.++A normal cold launch was requested with no recovery argument, but iOS denied it+because The Dark Side is locked (CoreDevice 10002 / FBSOpenApplicationErrorDomain 7).+The user can unlock the phone and open Meddy New normally. Runtime CloudKit success+is not claimed. Revert the two temporary CFBundleDisplayName plist lines when the+user no longer needs this visible distinction; keep the bundle ID unchanged.+Receipts: `/tmp/meddy-display-label-build.log`, `/tmp/meddy-display-label-install.json`,+`/tmp/meddy-display-label-new-installed.json`, `/tmp/meddy-display-label-old-installed.json`,+`/tmp/meddy-display-label-normal-launch.json`.+++## Final name restoration and publication candidate++The user reports removing the old app, and approved restoring the display name and+merging the migration work. The temporary phone CFBundleDisplayName override was+removed; built and installed metadata now display `Meddy` for+`me.nore.ig.apps.meddy`, version 1.0/build 1. Bundle, signing team, App Group and+CloudKit identity remain unchanged. The signed phone-only in-place update succeeded+and a normal cold launch succeeded with an empty argument list, PID 32265 (see the+launch receipt for authoritative process metadata). No reset/import/account action+was performed and no CloudKit runtime success is inferred.++Independent pre-push review identified a synchronous archive revalidation on the+main actor. Proof preparation now verifies input off MainActor, returns only archive+identity, then rechecks cancellation, journal, pending edits and destination state+under its permit. The UI shows progress while awaiting review. Additional synthetic+tests cover cancellation of an uncommitted proof and completion after a committed+save interruption. Publication gate and review evidence are recorded with the PR.++Receipts: `/tmp/meddy-merge-phone-name-build.log`,+`/tmp/meddy-name-restored-install.json`, `/tmp/meddy-name-restored-installed.json`,+`/tmp/meddy-name-restored-normal-launch.json`.
docs/meddy-design.md Modified
diff --git a/docs/meddy-design.md b/docs/meddy-design.mdindex dfa71a1..9f4a847 100644--- a/docs/meddy-design.md+++ b/docs/meddy-design.md@@ -1,5 +1,13 @@ # Meddy — Design Document +> Current identity (26 October 2026): the deliberate developer-account migration uses+> `me.nore.ig.apps.meddy`, Watch `me.nore.ig.apps.meddy.watchkitapp`, companion+> `me.nore.ig.apps.meddy`, and CloudKit `iCloud.me.nore.ig.apps.meddy`.+> See [account-migration.md](account-migration.md) for configuration and prerequisites.+> Earlier inspection/provisioning records below describe the old identity and are historical;+> they do not establish provisioning or data migration for the new identity.++ **Status:** Ready for implementation with the current working Apple Account; verify signing, Watch setup, and CloudKit provisioning during implementation   **Updated:** 5 October 2026; added Before sleeping and the 02:00 local logical day, retaining the temporary identifier and approved care workflows **Target:** iOS 27+ and watchOS 27+  @@ -171,20 +179,25 @@ If CloudKit is temporarily unavailable, the local SwiftData store must remain us  The Watch does **not** open the CloudKit/SwiftData store. -### Temporary development identity+### Current development identity -Use this temporary identifier family with the current working Apple Account while the different, future preferred account is being resolved:+Use this identifier family for the deliberate developer-account migration:  ```text-iOS bundle ID:                   me.nore.ig.meddy-Watch bundle ID:                 me.nore.ig.meddy.watchkitapp-WKCompanionAppBundleIdentifier:  me.nore.ig.meddy-CloudKit container (planned):    iCloud.me.nore.ig.meddy+iOS bundle ID:                   me.nore.ig.apps.meddy+Watch bundle ID:                 me.nore.ig.apps.meddy.watchkitapp+WKCompanionAppBundleIdentifier:  me.nore.ig.apps.meddy+CloudKit container (planned):    iCloud.me.nore.ig.apps.meddy ``` -The inspected iPhone starter already uses `me.nore.ig.meddy` in Debug and Release. The Watch target and CloudKit container/entitlements are not established by that inspection; their values above are the implementation plan, not proof of registration or provisioning. Any later test-target or generated companion-extension identifier must derive consistently from `me.nore.ig.meddy`. No App Group is required or introduced.+The project now uses this family in Debug and Release, including derived test identifiers.+The phone entitlement and both runtime CloudKit selectors agree. Configuration does not+prove registration, provisioning or access under the destination team. The upstream widget feature uses App Group `group.me.nore.ig.apps.meddy.widget`+for a display-only shared snapshot. See [account-migration.md](account-migration.md) for the preserved+team settings and remaining account prerequisites. -`me.nore.ig.apps.meddy` is the future preferred base only; it is not an active build, companion, test, or container value. Move to the preferred account and a new identifier when its issues are resolved, as a separate deliberate change; continue implementation under the working account now. Changing a bundle ID, signing team, or CloudKit container is not an automatic data migration: review signing and companion settings, existing local data, and container access before a deliberate change. Do not assume temporary local records or private CloudKit data will appear under a new identity. Apple's [developer account overview](https://developer.apple.com/help/account/basics/about-your-developer-account/) distinguishes team membership and provisioning from account sign-in; its [app-transfer guidance](https://developer.apple.com/help/app-store-connect/transfer-an-app/overview-of-app-transfer/) describes a separate App Store Connect process that retains the bundle ID. That process is not a promised migration path for this personal Xcode-installed app.+Changing bundle and container identity does not migrate local records or private CloudKit+data. Preserve the old app and container; data migration requires a separate deliberate step.  --- 
docs/meddy-implementation-plan.md Modified
diff --git a/docs/meddy-implementation-plan.md b/docs/meddy-implementation-plan.mdindex c967adc..c9514d1 100644--- a/docs/meddy-implementation-plan.md+++ b/docs/meddy-implementation-plan.md@@ -1,5 +1,13 @@ # Meddy — Implementation task plan +> Current identity (26 October 2026): the deliberate developer-account migration uses+> `me.nore.ig.apps.meddy`, Watch `me.nore.ig.apps.meddy.watchkitapp`, companion+> `me.nore.ig.apps.meddy`, and CloudKit `iCloud.me.nore.ig.apps.meddy`.+> See [account-migration.md](account-migration.md) for configuration and prerequisites.+> Earlier inspection/provisioning records below describe the old identity and are historical;+> they do not establish provisioning or data migration for the new identity.++ ## 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.@@ -35,7 +43,7 @@ The user approved this 15-task plan with “This looks good to proceed” on 5 O  ## Outcome and boundaries -Implement the approved personal iPhone/paired-Watch app, including private CloudKit under the current working Apple Account. Keep `me.nore.ig.meddy`, Watch `me.nore.ig.meddy.watchkitapp`, companion reference `me.nore.ig.meddy`, and container `iCloud.me.nore.ig.meddy` consistent. Test identifiers derive from this base. Local reminder notifications are included in v1, with Taken and Snooze actions; no separate server-sent push-notification service/capability is required for those reminders. Configure CloudKit-required entitlements/capabilities and the Remote notifications background mode according to the current SDK and preflight; this reminder clarification does not remove anything required for CloudKit delivery. Do not add App Groups, HealthKit or the design's other v1 non-goals. Watch owns cached snapshots, its durable outbox and checkpoints; iPhone owns canonical SwiftData/private CloudKit records.+Implement the approved personal iPhone/paired-Watch app, including private CloudKit under the current working Apple Account. Keep `me.nore.ig.apps.meddy`, Watch `me.nore.ig.apps.meddy.watchkitapp`, companion reference `me.nore.ig.apps.meddy`, and container `iCloud.me.nore.ig.apps.meddy` consistent. Test identifiers derive from this base. Local reminder notifications are included in v1, with Taken and Snooze actions; no separate server-sent push-notification service/capability is required for those reminders. Configure CloudKit-required entitlements/capabilities and the Remote notifications background mode according to the current SDK and preflight; this reminder clarification does not remove anything required for CloudKit delivery. Use only the widget feature's App Group `group.me.nore.ig.apps.meddy.widget`; do not add HealthKit or the design's other v1 non-goals. Watch owns cached snapshots, its durable outbox and checkpoints; iPhone owns canonical SwiftData/private CloudKit records.  The preferred future account/new identifier is a separate migration decision. It is neither a current blocker nor an automatic signing/data/container migration. Offline operation and isolated test stores are required parts of the CloudKit architecture, not a temporary local-only product phase. 
docs/meddy-implementation-preflight.md Modified
diff --git a/docs/meddy-implementation-preflight.md b/docs/meddy-implementation-preflight.mdindex 57ed1ec..207d8b4 100644--- a/docs/meddy-implementation-preflight.md+++ b/docs/meddy-implementation-preflight.md@@ -1,5 +1,13 @@ # Meddy — Implementation Preflight +> Current identity (26 October 2026): the deliberate developer-account migration uses+> `me.nore.ig.apps.meddy`, Watch `me.nore.ig.apps.meddy.watchkitapp`, companion+> `me.nore.ig.apps.meddy`, and CloudKit `iCloud.me.nore.ig.apps.meddy`.+> See [account-migration.md](account-migration.md) for configuration and prerequisites.+> Earlier inspection/provisioning records below describe the old identity and are historical;+> they do not establish provisioning or data migration for the new identity.++ **Purpose:** Implement Meddy from the inspected Xcode starter using the current working Apple Account, with the intended device, Watch, and CloudKit setup verified alongside implementation.  **Updated:** 5 October 2026; current working account clarified, temporary identifier and actual starter readiness retained, preserving treatment items, ordered routines, independent twice-daily sessions, and as-needed quick logging.@@ -59,7 +67,7 @@ WKCompanionAppBundleIdentifier = me.nore.ig.meddy  The iPhone bundle ID is already configured in the starter. The Watch ID and CloudKit container above are planned values, not claims that a target, identifier, or container has been created. For any later test target or Xcode-generated Watch extension, use a distinct identifier derived from `me.nore.ig.meddy`; keep companion references and examples on the same base. Do not add an App Group or an App Group identifier for this design. -`me.nore.ig.apps.meddy` is the future preferred base only and must not be used in active settings or examples. The intended future move to the preferred account and a new identifier is a separate deliberate change; it does not postpone current implementation. Before deliberately changing the bundle ID, signing team, or CloudKit container, review provisioning, companion references, local app data, and existing container access. Such a change is not an automatic migration; do not assume local records or private CloudKit data will carry over.+The temporary identifiers in this original preflight are superseded by the current identity notice above. The deliberate identifier change does not automatically migrate local records or private CloudKit data; see the current migration prerequisites.  Apple distinguishes account sign-in from developer-team membership and provisioning in its [developer account overview](https://developer.apple.com/help/account/basics/about-your-developer-account/). Its [app-transfer guidance](https://developer.apple.com/help/app-store-connect/transfer-an-app/overview-of-app-transfer/) describes a separate App Store Connect process that retains the bundle ID; it is not a promised migration route for this personal Xcode-installed app. Keep the temporary identity stable during development until a deliberate decision is made. 
specs/bugfixes/legacy-bootstrap-import/design.md Added
diff --git a/specs/bugfixes/legacy-bootstrap-import/design.md b/specs/bugfixes/legacy-bootstrap-import/design.mdnew file mode 100644index 0000000..d1be3b2--- /dev/null+++ b/specs/bugfixes/legacy-bootstrap-import/design.md@@ -0,0 +1,192 @@+# Explicit legacy-bootstrap import recovery: design review++Status: user-approved implementation is now prepared and under final validation.+Earlier proposal/rejected approaches below are retained as investigation history.+No real placeholder replacement, backup import or cloud clearing has been performed.+The user reports doing nothing in the newly installed migrated app. That statement+supports offering a deliberate recovery decision; it does not authorize importing,+resetting, deleting or retroactively fingerprinting an existing profile.++## Cause and supported behavior++The first installed migrated baseline predates backup bootstrap fingerprinting.+It creates Me without `bootstrap-profile.json`. New startup fingerprints only a Me+it creates itself. The importer permits an unchanged fingerprinted placeholder but+refuses an existing unfingerprinted Me. Synthetic production-bootstrap tests confirm+both the legacy refusal (unchanged destination) and fresh-placeholder success.+The displayed default name cannot prove historical non-editing.++## Proposed user action, conditional on closing the writer race++1. The user selects their backup through the existing Import backup action.+2. Existing decoding, validation, bounded staging, hash/readback and scratch roundtrip+   must succeed before a recovery option is considered. No real backup is inspected+   by development tools; validation remains in the user's app.+3. A read-only eligibility assessment offers the exceptional confirmation only when+   exactly one self profile is present, with the fixed Me identity/self lifecycle,+   nil display name and archive date, no other care rows of any kind, no restore+   receipts/journal, no semantic reminders and no pending edits. A present mismatching+   bootstrap fingerprint, malformed profile/metadata, duplicate profile or extra row+   must continue to reject. No age/timestamp tolerance can prove old non-editing;+   uncertain provenance must be stated, not silently inferred from profile shape.+4. Proposed text: “This installation contains only its default Me profile, but this+   older installation has no record proving it is unused. If you have not added or+   edited anything here, you can use it for this restore. Its profile details will+   be replaced by the verified backup. Your old Meddy app is unchanged.”+   Explicit action: “Use default profile and import”; Cancel leaves everything intact.+   This is a deliberate exception to the existing provenance rule, requiring approval+   of that policy before implementation. It cannot be described as proof of untouchedness.+5. Bind consent to the canonical full destination snapshot, semantic reminder state,+   validated archive hash, input name and archive identity. Any state change or a new+   backup invalidates consent. A reusable boolean/blanket empty-store flag is prohibited.+6. Reuse existing restore permit, durable pending journal, raw insertion and save with+   restore receipt. Do not create `bootstrap-profile.json` for this old profile.+   Journal recovery needs a strictly typed, bounded proof for this one confirmed+   baseline; extend strict parsing compatibly for old journals. Before-save recovery+   can resume only if the entire original baseline still matches. Committed recovery+   uses the existing receipt and retained verified input, never reclassifies a new store.+7. Save restored rows and receipt atomically; on pre-save error roll back only this+   operation's unsaved context, preserving independent data and pending recovery evidence.+   Cancel never clears care data. Existing edited/nonempty/reminder tests remain mandatory.++## Blocking atomicity question++`BackupOperationGate` uses an app-private flock and local service permits. CloudKit+mirroring or another independent ModelContext does not participate in that lock.+`emptyBaseline` rechecks a fresh context, then insertion/save follow; the code has no+store-level conditional-write primitive binding the check and save. The synthetic+`independentWriterCanArriveAfterFinalBaselineCheck` probe injects a separate saved+Medication at the existing `beforeSave` fault boundary to measure this window.+It is a design probe documenting current behavior, not an accepted regression contract.++An exact snapshot token plus another check narrows the window but does not close it.+An after-save comparison detects some problems too late and is not a rollback strategy+for an already committed or mirrored store. The local permit must not be presented+as a CloudKit lock. Offline mode/reinstall likewise does not establish cloud emptiness+or prevent later arrivals. No cloud state has been inspected or proven empty.++Before a production recovery exception, establish a supported persistence/coordinator+mechanism that excludes independent store imports through compare-and-save, or design+an isolated restore admission phase with explicit reconciliation of subsequent cloud+arrivals. SwiftData does not expose such exclusion in the current app. Do not use+private APIs, new cloud identities, remote deletions, or a system permission change+as an incidental workaround. If writer exclusion cannot be established, keep this+exception unavailable for the live CloudKit store and report the limitation.++## Synthetic validation required++- Fresh fingerprinted Me succeeds; legacy missing-proof Me is refused unchanged today.+- Explicit proof, once approved/implemented: exact allowed shape only; name/archive/+  lifecycle changes, duplicates, care rows, receipts, reminder state and pending edits+  reject without mutation; changed input/consent mismatch reject before journal/save.+- Writer injection before consent, during verification, before journal and immediately+  before save must be refused unchanged, including same-identity profile arrivals.+- Invalid/truncated archives and scratch mismatch never offer or mutate recovery.+- Injected save errors preserve all prior destination values. Journal reopen/cancel/+  resume and after-save completion retain archive identity and original provenance.++## Recommendation++Keep the user's installation and old app intact. Explain that their no-edits report+makes them the intended user for a recovery option, but no currently supported+button resolves this safely. Obtain approval for the explicit one-restore exception+and resolve the writer/CloudKit admission boundary before implementation/deployment.+Do not ask them to erase/reinstall as if that guaranteed a fresh destination.++## Duplicate-Me follow-up after authorised reinstall++The user reports two Me entries after the bounded reinstall and says they did not+add data. Do not repeat reinstall or delete anything else. Bootstrap can create a+self-profile locally before an independent writer supplies another physical row+with the same fixed logical ID. CareProfile has no uniqueness constraint. Both rows+render as Me and the importer correctly refuses `careProfiles.count != 1`.+A synthetic independent-context arrival reproduces that sequence; this does not+establish that CloudKit caused the phone's actual state.++### Narrow candidate and explicit confirmation++Scope this recovery candidate to the exact two observed default self-profile rows,+not arbitrary profile deduplication. Both must have the fixed self ID/lifecycle, nil+display name/archive, structurally valid dates, and no associated care/history rows+of any type, semantic reminders, restore receipts, journal or pending edits.+Visible Me labels are insufficient. Any unrecognized shape, third arrival, edited+value or nonempty state refuses unchanged. Record exact persistent row identities+and full canonical values, not just the common logical UUID. The current fingerprint+may prove one row but cannot prove the other; the UI must disclose that uncertainty.++Proposed confirmation, only after full backup validation:+“Replace these two unused default Me profiles with the profiles in this verified+backup? This only applies to the new Meddy app. Their removal may synchronize to+this new app's iCloud container. Your old Meddy app and backup are unchanged.”+Action: “Replace default profiles and restore”. Cancel changes nothing. The user+must authorise that narrow profile replacement/synchronization; their previous+new-app uninstall approval does not cover it. No wholesale cloud clearing is proposed.++Delete only the exact confirmed persistent rows and insert restored records plus+receipt in the same save; never clear profiles in a separate preliminary save.+Synthetic mechanics verify rollback leaves both original rows intact and a single+successful save can produce the exact backup plus receipt. Production still needs+archive-bound confirmation, journal recovery proof, precommit exact-state validation,+and rollback/error tests. The implementation would principally touch admission/+commit in PhoneBackupImporter, strict typed BackupRecoveryJournal proof, and the+existing BackupRestoreView preview confirmation; no schema, credentials, portal or+migration framework is needed.++The independent-writer race remains a blocking design condition: the existing+beforeSave probe admits an extra saved Medication despite the restore permit.+A second check or UI confirmation alone is not an atomic exclusion. Until a supported+writer-serialization/conditional commit can be established, do not describe this+candidate as guaranteed to reject all CloudKit arrivals or deploy an empty-store+bypass. A late arrival must never trigger automatic widening of the confirmed set.+++## Implemented bounded recovery (supersedes the open writer-boundary proposal)++The user explicitly approved adding and installing the repair, with actual profile+replacement/import still requiring confirmation in the app. The solution does not+freeze global CloudKit or change permissions. A cold launch with+`--meddy-default-profile-recovery` opens the existing configuration's exact URL/name+with managed CloudKit disabled (`ModelConfiguration.CloudKitDatabase.none`). No+CloudKit-enabled ModelContainer is constructed in that process. Normal care UI,+bootstrap and widget publishing are not started; widgets only read display snapshots+and never open SwiftData. The local restore permit excludes the remaining local+care producers. The marker persists across crashes/pending recovery; after completion,+closing/reopening returns to the usual CloudKit configuration.++Framework basis: Apple's documented `.none` disables managed CloudKit sync:+https://developer.apple.com/documentation/swiftdata/modelconfiguration/cloudkitdatabase-swift.struct/none+The explicit-url initializer preserves the existing persistent location; no new+identity, store reset, credential, cloud deletion or schema deployment is introduced.++This closes the particular production writer source for the short local commit+without claiming a distributed transaction with other devices. It does not promise+an empty remote database. Later remote arrivals are retained and are never grounds+for expanding the confirmed deletion set or automatically retrying cleanup.++The recovery importer is enabled only for a no-CloudKit configuration selected by+this session. It offers the confirmation only for exactly two fixed self-ID/lifecycle,+unnamed/unarchived profiles, no care/history/wake rows, no reminder semantics,+receipts, pending journal or edits. If a bootstrap fingerprint exists it must still+match one of these rows. Default shape is not historical provenance; the user's+explicit no-edits confirmation authorises this narrow exception. Full archive decode,+hash validation and disk scratch roundtrip precede the offer.++Consent binds canonical values and exact persistent row identities to archive ID+and hash. A final fresh-context check after the fault hook rejects a new care row,+third profile or selected-row edit and rolls back only staged work. Selected profile+removal, archive insertion and receipt are saved together. A typed, bounded journal+proof supports pre-save resume/cancel and existing post-save completion. No permanent+bootstrap fingerprint is issued for legacy data.++Synthetic probes established the actual limit: an unrelated independent care insert+survives a scoped save and can be detected; a concurrent edit of a selected row can+be lost under SwiftData's normal save. That is why post-save validation alone and+an extra UI check were rejected. The new recovery tests inject both kinds before+save and prove preservation/refusal under exact-state revalidation; the cold `.none`+session prevents managed CloudKit from introducing the unguarded final-window writer.++User flow: select backup, review it, tap “Review starter-profile recovery”, then+explicitly “Replace starter profiles and restore” or Cancel. Confirmation explains+that placeholder removals synchronize to the new app's container when sync resumes,+while the old app is untouched. Success directs the user to close/reopen Meddy.+Leaving recovery mode without importing also changes only the local mode marker.
specs/bugfixes/legacy-bootstrap-import/implementation.md Added
diff --git a/specs/bugfixes/legacy-bootstrap-import/implementation.md b/specs/bugfixes/legacy-bootstrap-import/implementation.mdnew file mode 100644index 0000000..dad2fd3--- /dev/null+++ b/specs/bugfixes/legacy-bootstrap-import/implementation.md@@ -0,0 +1,59 @@+# Migration and starter-profile recovery implementation++## Beginner++The app now uses the requested developer-account identifiers and keeps the latest+backup/restore, widget and prescription features. Its phone display name is Meddy+again. The old and new app identities were separate; the user reports removing the+old app and successfully restoring their backup in the new one.++An older installation created Me before import could record that it was a pristine+starter profile. A later independent arrival could produce a second Me. The repair+lets the user select and validate a backup, then explicitly confirm replacement of+only the two unused default profiles. It never clears an otherwise populated app.++## Intermediate++A cold recovery launch selects the normal configuration's exact persistent URL,+with managed CloudKit mirroring disabled for that process. Normal bootstrap, care+UI and widget publishing are not started. A durable marker retains this bounded+session across crashes. The existing archive decoder, scratch-store roundtrip,+restore gate, raw insertion, receipt and completion flow are reused.++Consent binds two exact persistent row identities and canonical profile values to+the archive identity/hash. A present bootstrap fingerprint must still match one row.+Any care/history/wake row, reminder semantics, prior receipt/journal, edited shape,+extra profile or pending edit blocks the exceptional offer. Verification runs off+the main actor and rechecks destination state after returning. One save replaces+only confirmed profiles, inserts restored records and saves the receipt.++## Expert++The existing local permit does not exclude independent CloudKit store writers.+Synthetic probes demonstrated that unrelated arrivals survive scoped replacement,+but a selected-row concurrent edit can be lost under default SwiftData save rules.+Post-save validation alone is therefore insufficient. The recovery process never+constructs a CloudKit-enabled container; widget extensions read derived snapshots+only, while the restore permit excludes other local care producers. A final fresh+snapshot after the fault hook rejects simulated arrivals and rolls back only this+operation's staged work. This is bounded local admission, not distributed atomicity.++The strict journal includes an optional bounded confirmation proof, preserving old+journal compatibility and archive binding. Pre-save interruption supports exact+resume/cancel; post-save interruption completes via its receipt without duplication.+On success the mode marker is cleared. Closing/reopening resumes the normal CloudKit+configuration; later remote arrivals are preserved and never expand a deletion set.+Default visible shape alone is not historical provenance: the explicit user no-edits+confirmation authorises this narrow exception, rather than silently fingerprinting it.++## Completeness assessment++Implemented: final phone/Watch/test/widget identifier family, matching singular App+Group, CloudKit selectors, install guard, explicitly confirmed two-profile recovery,+rollback/recovery coverage, current display name and preserved upstream features.++Validation includes synthetic safety and UI tests and signed in-place deployment.+Merge-phase full pre-push results are recorded in the review artefact. Watch UI test+signing retains the pre-existing old team, as documented; physical Watch deployment+and actual CloudKit runtime reconciliation are not claimed. No cloud provisioning,+credentials, schema deployment or further real import/reset accompanies publication.
specs/bugfixes/legacy-bootstrap-import/report.md Added
diff --git a/specs/bugfixes/legacy-bootstrap-import/report.md b/specs/bugfixes/legacy-bootstrap-import/report.mdnew file mode 100644index 0000000..7c5f2fb--- /dev/null+++ b/specs/bugfixes/legacy-bootstrap-import/report.md@@ -0,0 +1,97 @@+# Legacy starter-profile import recovery++User approved implementation and installation, with actual replacement/import+still confirmed by the user inside the app. No real backup was selected or imported+by the agent; no real profile, old-app, cloud or shared data was deleted by this repair.++## Result++Installed the current signed phone-only build in place on The Dark Side as+`me.nore.ig.apps.meddy`, version 1.0/build 1. Widget is+`me.nore.ig.apps.meddy.widget`; shared group is+`group.me.nore.ig.apps.meddy.widget`; signatures/team verified `4PJS97G236`.+The old `me.nore.ig.meddy` app remains installed.++Cold launch with `--meddy-default-profile-recovery` succeeded, PID 29502;+launch metadata confirms termination of the previous instance and that exact flag.+The app now opens its existing store in the bounded local-only recovery session;+no normal CloudKit-enabled container, bootstrap, care UI or widget publisher is+started in that process. The user's selection and destructive confirmation remain+required. See design.md for the exact admission/journal rules and writer evidence.++User steps: Import backup; select the exported backup; review it; choose Review+starter-profile recovery; confirm Replace starter profiles and restore. After+success, close and reopen Meddy to resume normal sync. Cancel/Leave recovery does+not clear care data. A changed/nonempty/ambiguous destination remains refused.++## Validation++- Focused safety/import/journal suites: 42 tests passed before additional probes.+- Full phone domain: 350 tests in 53 suites passed, including independent arrival,+  profile-edit and duplicate rejection, rollback, journal reopen and exact consent.+- Final synthetic UI: 3 tests passed: explicit confirmation/cancel/completion,+  existing backup navigation, and existing pending-restore completion.+- Strict lint: 193 files, zero violations; whitespace and all 4 install-tool tests pass.+- Signed device build and strict phone/widget signature, identifiers, team and group+  checks pass using existing profiles; no provisioning-update flags or grants.+- Installed staged Swift sources matched checked-out sources before installation.+- Original untracked design-handoff file hashes remain unchanged.++The first combined run passed domain tests but exposed a recovery completion-view+rebuild that cleared its result state. That was fixed and the final UI trio passes.+The first signed attempt failed because host temporary storage was full during+asset compilation. Only three obsolete task-owned temporary build caches were+removed; source, user caches, logs and result bundles were retained. Retry passed.+Neither failed attempt is counted as passing validation.++Receipts:+- `/tmp/meddy-rebase-results/default-recovery-focused.xcresult`+- `/tmp/meddy-rebase-results/default-recovery-full-domain.xcresult` (domain pass; original UI failure)+- `/tmp/meddy-rebase-results/default-recovery-ui-final.xcresult` (3/3 final UI pass)+- `/tmp/meddy-rebase-results/default-recovery-final-lint.log`+- `/tmp/meddy-default-recovery-device-retry.log`+- `/tmp/meddy-default-recovery-install.json`+- `/tmp/meddy-default-recovery-launch.json`+- `/tmp/meddy-default-recovery-old-preserved.json`++Actual backup restore and subsequent CloudKit runtime acceptance are not claimed.+Later remote arrivals are preserved; they do not authorise broader cleanup or retry.+At that deployment checkpoint, user project/team choices and migration edits remained uncommitted. Publication validation follows below.+++## Publication validation and final name++The phone display name is restored to Meddy. Existing-profile signed build,+strict signature/identifier/team/group checks, in-place phone installation and a+normal cold launch with no recovery arguments passed. No uninstall/reset, import,+account change or claimed CloudKit runtime verification accompanies this update.++Four independent pre-push scopes reviewed the full change. One UI responsiveness+finding was fixed: archive revalidation runs off MainActor and returns only archive+identity before destination rechecks under its permit. Additional cancellation and+post-save completion tests pass, and the finding was independently re-reviewed.++Current source validation: widget build; 352 phone domain tests; 14 Watch tests;+31 UI cases verified on the unchanged tree; strict lint and whitespace. The full+UI attempt completed 27 passing cases and 4 photo startup failures during actual+ENOSPC. The diagnostic hierarchy explicitly showed the test store could not open+because the Data volume was out of space. Its result writer stalled and was drained;+the byte-verified failed output is retained as+`/tmp/meddy-merge-gates/failed-ui-enospc.xcresult.tar.gz`.++Only task-owned compiler caches, the completed dedicated Watch simulator and a+redundant uncompressed failed result were cleaned; source, original handoff files,+user caches and all diagnostic evidence were preserved. Once stable space returned,+all 4 photo cases and the single navigation case whose record was truncated were+re-executed without building, with clean result bundles and zero failures/skips.+The other 26 named UI passes are retained in the original runner log. Thus all 31+UI cases have passing evidence; the initial wrapper run is not represented as a+passing `gmake pre-push` invocation. No source/assertion changes masked the failures.++Receipts: `/tmp/meddy-prepush-inputs/pre-push.log`,+`/tmp/meddy-prepush-inputs/photo-failure-evidence.txt`,+`/tmp/meddy-merge-gates/test-domain.BOOiWJ/Results.xcresult`,+`/tmp/meddy-merge-gates/test-watch.axvwdM/Results.xcresult`,+`/tmp/meddy-merge-photo-clean.xcresult`, `/tmp/meddy-merge-navigation-proof.xcresult`,+`/tmp/meddy-merge-phone-name-build.log`, `/tmp/meddy-name-restored-install.json`,+`/tmp/meddy-name-restored-normal-launch.json`.
specs/portable-backup-restore/requirements.md Modified
diff --git a/specs/portable-backup-restore/requirements.md b/specs/portable-backup-restore/requirements.mdindex 582b60d..c57b332 100644--- a/specs/portable-backup-restore/requirements.md+++ b/specs/portable-backup-restore/requirements.md@@ -46,7 +46,7 @@ Meddy provides a portable backup of the care data stored on this iPhone so it ca  **Acceptance Criteria:** -1. <a name="4.1"></a>WHEN importing, Meddy SHALL accept only a locally empty destination, allowing its unchanged automatically created Me placeholder, and SHALL reject any destination containing other care records, changed profile values or existing semantic reminder state without replacing them. Meddy SHALL recheck local emptiness immediately before committing and SHALL prevent competing local care changes through commit or recovery; newly present records SHALL cause rejection unchanged.+1. <a name="4.1"></a>WHEN importing, Meddy SHALL accept only a locally empty destination, allowing its unchanged automatically created Me placeholder, and SHALL reject any destination containing other care records, changed profile values or existing semantic reminder state without replacing them. Meddy SHALL recheck local emptiness immediately before committing and SHALL prevent competing local care changes through commit or recovery; newly present records SHALL cause rejection unchanged. The explicitly approved legacy-bootstrap recovery is a narrow exception for exactly two unused default-shaped self profiles after archive-bound in-app confirmation, in a cold local-only recovery session; see [the recovery design](../bugfixes/legacy-bootstrap-import/design.md). All edited, ambiguous or otherwise nonempty destinations remain protected. 2. <a name="4.2"></a>WHEN import succeeds, Meddy SHALL preserve archived field values, IDs, relationships, image bytes, historical dose values and tombstones through persistence and normal app relaunch; it SHALL NOT silently assign unknown ownership or recreate deleted care events. 3. <a name="4.3"></a>IF import fails or is interrupted, Meddy SHALL leave the original destination intact or enter a recoverable state that retains the input and prevents partial imported care from being used; retry/relaunch SHALL NOT duplicate records. 4. <a name="4.4"></a>WHEN an archive is selected again after successful import, including an archive containing only the default Me profile, Meddy SHALL refuse a second import without adding records and explain that the destination already contains data.

Things to double-check

Runtime limits

Existing-profile signing and device installation are separate from actual CloudKit sync acceptance. No runtime cloud success is inferred.