Use the rules_android launcher for Kotlin Android local tests
diff --git a/MODULE.bazel b/MODULE.bazel
index 467e188..83d8ae0 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
@@ -151,6 +151,7 @@
         "com.squareup.moshi:moshi-kotlin:1.15.2",
         "com.squareup.moshi:moshi-kotlin-codegen:1.15.2",
         "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2",
+        "org.jetbrains.kotlinx:kover-jvm-agent:0.8.3",
     ],
     fail_if_repin_required = True,
     fetch_sources = True,
diff --git a/kotlin/internal/jvm/BUILD b/kotlin/internal/jvm/BUILD
index 636c305..1d77d8d 100644
--- a/kotlin/internal/jvm/BUILD
+++ b/kotlin/internal/jvm/BUILD
@@ -39,6 +39,7 @@
         "//src/main/starlark/core/pipeline",
         "//third_party:bzl",
         "@bazel_skylib//lib:sets",
+        "@bazel_skylib//lib:structs",
         "@bazel_skylib//rules:common_settings",
         "@rules_java//java:rules",
     ],
diff --git a/kotlin/internal/jvm/BUILD.release.bazel b/kotlin/internal/jvm/BUILD.release.bazel
index aae942c..1be6e79 100644
--- a/kotlin/internal/jvm/BUILD.release.bazel
+++ b/kotlin/internal/jvm/BUILD.release.bazel
@@ -29,6 +29,7 @@
     deps = [
         "//third_party:bzl",
         "@bazel_skylib//lib:sets",
+        "@bazel_skylib//lib:structs",
         "@bazel_skylib//rules:common_settings",
     ],
 )
diff --git a/kotlin/internal/jvm/kover.bzl b/kotlin/internal/jvm/kover.bzl
index 904ea72..c846263 100644
--- a/kotlin/internal/jvm/kover.bzl
+++ b/kotlin/internal/jvm/kover.bzl
@@ -34,10 +34,6 @@
 #    rules_java and Bazel core. For now, we disabled JaCoCo instrumentation accross the board,
 #    you will need to cherry-pick this PR https://github.com/uber-common/bazel/commit/cb9f6f042c64af96bbd77e21fe6fb75936c74f47
 #
-# 3. Code in `kt_android_local_test_impl.bzl` needs to be kept in sync with rules_android. There is ongoing
-#    conversation with google to simply of to extend rules_android, and override pipeline's behavior without
-#    duplicating their code, we should be able to simplify this soon.
-#
 
 load(
     "@bazel_skylib//lib:paths.bzl",
@@ -187,3 +183,21 @@
     ctx.actions.write(kover_output_metadata_file, args)
 
     return depset([kover_output_metadata_file], transitive = [instrumented_files, runtime_jars])
+
+def create_kover_runtime(ctx):
+    """Creates the agent flags and files used by Kotlin test launchers.
+
+    Args:
+        ctx: The test rule context.
+
+    Returns:
+        The agent jar, JVM flags, and runfiles needed to generate a report.
+    """
+    agent = get_kover_agent_file(ctx)
+    report, args = create_kover_agent_actions(ctx, ctx.label.name)
+    report_runfiles = create_kover_metadata_action(ctx, ctx.label.name, ctx.attr.deps + ctx.attr.associates, report)
+    return struct(
+        agent = agent,
+        report_runfiles = depset([args], transitive = [report_runfiles]),
+        jvm_flags = get_kover_jvm_flags(agent, args),
+    )
diff --git a/kotlin/internal/jvm/kt_android_local_test_impl.bzl b/kotlin/internal/jvm/kt_android_local_test_impl.bzl
index 3f17b2d..820418a 100644
--- a/kotlin/internal/jvm/kt_android_local_test_impl.bzl
+++ b/kotlin/internal/jvm/kt_android_local_test_impl.bzl
@@ -13,6 +13,7 @@
 # limitations under the License.
 """Implementation of kt_android_local_test rule."""
 
+load("@bazel_skylib//lib:structs.bzl", _structs = "structs")
 load(
     "@bazel_skylib//rules:common_settings.bzl",
     _BuildSettingInfo = "BuildSettingInfo",
@@ -26,10 +27,6 @@
     _attrs = "attrs",
 )
 load(
-    "@rules_android//rules:common.bzl",
-    _common = "common",
-)
-load(
     "@rules_android//rules:java.bzl",
     _java = "java",
 )
@@ -52,9 +49,6 @@
 load(
     "@rules_android//rules/android_local_test:impl.bzl",
     _BASE_PROCESSORS = "PROCESSORS",
-    _DEFAULT_GC_FLAGS = "DEFAULT_GC_FLAGS",
-    _DEFAULT_JIT_FLAGS = "DEFAULT_JIT_FLAGS",
-    _DEFAULT_VERIFY_FLAGS = "DEFAULT_VERIFY_FLAGS",
     _filter_jdeps = "filter_jdeps",
     _finalize = "finalize",
 )
@@ -78,15 +72,10 @@
 )
 load(
     "//kotlin/internal/jvm:kover.bzl",
-    _create_kover_agent_actions = "create_kover_agent_actions",
-    _create_kover_metadata_action = "create_kover_metadata_action",
-    _get_kover_agent_file = "get_kover_agent_file",
-    _get_kover_jvm_flags = "get_kover_jvm_flags",
+    _create_kover_runtime = "create_kover_runtime",
     _is_kover_enabled = "is_kover_enabled",
 )
 
