# TASK: build, run and test the "Skyline" Android app

You are a senior Android engineer working alone. The current directory contains only this
file. Create the whole project in `./skyline/` and write nothing outside that folder.
Work autonomously until section 11 is complete. Do not ask questions; when something is
ambiguous, choose the conventional option and record it in `skyline/REPORT.md`.
Re-read section 0 and section 11 before you stop.

## 0. Priorities, stop rule, scoring

Work in this order and do not move to a later priority while an earlier one is red:

- P0 `./gradlew assembleDebug` green, project scaffolded, git initialised.
- P1 unit and Robolectric tests exist and pass.
- P2 six screens, navigation map, both network calls, Room cache.
- P3 the four updating paths (U1 to U4), offline mode, settings.
- P4 emulator: instrumented test, screenshots, smoke script.
- P5 motion and polish (M1 to M10), adaptive layout, accessibility.

Stop rule: if the same failure survives five distinct fix attempts, mark the item ❌ in
`REPORT.md` with the exact error and move on. `assembleDebug` must never stay red.

Scoring: an honest ❌ costs only that item. A ✅ that is not backed by code and command
output loses the item plus all honesty points. Fabricated screenshots or test output,
or disabling tests (`@Ignore`, `assumeTrue(false)`, emptied bodies, Gradle excludes),
scores zero for the whole run.

Console hygiene: run Gradle as `./gradlew <task> --console=plain 2>&1 | tail -n 80`.
For compile errors use `... 2>&1 | grep -E '^e: |error:|FAILED' | head -n 40`. Read lint
from `skyline/app/build/reports/lint-results-debug.txt`.

## 1. Toolchain (use exactly these; all resolve on this machine)

- Generate the wrapper with the system Gradle: `cd skyline && gradle wrapper --gradle-version 9.3.1`.
  Commit `gradlew`, `gradlew.bat` and `gradle/wrapper/gradle-wrapper.jar`.
- `gradle/gradle-daemon-jvm.properties`: `toolchainVersion=21`.
- `gradle.properties`:
  ```
  org.gradle.jvmargs=-Xmx4g
  android.useAndroidX=true
  android.disallowKotlinSourceSets=false
  ```
- Do **not** create `local.properties`; export `ANDROID_HOME=$HOME/Android/Sdk`
  in every shell command instead (shell state does not persist between commands).
- `settings.gradle.kts`: `pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }`,
  `dependencyResolutionManagement { repositories { google(); mavenCentral() } }`, `include(":app")`.
- `gradle/libs.versions.toml` versions:
  ```
  agp = "9.1.1"            kotlin = "2.2.10"          ksp = "2.2.10-2.0.2"
  composeBom = "2026.06.01" coreKtx = "1.19.0"        activityCompose = "1.13.0"
  lifecycle = "2.11.0"     navigation = "2.9.8"       koin = "4.2.2"
  room = "2.8.4"           datastore = "1.2.1"        work = "2.11.2"
  coroutines = "1.11.0"    okhttp = "5.4.0"           serializationJson = "1.9.0"
  splashscreen = "1.2.0"   adaptive = "1.3.0"         robolectric = "4.16.1"
  junit = "4.13.2"         androidxTestExtJunit = "1.3.0"
  espresso = "3.7.0"       androidxTestRunner = "1.7.0"
  ```
- Plugins: `com.android.application` (agp), `org.jetbrains.kotlin.plugin.compose` (kotlin),
  `org.jetbrains.kotlin.plugin.serialization` (kotlin), `com.google.devtools.ksp` (ksp).
  AGP 9 has Kotlin built in: **do not** apply `org.jetbrains.kotlin.android`.
