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.
Repository layout
Section titled “Repository layout”| 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) |
Identity and storage
Section titled “Identity and storage”- Android
app.mauri.sukrara; Macapp.mauri.sukrara, widgetapp.mauri.sukrara.widget, App GroupQWUV9H4A3G.app.mauri.sukrara. - Settings:
contracts/settings/settings.json→ generatedSettingsSpec(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.
Android (apps/android)
Section titled “Android (apps/android)”Services, alerts and notifications
Section titled “Services, alerts and notifications”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 oneMutex. Inputs: hub state (role, latest reading,monitoringStartedAt, sensor), alert settings (storealerts, keyalerts, SPEC §3 JSON viaAlertStateStore), treatments (→Doses), the wearer’s mirrored settings andalertevents (25), this device’s actions (AlertControlsin:core:model, also the notification buttons). Per input: machine → effects applied (AlertAlarmfirst, thenAlertPresenter,AlertEventSink) →AlertRecordsaved (typed store) →AlertUiStatepublished to the hub. Every step is attempted on its own: a failure is logged toDiagLog(step + exception class) and listed inAlertUiState.failedStepsuntil that step works again; the alert checklist (AndroidAlertReadiness, THE answer to “may an alert not reach the person?”) reads it asAlertRequirement.AlertDelivery. Rolenullis ignored (setup / hub loading);monitoringStartedAt == nullswitchesno_dataoff.- Alarms: one
AndroidAlarms(monitor/service/) sets every alarm (health check, freshness step, alert check, sensor end) throughAlarmPolicy: protective checkssetExactAndAllowWhileIdle(72 / h Doze quota withUSE_EXACT_ALARM; inexact while-idle if exact alarms are refused), neversetAlarmClock(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, thensensorEnd.check(), each on its own) →MonitorRestarter.restart()(10’s starter). Boot, update, clock / zone change reach the same check throughBootReceiver, which starts the service once.AlertActionReceiver(Mute… / Change time direct reply, Remind less / as usual, Unmute, swipe tidy). All non-exported, through onerunAsync(goAsync, 9 s budget).AlertNotifier+AlertChannels(alert.<kind>/alert_alarm.<kind>) +NotificationGroups(notify/: thealertsandinfonotification 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 implementsAlertsHostso receivers and the provider reach it (awaitAlerts(): null before the first unlock on a phone that doesn’t monitor then); the monitoring service callsattach(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.
Updates (GitHub version only: :update)
Section titled “Updates (GitHub version only: :update)”: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+ itsApkAsset:Sukrara-<version>.apk, GitHub’ssha256: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 whileAlertHoldisn’t quiet; silent only when automatic and installs are allowed),UpdateEndpoint(GitHub, or a debug build’s local test server fromBuildVariant.updateServer). - Android:
Downloader(https on every hop, size-capped, hashed while streaming,.partthen rename),ApkCheck.facts(PackageManager.getPackageArchiveInfowith signing certificates),Installer(a PackageInstaller session; status toUpdateReceiver),UpdateNotifier(channel App updates, low importance),UpdateCheckWorker(daily, whileupdate.automaticChecks) andUpdateInstallWorker(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’sBootReceiverrestarts monitoring from the same broadcast). AlertHolds(:monitor): what an install waits for, from the alert runtime’s savedAlertState(episodes whose notification is up, a very low that is on, a follower’s mirrored alerts) and the hub’s livefiringKinds.
Sharing
Section titled “Sharing”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.offerHistoryAgainafterDataModule.databaseReplaced; the app opens it on its own at launch when due).SetupRecordpersists in the typed storesetup; the role is a separate store owned byAppGraph(RoleStore).setup/RestoreGate(pure): restore only with a live own-sensor reading (≤ 15 min, Libre 3 / Juggluco).:monitor’sAndroidAlertReadinessimplements:core:model’sAlertReadinessSource(the checklist setup, home and Settings › Alert reliability show).- Ports from the app:
OwnerSharing(adapterEngineOwnerSharingover:share’sOwnerEngine),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. SetupModuleis composed byAppGraph(SharingDeps.setup) overshareOwner’s engine (started for a wearer byfollowRole); 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,LaterRequestsinSetupModule—ProfilePage,BackupPage,InviteHereScreen),followers/,profile/(ProfileEditor),backup/(BackupScreen,PasswordManager= Credential Manager). All actions go throughSharingViewModel→OwnerSharing; the identity secret reaches onlyPasswordManager.save(insideOwnerEngine.saveToPasswordManager) and the recovery dialog (secure window, never saved state).- Pictures:
:core:designsystemavatar/AvatarDrawing(pure v1 geometry, tested againstcontracts/protocol/identity/avatar-v1.json) +AvatarImage(Compose Canvas); every face in the app goes through it.
Card, widgets and UI
Section titled “Card, widgets and UI”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 aCardPart(whole card, header, value, slots, chart) and returns aCardLayout(every element’s name, box and what it shows: what the layout tests read).GlucoseCard.imagedraws into a bitmap (widgets, notification, lock screen).GlucoseCard.facegives text / icon places the value, trend mark and freshness step (GlucoseLook).A11ybuilds 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 optionalmetricsOfcache.CardStyle/GraphStylecome from the surface and its place’sGraphConfig(built by the settings repository from the schema keys;GraphConfigis a plain data class, not a JSON blob). The renderer depends only on:core:model(with the generatedSettingsSpec) and:core:data’s schema settings keys (GraphSettings): no:core:alerts, no:monitor. - Status from outside. The alert runtime maps its
AlertStatustoCardStatus(:core:model: None / Needed / Taken / Paused / Muted) and publishes it in the hub’sAlertUiState.status, which every card surface (app panel, widgets) passes to the renderer; it also supplies theMuteRule(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 perResources(en + es strings of the module); durations through the one formattercore.model.Durationswith theduration_*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 andexpect.jsonover stand-ins for the registered card surfaces until their code lands) and the Roborazzi goldens incore/graph/src/test/snapshots(synthetic data, UTC, en-US; recorded on CI by.github/workflows/goldens.yml, since macOS renders text a little differently: locallycompareRoborazziDebug).
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.
Mac (apps/macos)
Section titled “Mac (apps/macos)”One SwiftPM package (swift-tools 6.2, Swift 6 language mode, macOS 15, arm64). Build, test and bundle commands:
apps/macos/README.md.
Targets
Section titled “Targets”Sukrara (exe, GitHub version) ─► SukraraUpdater ─► Sparkle 2.10.1 (prebuilt framework) └─► SukraraApp ─► SukraraCore, SukraraGraph, SukraraAlerts, SukraraShare ─► NostrSDK 0.45.1SukraraAppStore (exe, App Store version) ─► SukraraApp (no updater)SukraraWidget (exe, appex) ─► SukraraCore, SukraraGraph (extension-safe only)sukrara-snap (exe, debug) ─► SukraraAppTests: CoreTests GraphTests AlertsTests ShareTests AppTests ─► SukraraTesting (fakes, Contracts.url)SukraraCore,SukraraGraph: nonisolated, compiled with-application-extensionso the widget can link them.SukraraApp,SukraraUpdater,Sukrara,SukraraAppStore,sukrara-snap,AppTests:.defaultIsolation(MainActor.self)+NonisolatedNonsendingByDefault+InferIsolatedConformances. Background work goes into actors /@concurrent.SukraraAlertsis pure (no UI, no I/O);SukraraSharekeeps every transport behind a protocol.- The updater (#91):
SukraraAppknows onlyUpdaterEngineand theUpdatesmodel (the panel’s reminder, About’s button and switches);SukraraUpdaterimplements it with Sparkle (SparkleUpdater, gentle reminders). Only theSukraraexecutable links it (AppMain.run(updater:)); the App Store executable passes nil, so its binary has no Sparkle at all.AppServicescreates 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.
Ids and paths
Section titled “Ids and paths”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).
Launch gate
Section titled “Launch gate”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 unlessSUKRARA_DEV=1; with it:ServicesPlan.none(so no updater either) andDataScope.isolated(separate homeSUKRARA_DEV_HOMEor…/Application Support/app.mauri.sukrara.dev, Keychain service and defaults suiteapp.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 forsukrara-snap(the only snapshot path), debug only, no services, isolated data.ServicesPlanis an upper limit: the app ANDs it with the user’s settings (limited(by:)) and starts services only throughServicesPlan.start(using: some ServiceStarting). The app’sServiceStartingis 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:SystemCamerafor 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-upSyntheticCamerafeed, 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 onlywss://hosts),Derive(HKDF invite key, CryptoKit),SignedEvent(NIP-01 JSON; engines never see NostrSDK types),SecretKeyHex(redacted indescription,debugDescriptionandMirror), 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 ofpoc/spec/reference/ogs/follower.pyplus the settings rule; verdict strings are the OGS vector codes shared with Android’sStreamFollower.FollowerState(v1) holds F, the read keys, roster, writer-scope records (creator, held(u, o)per treatment id), settingsu, 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 (serviceapp.mauri.sukrara, accountfollower). Readings/treatments go out as deltas to 15’s stores. Unfollow = discard the state. - Relay/ —
RelayPoolactor: socket perwss://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-consumerinboundstream, 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.
WidgetReloadPolicyreloads 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 withnow= the entry’s date; the policy is.after(last entry),.neverwhen there is nothing to age. -
Stores (
SukraraCore/Stores):readings.csv(t_ms,mgdl,rate, appended, atomic rewrite for backfill, 31 days, first reading pertkept),treatments.json(TreatmentLogv1: entry + creator + delivery),sensor.json,wearer-settings.json. An unreadable file is copied to<name>.corrupt-<unix s>and reported as aStoreIssue(never silent “no data”).KeychainStore.secretspicks the keychain from the build’s entitlements: the data-protection keychain in groupQWUV9H4A3G.app.mauri.sukrarawhen a provisioning profile granted it (MovingSecretStoremoves 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 wiresNSWorkspace.didWakeNotificationand NWPathMonitor). Join = invite lookup pool (invite key,#p) →FollowerSession.join→ Keychain → request. -
Nearby (
SukraraShare/Nearby):BleFraming/BleReassembler/BleMessage/HelloProofpinned by the OGSblevectors;NearbyLinkis the per-connection protocol (HELLO, INFO proof, one write in flight, nothing written before the phone proved it’s the wearer’s);NearbyCentralis the CoreBluetooth adapter, an actor whose executor is the CB queue (delegate callbacks enter withassumeIsolated). -
Juggluco on this network (
SukraraShare/Lan):JugglucoApi(pure: URLs,sha1hexsecret, entries / SSE parsing,LanAddresshome ranges,LanInterface.hostssweep list) and theJugglucoLanSourceactor (find → history → live, backoff, its own 31-dayReadingsFileStoreunderjuggluco/) behindLanSourcing; every request goes throughLanHTTP(URLSessionLanHTTP; testsFakeLanHTTP).ServicesPlan.lancreates it idle;AppModelturns 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— aSendablevalue 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/noDataOnlyfor a follower that mirrors the wearer),tick, and this device’s actionsmute,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 lastschedule(Date?)(the nexttick). The shell should also sendtickon wake from sleep (NSWorkspace.didWakeNotification).
- Inputs:
AlertEngine.Snapshot(v1: episodes,SideSnoozes, Mute all) andAlertEngine.restore(_:context:at:);Snapshot.decodereturns 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 generatedSettingsSpecnumber formats) stored under the schema keyalerts, 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 andAlertMirror(a follower mirroring the wearer’salertevents: 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;QuietReasonis typed, the words come fromMuteCopy(contracts/alerts/copy.json, en) withSukraraCore.Durations.AlertNotificationIDs— category / action / notification ids (app.mauri.sukrara.alert…,app.mauri.sukrara.muted).- Tests (
Tests/AlertsTests, Swift Testing):ScenarioTests(one case per timeline incontracts/alerts/scenarios, the SPEC §7 driver; also run with anAlertMirrorformirrorscenarios),SettingsCodecTests,EpisodesRestoreTests,EngineTests(safety invariants, effect order, clock jumps, deterministic ids),MuteCopyTests.
Android sensor (apps/android/sensor)
Section titled “Android sensor (apps/android/sensor)”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, whosefinallycloses 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(AndroidGatton the phone, fakes in tests).libre3/Libre3Cryptois 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/AidexXDriverextendbrand/BrandDriver(finding rules, value range / clock / live-vs-history rules, end, fail, retry) and run on the sameGattLink. The saved pairing’sSensorProfilepicks the driver (SourceManager.runDirect); a pairing without an address is found first byble/SensorScanner(filtered windows over theBleScannerport,AndroidScanneron 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 aliassukrara.sensor): one atomic write; unreadable →PairingLoad.Corrupt→ scan the sensor again. Receiver IDs (Sukrara’s own, the LibreView account’s) in the typed DataStorereceiver-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:datalibreview/LibreViewLoginin SecureStorelibreview-account(DataModule.libreViewLogin): signed in once on the account screen (:feature:sensorLibreViewSignInScreen) through:sensorLibreViewAccount(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/JugglucoSourcereadshttp://127.0.0.1:17580(loopback, allow-listed): history, then SSE.
Android storage (apps/android/core/data)
Section titled “Android storage (apps/android/core/data)”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).:shareimplements it withorg.nostrdevkit:nostr-sdk(AAR). The module’s tests use the JVM build of the same library (nostr-sdk-jvm, test classpath only).testFixturesshipsNostrCryptoContractTest(OGS vectors: every event verifies / decrypts, wraps open to their rumor and itscreated_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’sEvent.verify(). HKDF is RFC 5869 over the JCA’s HMAC, pinned by RFC 5869 case 1 andidentity/vectors.json. - Keys:
PublicKeyHex,SecretKey(redactedtoString, hex only viarevealHex()),KeyPair,Derive.inviteKey. - Events (
event/): payload codecs per family (ReadingsCodeclive / sensor / chunk,AlertCodec,TreatmentCodec+WriterScope,SettingsCodec,RosterCodec,BackupCodec,RumorCodecfor 30500 / 30501 / 30502,Profile/Avatar) andEventFactory, which signs every event the wearer and writers publish. Decoders throw onlyInvalidPayload; health payloads redacttoString. - Follower acceptance (
follow/StreamFollower): the transport-independent judge for relays and Bluetooth: verdictAccepted(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, settingsu, 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 PoCFollowerEngine: 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 withhave= newest heldgk. 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 theviatag (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 areFine; the engine persistsOwnerMarks),RecoveryCode(NIP-49 export log_n 18 / key_security 0x01; import of ncryptsec, nsec or hex for the first-run restore). - Invites (
invite/):InviteLinkparse / build,Invites.create/open(fingerprint, expiry, typed failure), match code. BLE (ble/): UUIDs, framing,ReassemblerandRateLimit(limits of B§4.3 / B§8), HELLO / INFO messages,HelloProof. - Fixtures:
contracts/protocol/{identity,ogs}vectors andcontracts/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:protocolNostrCryptooverorg.nostrdevkit:nostr-sdk0.45.1 (+ JNA AAR; R8 keeps inconsumer-rules.pro). Host tests run it onnostr-sdk-jvmand subclassNostrCryptoContractTest.transport/—RelayTransport(inbound flow, per-relay status, subscribe / publish / fetch,reconnectNow) andRelayPool, the Kotlin twin of the MacRelayPool: 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 useFakeRelayTransport.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 useFakeNetworkWatch.owner/—OwnerState(typed state,@Serializable, redacted) inOwnerIdentityStore(SecureStoreidentity.owner; unreadable ≠ missing). Use-cases inowner/usecaseare pure(state, input, now) → Step(state, events):CreateIdentity,RestoreIdentity(+restoreAllowedgate),ExportRecovery,CreateInvite,HandleInbox,ApproveRequest,DenyRequest,RemoveFollower,SetWriter,SetProfile,Rotate,PublishReadings,IdentityConflictDetector; control events (deliveries, notices, roster, backup) wait inpendingControluntil a relay answers OK, so a rotation interrupted by a crash still reaches every follower.OwnerEngineruns them on one serial dispatcher, persists before publishing and exposesStateFlow<OwnerShareState>;ShareOwnerModule(A4) builds it forAppGraphfrom only the storage it uses (the secure store, the settings, the treatment log, the seen-wraps ledger as aSeenWrapsport), not the wholeDataModule;FollowerModulelikewise.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) andNearbyLink(follower: HELLO + proof, the which-owner gate, one write in flight). Thin adapters run them on one handler thread:AndroidNearbyServer(the engine’sOwnerNearby; GATT server + advertiser, Bluetooth on/off, thesharing.bleFollowersswitch) andAndroidNearbyCentral(the follower engine’sNearbyTransport; scan, connect, timeouts, backoff).OwnerEngine.sendkeeps the backup and the invite wrap off Bluetooth;FollowerEngineruns the transport beside the relays while attached and feeds its events to the sameStreamFollower. Tests:NearbyServerCoreTest,NearbyLinkTest,OwnerNearbyTest,FollowerNearbyTest(fakesFakeNearbyServer/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, oneUploadStatusfor 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 JSONapps.nightscoutUpload, credential only in SecureStorenightscout, state in the typed storenightscout-upload, deviceSukrara-<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 JSONapps.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 SecureStorelibreview; ledger, sent life counts, device id, the other-device stop andglucoseFrom/entriesFrom/ AccountId in the typed storelibreview-upload; history not sent yet inlibreview-unsent). Glucose comes from:sensor’sSourceManager.sensorGlucose(Libre 3 only, each batch tagged with its serial), mapped inAppGraph.localserver/—LocalHttpServer(127.0.0.1, fixed pool, bounded head and deadline),XdripEndpoint(Juggluco’s JSON, pure),XdripServer(followsapps.xdripand the sensor source; readings from the store, “last asked” in memory),NightscoutApi(the v1 read API, pure: routes, secret check, per-sourcedevicelabels) andNightscoutApiServer(apps.nightscouton 127.0.0.1:17581; the API secret only in SecureStorenightscout-api;apps.nightscoutLanadds a secondLocalHttpServerbound to the Wi-Fi’s private address withLanPolicy’s subnet and Host rules and its own secret in SecureStorenightscout-api-lan, the Wi-Fi fromLanWatcher’s ConnectivityManager callback while it is on, pinned network in the typed storenightscout-lan).broadcasts/—BroadcastPayloads(pure extras per action),BroadcastPlan(pure: who gets what for one live Libre 3 reading),Broadcaster(allowed apps + signer pins inapps.broadcasts; throttle / life count / activations in the typed storebroadcasts;PlatformApps= PackageManager +sendBroadcast). Input:SourceManager.sensorGlucosecurrent(Libre 3 pairings only), mapped inAppGraph.healthconnect/—HealthConnectSync(healthConnect.on; readings store → written-minute runs, backoff, in the typed storehealth-connect),PlatformHealth(platformandroid.health.connect, glucose only),HealthConnectPage(permission sheet viaRequestMultiplePermissions;MainActivityroutesVIEW_PERMISSION_USAGE+HEALTH_PERMISSIONSfrom the.HealthPermissionsRationalealias to it).tidepool/—TidepoolClient(session login, token refresh; https, no redirects),TidepoolData(cbg / food / insulin / notes with origin ids),TidepoolQueue(pure plan),TidepoolUploader(settings JSONapps.tidepool; token + user id only in SecureStoretidepool, the email in SecureStoretidepool-email, the password never stored; state in the typed storetidepool-upload).export/—GlucoseCsv(contracts/export),Exporter(period → stores),ExportViewModel(SAF save, FileProvider${applicationId}.exportshare fromcache/export/).history/— Import history (wearer):HistoryCsv(reads thecontracts/exportlayout 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/notesread it,TidepoolUploader.withAccountlends the signed-in session under the upload’s lock),HistoryImporter(the last 90 days a week at a time throughDataModule.historyImport, one job in the app scope, Stop, a 429 / 503 waits forRetry-After;ImportStatefor the page and the Share with apps row),ImportPage. Imported readings / entries (SourceId.Imported,TreatmentRecord.importedFrom) are left out of every upload.
Contracts and tests
Section titled “Contracts and tests”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.
Release
Section titled “Release”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).