-_JACOCOCO_CLASS = "com.google.testing.coverage.JacocoCoverageRunner"
-
 def _process_resources(ctx, java_package, manifest_ctx, **_unused_sub_ctxs):
     # Note: This needs to be kept in sync with.
     # The main difference between this and the upstream macro is that both ctx.attr.associates and ctx.attr.deps needs to
@@ -125,7 +114,39 @@
         value = resources_ctx,
     )
 
-def _process_jvm(ctx, resources_ctx, **_unused_sub_ctxs):
+def _process_coverage(ctx, **sub_ctxs):
+    if ctx.configuration.coverage_enabled and _is_kover_enabled(ctx):
+        runtime = _create_kover_runtime(ctx)
+        return _ProviderInfo(
+            name = "coverage_ctx",
+            value = struct(
+                deps = [],
+                java_start_class = ctx.attr.main_class,
+                coverage_start_class = None,
+                additional_jvm_flags = runtime.jvm_flags,
+            ),
+            runfiles = ctx.runfiles(files = [runtime.agent], transitive_files = runtime.report_runfiles),
+        )
+
+    coverage = _BASE_PROCESSORS["CoverageProcessor"](ctx, **sub_ctxs)
+    if not coverage.value.deps:
+        return coverage
+
+    android_runner = _get_android_toolchain(ctx).jacocorunner
+    kotlin_runner = ctx.toolchains[_TOOLCHAIN_TYPE].jacocorunner
+    if android_runner == kotlin_runner:
+        return coverage
+
+    # Keep the Kotlin toolchain's JaCoCo override and inherit the rest of the Android runtime.
+    value = _structs.to_dict(coverage.value)
+    value["deps"] = [kotlin_runner if dep == android_runner else dep for dep in coverage.value.deps]
+    return _ProviderInfo(
+        name = coverage.name,
+        value = struct(**value),
+        runfiles = getattr(coverage, "runfiles", None),
+    )
+
+def _process_jvm(ctx, resources_ctx, coverage_ctx, **_unused_sub_ctxs):
     """Custom JvmProcessor that handles Kotlin compilation
     """
     _compile.verify_associates_not_duplicated_in_deps(deps = getattr(ctx.attr, "deps", []), associate_deps = getattr(ctx.attr, "associates", []))
@@ -135,38 +156,10 @@
     deps = (
         [_get_android_toolchain(ctx).testsupport] +
         getattr(ctx.attr, "associates", []) +
-        getattr(ctx.attr, "deps", [])
+        getattr(ctx.attr, "deps", []) +
+        coverage_ctx.deps
     )
 
