[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"nRIM75yBoT":3},"![Kotlean logo](docs/assets/kotlean-logo.webp)\n\n# Kotlean: Android apps, proven\n\n**The code you prove is the code that runs.**\n\nKotlean lets you write an Android app's state, behavior and UI in Lean, prove properties of that\ncode, and compile it into the app. A small Kotlin host renders native Android Views and performs\nplatform effects.\n\nThe problem it addresses is keeping a verified state machine connected to the application people\nactually use. Your Lean `update` and `view` functions run on the device. Buttons, text edits,\ngestures and timers enter that same state machine.\n\n## See it running\n\n\u003Cdiv align=\"center\">\n\nhttps://github.com/user-attachments/assets/448f86d3-7b9e-4f29-8ada-afcb71112eef\n\n\u003C/div>\n\nSnackNet is an original maze-chase game written in Lean. An AI machine collects thirteen data tokens\nwhile two human operators track and intercept it. **Overclock** turns the machine into a metal\nendoskeleton and lets it capture the operators. The recording shows a full win, including the\ncontinuously held D-pad and its highlighted directions.\n\nThe game has a 15-by-13 maze, continuous motion, buffered turns, swipe and keyboard steering, pause\nand restart. Its rules and drawing live in\n[SnackNet.Game](examples/snacknet/lean/SnackNet/Game.lean) and\n[SnackNet.View](examples/snacknet/lean/SnackNet/View.lean).\n\nThe [Counter example](examples/counter) is a smaller starter with buttons, an editable note, a\ndelayed increment, private-storage persistence and saved-instance restoration.\n\n## What you can build\n\n- Native interfaces with columns, rows, text, buttons, editable inputs and scrolling.\n- Canvas interfaces and games with drawing commands, multitouch and keyboard input.\n- Stateful apps with timers, Back handling, lifecycle subscriptions and persistence.\n- Android integrations through named plugins with byte payloads and replies.\n\nApp-specific models and messages stay in Lean. Both examples use the same Kotlin interface.\n\n## Architecture\n\nThe architecture follows an Elm-style model/update/view loop and Roc's separation between\napplication logic and platform effects. [Elm\narchitecture](https://guide.elm-lang.org/architecture/buttons) · [Roc\nplatforms](https://www.roc-lang.org/docs/main/langref/platforms/)\n\n1. `init` creates the model and initial commands.\n2. `update` consumes a message and returns a new model and command descriptions.\n3. `view` describes the native widgets or Canvas drawing.\n4. `subscriptions` describes the events the app currently wants.\n5. The host performs effects and sends their replies back through the Lean runtime.\n\n```text\nAndroid input → Event bytes → Lean update → Lean view/diff → Out bytes\n      ↑                                                       ↓\n      └──────── effect replies and subscriptions ← Android host\n```\n\nLean computes the view patches, request IDs and subscription changes. A fixed byte protocol crosses\nJNI. The Kotlin host interprets patches using Android Views and Canvas. One generated Lean app\nlibrary runs per process; Activities using that library have separate sessions.\n\nThe first version runs Lean on Android's main thread. Keep updates and drawing within the device's\nframe budget. Tick subscriptions carry eight little-endian bytes containing uptime in milliseconds,\nso animation can use elapsed time between callbacks.\n\n## Write an app\n\nCounter is a complete starter with a Lake package, Gradle configuration, manifest and Activity. A\nminimal Lean app has this shape.\n\n```lean\nmodule\nimport Kotlean\nmeta import Kotlean.Export\n\nopen Kotlean\n\ninductive Msg where\n  | increment\n\ndef update (_ : Msg) (count : Nat) : Nat × List (Cmd Msg) :=\n  (count + 1, [])\n\ntheorem increment_adds_one (count : Nat) :\n    (update .increment count).1 = count + 1 := rfl\n\ndef app : App := {\n  Model := Nat\n  Msg := Msg\n  init := (0, [])\n  update := update\n  view := fun count => .column { padding := 16 }\n    [ .text { text := toString count, textSize := 28 }\n    , .button { text := \"+1\", events := { click := some .increment } } ]\n}\n\nkotlean_app app\n```\n\n`kotlean_app` generates the native entry points at compile time. Start the host from\n`Activity.onCreate` after `super.onCreate`.\n\n```kotlin\nKotlean.run(this, \"counter\", savedInstanceState)\n```\n\nThe host owns the session through Activity destruction. Apps can supply a persistence codec, and\ncommand replies return through one-shot Lean continuations.\n\nThe Gradle plugin defaults to the app's `lean/` Lake package, its default target, and the Gradle\nproject name as the native library name. You can set them explicitly.\n\n```kotlin\nkotlean {\n    packageDirectory.set(file(\"lean\"))\n    module.set(\"Counter\")\n    libraryName.set(\"counter\")\n}\n```\n\nSee the repository [settings](settings.gradle.kts), [Counter\nbuild](examples/counter/build.gradle.kts) and [Lake package](examples/counter/lean/lakefile.toml)\nfor complete wiring.\n\n## Build the examples\n\nUse Linux x86-64 with Lean **4.34.0**, JDK **21**, Gradle **9.9**, Android SDK **37**, NDK **r30**,\nCMake, Git and `patch`. The apps require **Android 16 or later, API 36+**, on arm64.\n\nFrom the repository root, configure the installed tools and local build directories.\n\n```sh\nexport ANDROID_HOME=/path/to/Android/Sdk\nexport ANDROID_NDK_HOME=/path/to/android-ndk-r30\nexport KOTLEAN_TOOLCHAIN=\"$HOME/.elan/toolchains/leanprover--lean4---v4.34.0\"\nexport KOTLEAN_LEAN_SOURCE=\"$PWD/.deps/lean4\"\nexport KOTLEAN_LIBUV_SOURCE=\"$PWD/.deps/libuv\"\nexport KOTLEAN_CACHE=\"$PWD/.cache/kotlean\"\n\nmkdir -p .deps\ngit clone --depth 1 --branch v4.34.0 https://github.com/leanprover/lean4 \"$KOTLEAN_LEAN_SOURCE\"\ngit clone --depth 1 --branch v1.48.0 https://github.com/libuv/libuv \"$KOTLEAN_LIBUV_SOURCE\"\n\ncmake -S \"$KOTLEAN_LIBUV_SOURCE\" -B \"$KOTLEAN_LIBUV_SOURCE/build\" \\\n  -DCMAKE_TOOLCHAIN_FILE=\"$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake\" \\\n  -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-26 \\\n  -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \\\n  -DCMAKE_C_FLAGS=\"-ffunction-sections -fdata-sections\" \\\n  -DBUILD_TESTING=OFF -DLIBUV_BUILD_TESTS=OFF -DLIBUV_BUILD_SHARED=OFF\ncmake --build \"$KOTLEAN_LIBUV_SOURCE/build\" --target uv_a\n\nlake build kotlean\nexport KOTLEAN_BUILD=\"$PWD/.lake/build/bin/kotlean\"\ngradle --no-daemon :counter:assembleDebug :snacknet:assembleDebug\n```\n\nThe APKs are written to `examples/counter/build/outputs/apk/debug/counter-debug.apk` and\n`examples/snacknet/build/outputs/apk/debug/snacknet-debug.apk`.\n\nThe build generates Init and Std C with the pinned compiler, compiles Lean's runtime and links the\nselected app. Runtime imports support Init, Std and workspace modules compiled from Lean. Use\n`meta import` for Lean frontend and Lake code. Platform I/O goes through plugins. The NDK API 26\ncompilation target is compatible with the app's API 36 minimum.\n\nThe included runtime [patch](native/android/object-full-pointers.patch) preserves full pointer words\nin Lean's deletion worklist. Content-based receipts support incremental builds.\n\nFor device development, `-PsnacknetDeviceTest=true` enables a debug-only foreground mode that keeps\nthe display on and lets SnackNet appear over the lock screen. Default debug and release builds leave\nit off.\n\n## Verification boundary\n\nKotlean has Lean proofs for its wire codecs, canonical UI compilation, scene diff correctness, event\ndispatch, one-shot command continuations and subscription reconciliation. The [runtime\nlaws](lean/Kotlean/Runtime/Laws.lean) and [proofs](lean/Kotlean/Runtime/Verified.lean) expose those\ncontracts.\n\nApp authors prove their update properties. SnackNet proves traversable neighboring moves,\nnon-increasing token counts and preservation of lives during powered contact.\n\nJNI, Kotlin rendering and Android behavior are checked through integration and device tests. The\ncompiler and Android platform remain in the trusted execution path. Keep saved-instance data small\nbecause Android shares the process's Binder transaction buffer.\n\n## Measurements\n\nA Pixel 11 Pro playthrough reached the exit with **130 points and three lives**. Android reported\n**917 rendered frames and zero janky frames** after reset. The final 114 valid presentation\ntimestamps averaged **60.05 FPS**, with a maximum interval of **16.68 ms**.\n\nFor Counter, 1,000 warmed native JNI increment steps measured **39.25 μs median** and **47.29 μs\np95**. That interval covers the native step with pre-encoded input. Two cold Activity launches\nreported **174 ms** and **140 ms**.\n\nThe table compares generated arm64 native libraries with their stripped copies extracted from\nrelease APKs. The gzip column is a separate compression measurement.\n\n| Example | Generated bytes | Stripped bytes | Stripped + gzip bytes |\n| --- | ---: | ---: | ---: |\n| Counter | 6,846,184 | 1,694,760 | 535,719 |\n| SnackNet | 7,866,504 | 2,264,960 | 700,126 |\n\n## License\n\nKotlean is [MIT licensed](LICENSE). Lean's runtime retains its [Apache 2.0\nlicense](native/android/LEAN-LICENSE.txt).\n",1795286045287]