Merge origin/main into hands/variants-c2a-main (main-into-c2a)

Sixteen conflicted files resolved by the spec's rule: main owns payload
ownership, bounds and the Clock seam; C2a owns persistence semantics and exact
binding. MintStoredAt is internal static (previous, now); the cache and the
store pass their cache's Clock. Package versions are main's. The cultmesh-ts
payload-parse acceptance and its test are deleted under retire-schema-alias;
peer snapshot reads take the schema's own id, else an id the definition lists
as compatible. The held firstRecordAtKey fallback is removed: main's handles
take definitions only, so nothing could reach it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-14 04:06:41 +02:00
commit 3b83cb6c08
287 changed files with 55077 additions and 1820 deletions

View file

@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"microsoft.dotnet.apicompat.tool": {
"version": "10.0.202",
"commands": [
"apicompat"
],
"rollForward": false
}
}
}

1
scripts/api-gate/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
packages/

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Restores the netstandard2.1 reference assemblies for scripts/check-changelog-semver.mjs.
Not built: PackageDownload only fetches the package into ./packages. -->
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<RestorePackagesPath>$(MSBuildThisFileDirectory)packages</RestorePackagesPath>
</PropertyGroup>
<ItemGroup>
<PackageDownload Include="NETStandard.Library.Ref" Version="[2.1.0]" />
</ItemGroup>
</Project>

View file

