Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: integrate Vosk small English model and implement wake word detection functionality

Durganshu Mishra4f95cfb9d635
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/README b/app/src/main/assets/vosk-model-small-en-us-0.15/README
new file mode 100644
index 0000000..a7f7931
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/README
@@ -0,0 +1,9 @@
+US English model for mobile Vosk applications
+
+Copyright 2020 Alpha Cephei Inc
+
+Accuracy: 10.38 (tedlium test) 9.85 (librispeech test-clean)
+Speed: 0.11xRT (desktop)
+Latency: 0.15s (right context)
+
+
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl b/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl
new file mode 100644
index 0000000..5596b31
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/am/final.mdl differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf
new file mode 100644
index 0000000..eaa40c5
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/mfcc.conf
@@ -0,0 +1,7 @@
+--sample-frequency=16000
+--use-energy=false
+--num-mel-bins=40
+--num-ceps=40
+--low-freq=20
+--high-freq=7600
+--allow-downsample=true
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf
new file mode 100644
index 0000000..9d5b0da
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/conf/model.conf
@@ -0,0 +1,10 @@
+--min-active=200
+--max-active=3000
+--beam=10.0
+--lattice-beam=2.0
+--acoustic-scale=1.0
+--frame-subsampling-factor=3
+--endpoint.silence-phones=1:2:3:4:5:6:7:8:9:10
+--endpoint.rule2.min-trailing-silence=0.5
+--endpoint.rule3.min-trailing-silence=0.75
+--endpoint.rule4.min-trailing-silence=1.0
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst
new file mode 100644
index 0000000..1f292e6
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/Gr.fst differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst
new file mode 100644
index 0000000..9797b26
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/HCLr.fst differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int
new file mode 100644
index 0000000..762fd5f
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/disambig_tid.int
@@ -0,0 +1,17 @@
+10015
+10016
+10017
+10018
+10019
+10020
+10021
+10022
+10023
+10024
+10025
+10026
+10027
+10028
+10029
+10030
+10031
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int
new file mode 100644
index 0000000..df23fd7
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/graph/phones/word_boundary.int
@@ -0,0 +1,166 @@
+1 nonword
+2 begin
+3 end
+4 internal
+5 singleton
+6 nonword
+7 begin
+8 end
+9 internal
+10 singleton
+11 begin
+12 end
+13 internal
+14 singleton
+15 begin
+16 end
+17 internal
+18 singleton
+19 begin
+20 end
+21 internal
+22 singleton
+23 begin
+24 end
+25 internal
+26 singleton
+27 begin
+28 end
+29 internal
+30 singleton
+31 begin
+32 end
+33 internal
+34 singleton
+35 begin
+36 end
+37 internal
+38 singleton
+39 begin
+40 end
+41 internal
+42 singleton
+43 begin
+44 end
+45 internal
+46 singleton
+47 begin
+48 end
+49 internal
+50 singleton
+51 begin
+52 end
+53 internal
+54 singleton
+55 begin
+56 end
+57 internal
+58 singleton
+59 begin
+60 end
+61 internal
+62 singleton
+63 begin
+64 end
+65 internal
+66 singleton
+67 begin
+68 end
+69 internal
+70 singleton
+71 begin
+72 end
+73 internal
+74 singleton
+75 begin
+76 end
+77 internal
+78 singleton
+79 begin
+80 end
+81 internal
+82 singleton
+83 begin
+84 end
+85 internal
+86 singleton
+87 begin
+88 end
+89 internal
+90 singleton
+91 begin
+92 end
+93 internal
+94 singleton
+95 begin
+96 end
+97 internal
+98 singleton
+99 begin
+100 end
+101 internal
+102 singleton
+103 begin
+104 end
+105 internal
+106 singleton
+107 begin
+108 end
+109 internal
+110 singleton
+111 begin
+112 end
+113 internal
+114 singleton
+115 begin
+116 end
+117 internal
+118 singleton
+119 begin
+120 end
+121 internal
+122 singleton
+123 begin
+124 end
+125 internal
+126 singleton
+127 begin
+128 end
+129 internal
+130 singleton
+131 begin
+132 end
+133 internal
+134 singleton
+135 begin
+136 end
+137 internal
+138 singleton
+139 begin
+140 end
+141 internal
+142 singleton
+143 begin
+144 end
+145 internal
+146 singleton
+147 begin
+148 end
+149 internal
+150 singleton
+151 begin
+152 end
+153 internal
+154 singleton
+155 begin
+156 end
+157 internal
+158 singleton
+159 begin
+160 end
+161 internal
+162 singleton
+163 begin
+164 end
+165 internal
+166 singleton
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm
new file mode 100644
index 0000000..db789eb
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.dubm differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie
new file mode 100644
index 0000000..93737bf
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.ie differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat
new file mode 100644
index 0000000..c3ec635
Binary files /dev/null and b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/final.mat differ
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats
new file mode 100644
index 0000000..b9d92ef
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/global_cmvn.stats
@@ -0,0 +1,3 @@
+ [
+ 1.682383e+11 -1.1595e+10 -1.521733e+10 4.32034e+09 -2.257938e+10 -1.969666e+10 -2.559265e+10 -1.535687e+10 -1.276854e+10 -4.494483e+09 -1.209085e+10 -5.64008e+09 -1.134847e+10 -3.419512e+09 -1.079542e+10 -4.145463e+09 -6.637486e+09 -1.11318e+09 -3.479773e+09 -1.245932e+08 -1.386961e+09 6.560655e+07 -2.436518e+08 -4.032432e+07 4.620046e+08 -7.714964e+07 9.551484e+08 -4.119761e+08 8.208582e+08 -7.117156e+08 7.457703e+08 -4.3106e+08 1.202726e+09 2.904036e+08 1.231931e+09 3.629848e+08 6.366939e+08 -4.586172e+08 -5.267629e+08 -3.507819e+08 1.679838e+09
+ 1.741141e+13 8.92488e+11 8.743834e+11 8.848896e+11 1.190313e+12 1.160279e+12 1.300066e+12 1.005678e+12 9.39335e+11 8.089614e+11 7.927041e+11 6.882427e+11 6.444235e+11 5.151451e+11 4.825723e+11 3.210106e+11 2.720254e+11 1.772539e+11 1.248102e+11 6.691599e+10 3.599804e+10 1.207574e+10 1.679301e+09 4.594778e+08 5.821614e+09 1.451758e+10 2.55803e+10 3.43277e+10 4.245286e+10 4.784859e+10 4.988591e+10 4.925451e+10 5.074584e+10 4.9557e+10 4.407876e+10 3.421443e+10 3.138606e+10 2.539716e+10 1.948134e+10 1.381167e+10 0 ]
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf
new file mode 100644
index 0000000..7748a4a
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/online_cmvn.conf
@@ -0,0 +1 @@
+# configuration file for apply-cmvn-online, used in the script ../local/run_online_decoding.sh
diff --git a/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf
new file mode 100644
index 0000000..960cd2e
--- /dev/null
+++ b/app/src/main/assets/vosk-model-small-en-us-0.15/ivector/splice.conf
@@ -0,0 +1,2 @@
+--left-context=3
+--right-context=3
diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
index 968f8e9..27d0b6a 100644
--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt
@@ -6,50 +6,118 @@ import android.content.pm.PackageManager
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.MediaRecorder
+import android.util.Log
import androidx.core.content.ContextCompat
+import com.gotcha.BuildConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
-import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import org.json.JSONObject
import org.vosk.Model
import org.vosk.Recognizer
import java.io.File
+import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean
-/** On-device Vosk keyword listener. It owns the microphone only while running. */
+/**
+ * On-device Vosk keyword listener. It owns the microphone only while running.
+ *
+ * The model is loaded and the bundled assets are extracted on an IO coroutine:
+ * the small model is tens of megabytes, so doing either on the service's main
+ * thread would show up as a ball-service freeze right after boot.
+ */
class WakeWordDetector(
context: Context,
private val scope: CoroutineScope,
+ private val sensitivityProvider: () -> Float,
+ private val onStarted: () -> Unit = {},
private val onDetected: () -> Unit,
+ private val onError: (String) -> Unit = {},
private val modelAssetPath: String = MODEL_ASSET_PATH,
private val phrase: String = WAKE_PHRASE
) {
private val appContext = context.applicationContext
+ private val stateLock = Any()
private val running = AtomicBoolean(false)
private var job: Job? = null
private var recorder: AudioRecord? = null
private var model: Model? = null
private var recognizer: Recognizer? = null
+ private var matcher = WakeWordMatcher(phrase, DEFAULT_SENSITIVITY)
+ private var generation = 0
- @Synchronized
+ @Volatile
+ var lastError: String? = null
+ private set
+
+ /** Returns false only for a synchronous precondition failure (currently the mic grant). */
fun start(): Boolean {
- if (running.get()) return true
if (ContextCompat.checkSelfPermission(appContext, Manifest.permission.RECORD_AUDIO) !=
PackageManager.PERMISSION_GRANTED
- ) return false
+ ) {
+ lastError = "Microphone permission is not granted."
+ return false
+ }
+ synchronized(stateLock) {
+ if (running.get()) return true
+ lastError = null
+ generation++
+ matcher = WakeWordMatcher(phrase, sensitivityProvider().coerceIn(0f, 1f))
+ running.set(true)
+ val startGeneration = generation
+ job = scope.launch(Dispatchers.IO) { initializeAndListen(startGeneration) }
+ }
+ return true
+ }
+
+ fun stop() {
+ val oldRecorder: AudioRecord?
+ val oldRecognizer: Recognizer?
+ val oldModel: Model?
+ val oldJob: Job?
+ synchronized(stateLock) {
+ running.set(false)
+ generation++
+ matcher.reset()
+ oldRecorder = recorder
+ oldRecognizer = recognizer
+ oldModel = model
+ oldJob = job
+ recorder = null
+ recognizer = null
+ model = null
+ job = null
+ }
+ oldRecorder?.let {
+ try {
+ it.stop()
+ } catch (_: IllegalStateException) {
+ // Already stopped.
+ }
+ it.release()
+ }
+ oldRecognizer?.close()
+ oldModel?.close()
+ oldJob?.cancel()
+ }
+
+ fun isRunning(): Boolean = running.get()
- return try {
+ private suspend fun initializeAndListen() {
+ var createdModel: Model? = null
+ var createdRecognizer: Recognizer? = null
+ var createdRecorder: AudioRecord? = null
+ try {
val modelDir = copyModelToCache()
- val createdModel = Model(modelDir.absolutePath)
- val createdRecognizer = Recognizer(createdModel, SAMPLE_RATE)
+ createdModel = Model(modelDir.absolutePath)
+ createdRecognizer = Recognizer(createdModel, SAMPLE_RATE, KEYWORD_GRAMMAR)
val bufferSize = AudioRecord.getMinBufferSize(
SAMPLE_RATE.toInt(),
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT
- ).coerceAtLeast(SAMPLE_RATE.toInt())
- val createdRecorder = AudioRecord(
+ ).coerceAtLeast(MIN_BUFFER_BYTES)
+ createdRecorder = AudioRecord(
MediaRecorder.AudioSource.VOICE_RECOGNITION,
SAMPLE_RATE.toInt(),
AudioFormat.CHANNEL_IN_MONO,
@@ -57,84 +125,108 @@ class WakeWordDetector(
bufferSize
)
if (createdRecorder.state != AudioRecord.STATE_INITIALIZED) {
- createdRecorder.release()
- createdRecognizer.close()
- createdModel.close()
- return false
+ throw IOException("AudioRecord failed to initialize")
}
- model = createdModel
- recognizer = createdRecognizer
- recorder = createdRecorder
- running.set(true)
- job = scope.launch(Dispatchers.IO) { listen(bufferSize) }
- true
- } catch (_: Exception) {
- stop()
- false
- }
- }
- @Synchronized
- fun stop() {
- running.set(false)
- recorder?.let {
- try { it.stop() } catch (_: IllegalStateException) { }
- it.release()
+ synchronized(stateLock) {
+ if (!running.get()) {
+ closeResources(createdRecorder, createdRecognizer, createdModel)
+ return
+ }
+ model = createdModel
+ recognizer = createdRecognizer
+ recorder = createdRecorder
+ }
+ scope.launch(Dispatchers.Main) { onStarted() }
+ listen(createdRecorder, createdRecognizer, bufferSize)
+ } catch (e: Exception) {
+ closeResources(createdRecorder, createdRecognizer, createdModel)
+ fail(startupError(e), e)
}
- recorder = null
- recognizer?.close()
- recognizer = null
- model?.close()
- model = null
- job?.cancel()
- job = null
}
- fun isRunning(): Boolean = running.get()
-
- private fun listen(bufferSize: Int) {
- val localRecorder = recorder ?: return
- val localRecognizer = recognizer ?: return
+ private fun listen(localRecorder: AudioRecord, localRecognizer: Recognizer, bufferSize: Int) {
val buffer = ByteArray(bufferSize)
try {
localRecorder.startRecording()
- while (running.get() && scope.isActive) {
+ while (running.get()) {
val count = localRecorder.read(buffer, 0, buffer.size)
- if (count > 0 && localRecognizer.acceptWaveForm(buffer, count)) {
- val text = JSONObject(localRecognizer.result).optString("text")
- if (containsPhrase(text)) {
- running.set(false)
- scope.launch(Dispatchers.Main) { onDetected() }
+ if (count < 0) {
+ if (running.get()) throw IOException("AudioRecord read failed: $count")
+ return
+ }
+ if (count == 0) continue
+
+ var detected = false
+ synchronized(stateLock) {
+ if (!running.get() || recorder !== localRecorder || recognizer !== localRecognizer) {
return
}
+ val isFinal = localRecognizer.acceptWaveForm(buffer, count)
+ val json = if (isFinal) localRecognizer.result else localRecognizer.partialResult
+ val text = JSONObject(json).optString(if (isFinal) "text" else "partial")
+ detected = if (isFinal) matcher.onFinal(text) else matcher.onPartial(text)
+ if (detected) running.set(false)
+ }
+ if (detected) {
+ scope.launch(Dispatchers.Main) { onDetected() }
+ return
}
}
- } catch (_: Exception) {
- // A missing/incompatible model or a lost audio device must not kill the FGS.
+ } catch (e: Exception) {
+ if (running.get()) fail("Wake word listening stopped unexpectedly.", e)
}
}
- private fun containsPhrase(text: String): Boolean {
- val normalized = text.lowercase().trim()
- return normalized == phrase || normalized.contains(" $phrase ") ||
- normalized.startsWith("$phrase ") || normalized.endsWith(" $phrase")
+ private fun fail(message: String, cause: Exception? = null) {
+ lastError = message
+ if (cause != null) Log.w(TAG, message, cause)
+ stop()
+ scope.launch(Dispatchers.Main) { onError(message) }
+ }
+
+ private fun startupError(error: Exception): String = when (error) {
+ is SecurityException -> "Microphone permission is not available."
+ is IOException -> "The bundled wake-word model could not be loaded."
+ else -> "Wake word could not start."
+ }
+
+ private fun closeResources(
+ oldRecorder: AudioRecord?,
+ oldRecognizer: Recognizer?,
+ oldModel: Model?
+ ) {
+ oldRecorder?.release()
+ oldRecognizer?.close()
+ oldModel?.close()
}
private fun copyModelToCache(): File {
- val destination = File(appContext.cacheDir, "wake-word/$modelAssetPath")
- if (File(destination, ".ready").exists()) return destination
+ val root = File(appContext.cacheDir, "wake-word")
+ val versionedRoot = File(root, BuildConfig.VERSION_CODE.toString())
+ val destination = File(versionedRoot, modelAssetPath)
+ if (File(destination, MODEL_READY_MARKER).isFile) return destination
+
destination.deleteRecursively()
copyAssetTree(modelAssetPath, destination)
- File(destination, ".ready").createNewFile()
+ File(destination, MODEL_READY_MARKER).writeText("ok")
+
+ // Old app versions may carry their own extracted copy. They are pure cache.
+ root.listFiles()?.forEach { child ->
+ if (child != versionedRoot) child.deleteRecursively()
+ }
return destination
}
private fun copyAssetTree(assetPath: String, destination: File) {
val entries = appContext.assets.list(assetPath).orEmpty()
- destination.mkdirs()
if (entries.isEmpty()) {
- appContext.assets.open(assetPath).use { input -> destination.outputStream().use(input::copyTo) }
+ destination.parentFile?.mkdirs()
+ appContext.assets.open(assetPath).use { input ->
+ destination.outputStream().use { output -> input.copyTo(output) }
+ }
} else {
+ destination.mkdirs()
entries.forEach { entry -> copyAssetTree("$assetPath/$entry", File(destination, entry)) }
}
}
@@ -142,6 +234,11 @@ class WakeWordDetector(
companion object {
const val WAKE_PHRASE = "gotcha"
const val MODEL_ASSET_PATH = "vosk-model-small-en-us-0.15"
+ const val DEFAULT_SENSITIVITY = 0.75f
private const val SAMPLE_RATE = 16_000f
+ private const val MIN_BUFFER_BYTES = 8_000
+ private const val MODEL_READY_MARKER = ".ready"
+ private const val KEYWORD_GRAMMAR = "[\"gotcha\", \"[unk]\"]"
+ private const val TAG = "WakeWordDetector"
}
}
diff --git a/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt b/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt
new file mode 100644
index 0000000..b2a1d11
--- /dev/null
+++ b/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt
@@ -0,0 +1,55 @@
+package com.gotcha.service
+
+/**
+ * Converts a stream of Vosk partial/final transcripts into one wake-word event.
+ *
+ * Vosk has no Porcupine-style sensitivity knob, so sensitivity controls how
+ * many consecutive recognition updates must contain the phrase. The grammar is
+ * already constrained to the wake word and `[unk]`; this streak check is the
+ * second layer against a single noisy partial firing a call.
+ */
+internal class WakeWordMatcher(
+ private val phrase: String,
+ sensitivity: Float
+) {
+ private val requiredConsecutiveMatches = when {
+ sensitivity >= HIGH_SENSITIVITY -> 1
+ sensitivity >= MEDIUM_SENSITIVITY -> 2
+ else -> 3
+ }
+ private var consecutiveMatches = 0
+
+ fun onPartial(text: String): Boolean = accept(text)
+
+ fun onFinal(text: String): Boolean = accept(text)
+
+ fun reset() {
+ consecutiveMatches = 0
+ }
+
+ private fun accept(text: String): Boolean {
+ if (!containsPhrase(text, phrase)) {
+ consecutiveMatches = 0
+ return false
+ }
+ consecutiveMatches++
+ if (consecutiveMatches < requiredConsecutiveMatches) return false
+ reset()
+ return true
+ }
+
+ companion object {
+ private const val MEDIUM_SENSITIVITY = 0.40f
+ private const val HIGH_SENSITIVITY = 0.75f
+ private val NON_WORD = Regex("[^a-z0-9]+")
+
+ /** Exact-token match, so "gotcha" does not fire inside another word. */
+ fun containsPhrase(text: String, phrase: String): Boolean {
+ val wanted = phrase.lowercase().trim()
+ if (wanted.isEmpty()) return false
+ return text.lowercase()
+ .split(NON_WORD)
+ .any { it == wanted }
+ }
+ }
+}
diff --git a/docs/wake-word-handoff.md b/docs/wake-word-handoff.md
index a1beca0..396afb8 100644
--- a/docs/wake-word-handoff.md
+++ b/docs/wake-word-handoff.md
@@ -7,82 +7,136 @@ voice-call path.
## Current status
-### Implemented
-- Added Vosk Android dependency in `app/build.gradle.kts`.
-- Added `Settings.wakeWordEnabled` and `Settings.wakeWordSensitivity`, with
+### Already in the current baseline
+- Vosk Android dependency in `app/build.gradle.kts`.
+- `Settings.wakeWordEnabled` and `Settings.wakeWordSensitivity`, with
persistence in `SettingsRepository`.
-- Added `service/WakeWordDetector.kt`:
- - owns `AudioRecord` only while running;
- - copies a Vosk model from `assets/` into cache;
- - runs Vosk recognition on 16 kHz mono PCM;
- - stops itself and invokes the callback on the main thread when "gotcha" is
- recognized;
- - returns `false` instead of crashing when permission/model/audio init fails.
-- Wired the detector into `service/AssistiveBallService.kt`:
- - starts only when Assistive Ball + wake word are enabled, mic permission is
- granted, and the call is idle;
- - stops whenever any call state becomes active;
- - stops in `stopBall()` and `onDestroy()`;
- - on detection, gives vibration feedback and starts the existing call flow
- via `callController.startWakeWordCall()`.
-- Added `CallSessionController.startWakeWordCall()` and `autoEndOnReply` so a
- wake-word-triggered call ends after the spoken reply; ordinary calls keep the
- existing stay-open behavior.
-- Added `tools/WakeWordBootReceiver.kt` and manifest registration to restart
- the ball service after reboot when Assistive Ball + wake word are enabled.
-- Added a wake-word toggle to `ui/AssistiveBallScreen.kt` and updated
- `ui/SettingsScreen.kt` to pass `load`/`onSave`.
-- Added `docs/wake-word.md` with the Vosk model asset contract.
+- Initial `WakeWordDetector` integration in `AssistiveBallService`:
+ - listens only while the call controller is idle;
+ - stops for active call states, `stopBall()`, and `onDestroy()`;
+ - on detection, vibrates and starts the existing call flow through
+ `callController.startWakeWordCall()`.
+- `CallSessionController.startWakeWordCall()` plus `autoEndOnReply`, so a
+ wake-word-triggered call ends after the spoken reply while ordinary calls
+ keep the existing stay-open behavior.
+- `WakeWordBootReceiver` and manifest registration for reboot restart.
+- Wake-word toggle in `AssistiveBallScreen`, with `SettingsScreen` passing
+ `load`/`onSave`.
+- `docs/wake-word.md` setup notes.
-### Important limitation
-No Vosk model binary has been added to the repo. The implementation expects
-the model directory at:
-`app/src/main/assets/vosk-model-small-en-us-0.15`
-Without that asset, `WakeWordDetector.start()` safely returns `false` and the
-wake word simply stays non-functional.
+### Added in the current uncommitted worktree
+- The official `vosk-model-small-en-us-0.15` model is now under
+ `app/src/main/assets/vosk-model-small-en-us-0.15/`.
+ - Source: `https://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip`
+ - Upstream catalog lists it as Apache 2.0.
+ - Extracted size is about 71 MB; the source zip is about 40 MB.
+- New `service/WakeWordMatcher.kt`:
+ - exact-token phrase matching;
+ - maps sensitivity to 1/2/3 consecutive matching Vosk updates;
+ - intended to reduce false triggers from a single noisy partial result.
+- `service/WakeWordDetector.kt` is mid-refactor:
+ - model extraction/loading moved off the main thread;
+ - recognizer now uses the constrained grammar `["gotcha", "[unk]"]`;
+ - asset-tree copying was fixed for file leaves;
+ - cache extraction is versioned by `BuildConfig.VERSION_CODE`;
+ - callbacks were added for started/detected/error;
+ - a generation counter was started to avoid stale async initialization after
+ rapid stop/start, but that refactor is incomplete.
-## Files changed
+## Current build state: intentionally paused while red
+The earlier synchronous implementation compiled successfully with:
+
+```powershell
+./gradlew.bat :app:compileDebugKotlin
+```
+
+After the async/sensitivity refactor began, compilation is currently broken.
+Known issues:
+
+1. `AssistiveBallService.kt` still constructs `WakeWordDetector` without the
+ new required `sensitivityProvider` argument.
+2. `WakeWordDetector.start()` calls `initializeAndListen(startGeneration)`, but
+ `initializeAndListen()` has not yet been updated to accept a generation
+ parameter.
+3. The generation guard needs to be carried through initialization, listening,
+ and failure reporting so an old coroutine cannot install resources or report
+ an error after a newer start/stop cycle.
+
+Do not assume the worktree is green until the next compile succeeds.
+
+## Next implementation steps
+1. Finish the `WakeWordDetector` generation refactor:
+ - change `initializeAndListen()` to accept `generation: Int`;
+ - assign resources only when `running && generation == this.generation`;
+ - pass the generation into `listen()`;
+ - ignore stale listener failures from an old generation.
+2. Update `AssistiveBallService` construction:
+ - pass `sensitivityProvider = { settingsRepository.load().wakeWordSensitivity }`;
+ - pass `onStarted`, `onDetected`, and `onError` callbacks;
+ - surface detector startup failures through the existing overlay once, not
+ repeatedly.
+3. Add live settings handling in `AssistiveBallService` with
+ `settingsChangeNotifier`:
+ - track `(wakeWordEnabled, wakeWordSensitivity)`;
+ - stop when disabled;
+ - restart when sensitivity changes while idle;
+ - do not interrupt an active call.
+4. Add the sensitivity slider to `AssistiveBallScreen` and persist
+ `wakeWordSensitivity`.
+5. Decide whether to add the battery-optimization exemption request:
+ - manifest permission: `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`;
+ - contextual button/education from the Assistive Ball or Permissions page.
+6. Add/refresh legal copy:
+ - explain that wake-word listening uses the microphone while the ball is on
+ and idle;
+ - state that Vosk wake-word audio is processed on-device;
+ - state that only the post-trigger voice command uses the configured STT
+ provider;
+ - consider bumping `LEGAL_VERSION` because this is a material privacy change.
+7. Add an Apache 2.0 license/notice copy for the bundled Vosk model if the
+ project intends to commit and redistribute the model asset.
+8. Add tests:
+ - `WakeWordMatcher` exact-token and sensitivity-streak behavior;
+ - settings persistence for `wakeWordEnabled` / `wakeWordSensitivity`;
+ - `CallSessionController` wake-word auto-end behavior;
+ - optionally boot-receiver gating.
+9. Run:
+ - `./gradlew.bat :app:compileDebugKotlin`
+ - focused unit tests
+ - `:app:assembleDebug` to verify the 71 MB model packages correctly
+ - `:app:detekt` if time permits.
+10. Device-test the full loop:
+ - enable ball + microphone + wake word;
+ - say "Gotcha";
+ - confirm vibration, call start, mic turn, spoken reply, and auto-end;
+ - confirm ordinary long-press calls still stay open;
+ - test screen off, reboot, OEM battery behavior, and mic contention.
+
+## Files added or changed across the whole effort
- `app/build.gradle.kts`
- `app/src/main/AndroidManifest.xml`
+- `app/src/main/assets/vosk-model-small-en-us-0.15/**` (new, uncommitted)
- `app/src/main/java/com/gotcha/data/SettingsRepository.kt`
- `app/src/main/java/com/gotcha/service/AssistiveBallService.kt`
- `app/src/main/java/com/gotcha/service/CallSessionController.kt`
-- `app/src/main/java/com/gotcha/service/WakeWordDetector.kt` (new)
-- `app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt` (new)
+- `app/src/main/java/com/gotcha/service/WakeWordDetector.kt`
+- `app/src/main/java/com/gotcha/service/WakeWordMatcher.kt` (new, uncommitted)
+- `app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt`
- `app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt`
- `app/src/main/java/com/gotcha/ui/SettingsScreen.kt`
-- `docs/wake-word.md` (new)
-
-## Verification state
-- `git diff --stat` confirmed the patch shape.
-- A first Gradle compile attempt was started:
- `./gradlew.bat :app:compileDebugKotlin`
- but it exceeded the 120s shell timeout in this environment, so compilation
- has **not** yet been verified to completion.
-
-## Next steps for the next agent
-1. Run `./gradlew.bat :app:compileDebugKotlin` and fix any compile issues.
-2. Add the actual Vosk small English model under
- `app/src/main/assets/vosk-model-small-en-us-0.15/`, then run assemble/build.
-3. Add or update unit tests:
- - settings persistence for `wakeWordEnabled` / `wakeWordSensitivity`;
- - `CallSessionController` wake-word auto-end behavior;
- - ideally a fakeable detector wrapper or gate test so service logic is
- testable without native Vosk.
-4. Consider adding a runtime restart path when the wake-word setting changes:
- currently a running service does not re-read settings until call state goes
- back to idle or the service is restarted.
-5. Decide whether to use `wakeWordSensitivity` (currently persisted but unused).
-6. Add battery-optimization education/request flow if desired; the plan called
- for it, but no `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` flow has been added.
-7. Update `app/src/main/assets/legal/privacy-data-retention.md` and/or
- `disclaimer.md` to mention the always-on wake-word listener explicitly.
+- `docs/wake-word.md`
+- `docs/wake-word-handoff.md`
## Risks / notes
-- Vosk is Apache-2.0 and avoids Porcupine's commercial APK licensing concern.
-- The detector is intentionally conservative: failure is silent and non-fatal.
-- Mic contention is handled by the call-state idle gate, but it has not been
- runtime-tested on a device.
-- `WakeWordDetector` uses full Vosk recognition and phrase filtering rather
- than a dedicated grammar-limited KWS configuration; recognition quality and
- false positives need device testing.
+- Vosk avoids Porcupine's commercial APK licensing issue; the selected model is
+ listed upstream as Apache 2.0.
+- The model makes the APK substantially larger.
+- Vosk is being used with a constrained keyword grammar rather than unrestricted
+ transcription, but accuracy and false-positive behavior still require device
+ testing.
+- The current sensitivity model is app-defined (consecutive recognition hits),
+ not a native Vosk confidence threshold.
+- Mic contention is handled by the call-state idle gate, but this still needs
+ real-device validation.
+- The current worktree should be treated as an in-progress checkpoint, not as a
+ ready-to-run branch.
diff --git a/docs/wake-word.md b/docs/wake-word.md
index 3113268..f7ac746 100644
--- a/docs/wake-word.md
+++ b/docs/wake-word.md
@@ -4,12 +4,15 @@ Gotcha's optional wake word uses Vosk locally. No audio is sent anywhere while
the listener is waiting; only the existing voice call sends the spoken command
to the configured speech-to-text provider.
-The Android build expects the Vosk model directory
-`app/src/main/assets/vosk-model-small-en-us-0.15`. Download the corresponding
-small English model from the official Vosk model distribution and place its
-contents under that directory. The model is intentionally not committed to the
-source repository because it is a large binary asset.
+The build uses the small English Vosk model at
+`app/src/main/assets/vosk-model-small-en-us-0.15`. The model is currently
+present in the working tree and was downloaded from the official Vosk model
+catalog, which lists it as Apache 2.0. It adds roughly 40 MB of compressed
+model data to the app, so decide deliberately before committing it.
The listener is active only when both Assistive Ball and Wake word are enabled,
-the microphone permission is granted, and the call state is idle. A missing
+the microphone permission is granted, and the call state is idle. An unloadable
model or unavailable microphone disables detection without crashing the service.
+
+See `docs/wake-word-handoff.md` for the current implementation checkpoint and
+remaining work.