Skip to content

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

test(tools): add catalogue-wide contract tests

Durganshu26d00e3ca015
diff --git a/app/src/test/java/com/gotcha/testsupport/RepoPaths.kt b/app/src/test/java/com/gotcha/testsupport/RepoPaths.kt
new file mode 100644
index 0000000..f4c390f
--- /dev/null
+++ b/app/src/test/java/com/gotcha/testsupport/RepoPaths.kt
@@ -0,0 +1,31 @@
+package com.gotcha.testsupport
+
+import java.io.File
+
+/**
+ * Locating repo files from a unit test.
+ *
+ * Unit tests run with the working directory at the `app/` module dir, so paths are resolved by
+ * walking up until the directory holding `settings.gradle.kts` is found rather than hardcoding
+ * `../`. `TerminalToolTest` already establishes that filesystem access from unit tests is fine.
+ */
+object RepoPaths {
+
+ val root: File by lazy {
+ var dir: File? = File(System.getProperty("user.dir")).absoluteFile
+ while (dir != null) {
+ if (File(dir, "settings.gradle.kts").isFile) return@lazy dir
+ dir = dir.parentFile
+ }
+ error("could not locate the repo root (no settings.gradle.kts above ${System.getProperty("user.dir")})")
+ }
+
+ fun file(relativePath: String): File = File(root, relativePath)
+
+ /** Reads a main-source file under `app/src/main/java/`, failing loudly if it moved. */
+ fun mainSource(relativePath: String): String {
+ val f = file("app/src/main/java/$relativePath")
+ check(f.isFile) { "expected main source at ${f.path}; did the file move?" }
+ return f.readText()
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/FeatureCoverageManifestTest.kt b/app/src/test/java/com/gotcha/tools/FeatureCoverageManifestTest.kt
index 64e1166..0927364 100644
--- a/app/src/test/java/com/gotcha/tools/FeatureCoverageManifestTest.kt
+++ b/app/src/test/java/com/gotcha/tools/FeatureCoverageManifestTest.kt
@@ -1,5 +1,6 @@
package com.gotcha.tools
+import com.gotcha.testsupport.RepoPaths
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.junit.Assert.assertEquals
@@ -103,7 +104,7 @@ class FeatureCoverageManifestTest {
@Test
fun instrumentedEntriesNameExistingSourceFiles() {
- val androidTestRoot = File(repoRoot(), "app/src/androidTest/java")
+ val androidTestRoot = RepoPaths.file("app/src/androidTest/java")
val problems = manifest.tools.filter { it.tier == "INSTRUMENTED" }.mapNotNull { entry ->
when {
entry.tests.isEmpty() -> "${entry.tool}: tier INSTRUMENTED but no test classes listed"
@@ -134,7 +135,7 @@ class FeatureCoverageManifestTest {
@Test
fun generatedDocMatchesCommittedCopy() {
val expected = renderMarkdown(manifest)
- val doc = File(repoRoot(), DOC_PATH)
+ val doc = RepoPaths.file(DOC_PATH)
if (System.getProperty(UPDATE_PROPERTY) == "true") {
doc.parentFile.mkdirs()
@@ -259,18 +260,5 @@ class FeatureCoverageManifestTest {
Category.BACKGROUND to "Background tools (change device or account state)",
Category.INFO to "Info tools (read-only)"
)
-
- /**
- * Unit tests run with the working directory at the `app/` module dir, so walk up
- * until the dir holding `settings.gradle.kts` is found rather than hardcoding `../`.
- */
- fun repoRoot(): File {
- var dir: File? = File(System.getProperty("user.dir")).absoluteFile
- while (dir != null) {
- if (File(dir, "settings.gradle.kts").isFile) return dir
- dir = dir.parentFile
- }
- error("could not locate the repo root (no settings.gradle.kts above ${System.getProperty("user.dir")})")
- }
}
}
diff --git a/app/src/test/java/com/gotcha/tools/ToolDefinitionsSchemaTest.kt b/app/src/test/java/com/gotcha/tools/ToolDefinitionsSchemaTest.kt
index 7537f2c..d972971 100644
--- a/app/src/test/java/com/gotcha/tools/ToolDefinitionsSchemaTest.kt
+++ b/app/src/test/java/com/gotcha/tools/ToolDefinitionsSchemaTest.kt
@@ -64,6 +64,50 @@ class ToolDefinitionsSchemaTest {
}
}
+ /**
+ * A parameter with no `type` or no `description` is the most common cause of the model
+ * passing the wrong shape — the schema still validates, so nothing else catches it.
+ */
+ @Test
+ fun `every parameter declares a type and a description`() {
+ ToolDefinitions.all.forEach { def ->
+ def.function.parameters["properties"]!!.jsonObject.forEach { (param, spec) ->
+ val obj = spec.jsonObject
+ assertTrue(
+ "'${def.function.name}.$param' has no type",
+ obj["type"]?.jsonPrimitive?.content?.isNotBlank() == true
+ )
+ assertTrue(
+ "'${def.function.name}.$param' has no description",
+ obj["description"]?.jsonPrimitive?.content?.isNotBlank() == true
+ )
+ }
+ }
+ }
+
+ @Test
+ fun `required lists have no duplicates`() {
+ ToolDefinitions.all.forEach { def ->
+ val required = def.function.parameters["required"]?.jsonArray
+ ?.map { it.jsonPrimitive.content } ?: emptyList()
+ assertEquals(
+ "'${def.function.name}' lists a required parameter twice: $required",
+ required.size,
+ required.toSet().size
+ )
+ }
+ }
+
+ @Test
+ fun `parameter names follow the snake_case convention`() {
+ val pattern = Regex("^[a-z][a-zA-Z0-9_]*$")
+ ToolDefinitions.all.forEach { def ->
+ def.function.parameters["properties"]!!.jsonObject.keys.forEach { param ->
+ assertTrue("'${def.function.name}.$param' is not a valid parameter name", pattern.matches(param))
+ }
+ }
+ }
+
@Test
fun `tool names follow the snake_case convention`() {
val pattern = Regex("^[a-z][a-z0-9_]*$")
diff --git a/app/src/test/java/com/gotcha/tools/ToolDispatchCompletenessTest.kt b/app/src/test/java/com/gotcha/tools/ToolDispatchCompletenessTest.kt
new file mode 100644
index 0000000..adc6da4
--- /dev/null
+++ b/app/src/test/java/com/gotcha/tools/ToolDispatchCompletenessTest.kt
@@ -0,0 +1,131 @@
+package com.gotcha.tools
+
+import com.gotcha.testsupport.RepoPaths
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Every tool the LLM can call must be reachable by an executor.
+ *
+ * Catches the classic bug this catalogue invites: a schema is added to [ToolDefinitions], the
+ * executor is never wired, and the failure only surfaces at runtime as the LLM getting back
+ * `Tool 'x' has no executor.` from [ToolExecutor]'s `else` branch.
+ *
+ * Verified by **statically scanning source**, not by calling `execute()` in a loop: tools with no
+ * required parameters (`get_battery_info`, `check_root`, `take_photo`, `websearch`) would perform
+ * real side effects or network I/O. See `ToolArgValidationTest` for the dynamic half, which is
+ * safe because dispatch returns on the missing-argument check before touching anything.
+ */
+class ToolDispatchCompletenessTest {
+
+ @Test
+ fun everyToolHasAnExecutor() {
+ val handled = dispatchCaseLabels() + connectorOwnedToolNames()
+ val unreachable = ToolDefinitions.all.map { it.function.name }.filterNot { it in handled }
+
+ assertTrue(
+ "tool(s) declared in ToolDefinitions.all with no executor — calling them at runtime " +
+ "returns \"Tool 'x' has no executor.\": ${unreachable.sorted()}",
+ unreachable.isEmpty()
+ )
+ }
+
+ @Test
+ fun executorCaseLabelsAllHaveASchema() {
+ val declared = ToolDefinitions.all.map { it.function.name }.toSet()
+ val orphans = dispatchCaseLabels() - declared - INTERNAL_ONLY_LABELS
+
+ assertTrue(
+ "ToolExecutor.dispatch handles name(s) that no schema declares, so the LLM can never " +
+ "call them: ${orphans.sorted()}. Either add a schema, delete the branch, or add " +
+ "the name to INTERNAL_ONLY_LABELS with a note.",
+ orphans.isEmpty()
+ )
+ }
+
+ @Test
+ fun connectorRouterToolNamesAreAllDeclared() {
+ val declared = ToolDefinitions.all.map { it.function.name }.toSet()
+ val orphans = connectorOwnedToolNames() - declared
+
+ assertTrue(
+ "connector router(s) claim tool name(s) that no schema declares: ${orphans.sorted()}",
+ orphans.isEmpty()
+ )
+ }
+
+ @Test
+ fun theSourceScanFoundAPlausibleNumberOfBranches() {
+ // Guards the scan itself: if dispatch is refactored so the regex stops matching, the
+ // completeness assertions above would silently pass by matching nothing.
+ val labels = dispatchCaseLabels()
+ assertTrue(
+ "the ToolExecutor.dispatch source scan found only ${labels.size} case labels, which " +
+ "means the scan is broken rather than that dispatch shrank that far",
+ labels.size > MIN_EXPECTED_DISPATCH_LABELS
+ )
+ val routerNames = connectorOwnedToolNames()
+ assertTrue(
+ "the connector-router source scan found only ${routerNames.size} tool names",
+ routerNames.size > MIN_EXPECTED_ROUTER_NAMES
+ )
+ }
+
+ // ---- source scanning ----
+
+ /** String case labels inside `ToolExecutor.dispatch`'s `when (name)`, nested `when`s excluded. */
+ private fun dispatchCaseLabels(): Set<String> {
+ val source = RepoPaths.mainSource("com/gotcha/tools/ToolExecutor.kt")
+ val start = source.indexOf(DISPATCH_SIGNATURE)
+ check(start >= 0) { "could not find dispatch() in ToolExecutor.kt — did its signature change?" }
+ val end = source.indexOf(DISPATCH_FALLBACK, start)
+ check(end > start) { "could not find dispatch()'s else branch — did the fallback message change?" }
+
+ return source.substring(start, end)
+ .lineSequence()
+ // Top-level branches of `when (name)` sit at a fixed indent; nested `when`s are deeper.
+ .filter { it.startsWith(CASE_INDENT) && !it.startsWith("$CASE_INDENT ") }
+ .flatMap { CASE_LABEL.findAll(it) }
+ .map { it.groupValues[1] }
+ .toSet()
+ }
+
+ /** Tool names claimed by the connector routers `ConnectorRegistry.toolHandler` consults. */
+ private fun connectorOwnedToolNames(): Set<String> =
+ ROUTER_SOURCES.flatMap { path ->
+ val source = RepoPaths.mainSource(path)
+ val start = source.indexOf(TOOL_NAMES_DECLARATION)
+ check(start >= 0) { "no `override val toolNames` in $path" }
+ val block = source.substring(start, minOf(source.length, start + TOOL_NAMES_SCAN_WINDOW))
+ // Stop at the end of the setOf(...) initialiser, i.e. the first blank line after it.
+ QUOTED.findAll(block.substringBefore("\n\n")).map { it.groupValues[1] }
+ }.toSet()
+
+ private companion object {
+ const val DISPATCH_SIGNATURE = "private suspend fun dispatch(name: String"
+ const val DISPATCH_FALLBACK = "has no executor."
+ const val TOOL_NAMES_DECLARATION = "override val toolNames"
+ const val TOOL_NAMES_SCAN_WINDOW = 400
+ const val CASE_INDENT = " \""
+
+ val CASE_LABEL = Regex("\"([a-z0-9_]+)\"\\s*(?:,|->)")
+ val QUOTED = Regex("\"([a-z0-9_]+)\"")
+
+ /** Mirrors the routers in `ConnectorRegistry.init`. */
+ val ROUTER_SOURCES = listOf(
+ "com/gotcha/connectors/mail/EmailTools.kt",
+ "com/gotcha/connectors/microsoft/TaskTools.kt",
+ "com/gotcha/connectors/calendar/CalendarTools.kt",
+ "com/gotcha/connectors/notion/NotionTools.kt"
+ )
+
+ /**
+ * Executor branches deliberately not exposed as LLM-callable schemas.
+ * `read_image` is invoked internally when a tool result carries an image.
+ */
+ val INTERNAL_ONLY_LABELS = setOf("read_image")
+
+ const val MIN_EXPECTED_DISPATCH_LABELS = 70
+ const val MIN_EXPECTED_ROUTER_NAMES = 12
+ }
+}
diff --git a/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt
index f73bbcb..c325d23 100644
--- a/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt
+++ b/app/src/test/java/com/gotcha/tools/ToolRegistryTest.kt
@@ -43,11 +43,55 @@ class ToolRegistryTest {
}
}
+ @Test
+ fun `destructive tools are all registered tools`() {
+ ToolRegistry.destructiveTools.forEach { name ->
+ assertTrue("'$name' marked destructive but not registered", ToolRegistry.contains(name))
+ }
+ }
+
@Test
fun `unknown tools are rejected`() {
assertTrue(!ToolRegistry.contains("install_apk"))
}
+ /**
+ * A tool exposed on no agent surface is dead weight: it is catalogued, dispatchable and
+ * documented, but no agent is ever offered it, so the model cannot call it.
+ */
+ @Test
+ fun `every tool is reachable from at least one agent surface`() {
+ val reachable = (
+ ToolRegistry.toolsForAgent(AgentMode.MONITOR) +
+ ToolRegistry.toolsForAgent(AgentMode.OPERATOR) +
+ ToolRegistry.toolsForSubAgent() +
+ ToolRegistry.toolsForNavigator()
+ ).map { it.function.name }.toSet()
+
+ val orphans = ToolDefinitions.all.map { it.function.name }.filterNot { it in reachable }
+ assertTrue(
+ "tool(s) offered to no agent surface (Monitor, Operator, sub-agent or navigator), " +
+ "so the model can never call them: ${orphans.sorted()}",
+ orphans.isEmpty()
+ )
+ }
+
+ @Test
+ fun `every agent surface offers only catalogued tools`() {
+ val catalogued = ToolDefinitions.all.map { it.function.name }.toSet()
+ val surfaces = mapOf(
+ "MONITOR" to ToolRegistry.toolsForAgent(AgentMode.MONITOR),
+ "OPERATOR" to ToolRegistry.toolsForAgent(AgentMode.OPERATOR),
+ "sub-agent" to ToolRegistry.toolsForSubAgent(),
+ "navigator" to ToolRegistry.toolsForNavigator()
+ )
+ surfaces.forEach { (surface, defs) ->
+ assertTrue("$surface was offered no tools at all", defs.isNotEmpty())
+ val unknown = defs.map { it.function.name }.filterNot { it in catalogued }
+ assertTrue("$surface offers uncatalogued tool(s): ${unknown.sorted()}", unknown.isEmpty())
+ }
+ }
+
/**
* Connector routers claim tool names by string. A name that is not in the
* catalog would make the tool invisible to the model — and a typo would fail