From 3679e80ebb4fceba483d49698f2d6dbbcc3c7edf Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Mon, 26 Oct 2026 21:45:57 +0100 Subject: [PATCH] ci(release): move :latest to the highest pre-release while no stable release exists Only pre-releases (v0.1.0-rc.1, rc.2) are published, and :latest followed the highest stable release only, so the Unraid template and the compose file, which pull :latest, found no image while :nightly was pushed every night. The new Chronos.Tools command release-channels reads the published releases (stable and pre-releases), ignores drafts and tags that are not SemVer, counts the tag itself as published and compares by SemVer 2.0 precedence. It prints latest (the public releases repository: highest stable release only) and image_latest (:latest: the highest stable release, or the highest pre-release while none is stable). Re-publishing an older tag never rolls either back. release.yml uses it in place of curl|grep|sort -V; the image job pushes :latest on image_latest. README, the public README, the compose file and ARCHITECTURE explain :latest, : and :nightly. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/release.yml | 39 +++-- README.md | 14 +- deploy/docker/docker-compose.yml | 2 + deploy/releases-repo/README.md | 7 +- docs/ARCHITECTURE.md | 8 +- .../Commands/ReleaseChannelsCommand.cs | 154 ++++++++++++++++++ src/Chronos.Tools/Program.cs | 3 +- .../ReleaseChannelsCommandTests.cs | 147 +++++++++++++++++ 8 files changed, 343 insertions(+), 31 deletions(-) create mode 100644 src/Chronos.Tools/Commands/ReleaseChannelsCommand.cs create mode 100644 tests/Chronos.Tools.Tests/ReleaseChannelsCommandTests.cs diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 40b3b888..eb82e3f4 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -1,9 +1,10 @@ name: Release -# A tag vMAJOR.MINOR.PATCH[-PRERELEASE] builds, tests and publishes everything (BRIEF §19.3, amended 2026-10-23, R3) +# A tag vMAJOR.MINOR.PATCH[-PRERELEASE] builds, tests and publishes everything (BRIEF §19.3, amended 2026-10-26, R1) # on the Linux runner: the Windows programs cross-compiled (installers, portable and server zips), SHA256SUMS and -# release notes on the Gitea release, then the server image in the Gitea container registry. Pre-releases get no -# :latest image and are ignored by the in-app update check. +# release notes on the Gitea release, then the server image in the Gitea container registry. The image's :latest +# follows the highest stable release, or the highest pre-release while no stable one exists; the public releases +# repository and the in-app update check follow stable releases only. on: push: tags: ["v*"] @@ -48,6 +49,7 @@ jobs: outputs: version: ${{ steps.version.outputs.version }} latest: ${{ steps.publish.outputs.latest }} + image_latest: ${{ steps.publish.outputs.image_latest }} steps: - name: Version id: version @@ -191,16 +193,18 @@ jobs: if [ "$TARGET" != "${{ github.repository }}" ]; then token="$RELEASES_TOKEN"; fi GITEA_TOKEN="$token" dotnet "$TOOLS" gitea-release --server "${{ github.server_url }}" --repo "$TARGET" --tag "$TAG" \ --title "Chronos $VERSION" --notes-file out/release-notes.md --assets out/release --prerelease "$PRERELEASE" - # The public content and the image's :latest follow the highest stable version (not Gitea's "latest", which - # is the most recently created one): re-publishing an older tag or publishing a pre-release never rolls them back. - stable="$(curl -fsS -H "Authorization: token $token" "${{ github.server_url }}/api/v1/repos/$TARGET/releases?draft=false&pre-release=false&limit=50")" - newest="$(printf '%s' "$stable" | grep -o '"tag_name":"v[^"]*"' | cut -d '"' -f 4 | sed 's/^v//' | sort -V | tail -n 1 || true)" - newest="${newest:+v$newest}" - latest=false - if [ "$PRERELEASE" = "false" ] && [ "$newest" = "$TAG" ]; then latest=true; fi - echo "Newest stable release of $TARGET: ${newest:-none}; $TAG moves the public content and :latest: $latest" - echo "latest=$latest" >> "$GITHUB_OUTPUT" - echo "LATEST=$latest" >> "$GITHUB_ENV" + # What this tag moves, by SemVer precedence among all published releases (not Gitea's "latest", which is the + # most recently created one), so re-publishing an older tag never rolls a channel back. latest: the public + # content follows the highest stable release. image_latest: :latest follows it too, or the highest pre-release + # while no stable release exists, so compose and Unraid users find an image from the first pre-release on. + releases="$RUNNER_TEMP/releases.json" + curl -fsS -H "Authorization: token $token" -o "$releases" "${{ github.server_url }}/api/v1/repos/$TARGET/releases?draft=false&limit=50" + channels="$(dotnet "$TOOLS" release-channels --tag "$TAG" --releases "$releases")" + latest="$(printf '%s\n' "$channels" | sed -n 's/^latest=//p')" + image_latest="$(printf '%s\n' "$channels" | sed -n 's/^image_latest=//p')" + echo "Releases of $TARGET: $TAG moves the public content: $latest; :latest: $image_latest" + { echo "latest=$latest"; echo "image_latest=$image_latest"; } >> "$GITHUB_OUTPUT" + { echo "LATEST=$latest"; echo "IMAGE_LATEST=$image_latest"; } >> "$GITHUB_ENV" # Only with a separate releases repository (RELEASES_REPO and RELEASES_TOKEN, BRIEF §19.4): its README, EULA, # security policy, issue forms, Unraid template, compose file, i18n/ and SHA256SUMS follow the newest stable @@ -264,7 +268,7 @@ jobs: timeout-minutes: 60 env: VERSION: ${{ needs.release.outputs.version }} - LATEST: ${{ needs.release.outputs.latest }} + IMAGE_LATEST: ${{ needs.release.outputs.image_latest }} steps: - name: Checkout env: @@ -295,12 +299,13 @@ jobs: run: | docker build -f deploy/docker/Dockerfile --build-arg CHRONOS_VERSION="$VERSION" -t "$IMAGE:$VERSION" . docker push "$IMAGE:$VERSION" - # Compose and Unraid users follow :latest: it moves only to the newest stable release. - if [ "$LATEST" = "true" ]; then + # Compose and Unraid users follow :latest: the highest stable release, or the highest pre-release while no + # stable release exists (release-channels). :nightly (docker.yml) is the nightly build of main, never a release. + if [ "$IMAGE_LATEST" = "true" ]; then docker tag "$IMAGE:$VERSION" "$IMAGE:latest" docker push "$IMAGE:latest" fi - echo "Image: $IMAGE:$VERSION$([ "$LATEST" = "true" ] && echo " and :latest")" + echo "Image: $IMAGE:$VERSION$([ "$IMAGE_LATEST" = "true" ] && echo " and :latest")" - name: Clean up if: always() diff --git a/README.md b/README.md index cbb64b83..24ae595b 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ installed copy of either. 1. Make sure `main` is green, the Windows-only tests passed (on the Windows runner or a Windows PC) and `docs/CHANGELOG.md` / `docs/STATUS.md` are up to date. 2. Tag and push: `git tag v0.2.0 && git push origin v0.2.0` (pre-releases: `v0.2.0-rc.1`; they are published as - Gitea pre-releases, get no `:latest` image and are ignored by the in-app update check). + Gitea pre-releases, move `:latest` only while no stable release exists and are ignored by the in-app update check). 3. `release.yml` then, in its job *Build, test and publish* (SDK container): - validates the tag, builds with `ChronosVersion` from the tag and `ChronosReleasesUrl` (the repository the release goes to), runs the package guard, the i18n check and the Core, Data, Server and Tools tests; @@ -155,9 +155,10 @@ installed copy of either. 4. Its job *Server image* (the runner's own image with the docker CLI and the host's daemon) then builds the image for linux/amd64 only (arm64 would need QEMU on the host) and pushes `gitea.encke-hake.ts.net/balbosoft/chronos-server:`, plus `:latest` when the tag is the highest stable version among - the published releases (not Gitea's `releases/latest`, which is the most recently created one): a pre-release, or an - older tag published again, only gets its release and its `:` image. Without `REGISTRY_TOKEN` this job fails with instructions while the release is already published: add - the secret and re-run the job. + the published releases, or the highest pre-release while none is stable (`Chronos.Tools release-channels`, by SemVer + precedence; not Gitea's `releases/latest`, which is the most recently created one): an older tag published again, or + a pre-release once a stable release exists, only gets its release and its `:` image. Without `REGISTRY_TOKEN` + this job fails with instructions while the release is already published: add the secret and re-run the job. 5. To publish an existing tag again (for example after adding a secret), run *Release* manually (Actions › Release › *Run workflow*) with the tag. @@ -210,8 +211,9 @@ security problems go privately to the maintainers (`SECURITY.md`), never into a ### Server image, Compose and Unraid -- Image: `gitea.encke-hake.ts.net/balbosoft/chronos-server`, tags `:latest` (newest stable release), `:` and - `:nightly` (`main`, not for production); linux/amd64 only. +- Image: `gitea.encke-hake.ts.net/balbosoft/chronos-server`, tags `:latest` (newest stable release; before the first + one, the newest pre-release), `:` and `:nightly` (`main` rebuilt every night, not for production); + linux/amd64 only. - Compose: `deploy/docker/docker-compose.yml` and `.env.example`, downloaded from `https://gitea.encke-hake.ts.net/BalboSoft/Chronos/raw/branch/main/deploy/docker/docker-compose.yml` and `…/deploy/docker/.env.example`. diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 0f7fe1af..3ab41a3f 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -3,6 +3,8 @@ name: chronos services: chronos: + # :latest is the newest stable release (before the first one, the newest pre-release); : pins a release; + # :nightly is the development version rebuilt every night, not for production. # While the organisation on Gitea is private, sign in before pulling: docker login gitea.encke-hake.ts.net image: gitea.encke-hake.ts.net/balbosoft/chronos-server:latest restart: unless-stopped diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md index 80db0eb1..20db5bcf 100644 --- a/deploy/releases-repo/README.md +++ b/deploy/releases-repo/README.md @@ -74,9 +74,10 @@ Open `http://:8080/admin`, sign in as `admin` with the password from `.env clients connect to `https://:8443`; the first connection shows the server's certificate fingerprint, which the admin panel shows under Settings so you can compare them. -- Image: `gitea.encke-hake.ts.net/balbosoft/chronos-server:latest` (also `:`; `:nightly` follows development - and is not for production use; pre-releases have no `:latest`). Architecture: `linux/amd64`. If the registry asks you - to sign in, run `docker login gitea.encke-hake.ts.net` with your Gitea account first. +- Image: `gitea.encke-hake.ts.net/balbosoft/chronos-server:latest`, the newest stable release (before the first one, + the newest pre-release); also `:`, and `:nightly`, the development version rebuilt every night, not for + production use. Architecture: `linux/amd64`. If the registry asks you to sign in, run + `docker login gitea.encke-hake.ts.net` with your Gitea account first. - Volumes: `/archive` (originals, sidecars, proxies, renders — the archive stays readable without Chronos) and `/data` (settings, TLS certificate, uploads in progress, logs). - Upgrade: `docker compose pull && docker compose up -d`. Jobs in progress resume from their last checkpoint. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 372f712d..927d9e80 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -16,7 +16,7 @@ Companion to `docs/BRIEF.md` (scope, behaviour) and `docs/ui/DESIGN.md` (looks). | `src/Chronos.App` | WPF exe `Chronos.exe` | Desktop client | | `src/Chronos.Uploader` | WPF exe | Uploader (tray, watch folders, resumable queue) | | `src/Chronos.Setup` | WPF exe | In-house installer/uninstaller (TPK1 payload) | -| `src/Chronos.Tools` | net10.0 exe | CLI: `make-icon`, `i18n` (check, export, missing, import), `xaml-lint`, `package-guard`, `changelog`, `pack-installer`, `selftest`, `diagnose`, `fixtures`, `screenshots` (diff, accept), `zip`, `gitea-release`, `postgres-ci`, `pe-check` | +| `src/Chronos.Tools` | net10.0 exe | CLI: `make-icon`, `i18n` (check, export, missing, import), `xaml-lint`, `package-guard`, `changelog`, `pack-installer`, `selftest`, `diagnose`, `fixtures`, `screenshots` (diff, accept), `zip`, `gitea-release`, `release-channels`, `postgres-ci`, `pe-check` | | `tests/Chronos.Testing` | net10.0 | In-house test framework (`[Test]`, `[Theory]`+`[Case]`, `[Category]`, `[RequiresEnvironment]`, `[WindowsOnly]`, `[Serial]`, `Assert`, `TestContext`, JUnit) | | `tests/Chronos.*.Tests` | exe | One test program per area; `dotnet run --project tests/X -- --junit out.xml` | @@ -240,8 +240,8 @@ run as server jobs whose progress comes from the events. building it) and the 100,000-frame rebuild from sidecars (400 sequences of 250 real photos, every column compared, < 120 s), each on SQLite and PostgreSQL. `.gitea/workflows/perf.yml` runs them weekly against PostgreSQL 17. - `Chronos.Tools.Tests` covers the tools whose output CI relies on (fixtures warning lines and exit codes, the - screenshot diff, the PostgreSQL preparation, `pe-check`, `zip`, the Gitea release upload) and the test runner's - outcomes. + screenshot diff, the PostgreSQL preparation, `pe-check`, `zip`, the Gitea release upload, `release-channels`) and the + test runner's outcomes. - Visual regression: the CI job `windows` (or a run on a Windows PC) compares the `--capture` screenshots with `tests/visual/baselines` (`Chronos.Tools screenshots diff`; its README says how baselines are added). Once any baseline is committed, a screen without one fails too; before that the step warns that it compared nothing. The @@ -280,7 +280,7 @@ dotnet format whitespace Chronos.slnx --verify-no-changes | Workflow | Trigger | Does | |---|---|---| | `ci.yml` | push to `main`, pull requests, manual | Linux build and tests, guards, i18n, XAML lint, format, fixtures (warnings when missing), the Windows programs cross-compiled for win-x64, packed and checked (`pe-check`), PostgreSQL 16/17 (every authentication method, TLS), Docker smoke test, YAML check of the workflows, issue forms and compose file; with a Windows runner (`WINDOWS_RUNNER`): Windows tests, screenshots and their pixel diff, installer test (install, run, upgrade, uninstall) | -| `release.yml` | tag `v*` (or manual re-publish) | Tests, self-contained win-x64 publish cross-compiled on Linux, `pe-check`, optional signing (osslsigncode), installers, portable and server zips, SHA256SUMS, release notes, Gitea release (`gitea-release`), then the linux/amd64 image in the Gitea container registry (`:latest` only for the newest stable release); a separate releases repository is updated only when `RELEASES_REPO` names one | +| `release.yml` | tag `v*` (or manual re-publish) | Tests, self-contained win-x64 publish cross-compiled on Linux, `pe-check`, optional signing (osslsigncode), installers, portable and server zips, SHA256SUMS, release notes, Gitea release (`gitea-release`), then the linux/amd64 image in the Gitea container registry (`:latest` for the highest stable release, or the highest pre-release while none is stable: `release-channels`); a separate releases repository is updated only when `RELEASES_REPO` names one, for the highest stable release | | `docker.yml` | nightly, manual | `gitea.encke-hake.ts.net/balbosoft/chronos-server:nightly` from `main` | | `perf.yml` | weekly, manual | Performance gates (SQLite, PostgreSQL 17) with timings at the end of the log | diff --git a/src/Chronos.Tools/Commands/ReleaseChannelsCommand.cs b/src/Chronos.Tools/Commands/ReleaseChannelsCommand.cs new file mode 100644 index 00000000..c73eacef --- /dev/null +++ b/src/Chronos.Tools/Commands/ReleaseChannelsCommand.cs @@ -0,0 +1,154 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; + +namespace Chronos.Tools.Commands; + +/// What a published tag moves (). +/// The public content of the releases repository: the highest stable release only. +/// The image's :latest: the highest stable release, or the highest pre-release while no stable one exists. +internal sealed record ReleaseChannels(bool Latest, bool ImageLatest); + +/// +/// Decides which channels a release moves (BRIEF §19.3, amended 2026-10-26, R1). Gitea's "latest" +/// release is the most recently created one, so the choice is made by SemVer 2.0 precedence among the published +/// releases instead: re-publishing an older tag never rolls a channel back. Prints latest=… and +/// image_latest=…, ready for $GITHUB_OUTPUT. +/// +internal sealed class ReleaseChannelsCommand : ICommand +{ + public string Name => "release-channels"; + public string Summary => "Channels a tag moves: --tag vX.Y.Z[-pre] --releases ; prints latest= and image_latest="; + + public async Task RunAsync(string[] args) + { + var a = new Args(args); + if (a.Get("tag") is not { Length: > 0 } tag || a.Get("releases") is not { Length: > 0 } file) + throw new ToolException("Usage: release-channels --tag vMAJOR.MINOR.PATCH[-PRERELEASE] --releases "); + // The tag is checked before the file is read: a mistyped tag is the likelier error. + if (TagVersion.Parse(tag) is null) throw new ToolException(InvalidTag(tag)); + if (!File.Exists(file)) throw new ToolException($"Releases file not found: {file}"); + Console.Out.Write(Render(Decide(tag, await File.ReadAllTextAsync(file)))); + return 0; + } + + /// + /// The channels moves, given Gitea's releases list (GET /repos/{owner}/{repo}/releases). + /// Drafts and tags that are not SemVer are ignored; the tag itself always counts as published. A release is a + /// pre-release when its tag has a pre-release part or Gitea flags it so. + /// + internal static ReleaseChannels Decide(string tag, string releasesJson) + { + var current = TagVersion.Parse(tag) ?? throw new ToolException(InvalidTag(tag)); + var listed = Published(releasesJson); + var currentIsPrerelease = current.IsPrerelease || listed.Any(r => r.Version.Tag == tag && r.Prerelease); + var all = listed.Where(r => r.Version.Tag != tag).Append((Version: current, Prerelease: currentIsPrerelease)).ToList(); + + // Equal precedence (v1.0.0 and v1.0.0+build.2) counts as highest: publishing the same version again moves nothing back. + bool Highest(IEnumerable versions) => versions.All(v => v.CompareTo(current) <= 0); + var stable = all.Where(r => !r.Prerelease).Select(r => r.Version).ToList(); + var latest = !currentIsPrerelease && Highest(stable); + var imageLatest = stable.Count > 0 ? latest : Highest(all.Select(r => r.Version)); + return new ReleaseChannels(latest, imageLatest); + } + + /// The two output lines, with \n on every platform. + internal static string Render(ReleaseChannels channels) => + $"latest={(channels.Latest ? "true" : "false")}\nimage_latest={(channels.ImageLatest ? "true" : "false")}\n"; + + private static List<(TagVersion Version, bool Prerelease)> Published(string json) + { + JsonNode? root; + try + { + root = JsonNode.Parse(json); + } + catch (JsonException ex) + { + throw new ToolException($"The releases file is not JSON: {ex.Message}"); + } + if (root is not JsonArray releases) throw new ToolException("The releases file is not a JSON array of releases."); + + var published = new List<(TagVersion, bool)>(); + foreach (var release in releases.OfType()) + { + if (Flag(release, "draft")) continue; + if (release["tag_name"] is not JsonValue name || !name.TryGetValue(out var tagName)) continue; + if (TagVersion.Parse(tagName) is { } version) published.Add((version, version.IsPrerelease || Flag(release, "prerelease"))); + } + return published; + } + + private static bool Flag(JsonObject release, string name) => + release[name] is JsonValue value && value.TryGetValue(out var flag) && flag; + + private static string InvalidTag(string tag) => + $"--tag '{tag}' is not vMAJOR.MINOR.PATCH[-PRERELEASE][+BUILD] (for example v1.2.0 or v1.2.0-rc.1)."; +} + +/// A tag vMAJOR.MINOR.PATCH[-PRERELEASE][+BUILD] ordered by SemVer 2.0 precedence (build metadata ignored). +internal sealed partial class TagVersion : IComparable +{ + private readonly string[] _core; + private readonly string[] _prerelease; + + private TagVersion(string tag, string[] core, string[] prerelease) + { + Tag = tag; + _core = core; + _prerelease = prerelease; + } + + public string Tag { get; } + + public bool IsPrerelease => _prerelease.Length > 0; + + /// The version of , or null when it is not SemVer 2.0 with a leading v. + public static TagVersion? Parse(string? tag) + { + if (tag is null) return null; + var m = Pattern().Match(tag); + if (!m.Success) return null; + string[] core = [m.Groups["major"].Value, m.Groups["minor"].Value, m.Groups["patch"].Value]; + return new TagVersion(tag, core, m.Groups["pre"].Success ? m.Groups["pre"].Value.Split('.') : []); + } + + public int CompareTo(TagVersion? other) + { + if (other is null) return 1; + for (var i = 0; i < _core.Length; i++) + { + var c = CompareNumbers(_core[i], other._core[i]); + if (c != 0) return c; + } + // A version without a pre-release part is higher than the same version with one. + if (_prerelease.Length == 0 || other._prerelease.Length == 0) return other._prerelease.Length.CompareTo(_prerelease.Length); + for (var i = 0; i < Math.Min(_prerelease.Length, other._prerelease.Length); i++) + { + var c = CompareIdentifiers(_prerelease[i], other._prerelease[i]); + if (c != 0) return c; + } + return _prerelease.Length.CompareTo(other._prerelease.Length); + } + + public override string ToString() => Tag; + + // Numeric identifiers rank below alphanumeric ones and compare by value; alphanumeric ones compare in ASCII order. + private static int CompareIdentifiers(string a, string b) => (IsNumeric(a), IsNumeric(b)) switch + { + (true, true) => CompareNumbers(a, b), + (true, false) => -1, + (false, true) => 1, + _ => string.CompareOrdinal(a, b), + }; + + private static bool IsNumeric(string identifier) => identifier.All(char.IsAsciiDigit); + + // Without leading zeros (the pattern refuses them) the longer number is the larger: no overflow on long ones. + private static int CompareNumbers(string a, string b) => + a.Length != b.Length ? a.Length.CompareTo(b.Length) : string.CompareOrdinal(a, b); + + // semver.org's pattern with a leading "v", ASCII digits only and no trailing newline. + [GeneratedRegex(@"^v(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)\.(?0|[1-9][0-9]*)(?:-(?
(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?\z")]
+    private static partial Regex Pattern();
+}
diff --git a/src/Chronos.Tools/Program.cs b/src/Chronos.Tools/Program.cs
index 74411bf4..c6e4af99 100644
--- a/src/Chronos.Tools/Program.cs
+++ b/src/Chronos.Tools/Program.cs
@@ -15,6 +15,7 @@ var commands = new ICommand[]
     new ScreenshotsCommand(),
     new ZipCommand(),
     new GiteaReleaseCommand(),
