
Fetches server-exposed feature flags via OFREP with strict payload validation, last-good cache, tri-state reads, apply-at-launch, live kill‑switches, ETag/304 handling and upgrade-status monitoring.
Kotlin Multiplatform client for standard_flags. Android and iOS apps use it to read the flags the server exposes to them over OFREP, with a last-good cache, tri-state reads, apply-at-launch with live kill switches, and upgrade status.
Targets: Android, iosArm64, iosSimulatorArm64, and the JVM (for tests). Built with Kotlin 2.4, Ktor 3.6, kotlinx.serialization and coroutines.
| Module | What it is |
|---|---|
standard-flags-core |
Wire model and payload validation, FlagState (On, Off, NotLoaded) and typed reads, ceilings, SemVer Version and the neutral VersionRange/BuildRange, LastGoodStore, the RFC 8785 ETag. No HTTP. |
standard-flags-ofrep |
The Ktor OFREP client: X-Client-* headers (also a plugin for your own client), ETag / 304, jittered backoff with Retry-After, stop on 401/403, apply-at-launch, bootstrap seeding. |
standard-flags-openfeature |
An OpenFeature kotlin-sdk FeatureProvider over the OFREP client. Optional: skip it to bind your own seams to core. |
standard-flags-status |
/client/status as a StateFlow (ok, upgrade recommended, upgrade required, unknown), and a plugin that catches 426 answers. |
standard-flags-gradle-plugin |
checkFlagsManifest: fails the build when the app reads a wire its audience isn't exposed, or a wire's type changed. |
The artifacts are on Maven Central under one.rarebit.flags:
# gradle/libs.versions.toml
[versions]
standardFlags = "0.1.0"
[libraries]
standard-flags-ofrep = { module = "one.rarebit.flags:standard-flags-ofrep", version.ref = "standardFlags" }
standard-flags-status = { module = "one.rarebit.flags:standard-flags-status", version.ref = "standardFlags" }
standard-flags-openfeature = { module = "one.rarebit.flags:standard-flags-openfeature", version.ref = "standardFlags" }
[plugins]
standardFlagsContract = { id = "one.rarebit.flags.contract", version.ref = "standardFlags" }// shared/build.gradle.kts
kotlin {
sourceSets {
commonMain.dependencies {
implementation(libs.standard.flags.ofrep) // brings core
implementation(libs.standard.flags.status)
}
}
}The Gradle plugin resolves from Maven Central, so add mavenCentral() to pluginManagement.repositories in settings.gradle.kts.
Working against a local checkout. Use a composite build instead of publishing snapshots. In the app's settings.gradle.kts:
val localFlags = file("../standard-flags-kmp")
if (localFlags.isDirectory) includeBuild(localFlags)Gradle substitutes one.rarebit.flags:* with the local modules. For the contract plugin, add the same includeBuild inside pluginManagement { }. ./gradlew publishToMavenLocal here works too, for tools that need a Maven repository.
Declare the wires the app reads, with their code defaults. A wire is the name the server exposes to your audience, never the server's flag key.
object Flags {
val Chat = BooleanFlag("chat_enabled", default = false)
val Purchases = BooleanFlag("purchases", default = false, ceiling = true) // the server may only lower it
val Maintenance = BooleanFlag("maintenance", default = false, killSwitch = true)
val HomeHero = StringFlag("homeHero", default = "control", values = setOf("control", "savings"))
val all = listOf(Chat, Purchases, Maintenance, HomeHero)
}Build the client once, in shared code:
val client = ClientInfo(platform = "android", version = BuildConfig.VERSION_NAME, build = BuildConfig.VERSION_CODE.toLong())
val http = HttpClient {
install(ClientHeaders) { client(client) } // every API call carries X-Client-*
install(HttpTimeout) { requestTimeoutMillis = 15_000 }
// your auth plugin here; the OFREP endpoint sits behind the app's own authentication
}
check(client.isRecognised) { "the server would treat $client as an unknown build" } // in a debug build or a test
val flags = StandardFlagsClient(
fetcher = OfrepClient(http, "https://api.example.com/ofrep/v1/evaluate/flags", client),
definitions = Flags.all,
store = lastGoodStore, // see below
contextKey = session.accountId, // whose flags these are
)
flags.load() // at launch, before the first read: the cached values
scope.launch { flags.refresh() } // at launch and on every foregroundRead without suspending:
when (flags.state(Flags.Chat)) {
FlagState.On -> showChat()
FlagState.Off -> hideChat()
FlagState.NotLoaded -> showChatFromDefault() // nothing usable from the server: the code default applies
}
val hero: String = flags.value(Flags.HomeHero)
val read = flags.read(Flags.Chat) // value, loaded, reason (KILL_SWITCH, STATIC, …), variant, and why it fell backOn sign-in, sign-out or an account switch, switch the HTTP client's credentials first, then call flags.setContext(newAccountId) and refresh(). The old account's values are dropped at once, even while a fetch is still running; its late answer is thrown away. (Calling setContext before switching credentials would let a fetch in between store the old account's flags under the new key.)
ClientInfo.isRecognised matters because the server never errors on a bad platform or version: it quietly treats the build as unknown, which loses every min_client flag.
Android. Back the store with DataStore or SharedPreferences, and refresh on foreground, for example from a ProcessLifecycleOwner observer's onStart:
val lastGoodStore = StringLastGoodStore(
read = { prefs.getString("flags.last_good", null) },
write = { value -> prefs.edit { if (value == null) remove("flags.last_good") else putString("flags.last_good", value) } },
)iOS. The library is consumed through your shared KMP module (there is no separate Swift package). In iosMain, use the Darwin engine and NSUserDefaults, and call refresh() from the app's scenePhase == .active handler through a shared function:
val lastGoodStore = StringLastGoodStore(
read = { NSUserDefaults.standardUserDefaults.stringForKey("flags.last_good") },
write = { value -> NSUserDefaults.standardUserDefaults.setObject(value, forKey = "flags.last_good") },
)Bootstrap. If a response the app fetches at launch embeds the flags (the server's standard_flags_payload(audience, format: :ofrep), for example inside /me), seed from it to save a round trip: flags.seed(meResponse.flagsJson). The next refresh() sends its version as If-None-Match and usually gets a 304.
Pre-auth audiences. For an endpoint mounted with anonymous: true, pass targetingKey = { installId } to OfrepClient. Install IDs must be random and unguessable, and the answers are public.
PayloadLimits.maxBytes and maxFlags, strict RFC 8259 JSON in UTF-8 (no NaN, unquoted words, single quotes, leading zeros, lone or reversed surrogate escapes or trailing bytes, and at most maxNesting containers deep, 100 by default), an object with a flags array of objects with unique non-empty string keys, and metadata an object when present. Anything else is rejected, the last good payload stays, and the client backs off.StandardFlagsClient's PayloadLimits apply to fetched, seeded and stored payloads alike. The fetch streams the body: a Content-Length over the limit is refused without reading, and a body without one stops being read one byte past the limit, so an oversized answer never sits in memory.values all read as the code default with FlagState.NotLoaded. One bad flag never affects another.BooleanFlag(ceiling = true) reads default && server value, so the server can switch it off but never on, for example purchases on a platform whose store rules forbid them.LastGoodStore keeps the body, the contextKey it was fetched for and the build (ClientInfo.fingerprint: platform, version, build). A stored payload for another key, or saved by another build, is never applied: the server filters by build (min_client, deprecated wires), so an old build's answer could withhold or serve the wrong wires. After an upgrade the app starts on code defaults, and the first payload for the new build applies live. setContext drops the old values at once and clears a stored payload that belongs to another context. A store that throws never breaks the client: the failure shows in flags.storeError, and the in-memory values stay.metadata.version or ETag header that isn't a valid entity tag (1 to 256 printable ASCII characters other than a space or ") is ignored (no If-None-Match is sent), including the version of a stored payload loaded at launch. When three requests in a row that carry an If-None-Match are refused for it (400, 414 or 431, or the HTTP stack refuses the header), the client stops sending it, and remembers that in the stored record so a restart doesn't send it again; a payload with a new version sends its own. Offline spells, timeouts and other statuses don't count, so a bad value can't wedge fetching and an ordinary outage doesn't cost the 304.Backoff, 2 s doubling to 5 min by default), with Retry-After (seconds or any HTTP-date form) honoured as a floor, capped at an hour. A 401 or 403 stops fetching until setContext.refresh() calls share one fetch. Install a request timeout on the HTTP client all the same (HttpTimeout), so a stalled request doesn't hold up the next refresh.Values read at launch are the cached ones. A fresh payload is saved at once but applies at the next launch, so a screen never changes under the user. Two exceptions apply live:
KILL_SWITCH applies immediately, so a remote kill lands at the next foreground, not the next launch. Releasing it (the reason goes back to anything else) waits for the next launch. A BooleanFlag(killSwitch = true) applies live in both directions.setContext), the first payload applies at once.ApplyPolicy(freshValuesAtNextLaunch = false) applies every payload immediately; firstPayloadAppliesLive = false keeps code defaults until the next launch. flags.payload is a StateFlow of what code reads, and flags.pending holds the payload waiting for the next launch.
val status = ClientStatusClient(http, "https://api.example.com/client/status", client)
val api = HttpClient { install(UpgradeRequiredDetector) { this.status = status } }
scope.launch { status.check() } // at launch and on foreground
status.status.collect {
when (it) {
is ClientStatus.UpgradeRequired -> showBlockingUpgrade(it.details.storeUrl)
is ClientStatus.UpgradeRecommended -> showNudge(it.details.storeUrl, enforceAt = it.enforceAt) // a YYYY-MM-DD date, or null
is ClientStatus.Ok, is ClientStatus.Unknown -> Unit
}
}A failed check keeps the last known status, and an unknown build is never blocked. enforceAt is the UTC date enforcement starts (YYYY-MM-DD), not an instant. UpgradeRequiredDetector flips the status when any API call answers 426 with the server's client_upgrade_required error; a bare 426 is ignored. It reads the 426 body, which an ordinary Ktor call keeps for the app too, but a streaming call (prepare*().execute { }) doesn't.
OpenFeatureAPI.setProviderAndWait(StandardFlagsProvider(flags), ImmutableContext(targetingKey = accountId))
val chat = OpenFeatureAPI.getClient().getBooleanValue("chat_enabled", false)The provider reads through the client's declarations, so allowed values hold, and a ceiling flag is capped by its declared default whatever default the caller passes. It maps evaluation failures to OpenFeature error codes, passes the server's reason through (including KILL_SWITCH), and emits a configuration-changed event naming the wires that changed.
The targeting key is the client's context key: initialize hands it to setContext before loading, so the payload saved for it is the launch value, and a new targeting key calls setContext. Build the client with the same key, or none. The first fetch runs in the provider's scope: initialize waits up to initialFetchTimeout, and a slower fetch still lands afterwards.
The server commits a flags manifest (bin/rails standard_flags:manifest). Copy or reference it from the app and declare what the app reads:
plugins { id("one.rarebit.flags.contract") }
standardFlags {
manifest = rootProject.file("contracts/flags.manifest.json")
audience = "mobile"
wire("chat_enabled", "boolean")
stringWire("homeHero", "control", "savings") // with the values the app understands
// or wiresFile = file("flags.wires.json"):
// {"chat_enabled": "boolean", "homeHero": {"type": "string", "values": ["control", "savings"]}}
}Optionally, point baselineManifest at the manifest your shipped builds were made against. The check then also fails when the current manifest would break them (a wire removed or retyped, a public audience made private), with the server's standard_flags:manifest:check semantics. Both manifests are read as the server reads them, so a hand-edited file the server would refuse ({"version":2}, an audience without a boolean public, a date that isn't a calendar date) fails the check rather than passing. A version 1 baseline (standard_flags 0.3.0 and earlier) is read too, so removals across the upgrade to version 2 are still caught.
./gradlew check then runs checkFlagsManifest. It fails when a wire isn't exposed to the audience (naming any audience that does see it), when its type differs, or when the server can send a string value the app doesn't declare (the app would read its code default). It warns when the app declares a value the server never sends, and when a wire is only served by a deprecated tombstone, with its end date (failOnDeprecated = true makes that an error too). Once that date has passed the server no longer sends the wire, so reading it fails. Dates are UTC and computed when the task runs, even from the configuration cache; -PstandardFlags.today=YYYY-MM-DD reproduces a check on another day. It reads manifest versions 1 and 2.
The check depends on the date. A build that passed yesterday can fail today with nothing in the repository changed, in two ways:
until date has passed. Stop reading it: remove it from the app's declarations (and the code that reads it). The server no longer sends it, so the app already gets its code default.baselineManifest, the server moved a tombstone's until earlier than the baseline promised. Until the new date this is only a warning ("earlier than … shipped clients were promised"); the day after, the check fails with the wire as removed, whether or not this app still reads it, because the baseline covers every wire your shipped builds were told about. Removing the wire from the app doesn't help. If the earlier date is intended (the builds that read the wire are no longer supported), move baselineManifest to the current manifest; otherwise have the server restore the date it promised.To rebuild an old commit as it built at the time (a release branch, a reproducible build), pass the date it was built on: ./gradlew check -PstandardFlags.today=2026-01-15. Don't use this to keep shipping a wire past its end date.
The plugin's supported surface is the plugin id one.rarebit.flags.contract, the standardFlags { } block, the checkFlagsManifest task and the standardFlags.today property; its Java classes are internal and may change in any release.
conformance/ vendors the gem's wire-scope fixtures at the commit pinned in conformance/PIN.json. The tests run them on the JVM, Android and the iOS simulator: version and build ranges, payload in → reads out (through FlagCache and again through StandardFlagsClient), every golden delivery body and its ETag, every wire/client_status.json status body, and every wire/manifest_check.json case through the Gradle plugin's ManifestCheck. A test fails if a vendored fixture has no runner. scripts/sync-conformance --ref main moves the pin; CI runs scripts/sync-conformance --check, which also refuses any file in conformance/ the pin doesn't list.
Releases follow semantic versioning, and each Kotlin module's public API is checked against its api/ dump.
PayloadLimits, ApplyPolicy, ClientInfo) are regular classes, not data classes: construct them and read their properties, and compare them with ==.FlagEntry, FlagRead, StatusDetails, StoredPayload, and the cases of FetchStatus, FetchResult, RefreshOutcome, PayloadResult and ClientStatus mirror what the server sends or what the client reports, and grow with them. Read their properties by name; don't destructure them (val (key, value) = entry) or rely on copy or their constructor's parameter order. When building one for a test or a preview, use named arguments../gradlew check # every test; on macOS this includes the iOS simulator
./gradlew iosSimulatorTests # only the iOS simulator tests
./gradlew publishToMavenLocal # all modules into ~/.m2 (add -PRELEASE_SIGNING_ENABLED=false for a release version)
./gradlew updateKotlinAbi # after an intended public API change; check fails on any otherThe public API of each Kotlin module is recorded in its api/ folder (Kotlin's ABI validation), and check fails when it changes unexpectedly.
Releases go through CI: a v* tag matching VERSION_NAME publishes to Maven Central. See AGENTS.md.
MIT. See LICENSE.
Kotlin Multiplatform client for standard_flags. Android and iOS apps use it to read the flags the server exposes to them over OFREP, with a last-good cache, tri-state reads, apply-at-launch with live kill switches, and upgrade status.
Targets: Android, iosArm64, iosSimulatorArm64, and the JVM (for tests). Built with Kotlin 2.4, Ktor 3.6, kotlinx.serialization and coroutines.
| Module | What it is |
|---|---|
standard-flags-core |
Wire model and payload validation, FlagState (On, Off, NotLoaded) and typed reads, ceilings, SemVer Version and the neutral VersionRange/BuildRange, LastGoodStore, the RFC 8785 ETag. No HTTP. |
standard-flags-ofrep |
The Ktor OFREP client: X-Client-* headers (also a plugin for your own client), ETag / 304, jittered backoff with Retry-After, stop on 401/403, apply-at-launch, bootstrap seeding. |
standard-flags-openfeature |
An OpenFeature kotlin-sdk FeatureProvider over the OFREP client. Optional: skip it to bind your own seams to core. |
standard-flags-status |
/client/status as a StateFlow (ok, upgrade recommended, upgrade required, unknown), and a plugin that catches 426 answers. |
standard-flags-gradle-plugin |
checkFlagsManifest: fails the build when the app reads a wire its audience isn't exposed, or a wire's type changed. |
The artifacts are on Maven Central under one.rarebit.flags:
# gradle/libs.versions.toml
[versions]
standardFlags = "0.1.0"
[libraries]
standard-flags-ofrep = { module = "one.rarebit.flags:standard-flags-ofrep", version.ref = "standardFlags" }
standard-flags-status = { module = "one.rarebit.flags:standard-flags-status", version.ref = "standardFlags" }
standard-flags-openfeature = { module = "one.rarebit.flags:standard-flags-openfeature", version.ref = "standardFlags" }
[plugins]
standardFlagsContract = { id = "one.rarebit.flags.contract", version.ref = "standardFlags" }// shared/build.gradle.kts
kotlin {
sourceSets {
commonMain.dependencies {
implementation(libs.standard.flags.ofrep) // brings core
implementation(libs.standard.flags.status)
}
}
}The Gradle plugin resolves from Maven Central, so add mavenCentral() to pluginManagement.repositories in settings.gradle.kts.
Working against a local checkout. Use a composite build instead of publishing snapshots. In the app's settings.gradle.kts:
val localFlags = file("../standard-flags-kmp")
if (localFlags.isDirectory) includeBuild(localFlags)Gradle substitutes one.rarebit.flags:* with the local modules. For the contract plugin, add the same includeBuild inside pluginManagement { }. ./gradlew publishToMavenLocal here works too, for tools that need a Maven repository.
Declare the wires the app reads, with their code defaults. A wire is the name the server exposes to your audience, never the server's flag key.
object Flags {
val Chat = BooleanFlag("chat_enabled", default = false)
val Purchases = BooleanFlag("purchases", default = false, ceiling = true) // the server may only lower it
val Maintenance = BooleanFlag("maintenance", default = false, killSwitch = true)
val HomeHero = StringFlag("homeHero", default = "control", values = setOf("control", "savings"))
val all = listOf(Chat, Purchases, Maintenance, HomeHero)
}Build the client once, in shared code:
val client = ClientInfo(platform = "android", version = BuildConfig.VERSION_NAME, build = BuildConfig.VERSION_CODE.toLong())
val http = HttpClient {
install(ClientHeaders) { client(client) } // every API call carries X-Client-*
install(HttpTimeout) { requestTimeoutMillis = 15_000 }
// your auth plugin here; the OFREP endpoint sits behind the app's own authentication
}
check(client.isRecognised) { "the server would treat $client as an unknown build" } // in a debug build or a test
val flags = StandardFlagsClient(
fetcher = OfrepClient(http, "https://api.example.com/ofrep/v1/evaluate/flags", client),
definitions = Flags.all,
store = lastGoodStore, // see below
contextKey = session.accountId, // whose flags these are
)
flags.load() // at launch, before the first read: the cached values
scope.launch { flags.refresh() } // at launch and on every foregroundRead without suspending:
when (flags.state(Flags.Chat)) {
FlagState.On -> showChat()
FlagState.Off -> hideChat()
FlagState.NotLoaded -> showChatFromDefault() // nothing usable from the server: the code default applies
}
val hero: String = flags.value(Flags.HomeHero)
val read = flags.read(Flags.Chat) // value, loaded, reason (KILL_SWITCH, STATIC, …), variant, and why it fell backOn sign-in, sign-out or an account switch, switch the HTTP client's credentials first, then call flags.setContext(newAccountId) and refresh(). The old account's values are dropped at once, even while a fetch is still running; its late answer is thrown away. (Calling setContext before switching credentials would let a fetch in between store the old account's flags under the new key.)
ClientInfo.isRecognised matters because the server never errors on a bad platform or version: it quietly treats the build as unknown, which loses every min_client flag.
Android. Back the store with DataStore or SharedPreferences, and refresh on foreground, for example from a ProcessLifecycleOwner observer's onStart:
val lastGoodStore = StringLastGoodStore(
read = { prefs.getString("flags.last_good", null) },
write = { value -> prefs.edit { if (value == null) remove("flags.last_good") else putString("flags.last_good", value) } },
)iOS. The library is consumed through your shared KMP module (there is no separate Swift package). In iosMain, use the Darwin engine and NSUserDefaults, and call refresh() from the app's scenePhase == .active handler through a shared function:
val lastGoodStore = StringLastGoodStore(
read = { NSUserDefaults.standardUserDefaults.stringForKey("flags.last_good") },
write = { value -> NSUserDefaults.standardUserDefaults.setObject(value, forKey = "flags.last_good") },
)Bootstrap. If a response the app fetches at launch embeds the flags (the server's standard_flags_payload(audience, format: :ofrep), for example inside /me), seed from it to save a round trip: flags.seed(meResponse.flagsJson). The next refresh() sends its version as If-None-Match and usually gets a 304.
Pre-auth audiences. For an endpoint mounted with anonymous: true, pass targetingKey = { installId } to OfrepClient. Install IDs must be random and unguessable, and the answers are public.
PayloadLimits.maxBytes and maxFlags, strict RFC 8259 JSON in UTF-8 (no NaN, unquoted words, single quotes, leading zeros, lone or reversed surrogate escapes or trailing bytes, and at most maxNesting containers deep, 100 by default), an object with a flags array of objects with unique non-empty string keys, and metadata an object when present. Anything else is rejected, the last good payload stays, and the client backs off.StandardFlagsClient's PayloadLimits apply to fetched, seeded and stored payloads alike. The fetch streams the body: a Content-Length over the limit is refused without reading, and a body without one stops being read one byte past the limit, so an oversized answer never sits in memory.values all read as the code default with FlagState.NotLoaded. One bad flag never affects another.BooleanFlag(ceiling = true) reads default && server value, so the server can switch it off but never on, for example purchases on a platform whose store rules forbid them.LastGoodStore keeps the body, the contextKey it was fetched for and the build (ClientInfo.fingerprint: platform, version, build). A stored payload for another key, or saved by another build, is never applied: the server filters by build (min_client, deprecated wires), so an old build's answer could withhold or serve the wrong wires. After an upgrade the app starts on code defaults, and the first payload for the new build applies live. setContext drops the old values at once and clears a stored payload that belongs to another context. A store that throws never breaks the client: the failure shows in flags.storeError, and the in-memory values stay.metadata.version or ETag header that isn't a valid entity tag (1 to 256 printable ASCII characters other than a space or ") is ignored (no If-None-Match is sent), including the version of a stored payload loaded at launch. When three requests in a row that carry an If-None-Match are refused for it (400, 414 or 431, or the HTTP stack refuses the header), the client stops sending it, and remembers that in the stored record so a restart doesn't send it again; a payload with a new version sends its own. Offline spells, timeouts and other statuses don't count, so a bad value can't wedge fetching and an ordinary outage doesn't cost the 304.Backoff, 2 s doubling to 5 min by default), with Retry-After (seconds or any HTTP-date form) honoured as a floor, capped at an hour. A 401 or 403 stops fetching until setContext.refresh() calls share one fetch. Install a request timeout on the HTTP client all the same (HttpTimeout), so a stalled request doesn't hold up the next refresh.Values read at launch are the cached ones. A fresh payload is saved at once but applies at the next launch, so a screen never changes under the user. Two exceptions apply live:
KILL_SWITCH applies immediately, so a remote kill lands at the next foreground, not the next launch. Releasing it (the reason goes back to anything else) waits for the next launch. A BooleanFlag(killSwitch = true) applies live in both directions.setContext), the first payload applies at once.ApplyPolicy(freshValuesAtNextLaunch = false) applies every payload immediately; firstPayloadAppliesLive = false keeps code defaults until the next launch. flags.payload is a StateFlow of what code reads, and flags.pending holds the payload waiting for the next launch.
val status = ClientStatusClient(http, "https://api.example.com/client/status", client)
val api = HttpClient { install(UpgradeRequiredDetector) { this.status = status } }
scope.launch { status.check() } // at launch and on foreground
status.status.collect {
when (it) {
is ClientStatus.UpgradeRequired -> showBlockingUpgrade(it.details.storeUrl)
is ClientStatus.UpgradeRecommended -> showNudge(it.details.storeUrl, enforceAt = it.enforceAt) // a YYYY-MM-DD date, or null
is ClientStatus.Ok, is ClientStatus.Unknown -> Unit
}
}A failed check keeps the last known status, and an unknown build is never blocked. enforceAt is the UTC date enforcement starts (YYYY-MM-DD), not an instant. UpgradeRequiredDetector flips the status when any API call answers 426 with the server's client_upgrade_required error; a bare 426 is ignored. It reads the 426 body, which an ordinary Ktor call keeps for the app too, but a streaming call (prepare*().execute { }) doesn't.
OpenFeatureAPI.setProviderAndWait(StandardFlagsProvider(flags), ImmutableContext(targetingKey = accountId))
val chat = OpenFeatureAPI.getClient().getBooleanValue("chat_enabled", false)The provider reads through the client's declarations, so allowed values hold, and a ceiling flag is capped by its declared default whatever default the caller passes. It maps evaluation failures to OpenFeature error codes, passes the server's reason through (including KILL_SWITCH), and emits a configuration-changed event naming the wires that changed.
The targeting key is the client's context key: initialize hands it to setContext before loading, so the payload saved for it is the launch value, and a new targeting key calls setContext. Build the client with the same key, or none. The first fetch runs in the provider's scope: initialize waits up to initialFetchTimeout, and a slower fetch still lands afterwards.
The server commits a flags manifest (bin/rails standard_flags:manifest). Copy or reference it from the app and declare what the app reads:
plugins { id("one.rarebit.flags.contract") }
standardFlags {
manifest = rootProject.file("contracts/flags.manifest.json")
audience = "mobile"
wire("chat_enabled", "boolean")
stringWire("homeHero", "control", "savings") // with the values the app understands
// or wiresFile = file("flags.wires.json"):
// {"chat_enabled": "boolean", "homeHero": {"type": "string", "values": ["control", "savings"]}}
}Optionally, point baselineManifest at the manifest your shipped builds were made against. The check then also fails when the current manifest would break them (a wire removed or retyped, a public audience made private), with the server's standard_flags:manifest:check semantics. Both manifests are read as the server reads them, so a hand-edited file the server would refuse ({"version":2}, an audience without a boolean public, a date that isn't a calendar date) fails the check rather than passing. A version 1 baseline (standard_flags 0.3.0 and earlier) is read too, so removals across the upgrade to version 2 are still caught.
./gradlew check then runs checkFlagsManifest. It fails when a wire isn't exposed to the audience (naming any audience that does see it), when its type differs, or when the server can send a string value the app doesn't declare (the app would read its code default). It warns when the app declares a value the server never sends, and when a wire is only served by a deprecated tombstone, with its end date (failOnDeprecated = true makes that an error too). Once that date has passed the server no longer sends the wire, so reading it fails. Dates are UTC and computed when the task runs, even from the configuration cache; -PstandardFlags.today=YYYY-MM-DD reproduces a check on another day. It reads manifest versions 1 and 2.
The check depends on the date. A build that passed yesterday can fail today with nothing in the repository changed, in two ways:
until date has passed. Stop reading it: remove it from the app's declarations (and the code that reads it). The server no longer sends it, so the app already gets its code default.baselineManifest, the server moved a tombstone's until earlier than the baseline promised. Until the new date this is only a warning ("earlier than … shipped clients were promised"); the day after, the check fails with the wire as removed, whether or not this app still reads it, because the baseline covers every wire your shipped builds were told about. Removing the wire from the app doesn't help. If the earlier date is intended (the builds that read the wire are no longer supported), move baselineManifest to the current manifest; otherwise have the server restore the date it promised.To rebuild an old commit as it built at the time (a release branch, a reproducible build), pass the date it was built on: ./gradlew check -PstandardFlags.today=2026-01-15. Don't use this to keep shipping a wire past its end date.
The plugin's supported surface is the plugin id one.rarebit.flags.contract, the standardFlags { } block, the checkFlagsManifest task and the standardFlags.today property; its Java classes are internal and may change in any release.
conformance/ vendors the gem's wire-scope fixtures at the commit pinned in conformance/PIN.json. The tests run them on the JVM, Android and the iOS simulator: version and build ranges, payload in → reads out (through FlagCache and again through StandardFlagsClient), every golden delivery body and its ETag, every wire/client_status.json status body, and every wire/manifest_check.json case through the Gradle plugin's ManifestCheck. A test fails if a vendored fixture has no runner. scripts/sync-conformance --ref main moves the pin; CI runs scripts/sync-conformance --check, which also refuses any file in conformance/ the pin doesn't list.
Releases follow semantic versioning, and each Kotlin module's public API is checked against its api/ dump.
PayloadLimits, ApplyPolicy, ClientInfo) are regular classes, not data classes: construct them and read their properties, and compare them with ==.FlagEntry, FlagRead, StatusDetails, StoredPayload, and the cases of FetchStatus, FetchResult, RefreshOutcome, PayloadResult and ClientStatus mirror what the server sends or what the client reports, and grow with them. Read their properties by name; don't destructure them (val (key, value) = entry) or rely on copy or their constructor's parameter order. When building one for a test or a preview, use named arguments../gradlew check # every test; on macOS this includes the iOS simulator
./gradlew iosSimulatorTests # only the iOS simulator tests
./gradlew publishToMavenLocal # all modules into ~/.m2 (add -PRELEASE_SIGNING_ENABLED=false for a release version)
./gradlew updateKotlinAbi # after an intended public API change; check fails on any otherThe public API of each Kotlin module is recorded in its api/ folder (Kotlin's ABI validation), and check fails when it changes unexpectedly.
Releases go through CI: a v* tag matching VERSION_NAME publishes to Maven Central. See AGENTS.md.
MIT. See LICENSE.