-    jvm_flags = []
-    transitive = []
-
-    if ctx.configuration.coverage_enabled:
-        if _is_kover_enabled(ctx):
-            kover_agent_file = _get_kover_agent_file(ctx)
-            kover_output_file, kover_args_file = _create_kover_agent_actions(ctx, ctx.attr.name)
-            report_runfiles = _create_kover_metadata_action(
-                ctx,
-                ctx.attr.name,
-                ctx.attr.deps + ctx.attr.associates,
-                kover_output_file,
-            )
-
-            flags = _get_kover_jvm_flags(kover_agent_file, kover_args_file)
-            jvm_flags.extend(flags)
-
-            transitive.extend([depset([kover_agent_file, kover_args_file]), report_runfiles])
-
-            java_start_class = ctx.attr.main_class
-            coverage_start_class = None
-        else:
-            deps.append(ctx.toolchains[_TOOLCHAIN_TYPE].jacocorunner)
-            java_start_class = _JACOCOCO_CLASS
-            coverage_start_class = ctx.attr.main_class
-    else:
-        java_start_class = ctx.attr.main_class
-        coverage_start_class = None
-
     # Setup the compile action.
     providers = _compile.kt_jvm_produce_output_jar_actions(
         ctx,
@@ -209,6 +202,7 @@
         runfiles.append(filtered_jdeps)
 
     # Append the security manager override
+    jvm_flags = list(coverage_ctx.additional_jvm_flags)
     java_runtime = ctx.toolchains[_JAVA_RUNTIME_TOOLCHAIN_TYPE].java_runtime
 
     _java_runtime_version = getattr(java_runtime, "version", 0)
@@ -221,169 +215,19 @@
             java_info = java_info,
             providers = providers,
             deps = deps,
-            java_start_class = java_start_class,
-            coverage_start_class = coverage_start_class,
+            java_start_class = coverage_ctx.java_start_class,
+            coverage_start_class = coverage_ctx.coverage_start_class,
             android_properties_file = ctx.file.robolectric_properties_file.short_path,
             additional_jvm_flags = jvm_flags,
         ),
-        runfiles = ctx.runfiles(
-            files = runfiles,
-            transitive_files = depset(transitive = transitive),
-        ),
+        runfiles = ctx.runfiles(files = runfiles),
     )
 
