The sideloaded release APK needs a confirmation tap on the phone: without one, adb reports INSTALL_FAILED_USER_RESTRICTED: Install canceled by user even though the transfer succeeded, so the install step has to be retried rather than diagnosed as a signing or manifest problem. Also note that adb shell input, pm grant and uiautomator dump did work in that session (try them, then fall back to the debug broadcast hooks), and that API 31 grants READ_EXTERNAL_STORAGE because READ_MEDIA_IMAGES only exists from API 33. Release checklist: tick the minified-launch gate with what was verified on the phone for 1.1.2, and record the smoke test - cold scan, three cancel paths, no ForegroundServiceDidNotStartInTimeException - plus the one thing that was deliberately not exercised (deleting real photos).
22 KiB
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.2 / versionCode 7 (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
Standalone Mermaid graph: docs/codemap.mmd
Monetisation setup: docs/MONETIZATION.md
Roadmap: docs/ROADMAP.md
Release checklist: docs/PLAY_RELEASE_CHECKLIST.md
Privacy policy: PRIVACY.md
Current gate: the freemium release (1.1.2, the foreground-service bugfix on top of
the 1.1.1 freemium build) 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
# 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:
admob.appId=ca-app-pub-XXXXXXXXXXXXXXXX~YYYYYYYYYY
admob.bannerUnitId=ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN
legacyPro.cutoffEpochMs=1793491200000
./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):
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
- 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.
- 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.
- 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.
- Deletion is two-step and system-consented. Staging is not deletion. Android
11+ always uses
MediaStore.createDeleteRequest/createTrashRequest; never requestMANAGE_EXTERNAL_STORAGE. - Existing paid customers keep Pro. The legacy install cutoff is the migration path. Do not remove it without a replacement that preserves paid users.
- 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.
- Consent comes before ads. No
MobileAds.initialize()and no ad request until UMP sayscanRequestAds(). Pro users skip ad initialisation entirely. - 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 — noandroid.*, 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 ownsScanController; it must not import Compose or hold an Activity.service/mirrorsScanControllerinto 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 intext/TextRes.ktso the screen and notification cannot drift. FotoDupApplicationcreates exactly three process-scoped objects:ScanController,ProStore,AdsController.MainActivitystarts 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
- 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. - One decode per perceptual photo.
PhotoHasher.perceptualFingerprint()must produce both the pHash and the RGB dHash from the same decode/thumbnail. - The index is a cache. A row is reusable only when size and modified stamp
still match. Bump
PhotoIndexStore.DB_VERSIONwhenever the meaning of a stored hash changes;onUpgradedrops and rebuilds. - Every provider call has a deadline. Do not call
ContentResolver, file descriptors orloadThumbnailwithoutBoundedCall/withTimeoutOrNull. A stuck provider must produce an unreadable photo, not a frozen scan. - The scan is process-scoped.
ScanControllerowns the job and result; the ViewModel mirrorsScanState.ScanServicekeeps adataSyncforeground service alive while it runs. It callsstartForeground()inonCreate()and at the top of everyonStartCommand(), and nothing outside it callsstopService()— the service stops itself when it seesscanning == false. - Thresholds are fitted, then clamped.
DuplicatePolicysupplies ceilings;AdaptiveThresholdfits the pHash cut to the candidate population; exact grouping does not decode anything. - Unreadable photos are reported, not silently dropped. They still participate in exact matching but not in the perceptual pass.
- Grouping is deterministic. Union-find plus the suggested-keep rule must match
the UI's
BESTbadge and “select all but best”.
7. Monetisation workflow
- Free users get exactly one
BannerAdSlot, placed below the bottom action bar. It is only composed whenAdPolicy.shouldShowBanner(!isPro, canRequestAds, initialized)is true. AdsControllerrequests a UMP consent update at every free-user launch, shows a form if required, and only then callsMobileAds.initialize().- Pro users never initialise ads.
MainActivitychecks the cached entitlement before callingensureInitialized(). ProStoreis the only entitlement source. It queriespro_no_ads, grants onlyPurchaseState.PURCHASED, acknowledges the purchase, retries an outstanding acknowledgement, and keeps the local cache for offline launches.PENDINGnever grants Pro.USER_CANCELEDis not an error.ITEM_ALREADY_OWNEDrefreshes purchases. A successful query with no purchase revokes Pro unless the install is grandfathered.LegacyProcompares the earliestfirstInstallTimeof the freemium package and the old paid package (LegacyPro.OLD_PAID_PACKAGE, declared in<queries>) withBuildConfig.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.- Product id:
pro_no_ads(ProProduct.ID). Price comes from Play's localizedformattedPrice; never hardcode a currency amount in UI text. - 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<plurals>. - The bottom slot is
Column(navigationBarsPadding) { BottomActionBar; BannerAdSlot }. Do not reintroducenavigationBarsPadding()insideBottomActionBar. - 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.
AdPolicyTestandLegacyProTestare the pattern for monetisation logic;core/*Testfor hashing/ grouping;BoundedCallTestfor provider robustness. ScanEngineEndToEndTestruns the real pipeline through Robolectric andFakeMediaStoreProvider. 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
DebugProToggleto exercise the Pro UI without Billing. Use the UMP debug geography/test-device flow indocs/MONETIZATION.mdto exercise consent. - After any dependency or manifest change, audit the merged release manifest:
./gradlew :app:processReleaseMainManifestand inspectapp/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.
assembleDebugdoes 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 enableisMinifyEnabled/isShrinkResourcesin the debug build type and install it side by side. The1.1.0upload crashed inandroidx.startup.InitializationProviderbecause R8 removed WorkManager's generatedWorkDatabase_Implconstructor;app/proguard-rules.pronow 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, theACCESS_ADSERVICES_*permissions andWAKE_LOCK. Billing mergescom.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.dbis 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
compileSdkis 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.- AGP 9 has built-in Kotlin. Do not apply
org.jetbrains.kotlin.android; it is an error. Only the Compose compiler plugin is applied. - Billing 9 callbacks changed.
queryProductDetailsAsyncdelivers aQueryProductDetailsResult; useresult.productDetailsList, not the old list.enablePendingPurchases(PendingPurchasesParams...)is mandatory for one-time products. - Acknowledge after granting. Play refunds an unacknowledged purchase after
three days. Keep
KEY_PENDING_ACKand retry. - The adaptive ad API moved. Use
AdSize.getLargeAnchoredAdaptiveBannerAdSize(context, widthDp).getCurrentOrientationAnchoredAdaptiveBannerAdSizeis deprecated. - AdMob needs the manifest meta-data.
com.google.android.gms.ads.APPLICATION_IDmust resolve; without itMobileAds.initializefails. Test ids are the defaults. - Gradle parallel builds can collide on resources. If
mergeDebugResourcesreports a missingvalues-xx.xmlwhile another Gradle command is running, rerun the command sequentially; both tasks were writing the same incremental folder. - Robolectric needs the JVM flags in
app/build.gradle.kts(--add-opens/--add-exports). Removing them breaks the data-layer tests on JDK 17+. - 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.
versionCodemust increase for every Play upload.1.0.2used 3, the 1.1.0 internal-testing build used 4, the first 1.1.1 upload used 5, the corrected 1.1.1 freemium build used 6, and the foreground-service fix is1.1.2/ 7. UpdateCHANGELOG.mdand the release checklist too.- Do not call
navigationBarsPadding()twice. The bottom slot owns the inset;BottomActionBarmust not add it again. - The old paid-app docs are historical. Do not copy "pay once", "no ads" or "no INTERNET" claims into new copy.
- R8 reflects into Room/WorkManager.
play-services-adspulls in WorkManager 2.7.0. The generatedandroidx.work.impl.WorkDatabase_Implconstructor is removed by R8 unlessapp/proguard-rules.prokeeps it, producing a release-only crash beforeApplication.onCreate. Keep the rule and smoke-test a minified build; debug builds do not reproduce it. - Never
stopService()a foreground start that may still be pending. The service'sonCreate/onStartCommandrun on the main thread, so astopService()issued straight afterstartForegroundService()(a scan that finished at once, a Cancel tap, a stop from aDispatchers.Defaultcoroutine) can win the race. The service then never callsstartForeground()and Android throwsRemoteServiceException$ForegroundServiceDidNotStartInTimeExceptionon the app's main thread ~5–10 s later, with no app frames in the stack.ScanServicetherefore enters the foreground inonCreate()and stops itself from its own state collector;ScanServiceTestpins both halves down.
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<plurals>. - New pure logic has a focused JVM test.
./gradlew :app:testDebugUnitTestis green../gradlew :app:lintDebugis clean (or the existing warnings are unchanged)../gradlew :app:assembleDebugsucceeds.- For release-affecting work:
./gradlew :app:assembleReleasesucceeds 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
assembleDebugand unit tests). docs/codemap.mdanddocs/codemap.mmdare updated for architecture changes.README.md,PRIVACY.md,CHANGELOG.md,docs/MONETIZATION.md,docs/STORE_LISTING.mdanddocs/PLAY_RELEASE_CHECKLIST.mdare updated when user-visible behaviour, permissions or monetisation changed.- No secrets, keystores, APKs/AABs,
local.propertiesor build outputs staged. - The commit message describes the change.
13. Agent workflow
- Read this file,
README.md, the relevant part ofdocs/codemap.md, and — for monetisation changes —docs/MONETIZATION.md. - Run the baseline checks (
./gradlew :app:testDebugUnitTest) if time permits. - Locate the owning layer from the codemap; make the smallest coherent change.
- Add/adjust tests before or alongside the implementation.
- Run focused tests, then the full suite, lint and the debug build.
- For ads/Billing changes, verify the free/Pro UI with
DebugProToggle; state clearly which device/Play-console steps could not be run locally. - Update the codemap, AGENTS.md and the relevant user/release docs.
- 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 (Xiaomi M2101K7AG, Android 12 /
API 31). Observations from 2026-11-09, all worth keeping in mind:
adb installneeds a tap on the phone. MIUI asks for confirmation for a sideloaded APK; if nobody taps it, the client reportsFailure [INSTALL_FAILED_USER_RESTRICTED: Install canceled by user]even though the transfer itself worked. Just run the install again and confirm on the device. This applies to the minified release APK, which is not debuggable.adb shell input tap,pm grantanduiautomator dumpdid work in that session, so try them before falling back to the debug broadcast hooks insrc/debug/; earlier sessions hadinput/pm grantrefused, so treat both as "attempt, then fall back" rather than as guaranteed either way.- On API 31 grant
READ_EXTERNAL_STORAGE;READ_MEDIA_IMAGESonly exists from API 33, sopm grant … READ_MEDIA_IMAGESfails with "Unknown permission" there.
local.propertiesis machine-specific and git-ignored. Uselocal.properties.exampleas the template.- Release builds are signed only when
keystore.propertiesexists; 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.