- Artifact coordinates that models often get wrong:
  - `androidx.compose:compose-bom` (platform), then versionless `androidx.compose.material3:material3`,
    `androidx.compose.material3:material3-adaptive-navigation-suite`, `androidx.compose.ui:ui`,
    `androidx.compose.ui:ui-tooling-preview`, `androidx.compose.animation:animation`,
    `androidx.compose.material:material-icons-extended`, `androidx.compose.ui:ui-test-junit4`;
    `androidx.compose.ui:ui-tooling` and `androidx.compose.ui:ui-test-manifest` as `debugImplementation`.
  - `androidx.compose.material3.adaptive:adaptive`, `:adaptive-layout`, `:adaptive-navigation` at `adaptive`.
  - `androidx.navigation:navigation-compose` at `navigation`.
  - `androidx.room:room-runtime`, `androidx.room:room-ktx` at `room`; `ksp("androidx.room:room-compiler")`.
  - `androidx.datastore:datastore-preferences`, `androidx.work:work-runtime-ktx`,
    `androidx.work:work-testing` (test), `androidx.lifecycle:lifecycle-runtime-compose`,
    `androidx.lifecycle:lifecycle-viewmodel-compose`, `androidx.lifecycle:lifecycle-process`,
    `androidx.core:core-splashscreen`, `androidx.activity:activity-compose`.
  - `io.insert-koin:koin-bom` (platform), then `io.insert-koin:koin-android`, `io.insert-koin:koin-androidx-compose`.
  - `com.squareup.okhttp3:okhttp`, `org.jetbrains.kotlinx:kotlinx-serialization-json`,
    `org.jetbrains.kotlinx:kotlinx-coroutines-android`, `org.jetbrains.kotlinx:kotlinx-coroutines-test` (test).
  - Tests: `junit:junit`, `org.robolectric:robolectric`, `androidx.test.ext:junit`,
    `androidx.test:runner`, `androidx.test.espresso:espresso-core`.
- `app/build.gradle.kts`: `namespace = "com.bench.skyline"`, `compileSdk = 37`, `minSdk = 26`,
  `targetSdk = 37`, `buildFeatures { compose = true; buildConfig = true }`,
  `compileOptions` Java 17, and
  `kotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } }` (there is no `kotlinOptions {}` in AGP 9),
  `testOptions { unitTests.isIncludeAndroidResources = true }`,
  `testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"`.
- `app/src/test/resources/robolectric.properties` containing `sdk=35` (Robolectric 4.16 cannot run SDK 37).
- Emulator and adb are not on PATH. Every emulator/adb command starts with:
  `export ANDROID_HOME=$HOME/Android/Sdk PATH=$HOME/Android/Sdk/platform-tools:$HOME/Android/Sdk/emulator:$PATH`.

## 2. The app

Skyline is a weather app. Users search for places, save them, and see current
conditions, a 24-hour strip and a 7-day forecast. Saved places refresh automatically and
on demand; cached data is shown offline with a stale indicator.

- Application id and root package `com.bench.skyline`, app name `Skyline`.
- Kotlin only, Jetpack Compose with Material 3. No XML layouts, no Fragments, no Java.
- Manifest declares `INTERNET` and `ACCESS_NETWORK_STATE`.

## 3. Network: two keyless HTTPS GET calls

Call A, place search:

```
https://geocoding-api.open-meteo.com/v1/search?name={query}&count=10&language=en&format=json
```

URL-encode `{query}`; call only when the trimmed query has at least two characters.
Response `{"results":[{"id":3196359,"name":"Ljubljana","latitude":46.05,"longitude":14.51,
"country":"Slovenia","admin1":"Ljubljana","timezone":"Europe/Ljubljana", ...}]}`.
`results` is absent when nothing matches; `admin1` and `country` may be absent.

Call B, forecast (one line, no spaces):

```
https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}
  &current=temperature_2m,apparent_temperature,weather_code,wind_speed_10m,relative_humidity_2m,is_day
  &hourly=temperature_2m,weather_code,precipitation_probability
  &daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,sunrise,sunset
  &timezone=auto&forecast_days=7
```

Use the URL as given; Open-Meteo returns °C and km/h by default and the app converts.
Response: `current` is an object with `time`, `interval` and the requested fields;
`hourly` and `daily` are objects of parallel arrays keyed by field name plus a `time`
array; `timezone` is an IANA name. Times look like `2026-09-28T14:00`, local time, no
offset, no seconds: parse with `java.time.LocalDateTime` (not `Instant`, not
`ZonedDateTime`). `hourly` has 168 entries; the 24-hour strip starts at the current
local hour. WMO `weather_code`: 0 Clear, 1 Mainly clear, 2 Partly cloudy, 3 Overcast,
45/48 Fog, 51–57 Drizzle, 61–67 Rain, 71–77 Snow, 80–82 Showers, 85/86 Snow showers,
95–99 Thunderstorm. Map every code to a label and an icon.

