Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / docs / package-structure.md

package-structure.md12.3 KiBRenderedCodeRaw
1# Package and code-structure mandate
2
3This document is normative. “Must” and “must not” are merge requirements,
4not preferences. The root `AGENTS.md` §2 is the short form; this file is the
5complete rulebook. A change that needs a new package root, package segment,
6or structural exception must update this document, `AGENTS.md`, and the
7relevant lint detector in the same change. A suppression, lint baseline, or
8detekt/lint config relaxation is not an exception mechanism.
9
10## 1. Applicability and profiles
11
12### 1.1 App profile
13
14The app profile applies to every shipped Android app whose base package is
15`com.vayunmathur.<app>`, including the nested `com.vayunmathur.cast.tv`
16app. The Gradle module layout must mirror the package ownership below.
17
18### 1.2 Shared-library and SDK profile
19
20`com.vayunmathur.library.*`, `com.vayunmathur.sdk.*`, and the two wire-format
21packages `com.vayunmathur.cast.protocol` and `com.vayunmathur.auto.protocol`
22are shared-library packages, not app packages. Their first segment names the
23library or wire module. Files inside them still follow the responsibility
24rules in §4–§10: transport code in the networking library, persistence code
25in the persistence library, native bridges behind guarded wrappers, and no
26generic dumping-ground packages.
27
28### 1.3 Games profile
29
30Game packages under `com.vayunmathur.games.<game>` are not silently exempt
31from architecture review. They use the same responsibility vocabulary
32(`ui`, `data`, `domain`, `platform`, `network`, `intents`, `service`,
33`provider`, `widget`, `notifications`, `sync`, `telephony`) below
34the game segment. A game may keep an existing game-specific layout only as
35migration debt; it must not add a new top-level game root or a generic
36package segment.
37
38## 2. Package grammar
39
40An app package has this shape:
41
42```text
43com.vayunmathur.<app>[.<root>[.<feature>[.<subfeature>]]]
44```
45
461. Every segment is lowercase ASCII and uses a singular responsibility noun
47 (for example `widget`, not `widgets`).
482. The first segment after the app base is called the **root**. Roots are a
49 closed set (§3). No other root may be introduced without amending this
50 document, `AGENTS.md`, and `PackageStructureDetector` together.
513. A segment below the root names a feature, capability, provider, protocol,
52 or data boundary. It must not name a programming-language construct, UI
53 toolkit, generic class type, or vague bucket.
544. The following segments are forbidden at every depth:
55 `api`, `apis`, `base`, `common`, `core`, `feature`, `features`, `helper`,
56 `helpers`, `impl`, `manager`, `managers`, `misc`, `presentation`,
57 `repository`, `repositories`, `screen`, `screens`, `util`, `utils`,
58 `view`, `views`, `viewmodel`, and `viewmodels`.
595. The canonical class-shape exceptions are `ui/components`, `ui/dialogs`,
60 and `data/model`. They are allowed only with those exact meanings:
61 reusable UI pieces, modal UI, and persisted/wire data shapes. They do not
62 authorize synonyms elsewhere.
636. A package must not be created for one trivial file unless it is a root or
64 one of the explicit structural owners in §§5–10.
657. The directory path and the Kotlin `package` declaration must agree.
66
67## 3. Closed app roots and root files
68
69### 3.1 Allowed roots
70
71An app may use only these roots:
72
73| Root | Sole responsibility |
74|---|---|
75| `ui` | Screens, screen content, dialogs, and reusable app UI components. |
76| `data` | Room, DataStore, files, repositories, persistence/wire DTO mapping, and the single preferences owner. |
77| `domain` | Pure models, algorithms, parsers, validators, and business rules with no Android or Compose dependency. |
78| `platform` | ViewModels, Android-framework adapters, sensors, system-service integration, and guarded native bridges. |
79| `network` | The app’s single public `Networking` entry point and its private endpoint/protocol implementation. |
80| `intents` | Assistant/cross-app IPC contracts and exported-intent parsing/validation. |
81| `service` | Android `Service` implementations and service-owned helpers. |
82| `provider` | Android `ContentProvider` implementations. |
83| `widget` | All home-screen widget code, flat: Glance widgets, legacy widget providers, receivers, actions, and widget state. |
84| `notifications` | Notification channels, builders, actions, and presentation. |
85| `sync` | Sync adapters, sync workers, and reconciliation. |
86| `telephony` | Carrier, SIM, telephony, and messaging-transport adapters. |
87
88### 3.2 Widget package rule
89
90Widget code must be directly under `.<app>.widget`. The following are
91forbidden:
92
93- `.<app>.widgets`
94- `.<app>.widget.glance`
95- `.<app>.glance`
96- any other descendant of `.<app>.widget`
97
98`Glance` is an implementation detail of the widget surface, not a package
99boundary. A widget receiver, widget class, action callback, and immutable
100widget snapshot all belong directly in `widget`.
101
102One widget, one file: each widget lives in exactly one file directly in
103`widget`, and that file declares the widget class (a `MaWidget` subclass)
104at top level together with its receiver. Every file in `widget` must
105declare such a widget class at top level — there are no helper-only
106files in `widget`. Widget helper code (snapshot types, action
107callbacks, private composables, formatting helpers) is nested inside
108the widget class or kept in the same widget file; helpers that serve
109app (non-Glance) concerns do not belong in `widget` at all and move to
110the canonical root for that concern (`ui`, `data`, `domain`,
111`platform`).
112
113### 3.3 App-root files
114
115When the base package `com.vayunmathur.<app>` is not empty, it may contain
116only:
117
118- `MainActivity.kt`, containing only `class MainActivity : MaActivity`;
119- `Route.kt`, containing only `sealed interface Route : NavKey` and nested
120 route declarations;
121- `Navigation.kt`, containing only `@Composable fun Navigation(...)`;
122- `*Application.kt`, containing only the matching `Application` subclass.
123
124No other declaration may live in the app-root package.
125
126## 4. Root ownership rules
127
128### 4.1 `ui`
129
130- A screen or content composable lives in `ui`; a ViewModel never lives in
131 `ui`.
132- There is one public `@Composable` per file, and the file is named for it.
133- `ui` must not construct HTTP requests, open databases, access raw
134 preferences, load native libraries, or parse exported intents.
135- Feature subpackages are allowed. `ui/components` and `ui/dialogs` are the
136 only class-shape subpackages.
137
138### 4.2 `data`
139
140- Room databases, DAOs, repositories, DataStore owners, files, and DTO
141 mapping live here.
142- Every app has exactly one preferences owner in `data`, named
143 `<App>Prefs` (for example `CalendarPrefs`). It is the only app code that
144 opens that app’s DataStore or SharedPreferences. It must expose typed
145 values/flows and must recover from `CorruptionException` by returning the
146 documented default state instead of crashing.
147- Persisted or external data must be decoded through non-throwing helpers
148 in `data` or `domain`. A Room type converter must never throw; corrupt
149 input maps to null, an empty value, or a clamped valid value.
150
151### 4.3 `domain`
152
153- `domain` is pure Kotlin: no `android.*`, `androidx.*`, Compose, Android
154 resources, Context, or file/network I/O.
155- Models, algorithms, parsers, validators, recurrence/date logic, and
156 safe-decoding primitives belong here when they do not need Android.
157- A parser for untrusted or persisted input must return a result/null (or a
158 sealed failure), not throw for malformed data.
159
160### 4.4 `platform`
161
162- ViewModels, Android-framework adapters, permission/system-service glue,
163 sensors, workers that are not sync-owned, and native bridges live here.
164- A native library has exactly one Kotlin wrapper in `platform`, named
165 `<Feature>Native`. That wrapper is the only app file that may call
166 `System.loadLibrary` for that library. It must expose an `available`
167 result and must never let a load failure poison class initialization.
168- JNI-frozen fully-qualified names are the only exception, and each one must
169 carry `// PACKAGE STRUCTURE EXCEPTION (JNI)`.
170- Exported-intent parsing does not belong in an Activity. It belongs in an
171 `intents` contract (§4.6); `platform` may consume the validated result.
172
173### 4.5 `network`
174
175- Every app that talks to a network has exactly one public networking entry
176 point in `network`, named `Networking` (an `object`, or a single
177 injectable class with that name). Other packages call only `Networking`.
178- `Networking` owns the `NetworkClient`, the narrowest applicable
179 `TrustBundle`, base URLs, endpoint paths, HTTP methods, authentication
180 headers, retries, cancellation, and response-status mapping.
181- Endpoint-specific clients, DTOs, and protocol helpers inside `network`
182 are implementation details. They must not be called from `ui`, `data`,
183 `domain`, `platform`, `service`, `provider`, `widget`, or `intents`.
184- No code outside `network` and `library.network` may construct a raw HTTP
185 request or open a raw network socket for an API call. This includes
186 `NetworkClient`, `HttpURLConnection`, `URL.openConnection`, OkHttp, and
187 Retrofit.
188- Protocol libraries that are inherently connection-oriented (for example
189 IMAP/SMTP) live under `network` by protocol; their public surface is still
190 mediated by `Networking`.
191
192### 4.6 `intents`
193
194- Every exported Activity, Service, Receiver, provider, or assistant action
195 has exactly one contract type here, named `<Feature>IntentContract` or
196 the existing app-specific contract name ending in `Intent`.
197- The contract owns extra keys, type checks, numeric ranges, enum parsing,
198 defaults, and malformed-input rejection. Entry points consume only the
199 validated result.
200- Cross-app IPC payload types live here, not in `ui` or `platform`.
201
202### 4.7 `service`, `provider`, `notifications`, `sync`, `telephony`
203
204- `service` contains Android Service implementations; a Service’s parsing
205 and business rules belong in `intents`, `domain`, or `data` as above.
206- `provider` contains ContentProvider implementations and stays flat.
207- `notifications` owns notification construction; it does not own the work
208 that produces the notified event.
209- `sync` owns sync orchestration and reconciliation; remote calls go
210 through `network.Networking`.
211- `telephony` owns carrier/SIM/telephony adapters; message business rules
212 belong in `domain` and network transport in `network`.
213
214## 5. Initialization and parsing safety
215
2161. A companion object, object initializer, top-level property, or class
217 initializer must not perform unguarded I/O, parsing, database access, or
218 native-library loading.
2192. A throwing initializer is a crash bug even if the input that triggers it
220 is rare. Initializers use defaults, lazy initialization, or an explicit
221 guarded `available`/failure state.
2223. `Json.decodeFromString`, `Base64.decode`, `UUID.fromString`, enum
223 `valueOf`, and date/time `parse` calls on persisted, IPC, file, or network
224 data must go through a non-throwing helper in `data` or `domain`.
2254. Room converters and widget state loaders must be total functions: bad
226 persisted data produces a documented fallback, never an exception.
227
228## 6. Regex rule
229
230Regex patterns that can receive process death, restore, IPC, file, or user
231input must be valid for Android’s ICU-backed `java.util.regex`, not merely
232for the desktop JVM. In particular, a literal `{` or `}` outside a valid
233quantifier or character class must be escaped. Regex constants belong in
234`domain` when pure, or beside the single parser that owns them in `data`.
235
236## 7. Widget state rule
237
238A widget must render from one immutable snapshot loaded for that render.
239It must not combine a newly computed date/index/key with a stale map or
240list without a fallback. Indexing widget state uses `getOrNull`, an empty
241default, or an explicit loading state.
242
243## 8. Enforcement
244
2451. `PackageStructure` lint is blocking. It enforces the closed roots, the
246 app-root file contracts, and the flat `widget` rule.
2472. Every Modern-Apps lint issue is blocking. An issue may not be made
248 advisory to land a change.
2493. A violation is fixed by moving/factoring the code, not by adding a
250 suppression, lint baseline, detekt baseline, or config relaxation.
2514. The only package exception is a JNI-frozen fully-qualified name, marked
252 verbatim with `// PACKAGE STRUCTURE EXCEPTION (JNI)`.
2535. Existing violations are migration debt, not precedents. Touching a file
254 in a violating package requires either migrating that package or leaving
255 the code in a package that complies with this document.