From 43f796270505b2c2a81637cc18520413f5cb6fe7 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:21:00 -0600 Subject: [PATCH 1/9] Cap local test parallelism (Vitest workers, xUnit threads) --- Directory.Build.props | 5 +++++ src/Ui/tsconfig.json | 2 +- src/Ui/vite.config.ts | 6 +++++- src/Ui/vitest.workers.test.ts | 30 ++++++++++++++++++++++++++++++ src/Ui/vitest.workers.ts | 17 +++++++++++++++++ tests/xunit.runner.json | 4 ++++ 6 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 src/Ui/vitest.workers.test.ts create mode 100644 src/Ui/vitest.workers.ts create mode 100644 tests/xunit.runner.json diff --git a/Directory.Build.props b/Directory.Build.props index 1f594ea9..2d9e2ae3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -85,4 +85,9 @@ $(NoWarn);CA1859 + + + + + diff --git a/src/Ui/tsconfig.json b/src/Ui/tsconfig.json index 10c1614a..d8f49212 100644 --- a/src/Ui/tsconfig.json +++ b/src/Ui/tsconfig.json @@ -17,5 +17,5 @@ "skipLibCheck": true, "types": ["vite/client", "node"] }, - "include": ["src", "e2e", "a11y", "vite.config.ts", "vitest.e2e.config.ts", "vitest.a11y.config.ts", "eslint.config.js"] + "include": ["src", "e2e", "a11y", "vite.config.ts", "vitest.workers.ts", "vitest.workers.test.ts","vitest.e2e.config.ts", "vitest.a11y.config.ts", "eslint.config.js"] } diff --git a/src/Ui/vite.config.ts b/src/Ui/vite.config.ts index e8b62082..438cbb27 100644 --- a/src/Ui/vite.config.ts +++ b/src/Ui/vite.config.ts @@ -4,6 +4,9 @@ import { join } from 'node:path'; import type { Plugin } from 'vite'; import { defineConfig } from 'vitest/config'; import react from '@vitejs/plugin-react'; +import { resolveMaxWorkers } from './vitest.workers.ts'; + +const maxWorkers = resolveMaxWorkers(process.env); const devHostPort = process.env.TOMESTACK_DEV_PORT ?? '5178'; const devDataDir = @@ -43,7 +46,8 @@ function contentSecurityPolicy(): Plugin { export default defineConfig({ plugins: [react(), contentSecurityPolicy()], base: './', - test: { setupFiles: ['src/test/setup.ts'] }, + // Capped locally because an uncapped run on a 24-thread machine saturates the CPU and flakes timing tests. + test: { setupFiles: ['src/test/setup.ts'], ...(maxWorkers === undefined ? {} : { maxWorkers }) }, build: { outDir: 'dist', emptyOutDir: true, sourcemap: false }, server: { host: '127.0.0.1', diff --git a/src/Ui/vitest.workers.test.ts b/src/Ui/vitest.workers.test.ts new file mode 100644 index 00000000..de26abdc --- /dev/null +++ b/src/Ui/vitest.workers.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; +import { LOCAL_MAX_WORKERS, resolveMaxWorkers } from './vitest.workers'; + +describe('resolveMaxWorkers', () => { + it('caps local runs', () => { + expect(LOCAL_MAX_WORKERS).toBe(8); + expect(resolveMaxWorkers({})).toBe(8); + }); + + it('leaves the Vitest default on CI', () => { + expect(resolveMaxWorkers({ CI: 'true' })).toBeUndefined(); + expect(resolveMaxWorkers({ CI: '1' })).toBeUndefined(); + }); + + it('treats CI=false or empty as not CI', () => { + expect(resolveMaxWorkers({ CI: 'false' })).toBe(8); + expect(resolveMaxWorkers({ CI: 'FALSE' })).toBe(8); + expect(resolveMaxWorkers({ CI: '' })).toBe(8); + }); + + it('honours a positive integer override, even on CI', () => { + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '4' })).toBe(4); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: '3' })).toBe(3); + }); + + it.each(['abc', '0', '-3', '2.5'])('ignores the junk override %s', (junk) => { + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: junk })).toBe(8); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: junk })).toBeUndefined(); + }); +}); diff --git a/src/Ui/vitest.workers.ts b/src/Ui/vitest.workers.ts new file mode 100644 index 00000000..dc3b1f47 --- /dev/null +++ b/src/Ui/vitest.workers.ts @@ -0,0 +1,17 @@ +/** Local cap on Vitest workers; an uncapped run on a many-thread machine saturates the CPU and flakes timing tests. */ +export const LOCAL_MAX_WORKERS = 8; + +/** + * Worker count for Vitest: a positive-integer TOMESTACK_TEST_WORKERS wins; on CI (set, non-empty, not "false") + * returns undefined so Vitest keeps its default; otherwise the local cap. + */ +export function resolveMaxWorkers(env: Record): number | undefined { + const override = env.TOMESTACK_TEST_WORKERS; + if (override !== undefined && /^\d+$/.test(override)) { + const n = Number.parseInt(override, 10); + if (n > 0) return n; + } + const ci = env.CI; + if (ci !== undefined && ci !== '' && ci.toLowerCase() !== 'false') return undefined; + return LOCAL_MAX_WORKERS; +} diff --git a/tests/xunit.runner.json b/tests/xunit.runner.json new file mode 100644 index 00000000..ef9db13f --- /dev/null +++ b/tests/xunit.runner.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://xunit.net/schema/current/xunit.runner.schema.json", + "maxParallelThreads": 8 +} From 8e2c76390abf68a3e9183908204ea41b4ae07182 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:24:08 -0600 Subject: [PATCH 2/9] Keep test caps from raising parallelism: Vitest cap never exceeds the core count; xUnit cap only applies locally on machines with more than 8 cores --- Directory.Build.props | 6 ++++-- src/Ui/vitest.workers.test.ts | 30 +++++++++++++++++++----------- src/Ui/vitest.workers.ts | 11 ++++++++--- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 2d9e2ae3..5751becf 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -86,8 +86,10 @@ $(NoWarn);CA1859 - - + + diff --git a/src/Ui/vitest.workers.test.ts b/src/Ui/vitest.workers.test.ts index de26abdc..67ad28f9 100644 --- a/src/Ui/vitest.workers.test.ts +++ b/src/Ui/vitest.workers.test.ts @@ -1,30 +1,38 @@ import { describe, expect, it } from 'vitest'; import { LOCAL_MAX_WORKERS, resolveMaxWorkers } from './vitest.workers'; +const MANY = 24; + describe('resolveMaxWorkers', () => { it('caps local runs', () => { expect(LOCAL_MAX_WORKERS).toBe(8); - expect(resolveMaxWorkers({})).toBe(8); + expect(resolveMaxWorkers({}, MANY)).toBe(8); + }); + + it('never raises workers above the core count', () => { + expect(resolveMaxWorkers({}, 4)).toBe(4); + expect(resolveMaxWorkers({}, 1)).toBe(1); }); it('leaves the Vitest default on CI', () => { - expect(resolveMaxWorkers({ CI: 'true' })).toBeUndefined(); - expect(resolveMaxWorkers({ CI: '1' })).toBeUndefined(); + expect(resolveMaxWorkers({ CI: 'true' }, MANY)).toBeUndefined(); + expect(resolveMaxWorkers({ CI: '1' }, MANY)).toBeUndefined(); }); it('treats CI=false or empty as not CI', () => { - expect(resolveMaxWorkers({ CI: 'false' })).toBe(8); - expect(resolveMaxWorkers({ CI: 'FALSE' })).toBe(8); - expect(resolveMaxWorkers({ CI: '' })).toBe(8); + expect(resolveMaxWorkers({ CI: 'false' }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: 'FALSE' }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: '' }, MANY)).toBe(8); }); - it('honours a positive integer override, even on CI', () => { - expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '4' })).toBe(4); - expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: '3' })).toBe(3); + it('honours a positive integer override, even on CI or above the core count', () => { + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '4' }, MANY)).toBe(4); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: '3' }, MANY)).toBe(3); + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: '12' }, 4)).toBe(12); }); it.each(['abc', '0', '-3', '2.5'])('ignores the junk override %s', (junk) => { - expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: junk })).toBe(8); - expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: junk })).toBeUndefined(); + expect(resolveMaxWorkers({ TOMESTACK_TEST_WORKERS: junk }, MANY)).toBe(8); + expect(resolveMaxWorkers({ CI: 'true', TOMESTACK_TEST_WORKERS: junk }, MANY)).toBeUndefined(); }); }); diff --git a/src/Ui/vitest.workers.ts b/src/Ui/vitest.workers.ts index dc3b1f47..be893ee5 100644 --- a/src/Ui/vitest.workers.ts +++ b/src/Ui/vitest.workers.ts @@ -1,11 +1,16 @@ +import { availableParallelism } from 'node:os'; + /** Local cap on Vitest workers; an uncapped run on a many-thread machine saturates the CPU and flakes timing tests. */ export const LOCAL_MAX_WORKERS = 8; /** * Worker count for Vitest: a positive-integer TOMESTACK_TEST_WORKERS wins; on CI (set, non-empty, not "false") - * returns undefined so Vitest keeps its default; otherwise the local cap. + * returns undefined so Vitest keeps its default; otherwise the local cap, never above the core count. */ -export function resolveMaxWorkers(env: Record): number | undefined { +export function resolveMaxWorkers( + env: Record, + cores: number = availableParallelism(), +): number | undefined { const override = env.TOMESTACK_TEST_WORKERS; if (override !== undefined && /^\d+$/.test(override)) { const n = Number.parseInt(override, 10); @@ -13,5 +18,5 @@ export function resolveMaxWorkers(env: Record): numb } const ci = env.CI; if (ci !== undefined && ci !== '' && ci.toLowerCase() !== 'false') return undefined; - return LOCAL_MAX_WORKERS; + return Math.min(LOCAL_MAX_WORKERS, Math.max(1, cores)); } From 84c43079890f1ec86e06ac3b33e1b8c97b8dd705 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:25:37 -0600 Subject: [PATCH 3/9] Add scripts/gate.ps1: ordered gate with logs, summary, e2e watchdog --- scripts/gate.ps1 | 195 ++++++++++++++++++++++ tests/AppService.Tests/GateScriptTests.cs | 146 ++++++++++++++++ 2 files changed, 341 insertions(+) create mode 100644 scripts/gate.ps1 create mode 100644 tests/AppService.Tests/GateScriptTests.cs diff --git a/scripts/gate.ps1 b/scripts/gate.ps1 new file mode 100644 index 00000000..7bca3bf8 --- /dev/null +++ b/scripts/gate.ps1 @@ -0,0 +1,195 @@ +<# +.SYNOPSIS +Runs the TomeStack gate steps 1-7 (CONTRIBUTING.md, "The gate") in order, with logs, a summary and an e2e watchdog. + +.DESCRIPTION +Optional helper: the commands in CONTRIBUTING.md stay authoritative. Runs on Windows PowerShell 5.1. +Step ids, in order: npm-ci, lint, ui-test, ui-build, dotnet-build, dotnet-test, e2e. +The run stops at the first failing step; the summary is still printed and written to \summary.txt. +Exit codes: 0 all passed, the failing step's exit code, 124 watchdog timeout (e2e), 2 bad arguments or a CPU check failure under -RequireQuiet. + +.PARAMETER From +Start at this step id and run the later steps. +.PARAMETER Only +Run only these step ids (comma separated). +.PARAMETER LogDir +Where the per-step logs and summary.txt go. Default: a time-stamped folder under the temp directory. +.PARAMETER E2eTimeoutMinutes +Watchdog for the e2e step only; the whole process tree is killed on expiry. +.PARAMETER UiWorkers +Sets TOMESTACK_TEST_WORKERS for the children when greater than 0. +.PARAMETER XunitThreads +Adds "-- xUnit.MaxParallelThreads=" to dotnet test when greater than 0. +.PARAMETER ProjectParallelism +Adds "-m:" to dotnet test when greater than 0. +.PARAMETER LowPriority +Starts each step at BelowNormal priority. +.PARAMETER CpuWarnPercent +Warn (or fail under -RequireQuiet) when the average CPU load before the run is at or above this percentage. +.PARAMETER StepsJson +Tests only: a JSON array of {id, exe, args} that replaces the built-in step table. +#> +[CmdletBinding()] +param( + [string]$From, + [string[]]$Only, + [string]$LogDir = (Join-Path (Join-Path $env:TEMP 'tomestack-gate') (Get-Date -Format 'yyyyMMdd-HHmmss')), + [double]$E2eTimeoutMinutes = 15, + [int]$UiWorkers, + [int]$XunitThreads, + [int]$ProjectParallelism, + [switch]$LowPriority, + [int]$CpuWarnPercent = 25, + [switch]$RequireQuiet, + [switch]$SkipCpuCheck, + [switch]$DryRun, + [string]$StepsJson +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot + +# --- Step table --- +if ($StepsJson) { + # The parentheses make Windows PowerShell 5.1 enumerate the parsed array instead of passing it on as one object. + $steps = @((ConvertFrom-Json -InputObject $StepsJson) | ForEach-Object { + [pscustomobject]@{ id = [string]$_.id; exe = [string]$_.exe; args = @($_.args | ForEach-Object { [string]$_ }) } + }) +} +else { + $testArgs = @('test', 'TomeStack.slnx', '-c', 'Release') + if ($ProjectParallelism -gt 0) { $testArgs += "-m:$ProjectParallelism" } + if ($XunitThreads -gt 0) { $testArgs += @('--', "xUnit.MaxParallelThreads=$XunitThreads") } + $steps = @( + [pscustomobject]@{ id = 'npm-ci'; exe = 'npm.cmd'; args = @('ci', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'lint'; exe = 'npm.cmd'; args = @('run', 'lint', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'ui-test'; exe = 'npm.cmd'; args = @('test', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'ui-build'; exe = 'npm.cmd'; args = @('run', 'build', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'dotnet-build'; exe = 'dotnet'; args = @('build', 'TomeStack.slnx', '-c', 'Release') }, + [pscustomobject]@{ id = 'dotnet-test'; exe = 'dotnet'; args = $testArgs }, + [pscustomobject]@{ id = 'e2e'; exe = 'npm.cmd'; args = @('run', 'test:e2e', '--prefix', 'src/Ui') } + ) +} +$validIds = @($steps | ForEach-Object { $_.id }) + +# --- Select steps --- +$onlyIds = @() +foreach ($o in @($Only)) { if ($o) { $onlyIds += ($o -split ',') | Where-Object { $_ } } } +$bad = @() +if ($From -and ($validIds -notcontains $From)) { $bad += $From } +foreach ($o in $onlyIds) { if ($validIds -notcontains $o) { $bad += $o } } +if ($bad.Count -gt 0) { + Write-Host ("Unknown step id: {0}. Valid ids: {1}" -f ($bad -join ', '), ($validIds -join ', ')) + exit 2 +} +$selected = @($steps) +if ($From) { + $index = [array]::IndexOf($validIds, $From) + $selected = @($steps | Select-Object -Skip $index) +} +if ($onlyIds.Count -gt 0) { $selected = @($selected | Where-Object { $onlyIds -contains $_.id }) } + +function Format-Arg([string]$a) { + if ($a -match '[\s"]') { return '"' + ($a -replace '"', '\"') + '"' } + return $a +} + +if ($DryRun) { + # The CPU check below still runs under -DryRun so that -RequireQuiet can be exercised. + foreach ($s in $selected) { Write-Host ("{0}: {1} {2}" -f $s.id, $s.exe, (($s.args | ForEach-Object { Format-Arg $_ }) -join ' ')) } +} + +# --- CPU check --- +if (-not $SkipCpuCheck) { + try { + $counter = '\Processor(_Total)\% Processor Time' + $samples = Get-Counter -Counter $counter -SampleInterval 1 -MaxSamples 3 + $average = ($samples | ForEach-Object { $_.CounterSamples[0].CookedValue } | Measure-Object -Average).Average + $line = 'Average {0} was {1:N0}% over 3 s (threshold {2}%).' -f $counter, $average, $CpuWarnPercent + if ($average -ge $CpuWarnPercent) { + if ($RequireQuiet) { Write-Host "Machine is not quiet. $line"; exit 2 } + Write-Warning "Machine is busy; timings and flakes may not be representative. $line" + } + else { Write-Host $line } + } + catch { + if ($RequireQuiet) { Write-Host 'CPU check unavailable and -RequireQuiet was given.'; exit 2 } + Write-Warning 'CPU check unavailable.' + } +} + +if ($DryRun) { exit 0 } + +# --- Helpers --- +function Stop-DevHost { + # The e2e harness runs `dotnet \src\DevHost\bin\...\TomeStack.DevHost.dll`; an apphost TomeStack.DevHost.exe is covered too. + # Only processes belonging to this repo root are touched. + $count = 0 + try { + $devHostDir = Join-Path $repoRoot 'src\DevHost' + $found = Get-CimInstance Win32_Process | Where-Object { + ($_.Name -like 'TomeStack.DevHost*.exe' -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($repoRoot, [StringComparison]::OrdinalIgnoreCase)) -or + ($_.Name -ieq 'dotnet.exe' -and $_.CommandLine -and $_.CommandLine.IndexOf($devHostDir, [StringComparison]::OrdinalIgnoreCase) -ge 0 -and $_.CommandLine -like '*TomeStack.DevHost*') + } + foreach ($p in $found) { + Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue + $count++ + } + } + catch { Write-Warning 'DevHost cleanup unavailable.' } + Write-Host "DevHost cleanup: stopped $count process(es)." +} + +New-Item -ItemType Directory -Force -Path $LogDir | Out-Null +if ($UiWorkers -gt 0) { $env:TOMESTACK_TEST_WORKERS = [string]$UiWorkers } + +$results = @() +$exitCode = 0 +Stop-DevHost +try { + foreach ($s in $selected) { + Write-Host ("[{0}] {1} {2}" -f $s.id, $s.exe, (($s.args | ForEach-Object { Format-Arg $_ }) -join ' ')) + $clock = [Diagnostics.Stopwatch]::StartNew() + $startArgs = @{ + FilePath = $s.exe + PassThru = $true + NoNewWindow = $true + WorkingDirectory = $repoRoot + RedirectStandardOutput = (Join-Path $LogDir ($s.id + '.log')) + RedirectStandardError = (Join-Path $LogDir ($s.id + '.err.log')) + } + if ($s.args.Count -gt 0) { $startArgs.ArgumentList = @($s.args | ForEach-Object { Format-Arg $_ }) } + $proc = Start-Process @startArgs + $null = $proc.Handle # keeps the handle so ExitCode is readable (PS 5.1) + if ($LowPriority) { try { $proc.PriorityClass = 'BelowNormal' } catch { Write-Warning 'Could not lower priority.' } } + + $code = 0 + $note = '' + if ($s.id -eq 'e2e') { + if (-not $proc.WaitForExit([int]($E2eTimeoutMinutes * 60000))) { + & taskkill.exe /T /F /PID $proc.Id 2>&1 | Out-Null + $proc.WaitForExit() + $code = 124 + $note = 'timed out' + Write-Host ("[{0}] timed out after {1} min; process tree killed." -f $s.id, $E2eTimeoutMinutes) + } + else { $code = $proc.ExitCode } + } + else { + $proc.WaitForExit() + $code = $proc.ExitCode + } + $clock.Stop() + $results += [pscustomobject]@{ id = $s.id; exit = $code; seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); note = $note } + if ($code -ne 0) { $exitCode = $code; break } + } +} +finally { + Stop-DevHost + $lines = @('{0,-14} {1,5} {2,9} {3}' -f 'id', 'exit', 'seconds', '') + foreach ($r in $results) { $lines += ('{0,-14} {1,5} {2,9} {3}' -f $r.id, $r.exit, $r.seconds, $r.note) } + $lines | ForEach-Object { Write-Host $_ } + $lines | Out-File -FilePath (Join-Path $LogDir 'summary.txt') -Encoding ascii + Write-Host "Logs: $LogDir" +} +exit $exitCode diff --git a/tests/AppService.Tests/GateScriptTests.cs b/tests/AppService.Tests/GateScriptTests.cs new file mode 100644 index 00000000..4ab26dbc --- /dev/null +++ b/tests/AppService.Tests/GateScriptTests.cs @@ -0,0 +1,146 @@ +using System.Diagnostics; +using System.Text.Json; + +namespace TomeStack.AppService.Tests; + +/// +/// Runs scripts/gate.ps1 under Windows PowerShell with -DryRun or a -StepsJson table (never the real gate) and checks +/// step selection, the stop-on-failure summary, the e2e watchdog and the -RequireQuiet CPU check. +/// +public sealed class GateScriptTests +{ + private static string RepoRoot + { + get + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "TomeStack.slnx"))) + directory = directory.Parent; + return directory?.FullName ?? throw new InvalidOperationException("TomeStack.slnx not found above the test output folder."); + } + } + + /// Runs the script with a temporary -LogDir and returns its exit code, output, elapsed time and the log folder (deleted after ). + private static (int ExitCode, string Output, TimeSpan Elapsed) Run(Action? inspect, params string[] scriptArguments) + { + var logDir = Path.Combine(Path.GetTempPath(), "ts-gate-" + Guid.NewGuid().ToString("N")); + try + { + var start = new ProcessStartInfo("powershell") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + foreach (var arg in new[] { "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", Path.Combine(RepoRoot, "scripts", "gate.ps1"), "-LogDir", logDir }) + start.ArgumentList.Add(arg); + foreach (var arg in scriptArguments) + start.ArgumentList.Add(arg); + + var clock = Stopwatch.StartNew(); + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(120_000)) + { + process.Kill(entireProcessTree: true); + Assert.Fail("gate.ps1 did not finish within 120 s."); + } + clock.Stop(); + inspect?.Invoke(logDir); + return (process.ExitCode, stdout.Result + stderr.Result, clock.Elapsed); + } + finally + { + if (Directory.Exists(logDir)) + Directory.Delete(logDir, recursive: true); + } + } + + private static string Steps(params (string Id, string Command)[] steps) => + JsonSerializer.Serialize(steps.Select(s => new { id = s.Id, exe = "powershell", args = new[] { "-NoProfile", "-Command", s.Command } })); + + [Fact] + public void Dry_run_lists_the_seven_steps_in_order() + { + var (exitCode, output, _) = Run(null, "-DryRun", "-SkipCpuCheck"); + + Assert.Equal(0, exitCode); + var position = -1; + foreach (var id in new[] { "npm-ci", "lint", "ui-test", "ui-build", "dotnet-build", "dotnet-test", "e2e" }) + { + var next = output.IndexOf(id, position + 1, StringComparison.Ordinal); + Assert.True(next > position, $"Step '{id}' is missing or out of order in:\n{output}"); + position = next; + } + } + + [Fact] + public void From_skips_earlier_steps() + { + var (exitCode, output, _) = Run(null, "-DryRun", "-SkipCpuCheck", "-From", "dotnet-test"); + + Assert.Equal(0, exitCode); + Assert.Contains("dotnet-test", output); + Assert.Contains("e2e", output); + Assert.DoesNotContain("ui-test", output); + } + + [Fact] + public void Unknown_step_id_fails_fast() + { + var (exitCode, output, _) = Run(null, "-SkipCpuCheck", "-Only", "nope"); + + Assert.Equal(2, exitCode); + Assert.Contains("npm-ci", output); + } + + [Fact] + public void Failing_step_stops_the_run_and_writes_summary() + { + var marker = Path.Combine(Path.GetTempPath(), "ts-gate-marker-" + Guid.NewGuid().ToString("N")); + string summary = ""; + var logExists = false; + try + { + var (exitCode, _, _) = Run( + logDir => + { + summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")); + logExists = File.Exists(Path.Combine(logDir, "a.log")); + }, + "-SkipCpuCheck", "-StepsJson", Steps(("a", "exit 0"), ("b", "exit 3"), ("c", $"Set-Content -LiteralPath '{marker}' -Value x"))); + + Assert.Equal(3, exitCode); + Assert.False(File.Exists(marker), "Step c ran after step b failed."); + Assert.Contains("a", summary); + Assert.Contains("b", summary); + Assert.Contains("3", summary); + Assert.True(logExists); + } + finally + { + File.Delete(marker); + } + } + + [Fact] + public void Hung_e2e_is_killed_by_the_watchdog() + { + var (exitCode, output, elapsed) = Run(null, "-SkipCpuCheck", "-E2eTimeoutMinutes", "0.05", "-StepsJson", Steps(("e2e", "Start-Sleep 60"))); + + Assert.Equal(124, exitCode); + Assert.Contains("timed out", output); + Assert.True(elapsed < TimeSpan.FromSeconds(30), $"Took {elapsed.TotalSeconds:N0} s."); + } + + [Fact] + public void Require_quiet_fails_when_over_threshold() + { + var (exitCode, output, _) = Run(null, "-CpuWarnPercent", "0", "-RequireQuiet", "-DryRun"); + + Assert.Equal(2, exitCode); + Assert.Contains("% Processor Time", output); + } +} From 51cb53a93ed8d7b77c8da9f75675bf8158c28aca Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:27:52 -0600 Subject: [PATCH 4/9] gate.ps1: add the a11y step and watchdog it with e2e --- scripts/gate.ps1 | 23 +++++++++++++---------- tests/AppService.Tests/GateScriptTests.cs | 13 ++++++++----- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/scripts/gate.ps1 b/scripts/gate.ps1 index 7bca3bf8..0b9af324 100644 --- a/scripts/gate.ps1 +++ b/scripts/gate.ps1 @@ -1,12 +1,13 @@ <# .SYNOPSIS -Runs the TomeStack gate steps 1-7 (CONTRIBUTING.md, "The gate") in order, with logs, a summary and an e2e watchdog. +Runs the TomeStack gate steps 1-8 (CONTRIBUTING.md, "The gate") in order, with logs, a summary and a watchdog on the DevHost steps. .DESCRIPTION Optional helper: the commands in CONTRIBUTING.md stay authoritative. Runs on Windows PowerShell 5.1. -Step ids, in order: npm-ci, lint, ui-test, ui-build, dotnet-build, dotnet-test, e2e. +Step ids, in order: npm-ci, lint, ui-test, ui-build, dotnet-build, dotnet-test, e2e, a11y. +The GUI steps (scripts/smoke.ps1 and scripts/single-instance-check.ps1) need the built desktop exe and are left to the owner; they are not in this table. The run stops at the first failing step; the summary is still printed and written to \summary.txt. -Exit codes: 0 all passed, the failing step's exit code, 124 watchdog timeout (e2e), 2 bad arguments or a CPU check failure under -RequireQuiet. +Exit codes: 0 all passed, the failing step's exit code, 124 watchdog timeout (e2e or a11y), 2 bad arguments or a CPU check failure under -RequireQuiet. .PARAMETER From Start at this step id and run the later steps. @@ -14,8 +15,8 @@ Start at this step id and run the later steps. Run only these step ids (comma separated). .PARAMETER LogDir Where the per-step logs and summary.txt go. Default: a time-stamped folder under the temp directory. -.PARAMETER E2eTimeoutMinutes -Watchdog for the e2e step only; the whole process tree is killed on expiry. +.PARAMETER DevHostStepTimeoutMinutes +Watchdog for the e2e and a11y steps (both use the DevHost); the whole process tree is killed on expiry. Old name: -E2eTimeoutMinutes. .PARAMETER UiWorkers Sets TOMESTACK_TEST_WORKERS for the children when greater than 0. .PARAMETER XunitThreads @@ -34,7 +35,8 @@ param( [string]$From, [string[]]$Only, [string]$LogDir = (Join-Path (Join-Path $env:TEMP 'tomestack-gate') (Get-Date -Format 'yyyyMMdd-HHmmss')), - [double]$E2eTimeoutMinutes = 15, + [Alias('E2eTimeoutMinutes')] + [double]$DevHostStepTimeoutMinutes = 15, [int]$UiWorkers, [int]$XunitThreads, [int]$ProjectParallelism, @@ -67,7 +69,8 @@ else { [pscustomobject]@{ id = 'ui-build'; exe = 'npm.cmd'; args = @('run', 'build', '--prefix', 'src/Ui') }, [pscustomobject]@{ id = 'dotnet-build'; exe = 'dotnet'; args = @('build', 'TomeStack.slnx', '-c', 'Release') }, [pscustomobject]@{ id = 'dotnet-test'; exe = 'dotnet'; args = $testArgs }, - [pscustomobject]@{ id = 'e2e'; exe = 'npm.cmd'; args = @('run', 'test:e2e', '--prefix', 'src/Ui') } + [pscustomobject]@{ id = 'e2e'; exe = 'npm.cmd'; args = @('run', 'test:e2e', '--prefix', 'src/Ui') }, + [pscustomobject]@{ id = 'a11y'; exe = 'npm.cmd'; args = @('run', 'test:a11y', '--prefix', 'src/Ui') } ) } $validIds = @($steps | ForEach-Object { $_.id }) @@ -165,13 +168,13 @@ try { $code = 0 $note = '' - if ($s.id -eq 'e2e') { - if (-not $proc.WaitForExit([int]($E2eTimeoutMinutes * 60000))) { + if ($s.id -eq 'e2e' -or $s.id -eq 'a11y') { + if (-not $proc.WaitForExit([int]($DevHostStepTimeoutMinutes * 60000))) { & taskkill.exe /T /F /PID $proc.Id 2>&1 | Out-Null $proc.WaitForExit() $code = 124 $note = 'timed out' - Write-Host ("[{0}] timed out after {1} min; process tree killed." -f $s.id, $E2eTimeoutMinutes) + Write-Host ("[{0}] timed out after {1} min; process tree killed." -f $s.id, $DevHostStepTimeoutMinutes) } else { $code = $proc.ExitCode } } diff --git a/tests/AppService.Tests/GateScriptTests.cs b/tests/AppService.Tests/GateScriptTests.cs index 4ab26dbc..83657c8e 100644 --- a/tests/AppService.Tests/GateScriptTests.cs +++ b/tests/AppService.Tests/GateScriptTests.cs @@ -62,13 +62,13 @@ private static string Steps(params (string Id, string Command)[] steps) => JsonSerializer.Serialize(steps.Select(s => new { id = s.Id, exe = "powershell", args = new[] { "-NoProfile", "-Command", s.Command } })); [Fact] - public void Dry_run_lists_the_seven_steps_in_order() + public void Dry_run_lists_the_eight_steps_in_order() { var (exitCode, output, _) = Run(null, "-DryRun", "-SkipCpuCheck"); Assert.Equal(0, exitCode); var position = -1; - foreach (var id in new[] { "npm-ci", "lint", "ui-test", "ui-build", "dotnet-build", "dotnet-test", "e2e" }) + foreach (var id in new[] { "npm-ci", "lint", "ui-test", "ui-build", "dotnet-build", "dotnet-test", "e2e", "a11y" }) { var next = output.IndexOf(id, position + 1, StringComparison.Ordinal); Assert.True(next > position, $"Step '{id}' is missing or out of order in:\n{output}"); @@ -84,6 +84,7 @@ public void From_skips_earlier_steps() Assert.Equal(0, exitCode); Assert.Contains("dotnet-test", output); Assert.Contains("e2e", output); + Assert.Contains("a11y", output); Assert.DoesNotContain("ui-test", output); } @@ -125,10 +126,12 @@ public void Failing_step_stops_the_run_and_writes_summary() } } - [Fact] - public void Hung_e2e_is_killed_by_the_watchdog() + [Theory] + [InlineData("e2e")] + [InlineData("a11y")] + public void Hung_devhost_step_is_killed_by_the_watchdog(string id) { - var (exitCode, output, elapsed) = Run(null, "-SkipCpuCheck", "-E2eTimeoutMinutes", "0.05", "-StepsJson", Steps(("e2e", "Start-Sleep 60"))); + var (exitCode, output, elapsed) = Run(null, "-SkipCpuCheck", "-DevHostStepTimeoutMinutes", "0.05", "-StepsJson", Steps((id, "Start-Sleep 60"))); Assert.Equal(124, exitCode); Assert.Contains("timed out", output); From c804b790c251dcda169334dc418740338581e631 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:31:21 -0600 Subject: [PATCH 5/9] gate.ps1: anchor DevHost cleanup, skip it under -StepsJson, summary on every exit path --- scripts/gate.ps1 | 102 +++++++++++++++------- tests/AppService.Tests/GateScriptTests.cs | 31 ++++++- 2 files changed, 99 insertions(+), 34 deletions(-) diff --git a/scripts/gate.ps1 b/scripts/gate.ps1 index 0b9af324..004d502d 100644 --- a/scripts/gate.ps1 +++ b/scripts/gate.ps1 @@ -45,11 +45,64 @@ param( [switch]$RequireQuiet, [switch]$SkipCpuCheck, [switch]$DryRun, - [string]$StepsJson + [switch]$SkipDevHostCleanup, + [string]$StepsJson, + [string]$SelfTestMatch ) $ErrorActionPreference = 'Stop' $repoRoot = Split-Path -Parent $PSScriptRoot +# -StepsJson (tests) never touches real processes, so it implies -SkipDevHostCleanup. +$skipCleanup = $SkipDevHostCleanup -or [bool]$StepsJson + +# --- Helpers --- +function Format-Arg([string]$a) { + if ($a.Length -eq 0) { return '""' } + if ($a -notmatch '[\s"]') { return $a } + $q = $a -replace '(\\*)"', '$1$1\"' # backslashes before a quote are doubled, then the quote is escaped + $q = $q -replace '(\\+)$', '$1$1' # trailing backslashes are doubled so they do not escape the closing quote + return '"' + $q + '"' +} + +function Test-RepoDevHost([string]$Name, [string]$ExecutablePath, [string]$CommandLine, [string]$Root) { + # The e2e/a11y harness runs `dotnet \src\DevHost\bin\...\TomeStack.DevHost.dll`; an apphost TomeStack.DevHost.exe is covered too. + # Both matches are anchored on the repo root plus a trailing backslash, so a sibling folder such as 2 never matches. + $prefix = $Root.TrimEnd('\') + '\' + if ($Name -like 'TomeStack.DevHost*.exe' -and $ExecutablePath -and $ExecutablePath.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { return $true } + if ($Name -ieq 'dotnet.exe' -and $CommandLine -and + $CommandLine.IndexOf($prefix + 'src\DevHost\', [StringComparison]::OrdinalIgnoreCase) -ge 0 -and + $CommandLine.IndexOf('TomeStack.DevHost', [StringComparison]::OrdinalIgnoreCase) -ge 0) { return $true } + return $false +} + +function Stop-DevHost { + if ($skipCleanup) { return } + $count = 0 + try { + $found = Get-CimInstance Win32_Process | Where-Object { Test-RepoDevHost $_.Name $_.ExecutablePath $_.CommandLine $repoRoot } + foreach ($p in $found) { + try { Stop-Process -Id $p.ProcessId -Force -ErrorAction Stop; $count++ } catch { } + } + } + catch { Write-Warning 'DevHost cleanup unavailable.' } + Write-Host "DevHost cleanup: stopped $count process(es)." +} + +function Write-EarlySummary([string]$Reason) { + # Bad arguments and a failed CPU check end the run before any step; the reason still goes to summary.txt. + try { + New-Item -ItemType Directory -Force -Path $LogDir | Out-Null + $Reason | Out-File -FilePath (Join-Path $LogDir 'summary.txt') -Encoding ascii + } + catch { Write-Warning 'Could not write summary.txt.' } +} + +if ($SelfTestMatch) { + # Tests only: {name, exe, cmd, root} -> prints "match: True|False" without looking at any real process. + $probe = ConvertFrom-Json -InputObject $SelfTestMatch + Write-Host ('match: {0}' -f (Test-RepoDevHost ([string]$probe.name) ([string]$probe.exe) ([string]$probe.cmd) ([string]$probe.root))) + exit 0 +} # --- Step table --- if ($StepsJson) { @@ -82,7 +135,9 @@ $bad = @() if ($From -and ($validIds -notcontains $From)) { $bad += $From } foreach ($o in $onlyIds) { if ($validIds -notcontains $o) { $bad += $o } } if ($bad.Count -gt 0) { - Write-Host ("Unknown step id: {0}. Valid ids: {1}" -f ($bad -join ', '), ($validIds -join ', ')) + $reason = "Unknown step id: {0}. Valid ids: {1}" -f ($bad -join ', '), ($validIds -join ', ') + Write-Host $reason + Write-EarlySummary $reason exit 2 } $selected = @($steps) @@ -92,11 +147,6 @@ if ($From) { } if ($onlyIds.Count -gt 0) { $selected = @($selected | Where-Object { $onlyIds -contains $_.id }) } -function Format-Arg([string]$a) { - if ($a -match '[\s"]') { return '"' + ($a -replace '"', '\"') + '"' } - return $a -} - if ($DryRun) { # The CPU check below still runs under -DryRun so that -RequireQuiet can be exercised. foreach ($s in $selected) { Write-Host ("{0}: {1} {2}" -f $s.id, $s.exe, (($s.args | ForEach-Object { Format-Arg $_ }) -join ' ')) } @@ -110,41 +160,25 @@ if (-not $SkipCpuCheck) { $average = ($samples | ForEach-Object { $_.CounterSamples[0].CookedValue } | Measure-Object -Average).Average $line = 'Average {0} was {1:N0}% over 3 s (threshold {2}%).' -f $counter, $average, $CpuWarnPercent if ($average -ge $CpuWarnPercent) { - if ($RequireQuiet) { Write-Host "Machine is not quiet. $line"; exit 2 } + if ($RequireQuiet) { Write-Host "Machine is not quiet. $line"; Write-EarlySummary "Machine is not quiet. $line"; exit 2 } Write-Warning "Machine is busy; timings and flakes may not be representative. $line" } else { Write-Host $line } } catch { - if ($RequireQuiet) { Write-Host 'CPU check unavailable and -RequireQuiet was given.'; exit 2 } + if ($RequireQuiet) { Write-Host 'CPU check unavailable and -RequireQuiet was given.'; Write-EarlySummary 'CPU check unavailable and -RequireQuiet was given.'; exit 2 } Write-Warning 'CPU check unavailable.' } } if ($DryRun) { exit 0 } -# --- Helpers --- -function Stop-DevHost { - # The e2e harness runs `dotnet \src\DevHost\bin\...\TomeStack.DevHost.dll`; an apphost TomeStack.DevHost.exe is covered too. - # Only processes belonging to this repo root are touched. - $count = 0 - try { - $devHostDir = Join-Path $repoRoot 'src\DevHost' - $found = Get-CimInstance Win32_Process | Where-Object { - ($_.Name -like 'TomeStack.DevHost*.exe' -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($repoRoot, [StringComparison]::OrdinalIgnoreCase)) -or - ($_.Name -ieq 'dotnet.exe' -and $_.CommandLine -and $_.CommandLine.IndexOf($devHostDir, [StringComparison]::OrdinalIgnoreCase) -ge 0 -and $_.CommandLine -like '*TomeStack.DevHost*') - } - foreach ($p in $found) { - Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue - $count++ - } - } - catch { Write-Warning 'DevHost cleanup unavailable.' } - Write-Host "DevHost cleanup: stopped $count process(es)." -} - New-Item -ItemType Directory -Force -Path $LogDir | Out-Null if ($UiWorkers -gt 0) { $env:TOMESTACK_TEST_WORKERS = [string]$UiWorkers } +if ($LowPriority) { + # Lowering this process first means every step inherits BelowNormal from creation; the per-step set below is a fallback. + try { [Diagnostics.Process]::GetCurrentProcess().PriorityClass = 'BelowNormal' } catch { Write-Warning 'Could not lower priority.' } +} $results = @() $exitCode = 0 @@ -162,7 +196,14 @@ try { RedirectStandardError = (Join-Path $LogDir ($s.id + '.err.log')) } if ($s.args.Count -gt 0) { $startArgs.ArgumentList = @($s.args | ForEach-Object { Format-Arg $_ }) } - $proc = Start-Process @startArgs + try { $proc = Start-Process @startArgs } + catch { + $clock.Stop() + Write-Host ("[{0}] failed to start: {1}" -f $s.id, $_.Exception.Message) + $results += [pscustomobject]@{ id = $s.id; exit = 1; seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); note = 'failed to start' } + $exitCode = 1 + break + } $null = $proc.Handle # keeps the handle so ExitCode is readable (PS 5.1) if ($LowPriority) { try { $proc.PriorityClass = 'BelowNormal' } catch { Write-Warning 'Could not lower priority.' } } @@ -182,6 +223,7 @@ try { $proc.WaitForExit() $code = $proc.ExitCode } + if ($null -eq $code) { $code = 1 } # an unreadable exit code is a failure, not a pass $clock.Stop() $results += [pscustomobject]@{ id = $s.id; exit = $code; seconds = [math]::Round($clock.Elapsed.TotalSeconds, 1); note = $note } if ($code -ne 0) { $exitCode = $code; break } diff --git a/tests/AppService.Tests/GateScriptTests.cs b/tests/AppService.Tests/GateScriptTests.cs index 83657c8e..d10caf8b 100644 --- a/tests/AppService.Tests/GateScriptTests.cs +++ b/tests/AppService.Tests/GateScriptTests.cs @@ -91,10 +91,12 @@ public void From_skips_earlier_steps() [Fact] public void Unknown_step_id_fails_fast() { - var (exitCode, output, _) = Run(null, "-SkipCpuCheck", "-Only", "nope"); + string summary = ""; + var (exitCode, output, _) = Run(logDir => summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")), "-SkipCpuCheck", "-Only", "nope"); Assert.Equal(2, exitCode); Assert.Contains("npm-ci", output); + Assert.Contains("nope", summary); } [Fact] @@ -105,7 +107,7 @@ public void Failing_step_stops_the_run_and_writes_summary() var logExists = false; try { - var (exitCode, _, _) = Run( + var (exitCode, output, _) = Run( logDir => { summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")); @@ -119,6 +121,7 @@ public void Failing_step_stops_the_run_and_writes_summary() Assert.Contains("b", summary); Assert.Contains("3", summary); Assert.True(logExists); + Assert.DoesNotContain("DevHost cleanup", output); // -StepsJson implies -SkipDevHostCleanup: tests never touch real processes } finally { @@ -141,9 +144,29 @@ public void Hung_devhost_step_is_killed_by_the_watchdog(string id) [Fact] public void Require_quiet_fails_when_over_threshold() { - var (exitCode, output, _) = Run(null, "-CpuWarnPercent", "0", "-RequireQuiet", "-DryRun"); + string summary = ""; + var (exitCode, output, _) = Run(logDir => summary = File.ReadAllText(Path.Combine(logDir, "summary.txt")), "-CpuWarnPercent", "0", "-RequireQuiet", "-DryRun"); + // Exit 2 is the real assertion; the message depends on whether the machine has the English performance counters. Assert.Equal(2, exitCode); - Assert.Contains("% Processor Time", output); + Assert.True(output.Contains("% Processor Time", StringComparison.Ordinal) || output.Contains("CPU check unavailable", StringComparison.Ordinal), output); + Assert.False(string.IsNullOrWhiteSpace(summary)); + } + + [Theory] + [InlineData("TomeStack.DevHost.exe", @"C:\dev\ts-w4c\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.exe", "", true)] + [InlineData("TomeStack.DevHost.exe", @"C:\dev\ts-w4c2\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.exe", "", false)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.dll", true)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c2\src\DevHost\bin\Release\net10.0\TomeStack.DevHost.dll", false)] + [InlineData("dotnet.exe", @"C:\Program Files\dotnet\dotnet.exe", @"dotnet C:\dev\ts-w4c\src\DevHostTools\TomeStack.DevHost.dll", false)] + [InlineData("node.exe", @"C:\dev\ts-w4c\node.exe", @"node C:\dev\ts-w4c\src\DevHost\TomeStack.DevHost.dll", false)] + public void Devhost_match_is_anchored_on_the_repo_root(string name, string exe, string commandLine, bool expected) + { + var probe = System.Text.Json.JsonSerializer.Serialize(new { name, exe, cmd = commandLine, root = @"C:\dev\ts-w4c" }); + + var (exitCode, output, _) = Run(null, "-SelfTestMatch", probe); + + Assert.Equal(0, exitCode); + Assert.Contains(expected ? "match: True" : "match: False", output); } } From 993ff6b6490ee12f9224804705d9d9b40665b085 Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:33:30 -0600 Subject: [PATCH 6/9] gate.ps1: restore priority and TOMESTACK_TEST_WORKERS when run in an open shell --- scripts/gate.ps1 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/gate.ps1 b/scripts/gate.ps1 index 004d502d..ac25b549 100644 --- a/scripts/gate.ps1 +++ b/scripts/gate.ps1 @@ -174,6 +174,9 @@ if (-not $SkipCpuCheck) { if ($DryRun) { exit 0 } New-Item -ItemType Directory -Force -Path $LogDir | Out-Null +# Both are restored in the finally block, so running the script with & from an open shell leaves that shell as it was. +$originalWorkers = $env:TOMESTACK_TEST_WORKERS +$originalPriority = [Diagnostics.Process]::GetCurrentProcess().PriorityClass if ($UiWorkers -gt 0) { $env:TOMESTACK_TEST_WORKERS = [string]$UiWorkers } if ($LowPriority) { # Lowering this process first means every step inherits BelowNormal from creation; the per-step set below is a fallback. @@ -231,6 +234,8 @@ try { } finally { Stop-DevHost + $env:TOMESTACK_TEST_WORKERS = $originalWorkers + if ($LowPriority) { try { [Diagnostics.Process]::GetCurrentProcess().PriorityClass = $originalPriority } catch { Write-Warning 'Could not restore priority.' } } $lines = @('{0,-14} {1,5} {2,9} {3}' -f 'id', 'exit', 'seconds', '') foreach ($r in $results) { $lines += ('{0,-14} {1,5} {2,9} {3}' -f $r.id, $r.exit, $r.seconds, $r.note) } $lines | ForEach-Object { Write-Host $_ } From 28053cdeb3f8387fa9116ca5fc1637d3ae04d77e Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:33:58 -0600 Subject: [PATCH 7/9] Document the test load caps and scripts/gate.ps1 --- CONTRIBUTING.md | 4 ++++ docs/CHANGELOG.md | 1 + 2 files changed, 5 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3559626..1a5dc6e5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,10 @@ scripts/smoke.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.ex scripts/single-instance-check.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.exe # two processes on one data folder (M2.1) ``` +`scripts/gate.ps1` runs steps 1–8 in this order under Windows PowerShell, with one log per step and a summary (`summary.txt`) in `-LogDir`. It stops at the first failure, kills a hung e2e or a11y run after `-DevHostStepTimeoutMinutes` (15 by default), and stops this checkout's DevHost before and after the run. `-LowPriority` runs the steps below normal priority, and a CPU check warns when the machine is already busy (`-RequireQuiet` fails instead). It is a convenience: the commands above stay the gate, and smoke and single-instance still run by hand. + +Local test runs are capped so a full run doesn't saturate a many-core machine. Vitest uses at most 8 workers (never more than the core count), and xUnit at most 8 threads per project on machines with more than 8 cores. CI keeps the defaults. Override with `TOMESTACK_TEST_WORKERS=` for Vitest, or `dotnet test ... -- xUnit.MaxParallelThreads=` (`gate.ps1 -UiWorkers`, `-XunitThreads`, `-ProjectParallelism`). + When changing a package version, run `dotnet restore TomeStack.slnx` and commit the updated `packages.lock.json` files (CI restores in locked mode). ## Invariants diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 6628228a..feb6dfa5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased ### Added +- **Development only, test load caps and a gate script:** local test runs no longer use every core. Vitest runs at most 8 workers (override with `TOMESTACK_TEST_WORKERS`), and xUnit runs at most 8 threads per test project on machines with more than 8 cores; CI keeps its defaults. `scripts/gate.ps1` runs gate steps 1–8 in order, with per-step logs, a summary, a watchdog for a hung e2e or a11y run, DevHost cleanup, an optional lower priority and a CPU check. No app change. - **Accessibility check in CI, two contrast fixes:** `npm run test:a11y` runs axe, colour contrast included, in the installed Edge against the DevHost, in light and dark, over home, each builder step and each sheet tab, plus home in each named theme. Serious and critical violations fail it, and it now runs in CI. It found two low-contrast spots, both fixed without changing any colour: the "Offline" tag in the header now sits on the page colour, and in the dark theme the sheet's status-bar buttons (Hit points, Armor Class, Initiative, Speed) now sit on the page colour instead of the browser's grey button face. - **Tests only:** the UI flow tests in `src/Ui/e2e/` are split by feature (the 69 tests of `flow.e2e.tsx` into eight files, the 13 of `forms.e2e.tsx` into two, shared helpers in `helpers.tsx`); no test changed and no file is over 800 lines. The e2e files now run one after another against the shared DevHost. No app change. - **Release assets:** each release now includes two CycloneDX software bills of materials, `tomestack-X.Y.Z-nuget.cdx.json` (the .NET packages) and `tomestack-X.Y.Z-npm.cdx.json` (the UI's npm runtime packages). They are listed in `SHA256SUMS` and attested like the installer (D101). No app change. From 2e6987434b1528c47ad41452bf1c6f1da4463e8e Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:40:15 -0600 Subject: [PATCH 8/9] CONTRIBUTING: when to use gate.ps1 -LowPriority --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1a5dc6e5..9312f42e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,7 +22,7 @@ scripts/smoke.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.ex scripts/single-instance-check.ps1 -Exe src/DesktopShell/bin/Release/net10.0-windows/TomeStack.exe # two processes on one data folder (M2.1) ``` -`scripts/gate.ps1` runs steps 1–8 in this order under Windows PowerShell, with one log per step and a summary (`summary.txt`) in `-LogDir`. It stops at the first failure, kills a hung e2e or a11y run after `-DevHostStepTimeoutMinutes` (15 by default), and stops this checkout's DevHost before and after the run. `-LowPriority` runs the steps below normal priority, and a CPU check warns when the machine is already busy (`-RequireQuiet` fails instead). It is a convenience: the commands above stay the gate, and smoke and single-instance still run by hand. +`scripts/gate.ps1` runs steps 1–8 in this order under Windows PowerShell, with one log per step and a summary (`summary.txt`) in `-LogDir`. It stops at the first failure, kills a hung e2e or a11y run after `-DevHostStepTimeoutMinutes` (15 by default), and stops this checkout's DevHost before and after the run. `-LowPriority` runs the steps below normal priority, so the gate yields to other work. Use it only when that matters more than the result, because on a busy machine the UI tests' timing checks can then flake. A CPU check warns when the machine is already busy (`-RequireQuiet` fails instead). It is a convenience: the commands above stay the gate, and smoke and single-instance still run by hand. Local test runs are capped so a full run doesn't saturate a many-core machine. Vitest uses at most 8 workers (never more than the core count), and xUnit at most 8 threads per project on machines with more than 8 cores. CI keeps the defaults. Override with `TOMESTACK_TEST_WORKERS=` for Vitest, or `dotnet test ... -- xUnit.MaxParallelThreads=` (`gate.ps1 -UiWorkers`, `-XunitThreads`, `-ProjectParallelism`). From 5319945f95001a06b59a42b2b64cc4cb94783e7e Mon Sep 17 00:00:00 2001 From: Arlo Kharod <42082766+firegiant9000@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:02:16 -0600 Subject: [PATCH 9/9] e2e: wait for the loaded species list after a rules change (the old wait passed while options were still loading) --- src/Ui/e2e/builder.e2e.tsx | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Ui/e2e/builder.e2e.tsx b/src/Ui/e2e/builder.e2e.tsx index 1c6f835a..06cfdd46 100644 --- a/src/Ui/e2e/builder.e2e.tsx +++ b/src/Ui/e2e/builder.e2e.tsx @@ -347,9 +347,13 @@ it('drops picks that do not fit when the rules family changes, in the builder an await user.click(screen.getByRole('button', { name: 'Next: class' })); await user.click(screen.getByRole('button', { name: 'Next: ability scores' })); await user.click(screen.getByRole('button', { name: 'Next: species' })); - // D31: the 5.1 species leaves the list altogether, and the pick is cleared. - await waitFor(() => expect(within(screen.getByRole('group', { name: 'Species' })).queryByRole('radio', { name: /^Half-Orc/ })).toBeNull()); - expect(within(screen.getByRole('group', { name: 'Species' })).getByRole('radio', { name: 'None' }).checked).toBe(true); + // D31: the 5.1 species leaves the list altogether, and the pick is cleared. Wait for the loaded list ("None" present): + // while the options are still loading there are no radios at all, so "no Half-Orc" alone passes too early. + await waitFor(() => { + const list = within(screen.getByRole('group', { name: 'Species' })); + expect(list.getByRole('radio', { name: 'None' }).checked).toBe(true); + expect(list.queryByRole('radio', { name: /^Half-Orc/ })).toBeNull(); + }); await user.click(screen.getByRole('button', { name: 'Cancel' })); await user.click(await screen.findByRole('button', { name: 'Discard' })); // the rules family was changed: Cancel asks first