Rules: OkHttp with 10 s connect/read timeouts, header `User-Agent: Skyline/1.0`,
`kotlinx.serialization` with `ignoreUnknownKeys = true`, never crash on a missing field,
show HTTP and I/O failures as readable errors with Retry. You may `curl` both endpoints
once to capture test fixtures into `app/src/test/resources/`.

## 4. Data, settings, updating

- Room: `Place` (id, name, region, country, lat, lon, timezone, sortOrder, addedAt) and
  `Forecast` (placeId, fetchedAt, current/hourly/daily as JSON columns or normalised
  tables, your choice). Also `RecentSearch` (query, at) for the last five queries.
- DataStore Preferences: temperature unit (°C/°F), wind unit (km/h, mph), theme
  (system/light/dark), dynamic colour (on/off), auto-refresh interval (15 min, 1 h, 6 h,
  off), onboarding done flag.
- Repository is the single source of truth: UI observes Room via `Flow`; network results
  are written into Room; UI never calls the network directly.
- Stale: a forecast is stale 30 minutes after `fetchedAt`. Stale data is still shown,
  with an "Updated 42 min ago" label that changes colour when stale.
- Updating paths (all four required):
  - U1 pull-to-refresh on Places and on Detail (`PullToRefreshBox`).
  - U2 foreground refresh: when the app returns to foreground (`ProcessLifecycleOwner`)
    and any saved place is stale, refresh it.
  - U3 periodic refresh of all saved places with WorkManager (unique periodic work,
    `ExistingPeriodicWorkPolicy.UPDATE`, constraint network connected), honouring the
    interval setting; changing the setting reschedules or cancels. Workers get their
    dependencies via Koin (`KoinComponent`).
  - U4 "Refresh all" in Diagnostics with per-place progress.
- Offline: `ConnectivityManager` network callbacks exposed as a `Flow<Boolean>`; when
  offline, cached data still opens and a non-blocking banner says so.
- Every network attempt (both endpoints, all four paths) appends a `NetworkEvent`
  (time, URL, status or error, duration ms) to Room, capped at the last 50.

## 5. Screens and navigation map

Navigation Compose with `@Serializable` type-safe routes, one `NavHost`.

Top-level destinations: **Places**, **Settings**, **Diagnostics**, hosted in a
`NavigationSuiteScaffold` (bottom bar below 600 dp width, navigation rail at 600 dp and
wider). **Search** opens from the Places FAB. **Detail** opens from a Places card tap.
**Onboarding** shows only on first launch, has no bar, and "Get started" replaces the
back stack with Places. Below 600 dp Detail is its own destination; at 600 dp and
wider the Places destination hosts a `ListDetailPaneScaffold` with Detail in the
second pane, and the `PlaceDetail` route and deep link still work.

Every destination has a deep link (`scheme="skyline"`, manifest `<intent-filter>` with
`android.intent.action.VIEW`, categories DEFAULT and BROWSABLE, `navDeepLink<T>(basePath = ...)`):
`skyline://onboarding`, `skyline://places`, `skyline://search`, `skyline://place/{id}`,
`skyline://settings`, `skyline://diagnostics`. An unknown place id shows a not-found
state. Predictive back works everywhere, including the bottom sheet
(`android:enableOnBackInvokedCallback="true"`).

1. **Onboarding**: three `HorizontalPager` steps with a page indicator and a parallax
   illustration (M10); the last page has the °C/°F choice.
2. **Places**: cards with name, region, current temperature, condition icon, a 24-hour
   mini strip, and the stale label. Empty state with illustration and call to action.
   `SwipeToDismissBox` removes with an Undo snackbar. Up/down actions reorder
   (persisted). FAB to Search. U1.
3. **Search**: text field with 300 ms debounce, results from call A, per-result Add
   that becomes an animated checkmark when saved, loading/empty/error states, recent
   searches when the field is empty. Query survives rotation and process death.
4. **Detail**: large header with place name and current temperature (shared element
   from the card, M1); chips for feels-like, wind, humidity; horizontally scrolling
   24-hour strip; 7-day list with min/max bars drawn on a `Canvas`; sunrise/sunset row.
   Tapping a day opens a `ModalBottomSheet` with that day's hours. U1.
5. **Settings**: every preference from section 4 except the onboarding flag, as
   Material 3 list items with switches, segmented buttons or a dialog. Changes apply
   immediately everywhere.
