# FreeAuto Architecture > Status: draft v0.1 · Created 2026-11-01 > This document exists so that an agent can make a correct decision without asking a human. > If something here is ambiguous, that is a bug — file it. --- ## 1. Constraints that drive every decision Design for these; they are not negotiable. | Constraint | Consequence | |---|---| | Runs on aftermarket units, Android 8–14, 1–2 GB RAM, slow eMMC | Buckets of care: cold start < 1.5 s, steady RAM < 120 MB, no eager DI graphs, no reflection-heavy stacks. | | Often **no Google Play Services** | No Firebase, no Play Integrity, no `GmsCore` calls in core. Media via `NotificationListenerService`, not GMS. | | Screens are wide, low-DPI, often 1024×600 | Layout must be **density-and-aspect driven**, never phone-shaped assumptions. Test 800×480, 1024×600, 1280×720, 1920×720. | | The unit is often the OEM's HOME replacement target | Must survive being killed, must have a fast `onCreate`, must never show a blank frame. | | The MCU is a black box that varies by vendor | All hardware access behind interfaces, with a mock that replays traces. | | Users sideload; no store review | Self-update, honest permissions, no anti-features. | | Contributors arrive with one head unit | The HAL must be extendable by someone who owns exactly one device. | --- ## 2. Module map A Gradle monorepo. The dependency rule is a strict DAG — **no cycles, ever**, and `core/model` depends on nothing. ``` freeauto/ ├── app/ # thin shell: Application, HOME activity, DI wiring, navigation root ├── core/ │ ├── model/ # domain types: VehicleSignal, Trip, Dtc, PluginManifest. No Android deps. │ ├── design/ # tokens, typography, colour, spacing, Compose components │ └── data/ # preferences (DataStore), Room DB, export/import ├── feature/ │ ├── home/ # home screen composition, layout engine │ ├── apps/ # app grid, dock, folders, search │ ├── media/ # notification listener, now-playing card, transport controls │ ├── vehicle/ # gauges, trip computer, DTCs, live data │ ├── climate/ # (Phase 3) read-only HVAC display │ ├── radio/ # (Phase 3) delegation + later native tuner │ └── settings/ # preferences UI, per-vehicle profiles ├── hal/ │ ├── api/ # VehicleBus, HeadUnitBus, capability descriptors. Pure Kotlin. │ ├── obd/ # ELM327 over BT SPP + USB serial; PID codec │ ├── mcu-mock/ # trace replay — REQUIRED, first adapter written │ ├── mcu-mtcd/ # Rockchip MTCx family │ ├── mcu-ksw/ # Qualcomm KSW family │ └── mcu-fyt/ # Unisoc 7862 / FYT ├── plugin/ │ ├── api/ # the published contract. Separate artifact, semver, stable. │ ├── runtime/ # plugin discovery, loading, isolation, permission enforcement │ └── sample-widget/ # reference implementation, built in CI ├── tools/ │ ├── hal-capture/ # on-device trace recorder │ ├── screenshot-matrix/ # render all viewports, diff against goldens │ └── avd/ # Gradle Managed Device definitions for head-unit shapes └── docs/ ├── adr/ # one decision per file, numbered ├── device/ # getprop dumps, MCU notes, per-model quirks ├── ROADMAP.md ARCHITECTURE.md BACKLOG.md FEATURE-INVENTORY.md └── AGENTS.md → ../AGENTS.md ``` **Allowed dependencies:** `app → feature/* → core/*`, `feature/* → hal/api`, `hal/* → hal/api`, `plugin/runtime → plugin/api`, `feature/*` **must not** depend on `hal/obd` or any concrete MCU adapter. Only `app` wires implementations. Rationale: an agent working on `feature/vehicle` must never need to know whether a signal came from OBD or from the MCU. If it does, the interface is wrong. --- ## 3. The two buses Everything hardware-specific enters through exactly two interfaces. This is the single most important design decision in the project. ### 3.1 `VehicleBus` — data about the car ```kotlin // hal/api — pure Kotlin, no Android imports interface VehicleBus { val capabilities: Set // what THIS car/unit can provide fun signals(): Flow // hot stream, deduplicated suspend fun query(id: SignalId): VehicleSignal? } data class VehicleSignal( val id: SignalId, // e.g. Speed, Rpm, CoolantTemp, FuelLevel, BatteryVoltage val value: Double, val unit: Unit, val timestampMs: Long, val quality: Quality // Valid | Stale | Estimated | Unsupported ) ``` Rules: - **`quality` is mandatory and must be honoured.** A gauge showing `Stale` data as if it were live is a safety defect (R4). UI must visibly degrade. - Signals are *pushed*, not polled by the UI. Adapters own their own polling cadence. - Capabilities are declared up front so the UI can hide what doesn't exist instead of showing a dead gauge. Hiding is better than "N/A". ### 3.2 `HeadUnitBus` — the car's own hardware ```kotlin interface HeadUnitBus { val family: HeadUnitFamily // Mock, Mtcd, Ksw, Fyt, None val capabilities: Set fun events(): Flow // IgnitionOn/Off, Illumination, Reverse, SwcKey, McuReset suspend fun send(cmd: UnitCommand): Result // v1: only RadioDelegate } ``` Rules: - **Read-only in v1.** The only write command permitted is `RadioDelegate` (an intent to the OEM radio app). No climate writes, no CAN writes, no "secret menu" commands. - Absence is normal. `HeadUnitFamily.None` is a first-class, fully supported state — the launcher must be complete and pleasant with zero MCU access. ### 3.3 Adapter selection ```kotlin // app/HalModule.kt fun selectHeadUnitBus(ctx: Context): HeadUnitBus = listOf(KswBus(ctx), MtcdBus(ctx), FytBus(ctx)) .firstOrNull { it.probe().isAvailable } ?: NoHeadUnitBus() ``` `probe()` must be cheap, non-blocking, and must never crash on an unknown device. Log *why* each adapter declined — that log line is what makes a bug report actionable. --- ## 4. The digital twin (how agents test hardware) The problem: an agent cannot plug in a head unit. The solution: make the hardware replayable. ``` ┌─────────────┐ capture ┌──────────────┐ replay ┌───────────────┐ │ head unit │ ───────────► │ trace file │ ──────────► │ MockHeadUnit │ │ + OBD link │ (tools/ │ (committed, │ (tests) │ MockVehicle │ └─────────────┘ hal-capture) anonymised) └─────────────┴───────────────┘ ``` Trace format (JSONL, one record per line, monotonic offsets — no wall-clock): ```json {"t": 0, "ch": "mcu", "dir": "in", "hex": "2E 01 00 00 7F"} {"t": 43, "ch": "mcu", "dir": "out", "hex": "2E 01 01 00 7E"} {"t": 210, "ch": "obd", "dir": "out", "ascii": "010C\r"} {"t": 232, "ch": "obd", "dir": "in", "ascii": "41 0C 1A F8 \r"} ``` Anonymisation is mandatory before commit: strip VIN, GPS, phonebook, and any audio payload. A CI check greps the fixtures directory for VIN-shaped strings. This is also the on-ramp for community adapter contributions — the single best answer to risk R1. --- ## 5. Plugin API (the "bigger" part) ### 5.1 Shape Separate APKs, discovered by intent filter, bound via a small stable contract. Not reflection, not in-process scripting, not a shared classloader. ```xml ``` ```kotlin // plugin/api (Apache-2.0, semver, published artifact) interface FreeAutoPlugin { fun describe(): PluginDescriptor // id, name, version, requiredApi, permissions fun createWidgets(): List // draw into a slot fun createDataSources(): List // contribute a VehicleSignal fun createIntegrations(): List // actions, intents, external devices } ``` ### 5.2 Rules 1. **Crash isolation.** Every plugin call runs with a timeout and a try/catch; a dead plugin is quarantined and reported, never crashes the shell. 2. **Permissions are declared, not implied.** A data source that wants location asks for it; a widget that wants the network asks for it. Declared in `describe()`, granted by the user. 3. **API stability is a promise.** `plugin-api` is semver. Breaking changes need a major version and a deprecation cycle of one minor release minimum. 4. **Widgets draw into a slot, not onto the canvas.** The launcher owns layout and theming; the plugin owns content. This is what keeps the UI coherent across 200 community widgets. 5. **No plugin may be required for core function.** An empty plugin set must still be a complete launcher. ### 5.3 Why APK plugins and not scripting | | APK plugins | In-process scripting (Lua/JS) | |---|---|---| | Isolation | Process-level, safe | Shared heap, a bad script kills the shell | | Performance | Native | Interpreter overhead on 1 GB units | | Tooling | Android Studio, familiar | Custom runtime to build and maintain | | Distribution | Any app store / GitHub | Needs its own registry | | Cost to v1 | Medium (IPC, permissions) | Low to start, high to harden | Decision: APK plugins for v1 (D6 in the roadmap). Revisit scripting only if simple-widget authoring turns out to be a real barrier. --- ## 6. Rendering, layout and theming - **Jetpack Compose.** Not because it's fashionable — because screenshot tests and a token-based theme are how agents get visual feedback without a human. - **Layout is aspect-ratio driven.** Design at 1024×600 dp-ish and use `BoxWithConstraints`; never hardcode px. A 1920×720 unit is *very* wide and short: vertical space is the scarce axis. - **Tokens, not colours.** `core/design` exposes semantics (`surface`, `onSurface`, `accent`, `warning`, `gaugeTrack`), and palettes map to them. Plugins get tokens, never hex. - **Day/night** switches on civil twilight from location, with manual override. Transition must be a cross-fade, not a flash at speed. - **Contrast floor in sunlight.** Minimum 4.5:1 for body text, 7:1 for glanceable gauges. This is enforced by a lint rule on the token palette, because it is otherwise invisible on a desk. --- ## 7. Persistence | Data | Store | Why | |---|---|---| | Preferences | `DataStore` (proto) | Type-safe, async, no `SharedPreferences` race | | Trips, DTC history, signal samples | Room/SQLite | Queryable, exportable, migration story | | Plugin registry, grants | Room + `PackageManager` | Survives reinstall of the plugin | | Traces (dev only) | Files in `hal/src/test/resources` | Never shipped in the APK | **Retention:** raw signal samples are the biggest data risk on a 1 GB device. Keep a rolling window (default 7 days of downsampled 1 Hz), configurable, and downsample aggressively — 10 Hz is never needed for a trip log. --- ## 8. Performance budgets (enforced in CI) | Metric | Budget | Where measured | |---|---|---| | Cold start to first frame | < 1500 ms | Macrobenchmark on a 2 GB emulator | | Warm start (HOME press) | < 400 ms | Macrobenchmark | | Steady-state PSS | < 120 MB | Manual, per release | | APK size | < 8 MB (no bundled art) | CI | | Frame time on home | < 16 ms p95 | Jank stats on device | | OBD poll cycle | ≥ 5 Hz for the 4 core PIDs, ≤ 20 Hz total | Unit test on the codec | A green build that violates a budget is not green. --- ## 9. Security and safety posture - No network calls in core except: weather (Open-Meteo), update check (a static release index), geocoding if the user enables it. All opt-out, all documented. - No analytics, no crash reporting by default. If added, it must be opt-in and self-hostable. - No `INTERNET` permission in the core module's manifest — features that need it declare it, so the permission list stays honest. - **Never write to the vehicle bus in v1.** The blast radius of a bad CAN write is a dashboard light at best and a bricked module at worst. Read-only until there is a very good reason. - DTC clearing is a deliberate two-step with an explanation, because it wipes readiness monitors and can fail an emissions test.