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.
fix: gate debug logging behind BuildConfig.DEBUG via GotchaLog
Jalebi43d4f5a29f86
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 7260856..e969df7 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -392,6 +392,7 @@ dependencies {// Static analysisdetektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.6")+ detektPlugins(project(":detekt-rules"))// DebugdebugImplementation("androidx.compose.ui:ui-tooling")diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex c641401..ea65043 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -75,6 +75,7 @@ import com.gotcha.ui.tour.TourNavigationimport com.gotcha.ui.tour.TourOverlayimport com.gotcha.ui.tour.TourPlaceimport com.gotcha.ui.tour.rememberTourHost+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext@@ -158,14 +159,13 @@ class MainActivity : ComponentActivity() {/** MediaProjection consent result — stores intent for screenshot capture. */private val mediaProjectionLauncher =registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->- android.util.Log.d(- "ScreenCapture",+ GotchaLog.d("ScreenCapture") {"mediaProjectionLauncher: resultCode=${result.resultCode}, data=${result.data != null}"- )+ }if (result.resultCode == RESULT_OK && result.data != null) {ScreenPerception.mediaProjectionResultData = result.dataToast.makeText(this, "Screenshot permission granted.", Toast.LENGTH_SHORT).show()- android.util.Log.d("ScreenCapture", "mediaProjectionLauncher: consent stored successfully")+ GotchaLog.d("ScreenCapture") { "mediaProjectionLauncher: consent stored successfully" }} else {android.util.Log.w("ScreenCapture", "mediaProjectionLauncher: consent denied or data null")}diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 4eb00b7..26b4770 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -1,7 +1,6 @@package com.gotcha.agentimport android.content.Context-import android.util.Logimport com.gotcha.agent.skills.SkillPromptBuilderimport com.gotcha.agent.skills.SkillRegistryimport com.gotcha.connectors.ConnectorRegistry@@ -25,6 +24,7 @@ import com.gotcha.tools.SubAgentSessionimport com.gotcha.tools.ToolExecutorimport com.gotcha.tools.ToolRegistryimport com.gotcha.tools.ToolResult+import com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.delay@@ -219,7 +219,7 @@ class AgentEngine(fun setupWorkingDir(create: Boolean = true) {val dir = resolveWorkingDir(create)FileResolver.WORKING_DIR_BASE = dir.absolutePath- Log.d(TAG, "setupWorkingDir: ${dir.absolutePath}")+ GotchaLog.d(TAG) { "setupWorkingDir: ${dir.absolutePath}" }}/** LLM-generated short title, once available; set once per session. */@@ -833,7 +833,7 @@ class AgentEngine(}val label = parts[0]val pkg = parts[1]- Log.d(TAG, "handleUninstallConfirm: label=$label pkg=$pkg")+ GotchaLog.d(TAG) { "handleUninstallConfirm: label=$label pkg=$pkg" }val description = "Request to uninstall \"$label\". After you approve, a system dialog will " +"open — you must tap \"OK\" in that dialog to complete the removal. This action is irreversible."val approved = events.awaitConfirmation(listOf("uninstall_app"), description)@@ -1355,10 +1355,7 @@ class AgentEngine(* can "see" the screen alongside structured element data.*/internal suspend fun injectReadScreenObservation() {- android.util.Log.d(- "ScreenCapture",- "read_screen auto-injection: calling captureCompressedScreenshot()"- )+ GotchaLog.d("ScreenCapture") { "read_screen auto-injection: calling captureCompressedScreenshot()" }val uiTree = ScreenPerception.buildUiHierarchyText()val screenshot = try {events.onScreenCaptureChrome(true)@@ -1367,10 +1364,7 @@ class AgentEngine(} finally {events.onScreenCaptureChrome(false)}- android.util.Log.d(- "ScreenCapture",- "read_screen auto-injection: screenshot=${screenshot != null}"- )+ GotchaLog.d("ScreenCapture") { "read_screen auto-injection: screenshot=${screenshot != null}" }// The accessibility text read happened regardless of screenshot success —// signal the host so it can flash the "screen was read" feedback.events.onScreenReadDone()@@ -1379,10 +1373,9 @@ class AgentEngine(val visionMsg = visionUserMessage(observationText, screenshot.base64, "jpeg")history.add(visionMsg)events.onUi(MessageKind.ASSISTANT, "[Screenshot captured for visual context]")- android.util.Log.d(- "ScreenCapture",+ GotchaLog.d("ScreenCapture") {"read_screen auto-injection: vision message added, base64 length=${screenshot.base64.length}"- )+ }} else {android.util.Log.e("ScreenCapture",diff --git a/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.kt b/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.ktindex ed2121d..1525016 100644--- a/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.kt+++ b/app/src/main/java/com/gotcha/agent/skills/SkillRegistry.kt@@ -3,6 +3,7 @@ package com.gotcha.agent.skillsimport android.content.Contextimport android.util.Logimport androidx.annotation.VisibleForTesting+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport kotlinx.serialization.decodeFromString@@ -90,7 +91,7 @@ object SkillRegistry {val text = assetManager.open(fullPath).bufferedReader().use { it.readText() }val skill = json.decodeFromString<Skill>(text)bundledSkills.add(skill)- Log.d(TAG, "Loaded bundled skill: ${skill.id}")+ GotchaLog.d(TAG) { "Loaded bundled skill: ${skill.id}" }} catch (e: Exception) {Log.e(TAG, "Error parsing $fullPath", e)}diff --git a/app/src/main/java/com/gotcha/audio/AudioApi.kt b/app/src/main/java/com/gotcha/audio/AudioApi.ktindex 4bf0ba5..7cd47b1 100644--- a/app/src/main/java/com/gotcha/audio/AudioApi.kt+++ b/app/src/main/java/com/gotcha/audio/AudioApi.kt@@ -1,6 +1,8 @@package com.gotcha.audioimport android.util.Log+import com.gotcha.BuildConfig+import com.gotcha.util.GotchaLogimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitive@@ -40,7 +42,13 @@ class AudioApi(init {val logging = HttpLoggingInterceptor().apply {- level = HttpLoggingInterceptor.Level.BASIC+ // The request URL (the configured provider endpoint) is not user+ // content we should ship to release logcat; keep tracing debug-only.+ level = if (BuildConfig.DEBUG) {+ HttpLoggingInterceptor.Level.BASIC+ } else {+ HttpLoggingInterceptor.Level.NONE+ }redactHeader("Authorization")}client = OkHttpClient.Builder()@@ -67,7 +75,7 @@ class AudioApi(fun listAudioModels(): List<AudioModel> {return try {val url = "${baseUrl.trimEnd('/')}/models"- try { Log.d("AudioApi", "Fetching models from: $url") } catch (_: Throwable) {}+ try { GotchaLog.d("AudioApi") { "Fetching models from: $url" } } catch (_: Throwable) {}val request = Request.Builder().url(url).get().build()client.newCall(request).execute().use { response ->if (!response.isSuccessful) {@@ -75,7 +83,9 @@ class AudioApi(return@use emptyList()}val body = response.body?.string() ?: return@use emptyList()- try { Log.d("AudioApi", "Models response (first 200 chars): ${body.take(200)}") } catch (_: Throwable) {+ try {+ GotchaLog.d("AudioApi") { "Models response (first 200 chars): ${body.take(200)}" }+ } catch (_: Throwable) {}val jsonObj = jsonParser.parseToJsonElement(body).jsonObjectval dataArr = jsonObj["data"]?.jsonArray ?: return@use emptyList()diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 1fe4cc3..d49c0dd 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -15,6 +15,7 @@ import android.speech.RecognizerIntentimport android.speech.SpeechRecognizerimport android.util.Logimport com.gotcha.i18n.Language+import com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Dispatchers@@ -296,15 +297,15 @@ class SttEngine(recognizer = newRecnewRec.setRecognitionListener(object : RecognitionListener {override fun onReadyForSpeech(params: Bundle?) {- Log.d(TAG, "onReadyForSpeech")+ GotchaLog.d(TAG) { "onReadyForSpeech" }}- override fun onBeginningOfSpeech() { Log.d(TAG, "onBeginningOfSpeech") }+ override fun onBeginningOfSpeech() { GotchaLog.d(TAG) { "onBeginningOfSpeech" } }override fun onRmsChanged(rmsdB: Float) {}override fun onBufferReceived(buffer: ByteArray?) {}- override fun onEndOfSpeech() { Log.d(TAG, "onEndOfSpeech") }+ override fun onEndOfSpeech() { GotchaLog.d(TAG) { "onEndOfSpeech" } }override fun onError(error: Int) {val humanMsg = HumanReadableError.fromSpeechRecognizerCode(error)- Log.d(TAG, "onError: $error ($humanMsg)")+ GotchaLog.d(TAG) { "onError: $error ($humanMsg)" }if (error == SpeechRecognizer.ERROR_CLIENT ||error == SpeechRecognizer.ERROR_RECOGNIZER_BUSY ||error == SpeechRecognizer.ERROR_SERVER@@ -322,7 +323,7 @@ class SttEngine(}}override fun onResults(results: Bundle?) {- Log.d(TAG, "onResults")+ GotchaLog.d(TAG) { "onResults" }val matches = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)val text = matches?.firstOrNull() ?: ""if (text.isNotBlank()) {@@ -338,17 +339,17 @@ class SttEngine(}}override fun onPartialResults(partialResults: Bundle?) {- Log.d(TAG, "onPartialResults")+ GotchaLog.d(TAG) { "onPartialResults" }val matches = partialResults?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)val text = matches?.firstOrNull() ?: ""if (text.isNotBlank()) {currentPartialResult = text}}- override fun onEvent(eventType: Int, params: Bundle?) { Log.d(TAG, "onEvent: $eventType") }+ override fun onEvent(eventType: Int, params: Bundle?) { GotchaLog.d(TAG) { "onEvent: $eventType" } }override fun onSegmentResults(segmentResults: Bundle) {- Log.d(TAG, "onSegmentResults")+ GotchaLog.d(TAG) { "onSegmentResults" }val matches = segmentResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)val text = matches?.firstOrNull() ?: ""if (text.isNotBlank()) {@@ -359,7 +360,7 @@ class SttEngine(}override fun onEndOfSegmentedSession() {- Log.d(TAG, "onEndOfSegmentedSession")+ GotchaLog.d(TAG) { "onEndOfSegmentedSession" }if (isContinuousListening) {mainHandler.post { startContinuousListeningCycle() }} else {diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.ktindex 36bc9bb..0056ed2 100644--- a/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthApi.kt@@ -77,7 +77,12 @@ interface SamosaAuthApi {encodeDefaults = false}val logging = HttpLoggingInterceptor().apply {- level = HttpLoggingInterceptor.Level.BASIC+ // The request URL is the configured endpoint — not for release logcat.+ level = if (BuildConfig.DEBUG) {+ HttpLoggingInterceptor.Level.BASIC+ } else {+ HttpLoggingInterceptor.Level.NONE+ }redactHeader("Authorization")}val client = OkHttpClient.Builder()diff --git a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.ktindex cfebff7..8d91f0b 100644--- a/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt+++ b/app/src/main/java/com/gotcha/auth/SamosaAuthManager.kt@@ -11,6 +11,7 @@ import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOptionimport com.google.android.libraries.identity.googleid.GoogleIdTokenCredentialimport com.gotcha.BuildConfigimport com.gotcha.data.SettingsRepository+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.CancellationExceptionimport retrofit2.HttpExceptionimport java.io.IOException@@ -49,10 +50,10 @@ class SamosaAuthManager(val idToken = try {requestGoogleIdToken(activityContext)} catch (e: GetCredentialCancellationException) {- Log.d(TAG, "Sign-in cancelled by user", e)+ GotchaLog.d(TAG, e) { "Sign-in cancelled by user" }return SamosaSignInResult.Cancelled} catch (e: NoCredentialException) {- Log.d(TAG, "No Google credential available", e)+ GotchaLog.d(TAG, e) { "No Google credential available" }return SamosaSignInResult.Error("No Google account available. Add a Google account to this device and try again.")@@ -95,7 +96,7 @@ class SamosaAuthManager(} catch (e: HttpException) {SamosaSignInResult.Error(mapRegisterError(e.code()))} catch (e: IOException) {- Log.d(TAG, "Network error during register", e)+ GotchaLog.d(TAG, e) { "Network error during register" }SamosaSignInResult.Error("Network error. Check your connection and try again.")}@@ -115,7 +116,7 @@ class SamosaAuthManager(val token = settingsRepository.load().samosaSessionTokenif (token.isNotBlank()) {runCatching { api.logout("Bearer $token") }- .onFailure { Log.d(TAG, "Server logout failed (ignored): ${it.message}") }+ .onFailure { GotchaLog.d(TAG) { "Server logout failed (ignored): ${it.message}" } }}settingsRepository.clearSamosaSession()runCatching {@@ -143,7 +144,7 @@ class SamosaAuthManager(} catch (e: CancellationException) {throw e} catch (e: Exception) {- Log.d(TAG, "Could not fetch credit balance (ignored)", e)+ GotchaLog.d(TAG, e) { "Could not fetch credit balance (ignored)" }null}}diff --git a/app/src/main/java/com/gotcha/llm/LLMClient.kt b/app/src/main/java/com/gotcha/llm/LLMClient.ktindex 158d747..1dcd29e 100644--- a/app/src/main/java/com/gotcha/llm/LLMClient.kt+++ b/app/src/main/java/com/gotcha/llm/LLMClient.kt@@ -1,6 +1,7 @@package com.gotcha.llmimport android.content.Context+import com.gotcha.BuildConfigimport com.gotcha.audio.AudioModelimport com.gotcha.audio.ModelCategoryimport com.gotcha.i18n.Language@@ -38,7 +39,12 @@ class LLMClient(init {val logging = HttpLoggingInterceptor().apply {- level = HttpLoggingInterceptor.Level.BODY+ // BODY tracing writes full prompts/replies to logcat — never in release.+ level = if (BuildConfig.DEBUG) {+ HttpLoggingInterceptor.Level.BODY+ } else {+ HttpLoggingInterceptor.Level.NONE+ }redactHeader("Authorization")}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationApi.kt b/app/src/main/java/com/gotcha/notifications/NotificationApi.ktindex 6f58cbf..9ba3800 100644--- a/app/src/main/java/com/gotcha/notifications/NotificationApi.kt+++ b/app/src/main/java/com/gotcha/notifications/NotificationApi.kt@@ -39,7 +39,12 @@ open class NotificationApi(init {val logging = HttpLoggingInterceptor().apply {- level = HttpLoggingInterceptor.Level.BASIC+ // The request URL is the configured endpoint — not for release logcat.+ level = if (BuildConfig.DEBUG) {+ HttpLoggingInterceptor.Level.BASIC+ } else {+ HttpLoggingInterceptor.Level.NONE+ }}client = OkHttpClient.Builder().connectTimeout(timeoutSeconds, TimeUnit.SECONDS)diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 6302cf6..fa43223 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -26,6 +26,7 @@ import com.gotcha.data.settingsChangeNotifierimport com.gotcha.i18n.Languageimport com.gotcha.ui.AssistiveBallOverlayimport com.gotcha.ui.CallChatWindow+import com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -460,22 +461,21 @@ class AssistiveBallService : Service() {/** Read the clipboard (via a focus-stealing activity) and offer a smart action. */private fun handleClipboardRead() {- android.util.Log.d("AssistiveBallService", "onReadClipboardRequest called")+ GotchaLog.d("AssistiveBallService") { "onReadClipboardRequest called" }overlay.readClipboardWithFocus { clip ->- android.util.Log.d(- "AssistiveBallService",+ GotchaLog.d("AssistiveBallService") {"readClipboardWithFocus: null=${clip == null}, count=${clip?.itemCount ?: 0}"- )+ }com.gotcha.service.GotchaAccessibilityService.lastClipboardData = clipval clipText = clip?.getItemAt(0)?.text?.toString()- android.util.Log.d("AssistiveBallService", "clip length=${clipText?.length ?: 0}")+ GotchaLog.d("AssistiveBallService") { "clip length=${clipText?.length ?: 0}" }if (clipText.isNullOrBlank()) {- android.util.Log.d("AssistiveBallService", "clipText is null or blank, not setting smart action")+ GotchaLog.d("AssistiveBallService") { "clipText is null or blank, not setting smart action" }return@readClipboardWithFocus}val url = SmartActionDetector.extractUrl(clipText)if (url != null) {- android.util.Log.d("AssistiveBallService", "Setting smart action: Summarize link ($url)")+ GotchaLog.d("AssistiveBallService") { "Setting smart action: Summarize link ($url)" }val fetch = SmartActionDetector.fetchAction(url)overlay.setSmartActionAvailable(fetch.label, fetch.prompt)return@readClipboardWithFocusdiff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex 47dc49a..814bfd7 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -10,6 +10,7 @@ import android.view.Displayimport android.view.accessibility.AccessibilityEventimport android.view.accessibility.AccessibilityNodeInfoimport androidx.annotation.RequiresApi+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.suspendCancellableCoroutineimport kotlin.coroutines.resume@@ -57,10 +58,7 @@ class GotchaAccessibilityService : AccessibilityService() {val desc = source.contentDescription?.toString() ?: ""val viewId = source.viewIdResourceName ?: ""if (isCopyString(text) || isCopyString(desc) || viewId.lowercase().contains("copy")) {- android.util.Log.d(- "GotchaAccessibilityService",- "Copy click detected: id=$viewId"- )+ GotchaLog.d("GotchaAccessibilityService") { "Copy click detected: id=$viewId" }triggerClipboardBroadcast()}source.recycle()@@ -69,7 +67,7 @@ class GotchaAccessibilityService : AccessibilityService() {for (t in eventTexts) {val textStr = t?.toString() ?: ""if (isCopyString(textStr)) {- android.util.Log.d("GotchaAccessibilityService", "Copy event text detected")+ GotchaLog.d("GotchaAccessibilityService") { "Copy event text detected" }triggerClipboardBroadcast()break}@@ -79,10 +77,7 @@ class GotchaAccessibilityService : AccessibilityService() {for (t in eventTexts) {val textStr = t?.toString() ?: ""if (isClipboardToast(textStr)) {- android.util.Log.d(- "GotchaAccessibilityService",- "Clipboard toast detected"- )+ GotchaLog.d("GotchaAccessibilityService") { "Clipboard toast detected" }triggerClipboardBroadcast()break}@@ -123,10 +118,7 @@ class GotchaAccessibilityService : AccessibilityService() {setPackage(packageName)}sendBroadcast(intent)- android.util.Log.d(- "GotchaAccessibilityService",- "Sent CLIPBOARD_CHANGED broadcast"- )+ GotchaLog.d("GotchaAccessibilityService") { "Sent CLIPBOARD_CHANGED broadcast" }} catch (e: Exception) {android.util.Log.e("GotchaAccessibilityService",@@ -658,9 +650,6 @@ class GotchaAccessibilityService : AccessibilityService() {/** Register a clipboard listener to cache clipboard content. */internal fun initClipboardListener() {- android.util.Log.d(- "GotchaAccessibilityService",- "initClipboardListener: using event-based detection"- )+ GotchaLog.d("GotchaAccessibilityService") { "initClipboardListener: using event-based detection" }}}diff --git a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt b/app/src/main/java/com/gotcha/service/MediaProjectionService.ktindex 354b085..4ba1def 100644--- a/app/src/main/java/com/gotcha/service/MediaProjectionService.kt+++ b/app/src/main/java/com/gotcha/service/MediaProjectionService.kt@@ -21,6 +21,7 @@ import android.os.IBinderimport android.util.DisplayMetricsimport android.util.Logimport android.view.WindowManager+import com.gotcha.util.GotchaLogimport java.io.ByteArrayOutputStreamimport java.io.Fileimport java.util.concurrent.CountDownLatch@@ -68,7 +69,7 @@ class MediaProjectionService : Service() {resultIntent: Intent,timeoutMs: Long = 5000): ByteArray? = synchronized(captureLock) {- Log.d("ScreenCapture", "MediaProjectionService.capture() called")+ GotchaLog.d("ScreenCapture") { "MediaProjectionService.capture() called" }resultData = resultIntentresultReady = CountDownLatch(1)resultFilePath = null@@ -76,14 +77,16 @@ class MediaProjectionService : Service() {val serviceIntent = Intent(context, MediaProjectionService::class.java)try {context.startForegroundService(serviceIntent)- Log.d("ScreenCapture", "MediaProjectionService started")+ GotchaLog.d("ScreenCapture") { "MediaProjectionService started" }} catch (e: Exception) {Log.e("ScreenCapture", "Failed to start MediaProjectionService: ${e.message}")return null}val completed = resultReady.await(timeoutMs, TimeUnit.MILLISECONDS)- Log.d("ScreenCapture", "MediaProjectionService latch completed=$completed, resultFilePath=$resultFilePath")+ GotchaLog.d("ScreenCapture") {+ "MediaProjectionService latch completed=$completed, resultFilePath=$resultFilePath"+ }val path = resultFilePath ?: return nullval file = File(path)@@ -93,7 +96,7 @@ class MediaProjectionService : Service() {}val bytes = file.readBytes()file.delete()- Log.d("ScreenCapture", "MediaProjectionService returning ${bytes.size} bytes")+ GotchaLog.d("ScreenCapture") { "MediaProjectionService returning ${bytes.size} bytes" }return bytes}}@@ -112,7 +115,7 @@ class MediaProjectionService : Service() {/** API 34 requires a registered callback before createVirtualDisplay(). */private val projectionCallback = object : MediaProjection.Callback() {override fun onStop() {- Log.d("ScreenCapture", "MediaProjection.onStop()")+ GotchaLog.d("ScreenCapture") { "MediaProjection.onStop()" }finish(null)}}@@ -134,7 +137,7 @@ class MediaProjectionService : Service() {override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {val data = resultDataval handler = captureHandler- Log.d("ScreenCapture", "MediaProjectionService.onStartCommand: data=${data != null}")+ GotchaLog.d("ScreenCapture") { "MediaProjectionService.onStartCommand: data=${data != null}" }if (data == null || handler == null) {finish(null)return START_NOT_STICKY@@ -157,7 +160,7 @@ class MediaProjectionService : Service() {* asynchronously on [captureHandler] via the ImageReader listener.*/private fun startCapture(data: Intent) {- Log.d("ScreenCapture", "startCapture: starting")+ GotchaLog.d("ScreenCapture") { "startCapture: starting" }val mpManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager// A spent or stale token throws here rather than returning null on API 34+.val mp = try {@@ -182,7 +185,7 @@ class MediaProjectionService : Service() {val screenWidth = metrics.widthPixelsval screenHeight = metrics.heightPixelsval screenDpi = metrics.densityDpi- Log.d("ScreenCapture", "startCapture: screen ${screenWidth}x$screenHeight dpi=$screenDpi")+ GotchaLog.d("ScreenCapture") { "startCapture: screen ${screenWidth}x$screenHeight dpi=$screenDpi" }val reader = ImageReader.newInstance(screenWidth, screenHeight, PixelFormat.RGBA_8888, 2)imageReader = reader@@ -210,7 +213,7 @@ class MediaProjectionService : Service() {reader.surface,null, null)- Log.d("ScreenCapture", "startCapture: virtualDisplay=${virtualDisplay != null}")+ GotchaLog.d("ScreenCapture") { "startCapture: virtualDisplay=${virtualDisplay != null}" }// Never leave the caller (and the service) hanging if no frame is produced.captureHandler?.postDelayed({@@ -233,7 +236,7 @@ class MediaProjectionService : Service() {bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)bitmap.recycle()val pngBytes = stream.toByteArray()- Log.d("ScreenCapture", "onFrame: PNG compressed ${pngBytes.size} bytes")+ GotchaLog.d("ScreenCapture") { "onFrame: PNG compressed ${pngBytes.size} bytes" }if (pngBytes.isEmpty()) {Log.e("ScreenCapture", "onFrame: PNG compression produced 0 bytes")finish(null)@@ -241,7 +244,7 @@ class MediaProjectionService : Service() {}val outPath = File(cacheDir, RESULT_FILE).absolutePathFile(outPath).writeBytes(pngBytes)- Log.d("ScreenCapture", "onFrame: saved to $outPath")+ GotchaLog.d("ScreenCapture") { "onFrame: saved to $outPath" }finish(outPath)}@@ -270,7 +273,9 @@ class MediaProjectionService : Service() {}val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)bmp.copyPixelsFromBuffer(java.nio.ByteBuffer.wrap(packedBytes))- Log.d("ScreenCapture", "toBitmap: ${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)")+ GotchaLog.d("ScreenCapture") {+ "toBitmap: ${bmp.width}x${bmp.height} (stride=$rowStride, pxStride=$pixelStride)"+ }bmp} catch (t: Throwable) {Log.e("ScreenCapture", "toBitmap failed: ${t.message}", t)diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.ktindex 438ad7c..94385f1 100644--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt@@ -13,6 +13,7 @@ import android.os.Processimport android.util.Logimport androidx.core.content.ContextCompatimport com.gotcha.BuildConfig+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -119,7 +120,7 @@ class WakeWordDetector(matcher = WakeWordMatcher(sensitivityProvider().coerceIn(0f, 1f))running.set(true)val startGeneration = generation- if (BuildConfig.DEBUG) Log.d(TAG, "start(): generation=$startGeneration")+ GotchaLog.d(TAG) { "start(): generation=$startGeneration" }job = scope.launch(Dispatchers.IO) { initializeAndListen(startGeneration) }}return true@@ -155,9 +156,7 @@ class WakeWordDetector(}private fun teardown(closeSessions: Boolean) {- if (BuildConfig.DEBUG) {- Log.d(TAG, if (closeSessions) "release()" else "pause()", Throwable("called from"))- }+ GotchaLog.d(TAG, Throwable("called from")) { if (closeSessions) "release()" else "pause()" }val oldRecorder: AudioRecord?var oldSessions: Sessions? = nullval oldJob: Job?@@ -388,8 +387,7 @@ class WakeWordDetector(// processing left behind by a call. Record what we actually got.val audio = appContext.getSystemService(android.content.Context.AUDIO_SERVICE)as android.media.AudioManager- Log.d(- TAG,+ GotchaLog.d(TAG) {"listening: threshold=${matcher.threshold()} readFrames=$READ_FRAMES " +"rate=${localRecorder.sampleRate} ch=${localRecorder.channelCount} " +"session=${localRecorder.audioSessionId} " +@@ -397,7 +395,7 @@ class WakeWordDetector("audioMode=${audio.mode} " +"micMute=${audio.isMicrophoneMute} " +"bufFrames=${localRecorder.bufferSizeInFrames}"- )+ }}// An audio capture loop should be scheduled like one. At the default// priority of a Dispatchers.IO thread this loop competes with ordinary@@ -520,13 +518,12 @@ class WakeWordDetector(// Locale.ROOT, not the default: on a decimal-comma device these// become "-70,5" and stop being greppable, which is the whole point// of the line.- Log.d(- TAG,+ GotchaLog.d(TAG) {"heard: rms ${fmt(quietestRms, 1)}..${fmt(peakRms, 1)} dBFS, " +"frames=$frames scored=$scored gated=$gated peakScore=${fmt(peakScore, 3)} " +"mel[${fmt(melMin, 2)}..${fmt(melMax, 2)} avg ${fmt(melMean, 2)}] " +"emb[${fmt(embMin, 2)}..${fmt(embMax, 2)} avg ${fmt(embMean, 2)}]"- )+ }melMin = Float.MAX_VALUEmelMax = -Float.MAX_VALUEembMin = Float.MAX_VALUEdiff --git a/app/src/main/java/com/gotcha/tools/AppsTool.kt b/app/src/main/java/com/gotcha/tools/AppsTool.ktindex 6360c8f..115ea3c 100644--- a/app/src/main/java/com/gotcha/tools/AppsTool.kt+++ b/app/src/main/java/com/gotcha/tools/AppsTool.kt@@ -10,6 +10,7 @@ import android.net.ConnectivityManagerimport android.net.Uriimport android.os.Processimport android.util.Log+import com.gotcha.util.GotchaLogclass AppsTool(private val context: Context) {@@ -126,7 +127,7 @@ class AppsTool(private val context: Context) {* the app is gone via list_installed_apps after tapping OK.*/fun doUninstall(packageName: String): ToolResult {- Log.d(TAG, "doUninstall: $packageName")+ GotchaLog.d(TAG) { "doUninstall: $packageName" }return try {val pm = context.packageManagerval installed = try {@@ -150,7 +151,7 @@ class AppsTool(private val context: Context) {.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)context.startActivity(intent)- Log.d(TAG, "doUninstall: dialog opened for $label")+ GotchaLog.d(TAG) { "doUninstall: dialog opened for $label" }ToolResult.ok("System dialog opened to uninstall $label. After you tap OK in the dialog, ask the assistant to verify the app is gone.")diff --git a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.ktindex b4d9f96..6bc1eae 100644--- a/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt+++ b/app/src/main/java/com/gotcha/tools/MediaCaptureTool.kt@@ -11,6 +11,7 @@ import androidx.camera.core.ImageCaptureimport androidx.camera.core.ImageCaptureExceptionimport androidx.camera.lifecycle.ProcessCameraProviderimport androidx.core.content.ContextCompat+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.suspendCancellableCoroutineimport kotlinx.coroutines.withContext@@ -44,7 +45,7 @@ class MediaCaptureTool(private val context: Context) {private var lastSavedDurationSeconds: Long = 0Lsuspend fun takePhoto(camera: String?): ToolResult {- Log.d(TAG, "takePhoto: camera=$camera")+ GotchaLog.d(TAG) { "takePhoto: camera=$camera" }if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {@@ -76,20 +77,20 @@ class MediaCaptureTool(private val context: Context) {val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build()val result = withContext(Dispatchers.Main) {- Log.d(TAG, "takePhoto: on main thread, acquiring provider…")+ GotchaLog.d(TAG) { "takePhoto: on main thread, acquiring provider…" }val cameraProvider = ProcessCameraProvider.getInstance(context).get(5, TimeUnit.SECONDS)- Log.d(TAG, "takePhoto: provider acquired, binding…")+ GotchaLog.d(TAG) { "takePhoto: provider acquired, binding…" }cameraProvider.unbindAll()cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, imageCapture)val res = suspendCancellableCoroutine<ToolResult> { cont ->- Log.d(TAG, "takePhoto: calling takePicture…")+ GotchaLog.d(TAG) { "takePhoto: calling takePicture…" }imageCapture.takePicture(outputOptions,ContextCompat.getMainExecutor(context),object : ImageCapture.OnImageSavedCallback {override fun onImageSaved(output: ImageCapture.OutputFileResults) {- Log.d(TAG, "takePhoto: image saved to ${file.absolutePath}")+ GotchaLog.d(TAG) { "takePhoto: image saved to ${file.absolutePath}" }com.gotcha.data.GotchaStorage.publishToGallery(context, file)cont.resume(ToolResult.ok("Photo saved to ${file.absolutePath}."))}diff --git a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt b/app/src/main/java/com/gotcha/tools/ScreenPerception.ktindex 1da6f51..996c5f7 100644--- a/app/src/main/java/com/gotcha/tools/ScreenPerception.kt+++ b/app/src/main/java/com/gotcha/tools/ScreenPerception.kt@@ -11,6 +11,7 @@ import android.util.Logimport android.view.accessibility.AccessibilityNodeInfoimport com.gotcha.service.GotchaAccessibilityServiceimport com.gotcha.service.MediaProjectionService+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.delayimport kotlinx.coroutines.withContext@@ -82,13 +83,13 @@ object ScreenPerception {saveDir: File? = null): CompressedScreenshot? {return try {- Log.d("ScreenCapture", "compressScreenshot: starting capture...")+ GotchaLog.d("ScreenCapture") { "compressScreenshot: starting capture..." }val bytes = captureRawBytes()if (bytes == null) {Log.e("ScreenCapture", "compressScreenshot: captureRawBytes returned null — all paths failed")return null}- Log.d("ScreenCapture", "compressScreenshot: got ${bytes.size} raw bytes")+ GotchaLog.d("ScreenCapture") { "compressScreenshot: got ${bytes.size} raw bytes" }val originalSize = bytes.size.toLong()val options = BitmapFactory.Options().apply {inMutable = true@@ -102,7 +103,7 @@ object ScreenPerception {)return null}- Log.d("ScreenCapture", "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}")+ GotchaLog.d("ScreenCapture") { "compressScreenshot: decoded bitmap ${bitmap.width}x${bitmap.height}" }val annotated = if (drawGrid) {val elements = lastElementsCache ?: emptyList()if (elements.isNotEmpty()) {@@ -337,12 +338,12 @@ object ScreenPerception {private suspend fun captureRawBytes(): ByteArray? {// Path 1: AccessibilityService.takeScreenshot() — API 30+, no special perms.val service = GotchaAccessibilityService.instance- Log.d("ScreenCapture", "Path1: service=${service != null}")+ GotchaLog.d("ScreenCapture") { "Path1: service=${service != null}" }if (service != null) {for (attempt in 1..2) {- Log.d("ScreenCapture", "Path1: takeScreenshotBitmap attempt $attempt")+ GotchaLog.d("ScreenCapture") { "Path1: takeScreenshotBitmap attempt $attempt" }val bitmap = service.takeScreenshotBitmap()- Log.d("ScreenCapture", "Path1: takeScreenshotBitmap returned ${bitmap != null}")+ GotchaLog.d("ScreenCapture") { "Path1: takeScreenshotBitmap returned ${bitmap != null}" }if (bitmap != null) {val bytes = withContext(Dispatchers.Default) {val stream = ByteArrayOutputStream()@@ -350,7 +351,7 @@ object ScreenPerception {bitmap.recycle()stream.toByteArray()}- Log.d("ScreenCapture", "Path1: compressed to ${bytes.size} bytes")+ GotchaLog.d("ScreenCapture") { "Path1: compressed to ${bytes.size} bytes" }if (bytes.isNotEmpty()) return bytes}if (attempt < 2) delay(1100)@@ -364,26 +365,29 @@ object ScreenPerception {// consent instead of silently retrying with a dead token, and a concurrent// capture cannot claim the same single-use token.val projectionData = if (ctx != null) consumeMediaProjectionResultData() else null- Log.d(- "ScreenCapture",+ GotchaLog.d("ScreenCapture") {"Path2: projectionData=${projectionData != null}, ctx=${ctx != null}, appContext=${appContext != null}"- )+ }if (projectionData != null && ctx != null) {- Log.d("ScreenCapture", "Path2: calling MediaProjectionService.capture()")+ GotchaLog.d("ScreenCapture") { "Path2: calling MediaProjectionService.capture()" }val bytes = withContext(Dispatchers.IO) {MediaProjectionService.capture(ctx, projectionData)}- Log.d("ScreenCapture", "Path2: MediaProjectionService.capture returned ${bytes?.size ?: "null"} bytes")+ GotchaLog.d("ScreenCapture") {+ "Path2: MediaProjectionService.capture returned ${bytes?.size ?: "null"} bytes"+ }if (bytes != null && bytes.isNotEmpty()) return bytes}// Path 3: screencap via shell (works on rooted devices / emulators).- Log.d("ScreenCapture", "Path3: trying screencap -p")+ GotchaLog.d("ScreenCapture") { "Path3: trying screencap -p" }return try {withContext(Dispatchers.IO) {val process = Runtime.getRuntime().exec("screencap -p")val bytes = process.inputStream.use { it.readBytes() }process.waitFor()- Log.d("ScreenCapture", "Path3: screencap returned ${bytes.size} bytes, exit=${process.exitValue()}")+ GotchaLog.d("ScreenCapture") {+ "Path3: screencap returned ${bytes.size} bytes, exit=${process.exitValue()}"+ }if (bytes.isEmpty()) null else bytes}} catch (e: Exception) {diff --git a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt b/app/src/main/java/com/gotcha/tools/SubAgentSession.ktindex dd9b68e..0e9a2ab 100644--- a/app/src/main/java/com/gotcha/tools/SubAgentSession.kt+++ b/app/src/main/java/com/gotcha/tools/SubAgentSession.kt@@ -10,6 +10,7 @@ import com.gotcha.data.Settingsimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.llm.withValidToolCallArguments+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.CancellationExceptionimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObject@@ -41,7 +42,7 @@ class SubAgentSession(suspend fun run(): SubAgentOutput {val model = settings.subAgentModel.ifBlank { settings.model }- Log.d(TAG, "Starting sub-agent with model=$model: $description")+ GotchaLog.d(TAG) { "Starting sub-agent with model=$model: $description" }val subLlm = LLMClient(apiKey = settings.effectiveApiKey,@@ -58,7 +59,7 @@ class SubAgentSession(val subAgentTools = ToolRegistry.toolsForSubAgent(hiddenTools)for (round in 0 until maxRounds) {- Log.d(TAG, "Sub-agent round ${round + 1}/$maxRounds")+ GotchaLog.d(TAG) { "Sub-agent round ${round + 1}/$maxRounds" }val messages = buildList {addAll(history)@@ -94,7 +95,7 @@ class SubAgentSession(if (toolCalls.isEmpty()) {history.add(message)val text = message.textContent.ifEmpty { "(no output)" }- Log.d(TAG, "Sub-agent finished (text response): ${text.take(100)}")+ GotchaLog.d(TAG) { "Sub-agent finished (text response): ${text.take(100)}" }return SubAgentOutput(text, collectedSteps.toList())}@@ -109,7 +110,7 @@ class SubAgentSession(} catch (e: Exception) {"(failed to parse ask_final_answer: ${e.message})"}- Log.d(TAG, "Sub-agent finished (ask_final_answer)")+ GotchaLog.d(TAG) { "Sub-agent finished (ask_final_answer)" }return SubAgentOutput(answer, collectedSteps.toList())}diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex f31d9c7..3a0372b 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -1,9 +1,9 @@package com.gotcha.toolsimport android.content.Context-import android.util.Logimport com.gotcha.agent.skills.SkillRegistryimport com.gotcha.connectors.ConnectorCatalog+import com.gotcha.util.GotchaLogimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.delay@@ -120,10 +120,9 @@ class ToolExecutor(}// Do not log result.message — tool payloads can contain sensitive user data// (SMS bodies, clipboard text, file contents, location, etc.).- Log.d(- TAG,+ GotchaLog.d(TAG) {"execute: $name -> success=${result.success}, msgLen=${result.message.length}, perm=${result.needsPermission}"- )+ }actionLog.record(name, args.redactedForAudit(), result)return result}@@ -153,7 +152,7 @@ class ToolExecutor(* Bypasses the destructive-action confirmation flow.*/suspend fun executeUninstall(packageName: String): ToolResult {- Log.d(TAG, "executeUninstall: $packageName")+ GotchaLog.d(TAG) { "executeUninstall: $packageName" }val result = withContext(Dispatchers.IO) { appsTool.doUninstall(packageName) }actionLog.record("uninstall_app", packageName, result)return result@@ -423,7 +422,7 @@ class ToolExecutor(val secs = args.requireInt("duration_seconds")?.coerceIn(1, 86400)?: return missing("duration_seconds")for (remaining in secs downTo 1) {- Log.d(TAG, "sleep: ${remaining}s remaining")+ GotchaLog.d(TAG) { "sleep: ${remaining}s remaining" }delay(1000L)}ToolResult.ok("Slept for $secs seconds.")diff --git a/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt b/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.ktindex a0cbe5e..26e246f 100644--- a/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt+++ b/app/src/main/java/com/gotcha/ui/ClipboardReaderActivity.kt@@ -4,13 +4,14 @@ import android.app.Activityimport android.content.ClipboardManagerimport android.content.Contextimport android.os.Bundle+import com.gotcha.util.GotchaLogclass ClipboardReaderActivity : Activity() {private var hasAttemptedRead = falseoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)- android.util.Log.d("ClipboardReaderActivity", "onCreate")+ GotchaLog.d("ClipboardReaderActivity") { "onCreate" }// Create a dummy view and set it to ensure the window has a view that can gain focusval dummyView = android.view.View(this).apply {@@ -22,10 +23,7 @@ class ClipboardReaderActivity : Activity() {// Delay a bit in case window focus doesn't firewindow.decorView.postDelayed({- android.util.Log.d(- "ClipboardReaderActivity",- "postDelayed triggered, read=$hasAttemptedRead"- )+ GotchaLog.d("ClipboardReaderActivity") { "postDelayed triggered, read=$hasAttemptedRead" }if (!hasAttemptedRead) {readClipboardAndFinish("timeout")}@@ -34,26 +32,20 @@ class ClipboardReaderActivity : Activity() {override fun onWindowFocusChanged(hasFocus: Boolean) {super.onWindowFocusChanged(hasFocus)- android.util.Log.d(- "ClipboardReaderActivity",- "onWindowFocusChanged: $hasFocus, read=$hasAttemptedRead"- )+ GotchaLog.d("ClipboardReaderActivity") { "onWindowFocusChanged: $hasFocus, read=$hasAttemptedRead" }if (hasFocus && !hasAttemptedRead) {readClipboardAndFinish("focus")}}private fun readClipboardAndFinish(source: String) {- android.util.Log.d("ClipboardReaderActivity", "readClipboardAndFinish: $source")+ GotchaLog.d("ClipboardReaderActivity") { "readClipboardAndFinish: $source" }hasAttemptedRead = truetry {val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager- android.util.Log.d("ClipboardReaderActivity", "Retrieving primaryClip")+ GotchaLog.d("ClipboardReaderActivity") { "Retrieving primaryClip" }val clip = cm.primaryClip- android.util.Log.d(- "ClipboardReaderActivity",- "clip retrieved: count=${clip?.itemCount ?: 0}"- )+ GotchaLog.d("ClipboardReaderActivity") { "clip retrieved: count=${clip?.itemCount ?: 0}" }onClipboardRead?.invoke(clip)} catch (e: Exception) {android.util.Log.e("ClipboardReaderActivity", "Failed to read clipboard", e)diff --git a/app/src/main/java/com/gotcha/util/GotchaLog.kt b/app/src/main/java/com/gotcha/util/GotchaLog.ktnew file mode 100644index 0000000..b9d7c0d--- /dev/null+++ b/app/src/main/java/com/gotcha/util/GotchaLog.kt@@ -0,0 +1,28 @@+package com.gotcha.util++import android.util.Log+import com.gotcha.BuildConfig++/**+ * App-wide logging facade. `d`/`v` are no-ops in release builds: `BuildConfig.DEBUG`+ * folds to a constant `false`, and the message is a lambda so its string is never+ * built either. Raw `Log.w`/`Log.e` stay in use for failures worth reporting from+ * the field.+ */+object GotchaLog {+ fun d(tag: String, message: () -> String) {+ if (BuildConfig.DEBUG) Log.d(tag, message())+ }++ fun d(tag: String, throwable: Throwable?, message: () -> String) {+ if (BuildConfig.DEBUG) Log.d(tag, message(), throwable)+ }++ fun v(tag: String, message: () -> String) {+ if (BuildConfig.DEBUG) Log.v(tag, message())+ }++ fun v(tag: String, throwable: Throwable?, message: () -> String) {+ if (BuildConfig.DEBUG) Log.v(tag, message(), throwable)+ }+}diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.ymlindex 4a244fe..79b7f8d 100644--- a/config/detekt/detekt.yml+++ b/config/detekt/detekt.yml@@ -61,6 +61,13 @@ exceptions:TooGenericExceptionCaught:active: false+gotcha:+ NoRawDebugLog:+ active: true+ # GotchaLog.kt is the one sanctioned place raw Log.d/Log.v appears (behind+ # BuildConfig.DEBUG). Everything else must route through the facade.+ excludes: ["**/GotchaLog.kt"]+formatting:MaximumLineLength:maxLineLength: 140diff --git a/detekt-rules/build.gradle.kts b/detekt-rules/build.gradle.ktsnew file mode 100644index 0000000..f27caa4--- /dev/null+++ b/detekt-rules/build.gradle.kts@@ -0,0 +1,12 @@+// Custom detekt rules for the Gotcha repo. Compiled against detekt-api 1.23.6+// (the version the app pins) and the same kotlin-compiler-embeddable 1.9.x that+// detekt bundles, so rule bytecode stays binary-compatible at runtime.+plugins {+ `java-library`+ kotlin("jvm")+}++dependencies {+ compileOnly("io.gitlab.arturbosch.detekt:detekt-api:1.23.6")+ compileOnly("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.9.22")+}diff --git a/detekt-rules/src/main/kotlin/com/gotcha/detekt/GotchaRules.kt b/detekt-rules/src/main/kotlin/com/gotcha/detekt/GotchaRules.ktnew file mode 100644index 0000000..33e9e41--- /dev/null+++ b/detekt-rules/src/main/kotlin/com/gotcha/detekt/GotchaRules.kt@@ -0,0 +1,57 @@+package com.gotcha.detekt++import io.gitlab.arturbosch.detekt.api.CodeSmell+import io.gitlab.arturbosch.detekt.api.Config+import io.gitlab.arturbosch.detekt.api.Debt+import io.gitlab.arturbosch.detekt.api.Entity+import io.gitlab.arturbosch.detekt.api.Issue+import io.gitlab.arturbosch.detekt.api.Rule+import io.gitlab.arturbosch.detekt.api.RuleSet+import io.gitlab.arturbosch.detekt.api.RuleSetProvider+import io.gitlab.arturbosch.detekt.api.Severity+import org.jetbrains.kotlin.psi.KtCallExpression+import org.jetbrains.kotlin.psi.KtDotQualifiedExpression++/**+ * Blocks raw `android.util.Log.d` / `Log.v` calls. Those ship into release builds+ * (`isMinifyEnabled = false`, so R8 keeps them) and always build their message+ * string, even when nothing consumes the output. Debug-level logging must go+ * through `com.gotcha.util.GotchaLog`, whose `d`/`v` are compile-time no-ops in+ * release.+ */+class NoRawDebugLog(config: Config) : Rule(config) {+ override val issue = Issue(+ id = "NoRawDebugLog",+ severity = Severity.Security,+ description = "Raw Log.d/Log.v ships in release builds and always builds its " ++ "message string. Use com.gotcha.util.GotchaLog.d/v, which is a compile-time " ++ "no-op in release.",+ debt = Debt.FIVE_MINS+ )++ override fun visitCallExpression(expression: KtCallExpression) {+ super.visitCallExpression(expression)+ val method = expression.calleeExpression?.text+ if (method != "d" && method != "v") return+ val qualified = expression.parent as? KtDotQualifiedExpression ?: return+ val receiver = qualified.receiverExpression.text+ if (receiver != "Log" && receiver != "android.util.Log") return+ report(+ CodeSmell(+ issue,+ Entity.from(qualified),+ "Use GotchaLog.$method instead of raw android.util.Log.$method."+ )+ )+ }+}++/** Registers the repo's custom detekt rules. */+class GotchaRuleSetProvider : RuleSetProvider {+ override val ruleSetId: String = "gotcha"++ override fun instance(config: Config): RuleSet = RuleSet(+ ruleSetId,+ listOf(NoRawDebugLog(config))+ )+}diff --git a/detekt-rules/src/main/resources/META-INF/services/io.gitlab.arturbosch.detekt.api.RuleSetProvider b/detekt-rules/src/main/resources/META-INF/services/io.gitlab.arturbosch.detekt.api.RuleSetProvidernew file mode 100644index 0000000..e5edb81--- /dev/null+++ b/detekt-rules/src/main/resources/META-INF/services/io.gitlab.arturbosch.detekt.api.RuleSetProvider@@ -0,0 +1 @@+com.gotcha.detekt.GotchaRuleSetProviderdiff --git a/settings.gradle.kts b/settings.gradle.ktsindex d7324e4..70ce22d 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -19,3 +19,4 @@ dependencyResolutionManagement {rootProject.name = "gotcha"include(":app")+include(":detekt-rules")