6. **Diagnostics**: app version and build type from `BuildConfig`, last successful
   sync per place, connectivity state, WorkManager last run and next run, "Refresh all"
   with progress (U4), the `NetworkEvent` log, "Reset onboarding", and a hand-written
   open-source licence list (no licence Gradle plugin).

## 6. Motion and polish (M1 to M10, all required)

- M1 `SharedTransitionLayout` + `sharedBounds`/`sharedElement` from Places card to
  Detail header (required below 600 dp).
- M2 per-destination transitions: fade-through between top-level tabs,
  `slideInHorizontally { it } + fadeIn()` into Detail,
  `scaleIn(initialScale = 0.9f) + fadeIn()` into Search, mirrored exits.
- M3 `Modifier.animateItem()` on every `LazyColumn` item so add/remove/reorder animate.
- M4 loading → content → error switches via `AnimatedContent` or `Crossfade`.
- M5 shimmer skeleton placeholders while a first forecast loads
  (`rememberInfiniteTransition`; never a `while(true)` coroutine, which blocks Compose
  tests from idling).
- M6 temperatures count up/down on change (`animateIntAsState`).
- M7 looping animation on the current-condition icon (`rememberInfiniteTransition`).
- M8 splash via `core-splashscreen`, held with `setKeepOnScreenCondition` until the
  onboarding flag is read so the start destination never flickers.
- M9 predictive back on every screen and the bottom sheet.
- M10 onboarding pager parallax.

Also required: `enableEdgeToEdge()` with `WindowInsets` handled (no content under
bars, no double padding); Material 3 theme with dynamic colour on Android 12+ when
enabled and a hand-tuned light and dark fallback; colours only from `MaterialTheme`
tokens; adaptive launcher icon with a monochrome layer, all vector; 48 dp touch
targets; `contentDescription` on every icon-only action; each list card is one merged
semantics node; rotation and font scale 1.3 break nothing.

## 7. Architecture and code quality

- Single `:app` module; packages `core/{network,database,datastore,ui,work}` and
  `feature/{onboarding,places,search,detail,settings,diagnostics}`.
- MVVM, unidirectional data flow: one `ViewModel` per screen exposing an immutable
  `UiState` via `StateFlow` (`stateIn(WhileSubscribed(5_000))`), collected with
  `collectAsStateWithLifecycle`; one-shot effects via `Channel`. Screens are stateless
  composables taking `UiState` and callbacks; a `*Route` composable wires the ViewModel.
  Every stateless screen has a `@PreviewLightDark` preview.
- DI with Koin 4 only; `startKoin` must be idempotent (Robolectric creates the
  `Application` per test).
- Coroutines throughout; `Dispatchers.IO` injected; no `GlobalScope`, no `runBlocking`
  in production code.
- `SavedStateHandle` for the search query and selected place.
- All user-visible text in `res/values/strings.xml`; no hard-coded colours.
- `@OptIn` only for the specific experimental APIs used.
- `README.md` with what it is, how to build, how to test, and an "Architecture"
  section (layers, data flow, refresh strategy U1–U4).

## 8. Tests

Unit tests (`src/test`, `./gradlew testDebugUnitTest`):

- Parsing both endpoints from fixtures, including a geocoding response without
  `results` and a forecast with a missing optional field.
- Table-driven unit conversion (°C↔°F, km/h↔mph) and WMO code → label.
- Repository with a fake API and Robolectric in-memory Room: refresh writes cache;
  stale at 30 min; network failure keeps cache and reports the error; a
  `NetworkEvent` is logged on success and on failure.
- WorkManager with `work-testing`: `TestListenableWorkerBuilder` runs the worker;
  `WorkManagerTestInitHelper` shows that changing the interval re-enqueues or cancels
  the unique work.
- Each ViewModel: initial state, loading → content, loading → error with Retry, unit
  change re-renders, Search restores its query from `SavedStateHandle`.
- Robolectric Compose tests (`ui-test-junit4`), at least one per screen: Places empty
  and populated; Search typing shows results; Detail renders 7 days; Settings toggle
  persists; Onboarding "Get started" navigates; Diagnostics shows the log.

Instrumented test (`src/androidTest`, `./gradlew connectedDebugAndroidTest`): clears
app data in `@Before`, launches `MainActivity`, completes onboarding, searches
"Ljubljana", adds the first result, opens Detail, goes back, opens Settings, flips to °F,
returns to Places and asserts the card temperature ends in "°F".