+    new ReleaseChannelsCommand(),
     new PostgresCiCommand(),
     new PeCheckCommand(),
 };
@@ -22,7 +23,7 @@ var commands = new ICommand[]
 if (args.Length == 0 || args[0] is "-h" or "--help" or "help")
 {
     Console.WriteLine("Chronos.Tools  [options]");
-    foreach (var c in commands) Console.WriteLine($"  {c.Name,-14} {c.Summary}");
+    foreach (var c in commands) Console.WriteLine($"  {c.Name,-16} {c.Summary}");
     return args.Length == 0 ? 2 : 0;
 }
 
diff --git a/tests/Chronos.Tools.Tests/ReleaseChannelsCommandTests.cs b/tests/Chronos.Tools.Tests/ReleaseChannelsCommandTests.cs
new file mode 100644
index 00000000..dd48c7f1
--- /dev/null
+++ b/tests/Chronos.Tools.Tests/ReleaseChannelsCommandTests.cs
@@ -0,0 +1,147 @@
+using System.Text.Json.Nodes;
+using Chronos.Testing;
+using Chronos.Tools.Commands;
+
+namespace Chronos.Tools.Tests;
+
+/// 
+/// release-channels: the public content follows the highest stable release, the image's :latest the highest stable or,
+/// while none exists, the highest pre-release (BRIEF §19.3, amended 2026-10-26, R1).
+/// 
+public sealed class ReleaseChannelsCommandTests(TestContext context)
+{
+    private static readonly ReleaseChannels Both = new(Latest: true, ImageLatest: true);
+    private static readonly ReleaseChannels ImageOnly = new(Latest: false, ImageLatest: true);
+    private static readonly ReleaseChannels Neither = new(Latest: false, ImageLatest: false);
+
+    [Test]
+    public void TheHighestStableReleaseMovesBothChannels()
+    {
+        Assert.Equal(Both, Decide("v0.2.0", Releases("v0.1.0-rc.1", "v0.1.0", "v0.2.0-rc.1", "v0.2.0")));
+    }
+
+    [Test]
+    public void AnOlderStableReleasePublishedAgainMovesNothing()
+    {
+        Assert.Equal(Neither, Decide("v1.0.0", Releases("v1.0.0", "v1.1.0", "v0.9.0")));
+    }
+
+    [Test]
+    public void WithoutAStableReleaseTheHighestPreReleaseMovesOnlyTheImage()
+    {
+        var releases = Releases("v0.1.0-rc.1", "v0.1.0-rc.2");
+        Assert.Equal(ImageOnly, Decide("v0.1.0-rc.2", releases));
+        // An older pre-release published again does not take :latest back.
+        Assert.Equal(Neither, Decide("v0.1.0-rc.1", releases));
+    }
+
+    [Test]
+    public void APreReleaseAfterAStableReleaseMovesNothing()
+    {
+        Assert.Equal(Neither, Decide("v0.2.0-rc.1", Releases("v0.1.0-rc.2", "v0.1.0", "v0.2.0-rc.1")));
+    }
+
+    [Test]
+    public void NumericPreReleaseIdentifiersCompareByValue()
+    {
+        var releases = Releases("v0.1.0-rc.2", "v0.1.0-rc.10", "v0.1.0-rc.9");
+        Assert.Equal(ImageOnly, Decide("v0.1.0-rc.10", releases), "rc.10 is above rc.2 and rc.9");
+        Assert.Equal(Neither, Decide("v0.1.0-rc.2", releases), "rc.2 is below rc.10");
+    }
+
+    [Test]
+    public void BuildMetadataIsIgnoredForPrecedenceAndIsNotAPreRelease()
+    {
+        Assert.Equal(Both, Decide("v1.0.0+build.5", Releases("v1.0.0+build.4", "v0.9.0")));
+        Assert.Equal(Neither, Decide("v1.0.0+zzz", Releases("v1.0.1+aaa")));
+        Assert.Equal(ImageOnly, Decide("v1.0.0-rc.1+sha.5114f85", Releases("v1.0.0-rc.1")));
+    }
+
+    [Test]
+    public void DraftsAreIgnored()
+    {
+        var releases = new JsonArray(Release("v2.0.0", draft: true), Release("v1.0.0", draft: true), Release("v0.1.0-rc.1")).ToJsonString();
+        Assert.Equal(ImageOnly, Decide("v0.1.0-rc.1", releases));
+        Assert.Equal(Both, Decide("v1.5.0", releases));
+    }
+
+    [Test]
+    public void TagsThatAreNotSemVerAreIgnored()
+    {
+        var releases = Releases("latest", "nightly", "v9", "v9.9", "9.9.9", "V9.9.9", "v09.0.0", "v9.9.9.9", "v9.9.9-",
+            "v9.9.9-rc..1", "v9.9.9-rc.01", "v9.9.9\n");
+        Assert.Equal(Both, Decide("v0.1.0", releases));
+        // Entries without a usable tag name are skipped; one without flags counts as published.
+        Assert.Equal(Neither, Decide("v2.0.0", """[{"name":"no tag"},{"tag_name":42},{"tag_name":"v3.0.0"},7,null]"""));
+    }
+
+    [Test]
+    public void TheTagCountsAsPublishedWhenTheListIsEmpty()
+    {
+        Assert.Equal(Both, Decide("v1.0.0", "[]"));
+        Assert.Equal(ImageOnly, Decide("v1.0.0-rc.1", "[]"));
+    }
+
+    [Test]
+    public void AStableTagGiteaFlagsAsAPreReleaseCountsAsAPreRelease()
+    {
+        var releases = new JsonArray(Release("v1.0.0", prerelease: true), Release("v0.9.0")).ToJsonString();
+        Assert.Equal(Neither, Decide("v1.0.0", releases));
+        Assert.Equal(Both, Decide("v0.9.0", releases));
+    }
+
+    [Test]
+    public void VersionsFollowTheSemVerPrecedence()
+    {
+        // semver.org §11's example, then the core numbers (one longer than a long integer): each is lower than the next.
+        string[] ordered =
+        [
+            "v1.0.0-alpha", "v1.0.0-alpha.1", "v1.0.0-alpha.beta", "v1.0.0-beta", "v1.0.0-beta.2", "v1.0.0-beta.11",
+            "v1.0.0-rc.1", "v1.0.0", "v1.0.1", "v1.1.0", "v2.0.0", "v10.0.0", "v12345678901234567890.0.0",
+        ];
+        for (var i = 0; i + 1 < ordered.Length; i++)
+        {
+            var lower = Assert.NotNull(TagVersion.Parse(ordered[i]));
+            var higher = Assert.NotNull(TagVersion.Parse(ordered[i + 1]));
+            Assert.True(lower.CompareTo(higher) < 0 && higher.CompareTo(lower) > 0, $"{ordered[i]} < {ordered[i + 1]}");
+        }
+        Assert.Equal(0, Assert.NotNull(TagVersion.Parse("v1.0.0+a")).CompareTo(TagVersion.Parse("v1.0.0+b")));
+    }
+
+    [Test]
+    public void TheOutputIsTwoLinesForTheWorkflow()
+    {
+        Assert.Equal("latest=false\nimage_latest=true\n", ReleaseChannelsCommand.Render(ImageOnly));
+        Assert.Equal("latest=true\nimage_latest=true\n", ReleaseChannelsCommand.Render(Both));
+        Assert.Equal("latest=false\nimage_latest=false\n", ReleaseChannelsCommand.Render(Neither));
+    }
+
+    [Test]
+    public async Task AnInvalidTagOrReleasesFileIsRefused()
+    {
+        var file = Path.Combine(context.CreateTempDirectory("release-channels"), "releases.json");
+        await File.WriteAllTextAsync(file, "[]");
+        var command = new ReleaseChannelsCommand();
+
+        var invalid = await Assert.ThrowsAsync(() => command.RunAsync(["--tag", "1.0.0", "--releases", file]));
+        Assert.Contains("'1.0.0'", invalid.Message);
+        await Assert.ThrowsAsync(() => command.RunAsync(["--tag", "v1.0.0-rc.01", "--releases", file]));
+        await Assert.ThrowsAsync(() => command.RunAsync(["--releases", file]));
+        await Assert.ThrowsAsync(() => command.RunAsync(["--tag", "v1.0.0", "--releases", file + ".missing"]));
+        // A sign-in page or an API error instead of the list.
+        Assert.Throws(() => Decide("v1.0.0", "Sign in"));
+        Assert.Throws(() => Decide("v1.0.0", """{"message":"not found"}"""));
+    }
+
+    private static ReleaseChannels Decide(string tag, string releases) => ReleaseChannelsCommand.Decide(tag, releases);
+
+    private static string Releases(params string[] tags) => new JsonArray([.. tags.Select(t => Release(t))]).ToJsonString();
+
+    // The fields of Gitea's release list that matter, flagged as gitea-release publishes them.
+    private static JsonObject Release(string tag, bool draft = false, bool? prerelease = null) => new()
+    {
+        ["tag_name"] = tag,
+        ["draft"] = draft,
+        ["prerelease"] = prerelease ?? tag.Contains('-', StringComparison.Ordinal),
+    };
+}