Skip to content

Sukrara architecture

How the Sukrara apps are built. The rules are in CLAUDE.md, the day-to-day know-how in DEVELOPMENT.md, what the apps do in FEATURES.md.

Path What
apps/android/ the Android app (Gradle root: own settings.gradle.kts, wrapper, build-logic/)
apps/macos/ the Mac app (SwiftPM root: Package.swift, Sources/, Tests/, Bundle/)
contracts/ what every app agrees on and is tested against: alert spec + scenarios, graph fixtures + surface registry, settings schema, protocols + vectors, treatment / export / pen fixtures (README)
assets/brand/ icons and brand art for the apps and the docs
poc/ the frozen research PoC and its investigations; buildable, never changed
tools/ check/ (the rules as checks), hooks/, settings/gen.py, release/, install.sh
VERSION the one version source (0.12.0 → versionCode / CFBundleVersion 12000)
  • Android app.mauri.sukrara; Mac app.mauri.sukrara, widget app.mauri.sukrara.widget, App Group QWUV9H4A3G.app.mauri.sukrara.
  • Settings: contracts/settings/settings.json → generated SettingsSpec (Android Preferences DataStore files by area, Mac UserDefaults). Every persisted format carries a version.
  • No backwards compatibility, no migrations (the owner, 2026-11-10: “a new app and a fresh start”): a stored format of another version (a file, a typed store, the Android database, a Mac store) is not read; it starts empty. The Android database is replaced by an empty one on any version change (below). History comes back through Import history (LibreView, Tidepool or a file, deduplicated), never through a migration or a legacy reader.

Alerts (:monitor monitor/alerts/). The rules are :core:alerts (AlertMachine); the runtime only applies them.

  • AlertRuntime — the one owner of the machine per process, behind one Mutex. Inputs: hub state (role, latest reading, monitoringStartedAt, sensor), alert settings (store alerts, key alerts, SPEC §3 JSON via AlertStateStore), treatments (→ Doses), the wearer’s mirrored settings and alert events (25), this device’s actions (AlertControls in :core:model, also the notification buttons). Per input: machine → effects applied (AlertAlarm first, then AlertPresenter, AlertEventSink) → AlertRecord saved (typed store) → AlertUiState published to the hub. Every step is attempted on its own: a failure is logged to DiagLog (step + exception class) and listed in AlertUiState.failedSteps until that step works again; the alert checklist (AndroidAlertReadiness, THE answer to “may an alert not reach the person?”) reads it as AlertRequirement.AlertDelivery. Role null is ignored (setup / hub loading); monitoringStartedAt == null switches no_data off.
  • Alarms: one AndroidAlarms (monitor/service/) sets every alarm (health check, freshness step, alert check, sensor end) through AlarmPolicy: protective checks setExactAndAllowWhileIdle (72 / h Doze quota with USE_EXACT_ALARM; inexact while-idle if exact alarms are refused), never setAlarmClock (it would become the phone’s “next alarm”).
  • AlertCheckReceiver (the exact alarms only) → AlertsModule.check() (runtime.tick() from the saved record with the service dead, then sensorEnd.check(), each on its own) → MonitorRestarter.restart() (10’s starter). Boot, update, clock / zone change reach the same check through BootReceiver, which starts the service once. AlertActionReceiver (Mute… / Change time direct reply, Remind less / as usual, Unmute, swipe tidy). All non-exported, through one runAsync (goAsync, 9 s budget).
  • AlertNotifier + AlertChannels (alert.<kind> / alert_alarm.<kind>) + NotificationGroups (notify/: the alerts and info notification groups with summaries; every alerting notification of the app belongs to one) + AlertSoundProvider (${applicationId}.alertsound, exported read-only for System UI) + AlertHaptics.
  • SensorEndNotifier (monitor/sensorend/): SensorEndPlan (pure) + its own exact alarm.
  • AlertsModule (A4) wires it; the Application implements AlertsHost so receivers and the provider reach it (awaitAlerts(): null before the first unlock on a phone that doesn’t monitor then); the monitoring service calls attach(scope).