@ -9,13 +9,32 @@ param(
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$projectPath = Join-Path $repoRoot "src\GameCult.Mesh\GameCult.Mesh.csproj"
$webSocketProjectPath = Join-Path $repoRoot "src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj"
$quicProjectPath = Join-Path $repoRoot "src\GameCult.Mesh.Quic.Native\GameCult.Mesh.Quic.Native.csproj"
# The CultMath byte gate below needs a git checkout: ContinuousIntegrationBuild maps the repo root to /_/
# through the SDK's git source root, so in a tree that is not the top of a git checkout (git archive, a
# source zip, an empty .git) the DLL names the absolute obj path and its bytes change with the directory.
# Git itself answers, so a worktree, where .git is a file, passes.
$gitErrorAction = $ErrorActionPreference
$ErrorActionPreference = "Continue"
$gitTop = & git -C $repoRoot rev-parse --show-toplevel 2>$null
$gitExit = $LASTEXITCODE
$ErrorActionPreference = $gitErrorAction
$isGitTop = $gitExit -eq 0 -and $gitTop -and
([System.IO.Path]::GetFullPath("$gitTop").TrimEnd('\', '/') -eq [System.IO.Path]::GetFullPath($repoRoot).TrimEnd('\', '/'))
if (-not $isGitTop) {
throw "$repoRoot is not the top of a git checkout (git rev-parse --show-toplevel: '$gitTop', exit $gitExit), so CultMath.dll would carry this directory's path and fail the CultMath byte gate. Build from a git clone or worktree, not an archive or source zip."
}
$templateRoot = Join-Path $repoRoot "unity\org.gamecult.cultlib"
$publishRoot = Join-Path $repoRoot "artifacts\unity-publish"
$webSocketPublishRoot = Join-Path $repoRoot "artifacts\unity-websocket-publish"
$quicPublishRoot = Join-Path $repoRoot "artifacts\unity-quic-publish"
# Every managed publish the package is assembled from, in the order $publishedByName fills (last wins).
# This list is the one owner of publish-root identity: the clean step, the publish loop, the assembly
# lookup, the CultMath byte gate and the semver check's --api-refs all read it.
$managedPublishes = @(
@{ Project = "src\GameCult.Mesh\GameCult.Mesh.csproj"; Root = "artifacts\unity-publish"; Extra = @(); Label = "CultLib" },
@{ Project = "src\GameCult.Mesh.Quic.Native\GameCult.Mesh.Quic.Native.csproj"; Root = "artifacts\unity-quic-publish"; Extra = @(); Label = "CultLib native QUIC managed" },
@{ Project = "src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj"; Root = "artifacts\unity-websocket-publish"; Extra = @("-f", "netstandard2.1"); Label = "CultLib WebSocket" }
)
foreach ($publish in $managedPublishes) {
$publish.Root = Join-Path $repoRoot $publish.Root
}
$quicNativeRoot = Join-Path $repoRoot "artifacts\unity-quic-native"
$outputRoot = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) {
$OutputDirectory
@ -24,43 +43,23 @@ $outputRoot = if ([System.IO.Path]::IsPathRooted($OutputDirectory)) {
}
$pluginRoot = Join-Path $outputRoot "Runtime\Plugins"
if (Test-Path -LiteralPath $publishRoot) {
Remove-Item -LiteralPath $publishRoot -Recurse -Force
}
if (Test-Path -LiteralPath $quicPublishRoot) {
Remove-Item -LiteralPath $quicPublishRoot -Recurse -Force
}
if (Test-Path -LiteralPath $webSocketPublishRoot) {
Remove-Item -LiteralPath $webSocketPublishRoot -Recurse -Force
}
if (Test-Path -LiteralPath $outputRoot) {
Remove-Item -LiteralPath $outputRoot -Recurse -Force
foreach ($root in @($managedPublishes | ForEach-Object { $_.Root }) + $outputRoot) {
if (Test-Path -LiteralPath $root) {
Remove-Item -LiteralPath $root -Recurse -Force
}
}
$unityPackageVersion = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).version
# docs/semver-policy.md: refuse to build a release whose CHANGELOG.md entry
# claims a breaking change under too small a bump, or whose version skips or
# reverses the previous published tag. Runs before the (slow) build below so
# a bad version number fails fast.
& node (Join-Path $repoRoot "scripts\check-changelog-semver.mjs") `
--package "org.gamecult.cultlib" `
--changelog (Join-Path $templateRoot "CHANGELOG.md") `
--version $unityPackageVersion `
--tag-prefix "cultlib-unity" `
--cwd $repoRoot
if ($LASTEXITCODE -ne 0) {
throw "CultLib Unity package failed the semver policy check (see docs/semver-policy.md)."
}
# Release gate: cultlib's Unity package resolves CultMath through the org.gamecult.cultmath
# dependency, so a cultlib release must not run ahead of the CultMath package it names.
# (1) The declared dependency version must not exceed the CultMath package's own version.
# (2) The CultMath.dll that package tracks must define every type CultMathResolver formats.
# The names come from the resolver source (its Shape<T> entries); scripts\check-cultmath-types.cs
# looks them up in the assembly's type-definition table, which Windows PowerShell cannot load
# the assembly to do. It checks type names, not signatures.
# Release gate: cultlib compiles CultMath from source and ships beside org.gamecult.cultmath, which owns
# CultMath.dll and is resolved through the package.json dependency. Two gates bind the two:
# (1) The declared dependency version must equal the CultMath package's own version. Checked here,
# before anything is built.
# (2) Every CultMath.dll the publishes below produce must equal, byte for byte, the one that package
# tracks. Checked once they exist. The builds are deterministic for one toolchain and checkout, so a
# mismatch means the CultMath source changed since that package was released, its checkout's line
# endings differ from the CRLF that .gitattributes pins, or this SDK, compiler or host builds
# different bytes from the one that built the tracked DLL (no global.json pins the SDK).
$cultMathPackageRoot = Join-Path $repoRoot "packages\cultmath\unity\org.gamecult.cultmath"
$cultMathDeclared = (Get-Content -LiteralPath (Join-Path $templateRoot "package.json") -Raw | ConvertFrom-Json).dependencies.'org.gamecult.cultmath'
$cultMathAvailable = (Get-Content -LiteralPath (Join-Path $cultMathPackageRoot "package.json") -Raw | ConvertFrom-Json).version
@ -72,60 +71,50 @@ foreach ($declared in @(@("org.gamecult.cultlib's org.gamecult.cultmath dependen
throw "$($declared[0]) is '$($declared[1])'. The release gate compares exact release versions (major.minor.patch); prerelease and range versions are not supported."
}
}
if ([version]$cultMathDeclared -gt [version]$cultMathAvailable) {
throw "Release order: org.gamecult.cultlib depends on org.gamecult.cultmath $cultMathDeclared, but the CultMath package is at $cultMathAvailable. Release CultMath first."
}
$resolverSource = Get-Content -LiteralPath (Join-Path $repoRoot "src\GameCult.Caching.MessagePack\CultMathResolver.cs") -Raw
$resolverTypes = @([regex]::Matches($resolverSource, '\bShape<(?!T>)(\w+)>\(') | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique)
if ($resolverTypes.Count -eq 0) {
throw "Found no CultMath types in CultMathResolver.cs; the release gate cannot check the CultMath package."
}
$missingTypes = & dotnet run (Join-Path $PSScriptRoot "check-cultmath-types.cs") -- (Join-Path $cultMathPackageRoot "Runtime\Plugins\CultMath.dll") @resolverTypes
if ($LASTEXITCODE -eq 1) {
throw "The CultMath.dll in org.gamecult.cultmath $cultMathAvailable lacks types CultMathResolver formats: $missingTypes. Release CultMath first."
}
if ($LASTEXITCODE -ne 0) {
throw "scripts\check-cultmath-types.cs failed with exit code $LASTEXITCODE."
if ([version]$cultMathDeclared -ne [version]$cultMathAvailable) {
throw "Release order: org.gamecult.cultlib declares org.gamecult.cultmath $cultMathDeclared but the CultMath package is at $cultMathAvailable; cultlib compiles against that package's source, so they must be equal. Release CultMath first, then declare its version."
}
# The tracked DLLs and pdbs are committed beside their source, so none may name a commit or a worktree:
# Source Link writes the commit SHA into the pdb, the informational version carries it too, and each DLL
# carries its pdb's content id. ContinuousIntegrationBuild maps the local source path to /_/.
# dotnet publish has no --no-incremental, so clear the configuration's intermediates instead: a stale obj
# directory must not decide what the byte check compares.
Get-ChildItem -LiteralPath (Join-Path $repoRoot "obj\src") -Directory -ErrorAction SilentlyContinue |
ForEach-Object { Join-Path $_.FullName $Configuration } |
# directory must not decide what the byte check compares. Directory.Build.props puts every project's
# intermediates under obj\<project dir>, CultMath's at obj\packages\cultmath\src\CultMath, so clear the
# configuration directory beside every restored project's project.assets.json, not only those under obj\src.
@(Get-ChildItem -LiteralPath (Join-Path $repoRoot "obj") -Recurse -File -Filter "project.assets.json" -ErrorAction SilentlyContinue) |
ForEach-Object { Join-Path $_.DirectoryName $Configuration } |
Where-Object { Test-Path -LiteralPath $_ } |
ForEach-Object { Remove-Item -LiteralPath $_ -Recurse -Force }
$deterministicArguments = @("--disable-build-servers", "-p:UseSharedCompilation=false",
"-p:ContinuousIntegrationBuild=true", "-p:EnableSourceLink=false",
"-p:IncludeSourceRevisionInInformationalVersion=false", "-m:1")
$publishArguments = @("publish", $projectPath, "-c", $Configuration, "-o", $publishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments
if ($NoRestore) { $publishArguments += "--no-restore" }
if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) {
$publishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))"
foreach ($publish in $managedPublishes) {
$publishArguments = @("publish", (Join-Path $repoRoot $publish.Project), "-c", $Configuration) + $publish.Extra +
@("-o", $publish.Root, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments
if ($NoRestore) { $publishArguments += "--no-restore" }
if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) {
$publishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))"
}
& dotnet @publishArguments
if ($LASTEXITCODE -ne 0) {
throw "$($publish.Label) publish failed with exit code $LASTEXITCODE"
}
}
& dotnet @publishArguments
if ($LASTEXITCODE -ne 0) {
throw "CultLib publish failed with exit code $LASTEXITCODE"
# Gate (2): the CultMath bytes cultlib was built against are the bytes org.gamecult.cultmath ships.
$cultMathTrackedHash = (Get-FileHash -LiteralPath (Join-Path $cultMathPackageRoot "Runtime\Plugins\CultMath.dll") -Algorithm SHA256).Hash
$cultMathComparedRoots = @()
foreach ($publish in $managedPublishes) {
$builtCultMath = Join-Path $publish.Root "CultMath.dll"
if (-not (Test-Path -LiteralPath $builtCultMath)) { continue }
if ((Get-FileHash -LiteralPath $builtCultMath -Algorithm SHA256).Hash -ne $cultMathTrackedHash) {
throw "Release order: the CultMath.dll built into $($publish.Root) differs from the one org.gamecult.cultmath $cultMathAvailable tracks. Either CultMath source changed since that release, its checkout has other line endings, or this toolchain builds different bytes from the one that built the tracked DLL. Check first: git log cultmath-unity-v$cultMathAvailable.. -- packages/cultmath/src for a source change; git ls-files --eol packages/cultmath/src, where every file must read w/crlf (.gitattributes pins it; a clone checked out before that rule needs the files checked out again); then dotnet --version and the host against the build that produced the tracked DLL. A source change means release CultMath first, then declare its version; a toolchain difference means build with the toolchain that produced the tracked DLL."
}
$cultMathComparedRoots += $publish.Root
}
$webSocketPublishArguments = @("publish", $webSocketProjectPath, "-c", $Configuration, "-f", "netstandard2.1", "-o", $webSocketPublishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments
if ($NoRestore) { $webSocketPublishArguments += "--no-restore" }
if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) {
$webSocketPublishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))"
}
& dotnet @webSocketPublishArguments
if ($LASTEXITCODE -ne 0) {
throw "CultLib WebSocket publish failed with exit code $LASTEXITCODE"
}
$quicPublishArguments = @("publish", $quicProjectPath, "-c", $Configuration, "-o", $quicPublishRoot, "-p:CultLibPackageVersion=$unityPackageVersion") + $deterministicArguments
if ($NoRestore) { $quicPublishArguments += "--no-restore" }
if (-not [string]::IsNullOrWhiteSpace($NuGetConfig)) {
$quicPublishArguments += "-p:RestoreConfigFile=$([IO.Path]::GetFullPath($NuGetConfig))"
}
& dotnet @quicPublishArguments
if ($LASTEXITCODE -ne 0) {
throw "CultLib native QUIC managed publish failed with exit code $LASTEXITCODE"
if ($cultMathComparedRoots.Count -eq 0) {
throw "No managed publish produced CultMath.dll, so the CultMath byte gate measured nothing."
}
Write-Host "CultMath byte gate: CultMath.dll in $($cultMathComparedRoots -join ', ') equals org.gamecult.cultmath $cultMathAvailable's tracked DLL."
& (Join-Path $PSScriptRoot "build-quic-native.ps1") `
-Configuration $Configuration `
-OutputDirectory $quicNativeRoot
@ -172,14 +161,10 @@ if (($referencedAssemblies -join "|") -ne ($declaredAssemblies -join "|")) {
throw "GameCult.CultLib.asmdef precompiledReferences differ from the shipped plus external assembly lists."
}
$publishedByName = @{}
foreach ($assembly in Get-ChildItem -LiteralPath $publishRoot -Filter "*.dll") {
$publishedByName[$assembly.Name] = $assembly
}
foreach ($assembly in Get-ChildItem -LiteralPath $quicPublishRoot -Filter "*.dll") {
$publishedByName[$assembly.Name] = $assembly
}
foreach ($assembly in Get-ChildItem -LiteralPath $webSocketPublishRoot -Filter "*.dll") {
$publishedByName[$assembly.Name] = $assembly
foreach ($publish in $managedPublishes) {
foreach ($assembly in Get-ChildItem -LiteralPath $publish.Root -Filter "*.dll") {
$publishedByName[$assembly.Name] = $assembly
}
}
foreach ($assemblyName in $expectedAssemblies) {
if (-not $publishedByName.ContainsKey($assemblyName)) {
@ -187,6 +172,33 @@ foreach ($assemblyName in $expectedAssemblies) {
}
}
# docs/semver-policy.md: refuse a release whose version does not tell the truth. The check measures
# the public API of every shipped assembly against the DLLs the previous cultlib-unity tag
# tracked (read from git), so it runs here, once the assemblies under judgement exist. Every
# tracked assembly the build does not hand over counts as removed, so all of them are handed over.
# The package's tag prefix, changelog and assemblies directory are declared in
# scripts/release-packages.mjs; this call passes only the version and the built assemblies.
$measuredArguments = @()
foreach ($assemblyName in $expectedAssemblies) {
$measuredArguments += @("--api-built", $publishedByName[$assemblyName].FullName)
}
foreach ($publish in $managedPublishes) {
$measuredArguments += @("--api-refs", $publish.Root)
}
# The suite pins the checker's rules and the declared tag prefixes, so it runs first.
& node --test (Join-Path $repoRoot "scripts\check-changelog-semver.test.mjs")
if ($LASTEXITCODE -ne 0) {
throw "The release check suite failed (scripts/check-changelog-semver.test.mjs); not releasing."
}
& node (Join-Path $repoRoot "scripts\check-changelog-semver.mjs") `
--package "org.gamecult.cultlib" `
--version $unityPackageVersion `
--cwd $repoRoot `
@measuredArguments
if ($LASTEXITCODE -ne 0) {
throw "CultLib Unity package failed the semver policy check (see docs/semver-policy.md)."
}
Copy-Item -LiteralPath (Join-Path $templateRoot "Runtime\GameCult.CultLib.asmdef") `
-Destination (Join-Path $outputRoot "Runtime")
foreach ($assemblyName in $expectedAssemblies) {

View file

@ -5,12 +5,14 @@
// enforces; this script is only the mechanical check.
//
// Pure, testable logic lives in the exported functions below. `main()` is the
// CLI wrapper that reads the changelog file and asks git for the previous
// published tag, then calls `evaluateRelease`.
// CLI wrapper that reads the package's declaration (scripts/release-packages.mjs),
// its changelog and the repository's tags, then calls `evaluateRelease`.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { pathToFileURL } from "node:url";
import { execFileSync, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
// The exact heading spelling the policy mandates for a breaking-change
// section. `unity/org.gamecult.cultlib/CHANGELOG.md`'s 1.0.60 entry set this
@ -71,12 +73,13 @@ export function classifyBump(prev, next) {
return { invalid: compareVersions(next, prev) < 0 ? "reverse" : "skip" };
}
// Extracts the `## [<version>]` section of a changelog and reports whether it
// carries a BREAKING_HEADING subsection. Throws if the version has no entry
// Extracts the `## [<version>]` section of a changelog (also `## <version>`,
// and either with Keep a Changelog's ` - YYYY-MM-DD` date) and reports whether
// it carries a BREAKING_HEADING subsection. Throws if the version has no entry
// at all — an undocumented release is refused the same as a mislabelled one.
export function hasBreakingSection(changelogText, version) {
const sectionHeading = new RegExp(
`^##\\s*\\[?${version.replace(/\./g, "\\.")}\\]?\\s*$`,
`^##\\s*\\[?${version.replace(/\./g, "\\.")}\\]?(\\s+-\\s+\\d{4}-\\d{2}-\\d{2})?\\s*$`,
"m",
);
const startMatch = sectionHeading.exec(changelogText);
@ -100,12 +103,15 @@ function isPreOneZero(prev) {
// Evaluates one release. `previousVersion` may be null for a package's first
// ever release (nothing to compare against, so the bump rule does not apply,
// but a changelog entry is still required).
export function evaluateRelease({ packageName, changelogText, version, previousVersion }) {
// but a changelog entry is still required). `measuredBreaks` lists the public
// API diagnostics measured against the previous tag's assemblies; a non-empty
// list makes the release breaking whether or not the changelog says so, and
// the changelog must then declare it.
export function evaluateRelease({ packageName, changelogText, version, previousVersion, measuredBreaks = [] }) {
const next = parseVersion(version);
let breaking;
let declared;
try {
breaking = hasBreakingSection(changelogText, version);
declared = hasBreakingSection(changelogText, version);
} catch (err) {
return { ok: false, reason: `${packageName}: ${err.message}` };
}
@ -127,9 +133,21 @@ export function evaluateRelease({ packageName, changelogText, version, previousV
};
}
if (!breaking) {
const measured = measuredBreaks.length > 0;
if (measured && !declared) {
const shown = measuredBreaks.slice(0, 5).join("; ") + (measuredBreaks.length > 5 ? "; ..." : "");
return {
ok: false,
reason: `${packageName}: ${version} breaks ${measuredBreaks.length} public API member(s) measured against ` +
`${previousVersion} (${shown}); declare them under "${BREAKING_HEADING}" in the changelog and bump accordingly`,
};
}
if (!declared) {
return { ok: true, reason: `${packageName}: ${version} is a ${bump} bump over ${previousVersion}, no breaking section` };
}
const evidence = measured
? `a "${BREAKING_HEADING}" section and ${measuredBreaks.length} measured public API break(s)`
: `a "${BREAKING_HEADING}" section`;
const pre1 = isPreOneZero(prev);
const requiredLanes = pre1 ? ["major", "minor"] : ["major"];
@ -139,102 +157,401 @@ export function evaluateRelease({ packageName, changelogText, version, previousV
: `a major bump`;
return {
ok: false,
reason: `${packageName}: ${version}'s changelog has a "${BREAKING_HEADING}" section but is only a ${bump} bump ` +
reason: `${packageName}: ${version} has ${evidence} but is only a ${bump} bump ` +
`over ${previousVersion}; a breaking release needs ${requirement}`,
};
}
return { ok: true, reason: `${packageName}: ${version} is a ${bump} bump over ${previousVersion} and its "${BREAKING_HEADING}" section agrees` };
return { ok: true, reason: `${packageName}: ${version} is a ${bump} bump over ${previousVersion} and has ${evidence}, which agree` };
}
// --- CLI wrapper: resolves the previous published tag via git and reads the
// changelog off disk, then delegates to the pure functions above. ---
// --- CLI wrapper: reads the package's declaration, the release record (git tags) and the
// changelog, then delegates to the pure functions above. ---
function resolvePreviousVersion(tagPrefix, currentVersion, cwd) {
// The release record, derived from `git tag -l` in --cwd. The previous release is the
// newest '<prefix>-vMAJOR.MINOR.PATCH' tag strictly older than the version, by version order
// (never git's string order), that is also an ancestor of the commit being checked (HEAD of
// --cwd): a backport tagged later on another branch is not in this commit's history, so it
// never changes a rebuild's predecessor. The version's own tag is ignored, so a rebuild at a
// tagged version gets its release-time verdict. A same-prefix tag that does not parse is never
// skipped. A first release is the absence of any older tag in a checkout that holds other tags (a
// checkout with none cannot tell a first release from a missing record), none of which, under
// any prefix, tracks a managed assembly under the package's declared assemblies directory. A
// package that declares none has no such proof: the prefix of an assembly-less package is
// pinned by the suite test that ties every declared prefix to its tag trigger.
function isAncestorOfHead(tag, cwd) {
const run = spawnSync("git", ["merge-base", "--is-ancestor", `refs/tags/${tag}`, "HEAD"], { cwd, stdio: "ignore" });
return run.status === 0 ? true : run.status === 1 ? false : null;
}
function resolveRelease(tagPrefix, versionText, cwd, assemblies) {
let tags;
try {
tags = execFileSync("git", ["tag", "-l", `${tagPrefix}-v*`], { cwd, encoding: "utf8" })
tags = execFileSync("git", ["tag", "-l"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
} catch {
return null;
return { failure: "the tags of --cwd could not be read (not a git repository?), so the previous release is unknown" };
}
const prefix = `${tagPrefix}-v`;
const current = parseVersion(currentVersion);
let best = null;
const current = parseVersion(versionText);
const own = `${prefix}${formatVersion(current)}`;
const older = [];
let newer = null;
for (const tag of tags) {
if (!tag.startsWith(prefix)) continue;
const versionText = tag.slice(prefix.length);
let candidate;
try {
candidate = parseVersion(versionText);
} catch {
continue;
const text = tag.slice(prefix.length);
if (!VERSION_PATTERN.test(text)) {
return { failure: `${tag} starts with ${prefix} but is not ${prefix}MAJOR.MINOR.PATCH, so it cannot be ordered among the releases` };
}
if (sameVersion(candidate, current)) continue; // the tag being released itself
if (compareVersions(candidate, current) >= 0) continue; // ignore anything not older
if (best === null || compareVersions(candidate, best) > 0) {
best = candidate;
const candidate = parseVersion(text);
const order = compareVersions(candidate, current);
if (order === 0) continue; // the tag being released itself
if (order > 0) {
newer ??= tag;
} else {
older.push({ tag, version: candidate });
}
}
return best ? formatVersion(best) : null;
older.sort((a, b) => compareVersions(b.version, a.version));
for (const { tag, version } of older) {
const ancestor = isAncestorOfHead(tag, cwd);
if (ancestor === null) return { failure: `whether ${tag} is an ancestor of the commit being checked could not be read` };
if (ancestor) return { previous: formatVersion(version) };
}
if (older.length > 0) {
return { failure: `${older.length} older ${prefix} tag(s) exist but none is an ancestor of the commit being checked, so the previous release is unknown` };
}
if (newer !== null) {
return { failure: `${newer} exists but no ${prefix} tag is older than ${formatVersion(current)}: the version is older than every release` };
}
if (!tags.some((tag) => tag !== own)) {
return { failure: "this checkout holds no tags; a first release cannot be told from a missing record (fetch the tags)" };
}
if (typeof assemblies === "string") {
// Under every other prefix too: a package whose assemblies some tag has shipped is not new,
// whatever the declared prefix says. This is read from git, never from the changelog's prose.
const tracked = firstTagTrackingManaged(tags.filter((tag) => tag !== own), assemblies, cwd);
if (tracked.failure) return tracked;
if (tracked.tag) {
return { failure: `no ${prefix} tag is an earlier release, but ${tracked.tag} tracks the managed assembly ${tracked.path}: the package has shipped before, so the declared tag prefix is wrong` };
}
}
return { previous: null };
}
// True when `<tagPrefix>-v<version>` already exists. The check gates a NEW
// release; rebuilding an already-tagged, already-immutable version (routine
// local iteration, CI re-runs) is not a release action and should not keep
// re-litigating history on every build.
function tagAlreadyPublished(tagPrefix, version, cwd) {
// The first of the tags that tracks a managed assembly anywhere under `dir`, or none. Whether a
// blob is managed is decided by its bytes once per blob id, however many tags track it. A tag
// that cannot be read, or a .dll that is not a PE image, is a refusal, never a tag that tracks
// nothing.
function firstTagTrackingManaged(tags, dir, cwd) {
const managedBlobs = new Map();
for (const tag of tags) {
try {
const entries = execFileSync("git", ["ls-tree", "-r", "-z", `refs/tags/${tag}`, "--", `${dir}/`], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
})
.split("\0")
.filter((entry) => entry.toLowerCase().endsWith(".dll"));
for (const entry of entries) {
const tab = entry.indexOf("\t");
const id = entry.slice(0, tab).split(" ")[2];
const path = entry.slice(tab + 1);
if (!managedBlobs.has(id)) {
const bytes = execFileSync("git", ["cat-file", "blob", id], { cwd, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1 << 28 });
try {
managedBlobs.set(id, isManagedAssembly(bytes));
} catch {
return { failure: `${path} at ${tag} is a .dll but not a PE image, so a first release cannot be told from a mistyped prefix` };
}
}
if (managedBlobs.get(id)) return { tag, path };
}
} catch {
return { failure: `the assemblies ${tag} tracks under ${dir} could not be read, so a first release cannot be told from a mistyped prefix` };
}
}
return {};
}
// The declaration as a whole: every entry names a string tagPrefix and changelog, and no two
// packages share a prefix (each would be measured against the other's releases). Returns a
// refusal text, or null.
export function checkDeclaration(declared) {
const seen = new Map();
for (const [name, entry] of Object.entries(declared ?? {})) {
if (entry == null || typeof entry.tagPrefix !== "string" || typeof entry.changelog !== "string") {
return `${name} must declare a string tagPrefix and a string changelog`;
}
if (seen.has(entry.tagPrefix)) return `${seen.get(entry.tagPrefix)} and ${name} share one tag prefix`;
seen.set(entry.tagPrefix, name);
}
return null;
}
// --- Measured public API: the built DLLs are compared with the DLLs the
// previous tag tracked, by Microsoft.DotNet.ApiCompat.Tool. The tool, and the
// netstandard reference assemblies it needs to resolve inherited members, are
// pinned in scripts/api-gate/ and restored there; nothing here compares
// members itself. ---
const gateRoot = join(dirname(fileURLToPath(import.meta.url)), "api-gate");
const DIAGNOSTIC_LINE = /^CP\d{4}: /;
// One ApiCompat run's verdict. A diagnostic line is a measured break. A
// non-zero exit with no diagnostic line means the tool did not measure
// anything (missing tool, unreadable input, crash): that is a failure, never a
// pass.
export function readApiCompatRun({ status, output }) {
const breaks = output.split(/\r?\n/).filter((line) => DIAGNOSTIC_LINE.test(line));
if (breaks.length === 0 && status !== 0) {
return { failure: `apicompat exited ${status} without measuring: ${output.trim().split(/\r?\n/).slice(0, 5).join(" | ")}` };
}
return { breaks };
}
function runApiCompat(args) {
const run = spawnSync("dotnet", ["tool", "run", "apicompat", ...args], { cwd: gateRoot, encoding: "utf8" });
return readApiCompatRun({ status: run.status, output: `${run.stdout}${run.stderr}` });
}
function lastLines(text) {
return text.trim().split(/\r?\n/).slice(-3).join(" | ");
}
// Restores the pinned tool and the pinned netstandard reference package, and
// returns the reference assemblies' directory. Both come from scripts/api-gate/
// and need NuGet only until they are cached there.
function prepareGate() {
if (!existsSync(join(gateRoot, ".config", "dotnet-tools.json"))) {
return { failure: "the api-gate tool manifest (scripts/api-gate/.config/dotnet-tools.json) is missing" };
}
for (const [what, args] of [["dotnet tool restore", ["tool", "restore"]], ["dotnet restore", ["restore", "ApiRefs.csproj", "--nologo", "-v", "q"]]]) {
const run = spawnSync("dotnet", args, { cwd: gateRoot, encoding: "utf8" });
if (run.status !== 0) {
return { failure: `${what} failed: ${run.error ? run.error.message : lastLines(`${run.stdout}${run.stderr}`)}` };
}
}
const packageDir = join(gateRoot, "packages", "netstandard.library.ref");
const versions = existsSync(packageDir) ? readdirSync(packageDir).sort() : [];
const refs = versions.length > 0 ? join(packageDir, versions[0], "ref", "netstandard2.1") : null;
if (refs == null || !existsSync(join(refs, "netstandard.dll"))) {
return { failure: "the pinned netstandard reference assemblies were not restored under scripts/api-gate/packages" };
}
return { refs };
}
// Whether a PE image is a managed assembly: its optional header's data directory 14 (the
// CLI header) is non-empty. A PE without one is native and ApiCompat cannot read it. A buffer
// that is not a PE image, or is cut short, throws: decided from the bytes, never from the
// file's name or place.
export function isManagedAssembly(bytes) {
const need = (end) => {
if (end > bytes.length) throw new RangeError("not a PE image");
};
need(0x40);
if (bytes.readUInt16LE(0) !== 0x5a4d) throw new RangeError("not a PE image");
const pe = bytes.readUInt32LE(0x3c);
need(pe + 24);
if (bytes.readUInt32LE(pe) !== 0x00004550) throw new RangeError("not a PE image");
const optionalSize = bytes.readUInt16LE(pe + 20);
const optional = pe + 24;
const magic = bytes.readUInt16LE(optional);
if (magic !== 0x10b && magic !== 0x20b) throw new RangeError("not a PE image");
const directories = optional + (magic === 0x10b ? 96 : 112);
need(directories);
if (bytes.readUInt32LE(directories - 4) <= 14 || optionalSize < directories + 15 * 8 - optional) return false;
need(directories + 15 * 8);
return bytes.readUInt32LE(directories + 14 * 8) !== 0 && bytes.readUInt32LE(directories + 14 * 8 + 4) !== 0;
}
// The managed assemblies the previous tag tracked anywhere under `dir`, as git blobs: no
// worktree, no network, and unaffected by what the working tree holds now. Each is written to
// `into` by file name. A git failure is a refusal that names the step, never git's own output.
function extractBaseline({ tag, dir, into, cwd }) {
const git = (args, options) => execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "ignore"], ...options });
const blobs = [];
try {
const output = execFileSync("git", ["tag", "-l", `${tagPrefix}-v${version}`], { cwd, encoding: "utf8" });
return output.trim().length > 0;
const paths = git(["ls-tree", "-r", "-z", "--name-only", tag, "--", `${dir}/`], { encoding: "utf8" })
.split("\0")
.filter((path) => path.toLowerCase().endsWith(".dll"));
for (const path of paths) blobs.push({ path, bytes: git(["show", `${tag}:${path}`], { maxBuffer: 1 << 28 }) });
} catch {
return false;
return { failure: `git could not read the assemblies tracked under ${dir} at ${tag}` };
}
const names = [];
for (const { path, bytes } of blobs) {
let managed;
try {
managed = isManagedAssembly(bytes);
} catch {
return { failure: `${path} at ${tag} is a .dll but not a PE image` };
}
if (!managed) continue;
const name = basename(path);
if (names.includes(name)) return { failure: `${tag} tracks two managed assemblies named ${name} under ${dir}` };
writeFileSync(join(into, name), bytes);
names.push(name);
}
return { names };
}
// Compares each built assembly with its namesake at the previous tag. Measuring nothing is a
// failure: the declared directory must hold a managed assembly at the tag. A managed assembly
// the tag tracked and the build no longer hands over is itself a break, whatever its name or
// place; a built assembly with no namesake is an addition and is not examined.
export function measureApiBreaks({ tagPrefix, previousVersion, assemblies, built, refs, cwd }) {
const tag = `${tagPrefix}-v${previousVersion}`;
const work = mkdtempSync(join(tmpdir(), "cultlib-apicompat-"));
try {
const left = join(work, "left");
mkdirSync(left);
const baseline = extractBaseline({ tag, dir: assemblies, into: left, cwd });
if (baseline.failure) return baseline;
const baselineNames = baseline.names;
if (baselineNames.length === 0) {
return { failure: `${tag} tracks no managed assembly under ${assemblies}: the declared directory is missing or moved, or that tag does not track the DLLs` };
}
const gate = prepareGate();
if (gate.failure) return gate;
const builtNames = new Set(built.map((path) => basename(path)));
const breaks = baselineNames
.filter((name) => !builtNames.has(name))
.map((name) => `assembly ${name} exists at ${tag} but is no longer built`);
for (const path of built) {
const name = basename(path);
if (!baselineNames.includes(name)) continue;
const leftRefs = [left, gate.refs].join(",");
const rightRefs = [...new Set([dirname(path), ...refs, gate.refs])].join(",");
const run = runApiCompat(["--left-assembly", join(left, name), "--right-assembly", path, "--left-assembly-references", leftRefs, "--right-assembly-references", rightRefs]);
if (run.failure) return { failure: `${name}: ${run.failure}` };
breaks.push(...run.breaks);
}
return { breaks };
} finally {
rmSync(work, { recursive: true, force: true });
}
}
// Repeatable options collect into arrays. Any other option is a usage error.
const KNOWN = new Set(["package", "version", "cwd", "api-built", "api-refs"]);
const REPEATABLE = new Set(["api-built", "api-refs"]);
function parseArgs(argv) {
const args = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith("--")) continue;
const key = arg.slice(2);
args[key] = argv[i + 1];
if (!KNOWN.has(key)) return { unknown: arg };
if (REPEATABLE.has(key)) {
(args[key] ??= []).push(argv[i + 1]);
} else {
args[key] = argv[i + 1];
}
i += 1;
}
return args;
}
function main() {
function refuse(message) {
console.error(message);
process.exitCode = 1;
}
const UNMEASURED_NOTICE =
'public API measured; changes ApiCompat cannot see (see "Unmeasured changes" in docs/semver-policy.md) must still be declared under "### Breaking"';
async function main() {
const args = parseArgs(process.argv.slice(2));
const { package: packageName, changelog, version, "tag-prefix": tagPrefix, cwd = process.cwd() } = args;
if (!packageName || !changelog || !version || !tagPrefix) {
const { package: packageName, version, cwd = process.cwd() } = args;
// The tool runs from scripts/api-gate, so a path given relative to this process is made absolute first.
const built = (args["api-built"] ?? []).map((path) => resolve(path));
if (args.unknown || !packageName || !version) {
console.error(
"usage: check-changelog-semver.mjs --package <name> --changelog <path> --version <x.y.z> --tag-prefix <prefix> [--cwd <dir>]",
"usage: check-changelog-semver.mjs --package <name> --version <x.y.z> [--cwd <dir>] [--api-built <dll>... [--api-refs <dir>...]]",
);
process.exitCode = 2;
return;
}
if (tagAlreadyPublished(tagPrefix, version, cwd)) {
console.log(`${packageName}: ${version} is already published as ${tagPrefix}-v${version}; not re-checking a rebuild of immutable history`);
// Checked before anything reads tags: a malformed version is its own refusal, and the
// value is not repeated back.
if (!VERSION_PATTERN.test(version.trim())) {
refuse(`${packageName}: --version is not a MAJOR.MINOR.PATCH version`);
return;
}
if (!existsSync(changelog)) {
console.error(`${packageName}: changelog not found at ${changelog}`);
process.exitCode = 1;
// The package's release identity is declared once, in the repository being released.
let declared;
try {
declared = (await import(pathToFileURL(resolve(cwd, "scripts", "release-packages.mjs")).href)).default;
} catch {
refuse(`${packageName}: scripts/release-packages.mjs could not be loaded from --cwd`);
return;
}
const changelogText = readFileSync(changelog, "utf8");
const previousVersion = resolvePreviousVersion(tagPrefix, version, cwd);
const result = evaluateRelease({ packageName, changelogText, version, previousVersion });
const malformed = checkDeclaration(declared);
if (malformed) {
refuse(`${packageName}: scripts/release-packages.mjs is malformed: ${malformed}`);
return;
}
const entry = Object.hasOwn(declared ?? {}, packageName) ? declared[packageName] : null;
if (entry == null) {
refuse(`${packageName}: not a package declared in scripts/release-packages.mjs`);
return;
}
const { tagPrefix, assemblies } = entry;
const changelog = resolve(cwd, entry.changelog);
let changelogText;
try {
changelogText = readFileSync(changelog, "utf8");
} catch (err) {
refuse(`${packageName}: ${err.code === "ENOENT" ? "changelog not found" : "changelog cannot be read"} at ${changelog}`);
return;
}
if (typeof assemblies === "string" && built.length === 0) {
refuse(`${packageName}: ships the assemblies under ${assemblies}, so the release must hand them over with --api-built`);
return;
}
if (typeof assemblies !== "string" && built.length > 0) {
refuse(`${packageName}: declares no assemblies directory, so --api-built has nothing to be measured against`);
return;
}
const release = resolveRelease(tagPrefix, version, cwd, assemblies);
if (release.failure) {
refuse(`${packageName}: ${release.failure}`);
return;
}
const previousVersion = release.previous;
let measuredBreaks = [];
if (previousVersion != null && built.length > 0) {
const measurement = measureApiBreaks({
tagPrefix,
previousVersion,
assemblies,
built,
refs: (args["api-refs"] ?? []).map((path) => resolve(path)),
cwd,
});
if (measurement.failure) {
refuse(`${packageName}: public API could not be measured against ${tagPrefix}-v${previousVersion}: ${measurement.failure}`);
return;
}
measuredBreaks = measurement.breaks;
}
const result = evaluateRelease({ packageName, changelogText, version, previousVersion, measuredBreaks });
console.log(result.reason);
if (!result.ok) {
process.exitCode = 1;
return;
}
if (previousVersion != null && built.length > 0) {
console.log(UNMEASURED_NOTICE);
}
}
const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
main();
await main();
}

File diff suppressed because it is too large Load diff

View file

@ -1,30 +0,0 @@
// Release gate helper for build-unity-package.ps1: reads an assembly's type-definition table and
// reports which of the named CultMath types it does not define as a public top-level type.
// Usage: dotnet run scripts/check-cultmath-types.cs -- <assembly.dll> <TypeName>...
// Exit 0 when every type is defined, 1 when any is missing, 2 on bad usage.
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
if (args.Length < 2)
{
Console.Error.WriteLine("usage: check-cultmath-types <assembly.dll> <TypeName>...");
return 2;
}
using var stream = File.OpenRead(args[0]);
using var pe = new PEReader(stream);
var metadata = pe.GetMetadataReader();
var defined = new HashSet<string>();
foreach (var handle in metadata.TypeDefinitions)
{
var type = metadata.GetTypeDefinition(handle);
if (!type.GetDeclaringType().IsNil) continue;
if ((type.Attributes & TypeAttributes.VisibilityMask) != TypeAttributes.Public) continue;
if (metadata.GetString(type.Namespace) == "CultMath") defined.Add(metadata.GetString(type.Name));
}
var missing = args.Skip(1).Where(name => !defined.Contains(name)).ToArray();
if (missing.Length == 0) return 0;
Console.WriteLine(string.Join(", ", missing));
return 1;

View file

@ -0,0 +1,54 @@
// Fails when a TypeScript test file exists that no npm script of its package runs.
//
// A package's `test` script names the compiled files it runs, either by glob or one by one, and a file that is compiled
// and listed nowhere passes every suite while proving nothing: cultcache-ts's decode-document-payload test sat in that
// state behind an explicit two-file list. Every test/**/*.test.ts maps to its dist-test/**/*.test.js, and that path has
// to match an argument of `node --test` in the package's `test` script, or in `test:interop` for test/interop.
import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const rootManifest = JSON.parse(readFileSync(join(repoRoot, "package.json"), "utf8"));
function testFiles(dir, prefix = "") {
return readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
entry.isDirectory()
? testFiles(join(dir, entry.name), `${prefix}${entry.name}/`)
: entry.name.endsWith(".test.ts") ? [`${prefix}${entry.name}`] : []);
}
// The paths `node --test` is given in a script: the words of its command after `--test` that are not flags.
function nodeTestArguments(script) {
const words = script?.split("&&").map(part => part.trim().split(/\s+/)).find(part => part[0] === "node" && part.includes("--test"));
return words ? words.slice(words.indexOf("--test") + 1).filter(argument => !argument.startsWith("--")) : [];
}
function matches(pattern, path) {
const [directory, file] = [dirname(pattern), pattern.slice(dirname(pattern).length + 1)];
if (directory !== dirname(path)) return false;
return new RegExp(`^${file.split("*").map(part => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")}$`)
.test(path.slice(directory.length + 1));
}
const unwired = [];
let checked = 0;
for (const workspace of rootManifest.workspaces) {
const packageRoot = join(repoRoot, workspace);
const scripts = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8")).scripts ?? {};
for (const file of testFiles(join(packageRoot, "test"))) {
checked += 1;
const compiled = `dist-test/test/${file.replace(/\.ts$/, ".js")}`;
const scriptName = file.startsWith("interop/") ? "test:interop" : "test";
if (!nodeTestArguments(scripts[scriptName]).some(pattern => matches(pattern, compiled))) {
unwired.push(`${workspace}: test/${file} is not run by its package's ${scriptName} script`);
}
}
}
if (checked === 0) throw new Error("The wiring check found no test files; it is looking in the wrong place.");
if (unwired.length > 0) {
console.error(unwired.join("\n"));
process.exit(1);
}
console.log(`${checked} TypeScript test files, all run by their package's script.`);

View file

@ -13,55 +13,90 @@ $outputRoot = if ([IO.Path]::IsPathRooted($OutputDirectory)) {
Join-Path $repoRoot $OutputDirectory
}
$projects = @(
"src\GameCult.Logging\GameCult.Logging.csproj",
"src\GameCult.Caching\GameCult.Caching.csproj",
"src\GameCult.Caching.MessagePack\GameCult.Caching.MessagePack.csproj",
"src\GameCult.Networking\GameCult.Networking.csproj",
"src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj",
"src\GameCult.Mesh\GameCult.Mesh.csproj"
# The public packages a consumer references directly. Everything they reach
# through ProjectReference is part of the published closure and is packed too,
# so a new internal dependency cannot leave the feed short of a package.
$rootProjects = @(
"src\GameCult.Mesh\GameCult.Mesh.csproj",
"src\GameCult.Networking.WebSockets\GameCult.Networking.WebSockets.csproj"
)
# MSBuild paths use backslashes; normalize them so the closure walk also
# resolves on Linux and macOS.
function Resolve-ProjectPath([string] $path) {
return [IO.Path]::GetFullPath($path.Replace('\', [string][IO.Path]::DirectorySeparatorChar))
}
function Get-ProjectReferenceClosure([string[]] $roots) {
$seen = [System.Collections.Generic.List[string]]::new()
$pending = [System.Collections.Generic.Queue[string]]::new()
foreach ($root in $roots) { $pending.Enqueue((Resolve-ProjectPath $root)) }
while ($pending.Count -gt 0) {
$project = $pending.Dequeue()
if ($seen.Contains($project)) { continue }
if (-not (Test-Path -LiteralPath $project -PathType Leaf)) {
throw "Project in the NuGet closure was not found: $project"
}
$seen.Add($project)
# Every ProjectReference counts, whatever its Condition: a reference
# present for any target framework ships in the package's dependencies.
foreach ($reference in ([xml](Get-Content -LiteralPath $project -Raw)).SelectNodes("//*[local-name()='ProjectReference']")) {
$include = $reference.GetAttribute("Include").Trim()
if ($include -match '\$\(') {
throw "Cannot resolve the MSBuild property in ProjectReference '$include' from $project"
}
$pending.Enqueue((Resolve-ProjectPath (Join-Path (Split-Path -Parent $project) $include)))
}
}
return $seen
}
$projects = Get-ProjectReferenceClosure ($rootProjects | ForEach-Object { Join-Path $repoRoot $_ })
if (Test-Path -LiteralPath $outputRoot) {
Remove-Item -LiteralPath $outputRoot -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $outputRoot | Out-Null
$versionArguments = @()
if (-not [string]::IsNullOrWhiteSpace($PackageVersion)) {
$versionArguments += "-p:CultLibPackageVersion=$PackageVersion"
}
$expectedPackages = @()
foreach ($project in $projects) {
$packArguments = @(
"pack", (Join-Path $repoRoot $project), "-c", $Configuration, "-o", $outputRoot,
"--nologo", "--verbosity", "quiet", "-p:NoWarn=1591%3BCS8632"
)
if (-not [string]::IsNullOrWhiteSpace($PackageVersion)) {
$packArguments += "-p:CultLibPackageVersion=$PackageVersion"
# The package identity comes from MSBuild itself: GameCult.Math, for one,
# carries its own PackageId and version rather than the CultLib version.
$identity = (& dotnet msbuild $project -nologo "-getProperty:PackageId" "-getProperty:Version" @versionArguments) |
Out-String | ConvertFrom-Json
if ($LASTEXITCODE -ne 0) {
throw "Could not read the package identity of $project"
}
$expectedPackages += "$($identity.Properties.PackageId).$($identity.Properties.Version).nupkg"
$packArguments = @(
"pack", $project, "-c", $Configuration, "-o", $outputRoot,
"--nologo", "--verbosity", "quiet", "-p:NoWarn=1591%3BCS8632"
) + $versionArguments
& dotnet @packArguments
if ($LASTEXITCODE -ne 0) {
throw "NuGet pack failed for $project with exit code $LASTEXITCODE"
}
}
foreach ($package in $expectedPackages) {
if (-not (Test-Path -LiteralPath (Join-Path $outputRoot $package))) {
throw "NuGet dependency closure is missing $package"
}
}
$meshPackage = Get-ChildItem -LiteralPath $outputRoot -Filter "GameCult.Mesh.*.nupkg" |
Where-Object { $_.Name -notlike "*.snupkg" } |
Select-Object -First 1
if (-not $meshPackage) {
throw "GameCult.Mesh package was not produced."
}
$version = [regex]::Match($meshPackage.Name, '^GameCult\.Mesh\.(.+)\.nupkg$').Groups[1].Value
$expectedPackages = @(
"GameCult.Logging.$version.nupkg",
"GameCult.Caching.$version.nupkg",
"GameCult.Caching.MessagePack.$version.nupkg",
"GameCult.Networking.$version.nupkg",
"GameCult.Networking.WebSockets.$version.nupkg",
"GameCult.Mesh.$version.nupkg"
)
foreach ($package in $expectedPackages) {
if (-not (Test-Path -LiteralPath (Join-Path $outputRoot $package))) {
throw "NuGet dependency closure is missing $package"
}
}
if (-not $SkipConsumerSmoke) {
$smokeRoot = Join-Path $repoRoot "artifacts\nuget-consumer-smoke"

View file

@ -0,0 +1,92 @@
// How publish-packages.yml releases a package. From this one process, in order: the release tag must name
// the package's declared prefix and its manifest version, the release-checks suite must pass, the semver
// policy check must pass for that version, the package's own tests must pass, and only then the release
// action runs. No workflow condition can then release what any of those checks did not pass.
// docs/semver-policy.md, "The suite gates every release".
//
// node scripts/release-after-suite.mjs npm-publish <package dir> <git ref> npm publish --access public in <dir>
// node scripts/release-after-suite.mjs python-build <package dir> <git ref> python -m build <dir>, for the PyPI step
//
// <git ref> is the run's GITHUB_REF. A tag ref is a release and gets the tag and semver checks; npm-publish
// refuses any other ref. python-build on a branch ref builds without them, for the manual runs that publish
// nothing.
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import releasePackages from "./release-packages.mjs";
export const suite = fileURLToPath(new URL("./check-changelog-semver.test.mjs", import.meta.url));
export const checker = fileURLToPath(new URL("./check-changelog-semver.mjs", import.meta.url));
const repoRoot = fileURLToPath(new URL("..", import.meta.url));
// The checks run without the variables that can make `node --test` run nothing and exit 0
// (NODE_OPTIONS test filters, NODE_TEST_CONTEXT, any NODE_TEST_*), and without the publish token,
// which only the release action receives.
const UNCHECKED = /^(NODE_OPTIONS|NODE_TEST_.*|NODE_AUTH_TOKEN)$/i;
export const checkEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => !UNCHECKED.test(key)));
const pyprojectField = (text, field) =>
text.split(/^\[/m).find((section) => section.startsWith("project]"))?.match(new RegExp(`^${field} = "([^"]+)"$`, "m"))?.[1];
// Scoped npm packages default to restricted, and CultLib is MIT, so the publish says public.
export const actions = {
"npm-publish": {
manifest: (dir) => JSON.parse(readFileSync(join(dir, "package.json"), "utf8")),
test: (dir) => ["npm", ["test"], dir],
release: (dir) => ["npm", ["publish", "--access", "public"], dir],
tagOnly: true,
},
"python-build": {
manifest: (dir) => {
const text = readFileSync(join(dir, "pyproject.toml"), "utf8");
return { name: pyprojectField(text, "name"), version: pyprojectField(text, "version") };
},
test: (dir) => ["python", ["-m", "unittest", "discover", "-s", join(dir, "tests")], undefined],
release: (dir) => ["python", ["-m", "build", dir], undefined],
tagOnly: false,
},
};
const spawn = (command, args, cwd, env) => spawnSync(command, args, { cwd, env, stdio: "inherit" }).status ?? 1;
const refuse = (message) => {
console.error(`${message}; not releasing.`);
return 1;
};
// Returns the exit code. `run(command, args, cwd, env)` returns a command's exit code; tests pass their own.
export function releaseAfterSuite(argv, run = spawn, env = process.env) {
const [name, dir, ref, ...rest] = argv;
if (!Object.hasOwn(actions, name ?? "") || !dir || !ref || rest.length > 0) {
console.error(`usage: node scripts/release-after-suite.mjs <${Object.keys(actions).join("|")}> <package dir> <git ref>`);
return 2;
}
const action = actions[name];
let manifest;
try {
manifest = action.manifest(dir);
} catch {
return refuse(`${dir} has no readable manifest`);
}
const entry = Object.hasOwn(releasePackages, manifest.name ?? "") ? releasePackages[manifest.name] : null;
if (entry === null) return refuse(`${dir} is ${manifest.name}, which scripts/release-packages.mjs does not declare`);
const isTag = ref.startsWith("refs/tags/");
const tag = `refs/tags/${entry.tagPrefix}-v${manifest.version}`;
if (isTag && ref !== tag) return refuse(`${ref} is not ${tag}, the tag of ${manifest.name}'s manifest version`);
if (!isTag && action.tagOnly) return refuse(`${name} releases only from a release tag, and ${ref} is not one`);
const clean = checkEnv(env);
if (run(process.execPath, ["--test", suite], undefined, clean) !== 0) {
return refuse("The release check suite failed (scripts/check-changelog-semver.test.mjs)");
}
if (isTag && run(process.execPath, [checker, "--package", manifest.name, "--version", manifest.version, "--cwd", repoRoot], undefined, clean) !== 0) {
return refuse(`${manifest.name} ${manifest.version} fails the semver policy (docs/semver-policy.md)`);
}
if (run(...action.test(dir), clean) !== 0) return refuse(`${manifest.name}'s own tests failed`);
return run(...action.release(dir), env);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exitCode = releaseAfterSuite(process.argv.slice(2));
}

View file

@ -0,0 +1,38 @@
// The one declaration of what each released package is, read by
// scripts/check-changelog-semver.mjs (docs/semver-policy.md) and by nothing a caller types.
// Keyed by the --package name. Paths are repo-relative.
// tagPrefix releases are tags named '<tagPrefix>-vMAJOR.MINOR.PATCH'
// changelog the package's CHANGELOG.md
// assemblies the directory whose tracked DLLs the package ships; absent when it ships none
export default {
"org.gamecult.cultlib": {
tagPrefix: "cultlib-unity",
changelog: "unity/org.gamecult.cultlib/CHANGELOG.md",
assemblies: "unity/org.gamecult.cultlib/Runtime/Plugins",
},
"org.gamecult.cultmath": {
tagPrefix: "cultmath-unity",
changelog: "packages/cultmath/unity/org.gamecult.cultmath/CHANGELOG.md",
assemblies: "packages/cultmath/unity/org.gamecult.cultmath/Runtime/Plugins",
},
"org.gamecult.caching.unity": {
tagPrefix: "caching-unity",
changelog: "src/GameCult.Unity/Assets/Caching/CHANGELOG.md",
},
"@gamecult/cultcache-ts": {
tagPrefix: "cultcache-ts",
changelog: "packages/cultcache-ts/CHANGELOG.md",
},
"cultcache-py": {
tagPrefix: "cultcache-py",
changelog: "packages/cultcache-py/CHANGELOG.md",
},
"cultnet-py": {
tagPrefix: "cultnet-py",
changelog: "packages/cultnet-py/CHANGELOG.md",
},
"cultmesh-py": {
tagPrefix: "cultmesh-py",
changelog: "packages/cultmesh-py/CHANGELOG.md",
},
};

View file

@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const command = process.argv[2];
if (!command) throw new Error("Usage: node scripts/run-typescript-workspaces.mjs <script>");
@ -26,6 +27,14 @@ const childEnv = process.platform === "win32"
}
: process.env;
// A test file no script runs is a suite that passes while proving nothing, so `test` starts by checking the wiring.
if (command === "test") {
execFileSync(process.execPath, [join(dirname(fileURLToPath(import.meta.url)), "check-typescript-tests-wired.mjs")], {
env: childEnv,
stdio: "inherit",
});
}
for (const workspace of workspaces) {
execFileSync(process.execPath, [npmCli, "--workspace", workspace, "run", command], {
env: childEnv,

View file

@ -78,9 +78,66 @@ try {
writeFileSync(join(consumerRoot, "runtime-smoke.cjs"), `
const assert = require("node:assert/strict");
const cache = require("@gamecult/cultcache-ts");
const documentEntry = require("@gamecult/cultcache-ts/document");
const net = require("cultnet-ts");
const mesh = require("cultmesh-ts");
assert.equal(typeof cache.defineDocumentType, "function");
// The document owner is also an entry of its own, which the browser client imports without the Node-only cache.
assert.equal(documentEntry.decodeDocumentPayload, cache.decodeDocumentPayload);
// No entry exports a function that reads a payload around its schema, whatever it is called, wherever it is mounted: the
// package-internal readers are loaded from the packed dist files by path and looked for by identity in every packed
// entry (own names, 'default', and the members of any namespace or function export), and every exported function is
// shown a MessagePack map and a slot record and must not hand either back decoded. The only reader allowed is the schema-checked owner.
const path = require("node:path");
const msgpack = require("@msgpack/msgpack");
const dist = path.dirname(require.resolve("@gamecult/cultcache-ts"));
const internalReaders = new Map([
["readWire", require(path.join(dist, "wire.js")).readWire],
["resolveDocumentFormatter", require(path.join(dist, "document-formatter.js")).resolveDocumentFormatter],
["@msgpack/msgpack decode", msgpack.decode],
["@msgpack/msgpack decodeMulti", msgpack.decodeMulti],
]);
for (const [name, reader] of internalReaders) assert.equal(typeof reader, "function", name + " was found in the packed package");
const inspection = require("@gamecult/cultcache-ts/inspection");
const entries = { root: cache, codecs: cache.codecs, document: documentEntry, inspection };
// A map and a slot record (an array), each with the text its decoded form prints as: a reader of either shape gives itself away.
const probes = [{ probe: 7 }, ["probe", 7]].map((value) => [msgpack.encode(value), JSON.stringify(value)]);
const exportsOf = (entry) => {
const found = [];
const seen = new Set();
const visit = (value, where, depth) => {
if ((typeof value !== "function" && (typeof value !== "object" || value === null)) || seen.has(value) || depth > 4) return;
seen.add(value);
found.push([where, value]);
for (const key of Object.getOwnPropertyNames(value)) {
if (typeof value === "function" && ["length", "name", "prototype", "caller", "arguments"].includes(key)) continue;
let member;
try { member = value[key]; } catch { continue; }
visit(member, where + "." + key, depth + 1);
}
};
for (const key of Object.getOwnPropertyNames(entry)) visit(entry[key], key, 0);
return found;
};
for (const [entryName, entry] of Object.entries(entries)) {
for (const [where, value] of exportsOf(entry)) {
for (const [name, reader] of internalReaders) {
assert.notEqual(value, reader, entryName + " entry exports " + name + " as " + where);
}
if (typeof value !== "function" || value === cache.decodeDocumentPayload) continue;
for (const [probePayload, decodedText] of probes) {
let shown;
try {
shown = JSON.stringify(value(probePayload), (_key, member) => (member instanceof Map ? Object.fromEntries(member) : member));
} catch { continue; }
assert.ok(!shown?.includes(decodedText), entryName + " entry exports " + where + ", which reads a payload without its schema");
}
}
}
assert.equal(typeof documentEntry.checkPayloadDepth, "undefined");
assert.equal(documentEntry.MAX_PAYLOAD_DEPTH, 256);
assert.equal(cache.MAX_PAYLOAD_DEPTH, 256);
assert.equal(documentEntry.CultCachePayloadDepthError, cache.CultCachePayloadDepthError);
assert.equal(typeof net.CultNetPeer, "function");
assert.equal(typeof mesh.CultMesh, "function");
assert.equal(typeof mesh.CultMeshProviderSession, "function");
@ -101,6 +158,7 @@ assert.equal("putDocument" in CultMeshBrowserClient.prototype, false);
writeFileSync(join(consumerRoot, "types-smoke.ts"), `
import { defineDocumentType } from "@gamecult/cultcache-ts";
import { decodeDocumentPayload, type DocumentPayload } from "@gamecult/cultcache-ts/document";
import { CultNetPeer } from "cultnet-ts";
import {
CultMesh,
@ -112,6 +170,8 @@ import {
const point: CultMeshVec2 = CultMesh.vec2(3, 4);
const defineDocument: typeof defineDocumentType = defineDocumentType;
const decodeOwner: typeof decodeDocumentPayload = decodeDocumentPayload;
let opaque: DocumentPayload | undefined;
const peerType: typeof CultNetPeer = CultNetPeer;
const providerSessionType: typeof CultMeshProviderSession = CultMeshProviderSession;
const providerIdentity: CultMeshProviderIdentity = {
@ -123,6 +183,8 @@ const providerIdentity: CultMeshProviderIdentity = {
let providerTransport: CultMeshProviderTransport | undefined;
void point;
void defineDocument;
void decodeOwner;
void opaque;
void peerType;
void providerSessionType;
void providerIdentity;
@ -142,6 +204,7 @@ void providerTransport;
], { cwd: consumerRoot, stdio: "inherit" });
writeFileSync(join(consumerRoot, "browser-types-smoke.mts"), `
import { decodeDocumentPayload } from "@gamecult/cultcache-ts/document";
import {
CultMeshBrowserClient,
type CultMeshBrowserIdentity,
@ -157,9 +220,11 @@ const lease: CultMeshRawDocumentLeaseOptions = {
recordKey: "smoke:main",
};
const clientType: typeof CultMeshBrowserClient = CultMeshBrowserClient;
const decodeOwner: typeof decodeDocumentPayload = decodeDocumentPayload;
void identity;
void lease;
void clientType;
void decodeOwner;
`);
execFileSync(process.execPath, [
tsc,
@ -172,6 +237,29 @@ void clientType;
"browser-types-smoke.mts",
], { cwd: consumerRoot, stdio: "inherit" });
// The formatter that reads a payload around its schema is in no entry: importing it from the document entry does not compile.
writeFileSync(join(consumerRoot, "formatter-refused.mts"), `
// @ts-expect-error resolveDocumentFormatter is not exported from the document entry
import { resolveDocumentFormatter } from "@gamecult/cultcache-ts/document";
void resolveDocumentFormatter;
import { codecs } from "@gamecult/cultcache-ts";
// @ts-expect-error codecFormatter is not exported from the document entry
import { codecFormatter } from "@gamecult/cultcache-ts/document";
void codecFormatter;
// @ts-expect-error codecFormatter is not a member of the root's codecs namespace
void codecs.codecFormatter;
`);
execFileSync(process.execPath, [
tsc,
"--noEmit",
"--strict",
"--target", "ES2022",
"--module", "NodeNext",
"--moduleResolution", "NodeNext",
"--skipLibCheck",
"formatter-refused.mts",
], { cwd: consumerRoot, stdio: "inherit" });
console.log("TypeScript package closure smoke: passed");
for (const tarball of tarballs) console.log(`Packed: ${tarball}`);
} finally {

View file

@ -11,15 +11,18 @@ $ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$packageRoot = Join-Path $repoRoot "src\GameCult.Unity\Assets\Caching"
$manifestPath = Join-Path $packageRoot "package.json"
$changelogPath = Join-Path $packageRoot "CHANGELOG.md"
$version = (Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json).version
# The suite pins the checker's rules and the declared tag prefixes, so it runs first.
& node --test (Join-Path $repoRoot "scripts\check-changelog-semver.test.mjs")
if ($LASTEXITCODE -ne 0) {
throw "The release check suite failed (scripts/check-changelog-semver.test.mjs); not releasing."
}
& node (Join-Path $repoRoot "scripts\check-changelog-semver.mjs") `
--package "org.gamecult.caching.unity" `
--changelog $changelogPath `
--version $version `
--tag-prefix "caching-unity" `
--cwd $repoRoot
if ($LASTEXITCODE -ne 0) {
throw "org.gamecult.caching.unity failed the semver policy check (see docs/semver-policy.md)."

View file

@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { createServer as createHttpServer } from "node:http";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createServer as createNetServer } from "node:net";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
@ -38,8 +38,33 @@ let browser;
try {
const tsc = join(repoRoot, "node_modules", "typescript", "bin", "tsc");
await run(process.execPath, [tsc, "-p", join(repoRoot, "packages", "cultcache-ts", "tsconfig.json"), "--pretty", "false"]);
await run(process.execPath, [tsc, "-p", join(repoRoot, "packages", "cultnet-ts", "tsconfig.json"), "--pretty", "false"]);
await run(process.execPath, [tsc, "-p", join(repoRoot, "packages", "cultmesh-browser", "tsconfig.json"), "--pretty", "false"]);
// esbuild strips types, so a package signature change would otherwise surface as a browser error. The page is
// type-checked against the same module map the bundle uses.
const moduleMap = {
"@gamecult/eve-contracts": join(eveRoot, "packages", "eve-contracts", "src", "index.ts"),
"@gamecult/eve-browser-lowering": join(eveRoot, "packages", "eve-browser-lowering", "src", "index.ts"),
"cultmesh-browser": join(repoRoot, "packages", "cultmesh-browser", "src", "index.ts"),
"cultnet-ts/contracts": join(repoRoot, "packages", "cultnet-ts", "src", "contracts.ts"),
};
const sampleTsconfig = join(workRoot, "tsconfig.json");
await writeFile(sampleTsconfig, JSON.stringify({
compilerOptions: {
target: "ES2022",
module: "ES2022",
moduleResolution: "Bundler",
lib: ["ES2022", "ESNext.Disposable", "DOM", "DOM.Iterable"],
strict: true,
noEmit: true,
skipLibCheck: true,
types: [],
paths: Object.fromEntries(Object.entries(moduleMap).map(([name, target]) => [name, [target]])),
},
files: [join(sampleRoot, "browser", "main.ts")],
}));
await run(process.execPath, [tsc, "-p", sampleTsconfig, "--pretty", "false"]);
await build({
entryPoints: [join(sampleRoot, "browser", "main.ts")],
outfile: bundlePath,
@ -48,12 +73,7 @@ try {
platform: "browser",
target: "es2022",
sourcemap: true,
alias: {
"@gamecult/eve-contracts": join(eveRoot, "packages", "eve-contracts", "src", "index.ts"),
"@gamecult/eve-browser-lowering": join(eveRoot, "packages", "eve-browser-lowering", "src", "index.ts"),
"cultmesh-browser": join(repoRoot, "packages", "cultmesh-browser", "src", "index.ts"),
"cultnet-ts/contracts": join(repoRoot, "packages", "cultnet-ts", "src", "contracts.ts"),
},
alias: moduleMap,
logLevel: "warning",
});
const bundle = await readFile(bundlePath, "utf8");
@ -222,10 +242,15 @@ function startDotnet(arguments_) {
waiter.reject(new Error(`dotnet sample exited ${code}\n${output}\n${error}`));
}
});
// A line is complete once its newline has arrived: a stdout chunk can end inside a line, and the 10,000-operation
// benchmark line was parsed as JSON half-written.
function completeLines() {
return output.split(/\r?\n/u).slice(0, -1);
}
function settle() {
for (let index = waiters.length - 1; index >= 0; index--) {
const waiter = waiters[index];
const line = output.split(/\r?\n/u).find(value => value.startsWith(waiter.prefix));
const line = completeLines().find(value => value.startsWith(waiter.prefix));
if (!line) continue;
waiters.splice(index, 1);
clearTimeout(waiter.timer);
@ -238,7 +263,7 @@ function startDotnet(arguments_) {
process.stdin.write(`${line}\n`);
},
waitFor(prefix, timeoutMs = 30_000) {
const existing = output.split(/\r?\n/u).find(value => value.startsWith(prefix));
const existing = completeLines().find(value => value.startsWith(prefix));
if (existing) return Promise.resolve(existing.slice(prefix.length));
return new Promise((resolve, reject) => {
const waiter = {