# AGENTS.md Operating instructions for AI coding agents working on **Foto Dup Finder**. Read this file before changing code, tests, monetisation, permissions or Android configuration. It defines the product boundaries, architecture rules and the definition of done for this repository. ## 1. Project snapshot | Item | Value | |---|---| | Product | Foto Dup Finder — offline duplicate/near-duplicate photo finder | | Model | **Freemium**: free tier with one AdMob banner, one-time Pro purchase removes ads | | Current version | `1.1.1` / `versionCode 6` (`app/build.gradle.kts`) | | Platform | Android, Kotlin + Jetpack Compose, single `:app` module | | Application id | `de.softwareapp_hb.fotodup.finder.free` (debug `.free.debug`); namespace/code package remains `de.softwareapp_hb.fotodup.finder` | | SDKs | `minSdk 26`, `compileSdk`/`targetSdk` 36 | | Toolchain | Gradle 9.3.1, AGP 9.1.0, Kotlin 2.4.10, JDK 17+ | | UI | Compose BOM 2026.06.01 (Compose 1.11.4, Material 3) | | Ads | Google Mobile Ads (legacy) 25.5.0 + UMP 4.0.0 | | Billing | Play Billing 9.1.0, one-time product `pro_no_ads` | | Persistence | SQLite `photo_index.db` (hash cache) + `pro_entitlement` SharedPreferences | | Tests | JVM unit tests + Robolectric; no instrumentation test suite | Architecture document: [`docs/codemap.md`](docs/codemap.md) Standalone Mermaid graph: [`docs/codemap.mmd`](docs/codemap.mmd) Monetisation setup: [`docs/MONETIZATION.md`](docs/MONETIZATION.md) Roadmap: [`docs/ROADMAP.md`](docs/ROADMAP.md) Release checklist: [`docs/PLAY_RELEASE_CHECKLIST.md`](docs/PLAY_RELEASE_CHECKLIST.md) Privacy policy: [`PRIVACY.md`](PRIVACY.md) **Current gate:** the freemium release (`1.1.1`) is implemented in code, but the Play Console work (change the app to free, create `pro_no_ads`, AdMob app/unit, UMP message, Data Safety, Ads/Advertising ID declarations) is manual. Do not describe the app as "ad-free", "no internet" or "paid once" — those claims belong to the historical pre-freemium build. ## 2. Commands ```bash # Build / test / lint ./gradlew :app:assembleDebug ./gradlew :app:testDebugUnitTest ./gradlew :app:lintDebug ./gradlew :app:assembleRelease ./gradlew :app:bundleRelease # Focused tests ./gradlew :app:testDebugUnitTest --tests '*AdPolicyTest*' ./gradlew :app:testDebugUnitTest --tests '*LegacyProTest*' ./gradlew :app:testDebugUnitTest --tests '*ScanEngineEndToEndTest*' # Opt-in similarity benchmark ./gradlew :app:testDebugUnitTest --tests '*SimilarityBenchmarkTest*' -DfotoBench=true # Install adb install -r app/build/outputs/apk/debug/app-debug.apk ``` **AdMob configuration.** Debug builds default to Google's public test ids. Real ids and the legacy-Pro cutoff come from `local.properties` (git-ignored) or Gradle properties: ```properties admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN legacyPro.cutoffEpochMs=1793491200000 ``` ```bash ./gradlew :app:bundleRelease \ -Padmob.appId=ca-app-pub-... \ -Padmob.bannerUnitId=ca-app-pub-.../... \ -PlegacyPro.cutoffEpochMs=1793491200000 ``` **Debug hooks** (debug source set only, absent from release): ```bash adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.GRANT_PRO \ -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REVOKE_PRO \ -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle adb shell am broadcast -a de.softwareapp_hb.fotodup.finder.debug.REPORT_PRO_STATE \ -n de.softwareapp_hb.fotodup.finder.free.debug/de.softwareapp_hb.fotodup.finder.debug.DebugProToggle ``` `DebugScanTrigger` is the existing scan driver; see `app/src/debug/AndroidManifest.xml`. Never use `./gradlew --offline` for a fresh dependency check, and never commit `local.properties`, `keystore.properties`, `*.jks`, APKs or AABs. ## 3. Non-negotiable product constraints 1. **The utility stays free.** Every scan, sensitivity preset, selection and deletion feature must work in the free tier. Pro removes the banner and nothing else. Do not add scan limits, locked groups or a paywall for deleting. 2. **Photo pixels never leave the device.** Only the ad SDK, UMP and Play Billing may use the network. No analytics, crash reporting, accounts, cloud sync or server-side purchase verification. 3. **Ads are the only free-tier monetisation.** One anchored adaptive banner at the bottom. No interstitial, app-open, rewarded or native ad without an explicit product decision and a UX review. 4. **Deletion is two-step and system-consented.** Staging is not deletion. Android 11+ always uses `MediaStore.createDeleteRequest` / `createTrashRequest`; never request `MANAGE_EXTERNAL_STORAGE`. 5. **Existing paid customers keep Pro.** The legacy install cutoff is the migration path. Do not remove it without a replacement that preserves paid users. 6. **Test ids are for development only.** Never ship Google's test AdMob ids in a release build. The build warns when they are still in use. 7. **Consent comes before ads.** No `MobileAds.initialize()` and no ad request until UMP says `canRequestAds()`. Pro users skip ad initialisation entirely. 8. **Historical claims are historical.** README/PRIVACY/store copy must not claim "no ads", "no INTERNET permission" or "paid once" for the freemium build. ## 4. Architecture rules - `core/` is **pure Kotlin** — no `android.*`, no Compose, no resources. It must run on a plain JVM so the hashing/grouping tests stay fast. - `data/` is the only layer that talks to MediaStore, the file system, SQLite, permissions and the system delete APIs. - `domain/` orchestrates scanning and owns `ScanController`; it must not import Compose or hold an Activity. - `service/` mirrors `ScanController` into a foreground notification; it contains no scan logic. - `monetization/` owns consent, Mobile Ads and Play Billing. It must not touch the photo pipeline. - `ui/` owns Compose, selection/staging and the ad slot. It may read domain/data/ monetisation state; it must not hash or delete photos directly. - All user-visible text lives in `res/values/strings.xml`; enum→resource mappings live in `text/TextRes.kt` so the screen and notification cannot drift. - `FotoDupApplication` creates exactly three process-scoped objects: `ScanController`, `ProStore`, `AdsController`. - `MainActivity` starts consent/ad init for free users and refreshes purchases on resume. Do not move scan ownership into an Activity or ViewModel. ## 5. Key files | Area | Files | |---|---| | Entry | `FotoDupApplication.kt`, `MainActivity.kt`, `AndroidManifest.xml` | | Scan UI | `ui/scanner/ScannerScreen.kt`, `ScannerViewModel.kt`, `ScannerUiState.kt`, `ScannerSections.kt`, `GroupSection.kt` | | Scan engine | `domain/ScanEngine.kt`, `ScanController.kt`, `ScanModels.kt`, `Parallel.kt` | | Data | `data/MediaStorePhotoSource.kt`, `PhotoHasher.kt`, `PhotoIndexStore.kt`, `MediaDeleter.kt`, `AppPermissions.kt`, `BoundedCall.kt` | | Core | `core/Hashing.kt`, `PerceptualHash.kt`, `RgbDHash.kt`, `DuplicateGrouper.kt`, `DuplicatePolicy.kt`, `AdaptiveThreshold.kt` | | Monetisation | `monetization/ProStore.kt`, `ProProduct.kt`, `LegacyPro.kt`, `AdsController.kt`, `AdPolicy.kt` | | Monetisation UI | `ui/ads/BannerAdSlot.kt`, `ui/pro/ProSheet.kt` | | Resources | `res/values/strings.xml`, `text/TextRes.kt`, `AndroidManifest.xml`, `app/build.gradle.kts` | | Tests | `app/src/test/.../core`, `data/BoundedCallTest.kt`, `domain/ScanEngineEndToEndTest.kt`, `monetization/*Test.kt` | ## 6. Scan-engine invariants 1. **Tiering is the performance contract.** Only photos with a duplicate file size are opened for the quick signature; only signature buckets with 2+ members get a full SHA-256; every readable photo gets a perceptual hash unless the policy is `EXACT_ONLY`. 2. **One decode per perceptual photo.** `PhotoHasher.perceptualFingerprint()` must produce both the pHash and the RGB dHash from the same decode/thumbnail. 3. **The index is a cache.** A row is reusable only when size and modified stamp still match. Bump `PhotoIndexStore.DB_VERSION` whenever the meaning of a stored hash changes; `onUpgrade` drops and rebuilds. 4. **Every provider call has a deadline.** Do not call `ContentResolver`, file descriptors or `loadThumbnail` without `BoundedCall`/`withTimeoutOrNull`. A stuck provider must produce an unreadable photo, not a frozen scan. 5. **The scan is process-scoped.** `ScanController` owns the job and result; the ViewModel mirrors `ScanState`. `ScanService` keeps a `dataSync` foreground service alive while it runs. 6. **Thresholds are fitted, then clamped.** `DuplicatePolicy` supplies ceilings; `AdaptiveThreshold` fits the pHash cut to the candidate population; exact grouping does not decode anything. 7. **Unreadable photos are reported, not silently dropped.** They still participate in exact matching but not in the perceptual pass. 8. **Grouping is deterministic.** Union-find plus the suggested-keep rule must match the UI's `BEST` badge and “select all but best”. ## 7. Monetisation workflow 1. Free users get exactly one `BannerAdSlot`, placed below the bottom action bar. It is only composed when `AdPolicy.shouldShowBanner(!isPro, canRequestAds, initialized)` is true. 2. `AdsController` requests a UMP consent update at every free-user launch, shows a form if required, and only then calls `MobileAds.initialize()`. 3. Pro users never initialise ads. `MainActivity` checks the cached entitlement before calling `ensureInitialized()`. 4. `ProStore` is the only entitlement source. It queries `pro_no_ads`, grants only `PurchaseState.PURCHASED`, acknowledges the purchase, retries an outstanding acknowledgement, and keeps the local cache for offline launches. 5. `PENDING` never grants Pro. `USER_CANCELED` is not an error. `ITEM_ALREADY_OWNED` refreshes purchases. A successful query with no purchase revokes Pro **unless** the install is grandfathered. 6. `LegacyPro` compares the earliest `firstInstallTime` of the freemium package and the old paid package (`LegacyPro.OLD_PAID_PACKAGE`, declared in ``) with `BuildConfig.LEGACY_PRO_CUTOFF_EPOCH_MS`. Set that cutoff to the first freemium release before shipping. The old app must still be installed on the first freemium launch; otherwise the grant is best-effort only. 7. Product id: `pro_no_ads` (`ProProduct.ID`). Price comes from Play's localized `formattedPrice`; never hardcode a currency amount in UI text. 8. Do not add a server-side entitlement check, analytics or a second ad network without an explicit product/privacy decision. ## 8. UI and UX conventions - Material 3 + `FotoDupTheme`; dynamic colour on Android 12+, branded green fallback otherwise. - All text through `stringResource` / `TextRes`. Plurals use ``. - The bottom slot is `Column(navigationBarsPadding) { BottomActionBar; BannerAdSlot }`. Do not reintroduce `navigationBarsPadding()` inside `BottomActionBar`. - Keep the ad separated from Apply by padding; never overlay an ad on a button. - Staging is optimistic: rows disappear immediately, nothing is deleted until Apply. The bottom bar must always say whether Apply will trash or delete. - The Pro sheet must state that every feature stays free and that the purchase is one-time. Show a localized price when Play provides one. - Keep the Options menu usable on a phone: Scan/Cancel + Options are the only top bar actions; Pro and privacy options live in the menu. - TalkBack: thumbnails are selectable and have content descriptions; ad views are announced by the SDK. Do not remove the ad's own accessibility behaviour. - Verify layouts on a phone and a tablet; the app supports edge-to-edge and both form factors. ## 9. Testing expectations - Add a focused JVM test for every new pure rule. `AdPolicyTest` and `LegacyProTest` are the pattern for monetisation logic; `core/*Test` for hashing/ grouping; `BoundedCallTest` for provider robustness. - `ScanEngineEndToEndTest` runs the real pipeline through Robolectric and `FakeMediaStoreProvider`. It can prove exact duplicates and unreadable-file handling, but **not** perceptual matching (Robolectric does not decode real pixels). Use the benchmark harness or a device for perceptual changes. - There is no instrumentation test. UI, ads and Billing must be checked on a device: - ads need a Play-services device and a real or test AdMob unit; - Billing needs an internal-testing track and a license-tester account; - the AOSP AVDs in this environment have no Play services, so they cannot fill ads or complete purchases. - Use `DebugProToggle` to exercise the Pro UI without Billing. Use the UMP debug geography/test-device flow in `docs/MONETIZATION.md` to exercise consent. - After any dependency or manifest change, audit the **merged** release manifest: `./gradlew :app:processReleaseMainManifest` and inspect `app/build/intermediates/merged_manifests/release/.../AndroidManifest.xml`. - Minimum before calling a change done: `./gradlew :app:testDebugUnitTest :app:lintDebug :app:assembleDebug`. For release changes also `:app:assembleRelease` (R8 + manifest merge). - **Launch a minified build before uploading.** `assembleDebug` does not run R8 and cannot catch shrinker-only startup crashes. Either install the release APK on a device (uninstall the Play-signed copy first if the signatures conflict) or temporarily enable `isMinifyEnabled`/`isShrinkResources` in the debug build type and install it side by side. The `1.1.0` upload crashed in `androidx.startup.InitializationProvider` because R8 removed WorkManager's generated `WorkDatabase_Impl` constructor; `app/proguard-rules.pro` now keeps it. ## 10. Privacy and security - The app's differentiator is on-device photo processing. Never add code that uploads a photo, a thumbnail, a hash, a filename or a folder path. - The only network traffic is AdMob/UMP and Play Billing. Adding analytics, crash reporting, a backend or another SDK changes the Data Safety declaration and `PRIVACY.md`; treat it as a product decision, not a refactor. - The ads SDK merges `INTERNET`, `ACCESS_NETWORK_STATE`, `AD_ID`, the `ACCESS_ADSERVICES_*` permissions and `WAKE_LOCK`. Billing merges `com.android.vending.BILLING`. Audit the merged manifest; do not claim the old "no INTERNET" permission set. - UMP consent must be collected where required and the privacy-options entry point must stay reachable. A refused consent means no ad request, not a broken app. - The Pro entitlement is client-side and can be tampered with on a rooted device. Do not log purchase tokens, do not put secrets in source, and do not pretend this is server-verified. - Keep `local.properties`, `keystore.properties`, `*.jks`, AdMob ids and the legacy cutoff out of commits. Test ids are public and may stay in the build defaults. - `photo_index.db` is a cache and is excluded from backup. The Pro prefs are included in Android backup; Play re-verifies on the next connection. ## 11. Common pitfalls 1. **`compileSdk` is pinned to 36.** Compose BOM 2026.06.01 and Coil 3.5.0 were chosen because the next versions require compileSdk 37, which AGP 9.1.0 does not support. Bump them together once AGP supports 37. 2. **AGP 9 has built-in Kotlin.** Do not apply `org.jetbrains.kotlin.android`; it is an error. Only the Compose compiler plugin is applied. 3. **Billing 9 callbacks changed.** `queryProductDetailsAsync` delivers a `QueryProductDetailsResult`; use `result.productDetailsList`, not the old list. `enablePendingPurchases(PendingPurchasesParams...)` is mandatory for one-time products. 4. **Acknowledge after granting.** Play refunds an unacknowledged purchase after three days. Keep `KEY_PENDING_ACK` and retry. 5. **The adaptive ad API moved.** Use `AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, widthDp)`. `getCurrentOrientationAnchoredAdaptiveBannerAdSize` is deprecated. 6. **AdMob needs the manifest meta-data.** `com.google.android.gms.ads.APPLICATION_ID` must resolve; without it `MobileAds.initialize` fails. Test ids are the defaults. 7. **Gradle parallel builds can collide on resources.** If `mergeDebugResources` reports a missing `values-xx.xml` while another Gradle command is running, rerun the command sequentially; both tasks were writing the same incremental folder. 8. **Robolectric needs the JVM flags** in `app/build.gradle.kts` (`--add-opens` / `--add-exports`). Removing them breaks the data-layer tests on JDK 17+. 9. **AOSP emulators do not have Play services.** An empty ad slot or a "purchases unavailable" message there is expected; it is not a code failure. 10. **`versionCode` must increase** for every Play upload. `1.0.2` used 3, the 1.1.0 internal-testing build used 4, the first 1.1.1 upload used 5, and the corrected freemium build is 6. Update `CHANGELOG.md` and the release checklist too. 11. **Do not call `navigationBarsPadding()` twice.** The bottom slot owns the inset; `BottomActionBar` must not add it again. 12. **The old paid-app docs are historical.** Do not copy "pay once", "no ads" or "no INTERNET" claims into new copy. 13. **R8 reflects into Room/WorkManager.** `play-services-ads` pulls in WorkManager 2.7.0. The generated `androidx.work.impl.WorkDatabase_Impl` constructor is removed by R8 unless `app/proguard-rules.pro` keeps it, producing a release-only crash before `Application.onCreate`. Keep the rule and smoke-test a minified build; debug builds do not reproduce it. ## 12. Definition of done - [ ] Feature works through a complete user flow, not a dead placeholder. - [ ] Free tier still does everything; Pro removes only the banner. - [ ] Photo data remains on-device; no new network dependency beyond ads/UMP/Billing. - [ ] `core/` remains pure Kotlin; no Android import. - [ ] All user-visible text is in `strings.xml`; plurals are real ``. - [ ] New pure logic has a focused JVM test. - [ ] `./gradlew :app:testDebugUnitTest` is green. - [ ] `./gradlew :app:lintDebug` is clean (or the existing warnings are unchanged). - [ ] `./gradlew :app:assembleDebug` succeeds. - [ ] For release-affecting work: `./gradlew :app:assembleRelease` succeeds and the merged manifest permissions are re-audited. - [ ] For release-affecting work: a **minified build launches** on a device (R8-only failures are invisible to `assembleDebug` and unit tests). - [ ] `docs/codemap.md` and `docs/codemap.mmd` are updated for architecture changes. - [ ] `README.md`, `PRIVACY.md`, `CHANGELOG.md`, `docs/MONETIZATION.md`, `docs/STORE_LISTING.md` and `docs/PLAY_RELEASE_CHECKLIST.md` are updated when user-visible behaviour, permissions or monetisation changed. - [ ] No secrets, keystores, APKs/AABs, `local.properties` or build outputs staged. - [ ] The commit message describes the change. ## 13. Agent workflow 1. Read this file, `README.md`, the relevant part of `docs/codemap.md`, and — for monetisation changes — `docs/MONETIZATION.md`. 2. Run the baseline checks (`./gradlew :app:testDebugUnitTest`) if time permits. 3. Locate the owning layer from the codemap; make the smallest coherent change. 4. Add/adjust tests before or alongside the implementation. 5. Run focused tests, then the full suite, lint and the debug build. 6. For ads/Billing changes, verify the free/Pro UI with `DebugProToggle`; state clearly which device/Play-console steps could not be run locally. 7. Update the codemap, AGENTS.md and the relevant user/release docs. 8. Commit with a scoped message. Do **not**: - add a feature gate to scanning or deletion; - add analytics, accounts, a backend or a new ad network without an explicit product/privacy decision; - weaken or delete correctness tests to make a change pass; - ship test ad ids in a release build; - claim the app has no network permission or is ad-free; - commit generated build outputs or secrets. ## 14. Environment notes - Verified with JDK 25, Gradle 9.3.1, AGP 9.1.0 and Android SDK 36. - The machine may expose no `/dev/kvm`; AOSP AVDs run in software emulation. That is fine for layout checks, but they have no Play services, so ads and Billing cannot be exercised there. - The real device used for earlier screenshots is MIUI, which denies `adb shell input`; the debug broadcast hooks exist for that reason. - `local.properties` is machine-specific and git-ignored. Use `local.properties.example` as the template. - Release builds are signed only when `keystore.properties` exists; otherwise they still run R8 and produce an unsigned APK for local checks. - The store assets and screenshots in `store-assets/` predate the freemium banner and need a re-shoot (banner visible, Pro sheet) before the next store listing.