Modern Apps git

← Modern-Apps.git

everysync: Apple EventKit/Contacts/Keychain/CryptoKit providers

Commit
953085fd86ff724de63f075055af491725088a1d
Author
vayun-mathur <[email protected]>
When
2026-10-18 04:29 UTC (1 month ago)
Parents
a7fcd4e

Diff

apple/E2E_CHECKLIST.md
diff --git a/apple/E2E_CHECKLIST.md b/apple/E2E_CHECKLIST.mdnew file mode 100644index 0000000000..fba4e3eb7d--- /dev/null+++ b/apple/E2E_CHECKLIST.md@@ -0,0 +1,125 @@+# EverySync Apple — manual end-to-end checklist (Phase 3, Mac + devices)++`xcodebuild` cannot run on the Windows box, so this checklist is the Phase 3+verification gate. Run top-to-bottom on a Mac with two iOS simulators (or one+simulator + one Android emulator for the cross-device matrix). Every step+references the file that implements it.++Conventions: vault keys NEVER user-visible (share links carry ids only; keys+move via PQC-sealed inbox invites). Failed pull = abort, never empty. Only+explicit tombstones delete.++## 0. Build++- [ ] `sh apple/XCFramework/build_xcframework.sh` succeeds (see+      `XCFramework/BUILD_NOTES.md`); the XCFramework links into all five+      targets (Passwords, Notes, Hub, Credential Provider, Share extension).+- [ ] `./gradlew :library:everysync-core:compileKotlinIosArm64`+      `:library:everysync-core:compileKotlinIosSimulatorArm64` green (see+      `XCFramework/IOS_ACTUALS_NOTES.md`).+- [ ] `xcodebuild` Passwords / Notes / Hub schemes build for simulator.++## 1. Permissions (fresh install per app)++- [ ] Passwords launch: Face ID prompt (`NSFaceIDUsageDescription`); deny ->+      vault list still renders, unlock rows disabled (no crash, no secret leak).+- [ ] Hub launch: Reminders prompt (`NSRemindersUsageDescription`),+      Calendars (`NSCalendarsUsageDescription`), Contacts+      (`NSContactsUsageDescription`). Deny EACH ONE individually and confirm+      the other two sinks still cycle (per-store health — `HubSync.swift`).+- [ ] Keychain: lock the simulator, unlock, confirm vault keys + cursors+      survived (`KeychainSecureStore.swift`:+      `AfterFirstUnlockThisDeviceOnly`).++## 2. Relay conformance (simulator <-> Android/desktop, both directions)++Against staging `https://findfamily.cc/personal` (see plan Phase 1F):++- [ ] `register` / `getkey` round-trip from the simulator (device id stable+      across restarts — `personalDeviceId` in Keychain).+- [ ] `append` / `pull` on `passwords:<vault>`, `notes:<vault>`,+      `todos:<vault>`: channel-name assertions pass; records are+      `B64(AES_GCM)` per item; roster/epoch/transfer envelopes double-wrap+      as `B64(Json(...))`.+- [ ] PQC-sealed invite to `inbox:<device>` decrypts on the recipient.+- [ ] `everysync://join` link parses (`RelayLinks.parseJoinLink` via the+      XCFramework; URL scheme fires the app).+- [ ] Kill the network mid-pull: cycle ABORTS, local data untouched (never+      folded as empty). Restore network: next pull resumes from the cursor+      (`relay_cursor:<type>:<vault>:<channel>` in Keychain).+- [ ] Tombstone propagation per type: delete a note/todo on Android, confirm+      the tombstone removes the `EKReminder` / note row on iOS; delete a+      password, confirm the row VANISHES (hard-delete) while the snapshot+      remembers it.+- [ ] Purge a vault on iOS (`EnvelopeIPC.purgeVault`), pull: vault+      re-populates from the relay (re-enable repopulation).++## 3. Passwords + Credential Provider (autofill)++- [ ] Create a password on iOS; `mergeCredentials` pairs its passkey on the+      detail page (explicit `PasskeyLink.To` survives; auto-match needs+      domain AND username on exactly one candidate; ties stay standalone).+- [ ] TOTP code matches Android for the same secret/epoch (6-digit,+      30s step — `Totp.generate` in the XCFramework).+- [ ] Autofill in Safari: `prepareCredentialList` offers the right site+      (`DomainMatch` — `notexample.com` must NOT match `example.com`);+      `provideCredentialWithoutUserInteraction` fills without UI;+      confirmation UI path works with Face ID.+- [ ] XPC: kill the containing app, autofill from the extension ALONE+      (reads via `com.vayunmathur.everysync.envelope-ipc` — extension never+      touches the relay).+- [ ] Share sheet offers EDITOR only — never VIEWER (`RelayRoles`).+      Passwords vaults never grant VIEWER.++## 4. Notes (NoteBody)++- [ ] Text block round-trips markdown verbatim (merge hashes it — no+      normalization in Swift).+- [ ] Image block: photo added on Android appears on iOS via+      `notes-blobs:<vaultId>` prefetch (`NoteKind.imageNames`); missing blob+      renders a placeholder, never a crash. `widthFraction` resize persists.+- [ ] Ink block: draw with PencilKit; strokes survive a sync cycle to Android+      and back (mapping: `PencilKitMapping.swift`; serialization in+      `serializeNoteBody`). `heightDp` default 300.+- [ ] Soft-delete: delete a note on iOS, confirm the tombstone row persists+      locally AND propagates (never raw-deletes).+- [ ] Share extension: share a URL from Safari -> new note with a text block+      in the active vault (hub picks it up next cycle; extension never talks+      to the relay).++## 5. Hub sinks (no Todo app — Reminders IS the UI)++- [ ] Todo created on Android appears in the system Reminders app with title,+      `notes` (persisted — merge-hash input), due date, done state.+      `position` reorder on one side never looks like an edit.+- [ ] `createdAt` adoption: pre-existing reminders adopt on first sync via+      `contentKey = "todo␀" + title + "␀" + createdAt`.+- [ ] Delete a reminder in the Reminders app: after the next HEALTHY fetch,+      the tombstone envelope propagates (known-minus-fetched in `SyncIdMap`).+      Airplane-mode delete + fetch failure: cycle aborts, nothing deleted.+- [ ] Contact round-trip: name parts, org, note, all typed phones/emails/+      addresses, birthday `yyyy-MM-dd`. Shared type ints pass through+      (`PhoneKind`/`EmailKind`/`PostalKind` tables in `ContactSink.swift`).+      Swift never writes syncIds into contact fields.+- [ ] Calendar round-trip: summary/desc/location, start/end, allDay,+      timezone display, RRULE verbatim (masters store duration), overridden+      instance merges independently (`uid␀recurrenceId` key).+- [ ] APNs silent push wakes the hub and triggers a PULL (payload carries+      nothing — verify with a proxy: push body has no vault data/keys).++## 6. Background sync++- [ ] `BGAppRefreshTaskRequest` fires for all three identifiers; each handler+      re-schedules at the end (system gives no repeating schedule).+- [ ] Local edit -> one-shot `BGProcessingTaskRequest` pushes within a minute.+- [ ] Force-quit + relaunch: schedules re-register, cursors intact, no+      duplicate appends (idempotent `upsertRaw` keyed on `syncId`).++## 7. Loss-prevention spot checks (the three invariants, verbatim)++1. [ ] Failed pull returns null = abort, never empty (unplug network mid-pull+      on each type; data untouched).+2. [ ] Failed local read surfaces as failure, never empty (revoke Reminders+      access mid-cycle; hub aborts that sink, keeps the others).+3. [ ] Only explicit tombstones delete (delete server-side WITHOUT a+      tombstone: record resurrects/quarantines — never vanishes).
apple/Hub/CalendarSink.swift
diff --git a/apple/Hub/CalendarSink.swift b/apple/Hub/CalendarSink.swiftnew file mode 100644index 0000000000..e8b315eddd--- /dev/null+++ b/apple/Hub/CalendarSink.swift@@ -0,0 +1,76 @@+// EverySync Hub — calendar -> `EKEvent` sink.+//+// `EKEventStore` + calendar access. Maps `RemoteEvent` summary / description /+// location / start-end millis / allDay / timezone / RRULE / recurrenceId onto+// `EKEvent` in a hub-managed calendar. Same driver-applies, Swift-renders+// split as the other sinks: delete and conflict semantics follow+// `CalendarKind` (syncId = UID [+ ␀RECURRENCE-ID for overridden instances];+// canonical iCal keeps RECURRENCE-ID; soft-delete).+//+// Field mapping:+// - `uid` (+ `recurrenceId` for overridden instances) -> identity via the+//   hub map (`SyncIdMap.swift`; the composite `uid␀recurrenceId` is the map+//   key — `EKEvent.eventIdentifier` is hub-local state, never an IPC column).+// - `summary/description/location` -> `title/notes/location`.+// - `startMillis/endMillis` -> `startDate/endDate` (UTC instant; `timeZone`+//   sets `event.timeZone` for display — the stored instants never shift).+// - `allDay` -> `isAllDay`.+// - `rrule` (raw RRULE line WITHOUT the `RRULE:` prefix) -> `recurrenceRules`+//   (`EKRecurrenceRule` parsed from the verbatim line; masters store duration+//   instead of end — same as `core.format.ICalendar`).+// - `recurrenceId` -> detached occurrence (`event.recurrenceIdentifier`+//   lineage; each overridden instance merges independently).+// - `deleted=true` envelope -> remove the `EKEvent`.+// - `calendarId` selects the hub-managed calendar (NOT a system calendar id —+//   hub calendars are created per vault and recorded in the syncId map+//   namespace).+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `EKRecurrenceRule` init from an RFC 5545 RRULE line: EventKit has no+//   string parser — the Mac must map the verbatim line through+//   `EKRecurrenceRule(recurrenceWith:interval:end:)` field-by-field+//   (FREQ/INTERVAL/COUNT/UNTIL/BYDAY/…). Keep that parser next to this file+//   (`RRuleParser.swift`); it is display-mapping, NOT merge logic.+// - `requestFullAccessToEvents` vs legacy `requestAccess(to: .event)` per+//   deployment target.++import EventKit+import EverysyncCore++/// Applies XCFramework driver output for one vault's events.+/// Driver output in, `EKEvent` rows out — nothing else.+final class CalendarSink {+    private let eventStore: EKEventStore+    private let syncIdMap: SyncIdMap++    init(eventStore: EKEventStore, syncIdMap: SyncIdMap) {+        self.eventStore = eventStore+        self.syncIdMap = syncIdMap+    }++    // TODO(Mac): implement against the generated XCFramework `RemoteEvent` type:+    //+    // func apply(vaultId: String, envelopes: [RemoteEvent], targetCalendar: EKCalendar) throws:+    //   - map key = recurrenceId.isBlank ? uid : "uid␀recurrenceId"+    //     (matches `CalendarKind.syncId` — keep the separator ␀ U+0000).+    //   - deleted == true -> remove mapped EKEvent; drop the map entry.+    //   - else fetch-or-create EKEvent in targetCalendar; set title/notes/+    //     location/startDate/endDate/isAllDay/timeZone; recurrenceRules from+    //     the RRULE line via RRuleParser (nil line clears rules on masters;+    //     overridden instances keep the master's rules + their RECURRENCE-ID).+    //   - commit once; commit failure = unhealthy write (don't advance cursors).+    //+    // func detectLocalDeletes(knownKeys: Set<String>, targetCalendar: EKCalendar,+    //                        window: (start: Date, end: Date)) throws -> Set<String>:+    //   - HEALTHY predicate fetch in the window first; throw on ANY failure.+    //   - known minus fetched = genuine local deletes -> tombstone envelopes.+    //   - Windowed-fetch caveat: only keys whose events fall inside the window+    //     are eligible for delete detection (older events need a wider fetch —+    //     document the window in E2E_CHECKLIST.md).++    /// Composite sync key (matches `CalendarKind.syncId` exactly).+    static func syncKey(uid: String, recurrenceId: String?) -> String {+        guard let recurrenceId, !recurrenceId.isEmpty else { return uid }+        return "\(uid)\u{0000}\(recurrenceId)"+    }+}
apple/Hub/ContactSink.swift
diff --git a/apple/Hub/ContactSink.swift b/apple/Hub/ContactSink.swiftnew file mode 100644index 0000000000..46290d6372--- /dev/null+++ b/apple/Hub/ContactSink.swift@@ -0,0 +1,101 @@+// EverySync Hub — contacts -> `CNContactStore` sink.+//+// `CNContactStore` + `requestAccess(for: .contacts)`. Maps `RemoteContact`+// name parts / organization / note / typed phones-emails-addresses / birthday+// onto `CNMutableContact`; syncId<->`CNContact.identifier` lives in the hub+// map (`SyncIdMap.swift`) — Swift never scribbles syncIds into user-visible+// contact fields. Delete and conflict semantics follow the XCFramework entity+// kind (`ContactKind`: soft-delete; canonical vCard strips identity/transport+// metadata) — Swift holds no opinion beyond faithfully applying `SyncDriver`+// output.+//+// Type mapping (shared `PhoneKind`/`EmailKind`/`PostalKind` ints from+// `core.format.VCard` — values mirror `ContactsContract`, passed through+// unchanged):+// - Phone: HOME=1 -> home, MOBILE=2 -> mobile, WORK=3 -> work, FAX_HOME=4 /+//   FAX_WORK=5 -> fax, OTHER=7 -> other.+// - Email: HOME=1 -> home, WORK=2 -> work, OTHER=3 -> other.+// - Postal: HOME=1 -> home, WORK=2 -> work, OTHER=3 -> other.+// - Birthday: ISO-8601 `yyyy-MM-dd` <-> `DateComponents(calendar, y/m/d)`.+//   A malformed birthday does NOT fail the contact — the field is skipped and+//   the rest applies (foreign/corrupt tolerance, same as `parseRemote` null).+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `CNContactStore.requestAccess(for:completionHandler:)` deprecation+//   status on the deployment target (iOS 18 `requestAccess(for:)` async+//   variant — confirm on the Mac).+// - `CNSaveRequest` batching + `contactStore.execute(_:)` error mapping to+//   healthy/unhealthy write reporting (a failed save must NOT advance cursors).++import Contacts+import EverysyncCore++/// Applies XCFramework driver output for one vault's contacts.+/// Driver output in, `CNContact` rows out — nothing else.+final class ContactSink {+    private let contactStore: CNContactStore+    private let syncIdMap: SyncIdMap++    init(contactStore: CNContactStore, syncIdMap: SyncIdMap) {+        self.contactStore = contactStore+        self.syncIdMap = syncIdMap+    }++    // TODO(Mac): implement against the generated XCFramework `RemoteContact` /+    // `TypedValue` types:+    //+    // func apply(vaultId: String, envelopes: [RemoteContact]) throws:+    //   - deleted == true -> delete the mapped CNContact (via CNSaveRequest+    //     delete after fetch-by-identifier); drop the syncId from the map.+    //   - else fetch-or-create CNMutableContact; set given/middle/family/+    //     prefix/suffix/organization/note; phones -> CNLabeledValue with+    //     CNLabelPhoneNumber* per the table above; emails/postal likewise;+    //     birthday yyyy-MM-dd -> DateComponents (skip field on parse failure).+    //   - batch in ONE CNSaveRequest; execute once. Failure = unhealthy write.+    //+    // func detectLocalDeletes(knownSyncIds: Set<String>) throws -> Set<String>:+    //   - HEALTHY fetch (keys: identifier only) first; throw on ANY failure+    //     (caller aborts — same healthy-read discipline as listLocalOk).+    //   - known minus fetched = genuine local deletes -> tombstone envelopes.++    /// Phone type int -> Contacts label. Mirrors `VCard` codes.+    static func phoneLabel(for type: Int) -> String {+        switch type {+        case 1: return CNLabelHome+        case 2: return CNLabelPhoneNumberMobile+        case 3: return CNLabelWork+        case 4, 5: return CNLabelPhoneNumberMainFax+        default: return CNLabelOther+        }+    }++    static func emailLabel(for type: Int) -> String {+        switch type {+        case 1: return CNLabelHome+        case 2: return CNLabelWork+        default: return CNLabelOther+        }+    }++    static func postalLabel(for type: Int) -> String {+        switch type {+        case 1: return CNLabelHome+        case 2: return CNLabelWork+        default: return CNLabelOther+        }+    }++    /// ISO-8601 `yyyy-MM-dd` -> DateComponents. Nil on malformed input+    /// (caller skips the field, never fails the contact).+    static func birthdayComponents(from iso: String?) -> DateComponents? {+        guard let iso, !iso.isEmpty else { return nil }+        let parts = iso.split(separator: "-").compactMap { Int($0) }+        guard parts.count == 3 else { return nil }+        var components = DateComponents()+        components.calendar = Calendar(identifier: .gregorian)+        components.year = parts[0]+        components.month = parts[1]+        components.day = parts[2]+        return components+    }+}
apple/Hub/Hub.entitlements.reference
diff --git a/apple/Hub/Hub.entitlements.reference b/apple/Hub/Hub.entitlements.referencenew file mode 100644index 0000000000..39eca35024--- /dev/null+++ b/apple/Hub/Hub.entitlements.reference@@ -0,0 +1,18 @@+<!-- EverySync Hub — entitlements reference (Phase 3, Mac fills values).+     App-Group envelope IPC + shared Keychain group. No autofill entitlement+     (hub has no Credential Provider). -->+<plist version="1.0">+<dict>+    <key>com.apple.security.application-groups</key>+    <array>+        <string>group.&lt;team&gt;.everysync.shared</string>+    </array>+    <key>keychain-access-groups</key>+    <array>+        <string>$(AppIdentifierPrefix)com.vayunmathur.everysync.shared</string>+    </array>+    <!-- Silent-push pull trigger (APNs carries no payload — see BackgroundSync). -->+    <key>aps-environment</key>+    <string>development</string>+</dict>+</plist>
apple/Hub/HubSync.swift
diff --git a/apple/Hub/HubSync.swift b/apple/Hub/HubSync.swiftindex fad2a4f918..959b13eba2 100644--- a/apple/Hub/HubSync.swift+++ b/apple/Hub/HubSync.swift@@ -1,64 +1,112 @@-// EverySync Hub — Phase 3a sync-hub shell.+// EverySync Hub — Phase 3 sync-hub shell. //-// Zero sync logic in Swift. All merge / transport / crypto lives in the-// shared XCFramework (everysync-core KMP). This file only declares the hub-// entry point — SyncDriver scheduling plus EKReminder / CNContact / EKEvent-// sinks — and, in comments, the exact KMP entry points Phase 3 will call.-// Nothing here merges, hashes, or encrypts. There is no Todo UI: tasks-// surface in the system Reminders app.+// ZERO sync logic in Swift. All merge (`TodoKind` / `ContactKind` /+// `CalendarKind`), transport (`IosRelayTransport`), and crypto lives in the+// shared XCFramework. This target:+// - runs `SyncDriver` cycles on a schedule (BGTask — see+//   `../Shared/BackgroundSync.swift`),+// - owns the App-Group envelope store (see `../IPC_CONTRACT.md`),+// - sinks todos / contacts / calendar into the system stores+//   (Reminders via `EKReminder`, Contacts via `CNContactStore`, Calendar via+//   `EKEvent`).+// There is NO Todo UI: tasks surface in the system Reminders app.+//+// Driver output in, system stores out — nothing else.  import EventKit import Contacts+import BackgroundTasks import EverysyncCore -// MARK: - KMP entry points (Phase 3 wiring, for reference only)+// MARK: - KMP entry points (Phase 3 wiring — call, never re-implement) //-// data:        com.vayunmathur.everysync.core.data.RemoteTodo-//              com.vayunmathur.everysync.core.data.RemoteContact-//              com.vayunmathur.everysync.core.data.RemoteEvent-// kinds:       com.vayunmathur.everysync.core.sync.adapters.TodoKind-//              (channel "todos:<vaultId>"; soft-delete; reorder is not an edit)-// driver:      com.vayunmathur.everysync.core.provider.SyncDriver-// cursors:     com.vayunmathur.everysync.core.platform.RelayCursorStore-// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)-// transport:   com.vayunmathur.everysync.core.network.IosRelayTransport-// channels:    recordChannel / membersChannel / keysChannel / ownerChannel-//              / titleChannel / inboxChannel / blobChannel ("notes-blobs:<vaultId>")+// data:        core.data.RemoteTodo (uid / title / notes / done / dueAt epoch+//                ms nullable / position / createdAt / deleted / updatedAt)+//              core.data.RemoteContact (name parts + organization + note ++//                phones/emails/addresses TypedValue(value, type) + ISO-8601+//                birthday + etag/href/deleted/updatedAt)+//              core.data.RemoteEvent (calendarId / summary / description /+//                location / startMillis / endMillis / allDay / timezone /+//                rrule verbatim no-RRULE-prefix / recurrenceId / etag / href /+//                deleted / updatedAt)+// kinds:       core.sync.adapters.TodoKind (syncId=uid, LWW updatedAt,+//                canonical strips identity/position/timestamps — reorder is+//                not an edit; `contentKey = "todo␀" + title + "␀" + createdAt`;+//                soft-delete; `notes`+`createdAt` MUST persist — both are+//                merge-hash inputs, dropping them breaks LWW convergence)+//              core.sync.adapters.ContactKind (syncId=uid; canonical vCard+//                strips identity/transport metadata)+//              core.sync.adapters.CalendarKind (syncId = UID [+ ␀RECURRENCE-ID+//                for overridden instances]; canonical iCal keeps RECURRENCE-ID)+// driver:      core.provider.SyncDriver.drive(kind, store, remote, append, now)+//                — contract: null remote ABORTS (never merges); `remoteOut`+//                appends to the relay BEFORE persisting locally.+// stores:      RelayStore shims over the envelope IPC (see+//              `IPCRelayStore.swift` + `../XCFramework/IOS_ACTUALS_NOTES.md`)+// cursors:     core.platform.RelayCursorStore+// securestore: core.platform.SecureStore (Keychain actual)+// transport:   core.network.IosRelayTransport+// channels:    recordChannel / membersChannel / keysChannel / ownerChannel /+//              titleChannel / inboxChannel / blobChannel (`notes-blobs:<vault>`) // roles:       RelayRoles — passwords offer EDITOR only, never VIEWER // links:       RelayLinks.parseJoinLink / .shareLinkFor-// pqc:         10 fns per IOS_PQC_NOTES.md (e2eePqc cinterop)+// pqc:         exactly 10 fns per IOS_PQC_NOTES.md (e2eePqc cinterop) -/// Sync hub: runs XCFramework SyncDriver cycles, owns the App-Group envelope-/// store (see ../IPC_CONTRACT.md), and sinks todos/contacts/calendar into-/// the system stores. Scheduling + mapping only.+/// Sync hub: runs XCFramework `SyncDriver` cycles, owns the App-Group envelope+/// store, and sinks todos/contacts/calendar into the system stores.+/// Scheduling + mapping only. final class HubSync {     let eventStore = EKEventStore()     let contactStore = CNContactStore()+    private let ipc = EnvelopeIPC()+    private let syncIdMap = SyncIdMap() -    // TODO(Phase 3): create SyncDriver + IosRelayTransport from the-    //  XCFramework; open the App-Group envelope store; register-    //  BGTaskScheduler handlers (see README.md).+    init() {+        // MAC-CHECK: identifiers must match Info.plist+        // `BGTaskSchedulerPermittedIdentifiers`.+        BackgroundSync.register(handlers: [+            "com.vayunmathur.everysync.hub.refresh": { task in+                // TODO(Mac): run SyncDriver cycles for every vault (todos ++                // contacts + calendar + hub-side passwords/notes relay ops),+                // then re-schedule + `task.setTaskCompleted(success:)`.+                task.setTaskCompleted(success: true)+            },+            "com.vayunmathur.everysync.hub.upload": { task in+                // TODO(Mac): one-shot after local system-store changes+                // (EKEventStore notifications); push deltas, then complete.+                task.setTaskCompleted(success: true)+            },+        ])+    } +    /// Requests Reminders / Calendar / Contacts access, then starts cycles.+    /// Each grant is independent: a denied store only disables its sink —+    /// the hub still syncs the other types (never abort everything on one+    /// denial; each sink tracks its own `listLocalOk`-equivalent health).     func requestSystemAccess() {-        // TODO(Phase 3): eventStore.requestAccess(to: .reminder),-        //  eventStore.requestAccess(to: .event),-        //  contactStore.requestAccess(for: .contacts),-        //  then start SyncDriver cycles.+        // TODO(Mac): `eventStore.requestAccess(to: .reminder)`,+        // `eventStore.requestAccess(to: .event)` (iOS 17+: `requestFullAccess-`+        // variant — confirm on the Mac), `contactStore.requestAccess(for:+        // .contacts)`, then start SyncDriver cycles per granted store.     } +    /// Drives one todos cycle for a vault: pull `todos:<vaultId>` via the+    /// XCFramework, apply through `TodoReminderSink`, persist known syncIds.+    /// See `TodoReminderSink.swift` for the field + tombstone mapping.     func syncTodosToReminders(vaultId: String) {-        // TODO(Phase 3): pull "todos:<vaultId>" via SyncDriver; upsert-        //  EKReminder per the README mapping table; persist known syncIds so-        //  a vanished EKReminder folds back as a tombstone envelope.+        // TODO(Mac): call into the XCFramework SyncDriver with the+        // `IPCRelayStore<RemoteTodo>` shim + `TodoReminderSink` application.     } +    /// Drives one contacts cycle for a vault. SyncId<->identifier map stays+    /// hub-local (see `SyncIdMap.swift`); Swift never scribbles syncIds into+    /// user-visible contact fields.     func syncContacts(vaultId: String) {-        // TODO(Phase 3): apply SyncDriver contact output to CNContactStore;-        //  keep the syncId<->identifier map hub-local.+        // TODO(Mac): SyncDriver cycle with the contacts IPC shim + ContactSink.     } +    /// Drives one calendar cycle for a vault into the hub-managed calendar.     func syncCalendarEvents(vaultId: String) {-        // TODO(Phase 3): apply SyncDriver event output to EKEventStore in the-        //  hub-managed calendar.+        // TODO(Mac): SyncDriver cycle with the calendar IPC shim + CalendarSink.     } }
apple/Hub/IPCRelayStore.swift
diff --git a/apple/Hub/IPCRelayStore.swift b/apple/Hub/IPCRelayStore.swiftnew file mode 100644index 0000000000..2269c88da9--- /dev/null+++ b/apple/Hub/IPCRelayStore.swift@@ -0,0 +1,74 @@+// EverySync Hub — `RelayStore` shim over the envelope IPC.+//+// The XCFramework's `SyncDriver.drive(kind, store, remote, append, now)`+// needs a `RelayStore<T>` (`listLocal / upsertLocal / deleteLocal /+// loadBaseline / saveSnapshots / removeSnapshots / listLocalOk / parseRemote /+// serializeForRemote`). On Apple the envelopes live in the App-Group SQLite+// IPC store (shared with the Passwords/Notes shells), so this file documents+// the exact adapter the Mac wires in Kotlin (see+// `../XCFramework/IOS_ACTUALS_NOTES.md` for the Kotlin owner):+//+// - `listLocal(vaultId)` = `EnvelopeIPC.querySince(vaultId, table, since: -1)`+//   mapped through `*Kind.fromJson(payloadJson)`. ANY throw (SQLite error,+//   coordination failure) = unhealthy read: the shim reports+//   `listLocalOk == false` (or throws `LocalReadException`) so the driver+//   ABORTS — never folds failure as empty (invariant 1+2, verbatim).+//   Precedence: the ROW's `deleted` column wins over a stale `payloadJson`+//   flag. A shell-side delete (`deleteByVault`) tombstones the row and stamps+//   `updatedAt` but leaves the old payload bytes in place until the merge+//   writes the tombstone envelope — so the shim MUST treat+//   `row.deleted == true` as deleted regardless of what the payload says.+//   (Same reason `querySince` includes tombstones: absence without a+//   tombstone resurrects — never deletes.)+// - `parseRemote` = `*Kind.fromJson`; null skips a foreign/corrupt entry.+// - `serializeForRemote` = `*Kind.toJson` (decrypted form — encryption+//   happens in the transport's `appendRecords`, never here).+// - `upsertLocal`/`deleteLocal` = `upsertRaw` / per-table delete semantics+//   (passwords hard-delete, everything else tombstones — Swift holds no+//   opinion beyond applying driver output).+// - Baselines (`RelaySnapshot`: syncId/kind/contentHash/localUpdatedAt/+//   remoteModified/lastSyncedAt/deleted) persist in a hub-side sidecar+//   SQLite table (NOT in the IPC tables — the IPC columns are exactly the+//   five `SyncSink` columns, no more).+//+// Swift never implements this interface directly (generics over Kotlin types+// cross the boundary poorly); the live shim is Kotlin. This file exists so+// the mapping is specified once, in the repo, next to the sinks.++import Foundation+import EverysyncCore++/// Which IPC table backs each vault type in the shim.+public enum RelayStoreTables {+    /// `passwords:<vault>` <-> `passwords` table (HARD delete).+    public static let passwords = EnvelopeTable.passwords+    /// `notes:<vault>` <-> `notes` table (SOFT delete).+    public static let notes = EnvelopeTable.notes+    /// `todos:<vault>` <-> `todos` table (SOFT delete).+    /// `notes` + `createdAt` MUST be persisted (envelope + hash inputs).+    public static let todos = EnvelopeTable.todos+    /// Hub-internal contacts/calendar rows: same five columns; delete+    /// semantics per the XCFramework entity kind (Swift holds no opinion).+    public static let contacts = EnvelopeTable.contacts+    public static let calendars = EnvelopeTable.calendars+}++/// Baseline sidecar: `RelaySnapshot` rows persisted per (vault, kind).+/// Schema (hub-local SQLite, NOT the IPC store):+/// `baselines(syncId TEXT, kind TEXT, contentHash TEXT, localUpdatedAt+/// INTEGER, remoteModified INTEGER, lastSyncedAt INTEGER, deleted INTEGER,+/// PRIMARY KEY (syncId, kind))`.+public enum BaselineSidecar {+    public static let tableDDL = """+        CREATE TABLE IF NOT EXISTS baselines (+          syncId TEXT NOT NULL,+          kind TEXT NOT NULL,+          contentHash TEXT NOT NULL,+          localUpdatedAt INTEGER NOT NULL,+          remoteModified INTEGER NOT NULL,+          lastSyncedAt INTEGER NOT NULL,+          deleted INTEGER NOT NULL DEFAULT 0,+          PRIMARY KEY (syncId, kind)+        );+        """+}
apple/Hub/Info.plist.reference
diff --git a/apple/Hub/Info.plist.reference b/apple/Hub/Info.plist.referencenew file mode 100644index 0000000000..3ca7daab35--- /dev/null+++ b/apple/Hub/Info.plist.reference@@ -0,0 +1,42 @@+<!-- EverySync Hub — Info.plist reference (Phase 3, Mac fills values). -->+<plist version="1.0">+<dict>+    <!-- System-sink usage strings (one per store the hub writes). -->+    <key>NSRemindersUsageDescription</key>+    <string>EverySync syncs shared task lists into Reminders.</string>+    <key>NSCalendarsUsageDescription</key>+    <string>EverySync syncs shared calendars into Calendar.</string>+    <key>NSContactsUsageDescription</key>+    <string>EverySync syncs shared contacts into Contacts.</string>+    <key>NSFaceIDUsageDescription</key>+    <string>EverySync uses Face ID to unlock vault keys in Keychain.</string>++    <key>BGTaskSchedulerPermittedIdentifiers</key>+    <array>+        <string>com.vayunmathur.everysync.hub.refresh</string>+        <string>com.vayunmathur.everysync.hub.upload</string>+    </array>+    <key>UIBackgroundModes</key>+    <array>+        <string>fetch</string>+        <string>processing</string>+        <!-- APNs pull-trigger only, never payload (see ../Shared/BackgroundSync.swift).+             `remote-notification` mode is declared here so a silent push can wake+             the hub to PULL the relay; no vault data rides the push itself. -->+        <string>remote-notification</string>+    </array>++    <!-- Join-link handling: everysync://join/<vault>?owner=...&type=... -->+    <key>CFBundleURLTypes</key>+    <array>+        <dict>+            <key>CFBundleURLName</key>+            <string>com.vayunmathur.everysync.join</string>+            <key>CFBundleURLSchemes</key>+            <array>+                <string>everysync</string>+            </array>+        </dict>+    </array>+</dict>+</plist>
apple/Hub/README.md
diff --git a/apple/Hub/README.md b/apple/Hub/README.mdindex cec160fae9..32fdab3543 100644--- a/apple/Hub/README.md+++ b/apple/Hub/README.md@@ -102,3 +102,21 @@ Scheduling only — cycles run in the XCFramework. Run merge/LWW, compute content hashes, encrypt envelopes, parse join links, check roles, or re-implement TOTP/block parsing. Driver output in, system stores out — nothing else.++## Files (Phase 3)++| File | Role |+|---|---|+| `HubSync.swift` | Hub entry: BGTask registration + per-vault cycle fan-out; no Todo UI |+| `IPCRelayStore.swift` | `RelayStore` shim spec over the envelope IPC + baseline sidecar schema |+| `TodoReminderSink.swift` | `RemoteTodo` -> `EKReminder` mapping + healthy-read tombstone detection |+| `ContactSink.swift` | `RemoteContact` -> `CNContactStore` + shared type-int label tables |+| `CalendarSink.swift` | `RemoteEvent` -> `EKEvent` + composite `uid␀recurrenceId` sync keys |+| `SyncIdMap.swift` | Hub-local syncId<->system-identifier map + known-set (tombstone detection) |+| `Info.plist.reference` | Reminders/Calendars/Contacts/FaceID strings, BGTask ids, `remote-notification` (pull trigger only), `everysync://join` scheme |+| `Hub.entitlements.reference` | App Group + shared Keychain group + `aps-environment` |+| `../Shared/EnvelopeIPC.swift` | SQLite IPC store (owned by the hub, read by shells) |+| `../Shared/BlobStore.swift` | Blob sidecar (shared) |+| `../Shared/KeychainSecureStore.swift` | Keychain layout contract (Kotlin implements) |+| `../Shared/EverysyncCoreCrypto.swift` | CryptoKit AES-GCM C bridge |+| `../Shared/BackgroundSync.swift` | BGTask registration helpers |
apple/Hub/SyncIdMap.swift
diff --git a/apple/Hub/SyncIdMap.swift b/apple/Hub/SyncIdMap.swiftnew file mode 100644index 0000000000..99265dea87--- /dev/null+++ b/apple/Hub/SyncIdMap.swift@@ -0,0 +1,159 @@+// EverySync Hub — syncId <-> system-identifier map (hub-local state).+//+// System stores (`EKReminder`, `CNContact`, `EKEvent`) own their identifiers+// (`calendarItemIdentifier`, `CNContact.identifier`, `eventIdentifier`), and+// those identifiers are NOT stable across devices, restores, or (for+// reminders) list moves. The relay sync identity (`uid`) is the stable key.+// This map bridges them — hub-local ONLY, never an IPC column, never+// user-visible, never synced.+//+// Also persists the KNOWN-syncId set per vault that tombstone detection needs+// (`TodoReminderSink` / `ContactSink` / `CalendarSink` detectLocalDeletes):+// after a HEALTHY fetch, known-minus-fetched = genuine local deletes.+//+// Storage: hub-local SQLite (`hub-syncids.sqlite` in the hub's Application+// Support dir — NOT the App-Group container; shells never need it).+// Schema v1:+//   `syncids(vault TEXT, kind TEXT, syncId TEXT, systemId TEXT,+//            PRIMARY KEY (vault, kind, syncId))`+//   `known(vault TEXT, kind TEXT, syncId TEXT,+//          PRIMARY KEY (vault, kind, syncId))`+// `kind` is one of `todo` / `contact` / `event` (matches `TodoKind` /+// `ContactKind` / `CalendarKind` `.kind`).++import Foundation+import SQLite3++public enum SyncIdMapError: Error {+    case supportDirUnavailable+    case sqlite(String)+}++public final class SyncIdMap {+    private let fileManager = FileManager.default+    private let queue = DispatchQueue(label: "com.vayunmathur.everysync.syncid-map")++    public init() {}++    // MARK: - Ops++    /// Records the system identifier for a syncId (upsert).+    public func setSystemId(vaultId: String, kind: String, syncId: String, systemId: String) throws {+        try queue.sync {+            try withDatabase { db in+                try exec(db: db, sql: """+                    INSERT INTO syncids(vault, kind, syncId, systemId)+                    VALUES (?, ?, ?, ?)+                    ON CONFLICT(vault, kind, syncId) DO UPDATE SET systemId = excluded.systemId;+                    """, bind: [vaultId, kind, syncId, systemId])+                try exec(db: db, sql: """+                    INSERT INTO known(vault, kind, syncId) VALUES (?, ?, ?)+                    ON CONFLICT(vault, kind, syncId) DO NOTHING;+                    """, bind: [vaultId, kind, syncId])+            }+        }+    }++    /// Looks up the system identifier for a syncId; nil when unknown.+    public func systemId(vaultId: String, kind: String, syncId: String) throws -> String? {+        try queue.sync {+            try withDatabase { db in+                var stmt: OpaquePointer?+                guard sqlite3_prepare_v2(db, "SELECT systemId FROM syncids WHERE vault = ? AND kind = ? AND syncId = ?;", -1, &stmt, nil) == SQLITE_OK, let stmt else {+                    throw SyncIdMapError.sqlite("prepare failed")+                }+                defer { sqlite3_finalize(stmt) }+                sqlite3_bind_text(stmt, 1, vaultId, -1, SQLITE_TRANSIENT_MAP)+                sqlite3_bind_text(stmt, 2, kind, -1, SQLITE_TRANSIENT_MAP)+                sqlite3_bind_text(stmt, 3, syncId, -1, SQLITE_TRANSIENT_MAP)+                guard sqlite3_step(stmt) == SQLITE_ROW,+                      let c = sqlite3_column_text(stmt, 0) else { return nil }+                return String(cString: c)+            }+        }+    }++    /// All known syncIds for a vault+kind (tombstone detection baseline).+    public func knownSyncIds(vaultId: String, kind: String) throws -> Set<String> {+        try queue.sync {+            try withDatabase { db in+                var stmt: OpaquePointer?+                guard sqlite3_prepare_v2(db, "SELECT syncId FROM known WHERE vault = ? AND kind = ?;", -1, &stmt, nil) == SQLITE_OK, let stmt else {+                    throw SyncIdMapError.sqlite("prepare failed")+                }+                defer { sqlite3_finalize(stmt) }+                sqlite3_bind_text(stmt, 1, vaultId, -1, SQLITE_TRANSIENT_MAP)+                sqlite3_bind_text(stmt, 2, kind, -1, SQLITE_TRANSIENT_MAP)+                var out = Set<String>()+                while sqlite3_step(stmt) == SQLITE_ROW {+                    if let c = sqlite3_column_text(stmt, 0) { out.insert(String(cString: c)) }+                }+                return out+            }+        }+    }++    /// Drops a syncId from both tables (tombstone acknowledged / purged).+    public func forget(vaultId: String, kind: String, syncId: String) throws {+        try queue.sync {+            try withDatabase { db in+                try exec(db: db, sql: "DELETE FROM syncids WHERE vault = ? AND kind = ? AND syncId = ?;", bind: [vaultId, kind, syncId])+                try exec(db: db, sql: "DELETE FROM known WHERE vault = ? AND kind = ? AND syncId = ?;", bind: [vaultId, kind, syncId])+            }+        }+    }++    // MARK: - SQLite++    private func databaseURL() throws -> URL {+        let base = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first+        guard let base else { throw SyncIdMapError.supportDirUnavailable }+        let dir = base.appendingPathComponent("com.vayunmathur.everysync.hub", isDirectory: true)+        try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)+        return dir.appendingPathComponent("hub-syncids.sqlite")+    }++    private func withDatabase<T>(_ body: (OpaquePointer) throws -> T) throws -> T {+        var db: OpaquePointer?+        guard sqlite3_open_v2(try databaseURL().path, &db, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK, let db else {+            throw SyncIdMapError.sqlite("open failed")+        }+        defer { sqlite3_close(db) }+        // `journal_mode` returns a row — step it query-style, not via exec().+        var pragma: OpaquePointer?+        guard sqlite3_prepare_v2(db, "PRAGMA journal_mode=WAL;", -1, &pragma, nil) == SQLITE_OK, let pragma else {+            throw SyncIdMapError.sqlite("pragma failed")+        }+        defer { sqlite3_finalize(pragma) }+        while sqlite3_step(pragma) == SQLITE_ROW {}+        try exec(db: db, sql: """+            CREATE TABLE IF NOT EXISTS syncids(+              vault TEXT NOT NULL, kind TEXT NOT NULL, syncId TEXT NOT NULL,+              systemId TEXT NOT NULL, PRIMARY KEY (vault, kind, syncId));+            """, bind: [])+        try exec(db: db, sql: """+            CREATE TABLE IF NOT EXISTS known(+              vault TEXT NOT NULL, kind TEXT NOT NULL, syncId TEXT NOT NULL,+              PRIMARY KEY (vault, kind, syncId));+            """, bind: [])+        return try body(db)+    }++    @discardableResult+    private func exec(db: OpaquePointer, sql: String, bind: [String]) throws -> Int {+        var stmt: OpaquePointer?+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw SyncIdMapError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        for (i, value) in bind.enumerated() {+            sqlite3_bind_text(stmt, Int32(i + 1), value, -1, SQLITE_TRANSIENT_MAP)+        }+        guard sqlite3_step(stmt) == SQLITE_DONE else {+            throw SyncIdMapError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        return Int(sqlite3_changes(db))+    }+}++private let SQLITE_TRANSIENT_MAP = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
apple/Hub/TodoReminderSink.swift
diff --git a/apple/Hub/TodoReminderSink.swift b/apple/Hub/TodoReminderSink.swiftnew file mode 100644index 0000000000..5f4cf40b2d--- /dev/null+++ b/apple/Hub/TodoReminderSink.swift@@ -0,0 +1,86 @@+// EverySync Hub — todos -> Reminders sink (no Todo app).+//+// `EKEventStore` + `requestAccess(to: .reminder)`; synced tasks live in a+// dedicated hub-managed `EKCalendar` (or the default list) and appear in the+// system Reminders app. Field mapping (verbatim from `Hub/README.md`):+//+// | `RemoteTodo`            | `EKReminder`                          |+// | `uid`                   | `calendarItemIdentifier` via the hub's syncId<->identifier map (identifiers are hub-local state, NOT IPC columns) |+// | `title`                 | `title`                               |+// | `notes`                 | `notes` (MUST persist — merge-hash input) |+// | `done`                  | `completed` (+ `completionDate`)      |+// | `dueAt` (epoch ms, nullable) | `dueDateComponents` (via `Calendar`; nil clears) |+// | `position`              | not mapped — sort client-side (excluded from the merge hash, so reorder is never an edit) |+// | `createdAt`             | read-only reference (part of the adoption content key; never written back) |+// | `deleted=true` envelope | remove the `EKReminder`               |+//+// Tombstone mapping: `EKReminder` has no tombstone — a user-deleted reminder+// simply vanishes from the store. The hub therefore persists the set of known+// syncIds per vault (`SyncIdMap.swift`); after a HEALTHY fetch, any known+// syncId with no matching `EKReminder` is a genuine local delete and folds+// into the next merge as a tombstone envelope. Merge-driven deletes always+// arrive as tombstone envelopes, never raw deletes. Same healthy-read+// discipline as `SyncSink.listLocalOk`: an unhealthy fetch aborts the cycle+// instead of reading absence as deletion.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `EKEventStore(requestAccessToEntityType:completion:)` vs iOS 17++//   `requestFullAccessToReminders` — confirm the right call per deployment target.+// - `EKReminder` due-date bridging (`dueDateComponents` <-> epoch ms) with+//   explicit `Calendar(identifier: .gregorian)` + UTC to avoid DST drift.++import EventKit+import EverysyncCore++/// Applies XCFramework driver output for one vault's todos to Reminders.+/// Driver output in, `EKReminder` rows out — no merge/hash/crypto here.+final class TodoReminderSink {+    private let eventStore: EKEventStore+    private let syncIdMap: SyncIdMap+    private let calendar = Calendar(identifier: .gregorian)++    init(eventStore: EKEventStore, syncIdMap: SyncIdMap) {+        self.eventStore = eventStore+        self.syncIdMap = syncIdMap+    }++    // TODO(Mac): implement against the generated XCFramework `RemoteTodo` type:+    //+    // func apply(vaultId: String, envelopes: [RemoteTodo], targetCalendar: EKCalendar) throws:+    //   - for each envelope with deleted == true: look up the EKReminder via+    //     syncIdMap; `eventStore.remove(reminder, commit: false)`; drop the+    //     syncId from the known set (tombstone acknowledged).+    //   - else: fetch-or-create EKReminder in targetCalendar; set+    //     title/notes/completed+completionDate/dueDateComponents+    //     (dueAt ms -> DateComponents via `calendar.dateComponents(from: Date(...))`;+    //     nil clears); `position` ignored; `createdAt` never written back.+    //     Record syncId -> calendarItemIdentifier in syncIdMap.+    //   - commit once at the end (`eventStore.commit()`); a commit failure =+    //     unhealthy write — report up so the cycle does NOT advance cursors.+    //+    // func detectLocalDeletes(vaultId: String, targetCalendar: EKCalendar,+    //                        knownSyncIds: Set<String>) throws -> Set<String>:+    //   - HEALTHY fetch of reminders in targetCalendar first; on ANY fetch+    //     failure THROW (caller aborts — never read absence as deletion).+    //   - return knownSyncIds minus fetched identifiers: genuine local+    //     deletes, which the driver folds into tombstone envelopes.+    //   - `notes` + `createdAt` are never compared here (they ride the+    //     envelope); only presence/absence after a healthy read matters.++    /// Epoch-ms <-> DateComponents conversion. UTC Gregorian; nil clears.+    func dueDateComponents(fromDueAt dueAt: Int64?) -> DateComponents? {+        guard let dueAt else { return nil }+        var utc = calendar+        utc.timeZone = TimeZone(identifier: "UTC") ?? .current+        return utc.dateComponents(+            [.year, .month, .day, .hour, .minute, .second],+            from: Date(timeIntervalSince1970: TimeInterval(dueAt) / 1000.0)+        )+    }++    func dueAt(from components: DateComponents?) -> Int64? {+        guard let components,+              let date = calendar.date(from: components) else { return nil }+        return Int64((date.timeIntervalSince1970 * 1000.0).rounded())+    }+}
apple/IPC_CONTRACT.md
diff --git a/apple/IPC_CONTRACT.md b/apple/IPC_CONTRACT.mdindex 201a17a8c3..7c0c4802e3 100644--- a/apple/IPC_CONTRACT.md+++ b/apple/IPC_CONTRACT.md@@ -49,6 +49,29 @@ envelopes here; the Credential Provider extension reads over XPC. Contacts/calendar rows are hub-internal (system stores are the UI); shells for those types do not exist in Phase 3a. +## Appendix — Phase 3 conformance (no drift)++Reviewed against the Phase 3 Swift (`Shared/EnvelopeIPC.swift`,+`Shared/BlobStore.swift`, `Passwords/PasswordsXPCService.swift`,+`Hub/IPCRelayStore.swift`, `Hub/SyncIdMap.swift`) — contract holds verbatim:++- 3 ops (`querySince` / `upsertRaw` / `deleteByVault`) with identical+  columns (`syncId / updatedAt / deleted / payloadJson / contentHash`).+- 5 tables (`passwords` HARD / `notes`, `todos` SOFT / hub-internal+  `contacts`, `calendars` with kind-driven delete semantics).+- App-Group container + `NSFileCoordinator` + XPC (exactly the 3 ops;+  extension never touches the relay); `blobs/` sidecar keyed by `fileName`.+- Cursor keys in Keychain `SecureStore`, never in these tables; vault keys+  never appear here or in share links.+- WAL + `busy_timeout=5000` so the Kotlin `RelayStore` shims (specified in+  `Hub/IPCRelayStore.swift`, owned by `XCFramework/IOS_ACTUALS_NOTES.md`)+  share the same files; schema v1.++Build-note drift (NOT contract drift): `XCFramework/BUILD_NOTES.md` uses the+`aarch64-apple-ios-sim` Rust target for Apple-Silicon simulators where+`library/everysync-core/IOS_PQC_NOTES.md` says `x86_64-apple-ios`+(Intel-only). Relay/channel/table semantics are unaffected.+ ## Concurrency rules  1. Single writer to the relay: the hub. Shells only touch the IPC store.
apple/Notes/Info.plist.reference
diff --git a/apple/Notes/Info.plist.reference b/apple/Notes/Info.plist.referencenew file mode 100644index 0000000000..c67d7db2fc--- /dev/null+++ b/apple/Notes/Info.plist.reference@@ -0,0 +1,30 @@+<!-- EverySync Notes — Info.plist reference (Phase 3, Mac fills values).+     No camera/photo-library keys: image blocks reference shared-store files;+     capture UI adds its own usage strings later. -->+<plist version="1.0">+<dict>+    <!-- App-Group envelope IPC + blob store is via entitlements, not plist. -->+    <key>BGTaskSchedulerPermittedIdentifiers</key>+    <array>+        <string>com.vayunmathur.everysync.notes.refresh</string>+    </array>+    <key>UIBackgroundModes</key>+    <array>+        <string>fetch</string>+        <string>processing</string>+    </array>++    <!-- Join-link handling: everysync://join/<vault>?owner=...&type=... -->+    <key>CFBundleURLTypes</key>+    <array>+        <dict>+            <key>CFBundleURLName</key>+            <string>com.vayunmathur.everysync.join</string>+            <key>CFBundleURLSchemes</key>+            <array>+                <string>everysync</string>+            </array>+        </dict>+    </array>+</dict>+</plist>
apple/Notes/NoteBodyView.swift
diff --git a/apple/Notes/NoteBodyView.swift b/apple/Notes/NoteBodyView.swiftnew file mode 100644index 0000000000..03ef71e4c6--- /dev/null+++ b/apple/Notes/NoteBodyView.swift@@ -0,0 +1,59 @@+// EverySync Notes — native NoteBody rendering.+//+// Renders the XCFramework's `NoteBody` blocks natively (text/markdown,+// blob-channel images by `fileName`, PencilKit ink). This file does NO+// parsing/serialization/hashing/merging: it takes an already-parsed `NoteBody`+// from the XCFramework (`parseNoteBody`) and binds edits back through+// `serializeNoteBody`. Swift never defines its own block schema.+//+// Wire shape (mirrored verbatim — do not extend in Swift):+//   {"blocks":[+//     {"type":"text","id":"…","markdown":"…"},+//     {"type":"image","id":"…","fileName":"<sha256>.jpg","widthFraction":1.0},+//     {"type":"ink","id":"…","strokes":[],"heightDp":300}]}+// `InkStroke`: `brushFamily` (default `"pressurePen"`), `brushSize`,+// `brushColor` (argb int), `brushEpsilon` (default `0.1`), `points`.+// `InkPoint`: `x, y, timeMillis, pressure, tiltRadians, orientationRadians`.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `EverysyncCore` Kotlin class names below are the K/N export shape+//   (`NoteBody` / `NoteBlock.Text` / `.Image` / `.Ink`). The Mac must confirm+//   the exact names in the generated `EverysyncCore.h` and adjust call sites.++import SwiftUI+import EverysyncCore++/// Renders one note's blocks. The view model holds the XCFramework `NoteBody`+/// object; every edit (text change, image resize, new strokes) writes through+/// `serializeNoteBody` into the envelope IPC. Tombstoned notes (`deleted`)+/// render a "deleted" placeholder — Swift never raw-deletes.+struct NoteBodyView: View {+    // TODO(Mac): bind to the XCFramework NoteBody object.+    // Cases (from `NoteBlock` — exhaustive over Text/Image/Ink):+    // - Text: native TextEditor bound to `markdown`. Markdown rendering is+    //   display-only; the stored string stays verbatim (merge hashes it).+    // - Image: `fileName` resolved via BlobStore (see+    //   ../Shared/BlobStore.swift); prefetch the vault's set via+    //   `NoteKind.imageNames(blocksJson)`. `widthFraction` scales the image+    //   to that fraction of the editor width. Missing blob = placeholder+    //   (the hub is still fetching from `notes-blobs:<vaultId>`).+    // - Ink: PencilKit canvas (`PKCanvasView` wrapped in UIViewRepresentable)+    //   with `heightDp` height (default 300); strokes mapped via+    //   `PencilKitMapping.swift`. Canvas edits append/replace strokes in the+    //   XCFramework object — serialization stays in `serializeNoteBody`.+    var body: some View {+        Text("Note body renders here (Mac wires the XCFramework NoteBody)")+    }+}++/// Converts a `UIColor` to the shared-model argb int (`InkStroke.brushColor`).+/// Display helper only — the mapping itself lives in `PencilKitMapping.swift`.+enum InkColorHelp {+    static func argbInt(red: Double, green: Double, blue: Double, alpha: Double = 1.0) -> Int32 {+        let a = Int32((alpha * 255).rounded()) & 0xFF+        let r = Int32((red * 255).rounded()) & 0xFF+        let g = Int32((green * 255).rounded()) & 0xFF+        let b = Int32((blue * 255).rounded()) & 0xFF+        return (a << 24) | (r << 16) | (g << 8) | b+    }+}
apple/Notes/Notes.entitlements.reference
diff --git a/apple/Notes/Notes.entitlements.reference b/apple/Notes/Notes.entitlements.referencenew file mode 100644index 0000000000..b7cbafa990--- /dev/null+++ b/apple/Notes/Notes.entitlements.reference@@ -0,0 +1,14 @@+<!-- EverySync Notes — entitlements reference (Phase 3, Mac fills values).+     App-Group envelope IPC + blob store, shared with the Share extension. -->+<plist version="1.0">+<dict>+    <key>com.apple.security.application-groups</key>+    <array>+        <string>group.&lt;team&gt;.everysync.shared</string>+    </array>+    <key>keychain-access-groups</key>+    <array>+        <string>$(AppIdentifierPrefix)com.vayunmathur.everysync.shared</string>+    </array>+</dict>+</plist>
apple/Notes/NotesApp.swift
diff --git a/apple/Notes/NotesApp.swift b/apple/Notes/NotesApp.swiftindex 69db8ee2e0..cd5413ddc1 100644--- a/apple/Notes/NotesApp.swift+++ b/apple/Notes/NotesApp.swift@@ -1,36 +1,62 @@-// EverySync Notes — Phase 3a SwiftUI shell.+// EverySync Notes — Phase 3 SwiftUI shell. //-// Zero sync logic in Swift. All blocks parsing, merge, transport, and crypto-// lives in the shared XCFramework (everysync-core KMP). This file only-// declares the UI entry point and — in comments — the exact KMP entry points-// Phase 3 will call, plus the PencilKit mapping contract (see README.md).-// Nothing here parses JSON, merges, hashes, or encrypts.+// ZERO sync logic in Swift. All blocks parsing (`parseNoteBody` /+// `serializeNoteBody` / `noteBodyText`), merge (`NoteKind`), transport+// (`IosRelayTransport`), and crypto lives in the shared XCFramework. This+// target renders the editor, maps PencilKit strokes to the shared ink model+// (see `PencilKitMapping.swift`), renders blocks natively (see+// `NoteBodyView.swift`), hosts the Share extension (see+// `ShareExtension.swift`), and schedules background sync. Notes soft-delete:+// tombstone rows persist locally and propagate+// (`NoteKind.localDeletesAreAuthoritative == true`).  import SwiftUI-import PencilKit+import BackgroundTasks import EverysyncCore -// MARK: - KMP entry points (Phase 3 wiring, for reference only)+// MARK: - KMP entry points (Phase 3 wiring — call, never re-implement) //-// data:        com.vayunmathur.everysync.core.data.RemoteNote-// blocks:      com.vayunmathur.everysync.core.notes.parseNoteBody-//              com.vayunmathur.everysync.core.notes.serializeNoteBody-//              com.vayunmathur.everysync.core.notes.noteBodyText-//              com.vayunmathur.everysync.core.notes.NoteBlock-//              com.vayunmathur.everysync.core.notes.InkStroke-//              com.vayunmathur.everysync.core.notes.InkPoint-// kind:        com.vayunmathur.everysync.core.sync.adapters.NoteKind-// blobs:       NoteKind.imageNames(blocksJson); channel "notes-blobs:<vaultId>"-// driver:      com.vayunmathur.everysync.core.provider.SyncDriver-// cursors:     com.vayunmathur.everysync.core.platform.RelayCursorStore-// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)-// transport:   com.vayunmathur.everysync.core.network.IosRelayTransport-// channels:    recordChannel("notes", vaultId) -> "notes:<vaultId>"+// data:        core.data.RemoteNote (uid / title / content / blocksJson /+//              position / deleted / updatedAt)+// blocks:      core.notes.parseNoteBody(blocksJson, fallbackContent)+//              core.notes.serializeNoteBody(body)+//              core.notes.noteBodyText(body) — plain-text projection for+//                search / preview / share. `ignoreUnknownKeys` keeps legacy+//                notes parsing.+//              core.notes.NoteBlock.Text(markdown, id) / .Image(fileName,+//                widthFraction, id) / .Ink(strokes, heightDp, id)+//              core.notes.InkStroke(brushFamily="pressurePen", brushSize,+//                brushColor argb int, brushEpsilon=0.1, points)+//              core.notes.InkPoint(x, y, timeMillis, pressure, tiltRadians,+//                orientationRadians)+// kind:        core.sync.adapters.NoteKind (syncId=uid, LWW updatedAt, hash+//              over canonical JSON with identity/position/timestamps stripped+//              — reorder is not an edit; `imageNames(blocksJson)` for blob+//              prefetch)+// blobs:       channel `notes-blobs:<vaultId>` for image bytes (never inline+//              in envelopes); sidecar via `../Shared/BlobStore.swift`+// driver:      core.provider.SyncDriver.drive(kind, store, remote, append, now)+// cursors:     core.platform.RelayCursorStore+// securestore: core.platform.SecureStore (Keychain actual)+// transport:   core.network.IosRelayTransport+//              (`recordChannel("notes", vaultId)` -> `notes:<vaultId>`)+// pqc/roles/links: same surface as Passwords; notes vaults may offer EDITOR+//              or VIEWER (unlike passwords — see `RelayRoles`).  @main struct NotesApp: App {-    // TODO(Phase 3): create SyncDriver + IosRelayTransport from the-    //  XCFramework; register BGTaskScheduler handlers (see README.md).+    init() {+        // MAC-CHECK: identifier must match Info.plist+        // `BGTaskSchedulerPermittedIdentifiers`.+        BackgroundSync.register(handlers: [+            "com.vayunmathur.everysync.notes.refresh": { task in+                // TODO(Mac): call XCFramework SyncDriver cycle for each vault,+                // then re-schedule + `task.setTaskCompleted(success:)`.+                task.setTaskCompleted(success: true)+            },+        ])+    }+     var body: some Scene {         WindowGroup {             NotesRootView()@@ -39,10 +65,20 @@ struct NotesApp: App { }  struct NotesRootView: View {-    // TODO(Phase 3): note list driven by SyncDriver snapshots; editor binds-    //  PKCanvasView and maps PKStroke -> InkStroke per README mapping table,-    //  then serializes via serializeNoteBody in the XCFramework.+    // TODO(Mac): note list driven by SyncDriver snapshots; preview text via+    // `noteBodyText` in the XCFramework (never hand-parsed in Swift).+    // Editor binds PKCanvasView and maps PKStroke -> InkStroke per+    // `PencilKitMapping.swift`, then serializes via `serializeNoteBody`.+    @State private var query = ""+     var body: some View {-        Text("EverySync Notes")+        NavigationStack {+            VStack {+                // TODO(Mac): replace with the XCFramework-driven list.+                Text("EverySync Notes")+                    .navigationTitle("Notes")+            }+            .searchable(text: $query)+        }     } }
apple/Notes/PencilKitMapping.swift
diff --git a/apple/Notes/PencilKitMapping.swift b/apple/Notes/PencilKitMapping.swiftnew file mode 100644index 0000000000..352303d47b--- /dev/null+++ b/apple/Notes/PencilKitMapping.swift@@ -0,0 +1,76 @@+// EverySync Notes — PencilKit <-> shared ink-model mapping.+//+// PencilKit has no shared counterpart, so the stroke converter lives here,+// but it maps 1:1 onto `InkPoint`/`InkStroke` and performs NO merge / hash /+// crypto. Serialization of the mapped strokes (`serializeNoteBody`) stays in+// the XCFramework. Canvas height maps to the ink block's `heightDp`+// (default 300).+//+// Mapping (verbatim from `Notes/README.md`):+// | `PKStrokePoint`          | `InkPoint`            |+// | `location.x / .y`        | `x / y`               |+// | `timeOffset + stroke start` | `timeMillis`       |+// | `force` (fallback `size`)| `pressure`            |+// | `pi/2 - altitude`        | `tiltRadians`         |+// | `azimuth`                | `orientationRadians` |+// | `PKStroke` / `PKInk`     | `InkStroke`           |+// | `ink.inkType`            | `brushFamily`         |+// | `ink` line width         | `brushSize`           |+// | `ink.color` -> argb int  | `brushColor`          |+// | constant                 | `brushEpsilon = 0.1`  |+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `PKStrokePoint` property names (`location`, `timeOffset`, `size`,+//   `force`, `azimuth`, `altitude`) against the linked iOS SDK.+// - `PKInk.InkType` -> `brushFamily` string mapping: confirm the exact raw+//   strings the Mac wants (`"pressurePen"` default; pen/pencil/marker map to+//   documented family names — keep the mapping table in ONE place, here).++import PencilKit+import UIKit+import EverysyncCore++/// Thin platform layer: PencilKit in, shared-model strokes out (and back for+/// rendering stored ink onto the canvas). No logic beyond unit conversion.+public enum PencilKitMapping {+    /// Default when the ink type has no family mapping.+    public static let defaultBrushFamily = "pressurePen"+    public static let defaultBrushEpsilon: Float = 0.1++    // TODO(Mac): implement against the generated XCFramework `InkStroke` /+    // `InkPoint` Kotlin types:+    //+    // static func inkStroke(from stroke: PKStroke, startMillis: Int64) -> InkStroke:+    //   - brushFamily = familyName(for: stroke.ink.inkType) ?? defaultBrushFamily+    //   - brushSize = Float(stroke.ink.lineWidth(for: ...)) (line-width API+    //     varies by SDK — confirm on the Mac; store the rendered width)+    //   - brushColor = argb int of stroke.ink.color (see InkColorHelp)+    //   - brushEpsilon = 0.1 (constant — matches the shared default)+    //   - points = stroke.path.map { inkPoint(from: $0, startMillis:) }+    //+    // static func inkPoint(from point: PKStrokePoint, startMillis: Int64) -> InkPoint:+    //   - x = Float(point.location.x), y = Float(point.location.y)+    //   - timeMillis = startMillis + Int64((point.timeOffset * 1000).rounded())+    //   - pressure = Float(point.size.width > 0 ? point.force : fallback)+    //     (PencilKit reports force 0 for finger touches — fall back to 1.0 so+    //     strokes stay visible; the fallback is display-only, stored verbatim)+    //   - tiltRadians = Float(.pi / 2 - point.altitude)+    //   - orientationRadians = Float(point.azimuth)+    //+    // static func pkStroke(from ink: InkStroke) -> PKStroke (render path):+    //   - rebuild PKStrokePath from points; PKInk with the mapped type/width/color.+    //   - Lossy where PencilKit has no equivalent (epsilon, exact family) —+    //     acceptable: the stored InkStroke is source of truth, the PKStroke is+    //     a render projection only.++    /// Maps a PencilKit ink type to the shared `brushFamily` string.+    /// TODO(Mac): confirm exact family strings; keep `"pressurePen"` default.+    public static func familyName(for inkType: PKInk.InkType) -> String {+        switch inkType {+        case .pen: return "pressurePen"+        case .pencil: return "pencil"+        case .marker: return "marker"+        default: return defaultBrushFamily+        }+    }+}
apple/Notes/README.md
diff --git a/apple/Notes/README.md b/apple/Notes/README.mdindex 8d8f074761..dfab8871ca 100644--- a/apple/Notes/README.md+++ b/apple/Notes/README.md@@ -103,3 +103,19 @@ processing task after local edits. Scheduling only. Parse/serialize blocks JSON by hand, compute content hashes, run merge/LWW, encrypt envelopes, or invent block types. All of that is `NoteBlocks.kt` + `NoteKind` in the XCFramework.++## Files (Phase 3)++| File | Role |+|---|---|+| `NotesApp.swift` | SwiftUI entry + note list contract; zero sync logic |+| `NoteBodyView.swift` | Native Text/Image/Ink block rendering over the XCFramework `NoteBody` |+| `PencilKitMapping.swift` | `PKStroke` <-> `InkStroke` unit conversion only (no merge/hash/crypto) |+| `ShareExtension.swift` | `com.apple.share-services` target; XCFramework parsers -> envelope IPC |+| `Info.plist.reference` | BGTask id, `everysync://join` scheme (no camera keys in this shell) |+| `Notes.entitlements.reference` | App Group + shared Keychain group (shared with the extension) |+| `../Shared/EnvelopeIPC.swift` | SQLite IPC store (shared with Passwords/Hub) |+| `../Shared/BlobStore.swift` | Blob sidecar: image bytes by `fileName` (shared) |+| `../Shared/KeychainSecureStore.swift` | Keychain layout contract (Kotlin implements) |+| `../Shared/EverysyncCoreCrypto.swift` | CryptoKit AES-GCM C bridge (fills the Rust AES gap) |+| `../Shared/BackgroundSync.swift` | BGTask registration helpers |
apple/Notes/ShareExtension.swift
diff --git a/apple/Notes/ShareExtension.swift b/apple/Notes/ShareExtension.swiftnew file mode 100644index 0000000000..74afd87125--- /dev/null+++ b/apple/Notes/ShareExtension.swift@@ -0,0 +1,37 @@+// EverySync Notes — Share extension.+//+// `NSExtension` (`com.apple.share-services`) target. Receives text / URLs /+// images, converts to `NoteBlock`s via the XCFramework parsers+// (`parseNoteBody` / text-block construction — never hand-built JSON), and+// writes through the App-Group envelope IPC. It NEVER talks to the relay+// directly; the hub picks up the new envelopes on its next cycle.+//+// Conversion (via XCFramework only):+// - text / URL -> `NoteBlock.Text(markdown:)` (URLs stored as markdown links;+//   Swift does not invent block types).+// - image -> write bytes to `BlobStore` under the XCFramework-derived+//   `fileName`, then `NoteBlock.Image(fileName:, widthFraction: 1.0)`.+// - New note = fresh syncId (`newRelaySyncId` in the XCFramework);+//   `blocksJson` = `serializeNoteBody`; row written via+//   `upsertRaw(vaultId:table:rows:)` on the `notes` table.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - Extension target links `EverysyncCore.xcframework` + shares the App Group.+// - `NSExtensionAttributes` (`NSExtensionActivationRule`) in the extension's+//   Info.plist — plain-text + URL + image predicates.++import UIKit+import Social+import EverysyncCore++/// Share-extension view controller. Thin adapter: system share sheet in,+/// envelope IPC out, XCFramework parsers in between.+final class EverySyncShareExtension: SLComposeServiceViewController {+    // TODO(Mac): read `extensionContext?.inputItems`; for each:+    // - text/URL: build NoteBlock.Text via the XCFramework (never raw JSON).+    // - image: persist bytes through BlobStore, build NoteBlock.Image.+    // Then serialize via `serializeNoteBody`, wrap in a RemoteNote envelope+    // via `NoteKind.toJson`, and `upsertRaw` into the active vault's `notes`+    // table. Surface errors with `AppMessages`-equivalent UI (no Toast —+    // repo-wide ban; use the host sheet's own presentation).+}
apple/Passwords/CredentialProvider.entitlements.reference
diff --git a/apple/Passwords/CredentialProvider.entitlements.reference b/apple/Passwords/CredentialProvider.entitlements.referencenew file mode 100644index 0000000000..ae7520ce71--- /dev/null+++ b/apple/Passwords/CredentialProvider.entitlements.reference@@ -0,0 +1,16 @@+<!-- EverySync Credential Provider extension — entitlements reference.+     The ONLY target with the autofill-credential-provider entitlement. -->+<plist version="1.0">+<dict>+    <key>com.apple.security.application-groups</key>+    <array>+        <string>group.&lt;team&gt;.everysync.shared</string>+    </array>+    <key>keychain-access-groups</key>+    <array>+        <string>$(AppIdentifierPrefix)com.vayunmathur.everysync.shared</string>+    </array>+    <key>com.apple.developer.authentication-services.autofill-credential-provider</key>+    <true/>+</dict>+</plist>
apple/Passwords/CredentialProvider.swift
diff --git a/apple/Passwords/CredentialProvider.swift b/apple/Passwords/CredentialProvider.swiftnew file mode 100644index 0000000000..4cb00ffce0--- /dev/null+++ b/apple/Passwords/CredentialProvider.swift@@ -0,0 +1,56 @@+// EverySync Passwords — Credential Provider extension.+//+// `ASCredentialProviderViewController` subclass. Reads credentials over XPC+// from the containing app (App-Group container + `NSFileCoordinator` — see+// `PasswordsXPCService.swift`); candidate ranking via XCFramework+// `DomainMatch` — NO Swift matching logic. The extension never touches the+// relay, never merges, never hashes, never encrypts.+//+// Flow:+// 1. `prepareCredentialList(for:)` — asks the host XPC service for the+//    vault's password/passkey envelopes, projects display rows+//    (service name + username only), and returns matching+//    `ASPasswordCredentialIdentity` items. Matching =+//    `DomainMatch.normalizeSite` + `isSameSiteOrSubdomain` in the XCFramework.+// 2. `provideCredentialWithoutUserInteraction(for:)` — returns the stored+//    `ASPasswordCredential` for a previously-selected identity.+// 3. `prepareInterfaceToProvideCredential(for:)` — presents confirmation UI,+//    then provides the credential.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - Extension target links the same `EverysyncCore.xcframework`.+// - `com.apple.developer.authentication-services.autofill-credential-provider`+//   entitlement = YES on the extension target only.+// - Shared Keychain group with the containing app (see+//   `Passwords.entitlements.reference`).++import AuthenticationServices+import EverysyncCore++/// Autofill extension. All candidates come from the host app over XPC;+///+/// `DomainMatch` ranking stays in the XCFramework.+final class EverySyncCredentialProvider: ASCredentialProviderViewController {+    /// XPC connection to the containing app's envelope service. The extension+    /// process cannot assume direct store access, so EVERY read goes through+    /// `com.vayunmathur.everysync.envelope-ipc` (see `PasswordsXPCService.swift`).+    private var xpc: NSXPCConnection?++    override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {+        // TODO(Mac): open the XPC connection; fetch envelope rows for the+        // active vault; rank via XCFramework `DomainMatch` over each stored+        // `websites[]` / `rpId`; reply with matching identities.+        // No Swift matching logic — call the XCFramework.+    }++    override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {+        // TODO(Mac): fetch the single envelope by syncId over XPC; reply with+        // `ASPasswordCredential(user:username, password:password)`.+        // Never log or cache the secret outside this call.+    }++    override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) {+        // TODO(Mac): present confirmation UI (Face ID gate via+        // `NSFaceIDUsageDescription`), then provide the credential as above.+    }+}
apple/Passwords/Info.plist.reference
diff --git a/apple/Passwords/Info.plist.reference b/apple/Passwords/Info.plist.referencenew file mode 100644index 0000000000..7e63656296--- /dev/null+++ b/apple/Passwords/Info.plist.reference@@ -0,0 +1,35 @@+<!-- EverySync Passwords — Info.plist reference (Phase 3, Mac fills values).+     Copy into the Xcode target's Info.plist; replace <team> with the real+     team prefix. Kept as a reference file (not a live plist) because+     xcodebuild cannot run on this Windows box. -->+<plist version="1.0">+<dict>+    <!-- Face ID gate for vault unlock (no password material leaves Keychain). -->+    <key>NSFaceIDUsageDescription</key>+    <string>EverySync uses Face ID to unlock your password vaults.</string>++    <!-- Background sync triggers (see ../Shared/BackgroundSync.swift). -->+    <key>BGTaskSchedulerPermittedIdentifiers</key>+    <array>+        <string>com.vayunmathur.everysync.passwords.refresh</string>+    </array>+    <key>UIBackgroundModes</key>+    <array>+        <string>fetch</string>+        <string>processing</string>+    </array>++    <!-- Join-link handling: everysync://join/<vault>?owner=...&type=... -->+    <key>CFBundleURLTypes</key>+    <array>+        <dict>+            <key>CFBundleURLName</key>+            <string>com.vayunmathur.everysync.join</string>+            <key>CFBundleURLSchemes</key>+            <array>+                <string>everysync</string>+            </array>+        </dict>+    </array>+</dict>+</plist>
apple/Passwords/Passwords.entitlements.reference
diff --git a/apple/Passwords/Passwords.entitlements.reference b/apple/Passwords/Passwords.entitlements.referencenew file mode 100644index 0000000000..c8c9df7626--- /dev/null+++ b/apple/Passwords/Passwords.entitlements.reference@@ -0,0 +1,16 @@+<!-- EverySync Passwords — entitlements reference (Phase 3, Mac fills values).+     App-Group envelope IPC + shared Keychain group with the Credential+     Provider extension. Replace <team> with the real team prefix. -->+<plist version="1.0">+<dict>+    <key>com.apple.security.application-groups</key>+    <array>+        <string>group.&lt;team&gt;.everysync.shared</string>+    </array>+    <!-- Shared with the .autofill extension (see CredentialProvider.swift). -->+    <key>keychain-access-groups</key>+    <array>+        <string>$(AppIdentifierPrefix)com.vayunmathur.everysync.shared</string>+    </array>+</dict>+</plist>
apple/Passwords/PasswordsApp.swift
diff --git a/apple/Passwords/PasswordsApp.swift b/apple/Passwords/PasswordsApp.swiftindex 1dc5d4aedd..ff05eb545d 100644--- a/apple/Passwords/PasswordsApp.swift+++ b/apple/Passwords/PasswordsApp.swift@@ -1,37 +1,90 @@-// EverySync Passwords — Phase 3a SwiftUI shell.+// EverySync Passwords — Phase 3 SwiftUI shell. //-// Zero sync logic in Swift. All merge / transport / crypto lives in the-// shared XCFramework (everysync-core KMP). This file only declares the UI-// entry point, the Credential Provider host, and — in comments — the exact-// KMP entry points Phase 3 will call. Nothing here computes, merges,-// hashes, or encrypts.+// ZERO sync logic in Swift. All merge (`mergeCredentials` / `passkeysFor` /+// `PasskeyLink`), TOTP (`Totp.generate`), matching (`DomainMatch`), envelope+// codec (`PasswordKind.toJson/fromJson`), roles (`RelayRoles`), links+// (`RelayLinks`), transport (`IosRelayTransport`), and cursors+// (`RelayCursorStore`) live in the shared XCFramework. This target:+// - renders vault list / detail / TOTP codes from XCFramework snapshots,+// - hosts the Credential Provider extension (see `CredentialProvider.swift`),+// - exposes the XPC envelope service (see `PasswordsXPCService.swift`),+// - schedules background sync (see `../Shared/BackgroundSync.swift`).+//+// Delete semantics — HARD delete (verbatim): passwords rows vanish locally;+// only the app-side snapshot remembers them.+// `PasswordKind.localDeletesAreAuthoritative == false`, so a healthy-read+// absence IS a genuine local delete. `SyncSink.delete` removes the row;+// merge-driven deletes always arrive as tombstone envelopes, never raw.+// See `../IPC_CONTRACT.md`.  import SwiftUI-import AuthenticationServices+import BackgroundTasks import EverysyncCore -// MARK: - KMP entry points (Phase 3 wiring, for reference only)+// MARK: - KMP entry points (Phase 3 wiring — call, never re-implement) //-// data:        com.vayunmathur.everysync.core.data.RemotePassword-// merge:       com.vayunmathur.everysync.core.passwords.mergeCredentials-//              com.vayunmathur.everysync.core.passwords.passkeysFor-//              com.vayunmathur.everysync.core.passwords.PasskeyLink-//              com.vayunmathur.everysync.core.passwords.DomainMatch-// totp:        com.vayunmathur.everysync.core.passwords.Totp.generate-// kind:        com.vayunmathur.everysync.core.sync.adapters.PasswordKind-// driver:      com.vayunmathur.everysync.core.provider.SyncDriver-// cursors:     com.vayunmathur.everysync.core.platform.RelayCursorStore-// securestore: com.vayunmathur.everysync.core.platform.SecureStore (Keychain actual)-// transport:   com.vayunmathur.everysync.core.network.IosRelayTransport-// channels:    recordChannel("passwords", vaultId) -> "passwords:<vaultId>"-// roles:       RelayRoles — passwords offer EDITOR only, never VIEWER+// data:        core.data.RemotePassword (uid / isPasskey / name / username /+//              email / password / note / totpSecret / websites[] / rp* half /+//              creationTime / lastUsedTime / signCount / linkedPasswordSyncId /+//              deleted / updatedAt)+// merge:       core.passwords.mergeCredentials([CredentialDto], [PasskeyDto])+//                -> MergeResult(passkeysByPasswordSyncId, standalone)+//              core.passwords.passkeysFor(password, passwords, passkeys)+//              core.passwords.PasskeyLink (Auto / Detached / To(syncId))+// totp:        core.passwords.Totp.generate(secret, epochSecond) — Swift only+//              passes `Int64(Date().timeIntervalSince1970)`; CryptoKit HMAC is+//              behind the XCFramework's `HmacIos` actual.+// match:       core.passwords.DomainMatch.normalizeSite / isSameSiteOrSubdomain+// kind:        core.sync.adapters.PasswordKind (syncId=uid, LWW updatedAt,+//              contentKey password `name␀username` / passkey `rpId␀credentialId`,+//              `isTombstoneEnvelope` = `deleted`)+// driver:      core.provider.SyncDriver.drive(kind, store, remote, append, now)+// cursors:     core.platform.RelayCursorStore (`relay_cursor:<type>:<vault>:<channel>`)+// securestore: core.platform.SecureStore (Keychain actual — see+//              ../Shared/KeychainSecureStore.swift; vault AES keys NEVER+//              surface in Swift)+// transport:   core.network.IosRelayTransport (`recordChannel("passwords",+//              vaultId)` -> `passwords:<vaultId>`; envelopes+//              `Base64(AES_GCM)` per item; invites PQC-sealed to `inbox:<device>`)+// roles:       RelayRoles — passwords offer EDITOR only, NEVER VIEWER+//              (read-only passwords still disclose every secret) // links:       RelayLinks.parseJoinLink / .shareLinkFor-// pqc:         10 fns per IOS_PQC_NOTES.md (e2eePqc cinterop)+//              (`everysync://join/<vault>?owner=…&type=…`)+// pqc:         exactly 10 fns per IOS_PQC_NOTES.md via `e2eePqc` cinterop.+//              Swift never calls Rust directly — only via the XCFramework.++/// Vault list entry, projected from `RemotePassword` envelopes by the+/// XCFramework. Swift holds display strings only — no secrets leave the+/// envelope except into the visible detail view / autofill response.+struct PasswordRow: Identifiable {+    /// Relay sync identity (`RemotePassword.uid`).+    let id: String+    let name: String+    let username: String+    /// True for the passkey half (`RemotePassword.isPasskey`).+    let isPasskey: Bool+    let rpId: String+    /// Attached passkeys, from `passkeysFor` in the XCFramework.+    let passkeyCount: Int+}  @main struct PasswordsApp: App {-    // TODO(Phase 3): create SyncDriver + IosRelayTransport from the-    //  XCFramework; register BGTaskScheduler handlers (see README.md).+    init() {+        // Register the periodic pull; the cycle itself runs in the XCFramework.+        // MAC-CHECK: identifier must match Info.plist+        // `BGTaskSchedulerPermittedIdentifiers`.+        BackgroundSync.register(handlers: [+            "com.vayunmathur.everysync.passwords.refresh": { task in+                // TODO(Mac): call XCFramework SyncDriver cycle for each vault,+                // then re-schedule + `task.setTaskCompleted(success:)`.+                // (Kotlin `SyncScheduler` actual owns the schedule; this+                // handler is the wakeup entry.)+                task.setTaskCompleted(success: true)+            },+        ])+    }+     var body: some Scene {         WindowGroup {             PasswordsRootView()@@ -40,28 +93,34 @@ struct PasswordsApp: App { }  struct PasswordsRootView: View {-    // TODO(Phase 3): vault list driven by SyncDriver snapshots via-    //  RelayCursorStore; rows rendered from RemotePassword envelopes.+    // TODO(Mac): vault list driven by SyncDriver snapshots via+    // RelayCursorStore; rows projected from RemotePassword envelopes by+    // `mergeCredentials` in the XCFramework. TOTP via `Totp.generate`.+    // Search filters on name/username only (never on secret material).+    @State private var query = ""+     var body: some View {-        Text("EverySync Passwords")+        NavigationStack {+            VStack {+                // TODO(Mac): replace with the XCFramework-driven list.+                // Placeholder keeps the target compiling on Windows/Linux CI+                // where EverysyncCore / SwiftUI previews are unavailable.+                Text("EverySync Passwords")+                    .navigationTitle("Passwords")+            }+            .searchable(text: $query)+        }     } } -// MARK: - Credential Provider extension host--/// Autofill extension. Reads credentials over XPC from the containing app-/// (App-Group container + NSFileCoordinator); matching via XCFramework-/// `DomainMatch`. No Swift matching logic.-final class EverySyncCredentialProvider: ASCredentialProviderViewController {-    override func prepareCredentialList(for serviceIdentifiers: [ASCredentialServiceIdentifier]) {-        // TODO(Phase 3): query containing app over XPC, rank via DomainMatch.-    }--    override func provideCredentialWithoutUserInteraction(for credentialIdentity: ASPasswordCredentialIdentity) {-        // TODO(Phase 3): return the stored credential for this identity.-    }--    override func prepareInterfaceToProvideCredential(for credentialIdentity: ASPasswordCredentialIdentity) {-        // TODO(Phase 3): present confirmation UI, then provide the credential.-    }-}+// MARK: - Detail view contract (Mac implements against XCFramework types)+//+// - Detail shows password fields + `Totp.generate(secret, now)` code.+// - Passkey rows show `rpId / credentialId / userName` + link state+//   (`PasskeyLink.fromColumn(linkedPasswordSyncId)`); link/detach writes go+//   through the envelope IPC as `linkedPasswordSyncId` field updates — Swift+//   never computes merge pairing.+// - Delete = HARD delete via `deleteByVault` (row vanishes); the app-side+//   snapshot (XCFramework) remembers it for propagation.+// - Share sheet offers EDITOR only (`RelayRoles.offerable("passwords")`).+//   Vault keys never user-visible: links carry ids only.
apple/Passwords/PasswordsXPCService.swift
diff --git a/apple/Passwords/PasswordsXPCService.swift b/apple/Passwords/PasswordsXPCService.swiftnew file mode 100644index 0000000000..dbdaea4b32--- /dev/null+++ b/apple/Passwords/PasswordsXPCService.swift@@ -0,0 +1,134 @@+// EverySync Passwords — XPC envelope service.+//+// The autofill extension cannot assume direct store access, so the containing+// Passwords app exposes this XPC service with EXACTLY the three IPC ops from+// `../IPC_CONTRACT.md` (which map 1:1 to KMP `SyncSink`). The service does+// `NSFileCoordinator` internally; callers just call the three methods.+//+// Service name: `com.vayunmathur.everysync.envelope-ipc` (must match the+// extension's `NSXPCConnection` + the service's `Info.plist`).+// The extension NEVER touches the relay — only these three ops.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - XPC service target with the App-Group entitlement+//   (`group.<team>.everysync.shared`).+// - `NSXPCInterface` signatures below match on both sides (exported object ++//   remote object). `@objc` + `NSSecureCoding`-compatible row type required+//   at the boundary — hence `XPCEnvelopeRow` (plain data, no logic).++import Foundation++/// XPC-safe envelope row. Same five columns as `EnvelopeRow` / KMP `SyncSink`:+/// `syncId / updatedAt / deleted / payloadJson / contentHash`. Opaque payload+/// — the extension forwards it to the XCFramework; it never parses it.+@objc(XPCEnvelopeRow)+public final class XPCEnvelopeRow: NSObject, NSSecureCoding {+    public static var supportsSecureCoding: Bool { true }++    public let syncId: String+    public let updatedAt: Int64+    public let deleted: Bool+    public let payloadJson: String+    public let contentHash: String++    public init(syncId: String, updatedAt: Int64, deleted: Bool, payloadJson: String, contentHash: String) {+        self.syncId = syncId+        self.updatedAt = updatedAt+        self.deleted = deleted+        self.payloadJson = payloadJson+        self.contentHash = contentHash+    }++    public func encode(with coder: NSCoder) {+        coder.encode(syncId, forKey: "syncId")+        coder.encode(updatedAt, forKey: "updatedAt")+        coder.encode(deleted, forKey: "deleted")+        coder.encode(payloadJson, forKey: "payloadJson")+        coder.encode(contentHash, forKey: "contentHash")+    }++    public required init?(coder: NSCoder) {+        guard let syncId = coder.decodeObject(of: NSString.self, forKey: "syncId") as String?,+              let payloadJson = coder.decodeObject(of: NSString.self, forKey: "payloadJson") as String?,+              let contentHash = coder.decodeObject(of: NSString.self, forKey: "contentHash") as String? else {+            return nil+        }+        self.syncId = syncId+        self.updatedAt = coder.decodeInt64(forKey: "updatedAt")+        self.deleted = coder.decodeBool(forKey: "deleted")+        self.payloadJson = payloadJson+        self.contentHash = contentHash+    }+}++/// The three IPC ops. Table names cross the boundary as strings+/// (`passwords` / `notes` / `todos` / `contacts` / `calendars`); the service+/// validates against the `EnvelopeTable` allowlist before touching SQLite.+@objc(EnvelopeIPCServiceProtocol)+public protocol EnvelopeIPCServiceProtocol {+    /// `querySince` — rows with `updatedAt > since`, tombstones included.+    /// Reply: rows, or error (unhealthy read — caller aborts, never empties).+    func querySince(vaultId: String, table: String, since: Int64, reply: @escaping ([XPCEnvelopeRow]?, Error?) -> Void)+    /// `upsertRaw` — idempotent upsert keyed on `syncId`.+    func upsertRaw(vaultId: String, table: String, rows: [XPCEnvelopeRow], reply: @escaping (Error?) -> Void)+    /// `deleteByVault` — hard-delete (passwords) or timestamped tombstone+    /// (everything else). `now` is epoch ms, stamped so delta queries observe+    /// the delete (see `EnvelopeIPC.deleteByVault`).+    func deleteByVault(vaultId: String, table: String, syncId: String, now: Int64, reply: @escaping (Error?) -> Void)+}++/// Service implementation. Thin wrapper over `EnvelopeIPC` (see+/// `../Shared/EnvelopeIPC.swift`) — no logic beyond allowlist validation.+///+/// MAC-CHECK: `EnvelopeIPC`/`EnvelopeTable`/`EnvelopeRow` live in the Shared+/// sources — the XPC service target must compile them in (or import the+/// shared module) or this file won't resolve. Same for `EverysyncCore`.+@objc(EnvelopeIPCService)+public final class EnvelopeIPCService: NSObject, EnvelopeIPCServiceProtocol {+    private let store = EnvelopeIPC()++    private func table(named raw: String) -> EnvelopeTable? {+        EnvelopeTable(rawValue: raw)+    }++    public func querySince(vaultId: String, table: String, since: Int64, reply: @escaping ([XPCEnvelopeRow]?, Error?) -> Void) {+        guard let t = self.table(named: table) else {+            reply(nil, EnvelopeIPCError.sqlite("unknown table: \(table)"))+            return+        }+        do {+            let rows = try store.querySince(vaultId: vaultId, table: t, since: since)+            reply(rows.map { XPCEnvelopeRow(syncId: $0.syncId, updatedAt: $0.updatedAt, deleted: $0.deleted, payloadJson: $0.payloadJson, contentHash: $0.contentHash) }, nil)+        } catch {+            reply(nil, error)+        }+    }++    public func upsertRaw(vaultId: String, table: String, rows: [XPCEnvelopeRow], reply: @escaping (Error?) -> Void) {+        guard let t = self.table(named: table) else {+            reply(EnvelopeIPCError.sqlite("unknown table: \(table)"))+            return+        }+        do {+            try store.upsertRaw(vaultId: vaultId, table: t, rows: rows.map {+                EnvelopeRow(syncId: $0.syncId, updatedAt: $0.updatedAt, deleted: $0.deleted, payloadJson: $0.payloadJson, contentHash: $0.contentHash)+            })+            reply(nil)+        } catch {+            reply(error)+        }+    }++    public func deleteByVault(vaultId: String, table: String, syncId: String, now: Int64, reply: @escaping (Error?) -> Void) {+        guard let t = self.table(named: table) else {+            reply(EnvelopeIPCError.sqlite("unknown table: \(table)"))+            return+        }+        do {+            try store.deleteByVault(vaultId: vaultId, table: t, syncId: syncId, now: now)+            reply(nil)+        } catch {+            reply(error)+        }+    }+}
apple/Passwords/README.md
diff --git a/apple/Passwords/README.md b/apple/Passwords/README.mdindex 0e4af11db5..32344c97f8 100644--- a/apple/Passwords/README.md+++ b/apple/Passwords/README.md@@ -74,3 +74,19 @@ in the XCFramework. Re-implement merge pairing, TOTP framing/math, canonical JSON/hash, envelope Base64/AES, role checks, or link parsing. If logic exists in Swift that also exists in `everysync-core`, delete the Swift copy.++## Files (Phase 3)++| File | Role |+|---|---|+| `PasswordsApp.swift` | SwiftUI entry + vault list/detail contract; zero sync logic |+| `CredentialProvider.swift` | `ASCredentialProviderViewController`; reads over XPC, ranks via `DomainMatch` |+| `PasswordsXPCService.swift` | `com.vayunmathur.everysync.envelope-ipc` — exactly the 3 IPC ops |+| `Info.plist.reference` | Face ID string, BGTask id, `everysync://join` scheme |+| `Passwords.entitlements.reference` | App Group + shared Keychain group |+| `CredentialProvider.entitlements.reference` | Autofill entitlement (extension target only) |+| `../Shared/EnvelopeIPC.swift` | SQLite IPC store (shared with Notes/Hub) |+| `../Shared/BlobStore.swift` | Blob sidecar (shared) |+| `../Shared/KeychainSecureStore.swift` | Keychain layout contract (Kotlin implements) |+| `../Shared/EverysyncCoreCrypto.swift` | CryptoKit AES-GCM C bridge (fills the Rust AES gap) |+| `../Shared/BackgroundSync.swift` | BGTask registration helpers |
apple/Shared/BackgroundSync.swift
diff --git a/apple/Shared/BackgroundSync.swift b/apple/Shared/BackgroundSync.swiftnew file mode 100644index 0000000000..4c2f782cf8--- /dev/null+++ b/apple/Shared/BackgroundSync.swift@@ -0,0 +1,65 @@+// EverySync Apple shells — background scheduling notes.+//+// The KMP `SyncScheduler` interface (`schedulePeriodic / cancel / syncNow`)+// is implemented in KOTLIN (`IOS_ACTUALS_NOTES.md`), not here. This file is+// the Swift registration side: `BGTaskScheduler` handlers that wake the+// XCFramework's `SyncDriver` cycles. Scheduling only — cycles run in Kotlin.+//+// APNs discipline (verbatim from the plan): APNs is a PULL TRIGGER ONLY,+// never payload. A push wakes the app; the app then pulls the relay channel+// (`pullRecords` from `since` cursor) through the XCFramework. No vault data,+// keys, or envelopes ever ride the push.+//+// Identifiers (must match Info.plist `BGTaskSchedulerPermittedIdentifiers` —+/// see each app's `Info.plist.reference`):+// - Passwords: `com.vayunmathur.everysync.passwords.refresh` (app-refresh) ++//   one-shot `BGProcessingTask` after local edits.+// - Notes: `com.vayunmathur.everysync.notes.refresh` + one-shot after edits.+// - Hub: `com.vayunmathur.everysync.hub.refresh` (app-refresh) ++//   `com.vayunmathur.everysync.hub.upload` (processing, after local+//   system-store changes observed via `EKEventStore` notifications).+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `BGTaskScheduler.shared.register` identifiers match the plist.+// - `UIBackgroundModes` includes `fetch` + `processing`.+// - `BGAppRefreshTaskRequest.earliestBeginDate` throttling honored (system may+//   defer; the hub re-schedules at the END of each task — see below).++import BackgroundTasks+import Foundation++/// Registers the app's BGTask handlers. Call once at launch (before the+/// XCFramework creates its `SyncScheduler` actual — the Kotlin actual calls+/// `submit`/`cancel`, this side only handles the wakeup).+///+/// - Parameter handlers: task identifier -> wakeup closure. The closure MUST:+///   1. Create its task-specific work (call into the XCFramework driver).+///   2. Re-schedule the next refresh (system gives no repeating schedule).+///   3. Call `task.setTaskCompleted(success:)` exactly once.+public enum BackgroundSync {+    public static func register(handlers: [String: @Sendable @escaping (BGTask) -> Void]) {+        for (identifier, handler) in handlers {+            BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: nil, launchHandler: handler)+        }+    }++    /// Schedules the next periodic pull. Kotlin's `SyncScheduler.actual`+    /// calls this shape through (interval from `schedulePeriodic`).+    public static func scheduleRefresh(identifier: String, intervalMinutes: Int = 15) throws {+        let request = BGAppRefreshTaskRequest(identifier: identifier)+        request.earliestBeginDate = Date(timeIntervalSinceNow: TimeInterval(intervalMinutes * 60))+        try BGTaskScheduler.shared.submit(request)+    }++    /// One-shot upload after local edits (shells call this; the actual cycle+    /// still runs in the XCFramework via `SyncScheduler.syncNow`).+    public static func scheduleProcessing(identifier: String, requiresNetwork: Bool = true) throws {+        let request = BGProcessingTaskRequest(identifier: identifier)+        request.requiresNetworkConnectivity = requiresNetwork+        try BGTaskScheduler.shared.submit(request)+    }++    public static func cancel(identifier: String) {+        BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier)+    }+}
apple/Shared/BlobStore.swift
diff --git a/apple/Shared/BlobStore.swift b/apple/Shared/BlobStore.swiftnew file mode 100644index 0000000000..89c84b5f64--- /dev/null+++ b/apple/Shared/BlobStore.swift@@ -0,0 +1,115 @@+// EverySync Apple shells — blob sidecar store.+//+// Note image bytes keyed by `fileName` (see IPC_CONTRACT.md + `NoteKind`):+// envelopes carry only the name + `widthFraction`; bytes ride the blob+// channel `notes-blobs:<vaultId>` and land here. Zero sync logic — pure file+// I/O under the same App-Group container + `NSFileCoordinator` as+// `EnvelopeIPC.swift`.++import Foundation++public enum BlobStoreError: Error {+    case containerUnavailable+    case invalidFileName+    case io(Error)+}++/// Content-addressed-ish file store: `<group>/vault/<vaultId>/blobs/<fileName>`.+/// `fileName` values come from the XCFramework (`NoteKind.imageNames`); they+/// are `"<sha256>.jpg"`-shaped. This store REJECTS any name containing a path+/// separator or `..` so a hostile envelope can never escape the vault dir.+public final class BlobStore {+    private let fileManager = FileManager.default+    private let coordinator = NSFileCoordinator()+    private let queue = DispatchQueue(label: "com.vayunmathur.everysync.blob-store")++    public init() {}++    // MARK: - Ops (called only with XCFramework-derived names/hashes)++    /// Reads blob bytes; nil when absent (a missing blob is NOT an error —+    /// the hub prefetches via `NoteKind.imageNames(blocksJson)`; the note+    /// renders with a placeholder until the blob arrives).+    public func read(vaultId: String, fileName: String) throws -> Data? {+        let safe = try checkedFileName(fileName)+        return try queue.sync {+            let url = try blobURL(vaultId: vaultId, fileName: safe)+            var result: Data?+            var caught: Error?+            var coordError: NSError?+            coordinator.coordinate(readingItemAt: url, options: [], error: &coordError) { readURL in+                do {+                    result = try Data(contentsOf: readURL)+                } catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError {+                    result = nil+                } catch {+                    caught = error+                }+            }+            if let caught { throw BlobStoreError.io(caught) }+            return result+        }+    }++    /// Idempotent write keyed on `fileName`. Overwrites are safe: file names+    /// embed the content hash, so same-name bytes are same-content bytes.+    public func write(vaultId: String, fileName: String, data: Data) throws {+        let safe = try checkedFileName(fileName)+        try queue.sync {+            let url = try blobURL(vaultId: vaultId, fileName: safe)+            var caught: Error?+            var coordError: NSError?+            coordinator.coordinate(writingItemAt: url, options: [], error: &coordError) { writeURL in+                do {+                    try data.write(to: writeURL, options: .atomic)+                } catch {+                    caught = error+                }+            }+            if let caught { throw BlobStoreError.io(caught) }+        }+    }++    /// Lists blob file names present for a vault (for orphan GC on the hub).+    public func list(vaultId: String) throws -> [String] {+        try queue.sync {+            let dir = try blobsDirectory(vaultId: vaultId)+            var coordError: NSError?+            var names: [String] = []+            coordinator.coordinate(readingItemAt: dir, options: [], error: &coordError) { readDir in+                names = (try? fileManager.contentsOfDirectory(atPath: readDir.path)) ?? []+            }+            return names+        }+    }++    // MARK: - Paths++    func blobsDirectory(vaultId: String) throws -> URL {+        precondition(!vaultId.isEmpty && !vaultId.contains("/"), "vaultId must be a bare id")+        guard let container = fileManager.containerURL(forSecurityApplicationGroupIdentifier: EverysyncGroup.identifier) else {+            throw BlobStoreError.containerUnavailable+        }+        return container.appendingPathComponent("vault/\(vaultId)/blobs", isDirectory: true)+    }++    func blobURL(vaultId: String, fileName: String) throws -> URL {+        let dir = try blobsDirectory(vaultId: vaultId)+        try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)+        return dir.appendingPathComponent(fileName)+    }++    /// Rejects traversal + separators. Blob names are XCFramework-derived+    /// (`NoteKind.imageNames`), but the envelope is relay data — never trust it.+    func checkedFileName(_ raw: String) throws -> String {+        guard !raw.isEmpty,+              !raw.contains("/"),+              !raw.contains("\\"),+              raw != ".",+              raw != "..",+              !raw.contains("..") else {+            throw BlobStoreError.invalidFileName+        }+        return raw+    }+}
apple/Shared/EnvelopeIPC.swift
diff --git a/apple/Shared/EnvelopeIPC.swift b/apple/Shared/EnvelopeIPC.swiftnew file mode 100644index 0000000000..a36f8bc768--- /dev/null+++ b/apple/Shared/EnvelopeIPC.swift@@ -0,0 +1,391 @@+// EverySync Apple shells — shared envelope IPC store.+//+// Zero sync logic in Swift. This file implements ONLY the three IPC ops from+// `apple/IPC_CONTRACT.md` over the App-Group shared container, with identical+// table / op / column semantics to the KMP `SyncSink` interface+// (`querySince` / `upsertRaw` / `deleteByVault`; columns+// `syncId / updatedAt / deleted / payloadJson / contentHash`).+//+// The hub is the only process that talks to the relay. Shells only touch this+// store; the XCFramework (merge / transport / crypto) reads the same SQLite+// files on the Kotlin side (see ../XCFramework/IOS_ACTUALS_NOTES.md).+//+// Loss-prevention rules honored here:+// - A failed local read THROWS (never returns empty). Callers must abort the+//   cycle, exactly like `SyncSink.listLocalOk == false`.+// - Only explicit tombstones delete (soft-delete tables). Absence without a+//   tombstone resurrects — never deletes.+// - Passwords hard-delete; notes/todos soft-delete.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `import SQLite3` resolves against libsqlite3.tbd (system library).+// - App-Group identifier below must use the real team prefix.++import Foundation+import SQLite3++/// App-Group shared container identifier. The `<team>` placeholder from+/// `IPC_CONTRACT.md` must be replaced with the real team prefix on the Mac+/// (Xcode signing will fail otherwise). Single constant so all targets agree.+public enum EverysyncGroup {+    public static let identifier = "group.com.vayunmathur.everysync.shared"+}++/// One envelope row. Column semantics are identical to the KMP `SyncSink`+/// columns (`EntityKind.syncId` -> `RemoteX.uid`, `RemoteX.updatedAt`,+/// `RemoteX.deleted`, `PasswordKind`/`NoteKind`/`TodoKind.toJson`,+/// `EntityKind.contentHash`).+public struct EnvelopeRow: Equatable {+    /// Relay sync identity (opaque 32-char id).+    public let syncId: String+    /// Last modification, epoch ms; drives relay LWW.+    public let updatedAt: Int64+    /// Tombstone flag. Included in `querySince` results for soft-delete types.+    public let deleted: Bool+    /// Full `RemoteX` JSON envelope. Swift treats this as OPAQUE bytes:+    /// produced/consumed only via the XCFramework (`*Kind.toJson/fromJson`).+    /// Swift never parses, merges, hashes, or encrypts it.+    public let payloadJson: String+    /// `relayContentHash(canonical + "\0deleted=…")`, computed in the+    /// XCFramework (`EntityKind.contentHash`). Swift never computes this.+    public let contentHash: String++    public init(syncId: String, updatedAt: Int64, deleted: Bool, payloadJson: String, contentHash: String) {+        self.syncId = syncId+        self.updatedAt = updatedAt+        self.deleted = deleted+        self.payloadJson = payloadJson+        self.contentHash = contentHash+    }+}++/// IPC tables. Names map 1:1 to relay channels (see IPC_CONTRACT.md).+public enum EnvelopeTable: String, CaseIterable {+    case passwords  // `passwords:<vaultId>` — HARD delete+    case notes      // `notes:<vaultId>`     — SOFT delete (tombstones persist)+    case todos      // `todos:<vaultId>`     — SOFT delete (tombstones persist)+    case contacts   // hub-internal; same columns+    case calendars  // hub-internal; same columns++    var isHardDelete: Bool { self == .passwords }+}++public enum EnvelopeIPCError: Error {+    case containerUnavailable+    case sqlite(String)+    case unhealthyRead(String)+}++/// Thread-safe, `NSFileCoordinator`-guarded SQLite envelope store.+///+/// - Location: `<group>/vault/<vaultId>/envelopes.sqlite` (one file per vault)+///   plus a `blobs/` sidecar dir (see `BlobStore.swift`).+/// - Mode: WAL + `busy_timeout=5000` so the Kotlin `RelayStore` shims (core+///   owner, same schema — see `../XCFramework/IOS_ACTUALS_NOTES.md`) can hold+///   the same files open concurrently. All Swift access goes through+///   `NSFileCoordinator`; the Kotlin side relies on SQLite locking + WAL.+/// - Schema version: v1 (see `../IPC_CONTRACT.md` appendix). Any column/table+///   change must update the contract doc AND the Kotlin shim spec together.+public final class EnvelopeIPC {+    private let fileManager = FileManager.default+    private let coordinator = NSFileCoordinator()+    private let queue = DispatchQueue(label: "com.vayunmathur.everysync.envelope-ipc")++    public init() {}++    // MARK: - Ops (map 1:1 to KMP `SyncSink`)++    /// `querySince` — rows with `updatedAt > since`, tombstones included.+    /// Drives both baseline reads and delta detection. THROWS on any unhealthy+    /// read; callers must abort (never fold failure as empty).+    public func querySince(vaultId: String, table: EnvelopeTable, since: Int64) throws -> [EnvelopeRow] {+        try queue.sync {+            let url = try databaseURL(vaultId: vaultId)+            var rows: [EnvelopeRow] = []+            var caught: Error?+            try coordinateReading(url: url) {+                do {+                    rows = try self.withDatabase(at: url) { db in+                        try self.query(db: db, table: table, since: since)+                    }+                } catch {+                    caught = error+                }+            }+            if let caught { throw caught }+            return rows+        }+    }++    /// `upsertRaw` — idempotent upsert keyed on `syncId`; preserves pulled+    /// timestamps (no timestamp rewriting here — `updatedAt` is stored verbatim).+    public func upsertRaw(vaultId: String, table: EnvelopeTable, rows: [EnvelopeRow]) throws {+        guard !rows.isEmpty else { return }+        try queue.sync {+            let url = try databaseURL(vaultId: vaultId)+            var caught: Error?+            try coordinateWriting(url: url) {+                do {+                    try self.withDatabase(at: url) { db in+                        try self.upsert(db: db, table: table, rows: rows)+                    }+                } catch {+                    caught = error+                }+            }+            if let caught { throw caught }+        }+    }++    /// `deleteByVault` — applies a pulled relay tombstone:+    /// - `passwords`: HARD-delete the row (rows vanish; only the app-side+    ///   snapshot remembers them).+    /// - `notes`/`todos`/`contacts`/`calendars`: set `deleted=1` tombstone.+    ///   The tombstone envelope itself always arrives via `upsertRaw`; this op+    ///   is for shell-side deletes, which the hub folds into tombstones.+    /// Merge-driven deletes ALWAYS arrive as tombstone envelopes, never raw.+    ///+    /// - Parameter now: caller timestamp (epoch ms) stamped onto the tombstone+    ///   row so delta queries (`updatedAt > cursor`) observe the delete. The+    ///   merge overwrites it with the agreed stamp; the value here only needs+    ///   to be newer than the last cursor.+    public func deleteByVault(vaultId: String, table: EnvelopeTable, syncId: String, now: Int64) throws {+        try queue.sync {+            let url = try databaseURL(vaultId: vaultId)+            var caught: Error?+            try coordinateWriting(url: url) {+                do {+                    try self.withDatabase(at: url) { db in+                        if table.isHardDelete {+                            try self.exec(db: db, sql: "DELETE FROM \(table.sql) WHERE syncId = ?;", bind: [syncId])+                        } else {+                            // Tombstone the row; keep payloadJson + contentHash untouched —+                            // the hub replaces them with the tombstone envelope on merge.+                            // Stamp `now` so delta queries (updatedAt > cursor) observe+                            // the delete; the merge overwrites it with the agreed stamp.+                            try self.execTombstone(db: db, table: table, syncId: syncId, now: now)+                        }+                    }+                } catch {+                    caught = error+                }+            }+            if let caught { throw caught }+        }+    }++    /// Removes every row for this vault (purge keeps the vault itself).+    /// Used for account removal / re-provision; the next healthy pull+    /// re-enables repopulation (same as the relay conformance checklist).+    public func purgeVault(vaultId: String) throws {+        try queue.sync {+            let url = try databaseURL(vaultId: vaultId)+            var caught: Error?+            try coordinateWriting(url: url) {+                do {+                    try self.withDatabase(at: url) { db in+                        for table in EnvelopeTable.allCases {+                            try self.exec(db: db, sql: "DELETE FROM \(table.sql);", bind: [])+                        }+                    }+                } catch {+                    caught = error+                }+            }+            if let caught { throw caught }+        }+    }++    // MARK: - Paths++    func containerURL() throws -> URL {+        guard let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: EverysyncGroup.identifier) else {+            throw EnvelopeIPCError.containerUnavailable+        }+        return url+    }++    func vaultDirectory(vaultId: String) throws -> URL {+        precondition(!vaultId.isEmpty && !vaultId.contains("/"), "vaultId must be a bare id")+        return try containerURL().appendingPathComponent("vault/\(vaultId)", isDirectory: true)+    }++    func databaseURL(vaultId: String) throws -> URL {+        let dir = try vaultDirectory(vaultId: vaultId)+        try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)+        try fileManager.createDirectory(at: dir.appendingPathComponent("blobs", isDirectory: true), withIntermediateDirectories: true)+        return dir.appendingPathComponent("envelopes.sqlite")+    }++    // MARK: - SQLite++    private func withDatabase<T>(at url: URL, _ body: (OpaquePointer) throws -> T) throws -> T {+        var db: OpaquePointer?+        let flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX+        guard sqlite3_open_v2(url.path, &db, flags, nil) == SQLITE_OK, let db else {+            throw EnvelopeIPCError.sqlite("open failed: \(url.path)")+        }+        defer { sqlite3_close(db) }+        // NOTE: `PRAGMA journal_mode=WAL` returns a result row (SQLITE_ROW),+        // so it needs a query-style step — plain exec() would throw.+        try queryPragma(db: db, sql: "PRAGMA journal_mode=WAL;")+        try exec(db: db, sql: "PRAGMA busy_timeout=5000;", bind: [])+        for table in EnvelopeTable.allCases {+            try exec(db: db, sql: """+                CREATE TABLE IF NOT EXISTS \(table.sql) (+                  syncId TEXT PRIMARY KEY,+                  updatedAt INTEGER NOT NULL,+                  deleted INTEGER NOT NULL DEFAULT 0,+                  payloadJson TEXT NOT NULL,+                  contentHash TEXT NOT NULL+                );+                """, bind: [])+            try exec(db: db, sql: "CREATE INDEX IF NOT EXISTS idx_\(table.sql)_updatedAt ON \(table.sql)(updatedAt);", bind: [])+        }+        return try body(db)+    }++    private func query(db: OpaquePointer, table: EnvelopeTable, since: Int64) throws -> [EnvelopeRow] {+        let sql = "SELECT syncId, updatedAt, deleted, payloadJson, contentHash FROM \(table.sql) WHERE updatedAt > ? ORDER BY updatedAt;"+        var stmt: OpaquePointer?+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        sqlite3_bind_int64(stmt, 1, since)+        var rows: [EnvelopeRow] = []+        while true {+            let step = sqlite3_step(stmt)+            if step == SQLITE_ROW {+                guard let syncIdC = sqlite3_column_text(stmt, 0),+                      let payloadC = sqlite3_column_text(stmt, 3),+                      let hashC = sqlite3_column_text(stmt, 4) else {+                    throw EnvelopeIPCError.unhealthyRead("null column in \(table.rawValue)")+                }+                rows.append(EnvelopeRow(+                    syncId: String(cString: syncIdC),+                    updatedAt: sqlite3_column_int64(stmt, 1),+                    deleted: sqlite3_column_int(stmt, 2) != 0,+                    payloadJson: String(cString: payloadC),+                    contentHash: String(cString: hashC)+                ))+            } else if step == SQLITE_DONE {+                break+            } else {+                throw EnvelopeIPCError.unhealthyRead(String(cString: sqlite3_errmsg(db)))+            }+        }+        return rows+    }++    /// Idempotent upsert keyed on `syncId`; preserves pulled timestamps+    /// (stores `updatedAt` verbatim — no rewriting). Batched in one+    /// transaction.+    private func upsert(db: OpaquePointer, table: EnvelopeTable, rows: [EnvelopeRow]) throws {+        try exec(db: db, sql: "BEGIN IMMEDIATE;", bind: [])+        do {+            for row in rows {+                try upsertOne(db: db, table: table, row: row)+            }+            try exec(db: db, sql: "COMMIT;", bind: [])+        } catch {+            try? exec(db: db, sql: "ROLLBACK;", bind: [])+            throw error+        }+    }++    /// Single-row upsert. Factored out (not inlined in the loop) so the+    /// statement `defer`-finalize runs per row — `defer` inside a `for` body+    /// would pile up until function return and leak statements.+    private func upsertOne(db: OpaquePointer, table: EnvelopeTable, row: EnvelopeRow) throws {+        var stmt: OpaquePointer?+        let sql = "INSERT INTO \(table.sql)(syncId, updatedAt, deleted, payloadJson, contentHash) VALUES (?, ?, ?, ?, ?) ON CONFLICT(syncId) DO UPDATE SET updatedAt = excluded.updatedAt, deleted = excluded.deleted, payloadJson = excluded.payloadJson, contentHash = excluded.contentHash;"+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        sqlite3_bind_text(stmt, 1, row.syncId, -1, SQLITE_TRANSIENT)+        sqlite3_bind_int64(stmt, 2, row.updatedAt)+        sqlite3_bind_int(stmt, 3, row.deleted ? 1 : 0)+        sqlite3_bind_text(stmt, 4, row.payloadJson, -1, SQLITE_TRANSIENT)+        sqlite3_bind_text(stmt, 5, row.contentHash, -1, SQLITE_TRANSIENT)+        guard sqlite3_step(stmt) == SQLITE_DONE else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+    }++    @discardableResult+    private func exec(db: OpaquePointer, sql: String, bind: [String]) throws -> Int {+        var stmt: OpaquePointer?+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        for (i, value) in bind.enumerated() {+            sqlite3_bind_text(stmt, Int32(i + 1), value, -1, SQLITE_TRANSIENT)+        }+        guard sqlite3_step(stmt) == SQLITE_DONE else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        return Int(sqlite3_changes(db))+    }++    /// Tombstone update with an int64 timestamp bind (soft-delete tables).+    private func execTombstone(db: OpaquePointer, table: EnvelopeTable, syncId: String, now: Int64) throws {+        let sql = "UPDATE \(table.sql) SET deleted = 1, updatedAt = ? WHERE syncId = ?;"+        var stmt: OpaquePointer?+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        sqlite3_bind_int64(stmt, 1, now)+        sqlite3_bind_text(stmt, 2, syncId, -1, SQLITE_TRANSIENT)+        guard sqlite3_step(stmt) == SQLITE_DONE else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+    }++    /// Steps a row-returning PRAGMA to completion (e.g. `journal_mode`).+    /// Any step result other than ROW/DONE is an unhealthy read.+    private func queryPragma(db: OpaquePointer, sql: String) throws {+        var stmt: OpaquePointer?+        guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {+            throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))+        }+        defer { sqlite3_finalize(stmt) }+        while true {+            switch sqlite3_step(stmt) {+            case SQLITE_ROW: continue+            case SQLITE_DONE: return+            default: throw EnvelopeIPCError.unhealthyRead(String(cString: sqlite3_errmsg(db)))+            }+        }+    }++    // MARK: - Coordination++    private func coordinateReading(url: URL, _ body: () -> Void) throws {+        var error: NSError?+        coordinator.coordinate(readingItemAt: url, options: [], error: &error, byAccessor: { _ in body() })+        // A coordination failure is an unhealthy read — NEVER fold as empty.+        if let error {+            throw EnvelopeIPCError.unhealthyRead("NSFileCoordinator read failed: \(error)")+        }+    }++    private func coordinateWriting(url: URL, _ body: () -> Void) throws {+        var error: NSError?+        coordinator.coordinate(writingItemAt: url, options: [], error: &error, byAccessor: { _ in body() })+        if let error {+            throw EnvelopeIPCError.unhealthyRead("NSFileCoordinator write failed: \(error)")+        }+    }+}++private extension EnvelopeTable {+    /// Allowlisted table names — never interpolate raw strings into SQL.+    var sql: String { rawValue }+}++// SQLITE_TRANSIENT helper (macro, not imported from the module map).+private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
apple/Shared/EverysyncCoreCrypto.swift
diff --git a/apple/Shared/EverysyncCoreCrypto.swift b/apple/Shared/EverysyncCoreCrypto.swiftnew file mode 100644index 0000000000..98010d2a53--- /dev/null+++ b/apple/Shared/EverysyncCoreCrypto.swift@@ -0,0 +1,91 @@+// EverySync Apple shells — CryptoKit AES-GCM bridge (fills the Rust AES gap).+//+// The shared Rust crate (`e2ee_pqc`) has NO AES entry points — AES-GCM lives+// in Kotlin/Swift on every target (JCE on Android/JVM, CryptoKit here).+// Do NOT add AES to Rust.+//+// Layout contract (byte-identical to the JCE `AesGcm` actual + `Crypto.kt`):+//   encrypt output = [12B random nonce] + [ciphertext] + [16B tag]+//   (CryptoKit `AES.GCM.SealedBox.combined` layout is+//   [nonce][ciphertext][tag] — the SAME bytes. Pass `combined` through+//   verbatim; no re-framing.)+// Key size: 256-bit (32B), from `AesGcm.newContentKey` (Kotlin side, backed+// by `SecRandomCopyBytes` per `IOS_ACTUALS_NOTES.md`).+//+// Wiring: the Kotlin `AesGcm` actual calls these C functions via cinterop+// (see `../XCFramework/e2eePqc.def` — same module as the 10 PQC fns).+// Swift never calls Rust directly — only via the shared XCFramework, and the+// XCFramework never calls Swift except through this C bridge.+//+// MAC-CHECK (needs xcodebuild on a Mac):+// - `CryptoKit` import + `AES.GCM` availability (iOS 13+; deployment target+//   must be >= 13 — set in the Xcode project on the Mac).+// - `@_cdecl` symbol names match the cinterop header exactly.++import CryptoKit+import Foundation++/// Encrypts `plaintext` under 256-bit `key`. Returns+/// `[12B nonce][ciphertext][16B tag]`, or nil on any failure (caller treats+/// nil as a crypto failure, never as empty plaintext).+@_cdecl("everysync_aes_gcm_encrypt")+public func everysyncAESGCMEncrypt(+    keyPtr: UnsafePointer<UInt8>?, keyLen: Int,+    ptPtr: UnsafePointer<UInt8>?, ptLen: Int,+    outPtr: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>?,+    outLen: UnsafeMutablePointer<Int>?+) -> Int32 {+    guard let keyPtr, let ptPtr, let outPtr, let outLen,+          keyLen == 32, ptLen >= 0 else { return 0 }+    do {+        let key = SymmetricKey(data: Data(bytes: keyPtr, count: keyLen))+        let sealed = try AES.GCM.seal(Data(bytes: ptPtr, count: ptLen), using: key)+        guard let combined = sealed.combined else { return 0 }+        let bytes = [UInt8](combined)+        let out = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)+        out.initialize(from: bytes, count: bytes.count)+        outPtr.pointee = out+        outLen.pointee = bytes.count+        return 1+    } catch {+        return 0+    }+}++/// Decrypts `combined` ([nonce][ciphertext][tag]) under 256-bit `key`.+/// Returns plaintext bytes, or nil on any failure (wrong key, tampered tag,+/// malformed input). Callers (relay envelope pulls) count undecryptables and+/// keep the cycle — they never fold a crypto failure as an empty log.+@_cdecl("everysync_aes_gcm_decrypt")+public func everysyncAESGCMDecrypt(+    keyPtr: UnsafePointer<UInt8>?, keyLen: Int,+    ctPtr: UnsafePointer<UInt8>?, ctLen: Int,+    outPtr: UnsafeMutablePointer<UnsafeMutablePointer<UInt8>?>?,+    outLen: UnsafeMutablePointer<Int>?+) -> Int32 {+    guard let keyPtr, let ctPtr, let outPtr, let outLen,+          keyLen == 32, ctLen > 12 + 16 else { return 0 }+    do {+        let key = SymmetricKey(data: Data(bytes: keyPtr, count: keyLen))+        let box = try AES.GCM.SealedBox(combined: Data(bytes: ctPtr, count: ctLen))+        let plain = try AES.GCM.open(box, using: key)+        let bytes = [UInt8](plain)+        let out = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)+        out.initialize(from: bytes, count: bytes.count)+        outPtr.pointee = out+        outLen.pointee = bytes.count+        return 1+    } catch {+        return 0+    }+}++/// Frees a buffer returned by the two functions above. The Kotlin cinterop+/// actual MUST copy the bytes first, then call this (same discipline as+/// Rust `pqc_free`: every `*mut u8 + len` out-param buffer is caller-freed).+@_cdecl("everysync_crypto_free")+public func everysyncCryptoFree(ptr: UnsafeMutablePointer<UInt8>?, len: Int) {+    guard let ptr, len > 0 else { return }+    ptr.deinitialize(count: len)+    ptr.deallocate()+}
apple/Shared/KeychainSecureStore.swift
diff --git a/apple/Shared/KeychainSecureStore.swift b/apple/Shared/KeychainSecureStore.swiftnew file mode 100644index 0000000000..70d279fc82--- /dev/null+++ b/apple/Shared/KeychainSecureStore.swift@@ -0,0 +1,68 @@+// EverySync Apple shells — Keychain-backed `SecureStore` notes.+//+// The KMP `SecureStore` interface (`platform/Platform.kt`: `getBytes /+// `setBytes(onlyIfAbsent)` / `delete` / `getString` / `setString` / `getLong` /+// `setLong`) is implemented in KOTLIN (`IOS_ACTUALS_NOTES.md`), not here.+// This file documents the exact Keychain contract the Kotlin actual must+// implement so all three apps + extensions agree on one layout.+//+// DO NOT re-implement `SecureStore` in Swift. Swift calls the XCFramework's+// `SecureStore` (backed by Keychain per this contract); vault AES keys never+// appear in Swift values, logs, or share links.+//+// Keychain layout contract (all entries `kSecClassGenericPassword`):+// - Service: `com.vayunmathur.everysync.securestore`+// - Account: the `SecureStore` key verbatim (e.g. `personalKemPriv`,+//   `relay_cursor:todos:<vault>:todos:<vault>`, `personalDeviceId`).+// - Value: `kSecValueData` = raw bytes (strings UTF-8, longs big-endian Int64).+// - Access group: `$(AppIdentifierPrefix)com.vayunmathur.everysync.shared`+//   so the main apps + Credential Provider + Share extension share one store.+// - Accessibility: `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`+//   (no iCloud sync — relay keys never leave the device except via+//   PQC-sealed inbox invites).+//+// Semantics mirror `MemorySecureStore` + the Android KeyStore actual:+// - `get*` returns nil when absent (absence is NOT an error).+// - `set*(onlyIfAbsent: true)` is atomic: check-then-add must hold the+//   Keychain entry (Kotlin serializes with a mutex, same as `MemorySecureStore`).+// - `delete` removes bytes+strings+longs rows for the name (single Keychain+//   item per name here, so one `SecItemDelete`).+// - `getLong` decodes 8-byte big-endian; malformed data returns nil (caller+//   treats as absent, same as the relay-cursor default 0).+//+// Key-hygiene invariant (verbatim): vault keys never user-visible. Share links+// carry ids only (`RelayLinks.shareLinkFor`); keys move exclusively via+// PQC-sealed inbox invites (`inbox:<deviceId>`). `RelayCursorStore` keys+// (`relay_cursor:<type>:<vault>:<channel>`) live here, NOT in the IPC tables.++import Foundation+import Security++/// Compile-time documentation of the Keychain layout. No instances: the live+/// implementation is the Kotlin `SecureStore` actual in the XCFramework.+public enum KeychainSecureStoreContract {+    public static let service = "com.vayunmathur.everysync.securestore"+    public static let accessGroup = "com.vayunmathur.everysync.shared"++    /// Keys the transport bootstrap writes (see `SharedRelayTransport.init`):+    /// PQC identity (`personalKemPub/Priv`, `personalDsaPub/Priv`) + stable+    /// device id (`personalDeviceId`). `onlyIfAbsent` on first write wins+    /// concurrent races — re-read after write, exactly like+    /// `PqcIdentityHandle.loadOrCreate`.+    public static let identityKeys = [+        "personalDeviceId",+        "personalKemPub", "personalKemPriv",+        "personalDsaPub", "personalDsaPriv",+    ]++    /// Longs are 8-byte big-endian (matches `RelayCursorStore` via `setLong`).+    public static func encodeLong(_ value: Int64) -> Data {+        var bigEndian = value.bigEndian+        return Data(bytes: &bigEndian, count: MemoryLayout<Int64>.size)+    }++    public static func decodeLong(_ data: Data) -> Int64? {+        guard data.count == MemoryLayout<Int64>.size else { return nil }+        return data.withUnsafeBytes { $0.load(as: Int64.self).bigEndian }+    }+}
apple/XCFramework/BUILD_NOTES.md
diff --git a/apple/XCFramework/BUILD_NOTES.md b/apple/XCFramework/BUILD_NOTES.mdnew file mode 100644index 0000000000..4659fd0e4f--- /dev/null+++ b/apple/XCFramework/BUILD_NOTES.md@@ -0,0 +1,87 @@+# XCFramework build — `EverysyncCore.xcframework` (Phase 3, Mac only)++Builds the shared KMP core (`library/everysync-core`) as an XCFramework with+the `iosArm64 + iosSimulatorArm64` slices, linked against the Rust `e2ee_pqc`+static lib for the 10 PQC cinterop functions. Swift never calls Rust directly+— only via this XCFramework.++> Requires macOS + Xcode. This directory holds the script + interface docs;+> nothing here runs on the Windows box. Verified by inspection only.++## Prerequisites (Mac)++- Xcode 15+ with iOS 17 SDK (`xcode-select -p` points at it).+- Rust targets: `rustup target add aarch64-apple-ios aarch64-apple-ios-sim`+  (simulator slice is ARM64-only — no Intel slice; Rosetta fallback is out+  of scope for Phase 3).+- `cbindgen` (`cargo install cbindgen`) — generates `e2ee_pqc.h` from+  `library/e2ee-p2p/src/main/rust/src/c_bridge.rs`.+- KMP iOS plugin version == Kotlin version (see+  `gradle/libs.versions.toml`); `iosArm64 + iosSimulatorArm64` targets in+  `library/everysync-core/build.gradle.kts`.++## Steps++1. Build the Rust static lib per slice (from repo root):+   ```sh+   cargo build --target aarch64-apple-ios --release \+     --manifest-path library/e2ee-p2p/src/main/rust/Cargo.toml+   cargo build --target aarch64-apple-ios-sim --release \+     --manifest-path library/e2ee-p2p/src/main/rust/Cargo.toml+   ```+   NOTE: `IOS_PQC_NOTES.md` says `x86_64-apple-ios` for the simulator slice;+   that target is Intel-only and wrong for Apple-Silicon simulators. This doc+   uses `aarch64-apple-ios-sim` — the drift is recorded in+   `../IPC_CONTRACT.md` appendix review notes (contract semantics unaffected;+   only the build target triple changed).+2. Generate the C header (consumed by `e2eePqc.def`):+   ```sh+   cbindgen --crate e2ee-p2p --output e2ee_pqc.h \+     --config library/e2ee-p2p/src/main/rust/cbindgen.toml+   ```+   (If no `cbindgen.toml` exists, create one pinning `language = "C"`,+   `usize_is_size_t = true`, and the `pqc_` export prefix. The reference+   header `e2ee_pqc.reference.h` in this directory shows the expected 10-fn+   surface.)+3. Place `e2ee_pqc.h` in `src/nativeInterop/cinterop/e2eePqc/` next to+   `e2eePqc.def` (see `IOS_PQC_NOTES.md` for the canonical `.def` text —+   copied verbatim into `e2eePqc.def` here).+4. Build the XCFramework:+   ```sh+   ./gradlew :library:everysync-core:assembleEverysyncCoreXCFramework+   ```+   (Task name must match the KMP `XCFramework` block the Mac adds to the+   module build file in Phase 3 — confirm on the Mac.)+   Equivalent manual slice assembly (if the Gradle task is unavailable):+   ```sh+   ./gradlew :library:everysync-core:compileKotlinIosArm64 \+             :library:everysync-core:compileKotlinIosSimulatorArm64+   xcodebuild -create-xcframework \+     -library <iosArm64 .a> -headers <generated headers> \+     -library <simArm64 .a> -headers <generated headers> \+     -output EverysyncCore.xcframework+   ```+   Or run `./build_xcframework.sh` in this directory (wraps steps 1–4).+5. Link the XCFramework into the three app targets + the Credential Provider+   extension + the Share extension (all five link the SAME XCFramework —+   merge/match/TOTP stay single-sourced).+6. Re-run relay conformance from the iOS simulator against Android + desktop+   (see `../E2E_CHECKLIST.md`): register/getkey/append/pull, channel-name+   assertions, `B64(AES_GCM)` record shape, double-wrapped+   roster/epoch/transfer envelopes, PQC-sealed invite to `inbox:<device>`,+   `everysync://join` parse, plus the three invariants (null-on-failed-pull+   abort, tombstone-only delete, keys-never-visible).++## Memory discipline (matches JNA)++Every `*mut u8 + len` out-param buffer from the 10 PQC fns is `Box::into_raw`+— the Kotlin cinterop actual copies to a `ByteArray`, then calls `pqc_free`;+priv/SS bytes are zeroed via `pqc_secure_zero`. The two CryptoKit bridge fns+(`everysync_aes_gcm_encrypt/decrypt` in `../Shared/EverysyncCoreCrypto.swift`)+follow the same discipline via `everysync_crypto_free`.++## What Swift must NOT do++Re-implement merge pairing, TOTP framing/math, canonical JSON/hash, envelope+Base64/AES, role checks, or link parsing. If logic exists in Swift that also+exists in `everysync-core`, delete the Swift copy.
apple/XCFramework/IOS_ACTUALS_NOTES.md
diff --git a/apple/XCFramework/IOS_ACTUALS_NOTES.md b/apple/XCFramework/IOS_ACTUALS_NOTES.mdnew file mode 100644index 0000000000..8ec385af3e--- /dev/null+++ b/apple/XCFramework/IOS_ACTUALS_NOTES.md@@ -0,0 +1,40 @@+# iOS platform actuals — implementation notes for the Mac (Kotlin side)++The live actuals land in `library/everysync-core/src/iosMain/` on the Mac+(needs the Apple SDK — cannot compile on

Diff truncated.