-# TODO: follow up with Google to have rules_android provide better extensibility points
-def _process_stub(ctx, deploy_jar_ctx, jvm_ctx, stub_preprocess_ctx, **_unused_sub_ctxs):
-    runfiles = []
-
-    merged_instr = None
-    if ctx.configuration.coverage_enabled:
-        if not _is_kover_enabled(ctx):
-            merged_instr = ctx.actions.declare_file(ctx.label.name + "_merged_instr.jar")
-            _java.singlejar(
-                ctx,
-                [f for f in deploy_jar_ctx.classpath.to_list() if f.short_path.endswith(".jar")],
-                merged_instr,
-                mnemonic = "JavaDeployJar",
-                include_build_data = True,
-                java_toolchain = _common.get_java_toolchain(ctx),
-            )
-            runfiles.append(merged_instr)
-
-    stub = ctx.actions.declare_file(ctx.label.name)
-    classpath_file = ctx.actions.declare_file(ctx.label.name + "_classpath")
-    runfiles.append(classpath_file)
-    test_class = _get_test_class(ctx)
-
-    _create_stub(
-        ctx,
-        stub_preprocess_ctx.substitutes,
-        stub,
-        classpath_file,
-        deploy_jar_ctx.classpath,
-        _get_jvm_flags(ctx, test_class, jvm_ctx.android_properties_file, jvm_ctx.additional_jvm_flags),
-        jvm_ctx.java_start_class,
-        jvm_ctx.coverage_start_class,
-        merged_instr,
-    )
-    return _ProviderInfo(
-        name = "stub_ctx",
-        value = struct(
-            stub = stub,
-        ),
-        runfiles = ctx.runfiles(
-            files = runfiles,
-            transitive_files = depset(
-                transitive = stub_preprocess_ctx.runfiles,
-            ),
-        ),
-    )
-
-def _get_test_class(ctx):
-    # Use the specified test_class if set
-    if ctx.attr.test_class != "":
-        return ctx.attr.test_class
-
-    # Use a heuristic based on the rule name and the "srcs" list
-    # to determine the primary Java class.
-    expected = "/" + ctx.label.name + ".java"
-    for f in ctx.attr.srcs:
-        path = f.label.package + "/" + f.label.name
-        if path.endswith(expected):
-            return _java.resolve_package(path[:-5])
-
-    fail("test_class could not be derived for " + str(ctx.label) +
-         ". Explicitly set test_class or move this source file to " +
-         "a java source root.")
-
-def _create_stub(
-        ctx,
-        substitutes,
-        stub_file,
-        classpath_file,
-        runfiles,
-        jvm_flags,
-        java_start_class,
-        coverage_start_class,
-        merged_instr):
-    subs = {
-        # To avoid cracking open the depset, classpath is read from a separate
-        # file created in its own action. Needed as expand_template does not
-        # support ctx.actions.args().
-        "%classpath%": "$(eval echo $(<%s))" % (classpath_file.short_path),
-        "%java_start_class%": java_start_class,
-        "%jvm_flags%": " ".join(jvm_flags),
-        "%needs_runfiles%": "1",
-        "%runfiles_manifest_only%": "",
-        "%workspace_prefix%": ctx.workspace_name + "/",
-    }
-
-    if coverage_start_class:
-        prefix = ctx.attr._runfiles_root_prefix[_BuildSettingInfo].value
-        subs["%set_jacoco_metadata%"] = (
-            "export JACOCO_METADATA_JAR=${JAVA_RUNFILES}/" + prefix +
-            merged_instr.short_path
-        )
-        subs["%set_jacoco_main_class%"] = (
-            "export JACOCO_MAIN_CLASS=" + coverage_start_class
-        )
-        subs["%set_jacoco_java_runfiles_root%"] = (
-            "export JACOCO_JAVA_RUNFILES_ROOT=${JAVA_RUNFILES}/" + prefix
-        )
-    else:
-        subs["%set_jacoco_metadata%"] = ""
-        subs["%set_jacoco_main_class%"] = ""
-        subs["%set_jacoco_java_runfiles_root%"] = ""
-
-    subs.update(substitutes)
-
-    ctx.actions.expand_template(
-        template = _utils.only(_get_android_toolchain(ctx).java_stub.files.to_list()),
-        output = stub_file,
-        substitutions = subs,
-        is_executable = True,
-    )
-
-    args = ctx.actions.args()
-    args.add_joined(
-        runfiles,
-        join_with = ":",
-        map_each = _get_classpath,
-    )
-    args.set_param_file_format("multiline")
-    ctx.actions.write(
-        output = classpath_file,
-        content = args,
-    )
-    return stub_file
-
-def _get_classpath(s):
-    return "${J3}" + s.short_path
-
-def _get_jvm_flags(ctx, main_class, robolectric_properties_path, additional_jvm_flags):
-    return [
-        "-ea",
-        "-Dbazel.test_suite=" + main_class,
-        "-Drobolectric.offline=true",
-        "-Drobolectric-deps.properties=" + robolectric_properties_path,
-        "-Duse_framework_manifest_parser=true",
-        "-Drobolectric.logging=stdout",
-        "-Drobolectric.logging.enabled=true",
-        "-Dorg.robolectric.packagesToNotAcquire=com.google.testing.junit.runner.util",
-    ] + _DEFAULT_JIT_FLAGS + _DEFAULT_GC_FLAGS + _DEFAULT_VERIFY_FLAGS + additional_jvm_flags + [
-        ctx.expand_make_variables(
-            "jvm_flags",
-            ctx.expand_location(flag, ctx.attr.data),
-            {},
-        )
-        for flag in ctx.attr.jvm_flags
-    ]
-
 PROCESSORS = _processing_pipeline.replace(
     _BASE_PROCESSORS,
     ResourceProcessor = _process_resources,
+    CoverageProcessor = _process_coverage,
     JvmProcessor = _process_jvm,
-    StubProcessor = _process_stub,
 )
 
 _PROCESSING_PIPELINE = _processing_pipeline.make_processing_pipeline(
diff --git a/kotlin/internal/jvm/kt_jvm_test.bzl b/kotlin/internal/jvm/kt_jvm_test.bzl
index 7056db7..fb0ebbd 100644
--- a/kotlin/internal/jvm/kt_jvm_test.bzl
+++ b/kotlin/internal/jvm/kt_jvm_test.bzl
@@ -26,10 +26,7 @@
 load("//kotlin/internal/jvm:compile.bzl", _compile = "compile")
 load(
     "//kotlin/internal/jvm:kover.bzl",
-    _create_kover_agent_actions = "create_kover_agent_actions",
-    _create_kover_metadata_action = "create_kover_metadata_action",
-    _get_kover_agent_file = "get_kover_agent_file",
-    _get_kover_jvm_flags = "get_kover_jvm_flags",
+    _create_kover_runtime = "create_kover_runtime",
     _is_kover_enabled = "is_kover_enabled",
 )
 load(
@@ -87,20 +84,10 @@
 
     if ctx.configuration.coverage_enabled:
         if _is_kover_enabled(ctx):
-            kover_agent_file = _get_kover_agent_file(ctx)
-            kover_output_file, kover_args_file = _create_kover_agent_actions(ctx, ctx.attr.name)
-            report_runfiles = _create_kover_metadata_action(
-                ctx,
-                ctx.attr.name,
-                ctx.attr.deps + ctx.attr.associates,
-                kover_output_file,
-            )
-            flags = _get_kover_jvm_flags(kover_agent_file, kover_args_file)
-
-            # add Kover agent jvm_flag, inputs and outputs
-            coverage_jvm_flags = flags
-            coverage_inputs = [depset([kover_agent_file])]
-            coverage_runfiles = depset([kover_args_file], transitive = [report_runfiles])
+            runtime = _create_kover_runtime(ctx)
+            coverage_jvm_flags = runtime.jvm_flags
+            coverage_inputs = [depset([runtime.agent])]
+            coverage_runfiles = runtime.report_runfiles
         else:
             jacocorunner = ctx.toolchains[_TOOLCHAIN_TYPE].jacocorunner
             coverage_runfiles = jacocorunner.files
diff --git a/kotlin_rules_maven_test_install.json b/kotlin_rules_maven_test_install.json
index b965c49..86c81c6 100644
--- a/kotlin_rules_maven_test_install.json
+++ b/kotlin_rules_maven_test_install.json
@@ -13,6 +13,7 @@
     "javax.inject:javax.inject": -297932879,
     "junit:junit": 373369075,
     "org.jetbrains.kotlinx:kotlinx-coroutines-core": 1254427323,
+    "org.jetbrains.kotlinx:kover-jvm-agent": -677408209,
     "repositories": 582576641
   },
   "__RESOLVED_ARTIFACTS_HASH": {
@@ -97,6 +98,8 @@
     "org.jetbrains.kotlin:kotlin-stdlib:jar:sources": 1119042874,
     "org.jetbrains.kotlinx:kotlinx-coroutines-core": -2101682300,
     "org.jetbrains.kotlinx:kotlinx-coroutines-core:jar:sources": -1493138165,
+    "org.jetbrains.kotlinx:kover-jvm-agent": -165399876,
+    "org.jetbrains.kotlinx:kover-jvm-agent:jar:sources": 768828662,
     "org.jetbrains:annotations": 554168982,
     "org.jetbrains:annotations:jar:sources": 1226441379,
     "org.jspecify:jspecify": 117231129,
@@ -391,6 +394,13 @@
       },
       "version": "1.4.2"
     },
