Remove stdlib (#97)

* ensure jar normalization

* fix embed resources hash

* make the hashing test local and add ij runconfig

* remove kotlin_stdlib, refactor bootstrap macro, reorganize source to start working on a task model for the builder
diff --git a/.bazelproject b/.bazelproject
index f0131cf..3c59298 100644
--- a/.bazelproject
+++ b/.bazelproject
@@ -18,9 +18,12 @@
 
 targets:
   -//docs/...
-  //kotlin/builder:for_ide
   //:all_local_tests
   //examples/...
+  # These targets are built for the ide only. Primary purpose is to ensure the builder can build the targets, but it's a
+  # also a good way of testing the intellij plugin.
+  //kotlin/builder/src/io/bazel/kotlin/builder:builder_for_ide
+  //kotlin/builder:compiler_lib_for_ide
 
 test_sources:
   */unittests/*
diff --git a/BUILD b/BUILD
index 886f2de..a0e589f 100644
--- a/BUILD
+++ b/BUILD
@@ -16,8 +16,8 @@
 test_suite(
     name = "all_tests",
     tests = [
-        "//kotlin/builder:unittests",
-        "//kotlin/builder:integrationtests",
+        "//kotlin/builder/unittests",
+        "//kotlin/builder/integrationtests",
         "//tests/integrationtests"
     ]
 )
diff --git a/docs/BUILD b/docs/BUILD
index dda09b8..8943957 100644
--- a/docs/BUILD
+++ b/docs/BUILD
@@ -1,35 +1,35 @@
 load("@bazel_skylib//:skylark_library.bzl", "skylark_library")
-load("@io_bazel_skydoc//skylark:skylark.bzl", "skylark_doc" )
+load("@io_bazel_skydoc//skylark:skylark.bzl", "skylark_doc")
 
 skylark_library(
     name = "doc_public",
     srcs = ["//kotlin:kotlin.bzl"],
-    visibility=["//visibility:private"]
+    visibility = ["//visibility:private"],
 )
 
 skylark_library(
     name = "doc_toolchains",
     srcs = ["//kotlin:toolchains.bzl"],
-    visibility=["//visibility:private"]
+    visibility = ["//visibility:private"],
 )
 
 skylark_doc(
     name = "docs",
     srcs = [
         ":doc_public",
-        ":doc_toolchains"
+        ":doc_toolchains",
     ],
     format = "html",
     site_root = select({
         ":local": "/tmp/rules_kotlin",
-        "//conditions:default": "https://bazelbuild.github.io/rules_kotlin"
+        "//conditions:default": "https://bazelbuild.github.io/rules_kotlin",
     }),
-    visibility = ["//visibility:public"]
+    visibility = ["//visibility:public"],
 )
 
 config_setting(
     name = "local",
     values = {
         "define": "local=1",
-    }
-)
\ No newline at end of file
+    },
+)
diff --git a/examples/BUILD b/examples/BUILD
index 95da0c6..dea9df6 100644
--- a/examples/BUILD
+++ b/examples/BUILD
@@ -11,4 +11,4 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-package(default_visibility = ["//visibility:private"])
\ No newline at end of file
+package(default_visibility = ["//visibility:private"])
diff --git a/examples/dagger/BUILD b/examples/dagger/BUILD
index 5f5c2ff..94ccdc9 100644
--- a/examples/dagger/BUILD
+++ b/examples/dagger/BUILD
@@ -17,29 +17,29 @@
 
 java_plugin(
     name = "dagger_plugin",
+    processor_class = "dagger.internal.codegen.ComponentProcessor",
     deps = [
-        "//third_party/jvm/com/google/dagger:dagger_compiler",
-        "@//third_party/jvm/com/google/guava",
-        "//third_party/jvm/com/google/dagger:dagger_producers",
         "//third_party/jvm/com/google/dagger",
-        "//third_party/jvm/javax/inject:javax_inject"
+        "//third_party/jvm/com/google/dagger:dagger_compiler",
+        "//third_party/jvm/com/google/dagger:dagger_producers",
+        "//third_party/jvm/javax/inject:javax_inject",
+        "@//third_party/jvm/com/google/guava",
     ],
-    processor_class = "dagger.internal.codegen.ComponentProcessor"
 )
 
 java_library(
     name = "dagger_lib",
+    exported_plugins = ["dagger_plugin"],
     exports = [
+        "//third_party/jvm/com/google/dagger",
         "//third_party/jvm/javax/inject:javax_inject",
-        "//third_party/jvm/com/google/dagger"
     ],
-    exported_plugins = ["dagger_plugin"]
 )
 
 # Generate a srcjar to validate intellij plugin correctly attaches it.
 genrule(
     name = "tea_lib_src",
-    tools = ["@local_jdk//:jdk"],
+    outs = ["test.srcjar"],
     cmd = """
 cat << EOF > TeaPot.kt
 package tea
@@ -51,27 +51,27 @@
 external/local_jdk/bin/jar -cf $@ TeaPot.kt
 rm TeaPot.kt
 """,
-    outs = ["test.srcjar"]
+    tools = ["@local_jdk//:jdk"],
 )
 
 kt_jvm_library(
     name = "tea_lib",
-    srcs = [":tea_lib_src"]
+    srcs = [":tea_lib_src"],
 )
 
 kt_jvm_library(
     name = "coffee_lib",
     srcs = glob(["src/**"]),
     deps = [
-        ":tea_lib",
         ":dagger_lib",
-        "//third_party:kotlinx_coroutines"
+        ":tea_lib",
+        "//third_party:kotlinx_coroutines",
     ],
 )
 
 java_binary(
     name = "coffee_app",
     main_class = "coffee.CoffeeApp",
+    visibility = ["//visibility:public"],
     runtime_deps = [":coffee_lib"],
-    visibility = ["//visibility:public"]
 )
diff --git a/kotlin/BUILD.com_github_jetbrains_kotlin b/kotlin/BUILD.com_github_jetbrains_kotlin
new file mode 100644
index 0000000..e5a5b17
--- /dev/null
+++ b/kotlin/BUILD.com_github_jetbrains_kotlin
@@ -0,0 +1,66 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+package(default_visibility = ["//visibility:public"])
+
+# Kotlin home filegroup containing everything that is needed.
+filegroup(
+    name = "home",
+    srcs = glob(["**"]),
+)
+
+# Kotlin dependencies that are internal to this repo and are meant to be loaded at runtime.
+[
+    java_import(
+        name = "%s" % art,
+        jars = ["lib/%s.jar" % art],
+        neverlink = 1,
+    )
+    for art in [
+        "kotlin-annotation-processing",
+        "kotlin-annotation-processing-runtime",
+        "kotlin-compiler",
+    ]
+]
+
+# Kotlin dependencies that are internal to this repo and may be linked.
+[
+    java_import(
+        name = "%s" % art,
+        jars = ["lib/%s.jar" % art],
+    )
+    for art in [
+        "kotlin-preloader",
+    ]
+]
+
+load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_import")
+
+#  The Kotlin standard libraries. These should be setup in a Toolchain.
+[
+    kt_jvm_import(
+        name = "kotlin-%s" % art,
+        jars = ["lib/kotlin-%s.jar" % art],
+        srcjar = "lib/kotlin-%s-sources.jar" % art,
+        visibility = ["//visibility:public"],
+    )
+    for art in [
+        "runtime",
+        "stdlib",
+        "stdlib-jdk7",
+        "stdlib-jdk8",
+        "reflect",
+        "test",
+        "script-runtime",
+    ]
+]
diff --git a/kotlin/builder/BUILD b/kotlin/builder/BUILD
index 7a104a5..b11de2a 100644
--- a/kotlin/builder/BUILD
+++ b/kotlin/builder/BUILD
@@ -11,83 +11,34 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-load("//kotlin/builder:bootstrap.bzl", "kotlin_worker_lib")
-load("//kotlin:kotlin.bzl", "kt_jvm_library")
-
-# Should not be linked against to allow the compiler workspace to be switched out when toolchains support this.
-COMPILER_DEPS = [
-    "@com_github_jetbrains_kotlin//:compiler",
-    "@com_github_jetbrains_kotlin//:kotlin-annotation-processing",
-    "@com_github_jetbrains_kotlin//:kotlin-script-runtime",
-]
-
-# Common depset for the builder.
-COMMON_DEPS = [
-    "//kotlin/builder/proto:deps",
-    "//kotlin/builder/proto:kotlin_model",
-    "//kotlin/builder/proto:worker",
-    "@com_github_jetbrains_kotlin//:preloader",
-    "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java//jar",
-    "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java_util//jar",
-    "@io_bazel_rules_kotlin_com_google_inject_guice//jar",
-    "@io_bazel_rules_kotlin_aopalliance_aopalliance//jar",
-    "@io_bazel_rules_kotlin_javax_inject_javax_inject//jar",
-    "@io_bazel_rules_kotlin_com_google_guava_guava//jar",
-    "@io_bazel_rules_kotlin_com_google_code_gson_gson//jar",
-    "@com_github_jetbrains_kotlin//:kotlin-reflect",
-    "@com_github_jetbrains_kotlin//:kotlin-stdlib",
-    "@com_github_jetbrains_kotlin//:kotlin-stdlib-jdk7",
-    "@com_github_jetbrains_kotlin//:kotlin-stdlib-jdk8",
-]
+load("//kotlin/builder:bootstrap.bzl", "kt_bootstrap_library")
 
 # The compiler library, this is co-located in the kotlin compiler classloader.
-kotlin_worker_lib(
+kt_bootstrap_library(
     name = "compiler_lib",
     srcs = glob(["src/io/bazel/kotlin/compiler/**/*.kt"]),
-    args = [
-        "-jvm-target","1.8",
+    neverlink_deps = [
+        "@com_github_jetbrains_kotlin//:kotlin-compiler",
+        "@com_github_jetbrains_kotlin//:kotlin-annotation-processing",
+        "@com_github_jetbrains_kotlin//:kotlin-script-runtime",
     ],
-    neverlink_deps = COMPILER_DEPS,
-)
-
-# The builder library.
-kotlin_worker_lib(
-    name = "builder_lib",
-    srcs = glob(["src/io/bazel/kotlin/builder/**/*.kt"]),
-    args = [
-        "-jvm-target","1.8",
-    ],
-    deps = COMMON_DEPS
-)
-
-# This is a hack so that the builder and compiler sources can be picked up by intellij.
-kt_jvm_library(
-    name = "for_ide",
-    srcs = glob(["src/**/*.kt"]),
-    visibility = ["//visibility:private"],
-    deps = COMMON_DEPS + COMPILER_DEPS,
 )
 
 # The builder artifact.
 java_binary(
     name = "builder",
+    data = [":compiler_lib.jar"],
     main_class = "io.bazel.kotlin.builder.KotlinBuilder",
     visibility = ["//visibility:public"],
-    runtime_deps = [
-        ":builder_lib",
-    ],
-    data = [
-        ":compiler_lib.jar"
-    ]
+    runtime_deps = ["//kotlin/builder/src/io/bazel/kotlin/builder"],
 )
 
-# This is defined so that tests can wire up a builder.
 filegroup(
-    name = "builder_runfiles_for_tests",
+    name = "data_for_tests",
     srcs = [
-        ":compiler_lib.jar",
-        "@com_github_jetbrains_kotlin//:compiler",
+        ":compiler_lib",
         "@com_github_jetbrains_kotlin//:kotlin-annotation-processing",
+        "@com_github_jetbrains_kotlin//:kotlin-compiler",
         "@com_github_jetbrains_kotlin//:kotlin-script-runtime",
     ],
     testonly = 1,
@@ -95,32 +46,25 @@
 )
 
 java_library(
-    name = "builder_for_tests",
-    testonly = 1,
-    exports = COMMON_DEPS + [
-        ":builder_lib",
-        ":compiler_lib",
+    name = "builder_lib_for_tests",
+    runtime_deps = [
+        "@com_github_jetbrains_kotlin//:kotlin-reflect",
+        "@io_bazel_rules_kotlin_aopalliance_aopalliance//jar",
     ],
-    data = [
-        "builder_runfiles_for_tests"
-    ]
-)
-
-java_test(
-    name = "integrationtests",
-    srcs = glob(["integrationtests/*.java"]),
-    test_class = "io.bazel.kotlin.builder.KotlinBuilderTestSuite",
-    deps = [
-        "//kotlin/builder:builder_for_tests",
+    testonly = 1,
+    data = [":data_for_tests"],
+    exports = [
+        "//kotlin/builder/src/io/bazel/kotlin/builder",
         "//third_party/jvm/com/google/truth",
         "//third_party/jvm/junit",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:deps",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:kotlin_model",
+        "@io_bazel_rules_kotlin_com_google_guava_guava//jar",
+        "@io_bazel_rules_kotlin_com_google_inject_guice//jar",
+        "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java//jar",
     ],
-)
-
-java_test(
-    name = "unittests",
-    size = "small",
-    srcs = glob(["unittests/**/*.java"]),
-    test_class = "io.bazel.kotlin.builder.mode.jvm.utils.JdepsParserTest",
-    deps = [":builder_for_tests"],
+    visibility = [
+        "//kotlin/builder/integrationtests:__subpackages__",
+        "//kotlin/builder/unittests:__subpackages__"
+    ]
 )
diff --git a/kotlin/builder/bootstrap.bzl b/kotlin/builder/bootstrap.bzl
index 2dac1df..67f8c21 100644
--- a/kotlin/builder/bootstrap.bzl
+++ b/kotlin/builder/bootstrap.bzl
@@ -11,72 +11,86 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-load("//kotlin:kotlin.bzl", _for_ide = "kt_jvm_library", "kt_jvm_import")
+load("//kotlin:kotlin.bzl", _for_ide = "kt_jvm_library")
 
-_HEADER = """
-function join_by { local IFS="$$1"; shift; echo "$$*"; }
+_BOOTSTRAP_LIB_ARGS=["-jvm-target","1.8"]
 
-CP=$$(join_by : $(locations :%s))
-"""
+def _resolve_dep_label(d):
+    if d.startswith("//kotlin/builder/src/io/bazel/kotlin/builder") and not d.endswith("_for_ide"):
+        prefix, _, target = d.rpartition(":")
+        if target == None:
+            # untested
+            return d + "_for_ide"
+        else:
+            _ , _, target = d.rpartition("/")
+            return d + ":" + target + "_for_ide"
+    else:
+        return d
 
-# We manually call the Kotlin compiler by constructing the correct Java classpath, because the usual
-# "kotlinc" wrapper script fails to correctly detect KOTLIN_HOME unless we run with
-# --spawn_strategy=standalone
-def _gen_cmd(name, args):
-    return (_HEADER + """
-ARGS="%s"
+def kt_bootstrap_library(name, srcs, deps=[], neverlink_deps=[], runtime_deps=[]):
+    """
+    Simple compilation of a kotlin library using a non-persistent worker. The target is a JavaInfo provider.
 
-KOTLIN_HOME=external/com_github_jetbrains_kotlin
-java -Xmx256M -Xms32M -noverify \
-  -cp $${KOTLIN_HOME}/lib/kotlin-preloader.jar org.jetbrains.kotlin.preloading.Preloader \
-  -cp $${KOTLIN_HOME}/lib/kotlin-compiler.jar org.jetbrains.kotlin.cli.jvm.K2JVMCompiler \
-  -cp $${CP} -d $(OUTS) $${ARGS} $(SRCS)
-""") % (name,args)
+    The target is tagged `"no-ide"` as intellij can't compile it. A seperate private target is created which is suffixed
+    with `_for_ide`. If the dep is under the package `//kotlin/builder/src/io/bazel/kotlin/builder/...` then it will be
+    added to the `_for_ide` target by adding a `_for_ide` prefix.
 
-def kotlin_worker_lib(name, srcs, args = [], deps=[], runtime_deps=[], neverlink_deps=[]):
+    deps: the dependenices, the are setup as runtime_deps of the library.
+    neverlink_deps: deps that won't be linked. These deps are added to the `"for_ide"` target.
+    """
+    jar_label = name + "_jar"
     dep_label = name + "_deps"
-    jar_file_label =  name + "_file"
-    jar_name = name+".jar"
-    jar_sources_file_label = jar_file_label + "_sources"
-    jar_sources_name = name + "-sources.jar"
-
     native.filegroup(
         name = dep_label,
         srcs = deps + neverlink_deps,
-        visibility = ["//visibility:private"]
+        visibility=["//visibility:private"]
     )
+    command="""
+KOTLIN_HOME=external/com_github_jetbrains_kotlin
+
+function join_by { local IFS="$$1"; shift; echo "$$*"; }
+
+NAME=%s
+CP="$$(join_by : $(locations :%s))"
+ARGS="%s"
+
+java -Xmx256M -Xms32M -noverify \
+  -cp $${KOTLIN_HOME}/lib/kotlin-preloader.jar org.jetbrains.kotlin.preloading.Preloader \
+  -cp $${KOTLIN_HOME}/lib/kotlin-compiler.jar org.jetbrains.kotlin.cli.jvm.K2JVMCompiler \
+  -cp $${CP} -d $${NAME}_temp.jar $${ARGS} $(SRCS)
+
+$(location @bazel_tools//tools/jdk:singlejar) \
+    --normalize \
+    --compression \
+    --sources $${NAME}_temp.jar \
+    --output $(OUTS)
+
+rm $${NAME}_temp.jar
+""" % (name, dep_label, " ".join(_BOOTSTRAP_LIB_ARGS))
     native.genrule(
-        name = jar_file_label,
+        name =  jar_label,
         tools = [
             "@com_github_jetbrains_kotlin//:home",
             "@local_jdk//:jdk",
+            "@bazel_tools//tools/jdk:singlejar",
             dep_label
         ],
         srcs = srcs,
-        outs = [jar_name],
-        cmd = _gen_cmd(dep_label, " ".join(args)),
-        visibility = ["//visibility:private"]
-    )
-    native.genrule(
-        name = jar_sources_file_label,
-        tools = [
-            "@local_jdk//:jdk",
-        ],
-        srcs = srcs,
-        outs = [jar_sources_name],
-        cmd = "jar cf $(OUTS) $(SRCS)",
-        visibility = ["//visibility:private"]
-    )
-
-    # Use kt_jvm_import so that ijarification doesn't ruin the worker lib.
-    kt_jvm_import(
-        name = name,
-        jars = [jar_name],
-        srcjar = jar_sources_name,
+        outs = [name + ".jar"],
         tags = ["no-ide"],
-        runtime_deps = (depset(runtime_deps) + deps).to_list(),
-        visibility = [
-            "//tests:__subpackages__",
-            "//kotlin:__subpackages__"
-        ]
+        visibility = ["//visibility:private"],
+        cmd = command
+    )
+    native.java_import(
+        name = name,
+        jars = [jar_label],
+        runtime_deps=deps + runtime_deps,
+        visibility=["//visibility:public"]
+    )
+    # hsyed todo this part of the graph should not be wired up outside of development.
+    _for_ide(
+        name = name + "_for_ide",
+        srcs = srcs,
+        deps = [_resolve_dep_label(d) for d in deps] + neverlink_deps,
+        visibility = ["//kotlin/builder:__subpackages__"]
     )
diff --git a/kotlin/builder/integrationtests/BUILD b/kotlin/builder/integrationtests/BUILD
new file mode 100644
index 0000000..ff0448b
--- /dev/null
+++ b/kotlin/builder/integrationtests/BUILD
@@ -0,0 +1,19 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+java_test(
+    name = "integrationtests",
+    srcs = glob(["*.java"]),
+    test_class = "io.bazel.kotlin.builder.KotlinBuilderTestSuite",
+    deps = ["//kotlin/builder:builder_lib_for_tests"]
+)
\ No newline at end of file
diff --git a/kotlin/builder/integrationtests/KotlinBuilderActionTests.java b/kotlin/builder/integrationtests/KotlinBuilderActionTests.java
index a26c1a1..6e27646 100644
--- a/kotlin/builder/integrationtests/KotlinBuilderActionTests.java
+++ b/kotlin/builder/integrationtests/KotlinBuilderActionTests.java
@@ -1,6 +1,6 @@
 package io.bazel.kotlin.builder;
 
-import io.bazel.kotlin.builder.mode.jvm.actions.KotlinCompiler;
+import io.bazel.kotlin.builder.tasks.jvm.KotlinCompiler;
 import org.junit.Test;
 
 public class KotlinBuilderActionTests extends KotlinBuilderTestCase {
diff --git a/kotlin/builder/integrationtests/KotlinBuilderTestCase.java b/kotlin/builder/integrationtests/KotlinBuilderTestCase.java
index f1cc005..cf23da1 100644
--- a/kotlin/builder/integrationtests/KotlinBuilderTestCase.java
+++ b/kotlin/builder/integrationtests/KotlinBuilderTestCase.java
@@ -23,8 +23,8 @@
       Paths.get(Preconditions.checkNotNull(System.getenv("TEST_TMPDIR")));
   private static final AtomicInteger counter = new AtomicInteger(0);
 
-  private final KotlinModel.BuilderCommand.Builder builder =
-      KotlinModel.BuilderCommand.newBuilder();
+  private final KotlinModel.CompilationTask.Builder builder =
+      KotlinModel.CompilationTask.newBuilder();
   private final Injector injector = KotlinToolchain.createInjector(() -> System.out, null);
   private String label = null;
   private Path inputSourceDir = null;
@@ -34,11 +34,11 @@
     resetTestContext("a_test_" + counter.incrementAndGet());
   }
 
-  protected KotlinModel.BuilderCommand.Outputs outputs() {
+  protected KotlinModel.CompilationTask.Outputs outputs() {
     return builder.getOutputs();
   }
 
-  protected KotlinModel.BuilderCommand.Directories directories() {
+  protected KotlinModel.CompilationTask.Directories directories() {
     return builder.getDirectories();
   }
 
@@ -50,7 +50,7 @@
     return Paths.get(directories().getClasses());
   }
 
-  protected KotlinModel.BuilderCommand builderCommand() {
+  protected KotlinModel.CompilationTask builderCommand() {
     return builder.build();
   }
 
@@ -132,7 +132,7 @@
     TEMP,
     SOURCE_GEN;
 
-    protected static Path select(DirectoryType type, KotlinModel.BuilderCommand command) {
+    protected static Path select(DirectoryType type, KotlinModel.CompilationTask command) {
       Path ret;
       switch (type) {
         case CLASSES:
diff --git a/kotlin/builder/integrationtests/KotlinBuilderTests.java b/kotlin/builder/integrationtests/KotlinBuilderTests.java
index cb5aa62..e046fed 100644
--- a/kotlin/builder/integrationtests/KotlinBuilderTests.java
+++ b/kotlin/builder/integrationtests/KotlinBuilderTests.java
@@ -2,7 +2,8 @@
 
 import com.google.common.truth.Truth;
 import com.google.devtools.build.lib.view.proto.Deps;
-import io.bazel.kotlin.builder.mode.jvm.KotlinJvmCompilationExecutor;
+
+import io.bazel.kotlin.builder.tasks.jvm.KotlinJvmTaskExecutor;
 import io.bazel.kotlin.model.KotlinModel;
 import org.junit.Test;
 
@@ -34,7 +35,7 @@
   }
 
   private void runCompileTask() {
-    KotlinModel.BuilderCommand command = builderCommand();
+    KotlinModel.CompilationTask command = builderCommand();
     for (DirectoryType directoryType : DirectoryType.values()) {
       try {
         if (directoryType != DirectoryType.ROOT) {
@@ -45,7 +46,7 @@
       }
     }
     int timeoutSeconds = 10;
-    KotlinJvmCompilationExecutor executor = instance(KotlinJvmCompilationExecutor.class);
+    KotlinJvmTaskExecutor executor = instance(KotlinJvmTaskExecutor.class);
     try {
       CompletableFuture.runAsync(() -> executor.compile(command))
           .get(timeoutSeconds, TimeUnit.SECONDS);
diff --git a/kotlin/builder/proto/BUILD b/kotlin/builder/proto/BUILD
index 8bc369b..b16e4b6 100644
--- a/kotlin/builder/proto/BUILD
+++ b/kotlin/builder/proto/BUILD
@@ -11,8 +11,9 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-
+package(default_visibility=["//visibility:public"])
 # commented out till 0.16 is released. We aren't  prebuilding the libraries at the moment so it's fine.
+# TODO constrain the visibility  when fixing  the comments below as well
 #proto_library(
 #    name = "kotlin_model_proto",
 #    srcs = [":kotlin_model.proto"],
@@ -40,17 +41,14 @@
 java_import(
     name = "deps",
     jars = ["jars/libdeps_proto-speed.jar"],
-    visibility = ["//kotlin/builder:__subpackages__"]
 )
 
 java_import(
     name = "worker",
     jars = ["jars/libworker_protocol_proto-speed.jar"],
-    visibility = ["//kotlin/builder:__subpackages__"]
 )
 
 java_import(
     name = "kotlin_model",
     jars = ["jars/libkotlin_model_proto-speed.jar"],
-    visibility = ["//kotlin/builder:__subpackages__"]
 )
\ No newline at end of file
diff --git a/kotlin/builder/proto/jars/libkotlin_model_proto-speed.jar b/kotlin/builder/proto/jars/libkotlin_model_proto-speed.jar
index 943c343..1a74d68 100755
--- a/kotlin/builder/proto/jars/libkotlin_model_proto-speed.jar
+++ b/kotlin/builder/proto/jars/libkotlin_model_proto-speed.jar
Binary files differ
diff --git a/kotlin/builder/proto/kotlin_model.proto b/kotlin/builder/proto/kotlin_model.proto
index d1e4ced..a66b7d3 100644
--- a/kotlin/builder/proto/kotlin_model.proto
+++ b/kotlin/builder/proto/kotlin_model.proto
@@ -65,7 +65,7 @@
 }
 
 // Mested messages not marked with stable could be refactored.
-message BuilderCommand {
+message CompilationTask {
     message Info {
         string label = 1;
         // derived from label
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/BUILD b/kotlin/builder/src/io/bazel/kotlin/builder/BUILD
new file mode 100644
index 0000000..e13c047
--- /dev/null
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/BUILD
@@ -0,0 +1,38 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+load("//kotlin/builder:bootstrap.bzl", "kt_bootstrap_library")
+
+kt_bootstrap_library(
+    name = "builder",
+    srcs = glob(["**/*.kt"]),
+    runtime_deps = [
+        "@com_github_jetbrains_kotlin//:kotlin-reflect",
+        "@com_github_jetbrains_kotlin//:kotlin-stdlib-jdk7",
+        "@com_github_jetbrains_kotlin//:kotlin-stdlib-jdk8",
+        "@io_bazel_rules_kotlin_aopalliance_aopalliance//jar",
+        "@io_bazel_rules_kotlin_com_google_code_gson_gson//jar",
+    ],
+    deps = [
+        "@io_bazel_rules_kotlin_com_google_guava_guava//jar",
+        "@com_github_jetbrains_kotlin//:kotlin-stdlib",
+        "@com_github_jetbrains_kotlin//:kotlin-preloader",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:kotlin_model",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:deps",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:worker",
+        "@io_bazel_rules_kotlin_com_google_inject_guice//jar",
+        "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java//jar",
+        "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java_util//jar",
+        "@io_bazel_rules_kotlin_javax_inject_javax_inject//jar",
+    ],
+)
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/BazelWorker.kt b/kotlin/builder/src/io/bazel/kotlin/builder/BazelWorker.kt
index c2895fd..19c2a7f 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/BazelWorker.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/BazelWorker.kt
@@ -61,8 +61,6 @@
 /**
  * Bazel worker runner.
  *
- *
- *
  * This class adapts a traditional command line program so it can be spawned by Bazel as a
  * persistent worker process that handles multiple invocations per JVM. It will also be backwards
  * compatible with being run as a normal single-invocation command.
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/KotlinBuilder.kt b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinBuilder.kt
index 0b0e262..0f20535 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/KotlinBuilder.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinBuilder.kt
@@ -18,11 +18,8 @@
 import com.google.inject.Inject
 import com.google.inject.Provider
 import com.google.inject.Singleton
-import io.bazel.kotlin.builder.mode.jvm.KotlinJvmCompilationExecutor
-import io.bazel.kotlin.builder.utils.ArgMap
-import io.bazel.kotlin.builder.utils.ArgMaps
-import io.bazel.kotlin.builder.utils.IS_JVM_SOURCE_FILE
-import io.bazel.kotlin.builder.utils.ensureDirectories
+import io.bazel.kotlin.builder.tasks.jvm.KotlinJvmTaskExecutor
+import io.bazel.kotlin.builder.utils.*
 import io.bazel.kotlin.builder.utils.jars.SourceJarExtractor
 import io.bazel.kotlin.model.KotlinModel
 import java.nio.file.Paths
@@ -30,8 +27,8 @@
 @Singleton
 @Suppress("MemberVisibilityCanBePrivate")
 class KotlinBuilder @Inject internal constructor(
-    private val commandBuilder: BuildCommandBuilder,
-    private val compilationExector: KotlinJvmCompilationExecutor
+    private val commandBuilder: TaskBuilder,
+    private val jvmTaskExecutor: KotlinJvmTaskExecutor
 ) : CommandLineProgram {
     fun execute(args: List<String>): Int =
         ArgMaps.from(args).let { execute(it) }
@@ -39,7 +36,7 @@
     fun execute(args: ArgMap): Int =
         commandBuilder.fromInput(args).let { execute(it) }
 
-    fun execute(command: KotlinModel.BuilderCommand): Int {
+    fun execute(command: KotlinModel.CompilationTask): Int {
         ensureDirectories(
             command.directories.classes,
             command.directories.temp,
@@ -48,7 +45,7 @@
         )
         val updatedCommand = expandWithSourceJarSources(command)
         return try {
-            compilationExector.compile(updatedCommand)
+            jvmTaskExecutor.compile(updatedCommand)
             0
         } catch (ex: CompilationStatusException) {
             ex.status
@@ -56,10 +53,10 @@
     }
 
     /**
-     * If any sourcejars were provided expand the jars sources and create a new [KotlinModel.BuilderCommand] with the
+     * If any sourcejars were provided expand the jars sources and create a new [KotlinModel.CompilationTask] with the
      * Java and Kotlin sources merged in.
      */
-    private fun expandWithSourceJarSources(command: KotlinModel.BuilderCommand): KotlinModel.BuilderCommand =
+    private fun expandWithSourceJarSources(command: KotlinModel.CompilationTask): KotlinModel.CompilationTask =
         if (command.inputs.sourceJarsList.isEmpty()) {
             command
         } else {
@@ -70,7 +67,7 @@
                 it.jarFiles.addAll(command.inputs.sourceJarsList.map { Paths.get(it) })
                 it.execute()
             }.let {
-                commandBuilder.withSources(command, it.sourcesList.iterator())
+                command.expandWithSources(command, it.sourcesList.iterator())
             }
         }
 
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/utils/KotlinCompilerPluginArgsEncoder.kt b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinCompilerPluginArgsEncoder.kt
similarity index 83%
rename from kotlin/builder/src/io/bazel/kotlin/builder/utils/KotlinCompilerPluginArgsEncoder.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/KotlinCompilerPluginArgsEncoder.kt
index 1d29c0a..e67c1ae 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/utils/KotlinCompilerPluginArgsEncoder.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinCompilerPluginArgsEncoder.kt
@@ -13,26 +13,22 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.utils
+package io.bazel.kotlin.builder
 
-import com.google.common.collect.ImmutableList
-import com.google.inject.ImplementedBy
-import com.google.inject.Inject
+
 import io.bazel.kotlin.builder.KotlinToolchain.CompilerPlugin
 import io.bazel.kotlin.model.KotlinModel
 import java.io.ByteArrayOutputStream
 import java.io.ObjectOutputStream
 import java.util.*
+import javax.inject.Inject
+import javax.inject.Singleton
 
-@ImplementedBy(DefaultKotlinCompilerPluginArgsEncoder::class)
-interface KotlinCompilerPluginArgsEncoder {
-    fun encode(command: KotlinModel.BuilderCommandOrBuilder): List<String>
-}
-
-class DefaultKotlinCompilerPluginArgsEncoder @Inject internal constructor(
+@Singleton
+internal class KotlinCompilerPluginArgsEncoder @Inject constructor(
     @CompilerPlugin.Kapt3
     private val kapt3: CompilerPlugin
-) : KotlinCompilerPluginArgsEncoder {
+) {
     companion object {
         private fun encodeMap(options: Map<String, String>): String {
             val os = ByteArrayOutputStream()
@@ -66,6 +62,7 @@
             return Base64.getEncoder().encodeToString(os.toByteArray())
         }
     }
+
     /**
      * Plugin using the undocumented encoding format for kapt3
      */
@@ -83,15 +80,17 @@
 
         // "configuration" is an undocumented kapt3 argument. preparing the arguments this way is the only way to get more than one annotation processor class
         // passed to kotlinc.
-        fun encode(): ImmutableList<String> =
-            ImmutableList.of(
+        fun encode(): List<String> =
+            listOf(
                 "-Xplugin=${kapt3.jarPath}",
-                "-P", "plugin:${kapt3.id}:configuration=${encodeMultiMap(tally)}"
+                "-P", "plugin:${kapt3.id}:configuration=${encodeMultiMap(
+                    tally
+                )}"
             )
     }
 
-    override fun encode(
-        command: KotlinModel.BuilderCommandOrBuilder
+    fun encode(
+        command: KotlinModel.CompilationTaskOrBuilder
     ): List<String> {
         val javacArgs = mutableMapOf<String, String>(
             "-target" to command.info.toolchainInfo.jvm.jvmTarget
@@ -103,7 +102,7 @@
                 arg["classes"] = d.generatedClasses.toString()
                 arg["stubs"] = d.temp.toString()
                 arg["incrementalData"] = d.temp.toString()
-                arg["javacArguments"] = javacArgs.let(::encodeMap)
+                arg["javacArguments"] = javacArgs.let(Companion::encodeMap)
                 arg["aptMode"] = "stubsAndApt"
                 arg["correctErrorTypes"] = "true"
 //                arg["verbose"] = "true"
@@ -114,6 +113,6 @@
                     .joinToString(",") { it.processorClass }
                 arg.encode()
             }
-        }?.let { ImmutableList.copyOf(it) } ?: ImmutableList.of()
+        } ?: emptyList()
     }
 }
\ No newline at end of file
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/KotlinToolchain.kt b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinToolchain.kt
index 84766d3..22424a1 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/KotlinToolchain.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/KotlinToolchain.kt
@@ -15,7 +15,6 @@
  */
 package io.bazel.kotlin.builder
 
-import com.google.common.collect.ImmutableSet
 import com.google.inject.*
 import com.google.inject.util.Modules
 import io.bazel.kotlin.builder.utils.resolveVerified
@@ -32,7 +31,7 @@
     internal val javaHome: Path,
     val kotlinHome: Path,
     internal val classLoader: ClassLoader,
-    val kotlinStandardLibraries: ImmutableSet<String> = ImmutableSet.of(
+    val kotlinStandardLibraries: List<String> = listOf(
         "kotlin-stdlib.jar",
         "kotlin-stdlib-jdk7.jar",
         "kotlin-stdlib-jdk8.jar"
@@ -47,8 +46,8 @@
         private fun createClassLoader(javaHome: Path, kotlinHome: Path): ClassLoader {
             val preloadJars = mutableListOf<File>().also {
                 it += kotlinHome.resolveVerified("lib", "kotlin-compiler.jar")
-                it +=  javaRunfiles.resolveVerified("io_bazel_rules_kotlin", "kotlin", "builder", "compiler_lib.jar")
-                if(!isJdk9OrNewer) {
+                it += javaRunfiles.resolveVerified("io_bazel_rules_kotlin", "kotlin", "builder", "compiler_lib.jar")
+                if (!isJdk9OrNewer) {
                     it += javaHome.resolveVerified("lib", "tools.jar")
                 }
             }
@@ -65,7 +64,11 @@
             val javaHome = Paths.get(System.getProperty("java.home")).let {
                 it.takeIf { !it.endsWith(Paths.get("jre")) } ?: it.parent
             }
-            return KotlinToolchain(javaHome, kotlinHome, createClassLoader(javaHome, kotlinHome))
+            return KotlinToolchain(
+                javaHome,
+                kotlinHome,
+                createClassLoader(javaHome, kotlinHome)
+            )
         }
 
         /**
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/BuildCommandBuilder.kt b/kotlin/builder/src/io/bazel/kotlin/builder/TaskBuilder.kt
similarity index 73%
rename from kotlin/builder/src/io/bazel/kotlin/builder/BuildCommandBuilder.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/TaskBuilder.kt
index 54302c1..1746a8e 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/BuildCommandBuilder.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/TaskBuilder.kt
@@ -15,27 +15,18 @@
  */
 package io.bazel.kotlin.builder
 
-import com.google.inject.ImplementedBy
-import com.google.inject.Inject
-import com.google.inject.Singleton
 import com.google.protobuf.util.JsonFormat
 import io.bazel.kotlin.builder.utils.ArgMap
-import io.bazel.kotlin.builder.utils.DefaultKotlinCompilerPluginArgsEncoder
+import io.bazel.kotlin.builder.utils.partitionSources
 import io.bazel.kotlin.model.KotlinModel
-import io.bazel.kotlin.model.KotlinModel.BuilderCommand
-
-
-@ImplementedBy(DefaultBuildCommandBuilder::class)
-interface BuildCommandBuilder {
-    fun fromInput(argMap: ArgMap): BuilderCommand
-    fun withSources(command: BuilderCommand, sources: Iterator<String>): BuilderCommand
-    fun withGeneratedSources(command: BuilderCommand, sources: Iterator<String>): BuilderCommand
-}
+import io.bazel.kotlin.model.KotlinModel.CompilationTask
+import javax.inject.Inject
+import javax.inject.Singleton
 
 @Singleton
-private class DefaultBuildCommandBuilder @Inject constructor(
-    private val pluginEncoder: DefaultKotlinCompilerPluginArgsEncoder
-) : BuildCommandBuilder {
+class TaskBuilder @Inject internal constructor(
+    private val pluginEncoder: KotlinCompilerPluginArgsEncoder
+) {
     companion object {
         @JvmStatic
         private val jsonTypeRegistry = JsonFormat.TypeRegistry.newBuilder()
@@ -84,8 +75,8 @@
         TEST_ONLY("--testonly")
     }
 
-    override fun fromInput(argMap: ArgMap): BuilderCommand =
-        BuilderCommand.newBuilder().let { root ->
+    fun fromInput(argMap: ArgMap): CompilationTask =
+        CompilationTask.newBuilder().let { root ->
             with(root.outputsBuilder) {
                 jar = argMap.mandatorySingle(JavaBuilderFlags.OUTPUT.flag)
                 jdeps = argMap.mandatorySingle("--output_jdeps")
@@ -146,37 +137,5 @@
             }
             root.build()
         }
-
-    override fun withSources(command: BuilderCommand, sources: Iterator<String>): BuilderCommand =
-        command.updateBuilder { builder ->
-            sources.partitionSources(
-                { builder.inputsBuilder.addKotlinSources(it) },
-                { builder.inputsBuilder.addJavaSources(it) })
-        }
-
-
-    override fun withGeneratedSources(command: BuilderCommand, sources: Iterator<String>): BuilderCommand =
-        command.updateBuilder { builder ->
-            sources.partitionSources(
-                { builder.inputsBuilder.addGeneratedKotlinSources(it) },
-                { builder.inputsBuilder.addGeneratedJavaSources(it) })
-        }
-
-    private fun BuilderCommand.updateBuilder(init: (BuilderCommand.Builder) -> Unit): BuilderCommand =
-        toBuilder().let {
-            init(it)
-            it.build()
-        }
-
-
-    private fun Iterator<String>.partitionSources(kt: (String) -> Unit, java: (String) -> Unit) {
-        forEach {
-            when {
-                it.endsWith(".kt") -> kt(it)
-                it.endsWith(".java") -> java(it)
-                else -> throw IllegalStateException("invalid source file type $it")
-            }
-        }
-    }
 }
 
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JDepsGenerator.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JDepsGenerator.kt
similarity index 93%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JDepsGenerator.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JDepsGenerator.kt
index 0bcc45f..e5053f4 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JDepsGenerator.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JDepsGenerator.kt
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.actions
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.devtools.build.lib.view.proto.Deps
 import com.google.inject.ImplementedBy
@@ -21,7 +21,6 @@
 import io.bazel.kotlin.builder.CompilationException
 import io.bazel.kotlin.builder.CompilationStatusException
 import io.bazel.kotlin.builder.KotlinToolchain
-import io.bazel.kotlin.builder.mode.jvm.utils.JdepsParser
 import io.bazel.kotlin.builder.utils.resolveVerified
 import io.bazel.kotlin.builder.utils.rootCause
 import io.bazel.kotlin.model.KotlinModel
@@ -33,7 +32,7 @@
 
 @ImplementedBy(DefaultJDepsGenerator::class)
 interface JDepsGenerator {
-    fun generateJDeps(command: KotlinModel.BuilderCommand)
+    fun generateJDeps(command: KotlinModel.CompilationTask)
 }
 
 private class DefaultJDepsGenerator @Inject constructor(
@@ -42,7 +41,7 @@
 ) : JDepsGenerator {
     private val isKotlinImplicit = JdepsParser.pathSuffixMatchingPredicate(
         toolchain.kotlinHome.resolveVerified("lib").toPath(), *toolchain.kotlinStandardLibraries.toTypedArray())
-    override fun generateJDeps(command: KotlinModel.BuilderCommand) {
+    override fun generateJDeps(command: KotlinModel.CompilationTask) {
         val jdepsContent =
             if (command.inputs.classpathList.isEmpty()) {
                 Deps.Dependencies.newBuilder().let {
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JavaCompiler.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JavaCompiler.kt
similarity index 88%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JavaCompiler.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JavaCompiler.kt
index ee5df82..5f29bec 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/JavaCompiler.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JavaCompiler.kt
@@ -13,24 +13,24 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.actions
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.inject.ImplementedBy
 import com.google.inject.Inject
 import io.bazel.kotlin.builder.CompilationStatusException
 import io.bazel.kotlin.builder.KotlinToolchain
 import io.bazel.kotlin.builder.utils.addAll
-import io.bazel.kotlin.model.KotlinModel.BuilderCommand
+import io.bazel.kotlin.model.KotlinModel.CompilationTask
 
 @ImplementedBy(DefaultJavaCompiler::class)
 interface JavaCompiler {
-    fun compile(command: BuilderCommand)
+    fun compile(command: CompilationTask)
 }
 
 private class DefaultJavaCompiler @Inject constructor(
     val javacInvoker: KotlinToolchain.JavacInvoker
 ) : JavaCompiler {
-    override fun compile(command: BuilderCommand) {
+    override fun compile(command: CompilationTask) {
         val i = command.inputs
         val d = command.directories
         if (i.javaSourcesList.isNotEmpty() || i.generatedJavaSourcesList.isNotEmpty()) {
@@ -50,7 +50,7 @@
                 it.addAll(i.generatedJavaSourcesList)
                 it.toTypedArray()
             }
-            javacInvoker.compile(args).takeIf { it != 0 }?.also { throw CompilationStatusException("javac failed",it) }
+            javacInvoker.compile(args).takeIf { it != 0 }?.also { throw CompilationStatusException("javac failed", it) }
         }
     }
 }
\ No newline at end of file
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/JdepsParser.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JdepsParser.kt
similarity index 98%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/JdepsParser.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JdepsParser.kt
index f3419dc..5614add 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/JdepsParser.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/JdepsParser.kt
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.utils
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.devtools.build.lib.view.proto.Deps
 import java.nio.file.Path
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/KotlinCompiler.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompiler.kt
similarity index 83%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/KotlinCompiler.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompiler.kt
index ffcf837..8721c73 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/KotlinCompiler.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompiler.kt
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.actions
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.inject.ImplementedBy
 import com.google.inject.Inject
@@ -27,8 +27,8 @@
 
 @ImplementedBy(DefaultKotlinCompiler::class)
 interface KotlinCompiler {
-    fun runAnnotationProcessor(command: KotlinModel.BuilderCommand): List<String>
-    fun compile(command: KotlinModel.BuilderCommand): List<String>
+    fun runAnnotationProcessor(command: KotlinModel.CompilationTask): List<String>
+    fun compile(command: KotlinModel.CompilationTask): List<String>
 }
 
 // The Kotlin compiler is not suited for javac compilation as of 1.2.21. The errors are not conveyed directly and would need to be preprocessed, also javac
@@ -40,11 +40,11 @@
 private class DefaultKotlinCompiler @Inject constructor(
     val compiler: KotlinToolchain.KotlincInvoker
 ) : KotlinCompiler {
-    override fun runAnnotationProcessor(command: KotlinModel.BuilderCommand): List<String> {
+    override fun runAnnotationProcessor(command: KotlinModel.CompilationTask): List<String> {
         check(command.info.plugins.annotationProcessorsList.isNotEmpty()) {
             "method called without annotation processors"
         }
-        return setupCompileContext(command).also {
+        return getCommonArgs(command).also {
             it.addAll(command.info.encodedPluginDescriptorsList)
             it.addAll(command.inputs.kotlinSourcesList)
             it.addAll(command.inputs.javaSourcesList)
@@ -52,11 +52,9 @@
     }
 
     /**
-     * Evaluate the compilation context and add Metadata to the ctx if needed.
-     *
-     * @return The args to pass to the kotlin compile class.
+     * Return a list with the common arguments.
      */
-    private fun setupCompileContext(command: KotlinModel.BuilderCommand): MutableList<String> {
+    private fun getCommonArgs(command: KotlinModel.CompilationTask): MutableList<String> {
         val args = mutableListOf<String>()
 
         // use -- for flags not meant for the kotlin compiler
@@ -77,8 +75,8 @@
         return args
     }
 
-    override fun compile(command: KotlinModel.BuilderCommand): List<String> =
-        with(setupCompileContext(command)) {
+    override fun compile(command: KotlinModel.CompilationTask): List<String> =
+        with(getCommonArgs(command)) {
             addAll(command.inputs.javaSourcesList)
             addAll(command.inputs.generatedJavaSourcesList)
             addAll(command.inputs.kotlinSourcesList)
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/KotlinCompilerOutputSink.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompilerOutputSink.kt
similarity index 75%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/KotlinCompilerOutputSink.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompilerOutputSink.kt
index 42ddf53..c72628c 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/utils/KotlinCompilerOutputSink.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinCompilerOutputSink.kt
@@ -13,31 +13,26 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.utils
+package io.bazel.kotlin.builder.tasks.jvm
 
-import com.google.inject.ImplementedBy
 import com.google.inject.Inject
 import com.google.inject.Provider
+import com.google.inject.Singleton
 import java.io.File
 import java.io.PrintStream
 import java.nio.file.Paths
 
-@ImplementedBy(DefaultOutputProcessorFactory::class)
-interface KotlinCompilerOutputSink {
-    fun deliver(line: String)
-    fun deliver(lines: List<String>)
-}
-
-private class DefaultOutputProcessorFactory @Inject constructor(
+@Singleton
+class KotlinCompilerOutputSink @Inject constructor(
     val streamProvider: Provider<PrintStream>
-) : KotlinCompilerOutputSink {
+) {
     private val executionRoot: String = Paths.get("").toAbsolutePath().toString() + File.separator
 
-    override fun deliver(line: String) {
+    fun deliver(line: String) {
         streamProvider.get().println(trimExecutionRootPrefix(line))
     }
 
-    override fun deliver(lines: List<String>) {
+    fun deliver(lines: List<String>) {
         streamProvider.get().also { stream -> lines.map(::trimExecutionRootPrefix).forEach(stream::println) }
     }
 
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/KotlinJvmCompilationExecutor.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinJvmTaskExecutor.kt
similarity index 70%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/KotlinJvmCompilationExecutor.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinJvmTaskExecutor.kt
index db1b42d..fbf7655 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/KotlinJvmCompilationExecutor.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/KotlinJvmTaskExecutor.kt
@@ -13,41 +13,29 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.common.base.Stopwatch
-import com.google.inject.ImplementedBy
 import com.google.inject.Inject
 import com.google.inject.Singleton
-import io.bazel.kotlin.builder.BuildCommandBuilder
 import io.bazel.kotlin.builder.CompilationStatusException
-import io.bazel.kotlin.builder.mode.jvm.KotlinJvmCompilationExecutor.Result
-import io.bazel.kotlin.builder.mode.jvm.actions.JDepsGenerator
-import io.bazel.kotlin.builder.mode.jvm.actions.JavaCompiler
-import io.bazel.kotlin.builder.mode.jvm.actions.KotlinCompiler
-import io.bazel.kotlin.builder.mode.jvm.actions.OutputJarCreator
-import io.bazel.kotlin.builder.mode.jvm.utils.KotlinCompilerOutputSink
-import io.bazel.kotlin.model.KotlinModel.BuilderCommand
+import io.bazel.kotlin.builder.utils.expandWithGeneratedSources
+import io.bazel.kotlin.model.KotlinModel.CompilationTask
 import java.io.File
 import java.util.concurrent.TimeUnit
 
-@ImplementedBy(DefaultKotlinJvmCompilationExecutor::class)
-interface KotlinJvmCompilationExecutor {
-    class Result(val timings: List<String>, val command: BuilderCommand)
-
-    fun compile(command: BuilderCommand): Result
-}
 
 @Singleton
-private class DefaultKotlinJvmCompilationExecutor @Inject constructor(
-    private val commandBuilder: BuildCommandBuilder,
+class KotlinJvmTaskExecutor @Inject internal constructor(
     private val kotlinCompiler: KotlinCompiler,
     private val outputSink: KotlinCompilerOutputSink,
     private val javaCompiler: JavaCompiler,
     private val jDepsGenerator: JDepsGenerator,
     private val outputJarCreator: OutputJarCreator
-) : KotlinJvmCompilationExecutor {
-    override fun compile(command: BuilderCommand): Result {
+) {
+    class Result(val timings: List<String>, val command: CompilationTask)
+
+    fun compile(command: CompilationTask): Result {
         val context = Context()
         val commandWithApSources = context.execute("kapt") {
             runAnnotationProcessors(command)
@@ -62,7 +50,7 @@
         return Result(context.timings, commandWithApSources)
     }
 
-    private fun runAnnotationProcessors(command: BuilderCommand): BuilderCommand =
+    private fun runAnnotationProcessors(command: CompilationTask): CompilationTask =
         try {
             if (command.info.plugins.annotationProcessorsList.isNotEmpty()) {
                 kotlinCompiler.runAnnotationProcessor(command)
@@ -70,16 +58,16 @@
                     .filter { it.isFile }
                     .map { it.path }
                     .iterator()
-                    .let { commandBuilder.withGeneratedSources(command, it) }
+                    .let { command.expandWithGeneratedSources(command, it) }
             } else {
                 command
             }
-        } catch(ex: CompilationStatusException) {
+        } catch (ex: CompilationStatusException) {
             ex.lines.also(outputSink::deliver)
             throw ex
         }
 
-    private fun compileClasses(context: Context, command: BuilderCommand) {
+    private fun compileClasses(context: Context, command: CompilationTask) {
         var kotlinError: CompilationStatusException? = null
         var result: List<String>? = null
         context.execute("kotlinc") {
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/OutputJarCreator.kt b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/OutputJarCreator.kt
similarity index 87%
rename from kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/OutputJarCreator.kt
rename to kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/OutputJarCreator.kt
index 88c98af..540f673 100644
--- a/kotlin/builder/src/io/bazel/kotlin/builder/mode/jvm/actions/OutputJarCreator.kt
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/tasks/jvm/OutputJarCreator.kt
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package io.bazel.kotlin.builder.mode.jvm.actions
+package io.bazel.kotlin.builder.tasks.jvm
 
 import com.google.inject.ImplementedBy
 import io.bazel.kotlin.builder.utils.jars.JarCreator
@@ -22,11 +22,11 @@
 
 @ImplementedBy(DefaultOutputJarCreator::class)
 interface OutputJarCreator {
-    fun createOutputJar(command: KotlinModel.BuilderCommand)
+    fun createOutputJar(command: KotlinModel.CompilationTask)
 }
 
 private class DefaultOutputJarCreator : OutputJarCreator {
-    override fun createOutputJar(command: KotlinModel.BuilderCommand) {
+    override fun createOutputJar(command: KotlinModel.CompilationTask) {
         JarCreator(
             path = Paths.get(command.outputs.jar),
             normalize = true,
diff --git a/kotlin/builder/src/io/bazel/kotlin/builder/utils/TaskUtils.kt b/kotlin/builder/src/io/bazel/kotlin/builder/utils/TaskUtils.kt
new file mode 100644
index 0000000..4ec19b4
--- /dev/null
+++ b/kotlin/builder/src/io/bazel/kotlin/builder/utils/TaskUtils.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2018 The Bazel Authors. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.bazel.kotlin.builder.utils
+
+import io.bazel.kotlin.model.KotlinModel
+
+
+fun KotlinModel.CompilationTask.expandWithSources(
+    command: KotlinModel.CompilationTask,
+    sources: Iterator<String>
+): KotlinModel.CompilationTask =
+    command.updateBuilder { builder ->
+        sources.partitionSources(
+            { builder.inputsBuilder.addKotlinSources(it) },
+            { builder.inputsBuilder.addJavaSources(it) })
+    }
+
+
+fun KotlinModel.CompilationTask.expandWithGeneratedSources(
+    command: KotlinModel.CompilationTask,
+    sources: Iterator<String>
+): KotlinModel.CompilationTask =
+    command.updateBuilder { builder ->
+        sources.partitionSources(
+            { builder.inputsBuilder.addGeneratedKotlinSources(it) },
+            { builder.inputsBuilder.addGeneratedJavaSources(it) })
+    }
+
+private fun KotlinModel.CompilationTask.updateBuilder(
+    init: (KotlinModel.CompilationTask.Builder) -> Unit
+): KotlinModel.CompilationTask =
+    toBuilder().let {
+        init(it)
+        it.build()
+    }
+
+fun Iterator<String>.partitionSources(kt: (String) -> Unit, java: (String) -> Unit) {
+    forEach {
+        when {
+            it.endsWith(".kt") -> kt(it)
+            it.endsWith(".java") -> java(it)
+            else -> throw IllegalStateException("invalid source file type $it")
+        }
+    }
+}
diff --git a/kotlin/builder/unittests/BUILD b/kotlin/builder/unittests/BUILD
new file mode 100644
index 0000000..2895039
--- /dev/null
+++ b/kotlin/builder/unittests/BUILD
@@ -0,0 +1,25 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+java_test(
+    name = "unittests",
+    size = "small",
+    srcs = glob(["**/*.java"]),
+    test_class = "io.bazel.kotlin.builder.mode.jvm.utils.JdepsParserTest",
+    deps = [
+        "//kotlin/builder/src/io/bazel/kotlin/builder",
+        "@com_github_jetbrains_kotlin//:kotlin-stdlib",
+        "@io_bazel_rules_kotlin//kotlin/builder/proto:deps",
+        "@io_bazel_rules_kotlin_com_google_protobuf_protobuf_java//jar",
+    ]
+)
diff --git a/kotlin/builder/unittests/io/bazel/kotlin/workers/mode/jvm/utils/JdepsParserTest.java b/kotlin/builder/unittests/io/bazel/kotlin/workers/mode/jvm/utils/JdepsParserTest.java
index 7013b35..8bf24ec 100644
--- a/kotlin/builder/unittests/io/bazel/kotlin/workers/mode/jvm/utils/JdepsParserTest.java
+++ b/kotlin/builder/unittests/io/bazel/kotlin/workers/mode/jvm/utils/JdepsParserTest.java
@@ -16,6 +16,7 @@
 package io.bazel.kotlin.builder.mode.jvm.utils;
 
 import com.google.devtools.build.lib.view.proto.Deps;
+import io.bazel.kotlin.builder.tasks.jvm.JdepsParser;
 import org.junit.Assert;
 import org.junit.Test;
 import org.junit.runner.RunWith;
diff --git a/kotlin/internal/bootstrap.bzl b/kotlin/internal/bootstrap.bzl
index 4136a90..05cbbaf 100644
--- a/kotlin/internal/bootstrap.bzl
+++ b/kotlin/internal/bootstrap.bzl
@@ -17,21 +17,6 @@
 load("//kotlin/internal:rules.bzl", _kt_jvm_import_impl="kt_jvm_import_impl")
 load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_archive="http_archive")
 
-kotlin_stdlib = rule(
-    attrs = {
-        "jars": attr.label_list(
-            allow_files = True,
-            mandatory = True,
-        ),
-        "srcjar": attr.label(
-            allow_single_file = True,
-        ),
-    },
-    implementation = _kt_jvm_import_impl,
-)
-
-"""Import Kotlin libraries that are part of the compiler release."""
-
 def _kt_toolchain_ide_info_impl(ctx):
     tc=ctx.toolchains[kt.defs.TOOLCHAIN_TYPE]
     info = struct(
diff --git a/kotlin/kotlin.bzl b/kotlin/kotlin.bzl
index 2ecd9a5..73a0ea7 100644
--- a/kotlin/kotlin.bzl
+++ b/kotlin/kotlin.bzl
@@ -112,9 +112,9 @@
     _kt_jvm_junit_test_impl = "kt_jvm_junit_test_impl",
     _kt_jvm_library_impl = "kt_jvm_library_impl",
 )
+load("//kotlin:kotlin_releases.bzl", "KOTLIN_CURRENT_RELEASE")
 load(
     "//kotlin:kotlin_compiler_repositories.bzl",
-    "KOTLIN_CURRENT_RELEASE",
     _kotlin_compiler_repository = "kotlin_compiler_repositories",
 )
 load("//third_party/jvm:workspace.bzl", _maven_dependencies="maven_dependencies")
diff --git a/kotlin/kotlin_compiler_repositories.bzl b/kotlin/kotlin_compiler_repositories.bzl
index d338141..6161285 100644
--- a/kotlin/kotlin_compiler_repositories.bzl
+++ b/kotlin/kotlin_compiler_repositories.bzl
@@ -14,186 +14,30 @@
 """This file contains the Kotlin compiler repository definitions. It should not be loaded directly by client workspaces.
 """
 load("@bazel_tools//tools/build_defs/repo:http.bzl", _http_file="http_file", _http_archive="http_archive")
-load(
-    "//kotlin/internal:kt.bzl",
-    _kt = "kt",
+load("//kotlin/internal:kt.bzl", _kt = "kt")
+load("//kotlin:kotlin_releases.bzl",
+    _KOTLIN_COMPILER_RELEASES="KOTLIN_COMPILER_RELEASES",
+    _KOTLIN_CURRENT_RELEASE="KOTLIN_CURRENT_RELEASE"
 )
-load(
-  "//third_party/jvm:workspace.bzl",
-  _maven_dependencies="maven_dependencies"
-)
-
-KOTLIN_RELEASES = {
-    "1.2.50": {
-      "version": "1.2.50",
-      "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.50/kotlin-compiler-1.2.50.zip",
-      "sha256": "bc062c303b376711097a27bda4c28047eda0744e9acc64b9db640c19c7d171a9"
-    },
-    "1.2.41": {
-      "version": "1.2.41",
-      "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.41/kotlin-compiler-1.2.41.zip",
-      "sha256": "af872772f268da5ca79d263b2943f1d694d475dddb80b6d408e9548805ed265c"
-    },
-    "1.2.40": {
-        "version": "1.2.40",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.40/kotlin-compiler-1.2.40.zip",
-        "sha256": "3498571126c335be0feec24075c359f1954d46bbabccafc729ec49db1a509658",
-    },
-    "1.2.30": {
-        "version": "1.2.30",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.30/kotlin-compiler-1.2.30.zip",
-        "sha256": "4d6965877301d44241ca6de36480140992dc8a6b1c1884baeb5239ce2c43e071",
-    },
-    "1.2.21": {
-        "version": "1.2.21",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.21/kotlin-compiler-1.2.21.zip",
-        "sha256": "c5f2cbd35daa6c5c394e92e6c06b8eb41d85ad8da64762733874166b6807af22",
-    },
-    "1.2.20": {
-        "version": "1.2.20",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.20/kotlin-compiler-1.2.20.zip",
-        "sha256": "fb63d3d9f37b43f37575e3623c058d42a4b5dc8da08479ab065c4994e421a057",
-    },
-    "1.2.10": {
-        "version": "1.2.10",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.10/kotlin-compiler-1.2.10.zip",
-        "sha256": "95874568919121acb694bec0d6c92c60bdceea53f4c202e23ab734e94a0c26e3",
-    },
-    "1.2.0": {
-        "version": "1.2.0",
-        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.0/kotlin-compiler-1.2.0.zip",
-        "sha256": "895d0f8286db3e4f43d67cd5e09b600af6e0a5017cb74072d1b09c78b697775a",
-    },
-}
-
-KOTLIN_COMPILER_REPO_BUILD_FILE = """
-load("@io_bazel_rules_kotlin//kotlin/internal:bootstrap.bzl", kotlin_stdlib="kotlin_stdlib")
-package(default_visibility = ["//visibility:public"])
-
-filegroup(
-    name = "home",
-    srcs = glob(["lib/*.jar"], exclude = ["lib/*-sources.jar"]),
-)
-
-kotlin_stdlib(
-    name = "kotlin-runtime",
-    jars = ["lib/kotlin-runtime.jar"],
-    srcjar = "lib/kotlin-runtime-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-stdlib",
-    jars = ["lib/kotlin-stdlib.jar"],
-    srcjar = "lib/kotlin-stdlib-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-stdlib-jdk7",
-    jars = ["lib/kotlin-stdlib-jdk7.jar"],
-    srcjar = "lib/kotlin-stdlib-jdk7-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-stdlib-jdk8",
-    jars = ["lib/kotlin-stdlib-jdk8.jar"],
-    srcjar = "lib/kotlin-stdlib-jdk8-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-reflect",
-    jars = ["lib/kotlin-reflect.jar"],
-    srcjar = "lib/kotlin-reflect-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-test",
-    jars = ["lib/kotlin-test.jar"],
-    srcjar = "lib/kotlin-test-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-script-runtime",
-    jars = ["lib/kotlin-script-runtime.jar"],
-    srcjar = "lib/kotlin-script-runtime-sources.jar"
-)
-
-kotlin_stdlib(
-    name = "kotlin-annotation-processing",
-    jars = ["lib/kotlin-annotation-processing.jar"]
-)
-
-kotlin_stdlib(
-    name = "kotlin-annotation-processing-runtime",
-    jars = ["lib/kotlin-annotation-processing-runtime.jar"]
-)
-
-kotlin_stdlib(
-    name = "allopen-compiler-plugin",
-    jars = ["lib/allopen-compiler-plugin.jar"]
-)
-
-kotlin_stdlib(
-    name = "noarg-compiler-plugin",
-    jars = ["lib/noarg-compiler-plugin.jar"]
-)
-
-alias(name="runtime", actual="kotlin-runtime")
-alias(name="stdlib", actual="kotlin-stdlib")
-alias(name="stdlib-jdk7", actual="kotlin-stdlib-jdk7")
-alias(name="stdlib-jdk8", actual="kotlin-stdlib-jdk8")
-alias(name="reflect", actual="kotlin-reflect")
-alias(name="test", actual="kotlin-test")
-
-java_import(
-    name = "compiler",
-    jars = ["lib/kotlin-compiler.jar"],
-)
-
-java_import(
-    name = "script-runtime",
-    jars = ["lib/kotlin-script-runtime.jar"],
-)
-
-java_import(
-    name = "preloader",
-    jars = ["lib/kotlin-preloader.jar"],
-)
-
-sh_binary(
-    name = "kotlin",
-    srcs = ["bin/kotlin"],
-)
-
-sh_binary(
-    name = "kotlinc",
-    srcs = ["bin/kotlinc"],
-)
-
-exports_files(["src"])
-"""
-
-KOTLIN_CURRENT_RELEASE = "1.2.50"
 
 _BAZEL_JAVA_LAUNCHER_VERSION = "0.8.1"
 
-def kotlin_compiler_repositories(
-    kotlin_release_version=KOTLIN_CURRENT_RELEASE,
-):
+def kotlin_compiler_repositories(kotlin_release_version):
     """
     Prime the compiler repository.
 
     This function should not be called directly instead `kotlin_repositories` from `//kotlin:kotlin.bzl` should be
     called to ensure common deps are loaded.
     """
-    release=KOTLIN_RELEASES[kotlin_release_version]
+    release=_KOTLIN_COMPILER_RELEASES[kotlin_release_version]
     if not release:
-        fail('"%s" not a valid kotlin release, current release is "%s"' % (kotlin_release_version, KOTLIN_CURRENT_RELEASE))
+        fail('"%s" not a valid kotlin release, current release is "%s"' % (kotlin_release_version, _KOTLIN_CURRENT_RELEASE))
 
     _http_archive(
         name = _kt.defs.KT_COMPILER_REPO,
         url = release["url"],
         sha256 = release["sha256"],
-        build_file_content= KOTLIN_COMPILER_REPO_BUILD_FILE,
+        build_file= "@io_bazel_rules_kotlin//kotlin:BUILD.com_github_jetbrains_kotlin",
         strip_prefix = "kotlinc",
     )
 
diff --git a/kotlin/kotlin_releases.bzl b/kotlin/kotlin_releases.bzl
new file mode 100644
index 0000000..f84f7eb
--- /dev/null
+++ b/kotlin/kotlin_releases.bzl
@@ -0,0 +1,58 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+KOTLIN_CURRENT_RELEASE = "1.2.50"
+
+KOTLIN_COMPILER_RELEASES = {
+    "1.2.50": {
+      "version": "1.2.50",
+      "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.50/kotlin-compiler-1.2.50.zip",
+      "sha256": "bc062c303b376711097a27bda4c28047eda0744e9acc64b9db640c19c7d171a9"
+    },
+    "1.2.41": {
+      "version": "1.2.41",
+      "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.41/kotlin-compiler-1.2.41.zip",
+      "sha256": "af872772f268da5ca79d263b2943f1d694d475dddb80b6d408e9548805ed265c"
+    },
+    "1.2.40": {
+        "version": "1.2.40",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.40/kotlin-compiler-1.2.40.zip",
+        "sha256": "3498571126c335be0feec24075c359f1954d46bbabccafc729ec49db1a509658",
+    },
+    "1.2.30": {
+        "version": "1.2.30",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.30/kotlin-compiler-1.2.30.zip",
+        "sha256": "4d6965877301d44241ca6de36480140992dc8a6b1c1884baeb5239ce2c43e071",
+    },
+    "1.2.21": {
+        "version": "1.2.21",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.21/kotlin-compiler-1.2.21.zip",
+        "sha256": "c5f2cbd35daa6c5c394e92e6c06b8eb41d85ad8da64762733874166b6807af22",
+    },
+    "1.2.20": {
+        "version": "1.2.20",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.20/kotlin-compiler-1.2.20.zip",
+        "sha256": "fb63d3d9f37b43f37575e3623c058d42a4b5dc8da08479ab065c4994e421a057",
+    },
+    "1.2.10": {
+        "version": "1.2.10",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.10/kotlin-compiler-1.2.10.zip",
+        "sha256": "95874568919121acb694bec0d6c92c60bdceea53f4c202e23ab734e94a0c26e3",
+    },
+    "1.2.0": {
+        "version": "1.2.0",
+        "url": "https://github.com/JetBrains/kotlin/releases/download/v1.2.0/kotlin-compiler-1.2.0.zip",
+        "sha256": "895d0f8286db3e4f43d67cd5e09b600af6e0a5017cb74072d1b09c78b697775a",
+    },
+}
\ No newline at end of file
diff --git a/kotlin/toolchains.bzl b/kotlin/toolchains.bzl
index 64359ab..733bc06 100644
--- a/kotlin/toolchains.bzl
+++ b/kotlin/toolchains.bzl
@@ -50,7 +50,6 @@
     "kotlin_home": attr.label(
         default = Label("@" + _KT_COMPILER_REPO + "//:home"),
         allow_files = True,
-        cfg = "host"
     ),
     "kotlinbuilder": attr.label(
         default = Label("//kotlin/builder"),
@@ -84,14 +83,13 @@
 
 _kt_jvm_attrs = dict(_common_attrs.items() + {
     "jvm_runtime": attr.label(
-        single_file = True,
-        default = Label("@" + _KT_COMPILER_REPO + "//:runtime"),
+        default = Label("@" + _KT_COMPILER_REPO + "//:kotlin-runtime"),
     ),
     "jvm_stdlibs": attr.label_list(
         default = [
-            Label("@" + _KT_COMPILER_REPO + "//:stdlib"),
-            Label("@" + _KT_COMPILER_REPO + "//:stdlib-jdk7"),
-            Label("@" + _KT_COMPILER_REPO + "//:stdlib-jdk8"),
+            Label("@" + _KT_COMPILER_REPO + "//:kotlin-stdlib"),
+            Label("@" + _KT_COMPILER_REPO + "//:kotlin-stdlib-jdk7"),
+            Label("@" + _KT_COMPILER_REPO + "//:kotlin-stdlib-jdk8"),
         ]
     ),
     "jvm_target": attr.string(