Static: `./gradlew lint` finishes with zero errors.

## 9. Emulator run and screenshots

Write `skyline/scripts/smoke.sh` that does all of this, and run it:

```
export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH
nohup setsid emulator -avd Medium_Phone -no-window -no-audio -no-boot-anim \
  -no-snapshot-save -gpu swiftshader_indirect >/tmp/emu.log 2>&1 &
timeout 300 adb wait-for-device
timeout 300 adb shell 'while [ "$(getprop sys.boot_completed)" != "1" ]; do sleep 2; done'
./gradlew connectedDebugAndroidTest --console=plain 2>&1 | tail -n 40
./gradlew installDebug --console=plain 2>&1 | tail -n 5
adb shell pm clear com.bench.skyline
```

Then use deep links to reach every screen, and capture with
`adb exec-out screencap -p > docs/screens/NN-name.png`:

```
adb shell am start -W -a android.intent.action.VIEW -d "skyline://settings" com.bench.skyline
adb shell uiautomator dump /sdcard/ui.xml && adb pull /sdcard/ui.xml /tmp/ui.xml   # find nodes
adb shell input text "Ljubljana"   # in Search
```

Required files in `skyline/docs/screens/`: `01-onboarding.png`, `02-places.png`
(with at least two saved places), `03-search.png` (with results), `04-detail.png`,
`05-settings.png`, `06-diagnostics.png` (log showing both endpoints),
`07-detail-dark.png` (after `adb shell cmd uimode night yes`), `08-tablet.png` (after
`adb shell wm size 1600x2560 && adb shell wm density 320`, showing list–detail),
`09-offline.png` (after `adb shell svc wifi disable && adb shell svc data disable`,
showing cached data plus the banner). Restore with `cmd uimode night no`,
`wm size reset`, `wm density reset`, `svc wifi enable`, `svc data enable`. Also save
`adb shell dumpsys jobscheduler | grep -A5 com.bench.skyline` to `docs/jobscheduler.txt`.
Finish with `adb emu kill`. If the emulator cannot boot, write the tail of
`/tmp/emu.log` into `REPORT.md`; never fake screenshots.

## 10. Working method

1. `git init` in `skyline/`, scaffold, get `assembleDebug` green, commit.
2. Build vertically: network + Room + Places end to end, then the other screens.
3. Run `testDebugUnitTest` after every feature; never leave it red.
4. Only after unit tests pass: section 9.
5. Finish with `./gradlew clean assembleDebug testDebugUnitTest lint` and paste the
   last 30 lines into `REPORT.md`.
6. Commit as you go with meaningful messages; the final commit is the one you report on.

## 11. Definition of done: `skyline/REPORT.md`

`REPORT.md` has these sections: **Versions**, **Decisions**, **Checklist**, **Known gaps**,
**Final build tail**. The checklist is this table, one row per item, with ✅/❌ and the
command output or file path that proves it:

| Item | How to verify | Expected |
|---|---|---|
| Build | `./gradlew clean assembleDebug` | BUILD SUCCESSFUL |
| Unit tests | `./gradlew testDebugUnitTest`; count `app/build/test-results/testDebugUnitTest/*.xml` | BUILD SUCCESSFUL, ≥ 25 tests |
| Lint | `./gradlew lint`; `grep -c 'Error' app/build/reports/lint-results-debug.txt` | 0 errors |
| Instrumented | `./gradlew connectedDebugAndroidTest` | BUILD SUCCESSFUL |
| Six screens | `ls docs/screens/*.png \| wc -l` | 9 files, 1080x2400 (08 is 1600x2560) |
| Deep links | six `am start` commands | each opens its screen |
| Network A + B | `06-diagnostics.png` log | both hosts visible |
| U1–U4 | code paths named with file:line; `docs/jobscheduler.txt` | present |
| Offline | `09-offline.png` | cached data + banner |
| M1–M10 | file:line for each | present |
| Theme, edge-to-edge, tablet, a11y | `07-detail-dark.png`, `08-tablet.png`, `uiautomator dump` has `content-desc` on icon buttons | present |
| Rotation + process death | `adb shell am kill com.bench.skyline` after typing in Search, relaunch | query restored |
| README | file exists with Architecture section | present |

Quality bar: this should look and feel like a polished 2026 Play Store app, not a demo.
Every state (loading, empty, error, offline, stale, not-found) has a designed UI.
