Progmasoft Git

tazel

A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.

Clonegit clone https://git.progmasoft.com/tazel

Keep compiled project files, publish release archives with ReadyToRun

Every command compiled MODULE.csx and every BUILD.csx with Roslyn
again, which made a build that had nothing to do take about three
seconds on a module of a dozen packages.

- A project file is compiled once, to an assembly with its debugging
  information embedded, kept in .tazel/scripts/ under the SHA-256 of what
  it depends on: the cache format, the build of Tazel and the DSL, the
  .NET runtime, the type of the globals, the path it is shown as, the
  plugins' assemblies, the imports and the text. Later runs load it;
  Roslyn is not loaded at all when nothing changed.
- What runs is always that assembly, compiled now or kept, loaded into a
  load context that resolves the plugins' assemblies to those already
  loaded (it replaces Roslyn's InteractiveAssemblyLoader).
- Writes go beside the file and are moved into place; a kept file that
  does not load is compiled again and replaced; a file that cannot be
  written is not kept and the run goes on.
- A file of nothing but using directives has no code and Roslyn emits
  no assembly for it; it is kept empty and does nothing, as before.
- The embedded debugging information gives the line of an exception a
  project file throws ("BUILD.csx: 3: InvalidOperationException: ...").
- tazel clean removes the compiled files.
- The release archives are published with ReadyToRun: the assemblies
  carry machine code for their RID beside the IL, so a command does not
  wait for the JIT first; on another runtime the IL runs as before.

On a generated module of 10 libraries × 10 C++ files (13 project
files), a build with nothing to do: 3.09 s → 0.56 s and 224 → 64 MiB
peak memory; with ReadyToRun 0.40 s.
Commit
6470ee59ac0817ad465d8a99811c10e6ddb17e43
Author
Leitwolf11 ·
Parents
82ed59cd7f79

Files · Download .tar.gz

Changes

 .github/workflows/release.yml                    |   7 +-
 docs/commands.md                                 |   2 +-
 src/Progmasoft.Tazel/Cli/Commands.cs             |   2 +-
 src/Progmasoft.Tazel/Cli/Help.cs                 |   5 +-
 src/Progmasoft.Tazel/Project/Plugins.cs          |  14 +-
 src/Progmasoft.Tazel/Project/ScriptCache.cs      | 194 +++++++++++++++++++++++
 src/Progmasoft.Tazel/Project/ScriptHost.cs       | 107 ++++++++-----
 src/Progmasoft.Tazel/Project/Workspace.cs        |  19 ++-
 tests/Progmasoft.Tazel.Tests/ScriptCacheTests.cs | 153 ++++++++++++++++++
 9 files changed, 439 insertions(+), 64 deletions(-)

diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b5dfb05..a1fcd44 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -65,13 +65,16 @@ jobs:
           version=$(dotnet msbuild src/Progmasoft.Tazel -getProperty:Version)
           test "tazel-$version" = "$TAG" || { echo "the tag $TAG is not tazel-$version" >&2; exit 1; }
 
-      # Framework-dependent: the archive runs on the .NET 10 runtime of the machine.
+      # Framework-dependent: the archive runs on the .NET 10 runtime of the machine. ReadyToRun: the assemblies carry
+      # machine code for the RID beside their IL, so a command does not wait for the JIT to compile Tazel and its
+      # libraries first; on another runtime the IL runs as it is.
       - name: Publish
         shell: bash
         env:
           RID: ${{ matrix.rid }}
         run: |
-          dotnet publish src/Progmasoft.Tazel -c Release -r "$RID" --self-contained false -o "artifacts/$TAG-$RID"
+          dotnet publish src/Progmasoft.Tazel -c Release -r "$RID" --self-contained false -p:PublishReadyToRun=true \
+            -o "artifacts/$TAG-$RID"
           cd artifacts
           if [[ "$RID" == win-* ]]; then
             zip -qr "$TAG-$RID.zip" "$TAG-$RID"
diff --git a/docs/commands.md b/docs/commands.md
index 0e18558..8b52a7f 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -15,7 +15,7 @@
 | `tazel fetch` | downloads and checks the modules and plugins the module depends on, without building |
 | `tazel vendor` | copies the modules of Tazel Portal Modules and their indexes into `vendor/` |
 | `tazel portal-modules search\|info [-e] [--] <module\|group:module>` | searches Tazel Portal Modules, or shows one module |
-| `tazel clean [--expunge]` | removes the outputs, the test logs and zig's cache; `--expunge` removes all of `.tazel` |
+| `tazel clean [--expunge]` | removes the outputs, the test logs, zig's cache and the compiled project files; `--expunge` removes all of `.tazel` |
 | `tazel cache keygen [--algorithm ed25519\|rsa-4096\|ml-dsa]` | prints a key pair for signing the results of a remote cache ([Remote cache](remote-cache.md)) |
 | `tazel package` | writes `.tazel/package/$group.$module-$version.tazel.tar.xz` and its `.sha256sums` |
 | `tazel custom <name> [arguments]` | runs a command of the `tazel_custom.txt` of the current directory |
diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs
index 510c735..fdf0324 100644
--- a/src/Progmasoft.Tazel/Cli/Commands.cs
+++ b/src/Progmasoft.Tazel/Cli/Commands.cs
@@ -125,7 +125,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
         var state = Path.Combine(root, ModuleFiles.StateDirectory);
         var removed = expunge
             ? [state]
-            : new[] { "out", "testlogs", "coverage", "zig-cache", "package", "downloads" }.Select(name => Path.Combine(state, name)).ToArray();
+            : new[] { "out", "testlogs", "coverage", "zig-cache", "package", "downloads", Project.ScriptCache.Directory }.Select(name => Path.Combine(state, name)).ToArray();
         foreach (var directory in removed.Where(Directory.Exists))
         {
             Directory.Delete(directory, recursive: true);
diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs
index a47b352..70d840e 100644
--- a/src/Progmasoft.Tazel/Cli/Help.cs
+++ b/src/Progmasoft.Tazel/Cli/Help.cs
@@ -147,8 +147,9 @@ internal static class Help
         ["clean"] = new("tazel clean [--expunge]: removes what builds made.", """
             tazel clean [--expunge]
 
-            Removes the outputs of every platform and mode, the test logs, the coverage report, zig's cache and the
-            archives of tazel package; --expunge removes all of .tazel, the unpacked dependencies and plugins too.
+            Removes the outputs of every platform and mode, the test logs, the coverage report, zig's cache, the
+            archives of tazel package and the compiled project files; --expunge removes all of .tazel, the unpacked
+            dependencies and plugins too.
             """),
         ["package"] = new("tazel package: writes the archive of the module.", """
             tazel package
diff --git a/src/Progmasoft.Tazel/Project/Plugins.cs b/src/Progmasoft.Tazel/Project/Plugins.cs
index 2bcfda0..b5eae87 100644
--- a/src/Progmasoft.Tazel/Project/Plugins.cs
+++ b/src/Progmasoft.Tazel/Project/Plugins.cs
@@ -8,8 +8,6 @@ using System.Linq;
 using System.Reflection;
 using System.Runtime.Loader;
 using System.Text.Json;
-using MetadataReference = Microsoft.CodeAnalysis.MetadataReference;
-using Microsoft.CodeAnalysis.Scripting.Hosting;
 using NuGet.Versioning;
 using Progmasoft.Tazel.Archive;
 using Progmasoft.Tazel.Dsl.Build.Prelude;
@@ -90,7 +88,7 @@ internal static class Plugins
         return loaded;
     }
 
-    /// <summary>The references, imports and loader that let the BUILD.csx files of a module use its plugins.</summary>
+    /// <summary>The assemblies and imports that let the BUILD.csx files of a module use its plugins.</summary>
     public static ScriptEnvironment EnvironmentFor(IReadOnlyList<LoadedPlugin> plugins)
     {
         ArgumentNullException.ThrowIfNull(plugins);
@@ -99,15 +97,7 @@ internal static class Plugins
             return ScriptEnvironment.Default;
         }
 
-        var loader = new InteractiveAssemblyLoader();
-        var references = new List<MetadataReference>();
-        foreach (var assembly in plugins.SelectMany(plugin => plugin.Assemblies))
-        {
-            loader.RegisterDependency(assembly);
-            references.Add(MetadataReference.CreateFromFile(assembly.Location));
-        }
-
-        return ScriptEnvironment.Default.With(references, plugins.SelectMany(plugin => plugin.Imports), loader);
+        return ScriptEnvironment.With(plugins.SelectMany(plugin => plugin.Assemblies), plugins.SelectMany(plugin => plugin.Imports));
     }
 
     private static LoadedPlugin LoadOne(string mainRoot, LoadedModule module, PluginReference reference, string place)
diff --git a/src/Progmasoft.Tazel/Project/ScriptCache.cs b/src/Progmasoft.Tazel/Project/ScriptCache.cs
new file mode 100644
index 0000000..941c09c
--- /dev/null
+++ b/src/Progmasoft.Tazel/Project/ScriptCache.cs
@@ -0,0 +1,194 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Buffers.Binary;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.Loader;
+using System.Security.Cryptography;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace Progmasoft.Tazel.Project;
+
+/// <summary>
+/// The compiled project files of a module, in <c>.tazel/scripts/</c>: a file is compiled once and its assembly is
+/// loaded on later runs, so a run whose project files did not change does not start the compiler.
+/// </summary>
+/// <remarks>
+/// The name of an assembly is the SHA-256 of everything its code depends on: the format of this cache, the build of
+/// Tazel (the options a file is compiled with are part of it), the .NET runtime, the type of the globals, the path the
+/// file is shown as, the plugins' assemblies, the imports and the text. Nothing else changes what a file compiles to.
+/// </remarks>
+internal static class ScriptCache
+{
+    /// <summary>The directory of the compiled files, below the state directory of the main module.</summary>
+    public const string Directory = "scripts";
+
+    // Changes when what is cached or how it is named changes.
+    private const string Format = "tazel-script/1";
+
+    /// <summary>The name of the compiled form of <paramref name="code"/>.</summary>
+    public static string Key(string code, string shownPath, Type globals, ScriptEnvironment environment)
+    {
+        using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+        void Add(string text)
+        {
+            var bytes = Encoding.UTF8.GetBytes(text);
+            Span<byte> length = stackalloc byte[8];
+            BinaryPrimitives.WriteInt64LittleEndian(length, bytes.Length);
+            hash.AppendData(length);
+            hash.AppendData(bytes);
+        }
+
+        Add(Format);
+        foreach (var assembly in new[] { typeof(ScriptCache).Assembly, typeof(Dsl.DslException).Assembly, typeof(object).Assembly })
+        {
+            Add(assembly.ManifestModule.ModuleVersionId.ToString("N"));
+        }
+
+        Add(Environment.Version.ToString());
+        Add(globals.AssemblyQualifiedName ?? globals.FullName ?? globals.Name);
+        Add(shownPath);
+        foreach (var assembly in environment.Plugins)
+        {
+            Add(assembly.GetName().FullName);
+            Add(assembly.ManifestModule.ModuleVersionId.ToString("N"));
+        }
+
+        foreach (var import in environment.Imports)
+        {
+            Add(import);
+        }
+
+        Add(code);
+        return Convert.ToHexStringLower(hash.GetHashAndReset());
+    }
+
+    /// <summary>Whether <paramref name="directory"/> keeps the compiled file named <paramref name="key"/>.</summary>
+    public static bool IsKept(string directory, string key) => File.Exists(Path.Combine(directory, key + ".dll"));
+
+    /// <summary>The compiled file named <paramref name="key"/> in <paramref name="directory"/>, or null.</summary>
+    public static byte[]? TryRead(string directory, string key)
+    {
+        try
+        {
+            var file = Path.Combine(directory, key + ".dll");
+            return File.Exists(file) && new FileInfo(file).LinkTarget is null ? File.ReadAllBytes(file) : null;
+        }
+        catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+        {
+            return null;
+        }
+    }
+
+    /// <summary>
+    /// Keeps <paramref name="image"/> as <paramref name="key"/>: written beside it and moved into place, so a reader
+    /// sees the whole file or none. A failure leaves the file uncached; the run goes on.
+    /// </summary>
+    public static void TryWrite(string directory, string key, byte[] image)
+    {
+        var partial = Path.Combine(directory, $"{key}.{Guid.NewGuid():N}.partial");
+        try
+        {
+            System.IO.Directory.CreateDirectory(directory);
+            File.WriteAllBytes(partial, image);
+            File.Move(partial, Path.Combine(directory, key + ".dll"), overwrite: true);
+        }
+        catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+        {
+            try
+            {
+                File.Delete(partial);
+            }
+            catch (Exception again) when (again is IOException or UnauthorizedAccessException)
+            {
+                // Nothing more to do: a leftover .partial file is never read.
+            }
+        }
+    }
+}
+
+/// <summary>What a project file is compiled with beyond the DSL: the plugins' assemblies and imports.</summary>
+internal sealed class ScriptEnvironment
+{
+    private readonly Lazy<ScriptLoadContext> context;
+    private readonly ConcurrentDictionary<string, LoadedScript> loaded = new(StringComparer.Ordinal);
+
+    private ScriptEnvironment(IReadOnlyList<Assembly> plugins, IReadOnlyList<string> imports)
+    {
+        Plugins = plugins;
+        Imports = imports;
+        context = new Lazy<ScriptLoadContext>(() => new ScriptLoadContext(plugins));
+    }
+
+    /// <summary>The DSL alone.</summary>
+    public static ScriptEnvironment Default { get; } = new([], []);
+
+    /// <summary>The assemblies of the plugins, which project files may use.</summary>
+    public IReadOnlyList<Assembly> Plugins { get; }
+
+    /// <summary>The namespaces of the plugins that project files see without a <c>using</c>.</summary>
+    public IReadOnlyList<string> Imports { get; }
+
+    /// <summary>The DSL with the assemblies and imports of plugins.</summary>
+    public static ScriptEnvironment With(IEnumerable<Assembly> plugins, IEnumerable<string> imports) =>
+        new(plugins.ToList(), imports.ToList());
+
+    /// <summary>
+    /// The compiled file named <paramref name="key"/>, loaded once per environment, so running a file again in the
+    /// same process does not load its assembly twice.
+    /// </summary>
+    public LoadedScript Entry(string key, Func<byte[]> image) =>
+        loaded.GetOrAdd(key, _ =>
+        {
+            var bytes = image();
+            return new LoadedScript(bytes, context.Value.Entry(bytes));
+        });
+}
+
+/// <summary>A compiled project file: its assembly and its entry, which takes the submission array.</summary>
+internal sealed record LoadedScript(byte[] Image, Func<object?[], Task<object>> Entry);
+
+/// <summary>Where compiled project files are loaded: the plugins' assemblies resolve to those already loaded.</summary>
+internal sealed class ScriptLoadContext : AssemblyLoadContext
+{
+    // The class and the method Roslyn compiles the first submission of a script to.
+    private const string SubmissionType = "Submission#0";
+    private const string FactoryMethod = "<Factory>";
+
+    private readonly IReadOnlyList<Assembly> plugins;
+
+    public ScriptLoadContext(IReadOnlyList<Assembly> plugins)
+        : base("tazel-project-files")
+    {
+        this.plugins = plugins;
+    }
+
+    /// <summary>
+    /// Loads <paramref name="image"/> and returns its entry, which takes the submission array: the globals first, a
+    /// place for the submission itself second.
+    /// </summary>
+    public Func<object?[], Task<object>> Entry(byte[] image)
+    {
+        if (image.Length == 0)
+        {
+            return _ => Task.FromResult<object>(null!);
+        }
+
+        using var stream = new MemoryStream(image, writable: false);
+        var assembly = LoadFromStream(stream);
+        var factory = assembly.GetType(SubmissionType, throwOnError: true)!
+            .GetMethod(FactoryMethod, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
+            ?? throw new BadImageFormatException($"a compiled project file has no {FactoryMethod}");
+        return factory.CreateDelegate<Func<object?[], Task<object>>>();
+    }
+
+    /// <inheritdoc/>
+    protected override Assembly? Load(AssemblyName assemblyName) =>
+        plugins.FirstOrDefault(plugin => string.Equals(plugin.GetName().Name, assemblyName.Name, StringComparison.Ordinal));
+}
diff --git a/src/Progmasoft.Tazel/Project/ScriptHost.cs b/src/Progmasoft.Tazel/Project/ScriptHost.cs
index e46e105..fccfde7 100644
--- a/src/Progmasoft.Tazel/Project/ScriptHost.cs
+++ b/src/Progmasoft.Tazel/Project/ScriptHost.cs
@@ -5,14 +5,13 @@ using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
-using System.Reflection;
 using System.Text;
 using System.Threading.Tasks;
 using Microsoft.CodeAnalysis;
 using Microsoft.CodeAnalysis.CSharp;
 using Microsoft.CodeAnalysis.CSharp.Scripting;
+using Microsoft.CodeAnalysis.Emit;
 using Microsoft.CodeAnalysis.Scripting;
-using Microsoft.CodeAnalysis.Scripting.Hosting;
 using Progmasoft.Tazel.Dsl;
 
 namespace Progmasoft.Tazel.Project;
@@ -39,48 +38,104 @@ public sealed class ProjectException : Exception
 }
 
 /// <summary>Runs <c>MODULE.csx</c> and <c>BUILD.csx</c> files with the C# scripting of Roslyn.</summary>
+/// <remarks>
+/// A file is compiled to an assembly with its debugging information embedded, and that assembly is what runs, whether
+/// it was compiled now or kept from an earlier run (<see cref="ScriptCache"/>). The compiler is loaded only when a file
+/// is compiled: only <see cref="Emit"/> and <see cref="CreateOptions"/> use its types.
+/// </remarks>
 internal static class ScriptHost
 {
     /// <summary>The namespace every project file sees without a <c>using</c>.</summary>
     public const string CommonNamespace = "Progmasoft.Tazel.Dsl.Common";
 
+    private static readonly Lazy<ScriptOptions> BaseOptionsValue = new(CreateOptions);
+
     /// <summary>The options every project file is compiled with.</summary>
-    internal static ScriptOptions BaseOptions { get; } = CreateOptions();
+    internal static ScriptOptions BaseOptions => BaseOptionsValue.Value;
 
     /// <summary>
     /// Compiles and runs <paramref name="code"/> with <paramref name="globals"/>; <paramref name="shownPath"/> names
-    /// the file in messages. A compile error or an exception of the script becomes a <see cref="ProjectException"/>.
+    /// the file in messages. The compiled file is kept in the state directory of <paramref name="mainRoot"/>, the root
+    /// of the main module; null keeps nothing. A compile error or an exception of the script becomes a
+    /// <see cref="ProjectException"/>.
     /// </summary>
     public static async Task RunAsync<TGlobals>(
-        string code, string shownPath, TGlobals globals, ScriptEnvironment? environment = null)
+        string code, string shownPath, TGlobals globals, string? mainRoot, ScriptEnvironment? environment = null)
         where TGlobals : class
     {
         var used = environment ?? ScriptEnvironment.Default;
-        var script = CSharpScript.Create(code, used.Options.WithFilePath(shownPath), typeof(TGlobals), used.Loader);
-        var errors = script.Compile().Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
-        if (errors.Count > 0)
+        var key = ScriptCache.Key(code, shownPath, typeof(TGlobals), used);
+        var directory = mainRoot is null ? null : Path.Combine(mainRoot, ModuleFiles.StateDirectory, ScriptCache.Directory);
+        LoadedScript loaded;
+        try
         {
-            throw new ProjectException(Describe(errors, shownPath));
+            loaded = used.Entry(key, () => Image(code, shownPath, typeof(TGlobals), used, directory, key, reuse: true));
+        }
+        catch (BadImageFormatException) when (directory is not null)
+        {
+            // A kept file that does not load is compiled again and replaced.
+            loaded = used.Entry(key, () => Image(code, shownPath, typeof(TGlobals), used, directory, key, reuse: false));
+        }
+
+        // Loaded before in this process, perhaps for another module: this module keeps it too.
+        if (directory is not null && !ScriptCache.IsKept(directory, key))
+        {
+            ScriptCache.TryWrite(directory, key, loaded.Image);
         }
 
         try
         {
-            await script.RunAsync(globals).ConfigureAwait(false);
+            await loaded.Entry([globals, null]).ConfigureAwait(false);
         }
         catch (DslException error)
         {
             throw new ProjectException(error.Message, error);
         }
-        catch (CompilationErrorException error)
-        {
-            throw new ProjectException(Describe(error.Diagnostics, shownPath), error);
-        }
         catch (Exception error)
         {
             throw new ProjectException($"{shownPath}: {Where(error, shownPath)}{error.GetType().Name}: {error.Message}", error);
         }
     }
 
+    // The compiled file: the one kept under its key, else compiled now and kept.
+    private static byte[] Image(
+        string code, string shownPath, Type globals, ScriptEnvironment environment, string? directory, string key, bool reuse)
+    {
+        if (reuse && directory is not null && ScriptCache.TryRead(directory, key) is { } kept)
+        {
+            return kept;
+        }
+
+        var image = Emit(code, shownPath, globals, environment);
+        if (directory is not null)
+        {
+            ScriptCache.TryWrite(directory, key, image);
+        }
+
+        return image;
+    }
+
+    private static byte[] Emit(string code, string shownPath, Type globals, ScriptEnvironment environment)
+    {
+        var options = BaseOptions
+            .AddReferences(environment.Plugins.Select(assembly => MetadataReference.CreateFromFile(assembly.Location)))
+            .AddImports(environment.Imports)
+            .WithFilePath(shownPath)
+            .WithFileEncoding(Encoding.UTF8);
+        var compilation = CSharpScript.Create(code, options, globals).GetCompilation();
+        using var image = new MemoryStream();
+        // The debugging information names the lines of the file in the stack trace of an exception it throws.
+        var result = compilation.Emit(image, options: new EmitOptions(debugInformationFormat: DebugInformationFormat.Embedded));
+        if (result.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
+        {
+            throw new ProjectException(Describe(result.Diagnostics, shownPath));
+        }
+
+        // A file of nothing but using directives has no code, and Roslyn emits no assembly for it: it is kept as an
+        // empty file, whose entry does nothing.
+        return result.Success ? image.ToArray() : [];
+    }
+
     private static ScriptOptions CreateOptions()
     {
         // The whole base class library: every managed assembly of the .NET runtime Tazel runs on, as the host lists
@@ -108,7 +163,6 @@ internal static class ScriptHost
             .WithImports(CommonNamespace)
             .WithLanguageVersion(LanguageVersion.Latest)
             .WithOptimizationLevel(OptimizationLevel.Debug)
-            .WithEmitDebugInformation(false)
             .WithAllowUnsafe(false)
             .WithCheckOverflow(true);
     }
@@ -143,26 +197,3 @@ internal static class ScriptHost
         return "";
     }
 }
-
-/// <summary>What a project file is compiled with beyond the DSL: the plugins' references, imports and loader.</summary>
-internal sealed class ScriptEnvironment
-{
-    private ScriptEnvironment(ScriptOptions options, InteractiveAssemblyLoader? loader)
-    {
-        Options = options;
-        Loader = loader;
-    }
-
-    /// <summary>The DSL alone.</summary>
-    public static ScriptEnvironment Default { get; } = new(ScriptHost.BaseOptions, null);
-
-    public ScriptOptions Options { get; }
-
-    /// <summary>The loader that finds the plugins' assemblies in their load contexts; null without plugins.</summary>
-    public InteractiveAssemblyLoader? Loader { get; }
-
-    /// <summary>This environment with more references and imports, and the loader of the plugins.</summary>
-    public ScriptEnvironment With(
-        IEnumerable<MetadataReference> references, IEnumerable<string> imports, InteractiveAssemblyLoader loader) =>
-        new(Options.AddReferences(references).AddImports(imports), loader);
-}
diff --git a/src/Progmasoft.Tazel/Project/Workspace.cs b/src/Progmasoft.Tazel/Project/Workspace.cs
index d1ab5c7..075a3e9 100644
--- a/src/Progmasoft.Tazel/Project/Workspace.cs
+++ b/src/Progmasoft.Tazel/Project/Workspace.cs
@@ -104,7 +104,7 @@ internal sealed class Workspace
         string directory, BuildContext build, Version tazelVersion, Action<string>? status = null)
     {
         var root = ModuleFiles.FindRoot(directory);
-        var main = await LoadModuleAsync(root, null, tazelVersion).ConfigureAwait(false);
+        var main = await LoadModuleAsync(root, null, tazelVersion, root).ConfigureAwait(false);
         var workspace = new Workspace(main);
         await workspace.LoadDependenciesAsync(main, tazelVersion).ConfigureAwait(false);
         await workspace.LoadPortalModulesAsync(tazelVersion, offline: false).ConfigureAwait(false);
@@ -119,10 +119,13 @@ internal sealed class Workspace
     }
 
     /// <summary>Runs only the MODULE.csx of the module <paramref name="directory"/> is in.</summary>
-    public static Task<LoadedModule> LoadMainModuleAsync(string directory, Version tazelVersion) =>
-        LoadModuleAsync(ModuleFiles.FindRoot(directory), null, tazelVersion);
+    public static Task<LoadedModule> LoadMainModuleAsync(string directory, Version tazelVersion)
+    {
+        var root = ModuleFiles.FindRoot(directory);
+        return LoadModuleAsync(root, null, tazelVersion, root);
+    }
 
-    private static async Task<LoadedModule> LoadModuleAsync(string root, string? repository, Version tazelVersion)
+    private static async Task<LoadedModule> LoadModuleAsync(string root, string? repository, Version tazelVersion, string mainRoot)
     {
         var file = Path.Combine(root, ModuleFiles.ModuleFile);
         var shown = repository is null ? ModuleFiles.ModuleFile : $"@{repository}//{ModuleFiles.ModuleFile}";
@@ -130,7 +133,7 @@ internal sealed class Workspace
         var environment = EnvironmentOf(root, repository);
         using (Dsl.Environment.EnvironmentValues.Enter(environment))
         {
-            await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals)
+            await ScriptHost.RunAsync(await File.ReadAllTextAsync(file).ConfigureAwait(false), shown, globals, mainRoot)
                 .ConfigureAwait(false);
         }
 
@@ -211,7 +214,7 @@ internal sealed class Workspace
             }
 
             var unpacked = LocalModules.Unpack(Main.Root, module.Root, local, place);
-            var loaded = await LoadModuleAsync(unpacked, local.Name, tazelVersion).ConfigureAwait(false);
+            var loaded = await LoadModuleAsync(unpacked, local.Name, tazelVersion, Main.Root).ConfigureAwait(false);
             External[local.Name] = loaded;
             await LoadDependenciesAsync(loaded, tazelVersion).ConfigureAwait(false);
         }
@@ -243,7 +246,7 @@ internal sealed class Workspace
 
             var root = await PortalDependencies.FetchAsync(Main.Root, module, offline ? null : client,
                 System.Threading.CancellationToken.None).ConfigureAwait(false);
-            External[module.Repository] = await LoadModuleAsync(root, module.Repository, tazelVersion).ConfigureAwait(false);
+            External[module.Repository] = await LoadModuleAsync(root, module.Repository, tazelVersion, Main.Root).ConfigureAwait(false);
             PortalModules.Add(module);
         }
     }
@@ -281,7 +284,7 @@ internal sealed class Workspace
             using (Declarations.Enter(scope))
             using (Dsl.Environment.EnvironmentValues.Enter(module.Environment))
             {
-                await ScriptHost.RunAsync(code, shown, new BuildGlobals(build), environment).ConfigureAwait(false);
+                await ScriptHost.RunAsync(code, shown, new BuildGlobals(build), Main.Root, environment).ConfigureAwait(false);
             }
 
             return (Package: package, Scope: scope);
diff --git a/tests/Progmasoft.Tazel.Tests/ScriptCacheTests.cs b/tests/Progmasoft.Tazel.Tests/ScriptCacheTests.cs
new file mode 100644
index 0000000..4bd2473
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/ScriptCacheTests.cs
@@ -0,0 +1,153 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.Label;
+using Progmasoft.Tazel.Project;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class ScriptCacheTests
+{
+    private const string Prelude = "using Progmasoft.Tazel.Dsl.Build.Prelude;\n";
+
+    private static string[] Kept(TemporaryModule module)
+    {
+        var directory = Path.Combine(module.Root, ".tazel", ScriptCache.Directory);
+        return Directory.Exists(directory) ? Directory.GetFiles(directory).Order(StringComparer.Ordinal).ToArray() : [];
+    }
+
+    [Fact]
+    public async Task KeepsEveryCompiledFileAndUsesItAgain()
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile)
+            .Write("BUILD.csx", Prelude + "CC.StaticLibrary(\"a\", new());")
+            .Write("lib/BUILD.csx", Prelude + "CC.StaticLibrary(\"b\", new());");
+        await module.LoadAsync();
+        var kept = Kept(module);
+        Assert.Equal(3, kept.Length);
+        Assert.All(kept, file => Assert.EndsWith(".dll", file, StringComparison.Ordinal));
+        var written = kept.Select(File.GetLastWriteTimeUtc).ToArray();
+
+        var workspace = await module.LoadAsync();
+        Assert.Equal(kept, Kept(module));
+        Assert.Equal(written, kept.Select(File.GetLastWriteTimeUtc));
+        Assert.Equal(["//:a", "//lib:b"],
+            workspace.Targets.Keys.Select(label => label.ToString()).Order(StringComparer.Ordinal));
+    }
+
+    [Fact]
+    public async Task AnEditedFileIsCompiledAgainUnderAnotherName()
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Prelude + "CC.StaticLibrary(\"a\", new());");
+        await module.LoadAsync();
+        module.Write("BUILD.csx", Prelude + "CC.StaticLibrary(\"b\", new());");
+        var workspace = await module.LoadAsync();
+        Assert.Equal(3, Kept(module).Length);
+        Assert.Equal(new TargetLabel(PackageId.Root, "b"), Assert.Single(workspace.Targets.Keys));
+    }
+
+    [Fact]
+    public async Task ADamagedFileIsCompiledAgainAndReplaced()
+    {
+        using var module = new TemporaryModule();
+        // A new environment each time: in it nothing is loaded yet, as in a new process.
+        var first = new Counter();
+        await ScriptHost.RunAsync("Count += 1;", "BUILD.csx", first, module.Root, ScriptEnvironment.With([], []));
+        var kept = Assert.Single(Kept(module));
+        File.WriteAllText(kept, "not an assembly");
+
+        var second = new Counter();
+        await ScriptHost.RunAsync("Count += 1;", "BUILD.csx", second, module.Root, ScriptEnvironment.With([], []));
+        Assert.Equal(1, second.Count);
+        Assert.NotEqual("not an assembly", File.ReadAllText(Assert.Single(Kept(module))));
+
+        var third = new Counter();
+        await ScriptHost.RunAsync("Count += 1;", "BUILD.csx", third, module.Root, ScriptEnvironment.With([], []));
+        Assert.Equal(1, third.Count);
+    }
+
+    [Fact]
+    public async Task AFileOfUsingsAloneRunsAndIsKept()
+    {
+        using var module = new TemporaryModule();
+        var globals = new Counter();
+        await ScriptHost.RunAsync("using System;", "BUILD.csx", globals, module.Root, ScriptEnvironment.With([], []));
+        await ScriptHost.RunAsync("using System;", "BUILD.csx", globals, module.Root, ScriptEnvironment.With([], []));
+        Assert.Equal(0, globals.Count);
+        Assert.Empty(File.ReadAllBytes(Assert.Single(Kept(module))));
+    }
+
+    [Fact]
+    public async Task WithoutARootNothingIsKept()
+    {
+        var globals = new Counter();
+        await ScriptHost.RunAsync("Count += 2;", "BUILD.csx", globals, null, ScriptEnvironment.With([], []));
+        Assert.Equal(2, globals.Count);
+    }
+
+    [Fact]
+    public async Task AnExceptionNamesItsLineWhenTheFileWasKept()
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile)
+            .Write("BUILD.csx", Prelude + "\nthrow new System.InvalidOperationException(\"no\");");
+        for (var run = 0; run < 2; run++)
+        {
+            var error = await Assert.ThrowsAsync<ProjectException>(() => module.LoadAsync());
+            Assert.Equal("BUILD.csx: 3: InvalidOperationException: no", error.Message);
+        }
+    }
+
+    [Fact]
+    public async Task CleanRemovesTheCompiledFiles()
+    {
+        using var module = new TemporaryModule();
+        module.Write("MODULE.csx", TemporaryModule.ModuleFile).Write("BUILD.csx", Prelude + "CC.StaticLibrary(\"a\", new());");
+        await module.LoadAsync();
+        Assert.NotEmpty(Kept(module));
+        var (status, output) = await module.TazelAsync("", "clean");
+        Assert.True(status == 0, output);
+        Assert.Empty(Kept(module));
+    }
+
+    [Fact]
+    public void TheNameDependsOnTheTextThePathAndTheGlobals()
+    {
+        var environment = ScriptEnvironment.Default;
+        var key = ScriptCache.Key("x", "BUILD.csx", typeof(object), environment);
+        Assert.Equal(64, key.Length);
+        Assert.Equal(key, ScriptCache.Key("x", "BUILD.csx", typeof(object), environment));
+        Assert.NotEqual(key, ScriptCache.Key("y", "BUILD.csx", typeof(object), environment));
+        Assert.NotEqual(key, ScriptCache.Key("x", "lib/BUILD.csx", typeof(object), environment));
+        Assert.NotEqual(key, ScriptCache.Key("x", "BUILD.csx", typeof(string), environment));
+        // Framing: moving text from one part to the next is another name.
+        Assert.NotEqual(ScriptCache.Key("ab", "c", typeof(object), environment), ScriptCache.Key("a", "bc", typeof(object), environment));
+        Assert.NotEqual(key, ScriptCache.Key("x", "BUILD.csx", typeof(object),
+            ScriptEnvironment.With([typeof(ScriptCacheTests).Assembly], [])));
+        Assert.NotEqual(key, ScriptCache.Key("x", "BUILD.csx", typeof(object), ScriptEnvironment.With([], ["System.Text"])));
+    }
+
+    [Fact]
+    public void AFileThatCannotBeWrittenIsNotKept()
+    {
+        using var module = new TemporaryModule();
+        var blocked = Path.Combine(module.Root, "file");
+        File.WriteAllText(blocked, "");
+        ScriptCache.TryWrite(Path.Combine(blocked, "scripts"), "k", [1, 2, 3]);
+        Assert.Null(ScriptCache.TryRead(Path.Combine(blocked, "scripts"), "k"));
+        Assert.Null(ScriptCache.TryRead(module.Root, "missing"));
+    }
+
+    /// <summary>The globals of the scripts above.</summary>
+    public sealed class Counter
+    {
+        public int Count { get; set; }
+    }
+}