-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathbuild.gradle
More file actions
836 lines (762 loc) · 38.2 KB
/
Copy pathbuild.gradle
File metadata and controls
836 lines (762 loc) · 38.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
plugins {
id 'com.android.application' version '8.8.2'
id 'org.jetbrains.kotlin.android' version '2.0.0'
id 'org.jetbrains.kotlin.plugin.compose' version '2.0.0'
}
dependencies {
implementation "androidx.window:window-java:1.3.0"
implementation "androidx.core:core:1.13.1"
implementation "androidx.appcompat:appcompat:1.6.1"
implementation "androidx.multidex:multidex:2.0.1"
implementation "com.google.android.material:material:1.11.0"
implementation "androidx.viewpager2:viewpager2:1.0.0"
implementation "androidx.recyclerview:recyclerview:1.3.2"
implementation "androidx.preference:preference-ktx:1.2.1"
implementation "androidx.autofill:autofill:1.1.0"
// ExploreByTouchHelper (TalkBack virtual-view tree for the custom keyboard).
// Transitively present via other AndroidX libs, but pin it explicitly so the
// a11y helper never silently loses its dependency.
implementation "androidx.customview:customview:1.1.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib:2.0.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"
// REPRODUCIBILITY: Use Compose BOM for deterministic version resolution
implementation platform("androidx.compose:compose-bom:2024.06.00")
implementation "androidx.activity:activity-compose:1.9.0"
implementation "androidx.compose.ui:ui"
debugImplementation "androidx.compose.ui:ui-tooling-preview"
debugImplementation "androidx.compose.ui:ui-tooling"
implementation "androidx.compose.material3:material3"
implementation "androidx.compose.foundation:foundation"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.2"
implementation "androidx.savedstate:savedstate-ktx:1.2.1"
implementation "org.burnoutcrew.composereorderable:reorderable:0.9.6"
implementation "com.microsoft.onnxruntime:onnxruntime-android:1.20.0"
implementation "com.google.code.gson:gson:2.10.1"
// Coil: Kotlin-native image loader with animated WebP support
implementation "io.coil-kt:coil:2.6.0"
testImplementation "junit:junit:4.13.2"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3"
testImplementation "org.robolectric:robolectric:4.11.1"
testImplementation "androidx.test:core:1.5.0"
testImplementation "io.mockk:mockk:1.13.8"
testImplementation "com.google.truth:truth:1.1.5"
// Real org.json JSONObject for mock tests — android.jar provides only stubs
// that throw RuntimeException("Stub!") on construction. Tests that build a
// real JSON payload (BackupRestoreFullBackupTest) need this to shadow the
// stub on the unit-test classpath.
testImplementation "org.json:json:20231013"
// ONNX Runtime for JVM unit tests (Android runtime doesn't work on host JVM)
testImplementation "com.microsoft.onnxruntime:onnxruntime:1.20.0"
androidTestImplementation "androidx.test:core:1.5.0"
androidTestImplementation "androidx.test.ext:junit:1.1.5"
androidTestImplementation "androidx.test:runner:1.5.2"
androidTestImplementation "androidx.test:rules:1.5.0"
androidTestImplementation "androidx.test.uiautomator:uiautomator:2.2.0"
androidTestImplementation "androidx.test.espresso:espresso-core:3.5.1"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3"
androidTestImplementation "org.mockito:mockito-android:5.5.0"
androidTestImplementation "org.mockito:mockito-core:5.5.0"
androidTestImplementation platform("androidx.compose:compose-bom:2024.06.00")
androidTestImplementation "androidx.compose.ui:ui-test-junit4"
debugImplementation "androidx.compose.ui:ui-test-manifest"
}
// =============================================================================
// VERSIONING - F-Droid compatible (checkupdates does not parse ext values)
// =============================================================================
// UPDATE ONLY THESE THREE VALUES FOR A NEW RELEASE:
ext.VERSION_MAJOR = 1
ext.VERSION_MINOR = 5
ext.VERSION_PATCH = 0
// =============================================================================
// DERIVED VALUES (auto-calculated, do not edit):
// - versionCode = MAJOR*10000 + MINOR*100 + PATCH
// - versionNameStr = "MAJOR.MINOR.PATCH"
// - ABI versionCode = base*10 + abiCode (1=armv7, 2=arm64, 3=x86_64)
//
// WORKFLOW:
// 1. Update VERSION_MAJOR/MINOR/PATCH above
// 2. Commit, tag with "vX.Y.Z", push tag
// 3. GitHub Actions verifies tag matches version, builds, releases
// 4. F-Droid auto-detects tag and builds
// =============================================================================
ext.versionCode = ext.VERSION_MAJOR * 10000 + ext.VERSION_MINOR * 100 + ext.VERSION_PATCH
// Overflow guard: the MAJOR*10000 + MINOR*100 + PATCH packing only stays
// collision-free (and F-Droid-monotonic) while MINOR and PATCH are each < 100.
// e.g. 1.5.100 would collide with 1.6.0. Fail the build loudly rather than ship
// a colliding versionCode. Do NOT widen the scheme — F-Droid monotonicity depends
// on it (see versionCode formula comment above).
if (ext.VERSION_MINOR >= 100 || ext.VERSION_PATCH >= 100) {
throw new GradleException("versionCode scheme collision: MINOR/PATCH must stay < 100 (see build.gradle versionCode formula)")
}
ext.versionNameStr = "${ext.VERSION_MAJOR}.${ext.VERSION_MINOR}.${ext.VERSION_PATCH}"
// Per-ABI versionCode mapping for split APKs
ext.abiCodes = ['armeabi-v7a': 1, 'arm64-v8a': 2, 'x86_64': 3]
// Force reproducibility by excluding profile-guided optimization tools
configurations.all {
exclude group: 'androidx.profileinstaller', module: 'profileinstaller'
}
android {
namespace 'tribixbite.cleverkeys'
compileSdk 34
// REPRODUCIBILITY: Let AGP use its default build-tools (pinned per AGP version)
// Removed explicit buildToolsVersion - both GitHub and F-Droid use AGP 8.8.2 default
defaultConfig {
applicationId "tribixbite.cleverkeys"
minSdk 21
targetSdkVersion 34
// References ext values - see VERSION_MAJOR/MINOR/PATCH at top of file
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionNameStr
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
kotlinOptions {
// REPRODUCIBILITY: Use Java 11 target for deterministic bytecode
jvmTarget = "11"
}
aaptOptions {
noCompress 'onnx', 'tflite'
// REPRODUCIBILITY: Disable PNG crunching for deterministic output
cruncherEnabled = false
// REPRODUCIBILITY: Force consistent platformBuildVersionCode/Name across environments
// This ensures GitHub Actions and F-Droid produce identical AndroidManifest.xml
additionalParameters "--no-auto-version",
"--compile-sdk-version-code", "34",
"--compile-sdk-version-name", "14"
}
packaging {
resources {
// REPRODUCIBILITY: Exclude non-deterministic files
// Baseline profiles vary between build environments
excludes += "assets/dexopt/baseline.prof"
excludes += "assets/dexopt/baseline.profm"
// Build metadata that changes between environments (exact paths required)
excludes += "META-INF/version-control-info.textproto"
excludes += "META-INF/com/android/build/gradle/app-metadata.properties"
// Kotlin coroutines debug probes (non-deterministic)
excludes += "DebugProbesKt.bin"
// Kotlin coroutines service files (non-deterministic order)
excludes += "META-INF/services/kotlinx.coroutines.internal.MainDispatcherFactory"
excludes += "META-INF/services/kotlinx.coroutines.CoroutineExceptionHandler"
// License files and kotlin modules (reduce APK noise)
excludes += "META-INF/DEPENDENCIES"
excludes += "META-INF/LICENSE*"
excludes += "META-INF/NOTICE*"
excludes += "META-INF/AL2.0"
excludes += "META-INF/LGPL2.1"
excludes += "META-INF/*.kotlin_module"
excludes += "META-INF/*.version"
excludes += "META-INF/com.android.tools/**"
}
}
// REPRODUCIBILITY: Exclude dependency info from APK
dependenciesInfo {
includeInApk = false
includeInBundle = false
}
splits {
abi {
enable true
reset()
include 'armeabi-v7a', 'arm64-v8a', 'x86_64'
universalApk false
}
}
compileOptions {
// REPRODUCIBILITY: Use Java 11 target for deterministic bytecode
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
buildFeatures {
compose true
buildConfig true // Enable BuildConfig generation for ENABLE_VERBOSE_LOGGING
}
// REPRODUCIBILITY: Compose compiler configuration via native Kotlin 2.0 plugin
// (replaces composeOptions.kotlinCompilerExtensionVersion)
composeCompiler {
enableIntrinsicRemember = true
includeSourceInformation = false
// REPRODUCIBILITY: Disable strong skipping mode to avoid non-deterministic lambda generation
enableStrongSkippingMode = false
// REPRODUCIBILITY: Disable non-skippable group optimization
enableNonSkippingGroupOptimization = false
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
kotlin.srcDirs = ['src/main/kotlin', 'build/generated/search/kotlin']
java.srcDirs = ['src/main/java']
res.srcDirs = ['res', 'build/generated/layouts/res', 'build/generated/version/res']
assets.srcDirs = ['assets', 'src/main/assets']
}
test {
kotlin.srcDirs = ['src/test/kotlin']
java.srcDirs = ['src/test/java']
// Expose bundled assets to JVM tests so EmbedEnrichRulesTest (and any
// future test that loads url_rules/*.json) can resolve them via
// Class.getResourceAsStream("/url_rules/<name>.json").
resources.srcDirs += 'src/main/assets'
}
androidTest {
kotlin.srcDirs = ['src/androidTest/kotlin']
}
}
signingConfigs {
debug {
storeFile(System.env.DEBUG_KEYSTORE ? file(System.env.DEBUG_KEYSTORE) : file("debug.keystore"))
storePassword(System.env.DEBUG_KEYSTORE_PASSWORD ? "$System.env.DEBUG_KEYSTORE_PASSWORD" : "debug0")
keyAlias(System.env.DEBUG_KEY_ALIAS ? "$System.env.DEBUG_KEY_ALIAS" : "debug")
keyPassword(System.env.DEBUG_KEY_PASSWORD ? "$System.env.DEBUG_KEY_PASSWORD" : "debug0")
}
release {
// REPRODUCIBILITY: Check for non-empty keystore path (empty string is truthy in Groovy)
def keystorePath = System.env.RELEASE_KEYSTORE
if (keystorePath != null && keystorePath.trim().length() > 0) {
storeFile file(keystorePath)
storePassword "$System.env.RELEASE_KEYSTORE_PASSWORD"
keyAlias "$System.env.RELEASE_KEY_ALIAS"
keyPassword "$System.env.RELEASE_KEY_PASSWORD"
} else {
// No release keystore - use debug for local builds, CI will sign separately
storeFile file("debug.keystore")
storePassword "debug0"
keyAlias "debug"
keyPassword "debug0"
}
}
}
buildTypes {
// LOCAL_BUILD env var enables verbose logging for local development
// Set by build-on-termux.sh, not set by GitHub Actions
def isLocalBuild = System.env.LOCAL_BUILD == "true"
release {
// REPRODUCIBILITY: Disable VCS info to prevent version-control-info.textproto (AGP 8.3+)
vcsInfo.include = false
// REPRODUCIBILITY TEST: Disable R8 to isolate if it causes non-deterministic DEX
minifyEnabled false
shrinkResources false
debuggable false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
resValue "string", "app_name", "CleverKeys"
// Verbose logging: enabled for local builds, disabled for CI/production
buildConfigField "boolean", "ENABLE_VERBOSE_LOGGING", isLocalBuild ? "true" : "false"
// REPRODUCIBILITY: Only sign during build if non-empty keystore provided
// When unset/empty, build unsigned APK for post-processing and manual signing
def keystorePath = System.env.RELEASE_KEYSTORE
if (keystorePath != null && keystorePath.trim().length() > 0) {
signingConfig signingConfigs.release
}
// Note: If no signingConfig, APK is unsigned (requires manual signing)
}
debug {
// Separate applicationId so debug builds coexist with the prod-signed app
// and never overwrite/wipe its data on install.
applicationIdSuffix '.debug'
minifyEnabled false
shrinkResources false
debuggable true
resValue "string", "app_name", "CleverKeys (Debug)"
resValue "bool", "debug_logs", "true"
buildConfigField "boolean", "ENABLE_VERBOSE_LOGGING", "true"
signingConfig signingConfigs.debug
}
}
// ABI split versionCodes - must match F-Droid metadata exactly
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def abi = output.getFilter(com.android.build.OutputFile.ABI)
if (abi != null) {
def abiCode = rootProject.ext.abiCodes.get(abi, 0)
output.versionCodeOverride = variant.versionCode * 10 + abiCode
output.outputFileName = "CleverKeys-v${variant.versionName}-${abi}.apk"
} else {
output.outputFileName = "CleverKeys-v${variant.versionName}-universal.apk"
}
}
}
lint {
baseline = file("lint-baseline.xml")
// Lint gate phase 2 (2026-07-20): all 656 error/fatal issues fixed for real
// (unused-resource purge, NewApi guards, LongLogTag, backup rules, 21-locale
// translations). The baseline now suppresses only the remaining ~400 warnings
// + ~100 informational; any NEW error fails the build.
abortOnError = true
checkReleaseBuilds = false
}
testOptions {
unitTests {
includeAndroidResources = true
returnDefaultValues = true
}
}
}
// REPRODUCIBILITY: Apply deterministic compilation settings
// Note: sourceInformation is now set via composeCompiler {} block for Kotlin 2.0+
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
compilerOptions {
freeCompilerArgs.addAll([
"-Xbackend-threads=1",
"-Xno-call-assertions",
"-Xno-receiver-assertions",
"-Xno-param-assertions"
])
}
}
// REPRODUCIBILITY: Disable baseline profile compilation for deterministic APKs
// The ART profile varies between build environments and causes reproducibility issues
tasks.configureEach { task ->
if (task.name.contains("ArtProfile") || task.name.contains("BaselineProfile")) {
task.enabled = false
}
}
def isArm64 = System.getProperty("os.arch") in ["aarch64", "arm64"]
if (isArm64) {
tasks.withType(Test).configureEach {
enabled = false
}
}
// Pure JVM test runner — works on ARM64 where standard Test tasks are disabled.
// Runs JUnitCore directly via JavaExec, no proot or shell script needed.
// Usage: ./gradlew runPureTests [-PtestClass=BeamSearchEngineTest]
tasks.register('runPureTests', JavaExec) {
dependsOn 'compileDebugUnitTestKotlin', 'processDebugUnitTestJavaRes'
group = 'verification'
description = 'Run pure JVM tests via JUnitCore (works on ARM64)'
def pureTestClasses = [
'tribixbite.cleverkeys.AccentNormalizerTest',
'tribixbite.cleverkeys.VocabularyTrieTest',
'tribixbite.cleverkeys.DictionaryWordTest',
'tribixbite.cleverkeys.SwipeResamplerTest',
'tribixbite.cleverkeys.VocabularyUtilsTest',
'tribixbite.cleverkeys.BeamSearchModelsTest',
'tribixbite.cleverkeys.ConfigDefaultsTest',
'tribixbite.cleverkeys.DictionaryBinFormatTest',
'tribixbite.cleverkeys.AutocorrectDefaultsDriftTest',
'tribixbite.cleverkeys.ContractionFrequencyTest',
'tribixbite.cleverkeys.PipelineBenchmarkTest',
'tribixbite.cleverkeys.BeamSearchEngineTest',
'tribixbite.cleverkeys.PipelineIntegrationTest',
'tribixbite.cleverkeys.ShortSwipeIntentTest',
'tribixbite.cleverkeys.customization.ShortSwipeMappingTest',
'tribixbite.cleverkeys.GestureTest',
'tribixbite.cleverkeys.ModmapTest',
'tribixbite.cleverkeys.ComposeKeyPureTest',
'tribixbite.cleverkeys.KeyValueParserTest',
'tribixbite.cleverkeys.onnx.PrefixBoostTrieTest',
'tribixbite.cleverkeys.NeuralPredictionPureTest',
'tribixbite.cleverkeys.IntegrationPureTest',
'tribixbite.cleverkeys.CoordinateNormalizerTest',
'tribixbite.cleverkeys.TrajectoryFeatureCalculatorTest',
'tribixbite.cleverkeys.IssueRegressionTest',
'tribixbite.cleverkeys.AutoSpaceLogicTest',
'tribixbite.cleverkeys.SmartAutoSpaceLogicTest',
'tribixbite.cleverkeys.gif.GifTest',
'tribixbite.cleverkeys.gif.GifCategoryTest',
'tribixbite.cleverkeys.SwipeLayoutSupportTest',
'tribixbite.cleverkeys.BackspaceUndoTest',
'tribixbite.cleverkeys.ClipboardPaginationTest',
'tribixbite.cleverkeys.ClipboardFixesJvmTest',
'tribixbite.cleverkeys.ClipboardEditJvmTest',
'tribixbite.cleverkeys.Issue78SuggestionReplaceTest',
'tribixbite.cleverkeys.Issue118EmojiOverflowTest',
'tribixbite.cleverkeys.Issue136MaxSeqLengthClampTest',
'tribixbite.cleverkeys.backup.SettingsImportPlanBuilderTest',
'tribixbite.cleverkeys.backup.SettingsDefaultsDriftTest',
'tribixbite.cleverkeys.SettingsSearchCoverageTest',
'tribixbite.cleverkeys.GesturePrefAccessDriftTest',
'tribixbite.cleverkeys.backup.DictImportPlanBuilderTest',
'tribixbite.cleverkeys.backup.SettingsExporterTest',
'tribixbite.cleverkeys.BackupRestoreResultMessagesTest',
'tribixbite.cleverkeys.BackupRestorePreviewRenderTest',
'tribixbite.cleverkeys.backup.ShortSwipeDiffTest',
'tribixbite.cleverkeys.autocorrect.KeyAdjacencyTest',
'tribixbite.cleverkeys.autocorrect.MorphologyTest',
'tribixbite.cleverkeys.autocorrect.FrequencyFloorTest',
'tribixbite.cleverkeys.autocorrect.AutocorrectContextGuardTest',
'tribixbite.cleverkeys.LanguagePreferenceKeysReverseLookupTest',
'tribixbite.cleverkeys.BucketBSourceContractTest',
'tribixbite.cleverkeys.clipboard.sanitize.RulesetParserTest',
'tribixbite.cleverkeys.clipboard.sanitize.UrlSanitizerTest',
'tribixbite.cleverkeys.clipboard.sanitize.EmbedEnrichRulesTest',
'tribixbite.cleverkeys.HapticsBehaviorDriftTest',
// Audit remediation (2026-07-17) — new pure JVM tests
'tribixbite.cleverkeys.ClipboardSearchRegexTest',
'tribixbite.cleverkeys.ConfigNullSafetyTest',
'tribixbite.cleverkeys.CoreImeHygieneDriftTest',
'tribixbite.cleverkeys.EngineInitGateTest',
'tribixbite.cleverkeys.PredictionTaskRunnerTest',
'tribixbite.cleverkeys.TestRunnerListDriftTest',
'tribixbite.cleverkeys.onnx.CloseOnceGuardTest',
'tribixbite.cleverkeys.onnx.ModelLoaderReadBytesTest',
// Backup encryption (2026-07-17) — pure crypto substrate
'tribixbite.cleverkeys.backup.crypto.Pbkdf2Sha256VectorTest',
'tribixbite.cleverkeys.backup.crypto.BackupCryptoRoundTripTest',
'tribixbite.cleverkeys.backup.crypto.BackupCryptoTamperTest',
'tribixbite.cleverkeys.backup.crypto.EncryptedBackupFormatTest',
// Private copy/paste (#156) — pure helpers
'tribixbite.cleverkeys.clipboard.PrivateCopyIntentParserTest',
'tribixbite.cleverkeys.clipboard.PrivateCopyRateLimiterTest',
'tribixbite.cleverkeys.clipboard.PrivateClipMergeRuleTest',
'tribixbite.cleverkeys.customization.PrivateCopyCommandTest',
// TalkBack accessibility (a11y) — pure geometry + labeller
'tribixbite.cleverkeys.a11y.KeyboardGeometryTest',
'tribixbite.cleverkeys.a11y.KeyLabelsTest',
// SuggestionBar rework (WP6-R3) — de-stringified suggestion protocol
'tribixbite.cleverkeys.SuggestionModelTest',
// WP9 pipeline-unification characterization oracle (R-1 step 2) — pure JVM twin
'tribixbite.cleverkeys.PipelineOracleJvmTest',
// Render-perf + lifecycle hygiene (2026-07-20) — WP5 (R-6) scope cancel + WP6 (R2) render index
'tribixbite.cleverkeys.customization.ShortSwipeByKeyIndexTest',
'tribixbite.cleverkeys.EmojiKeywordIndexLifecycleTest',
'tribixbite.cleverkeys.CoroutineScopeLifecycleTest',
// Geometric swipe engine — pure JVM
'tribixbite.cleverkeys.swipe.geometric.GeoLayoutFixtureTest',
'tribixbite.cleverkeys.swipe.geometric.LayoutGeometryTest',
// WP9 R-1 step 9: layout-routed engine selection (steps 7-8 wiring)
'tribixbite.cleverkeys.swipe.SwipeEngineRouterTest',
'tribixbite.cleverkeys.swipe.ContractionOverlayTest',
'tribixbite.cleverkeys.swipe.geometric.GeoPurityDriftTest',
'tribixbite.cleverkeys.swipe.geometric.CkdtReaderTest',
'tribixbite.cleverkeys.swipe.geometric.GeoProjectionTest',
'tribixbite.cleverkeys.swipe.geometric.TemplateGeneratorTest',
'tribixbite.cleverkeys.swipe.geometric.CandidatePrunerTest',
'tribixbite.cleverkeys.swipe.geometric.GeoDecoderCoreTest',
// Step-0 SLOPPY prune-recall decomposition (geoFull-gated measurement)
'tribixbite.cleverkeys.swipe.geometric.GeoSloppyPruneRecallTest',
// Real-corpus REPLAY (FUTO swipe-1/test) — non-circular A/B validation (geoFull + local-cache gated)
'tribixbite.cleverkeys.swipe.geometric.GeoRealCorpusReplayTest',
'tribixbite.cleverkeys.swipe.geometric.GeoFutoTrain100kReplayTest',
// Real-corpus REPLAY on NON-QWERTY layouts (FUTO swipe-5/train dvorak/azerty/qwertz/german/spanish)
'tribixbite.cleverkeys.swipe.geometric.GeoRealCorpusMultiLayoutTest',
// Real-corpus REPLAY on the NEURAL model's held-out combined-corpus test set (local-only, geoFull-gated)
'tribixbite.cleverkeys.swipe.geometric.GeoLocalCorpusReplayTest',
// Phase 5 — synthetic traces + accuracy harness (PROVISIONAL floors)
'tribixbite.cleverkeys.swipe.geometric.GeoTraceSynthesizerTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyQwertyEnTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyJcukenRuTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyAzertyFrTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyQwertzDeTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyDvorakEnTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAccuracyWeirdLayoutTest',
// Phase 6 — tuning, final thresholds, adversarial + perf
'tribixbite.cleverkeys.swipe.geometric.GeoConfusablesTest',
'tribixbite.cleverkeys.swipe.geometric.GeoDoubleLetterTest',
'tribixbite.cleverkeys.swipe.geometric.GeoShortWordTest',
'tribixbite.cleverkeys.swipe.geometric.GeoAblationTest',
'tribixbite.cleverkeys.swipe.geometric.GeoBenchmarkTest',
// FUTO-style CTC swipe module (wired as the `ctc` engine mode, G5) — pure JVM
// golden-trace parity vs the Python port (scripts/futo_decoder_{eval,ceiling}.py)
// + module unit tests + the adapter's merge/ordinal + contraction-display oracles
// (CTC integration audit H1/L3, 2026-08-14).
'tribixbite.cleverkeys.swipe.ctc.CtcParityTest',
'tribixbite.cleverkeys.swipe.ctc.CtcModuleTest',
'tribixbite.cleverkeys.swipe.ctc.CtcLexiconMergeTest',
'tribixbite.cleverkeys.swipe.ctc.CtcContractionDisplayTest',
// Context-LM persistence fix (audit 2026-08-06) — debounced write-back substrate,
// language-keyed singleton BigramStore, UserVocabulary save-storm fix
'tribixbite.cleverkeys.persist.DebouncedPersisterTest',
'tribixbite.cleverkeys.contextaware.BigramStorePersistenceTest',
'tribixbite.cleverkeys.contextaware.ContextModelLanguageTest',
'tribixbite.cleverkeys.personalization.UserVocabularyPersistenceTest',
// User-configurable learned-vocabulary cap (personalization_max_words, 2026-08-08)
'tribixbite.cleverkeys.personalization.UserVocabularyCapTest',
// Opt-in next-word prediction (audit 2026-08-06 §4) — pure gating + generation
'tribixbite.cleverkeys.NextWordPredictorTest',
// Task A (2026-08-06): MASTER on-device-learning privacy gate — pure gate logic
// + write-layer enforcement over the real stores (nothing recorded/persisted when off)
'tribixbite.cleverkeys.LearningGateTest',
'tribixbite.cleverkeys.OnDeviceLearningPrivacyTest',
// Task B (2026-08-06): pipeline transparency — UnifiedScore combiner + provenance model
'tribixbite.cleverkeys.SuggestionProvenanceTest',
// Task C (2026-08-06): TrigramStore activation — same persistence discipline as BigramStore
'tribixbite.cleverkeys.contextaware.TrigramStorePersistenceTest',
'tribixbite.cleverkeys.contextaware.ContextModelTrigramTest',
// Review fixes 2026-08-06 (H1/H3/M1/M3/M4/M5/M7 + LOWs): learn-window boundaries,
// forget-vs-flush races, selection-history retention, wiring drift guards
'tribixbite.cleverkeys.ContextLearningBoundaryTest',
'tribixbite.cleverkeys.contextaware.LearnedStoreForgetRaceTest',
'tribixbite.cleverkeys.SelectionHistoryTest',
'tribixbite.cleverkeys.LearningWiringDriftTest',
// TODO-sweep 2026-08-06: autocorrect-undo learning rollback (inverse of recordCommit)
// + language-slot eviction coverage drift guard (formerly a DictionaryManager TODO)
'tribixbite.cleverkeys.contextaware.NgramRollbackTest',
'tribixbite.cleverkeys.LanguageSlotCoverageDriftTest',
// WP9 implementation-audit remediation 2026-08-11 (docs/audit/remediation/3-core-ime.md):
// n-2 ML-trace provenance (layout + decoder engine) incl. legacy-row compatibility
'tribixbite.cleverkeys.ml.SwipeMLDataProvenanceTest',
// SwipePrunerTest excluded: requires android.util.Log (MockK + Robolectric)
]
mainClass = 'org.junit.runner.JUnitCore'
// Build classpath from test + main compiled classes + all dependencies
// The java-res output dir holds processed test resources (incl. files exposed
// from src/main/assets via the test sourceSet's resources.srcDirs additions).
classpath = files(
"${buildDir}/intermediates/javac/debugUnitTest/classes",
"${buildDir}/tmp/kotlin-classes/debugUnitTest",
"${buildDir}/intermediates/javac/debug/classes",
"${buildDir}/tmp/kotlin-classes/debug",
"${buildDir}/intermediates/java_res/debugUnitTest/processDebugUnitTestJavaRes/out",
) + configurations.debugUnitTestRuntimeClasspath + configurations.debugRuntimeClasspath
// Forward the geometric-swipe full-grid flag into the forked JVM. Gradle `-P`
// properties do NOT reach a forked JavaExec, so the geometric accuracy/benchmark
// tests read System.getProperty("geoFull") — this line bridges `-PgeoFull=true`
// into that system property (default "false"). See spec Phase-6 item m27.
systemProperty 'geoFull', (project.findProperty('geoFull') ?: 'false')
// Allow single test via -PtestClass=ClassName
if (project.hasProperty('testClass')) {
def cls = project.property('testClass')
args = ["tribixbite.cleverkeys.${cls}"]
} else {
args = pureTestClasses
}
}
// MockK test runner — like runPureTests but with android.jar on classpath.
// Allows MockK to mock Android framework classes (Log, PointF, Context, etc.)
// without Robolectric. The android.jar stubs provide class definitions; MockK
// intercepts all calls before the stubs' "Stub!" exceptions are hit.
// Usage: ./gradlew runMockTests [-PtestClass=SwipePrunerTest]
tasks.register('runMockTests', JavaExec) {
dependsOn 'compileDebugUnitTestKotlin'
group = 'verification'
description = 'Run MockK-based tests with android.jar stubs (works on ARM64)'
def mockTestClasses = [
'tribixbite.cleverkeys.SwipePrunerTest',
'tribixbite.cleverkeys.PrivacyManagerTest',
'tribixbite.cleverkeys.DebugLoggingManagerTest',
'tribixbite.cleverkeys.AutocapitalisationTest',
'tribixbite.cleverkeys.DirectBootManagerTest',
'tribixbite.cleverkeys.DirectBootAwarePreferencesTest',
'tribixbite.cleverkeys.DictionaryManagerTest',
'tribixbite.cleverkeys.VibratorCompatTest',
'tribixbite.cleverkeys.TerminalUtilsTest',
'tribixbite.cleverkeys.KeyRepeatLogicTest',
'tribixbite.cleverkeys.backup.SettingsImportPlanApplyTest',
'tribixbite.cleverkeys.backup.DictImportPlanApplyTest',
'tribixbite.cleverkeys.backup.BackupRestoreManagerHeadlessTest',
'tribixbite.cleverkeys.BackupRestoreFullBackupTest',
'tribixbite.cleverkeys.clipboard.sanitize.SanitizationConfigBuildTest',
'tribixbite.cleverkeys.customization.CustomShortSwipeExecutorTest',
'tribixbite.cleverkeys.autocorrect.AutoCorrectEndToEndTest',
// Audit remediation (2026-07-17) — new MockK tests
'tribixbite.cleverkeys.NeuralSwipeTypingEngineInitRetryTest',
'tribixbite.cleverkeys.PredictionCoordinatorNeuralLifecycleTest',
'tribixbite.cleverkeys.InputCoordinatorReplayGuardTest',
'tribixbite.cleverkeys.CleanupHandlerTeardownTest',
'tribixbite.cleverkeys.AutocapitalisationCallbackDedupeTest',
'tribixbite.cleverkeys.ClipboardMediaManagerZipSlipTest',
'tribixbite.cleverkeys.BackupRestoreArchiveLimitsTest',
// Backup encryption (2026-07-17) — Android-touching tests (need android.jar)
'tribixbite.cleverkeys.backup.crypto.BackupPassphraseStoreTest',
'tribixbite.cleverkeys.BackupRestoreManagerEncryptionTest',
// Private copy/paste (#156)
'tribixbite.cleverkeys.PrivateCopyServiceTest',
]
mainClass = 'org.junit.runner.JUnitCore'
// android.jar MUST come AFTER MockK on classpath so MockK intercepts first
// Resolve SDK location: ANDROID_HOME (CI), ANDROID_SDK_ROOT, or ~/android-sdk (Termux)
def sdkDir = System.getenv('ANDROID_HOME') ?: System.getenv('ANDROID_SDK_ROOT') ?: "${System.getProperty('user.home')}/android-sdk"
def androidJar = file("${sdkDir}/platforms/android-34/android.jar")
classpath = files(
"${buildDir}/intermediates/javac/debugUnitTest/classes",
"${buildDir}/tmp/kotlin-classes/debugUnitTest",
"${buildDir}/intermediates/javac/debug/classes",
"${buildDir}/tmp/kotlin-classes/debug",
) + configurations.debugUnitTestRuntimeClasspath + configurations.debugRuntimeClasspath + files(androidJar)
if (project.hasProperty('testClass')) {
def cls = project.property('testClass')
args = ["tribixbite.cleverkeys.${cls}"]
} else {
args = mockTestClasses
}
}
// Run all tests: pure + mock
tasks.register('runAllTests') {
dependsOn 'runPureTests', 'runMockTests'
group = 'verification'
description = 'Run all tests (pure JVM + MockK-based)'
}
tasks.register('buildKeyboardFont') {
def fontFile = file("assets/special_font.ttf")
if (fontFile.exists()) return
exec {
workingDir "$projectDir/srcs/special_font"
def svgFiles = workingDir.listFiles().findAll { it.isFile() && it.name.endsWith(".svg") }
commandLine("fontforge", "-lang=ff", "-script", "build.pe", "$buildDir/special_font.ttf", *svgFiles)
}
copy { from "$buildDir/special_font.ttf" into "assets" }
}
tasks.register('genEmojis') {
def outFile = file("res/raw/emojis.txt")
if (outFile.exists() && outFile.length() > 1000) return
exec { workingDir = projectDir; commandLine "python3", "gen_emoji.py"; ignoreExitValue = true }
}
tasks.withType(Test).configureEach {
dependsOn 'genLayoutsList', 'checkKeyboardLayouts', 'generateComposeData'
}
tasks.register('genLayoutsList') {
def outFile = file("res/values/layouts.xml")
if (outFile.exists() && outFile.length() > 100) return
exec { workingDir = projectDir; commandLine "python3", "gen_layouts.py"; ignoreExitValue = true }
}
tasks.register('checkKeyboardLayouts') {
if (!file("res/values/layouts.xml").exists()) return
exec { workingDir = projectDir; commandLine "python3", "tools/check_layout.py"; ignoreExitValue = true }
}
tasks.register('generateBinaryDictionaries') {
doLast {
def dictDir = file("src/main/assets/dictionaries")
dictDir.listFiles().findAll { it.name.endsWith(".json") && !it.name.contains("contraction") }.each { jsonFile ->
def binFile = new File(dictDir, jsonFile.name.replace(".json", ".bin"))
if (!binFile.exists() || jsonFile.lastModified() > binFile.lastModified()) {
// DICT-1 guard: generate_binary_dict.py emits the V1 'DICT' format (no
// accent map). The English dictionary ships as V2 'CKDT' (built by
// build_wordlist.py) and is the only bundled dict with a .json in
// assets. A stray json mtime bump (formatter, partial checkout/stash,
// CI) would otherwise silently DOWNGRADE it to V1, losing accent-folding.
// Never overwrite an existing CKDT bin with a DICT one.
if (binFile.exists()) {
def magic = binFile.withInputStream { it.readNBytes(4) }
if (new String(magic, "US-ASCII") == "CKDT") {
logger.lifecycle("Skipping ${binFile.name}: existing bin is V2 (CKDT); " +
"regenerate it with build_wordlist.py --write, not generate_binary_dict.py (V1).")
return // continue to next json
}
}
exec { workingDir = projectDir; commandLine "python3", "scripts/generate_binary_dict.py", jsonFile.absolutePath, binFile.absolutePath }
}
}
}
}
tasks.register('generateBinaryContractions') {
doLast {
def dictDir = file("src/main/assets/dictionaries")
def binFile = new File(dictDir, "contractions.bin")
if (!binFile.exists()) {
exec {
workingDir = projectDir
commandLine "python3", "scripts/generate_binary_contractions.py",
new File(dictDir, "contractions_non_paired.json").absolutePath,
new File(dictDir, "contraction_pairings.json").absolutePath,
binFile.absolutePath
}
}
}
}
// REPRODUCIBILITY: Generate version info with deterministic values only
// Removes commit_date as it changes with each commit and breaks reproducibility
tasks.register('generateVersionInfo') {
def outDir = file("${buildDir}/generated/version/res/raw")
outputs.dir(outDir)
doLast {
// Use only the version string - no git info that could vary between builds
// Commit info is removed entirely to ensure byte-identical APKs
outDir.mkdirs()
def versionFile = new File(outDir, "version_info.txt")
versionFile.text = """\
version=${project.ext.versionNameStr}
"""
println "Generated version_info.txt in ${versionFile.absolutePath}: version=${project.ext.versionNameStr}"
}
}
tasks.named("preBuild") {
dependsOn "initDebugKeystore", "copyLayoutDefinitions", "generateBinaryDictionaries", "generateBinaryContractions", "generateComposeData", "generateVersionInfo", "generateSettingsSearchIndex"
}
// Auto-derive the settings search index from the SettingsActivity controls so it never
// has to be hand-maintained (see scripts/generate_settings_search_index.py). Inputs/outputs
// are declared so Gradle skips regeneration when nothing relevant changed.
tasks.register('generateSettingsSearchIndex') {
def src = file("src/main/kotlin/tribixbite/cleverkeys/SettingsActivity.kt")
def sectionsDir = fileTree("src/main/kotlin/tribixbite/cleverkeys/ui/settings/sections") { include "*.kt" }
def strings = file("res/values/strings.xml")
def script = file("scripts/generate_settings_search_index.py")
def outKt = file("build/generated/search/kotlin/tribixbite/cleverkeys/SettingsSearchIndex.kt")
inputs.files(src, strings, script)
inputs.files(sectionsDir)
outputs.file(outKt)
doLast {
exec { workingDir = projectDir; commandLine "python3", script.absolutePath, outKt.absolutePath }
}
}
tasks.register('generateComposeData') {
doLast {
def composeDir = file("srcs/compose")
def outputBin = file("src/main/assets/compose_data.bin")
def outputKt = file("src/main/kotlin/tribixbite/cleverkeys/ComposeKeyData.kt")
if (outputBin.exists() && outputKt.exists()) return
def jsonFiles = fileTree("srcs/compose").matching { include "*.json" }.files.collect { it.absolutePath }
exec { workingDir = projectDir; commandLine(["python3", "scripts/generate_compose_bin.py"] + jsonFiles + [file("srcs/compose/compose").absolutePath]) }
}
}
tasks.register('initDebugKeystore') {
if (!file("debug.keystore").exists()) {
exec { commandLine "keytool", "-genkeypair", "-dname", "cn=d, ou=e, o=b, c=ug", "-alias", "debug", "-keypass", "debug0", "-keystore", "debug.keystore", "-keyalg", "rsa", "-storepass", "debug0", "-validity", "10000" }
}
}
// copyLayoutDefinitions copies ALL layout XMLs from src/main/layouts/ (including latn_qwerty_us.xml)
// into build/generated/layouts/res/raw/ — no separate copyRawQwertyUS needed.
tasks.register('copyLayoutDefinitions', Copy) { from "src/main/layouts"; include "*.xml"; into "build/generated/layouts/res/raw" }
tasks.register("printR8Version") {
doLast {
try {
def r8Class = Class.forName("com.android.tools.r8.Version")
println "R8 Version: ${r8Class.getVersionString()}"
} catch (Exception e) {
println "R8 Version not found in classpath"
}
}
}
// REPRODUCIBILITY: Normalize APK resource paths by removing -v4 suffixes
// This fixes AAPT2 adding non-deterministic version qualifiers to resource paths
tasks.register("normalizeApkPaths") {
description = "Normalize APK resource paths for reproducibility"
group = "build"
// Only run after release builds
mustRunAfter tasks.matching { it.name.startsWith("assemble") && it.name.contains("Release") }
doLast {
def apkDir = file("${buildDir}/outputs/apk/release")
if (!apkDir.exists()) {
println "No release APKs found to normalize"
return
}
def scriptPath = file("${projectDir}/scripts/normalize_apk.py")
if (!scriptPath.exists()) {
println "Warning: normalize_apk.py not found at ${scriptPath}"
return
}
// Get signing config
def keystorePath = System.env.RELEASE_KEYSTORE ?: file("debug.keystore").absolutePath
def keyAlias = System.env.RELEASE_KEY_ALIAS ?: "debug"
def storePass = System.env.RELEASE_KEYSTORE_PASSWORD ?: "debug0"
def keyPass = System.env.RELEASE_KEY_PASSWORD ?: "debug0"
apkDir.listFiles()?.findAll { it.name.endsWith(".apk") }?.each { apkFile ->
println "Normalizing: ${apkFile.name}"
def normalizedApk = new File(apkFile.parentFile, apkFile.name.replace(".apk", "_normalized.apk"))
try {
exec {
commandLine "python3", scriptPath.absolutePath,
apkFile.absolutePath,
normalizedApk.absolutePath,
"--sign",
"--keystore", keystorePath,
"--key-alias", keyAlias,
"--store-pass", storePass,
"--key-pass", keyPass
}
// Replace original with normalized
if (normalizedApk.exists()) {
apkFile.delete()
normalizedApk.renameTo(apkFile)
println "Normalized: ${apkFile.name}"
}
} catch (Exception e) {
println "Warning: Failed to normalize ${apkFile.name}: ${e.message}"
}
}
}
}
// Hook normalization into release builds
tasks.configureEach { task ->
if (task.name == "assembleRelease") {
task.finalizedBy("normalizeApkPaths")
}
}