Test-per-coverage : JaCoCo offline instrumentation with gradle. Agent not started error

I am trying to get a coverage per test using jacoco offline instrumentation and Gradle test listeners
(details are at https://stackoverflow.com/questions/64402342/coverage-per-test-using-jacoco-offline-instrumentation-java-lang-noclassdeffound)

task sampletest(type: Test) {
//    debug true
    ignoreFailures = true

    println classpath.asPath

    forkEvery 1
    maxParallelForks 1

    doFirst {

        println "org.jacoco.agent.rt.RT loaded from "+ org.jacoco.agent.rt.RT.class.getProtectionDomain().getCodeSource();
        systemProperty 'jacoco-agent.destfile', buildDir.path + '/jacoco/atests.exec'
        classpath = files(instrument.outputDir) + classpath +   configurations.jacocoRuntime
        println classpath.asPath

    }
    beforeTest { TestDescriptor descriptor->
        println "org.jacoco.agent.rt.RT loaded from "+ org.jacoco.agent.rt.RT.class.getProtectionDomain().getCodeSource();
    }
    afterTest { TestDescriptor descriptor->
        def agent=org.jacoco.agent.rt.RT.agent
        agent.sessionId=descriptor.name
        agent.dump(true)
    }
}

Test run after instrumentation. The exec files is produced and has the data. What I am looking at is a way to reset the session between test. Accessing the Agent gives the error “Agent not started”.