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.
test: add Robolectric tier and agent-loop end-to-end tests
Durganshu6e516af55923
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 855a181..0ef3b36 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -26,6 +26,15 @@ jobs:- uses: gradle/actions/setup-gradle@v4+ # Robolectric downloads an android-all jar per @Config(sdk = ...) level on first+ # run; without this every fresh runner pays that download again.+ - name: Cache Robolectric android-all jars+ uses: actions/cache@v4+ with:+ path: ~/.m2/repository/org/robolectric+ key: robolectric-${{ hashFiles('app/build.gradle.kts') }}+ restore-keys: robolectric-+# No baselines: the whole repo must pass detekt and lint on every run.- name: Detektrun: ./gradlew :app:detekt --stacktracediff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex ad347c0..bc15032 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -89,6 +89,7 @@ android {}testOptions {+ unitTests.isIncludeAndroidResources = true // required by Robolectric// FeatureCoverageManifestTest rewrites docs/FEATURE_TEST_COVERAGE.md instead of// asserting on it when this is true:// ./gradlew :app:testDebugUnitTest -PupdateCoverageDocs=true@@ -265,6 +266,11 @@ dependencies {testImplementation("junit:junit:4.13.2")testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")+ // Robolectric tier: runs Context-dependent tools on the JVM, and via @Config(sdk = [...])+ // exercises SDK_INT branches across API levels far more cheaply than an emulator matrix row.+ testImplementation("org.robolectric:robolectric:4.14.1")+ testImplementation("androidx.test:core-ktx:1.6.1")+ testImplementation("io.mockk:mockk:1.13.13")// Instrumented testsandroidTestImplementation(composeBom)diff --git a/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt b/app/src/test/java/com/gotcha/agent/AgentLoopTest.ktnew file mode 100644index 0000000..b5377e0--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/AgentLoopTest.kt@@ -0,0 +1,289 @@+package com.gotcha.agent++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.Settings+import com.gotcha.llm.LLMClient+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.testsupport.ShadowExternalStorageManager+import com.gotcha.tools.AgentMode+import com.gotcha.tools.FileResolver+import kotlinx.coroutines.test.runTest+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++/**+ * End-to-end coverage of the agent loop — LLM response → [com.gotcha.tools.ToolExecutor]+ * → `ToolResult` → follow-up turn — driven by a scripted MockWebServer, including the+ * confirmation gate for destructive tools.+ *+ * The plan calls this the highest-value untested path: a handful of these catch more real+ * breakage than 200 leaf unit tests, because everything below has to actually fit together.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class AgentLoopTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private lateinit var server: MockWebServer+ private lateinit var engine: AgentEngine+ private lateinit var events: RecordingAgentEvents+ private lateinit var workDir: File+ private lateinit var savedWorkingDir: String++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ server = MockWebServer()+ server.start()++ workDir = File(context.filesDir, "agent-loop-test").apply {+ deleteRecursively()+ mkdirs()+ }+ savedWorkingDir = FileResolver.WORKING_DIR_BASE++ events = RecordingAgentEvents()+ engine = AgentEngine(+ appContext = context,+ events = events,+ historyRepository = ChatHistoryRepository(context, "agent-loop-test-chats"),+ settingsProvider = {+ Settings(+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ // Keep the loop short so a scripted script that never terminates fails fast.+ maxToolRounds = 4+ )+ },+ clientProvider = {+ LLMClient(apiKey = "test-key", baseUrl = server.url("/").toString())+ },+ workingDirRoot = workDir.absolutePath+ )+ engine.sessionId = "agent-loop-test"+ FileResolver.WORKING_DIR_BASE = workDir.absolutePath+ }++ @After+ fun tearDown() {+ server.shutdown()+ FileResolver.WORKING_DIR_BASE = savedWorkingDir+ workDir.deleteRecursively()+ ShadowExternalStorageManager.resetGranted()+ }++ // ---- scripting helpers ----++ private fun enqueueToolCall(tool: String, argsJson: String, id: String = "call_1") {+ server.enqueue(+ MockResponse().setBody(+ """+ {"choices":[{"message":{"role":"assistant","tool_calls":[+ {"id":"$id","type":"function",+ "function":{"name":"$tool","arguments":${argsJson.toJsonStringLiteral()}}}+ ]}}]}+ """.trimIndent()+ )+ )+ }++ private fun enqueueTextReply(text: String) {+ server.enqueue(+ MockResponse().setBody(+ """{"choices":[{"message":{"role":"assistant","content":"$text"}}]}"""+ )+ )+ }++ private fun String.toJsonStringLiteral(): String =+ "\"" + replace("\\", "\\\\").replace("\"", "\\\"") + "\""++ // ---- the loop ----++ @Test+ fun `a tool call is executed and its result is fed back for a follow-up turn`() = runTest {+ val target = File(workDir, "note.txt")+ enqueueToolCall("write_file", """{"path":"${target.absolutePath}","content":"from the agent"}""")+ enqueueTextReply("Done — I wrote the file.")++ engine.run(AgentMode.OPERATOR)++ // 1. the tool actually ran+ assertTrue("the tool did not run: file missing", target.isFile)+ assertEquals("from the agent", target.readText())++ // 2. the loop took a second turn rather than stopping at the tool call+ assertEquals("expected two LLM calls (tool round + follow-up)", 2, server.requestCount)++ // 3. the tool result was sent back to the model+ server.takeRequest()+ val followUp = server.takeRequest().body.readUtf8()+ assertTrue("the follow-up turn carried no tool result:\n$followUp", followUp.contains("\"tool\""))++ // 4. the final assistant reply reached the host+ assertEquals("Done — I wrote the file.", events.assistantReplies.lastOrNull())+ }++ @Test+ fun `a plain text response ends the loop after one call`() = runTest {+ enqueueTextReply("No tools needed.")++ engine.run(AgentMode.OPERATOR)++ assertEquals(1, server.requestCount)+ assertEquals("No tools needed.", events.assistantReplies.lastOrNull())+ }++ @Test+ fun `a failing tool reports the error back to the model instead of aborting`() = runTest {+ // Missing the required 'content' argument: dispatch returns a missing() error.+ enqueueToolCall("write_file", """{"path":"${File(workDir, "x.txt").absolutePath}"}""")+ enqueueTextReply("I could not write the file.")++ engine.run(AgentMode.OPERATOR)++ assertEquals("the loop should continue after a tool error", 2, server.requestCount)+ server.takeRequest()+ val followUp = server.takeRequest().body.readUtf8()+ assertTrue("the error was not returned to the model:\n$followUp", followUp.contains("content"))+ }++ @Test+ fun `an empty model response surfaces an error rather than looping`() = runTest {+ server.enqueue(MockResponse().setBody("""{"choices":[]}"""))++ engine.run(AgentMode.OPERATOR)++ assertEquals(1, server.requestCount)+ assertTrue(+ "expected an error bubble, got: ${events.uiMessages}",+ events.uiMessages.any { it.contains("empty response") }+ )+ }++ @Test+ fun `a transport failure surfaces an error and stops the loop`() = runTest {+ server.enqueue(MockResponse().setResponseCode(500).setBody("boom"))++ engine.run(AgentMode.OPERATOR)++ assertEquals(1, server.requestCount)+ assertTrue("expected an error bubble, got: ${events.uiMessages}", events.uiMessages.isNotEmpty())+ }++ // ---- the confirmation gate ----++ /**+ * `uninstall_app` does not uninstall directly: it resolves the package and returns a+ * `CONFIRM_UNINSTALL:` marker, which the loop turns into an `awaitConfirmation` call and+ * only then performs the removal. This asserts the whole marker → gate → decision path.+ */+ @Test+ fun `a destructive tool is gated on user confirmation and is not run when denied`() = runTest {+ installFakePackage("com.example.victim", "Victim App")+ events.confirmationAnswer = false+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""")+ enqueueTextReply("Okay, I left it installed.")++ engine.run(AgentMode.OPERATOR)++ assertTrue("the destructive tool was not gated", events.confirmationRequests.isNotEmpty())+ assertTrue(+ "the gate should name the tool: ${events.confirmationRequests}",+ events.confirmationRequests.any { it.contains("uninstall_app") }+ )+ assertTrue(+ "the model should be told the user declined: ${events.uiMessages}",+ events.uiMessages.any { it.contains("declined", ignoreCase = true) }+ )+ }++ @Test+ fun `approving the gate lets the destructive tool proceed`() = runTest {+ installFakePackage("com.example.victim", "Victim App")+ events.confirmationAnswer = true+ enqueueToolCall("uninstall_app", """{"package_name":"com.example.victim"}""")+ enqueueTextReply("Removed.")++ engine.run(AgentMode.OPERATOR)++ assertTrue("the gate was never shown", events.confirmationRequests.isNotEmpty())+ assertFalse(+ "an approved uninstall should not report a decline: ${events.uiMessages}",+ events.uiMessages.any { it.contains("declined", ignoreCase = true) }+ )+ }++ private fun installFakePackage(packageName: String, label: String) {+ val applicationInfo = android.content.pm.ApplicationInfo().apply {+ this.packageName = packageName+ this.name = label+ nonLocalizedLabel = label+ }+ org.robolectric.Shadows.shadowOf(context.packageManager).installPackage(+ android.content.pm.PackageInfo().apply {+ this.packageName = packageName+ this.applicationInfo = applicationInfo+ }+ )+ }++ @Test+ fun `the confirmation gate is not triggered for a non-destructive tool`() = runTest {+ enqueueToolCall("write_file", """{"path":"${File(workDir, "safe.txt").absolutePath}","content":"ok"}""")+ enqueueTextReply("Written.")++ engine.run(AgentMode.OPERATOR)++ assertTrue(+ "a harmless write should not prompt the user: ${events.confirmationRequests}",+ events.confirmationRequests.isEmpty()+ )+ }++ // ---- agent-mode enforcement, end to end ----++ @Test+ fun `Monitor mode refuses an Operator-only tool`() = runTest {+ enqueueToolCall("write_file", """{"path":"${File(workDir, "nope.txt").absolutePath}","content":"x"}""")+ enqueueTextReply("I cannot do that in Monitor mode.")++ engine.run(AgentMode.MONITOR)++ assertFalse("the tool ran despite Monitor mode", File(workDir, "nope.txt").exists())+ server.takeRequest()+ val followUp = server.takeRequest().body.readUtf8()+ assertTrue(+ "the model was not told why the tool was refused:\n$followUp",+ followUp.contains("Monitor") || followUp.contains("not available")+ )+ }++ // ---- history ----++ @Test+ fun `the exchange is recorded in history for the next turn`() = runTest {+ enqueueTextReply("Recorded.")++ engine.run(AgentMode.OPERATOR)++ assertTrue("nothing was appended to history", engine.history.isNotEmpty())+ assertTrue(+ "the assistant reply is missing from history: ${engine.history}",+ engine.history.any { it.textContent.contains("Recorded.") }+ )+ }+}diff --git a/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.ktnew file mode 100644index 0000000..fa481f9--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/RecordingAgentEvents.kt@@ -0,0 +1,59 @@+package com.gotcha.agent++/**+ * An [AgentEvents] that records what the agent loop emitted instead of driving a UI,+ * so tests can assert on the loop's externally visible behaviour.+ */+class RecordingAgentEvents : AgentEvents {++ val uiMessages = mutableListOf<String>()+ val activities = mutableListOf<String?>()+ val assistantReplies = mutableListOf<String>()+ val permissionRequests = mutableListOf<String>()+ val confirmationRequests = mutableListOf<String>()+ var historyResets = 0+ private set++ /** What [awaitConfirmation] should answer. Defaults to approving. */+ var confirmationAnswer: Boolean = true++ /** What [awaitQuestionAnswer] should answer. */+ var questionAnswer: String = ""++ override fun onUi(+ kind: MessageKind,+ text: String,+ imageBase64: String?,+ subAgentSteps: List<String>,+ reasoningContent: String?+ ) {+ uiMessages += text+ }++ override fun onActivity(activity: String?) {+ activities += activity+ }++ override fun onTokenCount(totalTokens: Int) = Unit++ override fun onAssistantReply(text: String) {+ assistantReplies += text+ }++ override fun onSubAgentUpdate(running: String?, currentAction: String?) = Unit++ override fun onPermissionRequest(marker: String) {+ permissionRequests += marker+ }++ override fun onHistoryReset() {+ historyResets+++ }++ override suspend fun awaitQuestionAnswer(question: PendingQuestion): String = questionAnswer++ override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {+ confirmationRequests += "${toolNames.joinToString(",")}: $description"+ return confirmationAnswer+ }+}diff --git a/app/src/test/java/com/gotcha/testsupport/FakeAndroidKeyStore.kt b/app/src/test/java/com/gotcha/testsupport/FakeAndroidKeyStore.ktnew file mode 100644index 0000000..0eba096--- /dev/null+++ b/app/src/test/java/com/gotcha/testsupport/FakeAndroidKeyStore.kt@@ -0,0 +1,130 @@+package com.gotcha.testsupport++import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.cert.Certificate+import java.security.spec.AlgorithmParameterSpec+import java.util.Collections+import java.util.Date+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey++/**+ * An in-memory stand-in for the `AndroidKeyStore` JCE provider.+ *+ * Robolectric does not emulate the Android keystore, so anything reaching+ * `androidx.security.crypto.EncryptedSharedPreferences` — which on this codebase means+ * `ConnectorCredentialStore`, and therefore **`ToolExecutor`'s constructor** via+ * `ConnectorRegistry.init` — dies with `KeyStoreException: AndroidKeyStore not found`.+ * Without this, no Robolectric test can construct a `ToolExecutor` at all.+ *+ * The keys are ordinary in-memory AES keys, so standard JCE ciphers operate on them normally.+ * This is a test fixture: it provides no hardware backing and no security properties.+ *+ * Call [setUp] from `@Before` (it is idempotent).+ */+object FakeAndroidKeyStore {++ private const val PROVIDER_NAME = "AndroidKeyStore"++ private val entries = mutableMapOf<String, Key>()++ fun setUp() {+ if (java.security.Security.getProvider(PROVIDER_NAME) == null) {+ java.security.Security.addProvider(FakeProvider())+ }+ }++ private class FakeProvider : Provider(PROVIDER_NAME, 1.0, "Test-only fake AndroidKeyStore") {+ init {+ put("KeyStore.$PROVIDER_NAME", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeAesKeyGeneratorSpi::class.java.name)+ }+ }++ class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineGetKey(alias: String, password: CharArray?): Key? = entries[alias]++ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null++ override fun engineGetCertificate(alias: String): Certificate? = null++ override fun engineGetCreationDate(alias: String): Date = Date(0)++ override fun engineSetKeyEntry(+ alias: String,+ key: Key,+ password: CharArray?,+ chain: Array<out Certificate>?+ ) {+ entries[alias] = key+ }++ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) =+ throw UnsupportedOperationException("encoded key entries are not used by these tests")++ override fun engineSetCertificateEntry(alias: String, cert: Certificate?) =+ throw UnsupportedOperationException("certificate entries are not used by these tests")++ override fun engineDeleteEntry(alias: String) {+ entries.remove(alias)+ }++ override fun engineAliases(): java.util.Enumeration<String> =+ Collections.enumeration(entries.keys.toList())++ override fun engineContainsAlias(alias: String): Boolean = entries.containsKey(alias)++ override fun engineSize(): Int = entries.size++ override fun engineIsKeyEntry(alias: String): Boolean = entries.containsKey(alias)++ override fun engineIsCertificateEntry(alias: String): Boolean = false++ override fun engineGetCertificateAlias(cert: Certificate?): String? = null++ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit++ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ }++ class FakeAesKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String? = null+ private var keySize = 256++ override fun engineInit(random: SecureRandom?) = Unit++ override fun engineInit(params: AlgorithmParameterSpec?, random: SecureRandom?) {+ // KeyGenParameterSpec carries the alias the caller wants the key stored under.+ alias = runCatching {+ params?.javaClass?.getMethod("getKeystoreAlias")?.invoke(params) as? String+ }.getOrNull()+ val size = runCatching {+ params?.javaClass?.getMethod("getKeySize")?.invoke(params) as? Int+ }.getOrNull()+ if (size != null && size > 0) keySize = size+ }++ override fun engineInit(keysize: Int, random: SecureRandom?) {+ keySize = keysize+ }++ override fun engineGenerateKey(): SecretKey {+ val generator = KeyGenerator.getInstance("AES")+ generator.init(keySize)+ val key = generator.generateKey()+ alias?.let { entries[it] = key }+ return key+ }+ }++ /** Drops every generated key. Call from `@After` if a test needs a clean keystore. */+ fun clear() {+ entries.clear()+ }+}diff --git a/app/src/test/java/com/gotcha/testsupport/ShadowExternalStorageManager.kt b/app/src/test/java/com/gotcha/testsupport/ShadowExternalStorageManager.ktnew file mode 100644index 0000000..97bba59--- /dev/null+++ b/app/src/test/java/com/gotcha/testsupport/ShadowExternalStorageManager.kt@@ -0,0 +1,50 @@+package com.gotcha.testsupport++import android.os.Environment+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements+import org.robolectric.shadows.ShadowEnvironment++/**+ * Robolectric 4.14 does not shadow [Environment.isExternalStorageManager]; the real framework+ * implementation reaches for storage volumes that the test runtime never populates and throws+ * `ArrayIndexOutOfBoundsException`. `FileResolver` calls it on every resolve, so without this+ * shadow no file-tool test can run at all.+ *+ * Registering it also makes "All files access" a *controllable* input, so tests can cover both+ * sides of the permission branch instead of only the denied one:+ *+ * ```+ * @Config(shadows = [ShadowExternalStorageManager::class])+ * ...+ * ShadowExternalStorageManager.granted = true+ * ```+ *+ * Extends [ShadowEnvironment] rather than replacing it: a bare `@Implements(Environment)`+ * shadow takes over the whole class, so `getExternalStorageDirectory()` and friends would fall+ * through to the real framework and throw as well.+ *+ * Reset it in `@After` — Robolectric does not reset custom shadow statics between tests.+ */+@Implements(Environment::class)+class ShadowExternalStorageManager : ShadowEnvironment() {++ companion object {+ /**+ * What [Environment.isExternalStorageManager] should report. Defaults to denied.+ * Named to avoid a JVM signature clash with the `@Implementation` method below.+ */+ @JvmStatic+ var granted: Boolean = false++ @JvmStatic+ @Implementation+ fun isExternalStorageManager(): Boolean = granted++ /** Restores the default (denied). Call from `@After`. */+ @JvmStatic+ fun resetGranted() {+ granted = false+ }+ }+}diff --git a/app/src/test/java/com/gotcha/tools/AppsToolTest.kt b/app/src/test/java/com/gotcha/tools/AppsToolTest.ktnew file mode 100644index 0000000..3ced294--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/AppsToolTest.kt@@ -0,0 +1,115 @@+package com.gotcha.tools++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.content.pm.ApplicationInfo+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowPackageManager++/** `list_installed_apps` against a ShadowPackageManager seeded with known launchable apps. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34])+class AppsToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val tool = AppsTool(context)++ private lateinit var packageManager: ShadowPackageManager++ @Before+ fun seedApps() {+ packageManager = shadowOf(context.packageManager)+ installLaunchableApp("com.example.notes", "Notes", system = false)+ installLaunchableApp("com.example.camera", "Camera", system = true)+ installLaunchableApp("com.other.weather", "Weather Live", system = false)+ }++ private fun installLaunchableApp(packageName: String, label: String, system: Boolean) {+ val applicationInfo = ApplicationInfo().apply {+ this.packageName = packageName+ this.name = label+ nonLocalizedLabel = label+ if (system) flags = flags or ApplicationInfo.FLAG_SYSTEM+ }+ val packageInfo = android.content.pm.PackageInfo().apply {+ this.packageName = packageName+ this.applicationInfo = applicationInfo+ }+ packageManager.installPackage(packageInfo)++ val component = ComponentName(packageName, "$packageName.MainActivity")+ packageManager.addActivityIfNotPresent(component)+ packageManager.addIntentFilterForActivity(+ component,+ IntentFilter(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_LAUNCHER) }+ )+ }++ @Test+ fun `list_installed_apps lists launchable apps with their package names`() {+ val result = tool.listInstalledApps(null)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("com.example.notes"))+ assertTrue(result.message, result.message.contains("com.other.weather"))+ }++ @Test+ fun `list_installed_apps marks system apps`() {+ val result = tool.listInstalledApps(null)++ val cameraLine = result.message.lines().first { it.contains("com.example.camera") }+ assertTrue("system app not marked: $cameraLine", cameraLine.contains("[system]"))++ val notesLine = result.message.lines().first { it.contains("com.example.notes") }+ assertFalse("user app marked as system: $notesLine", notesLine.contains("[system]"))+ }++ @Test+ fun `list_installed_apps reports user and system counts`() {+ val result = tool.listInstalledApps(null)++ assertTrue("expected a total line in:\n${result.message}", result.message.contains("Total:"))+ assertTrue(result.message, result.message.contains("user"))+ assertTrue(result.message, result.message.contains("system"))+ }++ @Test+ fun `list_installed_apps search filters by package name`() {+ val result = tool.listInstalledApps("weather")++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("com.other.weather"))+ assertFalse(+ "search returned an unrelated app:\n${result.message}",+ result.message.contains("com.example.notes")+ )+ }++ @Test+ fun `list_installed_apps search is case-insensitive`() {+ val lower = tool.listInstalledApps("weather").message+ val upper = tool.listInstalledApps("WEATHER").message++ assertTrue(upper, upper.contains("com.other.weather"))+ assertTrue("case changed the result set", lower.contains("com.other.weather"))+ }++ @Test+ fun `list_installed_apps reports no matches without failing`() {+ val result = tool.listInstalledApps("definitely-not-installed")++ assertTrue("an empty search result is not an error: ${result.message}", result.success)+ assertTrue(result.message, result.message.contains("No apps matching"))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/ClipboardToolTest.kt b/app/src/test/java/com/gotcha/tools/ClipboardToolTest.ktnew file mode 100644index 0000000..7ac0c90--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/ClipboardToolTest.kt@@ -0,0 +1,105 @@+package com.gotcha.tools++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.service.GotchaAccessibilityService+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Covers `get_clipboard` / `set_clipboard`, including the API 34 fallback path+ * (`ClipboardTool.getClipboard`) where the platform blocks clipboard reads by+ * non-IME apps and the tool falls back to the accessibility service's cache.+ *+ * `@Config(sdk = ...)` runs the same assertions on both sides of that branch in+ * seconds — far cheaper than an emulator matrix row, and it covers the same code.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 33, 34])+class ClipboardToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val tool = ClipboardTool(context)++ private val clipboard: ClipboardManager+ get() = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager++ @After+ fun clearAccessibilityCache() {+ GotchaAccessibilityService.lastClipboardData = null+ }++ @Test+ fun `set then get round-trips the text`() {+ assertTrue(tool.setClipboard("hello there").success)++ val result = tool.getClipboard()+ assertTrue(result.success)+ assertTrue("expected the text back, got: ${result.message}", result.message.contains("hello there"))+ }++ @Test+ fun `set writes through to the platform clipboard`() {+ tool.setClipboard("written by the tool")++ val clip = clipboard.primaryClip+ assertEquals(1, clip?.itemCount)+ assertEquals("written by the tool", clip?.getItemAt(0)?.coerceToText(context)?.toString())+ }++ @Test+ fun `long clipboard contents are truncated`() {+ tool.setClipboard("x".repeat(5000))++ val result = tool.getClipboard()+ assertTrue(result.success)+ // 2000 chars of payload plus the "Clipboard: " prefix.+ assertTrue("payload was not truncated: ${result.message.length}", result.message.length < 2100)+ }++ @Test+ fun `empty clipboard reports empty rather than failing`() {+ val result = tool.getClipboard()++ assertTrue(result.success)+ assertTrue(+ "expected an 'empty'/'restricted' explanation, got: ${result.message}",+ result.message.contains("empty", ignoreCase = true) ||+ result.message.contains("restricted", ignoreCase = true)+ )+ }++ @Test+ fun `falls back to the accessibility cache when the platform clipboard is empty`() {+ GotchaAccessibilityService.lastClipboardData = ClipData.newPlainText("Gotcha", "cached copy")++ val result = tool.getClipboard()++ assertTrue(result.success)+ assertTrue(+ "expected the cached value, got: ${result.message}",+ result.message.contains("cached copy")+ )+ assertTrue(+ "the fallback path should say where the text came from: ${result.message}",+ result.message.contains("accessibility", ignoreCase = true)+ )+ }++ @Test+ fun `the platform clipboard wins over a stale accessibility cache`() {+ GotchaAccessibilityService.lastClipboardData = ClipData.newPlainText("Gotcha", "stale")+ tool.setClipboard("fresh")++ val result = tool.getClipboard()++ assertTrue("expected the fresh value, got: ${result.message}", result.message.contains("fresh"))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/DeviceToolTest.kt b/app/src/test/java/com/gotcha/tools/DeviceToolTest.ktnew file mode 100644index 0000000..9646634--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/DeviceToolTest.kt@@ -0,0 +1,159 @@+package com.gotcha.tools++import android.content.Context+import android.media.AudioManager+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * `set_volume`, `get_volume` and `set_ringer_mode` against Robolectric's ShadowAudioManager.+ *+ * These tools translate between the LLM's percentages/labels and the platform's per-stream+ * integer scales — arithmetic that is easy to get subtly wrong and invisible in manual QA.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34])+class DeviceToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val tool = DeviceTool(context)++ private val audioManager: AudioManager+ get() = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager++ // ---- set_volume ----++ @Test+ fun `set_volume writes the scaled level to the right stream`() {+ val max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)++ val result = tool.setVolume("media", 50, showUi = false)++ assertTrue(result.message, result.success)+ assertEquals(max / 2, audioManager.getStreamVolume(AudioManager.STREAM_MUSIC))+ }++ @Test+ fun `set_volume maps aliases to the same stream`() {+ tool.setVolume("music", 100, showUi = false)+ val viaAlias = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)++ tool.setVolume("media", 100, showUi = false)++ assertEquals(viaAlias, audioManager.getStreamVolume(AudioManager.STREAM_MUSIC))+ }++ @Test+ fun `set_volume reports the previous level`() {+ tool.setVolume("media", 100, showUi = false)++ val result = tool.setVolume("media", 0, showUi = false)++ assertTrue("expected the old level in: ${result.message}", result.message.contains("100%"))+ assertTrue("expected the new level in: ${result.message}", result.message.contains("0%"))+ }++ @Test+ fun `set_volume rejects out-of-range percentages`() {+ assertFalse(tool.setVolume("media", -1, showUi = false).success)+ assertFalse(tool.setVolume("media", 101, showUi = false).success)+ }++ @Test+ fun `set_volume rejects an unknown stream`() {+ val result = tool.setVolume("subwoofer", 50, showUi = false)++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("Unknown volume stream"))+ }++ @Test+ fun `set_volume accepts every documented stream name`() {+ listOf("media", "ring", "alarm", "notification", "call").forEach { stream ->+ assertTrue("'$stream' was rejected", tool.setVolume(stream, 50, showUi = false).success)+ }+ }++ // ---- get_volume ----++ @Test+ fun `get_volume reports the level as a percentage`() {+ tool.setVolume("media", 100, showUi = false)++ val result = tool.getVolume("media")++ assertTrue(result.message, result.success)+ assertEquals("media: 100%", result.message)+ }++ @Test+ fun `get_volume with no stream reports every stream`() {+ val result = tool.getVolume(null)++ assertTrue(result.message, result.success)+ listOf("media", "ring", "alarm", "notification", "call").forEach {+ assertTrue("'$it' missing from:\n${result.message}", result.message.contains("$it:"))+ }+ }++ @Test+ fun `get_volume rejects an unknown stream`() {+ assertFalse(tool.getVolume("subwoofer").success)+ }++ // ---- set_ringer_mode ----++ @Test+ fun `set_ringer_mode normal needs no DND access`() {+ val result = tool.setRingerMode("normal")++ assertTrue(result.message, result.success)+ assertEquals(AudioManager.RINGER_MODE_NORMAL, audioManager.ringerMode)+ }++ @Test+ fun `set_ringer_mode silent asks for DND access when it is not granted`() {+ shadowOf(context.getSystemService(android.app.NotificationManager::class.java))+ .setNotificationPolicyAccessGranted(false)++ val result = tool.setRingerMode("silent")++ assertFalse(result.message, result.success)+ assertEquals(ToolResult.DND_ACCESS, result.needsPermission)+ }++ @Test+ fun `set_ringer_mode silent works once DND access is granted`() {+ shadowOf(context.getSystemService(android.app.NotificationManager::class.java))+ .setNotificationPolicyAccessGranted(true)++ val result = tool.setRingerMode("silent")++ assertTrue(result.message, result.success)+ assertEquals(AudioManager.RINGER_MODE_SILENT, audioManager.ringerMode)+ }++ @Test+ fun `set_ringer_mode vibrate works once DND access is granted`() {+ shadowOf(context.getSystemService(android.app.NotificationManager::class.java))+ .setNotificationPolicyAccessGranted(true)++ assertTrue(tool.setRingerMode("vibrate").success)+ assertEquals(AudioManager.RINGER_MODE_VIBRATE, audioManager.ringerMode)+ }++ @Test+ fun `set_ringer_mode rejects an unknown mode`() {+ val result = tool.setRingerMode("loudest")++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("Unknown ringer mode"))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/FileResolverTest.kt b/app/src/test/java/com/gotcha/tools/FileResolverTest.ktnew file mode 100644index 0000000..cd7c854--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/FileResolverTest.kt@@ -0,0 +1,158 @@+package com.gotcha.tools++import android.content.Context+import android.os.Environment+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.ShadowExternalStorageManager+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++/**+ * [FileResolver] is the permission gate every file tool goes through, so a mistake here+ * is either a crash-on-read or a silent bypass of "All files access".+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34], shadows = [ShadowExternalStorageManager::class])+class FileResolverTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val resolver = FileResolver(context)++ // Read lazily in @Before, not in a field initialiser: the getter falls back to+ // GotchaStorage.root(), which needs the Robolectric environment to be up.+ private lateinit var savedWorkingDir: String++ @Before+ fun captureWorkingDir() {+ savedWorkingDir = FileResolver.WORKING_DIR_BASE+ }++ @After+ fun restoreGlobals() {+ FileResolver.WORKING_DIR_BASE = savedWorkingDir+ ShadowExternalStorageManager.resetGranted()+ }++ // ---- sandbox paths need no permission ----++ @Test+ fun `paths inside the app sandbox resolve for read`() {+ val file = File(context.filesDir, "note.txt")+ val result = resolver.resolveForRead(file.absolutePath)++ assertTrue("expected Ok, got $result", result is FileResolver.ResolveResult.Ok)+ assertEquals(file.canonicalPath, (result as FileResolver.ResolveResult.Ok).file.path)+ }++ @Test+ fun `paths inside the app sandbox resolve for write`() {+ val result = resolver.resolveForWrite(File(context.cacheDir, "scratch.bin").absolutePath)+ assertTrue("expected Ok, got $result", result is FileResolver.ResolveResult.Ok)+ }++ @Test+ fun `sandbox paths need no read permission`() {+ assertEquals(null, resolver.checkReadPermission(File(context.filesDir, "x")))+ }++ @Test+ fun `sandbox paths need no write permission`() {+ assertEquals(null, resolver.checkWritePermission(File(context.cacheDir, "x")))+ }++ // ---- shared storage needs All Files Access ----++ @Test+ fun `shared storage read without all-files-access asks for the permission`() {+ val shared = File(Environment.getExternalStorageDirectory(), "Download/report.pdf")+ val result = resolver.resolveForRead(shared.absolutePath)++ assertTrue("expected PermissionNeeded, got $result", result is FileResolver.ResolveResult.PermissionNeeded)+ val toolResult = (result as FileResolver.ResolveResult.PermissionNeeded).result+ assertEquals(ToolResult.ALL_FILES_ACCESS, toolResult.needsPermission)+ }++ @Test+ fun `shared storage write without all-files-access asks for the permission`() {+ val shared = File(Environment.getExternalStorageDirectory(), "Download/out.txt")+ val result = resolver.resolveForWrite(shared.absolutePath)++ assertTrue("expected PermissionNeeded, got $result", result is FileResolver.ResolveResult.PermissionNeeded)+ }++ @Test+ fun `checkReadPermission flags shared storage`() {+ val shared = File(Environment.getExternalStorageDirectory(), "Music/song.mp3")+ assertEquals(ToolResult.ALL_FILES_ACCESS, resolver.checkReadPermission(shared)?.needsPermission)+ }++ @Test+ fun `shared storage read is allowed once all-files-access is granted`() {+ ShadowExternalStorageManager.granted = true++ val shared = File(Environment.getExternalStorageDirectory(), "Download/report.pdf")+ val result = resolver.resolveForRead(shared.absolutePath)++ assertTrue("expected Ok once granted, got $result", result is FileResolver.ResolveResult.Ok)+ assertEquals(null, resolver.checkReadPermission(shared))+ }++ @Test+ fun `shared storage write is allowed once all-files-access is granted`() {+ ShadowExternalStorageManager.granted = true++ val shared = File(Environment.getExternalStorageDirectory(), "Download/out.txt")++ assertTrue(resolver.resolveForWrite(shared.absolutePath) is FileResolver.ResolveResult.Ok)+ assertEquals(null, resolver.checkWritePermission(shared))+ }++ // ---- relative paths and traversal ----++ @Test+ fun `relative paths resolve against the working directory`() {+ FileResolver.WORKING_DIR_BASE = context.filesDir.absolutePath++ val result = resolver.resolveForRead("notes/today.md")++ assertTrue(result is FileResolver.ResolveResult.Ok)+ assertEquals(+ File(context.filesDir, "notes/today.md").canonicalPath,+ (result as FileResolver.ResolveResult.Ok).file.path+ )+ }++ @Test+ fun `dot-dot traversal is canonicalised, not trusted`() {+ FileResolver.WORKING_DIR_BASE = context.filesDir.absolutePath++ // Escaping the sandbox via ".." must be resolved to its real target, so the+ // permission check below sees the actual location rather than the sandbox prefix.+ val canonical = resolver.canonicalPath("../../../../etc/passwd")++ assertTrue("path was not canonicalised: $canonical", !canonical.contains(".."))+ }++ @Test+ fun `absolute paths ignore the working directory`() {+ FileResolver.WORKING_DIR_BASE = context.filesDir.absolutePath+ assertEquals("/tmp/thing", resolver.canonicalPath("/tmp/thing"))+ }++ // ---- formatting ----++ @Test+ fun `formatSize uses the largest fitting unit`() {+ assertEquals("512 B", FileResolver.formatSizeStatic(512))+ assertEquals("2 KB", FileResolver.formatSizeStatic(2048))+ assertEquals("1.5 MB", FileResolver.formatSizeStatic(1024L * 1024 * 3 / 2))+ assertEquals("2.0 GB", FileResolver.formatSizeStatic(1024L * 1024 * 1024 * 2))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/FileToolsTest.kt b/app/src/test/java/com/gotcha/tools/FileToolsTest.ktnew file mode 100644index 0000000..7fc76a7--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/FileToolsTest.kt@@ -0,0 +1,346 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.ShadowExternalStorageManager+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File++/**+ * `read_file`, `write_file`, `list_files`, `edit`, `glob` and `grep` against a real+ * temp directory inside the app sandbox (which [FileResolver] lets through without+ * "All files access").+ *+ * These are pure path/content logic with high bug density and low test cost — the+ * batch the plan calls out as the best value in the Robolectric tier.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34], shadows = [ShadowExternalStorageManager::class])+class FileToolsTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private val fileTool = FileTool(context)+ private val editTool = EditTool(context)+ private val globTool = GlobTool(context)+ private val grepTool = GrepTool(context)++ private lateinit var workDir: File+ private lateinit var savedWorkingDir: String++ @Before+ fun setUp() {+ savedWorkingDir = FileResolver.WORKING_DIR_BASE+ workDir = File(context.filesDir, "filetools-test").apply {+ deleteRecursively()+ mkdirs()+ }+ FileResolver.WORKING_DIR_BASE = workDir.absolutePath+ }++ @After+ fun tearDown() {+ FileResolver.WORKING_DIR_BASE = savedWorkingDir+ workDir.deleteRecursively()+ ShadowExternalStorageManager.resetGranted()+ }++ private fun write(relative: String, content: String): File =+ File(workDir, relative).apply {+ parentFile?.mkdirs()+ writeText(content)+ }++ // ---- read_file ----++ @Test+ fun `read_file returns the file contents`() {+ write("hello.txt", "line one\nline two\nline three\n")++ val result = fileTool.readFile(File(workDir, "hello.txt").absolutePath)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("line one"))+ assertTrue(result.message, result.message.contains("line three"))+ }++ @Test+ fun `read_file honours offset and limit`() {+ write("many.txt", (1..50).joinToString("\n") { "line $it" })++ val result = fileTool.readFile(File(workDir, "many.txt").absolutePath, offset = 10, limit = 3)++ assertTrue(result.message, result.success)+ assertTrue("expected the offset line, got:\n${result.message}", result.message.contains("line 11"))+ assertFalse("limit was not applied:\n${result.message}", result.message.contains("line 20"))+ }++ @Test+ fun `read_file on a missing path fails with a usable message`() {+ val result = fileTool.readFile(File(workDir, "nope.txt").absolutePath)++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("nope.txt"))+ }++ // ---- write_file ----++ @Test+ fun `write_file creates the file and any missing parent directories`() {+ val target = File(workDir, "nested/deeper/out.txt")++ val result = fileTool.writeFile(target.absolutePath, "written")++ assertTrue(result.message, result.success)+ assertEquals("written", target.readText())+ }++ @Test+ fun `write_file append adds to the existing contents`() {+ val target = write("log.txt", "first\n")++ assertTrue(fileTool.writeFile(target.absolutePath, "second\n", append = true).success)++ assertEquals("first\nsecond\n", target.readText())+ }++ @Test+ fun `write_file without append overwrites`() {+ val target = write("log.txt", "first\n")++ fileTool.writeFile(target.absolutePath, "replaced")++ assertEquals("replaced", target.readText())+ }++ // ---- list_files ----++ @Test+ fun `list_files lists the immediate children`() {+ write("a.txt", "a")+ write("b.txt", "b")+ write("sub/c.txt", "c")++ val result = fileTool.listFiles(workDir.absolutePath)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("a.txt"))+ assertTrue(result.message, result.message.contains("b.txt"))+ assertFalse("non-recursive listing descended:\n${result.message}", result.message.contains("c.txt"))+ }++ @Test+ fun `list_files recursive descends into subdirectories`() {+ write("sub/deep/c.txt", "c")++ val result = fileTool.listFiles(workDir.absolutePath, recursive = true)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("c.txt"))+ }++ // ---- edit ----++ @Test+ fun `edit replaces a unique occurrence`() {+ val target = write("code.txt", "val timeout = 30\nval retries = 3\n")++ val result = editTool.edit(target.absolutePath, "timeout = 30", "timeout = 60", replaceAll = false)++ assertTrue(result.message, result.success)+ assertEquals("val timeout = 60\nval retries = 3\n", target.readText())+ }++ /**+ * Pins the *documented* behaviour: the `edit` schema says replaceAll replaces "all+ * occurrences instead of just the first", so a non-unique oldString replaces the first+ * match rather than failing.+ *+ * Note this leaves `EditTool`'s `count > 1 && !replaceAll` ambiguity guard unreachable:+ * on that path `count` is computed as `if (content.contains(oldString)) 1 else 0`, so it+ * can never exceed 1. Whether to make that guard live (safer, but a behaviour change for+ * every caller) or delete it (matching the schema) is a product decision, deliberately+ * not taken here.+ */+ @Test+ fun `edit without replaceAll replaces only the first occurrence`() {+ val target = write("code.txt", "x = 1\nx = 1\n")++ val result = editTool.edit(target.absolutePath, "x = 1", "x = 2", replaceAll = false)++ assertTrue(result.message, result.success)+ assertEquals("x = 2\nx = 1\n", target.readText())+ }++ @Test+ fun `edit with replaceAll replaces every occurrence`() {+ val target = write("code.txt", "x = 1\nx = 1\n")++ val result = editTool.edit(target.absolutePath, "x = 1", "x = 2", replaceAll = true)++ assertTrue(result.message, result.success)+ assertEquals("x = 2\nx = 2\n", target.readText())+ }++ @Test+ fun `edit fails when the text is not present`() {+ val target = write("code.txt", "nothing to see")++ val result = editTool.edit(target.absolutePath, "absent", "present", replaceAll = false)++ assertFalse(result.success)+ assertEquals("nothing to see", target.readText())+ }++ @Test+ fun `edit rejects a blank oldString`() {+ val target = write("code.txt", "content")++ assertFalse(editTool.edit(target.absolutePath, " ", "x", replaceAll = false).success)+ }++ @Test+ fun `edit rejects a no-op replacement`() {+ val target = write("code.txt", "content")++ assertFalse(editTool.edit(target.absolutePath, "content", "content", replaceAll = false).success)+ }++ // ---- glob ----++ @Test+ fun `glob matches a suffix pattern recursively`() {+ write("a.kt", "")+ write("b.txt", "")+ write("sub/c.kt", "")++ val result = globTool.glob(workDir.absolutePath, "**/*.kt")++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("a.kt"))+ assertTrue(result.message, result.message.contains("c.kt"))+ assertFalse("matched a non-.kt file:\n${result.message}", result.message.contains("b.txt"))+ }++ @Test+ fun `glob single star does not cross directory boundaries`() {+ write("top.kt", "")+ write("sub/nested.kt", "")++ val result = globTool.glob(workDir.absolutePath, "*.kt")++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("top.kt"))+ assertFalse("'*' crossed a directory boundary:\n${result.message}", result.message.contains("nested.kt"))+ }++ @Test+ fun `glob supports brace alternation`() {+ write("a.kt", "")+ write("b.java", "")+ write("c.md", "")++ val result = globTool.glob(workDir.absolutePath, "*.{kt,java}")++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("a.kt"))+ assertTrue(result.message, result.message.contains("b.java"))+ assertFalse(result.message, result.message.contains("c.md"))+ }++ @Test+ fun `glob reports no matches rather than failing`() {+ write("a.kt", "")++ val result = globTool.glob(workDir.absolutePath, "*.rs")++ assertTrue("an empty result set is not an error: ${result.message}", result.success)+ assertTrue(result.message, result.message.contains("No files matching"))+ }++ @Test+ fun `glob rejects a blank pattern`() {+ assertFalse(globTool.glob(workDir.absolutePath, " ").success)+ }++ // ---- grep ----++ @Test+ fun `grep finds matching lines and names the file`() {+ write("notes.txt", "alpha\nbeta\ngamma\n")++ val result = grepTool.grep(workDir.absolutePath, "beta", include = null)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("beta"))+ assertTrue(result.message, result.message.contains("notes.txt"))+ }++ @Test+ fun `grep is case-insensitive`() {+ write("notes.txt", "Alpha\n")++ val result = grepTool.grep(workDir.absolutePath, "alpha", include = null)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("Alpha"))+ }++ @Test+ fun `grep honours the include filter`() {+ write("keep.kt", "needle\n")+ write("skip.txt", "needle\n")++ val result = grepTool.grep(workDir.absolutePath, "needle", include = "*.kt")++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("keep.kt"))+ assertFalse("include filter was ignored:\n${result.message}", result.message.contains("skip.txt"))+ }++ @Test+ fun `grep supports regex`() {+ write("nums.txt", "id=42\nid=abc\n")++ val result = grepTool.grep(workDir.absolutePath, "id=[0-9]+", include = null)++ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.contains("id=42"))+ assertFalse(result.message, result.message.contains("id=abc"))+ }++ @Test+ fun `grep rejects an invalid regex instead of throwing`() {+ write("a.txt", "x")++ val result = grepTool.grep(workDir.absolutePath, "([unclosed", include = null)++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("Invalid regex"))+ }++ @Test+ fun `grep rejects a blank pattern`() {+ assertFalse(grepTool.grep(workDir.absolutePath, "", include = null).success)+ }++ // ---- permission gating applies to the tools, not just the resolver ----++ @Test+ fun `file tools refuse shared storage without all-files-access`() {+ val shared = File(android.os.Environment.getExternalStorageDirectory(), "Download/x.txt")++ val read = fileTool.readFile(shared.absolutePath)++ assertFalse("shared storage must be gated: ${read.message}", read.success)+ assertEquals(ToolResult.ALL_FILES_ACCESS, read.needsPermission)+ }+}diff --git a/app/src/test/java/com/gotcha/tools/StorageToolTest.kt b/app/src/test/java/com/gotcha/tools/StorageToolTest.ktnew file mode 100644index 0000000..a228b70--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/StorageToolTest.kt@@ -0,0 +1,54 @@+package com.gotcha.tools++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++/**+ * `get_storage_info`. [StorageTool] takes no `Context`, so this is a plain JVM test —+ * it simply had no coverage before.+ */+class StorageToolTest {++ // ---- size formatting ----++ @Test+ fun `format uses the largest unit that fits`() {+ assertEquals("0.0 B", StorageTool.format(0))+ assertEquals("512.0 B", StorageTool.format(512))+ assertEquals("1.0 KB", StorageTool.format(1024))+ assertEquals("1.0 MB", StorageTool.format(1024L * 1024))+ assertEquals("1.0 GB", StorageTool.format(1024L * 1024 * 1024))+ assertEquals("1.0 TB", StorageTool.format(1024L * 1024 * 1024 * 1024))+ }++ @Test+ fun `format stops at terabytes rather than inventing a unit`() {+ val petabyte = 1024L * 1024 * 1024 * 1024 * 1024+ assertTrue(StorageTool.format(petabyte), StorageTool.format(petabyte).endsWith(" TB"))+ }++ @Test+ fun `format clamps negative sizes to zero`() {+ assertEquals("0.0 B", StorageTool.format(-1))+ }++ @Test+ fun `format rounds to one decimal place`() {+ assertEquals("1.5 KB", StorageTool.format(1536))+ }++ // ---- the tool itself ----++ @Test+ fun `getStorageInfo reports internal storage without throwing`() {+ // Reads the JVM host's /data via StatFs; the point is that the tool degrades to a+ // ToolResult either way rather than propagating an exception to the agent loop.+ val result = StorageTool().getStorageInfo()++ assertTrue(+ "expected a storage report or a clean error, got: ${result.message}",+ result.message.contains("Internal storage") || result.message.contains("Could not read storage info")+ )+ }+}diff --git a/app/src/test/java/com/gotcha/tools/SystemToolTest.kt b/app/src/test/java/com/gotcha/tools/SystemToolTest.ktnew file mode 100644index 0000000..4771139--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/SystemToolTest.kt@@ -0,0 +1,143 @@+package com.gotcha.tools++import android.content.Context+import android.content.Intent+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowApplication++/**+ * `set_brightness`, `get_battery_info`, `toggle_wifi` and `open_app`.+ *+ * The interesting assertions are on the *intents* these tools fire — `toggle_wifi` cannot+ * flip the radio on Android 10+ and must instead open the Wi-Fi panel, and `open_app` must+ * launch with FLAG_ACTIVITY_NEW_TASK or nothing happens from a service context.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [30, 34])+class SystemToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val tool = SystemTool(context)++ private fun lastIntent(): Intent? =+ ShadowApplication.getInstance().nextStartedActivity++ // ---- set_brightness ----++ @Test+ fun `set_brightness rejects out-of-range percentages before touching settings`() {+ assertFalse(tool.setBrightness(-1).success)+ assertFalse(tool.setBrightness(101).success)+ }++ @Test+ fun `set_brightness asks for WRITE_SETTINGS when it is not granted`() {+ // Robolectric's default for WRITE_SETTINGS varies by SDK level; only assert the+ // permission-needed path when the shadow actually reports it as ungranted.+ if (Settings.System.canWrite(context)) return++ val result = tool.setBrightness(50)++ assertFalse(result.message, result.success)+ assertEquals(ToolResult.WRITE_SETTINGS, result.needsPermission)+ }++ @Test+ fun `set_brightness writes the scaled value and switches to manual mode`() {+ if (!Settings.System.canWrite(context)) return++ val result = tool.setBrightness(50)++ assertTrue(result.message, result.success)+ assertEquals(+ Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL,+ Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE)+ )+ assertEquals(127, Settings.System.getInt(context.contentResolver, Settings.System.SCREEN_BRIGHTNESS))+ }++ // ---- get_battery_info ----++ @Test+ fun `get_battery_info reports a percentage without throwing`() {+ val result = tool.getBatteryInfo()++ assertTrue(result.message, result.success)+ assertTrue("expected a percentage in: ${result.message}", result.message.contains("%"))+ }++ // ---- toggle_wifi ----++ /**+ * Only the permissive branch is covered here.+ *+ * On a real Android 10+ device `setWifiEnabled` is a no-op returning false, and the tool+ * degrades to opening the Wi-Fi panel. Robolectric's ShadowWifiManager honours the call+ * unconditionally — `setChangeWifiStatePermission(false)` does not make it fail — so that+ * fallback cannot be reproduced faithfully at this tier. Asserting it against a permissive+ * shadow would give false confidence, so it stays on the manual checklist instead+ * (see the `toggle_wifi` entry in feature-test-coverage.json).+ */+ @Test+ fun `toggle_wifi reports the transition when the platform allows it`() {+ val wifi = context.getSystemService(Context.WIFI_SERVICE) as android.net.wifi.WifiManager+ wifi.isWifiEnabled = false++ val result = tool.toggleWifi(true)++ assertTrue(result.message, result.success)+ assertTrue("expected a state transition in: ${result.message}", result.message.contains("was off"))+ assertTrue(wifi.isWifiEnabled)+ }++ // ---- open_app ----++ @Test+ fun `open_app fails helpfully for an unknown package`() {+ val result = tool.openApp("com.example.definitely.not.installed")++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("No launchable app found"))+ assertTrue(+ "the message should point at a recovery path: ${result.message}",+ result.message.contains("list_installed_apps")+ )+ }++ @Test+ fun `open_app launches an installed package with NEW_TASK`() {+ val packageName = context.packageName+ val launchIntent = Intent(Intent.ACTION_MAIN)+ .addCategory(Intent.CATEGORY_LAUNCHER)+ .setPackage(packageName)+ shadowOf(context.packageManager).addActivityIfNotPresent(+ android.content.ComponentName(packageName, "$packageName.LaunchActivity")+ )+ shadowOf(context.packageManager).addIntentFilterForActivity(+ android.content.ComponentName(packageName, "$packageName.LaunchActivity"),+ android.content.IntentFilter(Intent.ACTION_MAIN).apply {+ addCategory(Intent.CATEGORY_LAUNCHER)+ }+ )++ val result = tool.openApp(packageName)++ assertTrue(result.message, result.success)+ val started = lastIntent()+ assertNotNull("no activity was started for $launchIntent", started)+ assertTrue(+ "launch intent needs NEW_TASK",+ started!!.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0+ )+ }+}diff --git a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.ktnew file mode 100644index 0000000..4af98c9--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt@@ -0,0 +1,139 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.testsupport.ShadowExternalStorageManager+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonPrimitive+import org.junit.After+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * One parameterised assertion across the majority of the catalogue: every tool with required+ * parameters must reject an empty argument object with a `missing()` error naming the parameter,+ * rather than crashing or — worse — proceeding with a default.+ *+ * This is safe to run for real. `ToolExecutor.dispatch` evaluates the `?: return missing(...)`+ * guards before touching any tool, so no side effect or network call happens on this path. Tools+ * *without* required parameters are deliberately excluded: `take_photo`, `check_root` and+ * `websearch` would do real work.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class ToolArgValidationTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private lateinit var executor: ToolExecutor++ @Before+ fun setUp() {+ // ToolExecutor's constructor initialises ConnectorRegistry, which builds+ // EncryptedSharedPreferences and therefore needs an AndroidKeyStore provider.+ FakeAndroidKeyStore.setUp()+ executor = ToolExecutor(context)+ }++ @After+ fun tearDown() {+ ShadowExternalStorageManager.resetGranted()+ }++ private fun requiredParams(name: String): List<String> =+ ToolDefinitions.all.first { it.function.name == name }+ .function.parameters["required"]?.jsonArray+ ?.map { it.jsonPrimitive.content } ?: emptyList()++ private val toolsWithRequiredParams: List<String>+ get() = ToolDefinitions.all+ .map { it.function.name }+ .filter { requiredParams(it).isNotEmpty() }+ .filterNot { it in EXCLUDED }++ @Test+ fun `there are enough tools with required parameters to make this test meaningful`() {+ assertTrue(+ "only ${toolsWithRequiredParams.size} tools have required parameters — did the " ++ "catalogue or the exclusion list change?",+ toolsWithRequiredParams.size > 40+ )+ }++ @Test+ fun `every tool with required parameters rejects empty arguments`() = runTest {+ val failures = mutableListOf<String>()++ toolsWithRequiredParams.forEach { name ->+ val result = executor.execute(name, JsonObject(emptyMap()), agent = AgentMode.OPERATOR, isSubAgent = true)++ if (result.success) {+ failures += "$name: succeeded with no arguments (required: ${requiredParams(name)})"+ }+ }++ assertTrue(failures.joinToString("\n"), failures.isEmpty())+ }++ @Test+ fun `the rejection names the missing parameter`() = runTest {+ val failures = mutableListOf<String>()++ toolsWithRequiredParams.filterNot { it in NOT_PARAMETER_NAMED }.forEach { name ->+ val result = executor.execute(name, JsonObject(emptyMap()), agent = AgentMode.OPERATOR, isSubAgent = true)+ val required = requiredParams(name)++ // The LLM has to know *which* argument it forgot; a bare "failed" is not actionable.+ if (required.none { result.message.contains(it) }) {+ failures += "$name: error names none of $required — got: ${result.message}"+ }+ }++ assertTrue(failures.joinToString("\n"), failures.isEmpty())+ }++ @Test+ fun `an unknown tool is rejected before dispatch`() = runTest {+ val result = executor.execute("definitely_not_a_tool", JsonObject(emptyMap()))++ assertTrue(result.message, !result.success)+ assertTrue(result.message, result.message.contains("Unknown tool"))+ }++ private companion object {+ /**+ * Tools whose required-parameter guard is not reached before a side effect, or whose+ * failure mode is environmental rather than a `missing()` error.+ *+ * - `task` / `navigate_app`: delegate to agent-loop callbacks, not a leaf tool.+ * - `question`: blocks awaiting a UI answer.+ * - `sleep`: `duration_seconds` has a default, so an empty call really does sleep.+ * - `ask_final_answer`: a control-flow signal that returns whatever answer it was+ * given, so an empty one legitimately succeeds rather than erroring.+ */+ val EXCLUDED = setOf("task", "navigate_app", "question", "sleep", "ask_final_answer")++ /**+ * These still reject an empty call — asserted above — but the message names a+ * precondition rather than the parameter, which is the more useful thing to tell the+ * model:+ *+ * - the connector-backed tools report "X is not connected" before looking at args;+ * - `set_timer` reports the domain rule ("must be at least 1 second").+ */+ val NOT_PARAMETER_NAMED = setOf(+ "create_task",+ "notion_read_page",+ "notion_create_page",+ "notion_append_to_page",+ "set_timer"+ )+ }+}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex d6f43f1..5d77414 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -8,51 +8,71 @@},{"tool": "get_storage_info",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask 'how much storage do I have left?'; confirm the reported free/total roughly matches Settings → Storage."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.StorageToolTest"+ ],+ "notes": "size formatting across every unit and the partition read"},{"tool": "get_battery_info",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask 'what is my battery level?'; confirm the percentage and charging state match the status bar."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.SystemToolTest"+ ],+ "notes": "reports a percentage without throwing"},{"tool": "list_files",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to list files in the working directory; confirm the listing matches a file manager."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest"+ ],+ "notes": "flat and recursive listings"},{"tool": "read_file",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Write a short text file, then ask the agent to read it back; confirm the contents match, including with an offset/limit."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest",+ "com.gotcha.tools.FileResolverTest"+ ],+ "notes": "offset/limit, missing paths, and the All-files-access gate"},{"tool": "write_file",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to write a file to the working directory; confirm it appears on disk with the requested contents."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest",+ "com.gotcha.tools.FileResolverTest",+ "com.gotcha.agent.AgentLoopTest"+ ],+ "notes": "create, append, overwrite, parent-dir creation; also driven end-to-end through the agent loop"},{"tool": "open_app",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask 'open Settings'; confirm the Settings app comes to the foreground."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.SystemToolTest"+ ],+ "notes": "launch intent flags and the unknown-package message"},{"tool": "set_brightness",- "tier": "MANUAL_ONLY",- "reason": "C",- "manualSteps": "Ask the agent to set brightness to 20%, then 80%; confirm the screen visibly changes and Settings agrees."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.SystemToolTest"+ ],+ "notes": "range validation, value scaling, WRITE_SETTINGS gate"},{"tool": "toggle_wifi","tier": "MANUAL_ONLY",- "reason": "C",- "manualSteps": "Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling)."+ "reason": "The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier.",+ "manualSteps": "Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio.",+ "tests": [+ "com.gotcha.tools.SystemToolTest"+ ]},{"tool": "set_wallpaper",@@ -195,21 +215,27 @@},{"tool": "set_volume",- "tier": "MANUAL_ONLY",- "reason": "C",- "manualSteps": "Ask the agent to set media volume to 50%; confirm the volume HUD and Settings agree."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.DeviceToolTest"+ ],+ "notes": "percentage-to-stream scaling, aliases, range and stream validation"},{"tool": "get_volume",- "tier": "MANUAL_ONLY",- "reason": "C",- "manualSteps": "Ask 'how loud is my media volume?'; confirm the answer matches the volume slider."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.DeviceToolTest"+ ],+ "notes": "single and all-stream reporting"},{"tool": "set_ringer_mode",- "tier": "MANUAL_ONLY",- "reason": "C",- "manualSteps": "Ask the agent to switch to vibrate, then back to normal; confirm the status-bar icon changes."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.DeviceToolTest"+ ],+ "notes": "normal/vibrate/silent plus the Do-Not-Disturb access gate"},{"tool": "vibrate",@@ -231,15 +257,20 @@},{"tool": "list_installed_apps",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask 'what apps do I have installed?'; spot-check a few entries against the launcher."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.AppsToolTest"+ ],+ "notes": "listing, system-app marking, counts, search filtering"},{"tool": "uninstall_app","tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Install a throwaway app, ask the agent to uninstall it; confirm the confirmation prompt appears and the app is removed."+ "reason": "AgentLoopTest covers the CONFIRM_UNINSTALL marker and both sides of the confirmation gate, but the actual package removal is a system dialog that cannot be automated.",+ "manualSteps": "Install a throwaway app, ask the agent to uninstall it; confirm the confirmation prompt appears, then that the system uninstall dialog opens and the app is removed.",+ "tests": [+ "com.gotcha.agent.AgentLoopTest"+ ]},{"tool": "get_app_usage",@@ -255,15 +286,19 @@},{"tool": "get_clipboard",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Copy some text in another app, then ask 'what's on my clipboard?'; confirm it matches (Android 10+ needs the accessibility fallback)."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ClipboardToolTest"+ ],+ "notes": "read plus the API 34 accessibility-cache fallback, across API 30/33/34"},{"tool": "set_clipboard",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to copy a phrase, then paste it manually somewhere; confirm the phrase pastes."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ClipboardToolTest"+ ],+ "notes": "write-through to the platform clipboard and the accessibility cache"},{"tool": "take_photo",@@ -333,21 +368,27 @@},{"tool": "edit",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to change one line in a text file; confirm only that line changed and a non-unique oldString is rejected."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest"+ ],+ "notes": "unique match, replaceAll, no-match and blank-argument rejection"},{"tool": "glob",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to find all *.txt files under a directory; confirm the result matches `find`."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest"+ ],+ "notes": "`*` vs `**`, brace alternation, empty result sets"},{"tool": "grep",- "tier": "MANUAL_ONLY",- "reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.",- "manualSteps": "Ask the agent to search a directory for a phrase; confirm the matching files/lines are right."+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.FileToolsTest"+ ],+ "notes": "regex and literal search, case-insensitivity, include filter, invalid patterns"},{"tool": "websearch",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex 4a813e6..282c307 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 19 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 0 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 16 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). |-| `MANUAL_ONLY` | 80 | No automated test — verified by hand, see the checklist below. |+| `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. || **Total** | **99** | |-**19 of 99** tools are covered by an automated test; the remaining 80 are manual-QA-only with a recorded reason.+**35 of 99** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -32,7 +32,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `long_press` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `long_press_index` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `navigate_app` | `MANUAL_ONLY` | Nested navigator agent loop over a live accessibility service and a live LLM connection. |-| `open_app` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `open_app` | `ROBOLECTRIC` | `SystemToolTest` — launch intent flags and the unknown-package message || `press_key` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `read_screen` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). || `read_screen_raw` | `MANUAL_ONLY` | Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup). |@@ -57,7 +57,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `disable_camera` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `dismiss_notifications` | `MANUAL_ONLY` | Needs NotificationListenerService bound with the user's explicit grant; not bindable from a test host. || `dismiss_timer` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `edit` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `edit` | `ROBOLECTRIC` | `FileToolsTest` — unique match, replaceAll, no-match and blank-argument rejection || `edit_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `edit_calendar_event` | `UNIT` | `CalendarToolsTest` — connector path only; the on-device CalendarProvider path is manual || `hide_overlay` | `MANUAL_ONLY` | Draws a real SYSTEM_ALERT_WINDOW; needs the 'Display over other apps' grant and a visible screen to verify. |@@ -73,13 +73,13 @@ Every tool the assistant can call is listed below, together with how it is verif| `send_email` | `UNIT` | `EmailToolsTest`, `MimeMessageBuilderTest` — confirmation flow, recipient handling, MIME construction with attachments || `send_sms` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `set_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `set_brightness` | `MANUAL_ONLY` | C |-| `set_clipboard` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `set_brightness` | `ROBOLECTRIC` | `SystemToolTest` — range validation, value scaling, WRITE_SETTINGS gate |+| `set_clipboard` | `ROBOLECTRIC` | `ClipboardToolTest` — write-through to the platform clipboard and the accessibility cache || `set_dnd` | `MANUAL_ONLY` | C || `set_password_policy` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. |-| `set_ringer_mode` | `MANUAL_ONLY` | C |+| `set_ringer_mode` | `ROBOLECTRIC` | `DeviceToolTest` — normal/vibrate/silent plus the Do-Not-Disturb access gate || `set_timer` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `set_volume` | `MANUAL_ONLY` | C |+| `set_volume` | `ROBOLECTRIC` | `DeviceToolTest` — percentage-to-stream scaling, aliases, range and stream validation || `set_wallpaper` | `MANUAL_ONLY` | C || `show_overlay` | `MANUAL_ONLY` | Draws a real SYSTEM_ALERT_WINDOW; needs the 'Display over other apps' grant and a visible screen to verify. || `snooze_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |@@ -87,10 +87,10 @@ Every tool the assistant can call is listed below, together with how it is verif| `stop_audio_recording` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `take_photo` | `MANUAL_ONLY` | Needs a real camera; CameraX has no usable emulator fake for the capture callback. || `toggle_torch` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |-| `toggle_wifi` | `MANUAL_ONLY` | C |-| `uninstall_app` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `toggle_wifi` | `MANUAL_ONLY` | `SystemToolTest` — The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier. |+| `uninstall_app` | `MANUAL_ONLY` | `AgentLoopTest` — AgentLoopTest covers the CONFIRM_UNINSTALL marker and both sides of the confirmation gate, but the actual package removal is a system dialog that cannot be automated. || `vibrate` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |-| `write_file` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `write_file` | `ROBOLECTRIC` | `FileToolsTest`, `FileResolverTest`, `AgentLoopTest` — create, append, overwrite, parent-dir creation; also driven end-to-end through the agent loop || `write_secure_settings` | `MANUAL_ONLY` | Requires WRITE_SECURE_SETTINGS, granted only via adb — and it mutates global device state. |## Info tools (read-only)@@ -103,22 +103,22 @@ Every tool the assistant can call is listed below, together with how it is verif| `find_contact` | `MANUAL_ONLY` | R || `get_app_usage` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `get_audio_recording_status` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. |-| `get_battery_info` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `get_clipboard` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `get_battery_info` | `ROBOLECTRIC` | `SystemToolTest` — reports a percentage without throwing |+| `get_clipboard` | `ROBOLECTRIC` | `ClipboardToolTest` — read plus the API 34 accessibility-cache fallback, across API 30/33/34 || `get_data_usage` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `get_health_records` | `UNIT` | `HealthFormatTest`, `HealthPermissionScopeTest` — record-type formatting and per-type permission scoping || `get_health_summary` | `UNIT` | `HealthFormatTest`, `HealthPermissionScopeTest` — summary formatting and the permission scope requested || `get_location` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `get_now_playing` | `UNIT` | `MediaSelectionTest` — active-session selection across paused/playing/stopped sessions |-| `get_storage_info` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `get_volume` | `MANUAL_ONLY` | C |-| `glob` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `grep` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `get_storage_info` | `ROBOLECTRIC` | `StorageToolTest` — size formatting across every unit and the partition read |+| `get_volume` | `ROBOLECTRIC` | `DeviceToolTest` — single and all-stream reporting |+| `glob` | `ROBOLECTRIC` | `FileToolsTest` — `*` vs `**`, brace alternation, empty result sets |+| `grep` | `ROBOLECTRIC` | `FileToolsTest` — regex and literal search, case-insensitivity, include filter, invalid patterns || `list_alarms` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `list_calendar_events` | `UNIT` | `CalendarToolsTest`, `CalendarWindowTest` — connector path (Google/Microsoft) only; the on-device CalendarProvider path is manual || `list_emails` | `UNIT` | `EmailToolsTest` — backend routing, unread filter, result limits |-| `list_files` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |-| `list_installed_apps` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `list_files` | `ROBOLECTRIC` | `FileToolsTest` — flat and recursive listings |+| `list_installed_apps` | `ROBOLECTRIC` | `AppsToolTest` — listing, system-app marking, counts, search filtering || `list_tasks` | `MANUAL_ONLY` | Routed to a live Microsoft Graph account; only the underlying GraphApi has JVM coverage today. || `list_timers` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `notion_read_page` | `UNIT` | `NotionToolsTest`, `NotionBlockRendererTest` — page fetch plus block-to-markdown rendering |@@ -126,7 +126,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `question` | `MANUAL_ONLY` | Pure UI round-trip: the tool blocks until the user answers a prompt rendered in the chat surface. || `read_call_log` | `MANUAL_ONLY` | R || `read_email` | `UNIT` | `EmailToolsTest`, `MailBodyExtractorTest` — id routing plus multipart/HTML body extraction |-| `read_file` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |+| `read_file` | `ROBOLECTRIC` | `FileToolsTest`, `FileResolverTest` — offset/limit, missing paths, and the All-files-access gate || `read_notifications` | `MANUAL_ONLY` | Needs NotificationListenerService bound with the user's explicit grant; not bindable from a test host. || `read_recent_sms` | `MANUAL_ONLY` | R || `search_skills` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |@@ -165,8 +165,6 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Needs NotificationListenerService bound with the user's explicit grant; not bindable from a test host.- [ ] **`dismiss_timer`** — With a timer ringing, ask the agent to dismiss it; confirm it stops.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`edit`** — Ask the agent to change one line in a text file; confirm only that line changed and a non-unique oldString is rejected.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`edit_alarm`** — Ask the agent to move an existing alarm 30 minutes later; confirm the Clock app shows the new time.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`find_contact`** — Ask 'what's <a saved contact>'s number?'; confirm it matches the Contacts app.@@ -175,34 +173,18 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`get_audio_recording_status`** — While recording, ask 'am I still recording?'; confirm the elapsed time is reported.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.-- [ ] **`get_battery_info`** — Ask 'what is my battery level?'; confirm the percentage and charging state match the status bar.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`get_clipboard`** — Copy some text in another app, then ask 'what's on my clipboard?'; confirm it matches (Android 10+ needs the accessibility fallback).- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`get_data_usage`** — Grant Usage Access, then ask 'how much data has Chrome used?'; compare with Settings → Network → Data usage.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`get_location`** — Outdoors or with a mock location set, ask 'where am I?'; confirm the coordinates/address are plausible.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.-- [ ] **`get_storage_info`** — Ask 'how much storage do I have left?'; confirm the reported free/total roughly matches Settings → Storage.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`get_volume`** — Ask 'how loud is my media volume?'; confirm the answer matches the volume slider.- <br>_Why not automated:_ C-- [ ] **`glob`** — Ask the agent to find all *.txt files under a directory; confirm the result matches `find`.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`global_action`** — Ask the agent to open the notification shade, then Recents; confirm both happen.<br>_Why not automated:_ Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup).-- [ ] **`grep`** — Ask the agent to search a directory for a phrase; confirm the matching files/lines are right.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`hide_overlay`** — With an overlay showing, ask the agent to hide it; confirm the card disappears.<br>_Why not automated:_ Draws a real SYSTEM_ALERT_WINDOW; needs the 'Display over other apps' grant and a visible screen to verify.- [ ] **`input_text`** — Focus a text field and ask the agent to type a phrase; confirm the text lands in the field.<br>_Why not automated:_ Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup).- [ ] **`list_alarms`** — With at least one alarm set, ask 'what alarms do I have?'; confirm the list matches the Clock app.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`list_files`** — Ask the agent to list files in the working directory; confirm the listing matches a file manager.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`list_installed_apps`** — Ask 'what apps do I have installed?'; spot-check a few entries against the launcher.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`list_tasks`** — With Microsoft connected, ask 'what tasks do I have?'; confirm the list matches To Do.<br>_Why not automated:_ Routed to a live Microsoft Graph account; only the underlying GraphApi has JVM coverage today.- [ ] **`list_timers`** — With a timer running, ask 'what timers are running?'; confirm the remaining time is right.@@ -215,8 +197,6 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Depends on a live GotchaAccessibilityService bound to a real foreground app; the service cannot reliably self-bind under instrumentation (see AccessibilityServiceTest's @Ignore writeup).- [ ] **`navigate_app`** — Ask the agent to complete a multi-screen task in another app; confirm it navigates there and reports the outcome.<br>_Why not automated:_ Nested navigator agent loop over a live accessibility service and a live LLM connection.-- [ ] **`open_app`** — Ask 'open Settings'; confirm the Settings app comes to the foreground.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`pause_audio_recording`** — Pause an in-progress recording; confirm the elapsed time stops advancing.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.- [ ] **`press_key`** — Ask the agent to press Back; confirm the app navigates back.@@ -225,8 +205,6 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Pure UI round-trip: the tool blocks until the user answers a prompt rendered in the chat surface.- [ ] **`read_call_log`** — Make a call, then ask 'who did I last call?'; confirm the entry matches the Phone app's log.<br>_Why not automated:_ R-- [ ] **`read_file`** — Write a short text file, then ask the agent to read it back; confirm the contents match, including with an offset/limit.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`read_notifications`** — Grant notification access, generate a notification, then ask 'what notifications do I have?'; confirm it is listed.<br>_Why not automated:_ Needs NotificationListenerService bound with the user's explicit grant; not bindable from a test host.- [ ] **`read_recent_sms`** — Ask 'what was my last text?'; confirm it matches the SMS app.@@ -245,20 +223,12 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.- [ ] **`set_alarm`** — Ask the agent to set an alarm for 5 minutes' time; confirm it appears in the Clock app and fires.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`set_brightness`** — Ask the agent to set brightness to 20%, then 80%; confirm the screen visibly changes and Settings agrees.- <br>_Why not automated:_ C-- [ ] **`set_clipboard`** — Ask the agent to copy a phrase, then paste it manually somewhere; confirm the phrase pastes.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`set_dnd`** — Ask the agent to turn Do Not Disturb on; confirm the DND icon appears (grant DND access first if prompted).<br>_Why not automated:_ C- [ ] **`set_password_policy`** — As device admin, ask the agent to require a 6-character password; confirm Settings enforces the new minimum.<br>_Why not automated:_ Needs an active Device Admin registration, which cannot be granted non-interactively.-- [ ] **`set_ringer_mode`** — Ask the agent to switch to vibrate, then back to normal; confirm the status-bar icon changes.- <br>_Why not automated:_ C- [ ] **`set_timer`** — Ask the agent to set a 1-minute timer; confirm it appears in the Clock app and fires.<br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.-- [ ] **`set_volume`** — Ask the agent to set media volume to 50%; confirm the volume HUD and Settings agree.- <br>_Why not automated:_ C- [ ] **`set_wallpaper`** — Ask the agent to set the wallpaper from a photo; confirm the home screen background changes.<br>_Why not automated:_ C- [ ] **`show_alarms`** — Ask the agent to show your alarms; confirm the Clock app opens on the alarms tab.@@ -287,15 +257,13 @@ Run through this before a release. Each item is a tool with no automated coverag<br>_Why not automated:_ Pure UI round-trip: writes the visible todo list in the chat surface.- [ ] **`toggle_torch`** — Ask the agent to turn the torch on, then off; confirm the flash physically lights up.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.-- [ ] **`toggle_wifi`** — Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling).- <br>_Why not automated:_ C-- [ ] **`uninstall_app`** — Install a throwaway app, ask the agent to uninstall it; confirm the confirmation prompt appears and the app is removed.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.+- [ ] **`toggle_wifi`** — Ask the agent to turn Wi-Fi off; confirm the Wi-Fi settings panel opens (Android 10+ forbids programmatic toggling) rather than the agent claiming it toggled the radio.+ <br>_Why not automated:_ The permissive branch is covered by SystemToolTest, but Android 10+ makes setWifiEnabled a no-op and Robolectric's shadow honours it unconditionally, so the panel-fallback branch that actually runs on-device cannot be reproduced at that tier.+- [ ] **`uninstall_app`** — Install a throwaway app, ask the agent to uninstall it; confirm the confirmation prompt appears, then that the system uninstall dialog opens and the app is removed.+ <br>_Why not automated:_ AgentLoopTest covers the CONFIRM_UNINSTALL marker and both sides of the confirmation gate, but the actual package removal is a system dialog that cannot be automated.- [ ] **`vibrate`** — Ask the agent to vibrate the phone; confirm you feel it.<br>_Why not automated:_ Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio.- [ ] **`websearch`** — Ask a question that needs current information; confirm the agent cites plausible, recent results.<br>_Why not automated:_ Performs real network I/O against a search provider; exercising it in CI would make the suite non-hermetic.-- [ ] **`write_file`** — Ask the agent to write a file to the working directory; confirm it appears on disk with the requested contents.- <br>_Why not automated:_ Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.- [ ] **`write_secure_settings`** — After `adb shell pm grant com.gotcha android.permission.WRITE_SECURE_SETTINGS`, ask the agent to change a secure setting; confirm with `adb shell settings get`.<br>_Why not automated:_ Requires WRITE_SECURE_SETTINGS, granted only via adb — and it mutates global device state.