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

Add tazel cache validate and tazel cache repair

- validate reads .tazel and changes nothing. Action records are valid
  (every file has its recorded digest), stale (an input changed: what
  builds work from) or broken (unreadable, malformed, not naming the
  output beside it, or that output gone or changed while everything
  else is as recorded). Test results are broken with a key that is no
  digest or without their log; compiled project files with a name that
  is no digest or metadata that does not read (read, never loaded; an
  empty image is a script of usings). Half-written files are counted.
  Each broken entry is E0508 and the command exits 1.
- repair removes broken entries and half-written files, never stale
  records or outputs, so the next build redoes them.
- --remote reads MODULE.csx: a request for a random key must come back
  404 (reached and let in), and a SigningKey must sign what the
  PublicKey verifies. repair --remote, for a cache that takes writes,
  plans //... for this platform in debug and stores again the results
  of valid local records that the cache lacks or holds untrusted
  (RemoteActions.HoldsTrustedAsync).
- --remote belongs to validate and repair, --algorithm to keygen.
Commit
0bbcafd71a5e73e36a17c2ce328427f4d4bba07d
Author
Leitwolf11 ·
Parents
c605a590fe07

Files · Download .tar.gz

Changes

 CHANGELOG.md                                    |   4 +
 docs/commands.md                                |  17 ++
 src/Progmasoft.Tazel/Cache/RemoteActions.cs     |  17 ++
 src/Progmasoft.Tazel/Cli/CacheCommands.cs       | 272 ++++++++++++++++++++++++
 src/Progmasoft.Tazel/Cli/CommandLine.cs         |  15 +-
 src/Progmasoft.Tazel/Cli/Commands.cs            |   1 +
 src/Progmasoft.Tazel/Cli/Help.cs                |  14 +-
 src/Progmasoft.Tazel/Cli/RemoteCacheCommands.cs | 150 +++++++++++++
 src/Progmasoft.Tazel/Output/ErrorCodes.cs       |   9 +
 tests/Progmasoft.Tazel.Tests/CacheCheckTests.cs | 212 ++++++++++++++++++
 10 files changed, 709 insertions(+), 2 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3c825d0..ca660e7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,10 @@
 
 ## Unreleased
 
+- `tazel cache validate [--remote]` checks the action records, test results and compiled project files of `.tazel`
+  (valid, stale, broken), and with `--remote` the remote cache and its keys; `tazel cache repair [--remote]` removes
+  what is broken, and stores again in the remote cache what it lacks. Error `E0508`.
+
 - `.tazelignore`: gitignore rules, `regex:` and `!regex:`, `pragma:once`, `import:` and `include:`, nested per
   directory, for package discovery, patterns, source globs and module archives; explicit paths and labels are never
   ignored. `tazel ignore create-from|validate|add|delete|del`. Error `E0013`.
diff --git a/docs/commands.md b/docs/commands.md
index d08f124..a82a3ba 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -17,6 +17,8 @@
 | `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, 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 cache validate [--remote]` | checks the records of `.tazel`, and with `--remote` the remote cache and its keys; changes nothing |
+| `tazel cache repair [--remote]` | removes broken records; with `--remote`, stores again what the remote cache lacks |
 | `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 |
 | `tazel version`, `tazel help [command] [--long]` | print the version, or what Tazel or one command does |
@@ -57,6 +59,21 @@ the compiler takes the last flag, and they are part of the key of each action.
 The platform comes from `--platform`, else from `tazel_options.txt`, else it is this machine's. `--jobs` and
 `--keep-going` win over `Execution` of `MODULE.csx`.
 
+## Checking the caches
+
+`tazel cache validate` sorts the action records of `.tazel` into valid, stale and broken. A stale record names an
+input that changed: that is how builds find what to run, not a fault. A broken one cannot be read, or the output it is
+kept beside is gone or changed while every input is as recorded, which means something touched the file behind
+Tazel's back. A test result without its log and a compiled project file whose metadata does not read are broken too;
+each is an `error[E0508]`, and the command exits 1. `tazel cache repair` removes what is broken and the files writes
+left half done, and the next build redoes them; it keeps stale records and outputs. Run it when no build runs.
+
+With `--remote` both read `MODULE.csx`. `validate` asks the remote cache for a key no action has: a 404 means it is
+reached and lets this machine in, an error or no answer exits 1. A `SigningKey` with a `PublicKey` must sign what the
+`PublicKey` verifies. `repair --remote`, for a cache that takes writes, plans `//...` for this machine's platform in
+debug and stores again every result whose local record is valid and that the cache lacks or holds without a signature
+the `PublicKey` takes; HTTP caches have no delete, so nothing is removed there.
+
 ## Recompile and no-cache
 
 | | default | `--recompile` | `--no-cache` |
diff --git a/src/Progmasoft.Tazel/Cache/RemoteActions.cs b/src/Progmasoft.Tazel/Cache/RemoteActions.cs
index 586e46f..5bdd10f 100644
--- a/src/Progmasoft.Tazel/Cache/RemoteActions.cs
+++ b/src/Progmasoft.Tazel/Cache/RemoteActions.cs
@@ -118,6 +118,23 @@ internal sealed class RemoteActions(
         }
     }
 