+    "org.jetbrains.kotlinx:kover-jvm-agent": {
+      "shasums": {
+        "jar": "3c07bdf995edce414d078dbd9725cd78c49f9cce871831264d09fa1f7ea067ed",
+        "sources": "d296554c07918b237cd464071b169944fdf01f0dc620671100faee817d9cc736"
+      },
+      "version": "0.8.3"
+    },
     "org.jetbrains:annotations": {
       "shasums": {
         "jar": "ace2a10dc8e2d5fd34925ecac03e4988b2c0f851650c94b8cef49ba1bd111478",
@@ -964,6 +974,31 @@
       "kotlinx.coroutines.sync",
       "kotlinx.coroutines.test"
     ],
+    "org.jetbrains.kotlinx:kover-jvm-agent": [
+      "com.intellij.rt.coverage.data",
+      "com.intellij.rt.coverage.data.instructions",
+      "com.intellij.rt.coverage.instrumentation",
+      "com.intellij.rt.coverage.instrumentation.data",
+      "com.intellij.rt.coverage.instrumentation.dataAccess",
+      "com.intellij.rt.coverage.instrumentation.filters",
+      "com.intellij.rt.coverage.instrumentation.filters.branches",
+      "com.intellij.rt.coverage.instrumentation.filters.classFilter",
+      "com.intellij.rt.coverage.instrumentation.filters.classes",
+      "com.intellij.rt.coverage.instrumentation.filters.compose",
+      "com.intellij.rt.coverage.instrumentation.filters.lines",
+      "com.intellij.rt.coverage.instrumentation.filters.methods",
+      "com.intellij.rt.coverage.instrumentation.testTracking",
+      "com.intellij.rt.coverage.instrumentation.util",
+      "com.intellij.rt.coverage.main",
+      "com.intellij.rt.coverage.report",
+      "com.intellij.rt.coverage.util",
+      "com.intellij.rt.coverage.util.classFinder",
+      "kotlinx.kover.jvmagent",
+      "org.jetbrains.coverage.gnu.trove",
+      "org.jetbrains.coverage.org.objectweb.asm",
+      "org.jetbrains.coverage.org.objectweb.asm.commons",
+      "org.jetbrains.coverage.org.objectweb.asm.tree"
+    ],
     "org.jetbrains:annotations": [
       "org.intellij.lang.annotations",
       "org.jetbrains.annotations"
@@ -1059,6 +1094,8 @@
       "org.jetbrains.kotlin:kotlin-stdlib:jar:sources",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core:jar:sources",
+      "org.jetbrains.kotlinx:kover-jvm-agent",
+      "org.jetbrains.kotlinx:kover-jvm-agent:jar:sources",
       "org.jetbrains:annotations",
       "org.jetbrains:annotations:jar:sources",
       "org.jspecify:jspecify",
@@ -1148,6 +1185,8 @@
       "org.jetbrains.kotlin:kotlin-stdlib:jar:sources",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core:jar:sources",
+      "org.jetbrains.kotlinx:kover-jvm-agent",
+      "org.jetbrains.kotlinx:kover-jvm-agent:jar:sources",
       "org.jetbrains:annotations",
       "org.jetbrains:annotations:jar:sources",
       "org.jspecify:jspecify",
@@ -1237,6 +1276,8 @@
       "org.jetbrains.kotlin:kotlin-stdlib:jar:sources",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core",
       "org.jetbrains.kotlinx:kotlinx-coroutines-core:jar:sources",
+      "org.jetbrains.kotlinx:kover-jvm-agent",
+      "org.jetbrains.kotlinx:kover-jvm-agent:jar:sources",
       "org.jetbrains:annotations",
       "org.jetbrains:annotations:jar:sources",
       "org.jspecify:jspecify",
diff --git a/src/test/starlark/android_local_test/BUILD.bazel b/src/test/starlark/android_local_test/BUILD.bazel
new file mode 100644
index 0000000..0d54643
--- /dev/null
+++ b/src/test/starlark/android_local_test/BUILD.bazel
@@ -0,0 +1,47 @@
+load("@rules_java//java:java_library.bzl", "java_library")
+load("//kotlin:android.bzl", "kt_android_local_test")
+load("//kotlin:core.bzl", "define_kt_toolchain")
+load(":coverage_test.bzl", "coverage_off_test", "jacoco_test", "kover_test")
+
+kt_android_local_test(
+    name = "CoverageTest",
+    srcs = ["com/example/CoverageTest.kt"],
+    custom_package = "com.example",
+    env = {"LAUNCHER_ENV": "from_android_local_test"},
+    tags = ["manual"],
+    test_class = "com.example.CoverageTest",
+    deps = ["@kotlin_rules_maven_test//:junit_junit"],
+)
+
+define_kt_toolchain(
+    name = "kover_toolchain",
+    experimental_kover_agent = "@kotlin_rules_maven_test//:org_jetbrains_kotlinx_kover_jvm_agent",
+    experimental_kover_enabled = True,
+)
+
+java_library(
+    name = "custom_jacoco_runner",
+    # Give this runner its own jar so the test can distinguish it from the Android toolchain default.
+    resources = ["com/example/CoverageTest.kt"],
+    exports = ["@remote_java_tools//:jacoco_coverage_runner"],
+)
+
+define_kt_toolchain(
+    name = "jacoco_toolchain",
+    jacocorunner = ":custom_jacoco_runner",
+)
+
+coverage_off_test(
+    name = "coverage_off",
+    target_under_test = ":CoverageTest",
+)
+
+jacoco_test(
+    name = "jacoco",
+    target_under_test = ":CoverageTest",
+)
+
+kover_test(
+    name = "kover",
+    target_under_test = ":CoverageTest",
+)
diff --git a/src/test/starlark/android_local_test/com/example/CoverageTest.kt b/src/test/starlark/android_local_test/com/example/CoverageTest.kt
new file mode 100644
index 0000000..c75afc3
--- /dev/null
+++ b/src/test/starlark/android_local_test/com/example/CoverageTest.kt
@@ -0,0 +1,11 @@
+package com.example
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class CoverageTest {
+  @Test
+  fun launcherPassesTestEnvironment() {
+    assertEquals("from_android_local_test", System.getenv("LAUNCHER_ENV"))
+  }
+}
diff --git a/src/test/starlark/android_local_test/coverage_test.bzl b/src/test/starlark/android_local_test/coverage_test.bzl
new file mode 100644
index 0000000..fa440d0
--- /dev/null
+++ b/src/test/starlark/android_local_test/coverage_test.bzl
@@ -0,0 +1,62 @@
+"""Coverage runtime checks for kt_android_local_test."""
+
+load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts")
+load("@rules_java//java/common:java_info.bzl", "JavaInfo")
+
+def _coverage_test_impl(ctx):
+    env = analysistest.begin(ctx)
+    target = analysistest.target_under_test(env)
+    actions = analysistest.target_actions(env)
+    executable = target[DefaultInfo].files_to_run.executable
+    subs = [a.substitutions for a in actions if executable in a.outputs.to_list()][0]
+    jacoco = ctx.attr.mode == "jacoco"
+    kover = ctx.attr.mode == "kover"
+
+    runner = "com.google.testing.junit.runner.BazelTestRunner"
+    deploy_jar = target.label.name + "_deploy.jar"
+    asserts.true(env, deploy_jar in subs["%classpath%"], msg = "Android launcher uses the deploy jar")
+    asserts.equals(env, "com.google.testing.coverage.JacocoCoverageRunner" if jacoco else runner, subs["%java_start_class%"])
+    asserts.equals(env, "export JACOCO_MAIN_CLASS=" + runner if jacoco else "", subs["%set_jacoco_main_class%"])
+    if jacoco:
+        asserts.true(env, deploy_jar in subs["%set_jacoco_metadata%"], msg = "JaCoCo uses the deploy jar for metadata")
+    else:
+        asserts.equals(env, "", subs["%set_jacoco_metadata%"])
+
+    runtime_jars = target[JavaInfo].transitive_runtime_jars.to_list()
+    asserts.equals(env, jacoco, any([f.basename == "libcustom_jacoco_runner.jar" for f in runtime_jars]))
+    asserts.equals(env, jacoco, any(["jacoco" in f.basename.lower() for f in runtime_jars]))
+    argv = [a.argv for a in actions if a.mnemonic == "KotlinCompile"][0]
+    asserts.equals(env, "true" if jacoco else "false", argv[argv.index("--instrument_coverage") + 1])
+
+    runfiles = target[DefaultInfo].default_runfiles.files.to_list()
+    flags = subs["%jvm_flags%"].split(" ")
+    agents = [f for f in runfiles if "kover-jvm-agent" in f.basename and f.extension == "jar"]
+    args = [f for f in runfiles if f.basename.endswith("-kover.args.txt")]
+    metadata = [f for f in runfiles if f.basename.endswith("-kover_metadata.txt")]
+    asserts.equals(env, 1 if kover else 0, len(agents), msg = "agent jars in runfiles")
+    asserts.equals(env, 1 if kover else 0, len(args), msg = "agent argument files in runfiles")
+    asserts.equals(env, 1 if kover else 0, len(metadata), msg = "CLI metadata files in runfiles")
+    if kover and agents and args:
+        asserts.true(env, "-Xbootclasspath/a:" + agents[0].short_path in flags)
+        asserts.true(env, "-javaagent:%s=file:%s" % (agents[0].short_path, args[0].short_path) in flags)
+    else:
+        asserts.false(env, any([f.startswith(("-javaagent:", "-Xbootclasspath/a:")) for f in flags]))
+    return analysistest.end(env)
+
+def _coverage_test(mode):
+    return analysistest.make(
+        _coverage_test_impl,
+        attrs = {"mode": attr.string(default = mode)},
+        config_settings = {
+            "//command_line_option:collect_code_coverage": mode != "off",
+            "//command_line_option:extra_toolchains": [
+                "//src/test/starlark/android_local_test:jacoco_toolchain" if mode == "jacoco" else "//src/test/starlark/android_local_test:kover_toolchain",
+            ],
+            "//command_line_option:instrument_test_targets": True,
+            "//command_line_option:instrumentation_filter": "//src/test/starlark/android_local_test",
+        },
+    )
+
+coverage_off_test = _coverage_test("off")
+jacoco_test = _coverage_test("jacoco")
+kover_test = _coverage_test("kover")