Before the first unlock after a restart (docs/30, #160). MonitoringService, HealthCheckReceiver, AlertCheckReceiver, AlertActionReceiver, LockedBootReceiver and AlertSoundProvider are direct-boot aware (ManifestTest pins the list). App builds AppGraph at once; before the unlock only its device-protected part runs (monitorReady: the role, the hub; then the sensor source, the monitor and the alert runtime), and only on the wearer’s phone reading its own sensor (monitorsLocked): LockedBootReceiver asks the graph at LOCKED_BOOT_COMPLETED and starts monitoring as BootReceiver does after an unlock, or falls back to the LockedBootPlan notice and No data alarm (a follower, Juggluco, nothing paired). The graph’s credential-encrypted inputs to those modules (treatments, the owner engine’s sharing line and alert events, the follower engine) wait behind AppGraph.whenUnlocked; FollowerSettingsBridge reads the follower-only follower.settingsFrom (store sharing) only on a follower. At ACTION_USER_UNLOCKED (App) DataModule.unlock() merges the readings taken before it into the history and opens the rest (AppGraph.unlocked), ready loads it (root status bar, widgets, integrations, sharing…); the service, the hub, the source and the alert runtime are the same objects before and after. Notifications resolve the app’s activities with AppActivities (direct-boot-unaware matches included: a plain lookup before the unlock finds none).

Root status bar (:monitor monitor/systemui/). In every build: MonitorModule builds SystemUiRoot (SystemAccess and RootStatusBar, started in readyUnlocked()), no flavor seam. RootStatusBar follows the hub, SurfaceSettings.Root*, the ranges and the freshness ticks; conflated on one background thread it (1) sends HookState to System UI (${applicationId}.SYSTEMUI_STATE, signature permission …permission.SYSTEMUI_STATE, sender identity shared) and (2) drives SlotDaemon (su + app_process, line protocol DaemonProtocol, own slots sukrara_glucose*, drawables sb_* from tools/android/gen-slot-drawables.swift, kept by res/raw/keep_status_icons.xml and consumer-rules.pro). SystemUiHook is the LSPosed module in the same APK (src/main/resources/META-INF/xposed, libxposed API compileOnly); its pure parts are HookText, IconFit, SlotIcons, and for the lock-screen widget LockGeometry, sceneAlpha, LockTouches (LockWidgetHost: System UI’s AppWidgetHost hosting :widgets’ LockWidgetReceiver, named in :core:model LockWidgetLink). Its hello reaches HookHelloReceiver (permission STATUS_BAR_SERVICE: only System UI). SystemAccess (root via su, LSPosed via the libxposed service, the hello’s HookCode.VERSION) implements :core:model’s SystemAccessPort for Settings › Status bar and › Lock screen. The same HookState carries SurfaceSettings.LockWidget*; StateGate sends it only while a feature needs it.

:update is a dependency of the full flavor only (app/build.gradle.kts fullImplementation), so the Google Play build has none of it: no classes, no UpdateReceiver, no REQUEST_INSTALL_PACKAGES / UPDATE_PACKAGES_WITHOUT_USER_ACTION (ManifestTest, verify-apk.sh --play). Store (app/src/full) builds UpdateModule from the graph (UpdatePorts: version, OkHttp, the update typed store, the update.* settings, the alert hold, the notification ports of :monitor’s Channels.UPDATES / NotificationIds.UPDATE in the info group); App.onCreate starts it, so its workers and receiver find it (UpdateModule.current). Settings › About sees it as the AppUpdates port of :core:model (null in the Play build).

  • Pure: Releases (List-releases JSON → Release + its ApkAsset: Sukrara-<version>.apk, GitHub’s sha256: digest, size, only under the endpoint’s download prefix; version compare; drafts and prereleases, release candidates, skipped), ApkCheck.verify (hash, the one signer = UpdateEndpoint.RELEASE_CERT = tools/release/android-cert.sha256, package, newer), InstallGate (no install while AlertHold isn’t quiet; silent only when automatic and installs are allowed), UpdateEndpoint (GitHub, or a debug build’s local test server from BuildVariant.updateServer).
  • Android: Downloader (https on every hop, size-capped, hashed while streaming, .part then rename), ApkCheck.facts (PackageManager.getPackageArchiveInfo with signing certificates), Installer (a PackageInstaller session; status to UpdateReceiver), UpdateNotifier (channel App updates, low importance), UpdateCheckWorker (daily, while update.automaticChecks) and UpdateInstallWorker (one at a time; a held install retries with WorkManager’s backoff), UpdateReceiver (the notification’s buttons, the session status, MY_PACKAGE_REPLACED: cleans up; :monitor’s BootReceiver restarts monitoring from the same broadcast).
  • AlertHolds (:monitor): what an install waits for, from the alert runtime’s saved AlertState (episodes whose notification is up, a very low that is on, a follower’s mirrored alerts) and the hub’s live firingKinds.

First-run setup and wearer sharing screens: :feature:sharing (package app.mauri.sukrara.feature.sharing).

  • setup/SetupMachine (pure): the binding step order, what completes / skips each step, the Finish-setup items, and the history step (Bring your history back, wearer, last, offered once: historyDue; SetupModule.offerHistoryAgain after DataModule.databaseReplaced; the app opens it on its own at launch when due). SetupRecord persists in the typed store setup; the role is a separate store owned by AppGraph (RoleStore).
  • setup/RestoreGate (pure): restore only with a live own-sensor reading (≤ 15 min, Libre 3 / Juggluco).
  • :monitor’s AndroidAlertReadiness implements :core:model’s AlertReadinessSource (the checklist setup, home and Settings › Alert reliability show).
  • Ports from the app: OwnerSharing (adapter EngineOwnerSharing over :share’s OwnerEngine), AlertSettingsAccess (the alert settings store), RoleStore, resetAlerts (AlertsModule.reset, on a role change only — at the identity step the sensor already runs and a reset would pause alerts), the alert channel ids.
  • SetupModule is composed by AppGraph (SharingDeps.setup) over shareOwner’s engine (started for a wearer by followRole); screens get callbacks for other features (the sensor flow) instead of depending on them.
  • share/ (share screen, Settings › Sharing, ApproveHost — the approve dialog the app draws over its navigation, LaterRequests in SetupModule — ProfilePage, BackupPage, InviteHereScreen), followers/, profile/ (ProfileEditor), backup/ (BackupScreen, PasswordManager = Credential Manager). All actions go through SharingViewModel → OwnerSharing; the identity secret reaches only PasswordManager.save (inside OwnerEngine.saveToPasswordManager) and the recovery dialog (secure window, never saved state).
  • Pictures: :core:designsystem avatar/AvatarDrawing (pure v1 geometry, tested against contracts/protocol/identity/avatar-v1.json) + AvatarImage (Compose Canvas); every face in the app goes through it.

Widgets: :widgets (Glance). WidgetsModule (one line in AppGraph; the Application is its WidgetsHost) combines the hub’s state, treatments, GraphConfig, per-placement WidgetOverrides and monitor’s freshness ticks in WidgetUpdater, which publishes a WidgetFrame and calls GlanceAppWidget.update per placed id when the draw key changes (screen on only). Each CardWidget composes that frame at LocalSize through renderWidget → GlucoseCard.draw with widgetCardStyle (in :core:graph, shared with CardLayoutTest) and cardModelOf (GlucoseState → CardModel). The lock-screen widget (LockWidget, hosted by System UI’s module) composes the same frame through renderLockWidget (lockWidgetCardStyle, lockWidgetBoxes), updated by the ids it keeps in WidgetPlacements.lock (the system doesn’t list them).

Settings pages: :settingslib-spa + :core:designsystem rows/. :settingslib-spa is AOSP SettingsLib SPA (frameworks/base/packages/SettingsLib/Spa/spa, android17-release), the code the stock Settings app draws its Compose pages with, vendored as upstream wrote it (Apache-2.0 headers, its NOTICE lists every change; no Sukrara convention plugin, so no GPL header or ktlint on it; tools/check allow.json vendored). Pages never call it for rows: the one row layer in :core:designsystem does (SettingsScaffoldPage = SettingsScaffold in SettingsTheme, SettingsGroup = Category with a heading title, SwitchRow / SplitSwitchRow / MainSwitchRow / NavigationRow / ValueRow / RadioRow / CheckboxRow / FooterText / SettingsIntro / SectionButton / NumberButton, SettingsBannerCard, the ChoiceDialog / NumberDialog on SPA’s SettingsDialog). :feature:settings’ SettingsPage (also what the app puts around other features’ pages) is that scaffold; a glucose card inside a page is drawn in SukraraTheme.

The one card renderer: :core:graph (package app.mauri.sukrara.graph, flat so tools/check card-api matches the api names in contracts/graph/surfaces/surfaces.json).

  • Entry points. GlucoseCard.draw(canvas, w, h, model, style, palette, d, surface, part) lays out and paints a CardPart (whole card, header, value, slots, chart) and returns a CardLayout (every element’s name, box and what it shows: what the layout tests read). GlucoseCard.image draws into a bitmap (widgets, notification, lock screen). GlucoseCard.face gives text / icon places the value, trend mark and freshness step (GlucoseLook). A11y builds the screen-reader sentence from the same decisions.
  • Inputs, no app state. CardModel = readings (GlucosePoint), treatments, nowS, CardWords, CardStatus, MuteRule?, SensorInfo?, countdown hours and an optional metricsOf cache. CardStyle / GraphStyle come from the surface and its place’s GraphConfig (built by the settings repository from the schema keys; GraphConfig is a plain data class, not a JSON blob). The renderer depends only on :core:model (with the generated SettingsSpec) and :core:data’s schema settings keys (GraphSettings): no :core:alerts, no :monitor.
  • Status from outside. The alert runtime maps its AlertStatus to CardStatus (:core:model: None / Needed / Taken / Paused / Muted) and publishes it in the hub’s AlertUiState.status, which every card surface (app panel, widgets) passes to the renderer; it also supplies the MuteRule (when a treatment’s mute ends, from the alert settings). The renderer only draws them (badge, last-treatment slot, mute lines).
  • Words. CardWords.of(resources) once per Resources (en + es strings of the module); durations through the one formatter core.model.Durations with the duration_* strings.
  • Tests (./gradlew :core:graph:testDebugUnitTest): GraphFixtureTest (contracts/graph share, mark, sensor, place, labels, status), FreshnessFixtureTest, ClockTest, DurationsTest (contracts/settings/durations.json, en + es), A11ySentenceTest, CardLayoutTest (contracts/graph/layout rules and expect.json over stand-ins for the registered card surfaces until their code lands) and the Roborazzi goldens in core/graph/src/test/snapshots (synthetic data, UTC, en-US; recorded on CI by .github/workflows/goldens.yml, since macOS renders text a little differently: locally compareRoborazziDebug).

Screens: :app SukraraNavigation + :core:designsystem motion/ScreenHost. The back stack is Navigation 3’s (rememberNavBackStack, one NavKey per screen; rememberDecoratedNavEntries gives each entry its saved state and view models). ScreenHost draws it, not Navigation 3’s NavDisplay: one page at rest, two while moving, each in a fixed slot so no page is composed again mid-move; it owns Back and the predictive back gesture (pages’ own back handlers, composed inside, come first) and gives each page a lifecycle that is RESUMED only at rest. How a screen moves is its ScreenMotion (Page or FadeThrough), named per route by screenMotion in :app; every number is in ScreenMoves (pure, tested). NavDisplay was dropped because its predictive back scrubs one seekable transition with the gesture’s progress, which can’t draw the system’s two-phase cross-activity back (preview, then a full 450 ms finish), and its default was a 700 ms cross-fade.

One SwiftPM package (swift-tools 6.2, Swift 6 language mode, macOS 15, arm64). Build, test and bundle commands: apps/macos/README.md.

Sukrara (exe, GitHub version) ─► SukraraUpdater ─► Sparkle 2.10.1 (prebuilt framework)
└─► SukraraApp ─► SukraraCore, SukraraGraph, SukraraAlerts, SukraraShare ─► NostrSDK 0.45.1
SukraraAppStore (exe, App Store version) ─► SukraraApp (no updater)
SukraraWidget (exe, appex) ─► SukraraCore, SukraraGraph (extension-safe only)
sukrara-snap (exe, debug) ─► SukraraApp
Tests: CoreTests GraphTests AlertsTests ShareTests AppTests ─► SukraraTesting (fakes, Contracts.url)
  • SukraraCore, SukraraGraph: nonisolated, compiled with -application-extension so the widget can link them.
  • SukraraApp, SukraraUpdater, Sukrara, SukraraAppStore, sukrara-snap, AppTests: .defaultIsolation(MainActor.self) + NonisolatedNonsendingByDefault + InferIsolatedConformances. Background work goes into actors / @concurrent.
  • SukraraAlerts is pure (no UI, no I/O); SukraraShare keeps every transport behind a protocol.
  • The updater (#91): SukraraApp knows only UpdaterEngine and the Updates model (the panel’s reminder, About’s button and switches); SukraraUpdater implements it with Sparkle (SparkleUpdater, gentle reminders). Only the Sukrara executable links it (AppMain.run(updater:)); the App Store executable passes nil, so its binary has no Sparkle at all. AppServices creates the updater only when the launch plan allows .updater (the installed GitHub version).

The widget extension: built by SwiftPM, wrapped by Bundle/bundle.sh

Section titled “The widget extension: built by SwiftPM, wrapped by Bundle/bundle.sh”

Decision: SwiftPM executable target + bundle script, no Xcode project. SukraraWidget is linked with -application-extension -e _NSExtensionMain -u _main: Xcode links extensions with Foundation’s _NSExtensionMain entry point (the Swift main traps in ExtensionFoundation, docs/13), and -u _main keeps the @main WidgetBundle, which nothing else references, from being dead-stripped in release builds (xtool-org/xtool#313). Checked on the release binary: LC_MAIN points at the _NSExtensionMain stub, the widget’s code and kinds are present, pluginkit -a registers app.mauri.sukrara.widget and chronod adds it (“Added extensions: … app.mauri.sukrara.widget, version: 12000”). chronod purges dev copies outside an Applications folder, so the live widget gallery is checked after tools/install.sh mac. Fallback if it ever stops loading: the PoC’s proven raw swiftc command (poc/spikes/menubar/bundle.sh), same flags.

Bundle/bundle.sh assembles build/Sukrara.app (+ Contents/PlugIns/SukraraWidget.appex) from Bundle/Info.plist.in, Bundle/Widget-Info.plist.in and the entitlement templates, version from <repo>/VERSION (CFBundleVersion = versionCode, --dev appends .<yyMMddHHmm>), and signs inside-out with an identity of team QWUV9H4A3G (hardened runtime; the app is not sandboxed, the widget is; both share the App Group). With the provisioning profiles in ~/.apple-dev/profiles (Developer ID) it embeds them and signs with app-profile.entitlements.in / widget-profile.entitlements.in: Time Sensitive, keychain-access-groups, Associated Domains; without them, with the Apple Development identity and app.entitlements.in / widget.entitlements.in. The app reads what it got at launch (Entitlements.current: alarms’ interruption level, which keychain, universal links). --unsigned signs ad hoc for CI (without the hardened runtime, whose library validation needs a Team ID to load Sparkle). The GitHub version gets Sparkle.framework in Contents/Frameworks (signed inside-out: its XPC services, Autoupdate, Updater.app, then the framework; the rpaths SwiftPM adds for its build folders are removed) and Bundle/sparkle.plist (feed, EdDSA public key) merged into its Info.plist; --app-store builds SukraraAppStore and checks nothing of Sparkle is in it. Bundle/dmg.sh makes the dmg and zip.

All in SukraraCore (SukraraIDs, SukraraPaths): bundle app.mauri.sukrara, widget app.mauri.sukrara.widget, App Group QWUV9H4A3G.app.mauri.sukrara (Info key SukraraAppGroup), Keychain service app.mauri.sukrara, defaults = the standard domain with schema keys, URL scheme sukrara, widget kinds app.mauri.sukrara.widget.{value,graph,combined}, ~/Library/Application Support/app.mauri.sukrara/, ~/Library/Logs/app.mauri.sukrara/ (1 MB × 2), ~/Library/Sounds/app.mauri.sukrara.<name>.caf, App Group snapshot glucose.json (path only from SukraraPaths.appGroupSnapshot(), i.e. the system’s group container).

SukraraApp/Launch/LaunchMode.swift, pure and covered by AppTests/LaunchModeTests:

  • LaunchPlan.parse(args, build:, env:, home:, exists:) throws(LaunchError) -> LaunchPlan (mode + services + data). Arguments other than -psn_… → exit 2. A dev build (debug build, bare executable, or a bundle inside a git checkout) → exit 3 unless SUKRARA_DEV=1; with it: ServicesPlan.none (so no updater either) and DataScope.isolated (separate home SUKRARA_DEV_HOME or …/Application Support/app.mauri.sukrara.dev, Keychain service and defaults suite app.mauri.sukrara.dev). A refused launch writes stderr + os_log and, when started by LaunchServices, shows an alert (never a silent exit).
  • LaunchPlan.snapshot(request, build:, scratch:): only for sukrara-snap (the only snapshot path), debug only, no services, isolated data.
  • ServicesPlan is an upper limit: the app ANDs it with the user’s settings (limited(by:)) and starts services only through ServicesPlan.start(using: some ServiceStarting). The app’s ServiceStarting is the only code that creates a Bluetooth central, relay pool, alert engine, widget feed, notification request or the Juggluco source (lan), and the only place that may hand out the Mac’s camera (camera: SystemCamera for the follow step’s QR scanner, which runs the capture session only while the scanner is on screen). A dev, fixture or snapshot run never gets it: a debug run’s scanner reads the made-up SyntheticCamera feed, a release dev copy says it doesn’t use the camera.

Android’s launch gate for relays is app/…/LaunchPlan.kt (pure, LaunchPlanTest): LaunchPlan.of(debugBuild, relayChoice) gives the launch’s RelayAccess, which every RelayPool applies to the relays the protocol names (ShareOwnerModule, FollowerModule). Release builds: Public (the wss:// relays named), whatever else is passed. Debug builds: Off (no relay) unless the debug RELAYS command (src/debug DebugRelays, read through BuildVariant.relayChoice) chose public or local URLs (Local: every pool goes only there, ws:// allowed; the debug build’s network security config adds cleartext to 10.0.2.2). The local test relay is tools/relay/relay.py.

Test fixtures: Contracts.url("alerts/scenarios") (SukraraTesting) resolves SUKRARA_CONTRACTS or walks up from the test source to contracts/.

Mac share (apps/macos/Sources/SukraraShare)

Section titled “Mac share (apps/macos/Sources/SukraraShare)”
FollowerSession (pure struct) ──receive(event, now)──► Outcome { verdict, deltas, publish, resubscribe }
│ uses ▲
▼ │ events (relays or BLE, same rules)
NostrCrypto (protocol) ◄── NostrSDKCrypto RelayTransport (protocol) ◄── RelayPool (actor) ── WebSocketFactory
(only file importing NostrSDK 0.45.1) ◄── FakeRelay (SukraraTesting)
  • Protocol/ — Wire (kinds, TTLs, tag derivations, match code, Wire.defaultRelays = the only wss:// hosts), Derive (HKDF invite key, CryptoKit), SignedEvent (NIP-01 JSON; engines never see NostrSDK types), SecretKeyHex (redacted in description, debugDescription and Mirror), typed payload decoders with the reference’s strict rules (Payloads.swift), Profile/Avatar (wire + v1 normalisation; drawing is UI), InviteLink + InviteOpener (v3 short link, fingerprint / expiry checks), FollowerMessages (request, profile, rekey, history gift wraps with absolute expiration; writer treatment events).
  • Follower/ — FollowerSession: port of poc/spec/reference/ogs/follower.py plus the settings rule; verdict strings are the OGS vector codes shared with Android’s StreamFollower. FollowerState (v 1) holds F, the read keys, roster, writer-scope records (creator, held (u, o) per treatment id), settings u, sensor/roster ordering and recent alert keys: everything trust depends on, so a restart can’t be used to slip a forged entry in. It is stored in the Keychain (service app.mauri.sukrara, account follower). Readings/treatments go out as deltas to 15’s stores. Unfollow = discard the state.
  • Relay/ — RelayPool actor: socket per wss:// relay, jittered backoff 2 s→5 min, subscriptions (deduped by filter) and a 1 h outbox re-sent on reconnect, NIP-42 AUTH as the pool’s key (F, or the invite key for an invite lookup pool), EOSE/OK/CLOSED/connection status on a single-consumer inbound stream, ping at 150 s silence, reconnect at 270 s. It does not dedupe events (the session does; an unknown-epoch event must be re-processable).
  • Tests (ShareTests): OGS vectors (derivations, every event verifies/opens, 27-step acceptance scenario, invite checks, treatment payloads), identity vectors, profile fixture, contracts/protocol/sync/*.json (made by the Android tests: Mac passes them unchanged → both followers agree), fake-relay end-to-end, RelayPool over scripted sockets. Nothing opens a network connection.

Mac runtime (follower, stores, nearby, widget feed)

Section titled “Mac runtime (follower, stores, nearby, widget feed)”
AppModel (21, @MainActor) ── snapshots()/alerts() ──► FollowerService (protocol) ◄── FollowerRuntime (actor)
│ owns
FollowerSession ◄─ receive ─┬─ RelayLink (RelayPool | FakeRelay) KeychainStore (SecretStoring)
└─ NearbyTransport (NearbyCentral | fake) ─ NearbyLink (pure BLE protocol)
stores: ReadingsFileStore · TreatmentFileStore · SensorStateStore · WearerSettingsStore (actors)
WidgetFeed (SukraraApp) ── glucose.json in the App Group + WidgetReloadPolicy (≤ 1 value reload / 5 min)
└──► SukraraWidget.appex: SnapshotProvider (reads only glucose.json) → WidgetTimeline → WidgetEntryView
  • Widget reloads: the reload budget is about 40–70 a day, so the app never reloads per reading or per minute. WidgetReloadPolicy reloads all three kinds when the shown state changes (at once) or the shown value changes (at most once per 5 min; a deferred reload carries the last value). Ageing needs no reload: WidgetTimeline (SukraraGraph, pure, TimelineTests) gives the timeline an entry at each future freshness step, mute end (and the countdown’s minutes in its last hour) and sensor warm-up / end, each drawing the same snapshot with now = the entry’s date; the policy is .after(last entry), .never when there is nothing to age.

  • Stores (SukraraCore/Stores): readings.csv (t_ms,mgdl,rate, appended, atomic rewrite for backfill, 31 days, first reading per t kept), treatments.json (TreatmentLog v1: entry + creator + delivery), sensor.json, wearer-settings.json. An unreadable file is copied to <name>.corrupt-<unix s> and reported as a StoreIssue (never silent “no data”). KeychainStore.secrets picks the keychain from the build’s entitlements: the data-protection keychain in group QWUV9H4A3G.app.mauri.sukrara when a provisioning profile granted it (MovingSecretStore moves an item still in the login keychain on its first read: copy, read back, compare, then remove the old one), else the login keychain; without the entitlement the data-protection keychain answers -34018 (TN3137), which is tested to surface as an error, never as “no item”.

  • FollowerRuntime: start reads the Keychain (missing item → wipe leftovers, not following; read error → keep data, broken), connects relays (+ Bluetooth when allowed), resubscribes when the session asks, persists trust changes at once and the rest ≤ every 5 min, re-sends unsent treatments, runs the missing-history check 90 s after the backfill. reconnect() is for wake / network-up (21 wires NSWorkspace.didWakeNotification and NWPathMonitor). Join = invite lookup pool (invite key, #p) → FollowerSession.join → Keychain → request.

  • Nearby (SukraraShare/Nearby): BleFraming / BleReassembler / BleMessage / HelloProof pinned by the OGS ble vectors; NearbyLink is the per-connection protocol (HELLO, INFO proof, one write in flight, nothing written before the phone proved it’s the wearer’s); NearbyCentral is the CoreBluetooth adapter, an actor whose executor is the CB queue (delegate callbacks enter with assumeIsolated).

  • Juggluco on this network (SukraraShare/Lan): JugglucoApi (pure: URLs, sha1hex secret, entries / SSE parsing, LanAddress home ranges, LanInterface.hosts sweep list) and the JugglucoLanSource actor (find → history → live, backoff, its own 31-day ReadingsFileStore under juggluco/) behind LanSourcing; every request goes through LanHTTP (URLSessionLanHTTP; tests FakeLanHTTP). ServicesPlan.lan creates it idle; AppModel turns it on from the setting while not following and feeds its readings to the card and the alerts.

  • Tests: FollowerRuntimeTests (join over a fake relay hub with the OGS invite and key, outbox, unfollow, Keychain errors), ProtocolCompatTests (every sync fixture through the runtime into file stores, incl. rotation.json = restore), NearbyTests, StoreTests, KeychainStoreTests (temp service), WidgetFeedTests.

Mac alerts (apps/macos/Sources/SukraraAlerts)

Section titled “Mac alerts (apps/macos/Sources/SukraraAlerts)”

The alert rules of contracts/alerts/SPEC.md as a pure Swift 6 library (functional core); the app shell owns notifications, sounds, timers and storage.

  • AlertEngine — a Sendable value type: mutating func handle(_ input: AlertInput, at: Date, using: inout RNG) -> [AlertEffect]. No I/O, no clock, no globals; firing ids come from the passed generator (the convenience overload uses the system one).
    • Inputs: reading, treatments (live carbs / rapid insulin), sensor (SensorWindow), settings, scope (all / noDataOnly for a follower that mirrors the wearer), tick, and this device’s actions mute, remindLess, unmute, remindAsUsual, muteAll, unmuteAll. Every input re-evaluates at once.
    • Effects, in order: fire (post, replacing the group’s notification), clear, back(side) (margin end, history), resume (after restore: show again silently, same id / n, never republish), and always last schedule(Date?) (the next tick). The shell should also send tick on wake from sleep (NSWorkspace.didWakeNotification).
  • AlertEngine.Snapshot (v 1: episodes, SideSnoozes, Mute all) and AlertEngine.restore(_:context:at:); Snapshot.decode returns nil for unreadable / other-version data (start fresh). The settings are not in it: they are the SPEC §3 JSON (AlertSettings.encoded() / .decode, lenient, coerced to the generated SettingsSpec number formats) stored under the schema key alerts, and on a follower they may come from the wearer.
  • SideSnoozes — the per-side Mute / Remind less with the one margin rule (advance), shared by the engine and AlertMirror (a follower mirroring the wearer’s alert events: which show here, and this device’s own actions).
  • AlertUIState (engine.uiState(at:)) — active alert per group, quiet / relaxed sides with their exits, Mute all; QuietReason is typed, the words come from MuteCopy (contracts/alerts/copy.json, en) with SukraraCore.Durations.
  • AlertNotificationIDs — category / action / notification ids (app.mauri.sukrara.alert…, app.mauri.sukrara.muted).
  • Tests (Tests/AlertsTests, Swift Testing): ScenarioTests (one case per timeline in contracts/alerts/scenarios, the SPEC §7 driver; also run with an AlertMirror for mirror scenarios), SettingsCodecTests, EpisodesRestoreTests, EngineTests (safety invariants, effect order, clock jumps, deterministic ids), MuteCopyTests.

The wearer’s glucose input. SensorModule builds it; the hub reads SourceManager as its one ReadingSource (:core:model).

  • Threading: one serial dispatcher (Dispatchers.Default.limitedParallelism(1)) runs the source switch, the Libre 3 driver, the GATT queue and every timer; Binder callbacks are queued into an unlimited channel and handled there. Juggluco’s blocking HTTP runs on IO. A switch, a restart (new pairing, Try again, Bluetooth on, watchdog) cancels the running source, whose finally closes the gatt, before the next one starts.
  • Layers: libre3/Libre3Driver (protocol only, no Android; ported byte for byte from the PoC) → ble/BleLink → ble/GattLink (queue, 10 s per-operation and discovery timeouts, close-now + new connection with 1–30 s backoff, Bluetooth off/on, generation-tagged callbacks) → ble/GattConnector (AndroidGatt on the phone, fakes in tests). libre3/Libre3Crypto is the JNI core (libsukrara_libre3.so, from Juggluco at the pinned revision); a build without it shows Libre 3 core missing and release builds refuse to build (verifyNativeCore).
  • Other families (untested on real sensors): dexcom/G7Driver, dexcom/G6Driver, cgms/SmartGuideDriver, aidex/AidexXDriver extend brand/BrandDriver (finding rules, value range / clock / live-vs-history rules, end, fail, retry) and run on the same GattLink. The saved pairing’s SensorProfile picks the driver (SourceManager.runDirect); a pairing without an address is found first by ble/SensorScanner (filtered windows over the BleScanner port, AndroidScanner on the phone) and the found address and name are saved. The source never delivers the same reading time twice as live per pairing (SensorStatus.Direct.key).
  • Storage: the whole pairing (family, address, start, PIN, authorization, ended; a scanned family: its id, found address and name, pairing time) is one SecureStore entry sensor (Keystore alias sukrara.sensor): one atomic write; unreadable → PairingLoad.Corrupt → scan the sensor again. Receiver IDs (Sukrara’s own, the LibreView account’s) in the typed DataStore receiver-ids.json; the account’s receiver ID counts only while the app has a LibreView account. The account itself (email and password) is THE LibreView account of the app, :core:data libreview/LibreViewLogin in SecureStore libreview-account (DataModule.libreViewLogin): signed in once on the account screen (:feature:sensor LibreViewSignInScreen) through :sensor LibreViewAccount (LibreLinkUp login), and used by the sensor, the LibreView upload and Import history; signing out there signs out everywhere (issue #177).
  • Takeover and receiver IDs (verified from code and docs/02; device test pending): a Libre 3 is bound for life to the receiver ID it was started with; NFC takeover (A8) succeeds only with that ID and a wrong one changes nothing (B1). Sukrara starts sensors only with the LibreView account’s ID (nothing sent without it) and tries account → own ID for a takeover (nothing sent without the account ID), so a sensor started by another app on the same account can be taken over, and taken back by that app. A takeover gives a new BLE PIN, so Sukrara pairs afresh and the previous owner’s Bluetooth session fails; if the sensor is taken away from Sukrara, 3 rejected authorizations in a row stop the link with another app has the sensor.
  • Juggluco: juggluco/JugglucoSource reads http://127.0.0.1:17580 (loopback, allow-listed): history, then SSE.

Ports live in :core:model (storage/Storage.kt, in-memory fakes in :core:testing); :core:data implements them and DataModule (built lazily by AppGraph, ready() opens the database on IO) exposes them. No PoC files or keys are read (new app id, no migration). Nothing is in cloud backup or device transfer (allowBackup=false, data_extraction_rules.xml excludes every domain).

What Where API
Settings datastore/<store>.preferences_pb, one per schema store, keys from contracts/settings/settings.json; alerts, settings (unit, source), graph, sensor, statusbar device-protected (DeviceProtected.SETTINGS) SettingsRepository + SchemaSettings.number/bool/text(id)
Typed state (alert episodes, the wearer’s last mirrored settings wearer_settings, …) files/state/<name>.json (DataStore + kotlinx JSON); role, role-backup, monitor-record, alert_state, sensor_end device-protected (DeviceProtected.STATES) DataModule.typedStore(name, serializer, initial, whenCorrupt)
A follower’s settings in use the stored settings, the mirrored graph rows resolved per follower.settingsFrom (Wearer / Default / Custom) FollowerSettingsRepository (:core:data), built by FollowerSettingsBridge (:app, also the alert runtime’s mirrored values, the alert pages’ values in use and alerts.source)
The wearer’s settings for its followers this phone’s mirrored graph rows under their wire keys + the whole alert settings (SPEC §3); the owner engine keeps the "mirror": true rows and publishes the settings event when they change WearerSettingsSource (:app) → MirroredSettingsSource of ShareOwnerModule
Secrets files/secure/<name>.bin = 0x01 ‖ IV ‖ AES-256-GCM (AAD = name); Keystore alias sukrara.<name>, one key per purpose (none bound to user authentication or setUnlockedDeviceRequired): identity.owner, identity.follower, nightscout, nightscout-api, nightscout-api-lan, tidepool, tidepool-email, libreview (the upload’s token), libreview-account (THE LibreView account: email + password), sensor (device-protected: DeviceProtected.SECRETS), juggluco SecureStore (KeystoreSecureStore on SecretBox)
History databases/sukrara.db (Room; only the current version’s schema in core/data/schemas/; no migrations: a database of any other version, older or newer, is dropped, every table, and created empty: fallbackToDestructiveMigration(dropAllTables = true), which covers downgrades too, DataModule.databaseReplaced, DatabaseSchemaTest, check room-schema): readings (PK t+source), treatments (LWW on modified_at, tombstones), seen_wraps, rejects, outbox, pen_ledger (the pen ledger, one JSON row, written with its entries in one transaction) ReadingsRepository, TreatmentsRepository, PenLedgerRepository, DAOs for the sharing ledger
Imported history the same tables: readings under SourceId.Imported (import-libreview, import-tidepool, import-file), entries with imported_from; stored only through THE import path (HistoryImport rules in :core:model, pure and property-tested; RoomHistoryImport, one transaction per batch); ReadingDao.upsertOwnFirst lets the sensor’s own reading replace an imported copy DataModule.historyImport (HistoryImportStore)
Other files files/<path> atomic tmp + fsync + rename DataModule.fileStore(path, codec) → Loaded / Missing / Corrupt
Diagnostics files/diag/diag.log + .1, 512 KB each, Redact scrubs keys / tokens DiagLog
Before the first unlock device-protected storage (/data/user_de/…, the same paths): what the wearer’s monitoring needs then (DeviceProtected: the settings stores, typed state and the sensor secret above), files/recent-readings.json (this phone’s own readings of the last 3 h, rewritten with every reading) and files/locked-readings.csv (every reading taken before the unlock, merged into readings at the unlock and deleted), files/locked-boot.json (the fallback plan: times and the No data rule, never a value). Everything else is credential-encrypted: DataModule throws LockedStorageException for it until the unlock (never “missing”); DiagLog holds its lines in memory until then DataModule.hubReadings (HubReadings over RecentReadings), DataModule.unlock(); LockedBootStore (:monitor), written by AlertRuntime
Network one OkHttp client (15 s connect, 30 s read, 60 s call, UA Sukrara/<version>, no body logging); one SukraraJson (ignoreUnknownKeys, explicitNulls = false) DataModule.http, DataModule.json

Retention (Retention, applied in ready()): readings 90 days, seen wraps / rejects / sent outbox 14 days.

Corruption is never silent. A file that can’t be decoded is copied to <file>.corrupt-<epochMs> and reported to DataModule.corruption (CorruptionLog), which AppGraph.startupState turns into a visible problem with Copy report. ready() re-reports every kept copy at each start until the person acknowledges it (renamed .seen-…, still kept), so a crash or a background start can’t hide it. Typed stores continue from the owner’s explicit whenCorrupt value and expose their own corruption flow; a FileStore keeps the damaged file in place and returns Corrupt on every load (never Missing) until a deliberate save or delete; settings read as defaults. A secret that can’t be opened throws SecretUnreadableException on every read and stays in place (an unreadable identity is never “no identity”); a transient Keystore error (busy after an OS update) throws transient = true, is not reported and deletes nothing; keys are never deleted by an error path. A damaged database is copied aside (with its WAL) and reported by QuarantiningOpenHelperFactory before SQLite recreates it.

What device-protected storage costs (#160). Android encrypts device-protected storage with a key it holds from the boot on, without the screen-lock secret. So the sensor pairing (its Keystore key has no user authentication either), the alert settings and record, the role, the unit / graph / status-bar settings and the last 3 hours of glucose values (and those read before an unlock) are protected only by the app sandbox and file-based encryption at rest, not by the person’s PIN: on a phone that is on but was never unlocked since its restart, someone who breaks the sandbox (root, an exploit) can read them, and with the pairing reach the sensor’s readings; with the credential-encrypted files they would wait for the unlock. Off, the phone protects both alike. The sharing identity and its state, the history, treatments, uploads and their accounts stay credential-encrypted. The trade is made for the person: alerts (very low!) and readings after an overnight update instead of silence until the morning.

No app-level encryption of the database (investigation 31): file-based encryption protects sukrara.db at rest. A SQLCipher key the app can use while the phone is locked (every reading arrives then) is a key anyone who can read the file on a running phone can use too, and it would add a way for the history to become unreadable. The same holds for the typed state and the device-protected plan. Secrets stay sealed by the Keystore (SecureStore).

Android protocol (apps/android/core/protocol)

Section titled “Android protocol (apps/android/core/protocol)”

Nostr protocol v2 + identity (contracts/protocol) as one pure-JVM module: no Android, no I/O, no clock (time is a parameter), no nostr-sdk. The wire formats are the PoC’s byte for byte (kinds, tag order, TTLs, JSON field names and number forms, invite link https://sukrara.mauri.app/join#…, BLE framing).

  • Crypto seam: NostrCrypto (sign / verify, NIP-44 v2, NIP-59 gift wraps, nsec / npub, NIP-49). :share implements it with org.nostrdevkit:nostr-sdk (AAR). The module’s tests use the JVM build of the same library (nostr-sdk-jvm, test classpath only). testFixtures ships NostrCryptoContractTest (OGS vectors: every event verifies / decrypts, wraps open to their rumor and its created_at, a rumor whose author isn’t the seal signer is refused, NIP-49 and nsec round trips, the BLE HELLO proof); every implementation subclasses it. The PoC’s hand-written BIP-340 verifier is gone: the HELLO proof is checked by the library’s Event.verify(). HKDF is RFC 5869 over the JCA’s HMAC, pinned by RFC 5869 case 1 and identity/vectors.json.
  • Keys: PublicKeyHex, SecretKey (redacted toString, hex only via revealHex()), KeyPair, Derive.inviteKey.
  • Events (event/): payload codecs per family (ReadingsCodec live / sensor / chunk, AlertCodec, TreatmentCodec + WriterScope, SettingsCodec, RosterCodec, BackupCodec, RumorCodec for 30500 / 30501 / 30502, Profile / Avatar) and EventFactory, which signs every event the wearer and writers publish. Decoders throw only InvalidPayload; health payloads redact toString.
  • Follower acceptance (follow/StreamFollower): the transport-independent judge for relays and Bluetooth: verdict Accepted(item) | Rejected(reason) | Ignored(reason, rekey?) with the codes of the OGS / sync fixtures. It keeps only trust and dedupe state (FollowerState: status, sid, epochs, roster, writer-scope creators, settings u, seen ids pruned at their expiry, rekey throttle); storing readings / treatments / settings is the follower engine’s (25). A port of the reference follower plus, from the PoC FollowerEngine: the settings rule, a key delivery newer than the revoked notice re-approves (older notices ignored), a newer epoch’s key outranks older-epoch rosters, rekey only for events newer than the latest key with have = newest held gk. Events rejected only because the author isn’t in the roster yet aren’t remembered, so they’re judged again after the roster arrives. Dropped from the PoC engine: the 24 h treatment window and the via tag (UI / engine concerns).
  • Owner side (owner/): IdentityConflict.check (A3: a newer roster without this device, under an epoch we don’t hold, or a newer backup with other epochs = another app publishing as this identity → Conflict; our own echoes, our own rotation and late old events are Fine; the engine persists OwnerMarks), RecoveryCode (NIP-49 export log_n 18 / key_security 0x01; import of ncryptsec, nsec or hex for the first-run restore).
  • Invites (invite/): InviteLink parse / build, Invites.create / open (fingerprint, expiry, typed failure), match code. BLE (ble/): UUIDs, framing, Reassembler and RateLimit (limits of B§4.3 / B§8), HELLO / INFO messages, HelloProof.
  • Fixtures: contracts/protocol/{identity,ogs} vectors and contracts/protocol/sync/*.json (owner → follower sequences and the owner-conflict cases, generated here with -Psukrara.regen=true, replayed by the Mac too).

Android sharing, wearer side (apps/android/share)

Section titled “Android sharing, wearer side (apps/android/share)”
  • crypto/SdkNostrCrypto — the :core:protocol NostrCrypto over org.nostrdevkit:nostr-sdk 0.45.1 (+ JNA AAR; R8 keeps in consumer-rules.pro). Host tests run it on nostr-sdk-jvm and subclass NostrCryptoContractTest.
  • transport/ — RelayTransport (inbound flow, per-relay status, subscribe / publish / fetch, reconnectNow) and RelayPool, the Kotlin twin of the Mac RelayPool: one OkHttp WebSocket per relay (OkHttpWebSockets, wss only, pings every 60 s), backoff 2 s → 5 min × jitter, subscriptions + a 1-hour outbox re-sent after reconnects (a newer live / addressable event replaces the older), NIP-42 AUTH as the identity. nostr-sdk’s Client isn’t used: one relay behaviour on both platforms, and the pool is unit-tested against fake sockets. Tests use FakeRelayTransport. NetworkWatch (Android: AndroidNetworkWatch, the default-network callback) makes the relays reconnect when a new network comes up; each engine opens it while it runs (the owner’s sharing, the follower’s connection) and closes it when it stops. Tests use FakeNetworkWatch.
  • owner/ — OwnerState (typed state, @Serializable, redacted) in OwnerIdentityStore (SecureStore identity.owner; unreadable ≠ missing). Use-cases in owner/usecase are pure (state, input, now) → Step(state, events): CreateIdentity, RestoreIdentity (+ restoreAllowed gate), ExportRecovery, CreateInvite, HandleInbox, ApproveRequest, DenyRequest, RemoveFollower, SetWriter, SetProfile, Rotate, PublishReadings, IdentityConflictDetector; control events (deliveries, notices, roster, backup) wait in pendingControl until a relay answers OK, so a rotation interrupted by a crash still reaches every follower. OwnerEngine runs them on one serial dispatcher, persists before publishing and exposes StateFlow<OwnerShareState>; ShareOwnerModule (A4) builds it for AppGraph from only the storage it uses (the secure store, the settings, the treatment log, the seen-wraps ledger as a SeenWraps port), not the whole DataModule; FollowerModule likewise.
  • ble/ — Bluetooth share (ogs-ble). Pure protocol cores without android.bluetooth, JVM-tested with fake frames: NearbyServerCore (wearer: per-central framing, HELLO → INFO + backlog, identity proof, pushes, B§8 limits) and NearbyLink (follower: HELLO + proof, the which-owner gate, one write in flight). Thin adapters run them on one handler thread: AndroidNearbyServer (the engine’s OwnerNearby; GATT server + advertiser, Bluetooth on/off, the sharing.bleFollowers switch) and AndroidNearbyCentral (the follower engine’s NearbyTransport; scan, connect, timeouts, backoff). OwnerEngine.send keeps the backup and the invite wrap off Bluetooth; FollowerEngine runs the transport beside the relays while attached and feeds its events to the same StreamFollower. Tests: NearbyServerCoreTest, NearbyLinkTest, OwnerNearbyTest, FollowerNearbyTest (fakes FakeNearbyServer / FakeNearbyTransport).

Android integrations (apps/android/integrations)

Section titled “Android integrations (apps/android/integrations)”

IntegrationsModule (built by AppGraph.integrations; load() + start(scope) in ready) owns everything that sends the person’s data to other apps; its pages (AppsPage, LibreViewPage, NightscoutPage, ExportPage) are content the app wraps in the settings page frame (AppsRoute, LibreViewRoute, NightscoutUploadRoute, ExportRoute).

  • upload/ — the shared upload design: no outbox (the readings / treatments stores are the queue; each uploader keeps what the service has), UploadLoop (one cycle per kick or 5 min, on IO, never in the reading path), UploadBackoff, SentRanges, one UploadStatus for every page.
  • nightscout/ — NsSite (https, or http to loopback only), NsClient (the app’s OkHttp without redirects; v1 / v3; token → JWT), NsDocs, NightscoutQueue (pure plan + reconcile: covered minutes, another-uploader pause), NightscoutUploader (settings JSON apps.nightscoutUpload, credential only in SecureStore nightscout, state in the typed store nightscout-upload, device Sukrara-<6 hex> per site).
  • libreview/ — LibreViewPayload (contracts/treatments §3, byte for byte), LibreViewClient (Abbott’s config → sign-in / measurements / sensor registration; https only, no redirects), LibreViewQueue (pure: entries LibreView lacks from the version ledger, glucose by life count), LibreViewUploader (settings JSON apps.libreview; signs in by itself with THE LibreView account, LibreViewLogin, and follows it: signed out drops the token, a refused password marks the account sign in again; token + profile only in SecureStore libreview; ledger, sent life counts, device id, the other-device stop and glucoseFrom / entriesFrom / AccountId in the typed store libreview-upload; history not sent yet in libreview-unsent). Glucose comes from :sensor’s SourceManager.sensorGlucose (Libre 3 only, each batch tagged with its serial), mapped in AppGraph.
  • localserver/ — LocalHttpServer (127.0.0.1, fixed pool, bounded head and deadline), XdripEndpoint (Juggluco’s JSON, pure), XdripServer (follows apps.xdrip and the sensor source; readings from the store, “last asked” in memory), NightscoutApi (the v1 read API, pure: routes, secret check, per-source device labels) and NightscoutApiServer (apps.nightscout on 127.0.0.1:17581; the API secret only in SecureStore nightscout-api; apps.nightscoutLan adds a second LocalHttpServer bound to the Wi-Fi’s private address with LanPolicy’s subnet and Host rules and its own secret in SecureStore nightscout-api-lan, the Wi-Fi from LanWatcher’s ConnectivityManager callback while it is on, pinned network in the typed store nightscout-lan).
  • broadcasts/ — BroadcastPayloads (pure extras per action), BroadcastPlan (pure: who gets what for one live Libre 3 reading), Broadcaster (allowed apps + signer pins in apps.broadcasts; throttle / life count / activations in the typed store broadcasts; PlatformApps = PackageManager + sendBroadcast). Input: SourceManager.sensorGlucose current (Libre 3 pairings only), mapped in AppGraph.
  • healthconnect/ — HealthConnectSync (healthConnect.on; readings store → written-minute runs, backoff, in the typed store health-connect), PlatformHealth (platform android.health.connect, glucose only), HealthConnectPage (permission sheet via RequestMultiplePermissions; MainActivity routes VIEW_PERMISSION_USAGE + HEALTH_PERMISSIONS from the .HealthPermissionsRationale alias to it).
  • tidepool/ — TidepoolClient (session login, token refresh; https, no redirects), TidepoolData (cbg / food / insulin / notes with origin ids), TidepoolQueue (pure plan), TidepoolUploader (settings JSON apps.tidepool; token + user id only in SecureStore tidepool, the email in SecureStore tidepool-email, the password never stored; state in the typed store tidepool-upload).
  • export/ — GlucoseCsv (contracts/export), Exporter (period → stores), ExportViewModel (SAF save, FileProvider ${applicationId}.export share from cache/export/).
  • history/ — Import history (wearer): HistoryCsv (reads the contracts/export layout back: Sukrara’s export, the earlier app’s, LibreView’s Download glucose data file; columns by position; FileDates: whatever date layout the account’s language and country write, the order every row fits, a clock change’s repeated hour kept), TidepoolHistory (Tidepool’s data model back into readings / entries; TidepoolClient.data / notes read it, TidepoolUploader.withAccount lends the signed-in session under the upload’s lock), HistoryImporter (the last 90 days a week at a time through DataModule.historyImport, one job in the app scope, Stop, a 429 / 503 waits for Retry-After; ImportState for the page and the Share with apps row), ImportPage. Imported readings / entries (SourceId.Imported, TreatmentRecord.importedFrom) are left out of every upload.

Every app’s tests read contracts/ (Android: the sukrara.contracts system property from the convention plugin; Mac: Contracts.url(…)). A contract change lands with every implementation (tools/check parity groups, CI runs every app). Alert scenario expectations change only with the owner’s OK.

VERSION → every app. Android: tools/release/android-release.sh (the full flavor’s APK with the release key + verify-apk.sh) and tools/release/play-bundle.sh (the play flavor’s app bundle for Google Play, the same key + verify-apk.sh --play; the play flavor has every feature, root and the LSPosed module included, but no updater: app/src/play, Store, no :update; Play approved root and exact alarms with 0.14.5); Mac: tools/release/mac-release.sh (bundle + dmg + verify-app.sh; a notarized dmg is signed with the Sparkle EdDSA key and added to website/public/appcast.xml by tools/release/appcast.py). Every release is a normal GitHub release (marked Latest); every app’s updater, and the Homebrew cask, skips a GitHub prerelease (a release candidate).