+    /// <summary>
+    /// Whether the cache holds a result for <paramref name="action"/> that this reader would take: there, readable and
+    /// signed as the PublicKey wants; true for an action the cache has no place for.
+    /// </summary>
+    public async Task<bool> HoldsTrustedAsync(BuildAction action, CancellationToken cancel)
+    {
+        ArgumentNullException.ThrowIfNull(action);
+        if (action.Work is not null || KeyOf(action) is not { } key)
+        {
+            return true;
+        }
+
+        return await cache.GetActionAsync(key, cancel).ConfigureAwait(false) is { } message &&
+            ActionResultMessage.Decode(message) is { } files &&
+            await IsTrustedAsync(key, files, cancel).ConfigureAwait(false);
+    }
+
     /// <summary>Gives the cache the outputs of <paramref name="action"/>, which just succeeded here.</summary>
     public async Task StoreAsync(BuildAction action, CancellationToken cancel)
     {
diff --git a/src/Progmasoft.Tazel/Cli/CacheCommands.cs b/src/Progmasoft.Tazel/Cli/CacheCommands.cs
new file mode 100644
index 0000000..a294cc0
--- /dev/null
+++ b/src/Progmasoft.Tazel/Cli/CacheCommands.cs
@@ -0,0 +1,272 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Reflection.PortableExecutable;
+using System.Text;
+using Progmasoft.Tazel.Driver;
+using Progmasoft.Tazel.Output;
+using Progmasoft.Tazel.Project;
+
+namespace Progmasoft.Tazel.Cli;
+
+/// <summary><c>tazel cache validate [--remote]</c> and <c>tazel cache repair [--remote]</c>.</summary>
+internal sealed record CacheCheckCommand(OutputOptions Output, bool Repair, bool Remote) : Command(Output);
+
+/// <summary>What the local caches hold, by kind.</summary>
+internal sealed record CacheCensus(int Valid, int Stale, IReadOnlyList<(string File, string Reason)> Broken, IReadOnlyList<string> Leftovers);
+
+/// <summary>
+/// Checks the caches of a module. An action record is valid when every file it names has the digest it recorded;
+/// stale when an input changed, which only means the next build runs it; broken when it cannot be read, or the
+/// output it is named after is missing or changed while everything else is as recorded. A test result is broken
+/// without its log or with a key that is not a digest. A compiled project file is broken when its metadata does not
+/// read; an empty one is the image of a file of usings only. Files a write left half done are leftovers.
+/// </summary>
+internal sealed class CacheChecks(string root)
+{
+    private readonly string _state = Path.Combine(root, ModuleFiles.StateDirectory);
+
+    /// <summary>The action records below <c>.tazel</c>.</summary>
+    public CacheCensus Actions()
+    {
+        var (valid, stale) = (0, 0);
+        var broken = new List<(string, string)>();
+        foreach (var record in Files("*.action"))
+        {
+            switch (Classify(record, out var reason))
+            {
+                case RecordState.Valid:
+                    valid++;
+                    break;
+                case RecordState.Stale:
+                    stale++;
+                    break;
+                default:
+                    broken.Add((record, reason!));
+                    break;
+            }
+        }
+
+        return new CacheCensus(valid, stale, broken, Files("*.partial").ToList());
+    }
+
+    /// <summary>The recorded passes of tests.</summary>
+    public CacheCensus Tests()
+    {
+        var logs = Path.Combine(_state, "testlogs");
+        var passed = Path.Combine(logs, ".passed");
+        if (!Directory.Exists(passed))
+        {
+            return new CacheCensus(0, 0, [], []);
+        }
+
+        // A pass is kept under the log directory's path with / as _ (a test of the root package with a _ before it);
+        // the log must be there.
+        var logged = Directory.EnumerateFiles(logs, "test.log", SearchOption.AllDirectories)
+            .Select(file => Path.GetRelativePath(logs, Path.GetDirectoryName(file)!).Replace('\\', '/'))
+            .SelectMany(directory => new[] { directory.Replace('/', '_'), "_" + directory.Replace('/', '_') })
+            .ToHashSet(StringComparer.Ordinal);
+        var (valid, broken) = (0, new List<(string, string)>());
+        foreach (var file in Directory.EnumerateFiles(passed).Order(StringComparer.Ordinal))
+        {
+            var key = File.ReadAllText(file);
+            if (!IsDigest(key))
+            {
+                broken.Add((file, "its key is not a SHA-256 digest"));
+            }
+            else if (!logged.Contains(Path.GetFileName(file)))
+            {
+                broken.Add((file, "the log of the run it records is not there"));
+            }
+            else
+            {
+                valid++;
+            }
+        }
+
+        return new CacheCensus(valid, 0, broken, []);
+    }
+
+    /// <summary>The compiled project files in <c>.tazel/scripts</c>.</summary>
+    public CacheCensus Scripts()
+    {
+        var directory = Path.Combine(_state, ScriptCache.Directory);
+        if (!Directory.Exists(directory))
+        {
+            return new CacheCensus(0, 0, [], []);
+        }
+
+        var (valid, broken) = (0, new List<(string, string)>());
+        foreach (var file in Directory.EnumerateFiles(directory, "*.dll").Order(StringComparer.Ordinal))
+        {
+            if (!IsDigest(Path.GetFileNameWithoutExtension(file)))
+            {
+                broken.Add((file, "its name is not the SHA-256 digest of a project file"));
+            }
+            else if (!ReadsAsAssembly(file))
+            {
+                broken.Add((file, "it is not an assembly whose metadata reads"));
+            }
+            else
+            {
+                valid++;
+            }
+        }
+
+        return new CacheCensus(valid, 0, broken, Directory.EnumerateFiles(directory, "*.partial").ToList());
+    }
+
+    private IEnumerable<string> Files(string pattern) => Directory.Exists(_state)
+        ? Directory.EnumerateFiles(_state, pattern, SearchOption.AllDirectories)
+            .Where(file => !file.Contains($"{Path.DirectorySeparatorChar}{ScriptCache.Directory}{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
+            .Order(StringComparer.Ordinal)
+        : [];
+
+    private enum RecordState
+    {
+        Valid,
+        Stale,
+        Broken,
+    }
+
+    private static RecordState Classify(string record, out string? reason)
+    {
+        reason = null;
+        string[] lines;
+        try
+        {
+            lines = File.ReadAllLines(record);
+        }
+        catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+        {
+            reason = $"it cannot be read: {error.Message}";
+            return RecordState.Broken;
+        }
+
+        var files = new Dictionary<string, string>(StringComparer.Ordinal);
+        if (lines.Length == 0 || !lines[0].StartsWith("key ", StringComparison.Ordinal) || !IsDigest(lines[0][4..]))
+        {
+            reason = "it does not start with the key of its action";
+            return RecordState.Broken;
+        }
+
+        foreach (var line in lines.Skip(1))
+        {
+            var parts = line.Split(' ', 3);
+            if (parts.Length != 3 || parts[0] != "file" || !IsDigest(parts[1]) || parts[2].Length == 0)
+            {
+                reason = $"'{line}' is not a line of a record";
+                return RecordState.Broken;
+            }
+
+            files[parts[2]] = parts[1];
+        }
+
+        var output = record[..^".action".Length];
+        if (!files.TryGetValue(output, out var recorded))
+        {
+            reason = "it does not name the output it is kept beside";
+            return RecordState.Broken;
+        }
+
+        var changed = files.Where(entry => DigestOf(entry.Key) != entry.Value).Select(entry => entry.Key).ToList();
+        if (changed.Count == 0)
+        {
+            return RecordState.Valid;
+        }
+
+        if (changed is [var only] && only == output)
+        {
+            reason = DigestOf(output) is null
+                ? $"{output} is gone while its inputs are as recorded"
+                : $"{output} changed while its inputs are as recorded (it was {recorded[..12]}…)";
+            return RecordState.Broken;
+        }
+
+        return RecordState.Stale;
+    }
+
+    private static string? DigestOf(string file)
+    {
+        try
+        {
+            return File.Exists(file) ? Digests.Sha256(File.ReadAllBytes(file)) : null;
+        }
+        catch (Exception error) when (error is IOException or UnauthorizedAccessException)
+        {
+            return null;
+        }
+    }
+
+    private static bool IsDigest(string text) => text.Length == 64 && text.All(char.IsAsciiHexDigitLower);
+
+    // Read, never loaded: the metadata of an assembly, or nothing at all for a file of usings only.
+    private static bool ReadsAsAssembly(string file)
+    {
+        try
+        {
+            using var stream = File.OpenRead(file);
+            if (stream.Length == 0)
+            {
+                return true;
+            }
+
+            using var reader = new PEReader(stream);
+            return reader.HasMetadata && System.Reflection.Metadata.PEReaderExtensions.GetMetadataReader(reader).IsAssembly;
+        }
+        catch (Exception error) when (error is BadImageFormatException or IOException or InvalidOperationException)
+        {
+            return false;
+        }
+    }
+}
+
+/// <summary>The local part of <c>tazel cache validate</c> and <c>tazel cache repair</c>.</summary>
+internal sealed class CacheCommands(Reporter reporter, string workingDirectory)
+{
+    /// <summary>Says what the local caches hold; with <paramref name="repair"/>, removes what is broken. The broken left.</summary>
+    public int RunLocal(bool repair)
+    {
+        var root = ModuleFiles.FindRoot(workingDirectory);
+        var checks = new CacheChecks(root);
+        var broken = 0;
+        foreach (var (name, census) in new[] { ("action records", checks.Actions()), ("test results", checks.Tests()), ("compiled project files", checks.Scripts()) })
+        {
+            reporter.Plain($"{name}: {census.Valid} valid, {census.Stale} stale, {census.Broken.Count} broken" +
+                (census.Leftovers.Count > 0 ? $", {census.Leftovers.Count} left half written" : ""));
+            foreach (var (file, reason) in census.Broken)
+            {
+                if (repair)
+                {
+                    File.Delete(file);
+                    reporter.Plain($"removed {Shown(file)}: {reason}");
+                }
+                else
+                {
+                    reporter.Error(ErrorCodes.CacheBroken, $"{Shown(file)}: {reason}", "tazel cache repair removes it, and the next build redoes it");
+                    broken++;
+                }
+            }
+
+            if (repair)
+            {
+                foreach (var leftover in census.Leftovers)
+                {
+                    File.Delete(leftover);
+                }
+            }
+        }
+
+        return broken;
+    }
+
+    private string Shown(string file)
+    {
+        var relative = Path.GetRelativePath(workingDirectory, file);
+        return relative.StartsWith("..", StringComparison.Ordinal) ? file : relative.Replace('\\', '/');
+    }
+}
diff --git a/src/Progmasoft.Tazel/Cli/CommandLine.cs b/src/Progmasoft.Tazel/Cli/CommandLine.cs
index d97366d..02ee47f 100644
--- a/src/Progmasoft.Tazel/Cli/CommandLine.cs
+++ b/src/Progmasoft.Tazel/Cli/CommandLine.cs
@@ -172,6 +172,7 @@ internal static class CommandLine
         new("local", Kind.Flag, null, "options", "custom-cmds", "envs"),
         new("create", Kind.Flag, null, "options"),
         new("output-dir", Kind.Value, null, "tool"),
+        new("remote", Kind.Flag, null, "cache"),
         new("message-format", Kind.Value, ["rich-stdio", "script-friendly-stdio", "jsonl", "xml"]),
         new("help", Kind.Flag, null),
         new("platform", Kind.Value, Platforms.Names, Building),
@@ -469,9 +470,21 @@ internal static class CommandLine
 
     private static Command MakeCache(Scanned scanned, OutputOptions output)
     {
+        if (scanned.Positional is ["validate" or "repair"])
+        {
+            return Last(scanned.Seen, "algorithm") is not null
+                ? throw new CommandLineException("--algorithm is an option of tazel cache keygen")
+                : new CacheCheckCommand(output, scanned.Positional[0] == "repair", scanned.Has("remote"));
+        }
+
         if (scanned.Positional is not ["keygen"])
         {
-            throw new CommandLineException("tazel cache takes keygen: tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa]");
+            throw new CommandLineException("tazel cache takes keygen [--algorithm ed25519|rsa-4096|ml-dsa], validate [--remote] or repair [--remote]");
+        }
+
+        if (scanned.Has("remote"))
+        {
+            throw new CommandLineException("--remote is an option of tazel cache validate and repair");
         }
 
         var algorithm = Last(scanned.Seen, "algorithm") switch
diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs
index a238ede..967e8f2 100644
--- a/src/Progmasoft.Tazel/Cli/Commands.cs
+++ b/src/Progmasoft.Tazel/Cli/Commands.cs
@@ -43,6 +43,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector
             PortalModulesCommand portal => PortalModulesAsync(portal, cancel),
             PackageCommand => PackageAsync(),
             CustomCommandLine custom => CustomAsync(custom, cancel),
+            CacheCheckCommand check => CacheCheckAsync(check, cancel),
             ToolLaunchCommand tool => Task.FromResult(LaunchTool(tool)),
             IgnoreCommand ignore => Task.FromResult(new IgnoreCommands(reporter, workingDirectory).Run(ignore)),
             ToolWrapperCommand wrapper => Task.FromResult(CreateWrapper(wrapper)),
diff --git a/src/Progmasoft.Tazel/Cli/Help.cs b/src/Progmasoft.Tazel/Cli/Help.cs
index 4051410..ac34a50 100644
--- a/src/Progmasoft.Tazel/Cli/Help.cs
+++ b/src/Progmasoft.Tazel/Cli/Help.cs
@@ -205,8 +205,20 @@ internal static class Help
 
             Prints what Tazel can do, or what one command does; --long says more.
             """),
-        ["cache"] = new("tazel cache keygen: a key pair that signs and checks the results of a remote cache.", """
+        ["cache"] = new("tazel cache keygen|validate|repair: keys of a remote cache, and checks of the caches.", """
             tazel cache keygen [--algorithm ed25519|rsa-4096|ml-dsa]
+            tazel cache validate [--remote]
+            tazel cache repair [--remote]
+
+            validate reads the records of .tazel and changes nothing: action records are valid, stale (an input changed;
+            the next build runs the action) or broken (unreadable, or the output gone or changed while its inputs are as
+            recorded); test results are broken without their log; compiled project files when their metadata does not
+            read. With --remote it reads MODULE.csx, asks the remote cache for a key no action has, and checks that the
+            SigningKey signs what the PublicKey verifies. repair removes what is broken and what writes left half done,
+            never a stale record or an output; with --remote, and a cache that takes writes, it stores again the results
+            of this machine's valid records, for its platform in debug, that the cache lacks or holds unsigned. Run
+            repair when no build runs.
+
 
             Prints a PublicKey and a SigningKey for Remote.From in MODULE.csx, each written as its algorithm and the key
             in base64. The machines that write to the cache sign with the SigningKey; every machine that reads checks with
diff --git a/src/Progmasoft.Tazel/Cli/RemoteCacheCommands.cs b/src/Progmasoft.Tazel/Cli/RemoteCacheCommands.cs
new file mode 100644
index 0000000..0279047
--- /dev/null
+++ b/src/Progmasoft.Tazel/Cli/RemoteCacheCommands.cs
@@ -0,0 +1,150 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net.Http;
+using System.Security.Cryptography;
+using System.Threading;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.Driver;
+using Progmasoft.Tazel.Dsl.Build.Prelude;
+using Progmasoft.Tazel.Dsl.Common;
+using Progmasoft.Tazel.Output;
+using Progmasoft.Tazel.Project;
+
+namespace Progmasoft.Tazel.Cli;
+
+/// <summary>The remote part of <c>tazel cache validate --remote</c> and <c>tazel cache repair --remote</c>.</summary>
+internal sealed partial class Commands
+{
+    private async Task<int> CacheCheckAsync(CacheCheckCommand command, CancellationToken cancel)
+    {
+        var broken = new CacheCommands(reporter, workingDirectory).RunLocal(command.Repair);
+        var remoteFailed = command.Remote && !await RemoteCheckAsync(command.Repair, cancel).ConfigureAwait(false);
+        if (broken == 0 && !remoteFailed)
+        {
+            reporter.Success(command.Repair ? "the caches hold nothing broken now" : "nothing in the caches is broken");
+        }
+
+        return broken > 0 || remoteFailed ? 1 : 0;
+    }
+
+    /// <summary>
+    /// Whether the remote cache of MODULE.csx answers and its keys hold: a request for a key no action has, which a
+    /// cache that is reached and lets us in answers with 404; and the SigningKey, when there is one with a PublicKey,
+    /// signing what the PublicKey verifies. With <paramref name="repair"/>, results of this machine's valid records
+    /// that the cache lacks, or holds without a signature the PublicKey takes, are stored again.
+    /// </summary>
+    private async Task<bool> RemoteCheckAsync(bool repair, CancellationToken cancel)
+    {
+        var main = await Workspace.LoadMainModuleAsync(workingDirectory, TazelVersion).ConfigureAwait(false);
+        if (main.Globals.cache?.Settings.Remote is not { } remote)
+        {
+            reporter.Plain("remote cache: MODULE.csx sets none");
+            return true;
+        }
+
+        using var cache = new Cache.RemoteCache(remote.Url, remote.Settings.Token);
+        try
+        {
+            var probe = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(32));
+            await cache.GetActionAsync(probe, cancel).ConfigureAwait(false);
+            reporter.Plain($"remote cache: {remote.Url.Host} answers and lets this machine in");
+        }
+        catch (Exception error) when (error is Cache.RemoteCacheException or HttpRequestException or TaskCanceledException && !cancel.IsCancellationRequested)
+        {
+            reporter.Error(ErrorCodes.CacheBroken, $"the remote cache at {remote.Url.Host} cannot be used: {error.Message}",
+                "check its address, and the Token of Remote.From in MODULE.csx");
+            return false;
+        }
+
+        if (!KeysMatch(remote.Settings))
+        {
+            return false;
+        }
+
+        return !repair || await StoreMissingAsync(cache, remote.Settings, cancel).ConfigureAwait(false);
+    }
+
+    private bool KeysMatch(Dsl.Module.Prelude.RemoteSettings settings)
+    {
+        var digests = new Digests();
+        using var unused = new Cache.RemoteCache(new Uri("http://127.0.0.1/"), null);
+        // RemoteActionsOf reads both keys and says which one it cannot.
+        RemoteActionsOf(unused, settings, digests);
+        if (settings.PublicKey is not { Length: > 0 } publicText || settings.SigningKey is not { Length: > 0 } signingText)
+        {
+            reporter.Plain(settings.PublicKey is { Length: > 0 }
+                ? "remote cache keys: a PublicKey; results are taken only with its signature"
+                : "remote cache keys: none; results are taken unsigned");
+            return true;
+        }
+
+        var message = RandomNumberGenerator.GetBytes(64);
+        var publicKey = Cache.CacheKey.ParsePublic(publicText, "the PublicKey of the remote cache");
+        var signingKey = Cache.CacheKey.ParseSigning(signingText, "the SigningKey of the remote cache");
+        if (publicKey.Algorithm == signingKey.Algorithm && publicKey.Verify(message, signingKey.Sign(message)))
+        {
+            reporter.Plain($"remote cache keys: the SigningKey signs what the PublicKey verifies ({Cache.CacheKey.NameOf(publicKey.Algorithm)})");
+            return true;
+        }
+
+        reporter.Error(ErrorCodes.CacheBroken, "the SigningKey of the remote cache does not sign what its PublicKey verifies; " +
+            "what this machine writes is not taken by those who trust that key", "make a pair with tazel cache keygen and use both halves");
+        return false;
+    }
+
+    // The valid local results of the module's targets for this machine, stored again where the cache lacks them.
+    private async Task<bool> StoreMissingAsync(Cache.RemoteCache cache, Dsl.Module.Prelude.RemoteSettings settings, CancellationToken cancel)
+    {
+        if (!settings.Write)
+        {
+            reporter.Plain("remote cache: Remote.From does not write, so nothing is stored again");
+            return true;
+        }
+
+        var (options, _) = Dsl.Options.TazelOptionsFile.Effective(workingDirectory);
+        var platform = options.Platform ?? Host.Platform;
+        var workspace = await Workspace.LoadAsync(workingDirectory, new BuildContext(BuildMode.Debug, platform), TazelVersion,
+            reporter.Status, ["//..."]).ConfigureAwait(false);
+        var buildOptions = new BuildOptions { Platform = platform, Mode = BuildMode.Debug };
+        var planner = new Planner(workspace, buildOptions, new ToolchainChooser(workspace, platform));
+        var selector = new Selector(workspace, platform);
+        var actions = new HashSet<BuildAction>();
+        foreach (var target in Select(selector, ["//..."], BuildKind.Build, platform))
+        {
+            Collect(planner.Plan(target).Main, actions);
+        }
+
+        var digests = new Digests();
+        var local = new ActionCache(digests);
+        var remote = RemoteActionsOf(cache, settings, digests);
+        var stored = 0;
+        foreach (var action in actions.Where(local.IsCurrent))
+        {
+            if (!await remote.HoldsTrustedAsync(action, cancel).ConfigureAwait(false))
+            {
+                await remote.StoreAsync(action, cancel).ConfigureAwait(false);
+                stored++;
+            }
+        }
+
+        reporter.Plain($"remote cache: stored {stored} result{(stored == 1 ? "" : "s")} of {platform.Name()}, debug, again");
+        return true;
+    }
+
+    private static void Collect(BuildAction? action, HashSet<BuildAction> into)
+    {
+        if (action is null || !into.Add(action))
+        {
+            return;
+        }
+
+        foreach (var prerequisite in action.Prerequisites)
+        {
+            Collect(prerequisite, into);
+        }
+    }
+}
diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs
index 5d9a7fd..36570b8 100644
--- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs
+++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs
@@ -88,6 +88,7 @@ internal static partial class ErrorCodes
     public const string CacheKey = "E0505";
     public const string DotnetSettingRefused = "E0506";
     public const string Tool = "E0507";
+    public const string CacheBroken = "E0508";
     public const string Label = "E0600";
 
     private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt";
@@ -165,6 +166,14 @@ internal static partial class ErrorCodes
             "and in percent. Limits per object heap need both SOH and LOH; their percentages are each below 100, and so is " +
             "their sum. .NET itself may refuse a heap limit below what this process has committed, a latency mode its GC " +
             "cannot take, or thread counts it does not allow. Nothing of the command ran.", null, null, "tazel"),
+        new(CacheBroken, "a cache entry that cannot be trusted, or a remote cache that cannot be used",
+            "tazel cache validate reads the records of .tazel. A record is broken when it cannot be read, or when the output " +
+            "it is kept beside is gone or changed while every input is as it recorded: a file touched behind Tazel's back, " +
+            "or a disk that lost it. A test result is broken without its log, a compiled project file when its metadata " +
+            "does not read. tazel cache repair removes what is broken, and the next build redoes it; stale records, whose " +
+            "inputs changed, are left, as builds handle them. With --remote, the remote cache must answer, let this machine " +
+            "in, and have a SigningKey that signs what its PublicKey verifies.",
+            null, null, "tazel"),
         new(Tool, "a tool Tazel cannot find, start or give its arguments",
             "tazel tool launch <name> runs TAZEL_TOOL_EXECUTABLE when it is set, and nothing else then: it must be a " +
             "program this user may run, its path absolute or from the working directory. Otherwise it runs the first " +
diff --git a/tests/Progmasoft.Tazel.Tests/CacheCheckTests.cs b/tests/Progmasoft.Tazel.Tests/CacheCheckTests.cs
new file mode 100644
index 0000000..5255272
--- /dev/null
+++ b/tests/Progmasoft.Tazel.Tests/CacheCheckTests.cs
@@ -0,0 +1,212 @@
+// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
+// SPDX-License-Identifier: MIT
+
+using System;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading.Tasks;
+using Progmasoft.Tazel.Cache;
+using Progmasoft.Tazel.Cli;
+using Progmasoft.Tazel.Driver;
+using Xunit;
+
+namespace Progmasoft.Tazel.Tests;
+
+public sealed class CacheCheckTests
+{
+    private const string Build = """
+        using Progmasoft.Tazel.Dsl.Build.Prelude;
+        CC.Executable("app", new() { Sources = ["main.c", "two.c"] });
+        CC.Test("t", new() { Sources = ["t.c"] });
+        """;
+
+    private static TemporaryModule Sample(string module = TemporaryModule.ModuleFile) => new TemporaryModule()
+        .Write("MODULE.csx", module)
+        .Write("BUILD.csx", Build)
+        .Write("main.c", "int two(void);\nint main(void) { return two() - 2; }\n")
+        .Write("two.c", "int two(void) { return 2; }\n")
+        .Write("t.c", "int main(void) { return 0; }\n");
+
+    private static void SkipWithoutCompiler() =>
+        Assert.SkipWhen(Host.Which("cc") is null && Host.Which("gcc") is null && Host.Which("clang") is null, "no C compiler");
+
+    private static async Task<(int Status, string Output)> Tazel(TemporaryModule module, params string[] arguments) =>
+        await module.TazelAsync(".", ["--color", "never", .. arguments]);
+
+    private static async Task Built(TemporaryModule module)
+    {
+        Assert.Equal(0, (await Tazel(module, "build", "//:app")).Status);
+        Assert.Equal(0, (await Tazel(module, "test", "//:t")).Status);
+    }
+
+    private static string Object(TemporaryModule module, string name) =>
+        Directory.EnumerateFiles(Path.Combine(module.Root, ".tazel"), name, SearchOption.AllDirectories).Single();
+
+    [Fact]
+    public void TheCommandLineTakesValidateAndRepairWithRemote()
+    {
+        Assert.Equal(new CacheCheckCommand(new OutputOptions(Output.When.Auto, Output.When.Auto, false, Output.MessageFormat.RichStdio), false, true),
+            CommandLine.Parse(["cache", "validate", "--remote"]) with { DotnetSettings = [] });
+        Assert.True(Assert.IsType<CacheCheckCommand>(CommandLine.Parse(["cache", "repair"])).Repair);
+        Assert.Throws<CommandLineException>(() => CommandLine.Parse(["cache", "keygen", "--remote"]));
+        Assert.Throws<CommandLineException>(() => CommandLine.Parse(["cache", "validate", "--algorithm", "ed25519"]));
+        Assert.Throws<CommandLineException>(() => CommandLine.Parse(["build", "--remote"]));
+        Assert.Throws<CommandLineException>(() => CommandLine.Parse(["cache", "check"]));
+    }
+
+    [Fact]
+    public async Task AFreshBuildHasNothingBrokenAndAChangedSourceOnlyMakesRecordsStale()
+    {
+        SkipWithoutCompiler();
+        using var module = Sample();
+        await Built(module);
+        var (status, output) = await Tazel(module, "cache", "validate");
+        Assert.True(status == 0, output);
+        Assert.Contains("0 stale, 0 broken", output, StringComparison.Ordinal);
+        Assert.Contains("test results: 1 valid", output, StringComparison.Ordinal);
+        Assert.Contains("nothing in the caches is broken", output, StringComparison.Ordinal);
+        module.Write("main.c", "int two(void);\nint main(void) { return two() - 2 + 0; }\n");
+        (status, output) = await Tazel(module, "cache", "validate");
+        Assert.True(status == 0, output);
+        // Only the compilation of main.c is stale: the link reads the object, which has not been made again.
+        Assert.Contains("1 stale, 0 broken", output, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task AnOutputChangedBehindTazelIsBrokenAndRepairLeavesItToTheNextBuild()
+    {
+        SkipWithoutCompiler();
+        using var module = Sample();
+        await Built(module);
+        var two = Object(module, "two.c.o");
+        File.AppendAllText(two, "junk");
+        module.Write("main.c", "int two(void);\nint main(void) { return two() - 2 + 0; }\n");
+        var (status, output) = await Tazel(module, "cache", "validate");
+        Assert.Equal(1, status);
+        Assert.Contains("error[E0508]", output, StringComparison.Ordinal);
+        Assert.Contains("two.c.o changed while its inputs are as recorded", output, StringComparison.Ordinal);
+        Assert.True(File.Exists(two + ".action"));
+        var stale = Object(module, "main.c.o.action");
+        var staleText = File.ReadAllText(stale);
+        (status, output) = await Tazel(module, "cache", "repair");
+        Assert.True(status == 0, output);
+        Assert.False(File.Exists(two + ".action"));
+        Assert.Equal(staleText, File.ReadAllText(stale));
+        Assert.Equal(0, (await Tazel(module, "cache", "validate")).Status);
+        (_, output) = await Tazel(module, "build", "//:app");
+        Assert.Contains("Compiling //:app two.c", output, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public void ReadsEveryKindOfEntry()
+    {
+        using var module = Sample();
+        var state = Path.Combine(module.Root, ".tazel");
+        var digest = new string('a', 64);
+        module.Write(".tazel/out/x/good.o", "object")
+            .Write(".tazel/out/x/good.o.action", $"key {digest}\nfile {Digests.Sha256("object"u8.ToArray())} {Path.Combine(state, "out", "x", "good.o")}\n")
+            .Write(".tazel/out/x/bad.o.action", "not a record\n")
+            .Write(".tazel/out/x/lost.o.action", $"key {digest}\nfile {digest} {Path.Combine(state, "out", "x", "lost.o")}\n")
+            .Write(".tazel/out/x/other.o.action", $"key {digest}\nfile {digest} {Path.Combine(state, "out", "x", "elsewhere.o")}\n")
+            .Write(".tazel/out/x/half.o.1234.partial", "")
+            .Write(".tazel/testlogs/.passed/_kept", digest)
+            .Write(".tazel/testlogs/kept/test.log", "ok")
+            .Write(".tazel/testlogs/.passed/_alone", digest)
+            .Write(".tazel/testlogs/.passed/pkg_t", "short")
+            .Write($".tazel/scripts/{digest}.dll", "")
+            .Write($".tazel/scripts/{new string('b', 64)}.dll", "not an assembly")
+            .Write(".tazel/scripts/name.dll", "");
+        File.Copy(typeof(CacheChecks).Assembly.Location, Path.Combine(state, "scripts", new string('c', 64) + ".dll"));
+        var checks = new CacheChecks(module.Root);
+        var actions = checks.Actions();
+        Assert.Equal(1, actions.Valid);
+        Assert.Equal(["bad.o.action", "lost.o.action", "other.o.action"], actions.Broken.Select(entry => Path.GetFileName(entry.File)));
+        Assert.Contains("does not start with the key", actions.Broken[0].Reason, StringComparison.Ordinal);
+        Assert.Contains("is gone while its inputs are as recorded", actions.Broken[1].Reason, StringComparison.Ordinal);
+        Assert.Contains("does not name the output", actions.Broken[2].Reason, StringComparison.Ordinal);
+        Assert.Single(actions.Leftovers);
+        var tests = checks.Tests();
+        Assert.Equal(1, tests.Valid);
+        Assert.Equal(["_alone", "pkg_t"], tests.Broken.Select(entry => Path.GetFileName(entry.File)).Order(StringComparer.Ordinal));
+        var scripts = checks.Scripts();
+        Assert.Equal(2, scripts.Valid);
+        Assert.Equal(2, scripts.Broken.Count);
+    }
+
+    [Fact]
+    public async Task RemoteSaysWhenMODULEcsxSetsNone()
+    {
+        using var module = Sample();
+        var (status, output) = await Tazel(module, "cache", "validate", "--remote");
+        Assert.True(status == 0, output);
+        Assert.Contains("remote cache: MODULE.csx sets none", output, StringComparison.Ordinal);
+    }
+
+    private static string WithRemote(string url, bool write, string? publicKey = null, string? signingKey = null) => $$"""
+        using Progmasoft.Tazel.Dsl.Module.Prelude;
+        module = Module.Define(new() { Group = "com.example", Name = "sample", Version = "0.1.0" });
+        cache = Cache.Define(new() {
+            Remote = Remote.From("{{url}}", new() { Read = true, Write = {{(write ? "true" : "false")}}, Token = "secret",
+                PublicKey = {{(publicKey is null ? "null" : $"\"{publicKey}\"")}}, SigningKey = {{(signingKey is null ? "null" : $"\"{signingKey}\"")}} })
+        });
+        """;
+
+    [Fact]
+    public async Task ARemoteThatCannotBeReachedIsAnError()
+    {
+        int port;
+        using (var socket = new TcpListener(IPAddress.Loopback, 0))
+        {
+            socket.Start();
+            port = ((IPEndPoint)socket.LocalEndpoint).Port;
+        }
+
+        using var module = Sample(WithRemote($"http://127.0.0.1:{port}", write: false));
+        var (status, output) = await Tazel(module, "cache", "validate", "--remote");
+        Assert.Equal(1, status);
+        Assert.Contains("cannot be used", output, StringComparison.Ordinal);
+    }
+
+    [Fact]
+    public async Task TheKeysMustBeAPair()
+    {
+        using var server = new FakeRemoteCache();
+        var (publicKey, signingKey) = CacheKey.Generate(SigningAlgorithm.Ed25519);
+        var (otherPublic, _) = CacheKey.Generate(SigningAlgorithm.Ed25519);
+        using (var module = Sample(WithRemote(server.Address, write: true, publicKey, signingKey)))
+        {
+            var (status, output) = await Tazel(module, "cache", "validate", "--remote");
+            Assert.True(status == 0, output);
+            Assert.Contains("answers and lets this machine in", output, StringComparison.Ordinal);
+            Assert.Contains("the SigningKey signs what the PublicKey verifies (ed25519)", output, StringComparison.Ordinal);
+            Assert.Contains("Bearer secret", server.Authorizations);
+        }
+
+        using (var module = Sample(WithRemote(server.Address, write: true, otherPublic, signingKey)))
+        {
+            var (status, output) = await Tazel(module, "cache", "validate", "--remote");
+            Assert.Equal(1, status);
+            Assert.Contains("does not sign what its PublicKey verifies", output, StringComparison.Ordinal);
+        }
+    }
+
+    [Fact]
+    public async Task RepairRemoteStoresWhatTheCacheLacks()
+    {
+        SkipWithoutCompiler();
+        using var server = new FakeRemoteCache();
+        using var module = Sample(WithRemote(server.Address, write: true));
+        Assert.Equal(0, (await Tazel(module, "build", "//:app")).Status);
+        var stored = server.Actions.Count;
+        Assert.True(stored > 0);
+        server.Actions.Clear();
+        var (status, output) = await Tazel(module, "cache", "repair", "--remote");
+        Assert.True(status == 0, output);
+        Assert.Contains($"stored {stored} results", output, StringComparison.Ordinal);
+        Assert.Equal(stored, server.Actions.Count);
+        (_, output) = await Tazel(module, "cache", "repair", "--remote");
+        Assert.Contains("stored 0 results", output, StringComparison.Ordinal);
+    }
+}