From 58d4dea3f9ccd1d7a9554b0e89180a1ada862eb3 Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Wed, 11 Nov 2026 11:55:21 -0700 Subject: [PATCH 1/4] Add deterministic Windows validation admission Capture exact repository, provider, tool, binding, manifest, and environment identities before Windows shell validation. Enforce stale-root and environment admission, strict no-BOM child output, and semantic source line-ending normalization without changing raw evidence. RED: pwsh -NoProfile -File Tools\windows\Tests\CandidateAdmission.Tests.ps1 -> 0 passed, 5 failed because admission and source helpers were absent. GREEN: focused Pester admission and isolation run -> 50 passed, 0 failed with positive execution. REGRESSION: pwsh -NoProfile -File Tools\windows\Invoke-ValidationRunnerContract.ps1 -> complete true, 695 required, 695 passed, 2354 executed, 0 errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- .gitattributes | 4 + Tools/windows/CandidateAdmission.ps1 | 166 +++++++++++++++ Tools/windows/SourceReader.ps1 | 14 ++ .../Tests/CandidateAdmission.Tests.ps1 | 197 ++++++++++++++++++ .../Tests/ValidationIsolation.Tests.ps1 | 1 + .../Adapters/PowerShellPayload.cs | 4 +- .../ValidationRunner/Manifests/ownership.json | 12 ++ .../Adapters/RetentionBoundary.Contracts.ps1 | 4 +- .../Ownership/OwnedByteStreamCapture.cs | 22 ++ .../Ownership/OwnedFixture.cs | 4 +- .../Ownership/SuiteRegistration.cs | 26 ++- .../Ui/UiRootSourceContracts.ps1 | 9 +- .../ValidationRunner/Ui/UiSourceContracts.ps1 | 14 +- Tools/windows/validate.ps1 | 89 +++++--- 14 files changed, 512 insertions(+), 54 deletions(-) create mode 100644 Tools/windows/CandidateAdmission.ps1 create mode 100644 Tools/windows/SourceReader.ps1 create mode 100644 Tools/windows/Tests/CandidateAdmission.Tests.ps1 diff --git a/.gitattributes b/.gitattributes index d5ad9d3ca..1511f2fed 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,9 @@ *.swift text eol=lf *.sh text eol=lf +*.ps1 text eol=lf +*.psm1 text eol=lf +*.cs text eol=lf +*.zig text eol=lf investigation/macos-parity-evidence/evidence/*.png filter=lfs diff=lfs merge=lfs -text investigation/visual-baseline/rendered-macos/*.png filter=lfs diff=lfs merge=lfs -text investigation/visual-baseline/rendered-windows/*.png filter=lfs diff=lfs merge=lfs -text diff --git a/Tools/windows/CandidateAdmission.ps1 b/Tools/windows/CandidateAdmission.ps1 new file mode 100644 index 000000000..81fd0a111 --- /dev/null +++ b/Tools/windows/CandidateAdmission.ps1 @@ -0,0 +1,166 @@ +. (Join-Path $PSScriptRoot "SourceReader.ps1") + +function Invoke-CandidateAdmissionGit([string] $Repository, [string[]] $Arguments) { + $output = @(& git -C $Repository @Arguments 2>&1) + if ($LASTEXITCODE -ne 0) { + throw "Candidate admission git -C '$Repository' $($Arguments -join ' ') failed: $($output -join '; ')" + } + return $output +} + +function Get-CandidateAdmissionFileRecord([string] $Kind, [string] $Path, [string] $RelativeRoot) { + $fullPath = [IO.Path]::GetFullPath($Path) + if (-not (Test-Path -LiteralPath $fullPath -PathType Leaf)) { + throw "Candidate admission $Kind file is missing: $fullPath" + } + $relative = [IO.Path]::GetRelativePath($RelativeRoot, $fullPath).Replace('\', '/') + return [ordered]@{ + kind = $Kind + path = $fullPath + relativePath = $relative + length = [IO.FileInfo]::new($fullPath).Length + sha256 = (Get-FileHash -LiteralPath $fullPath -Algorithm SHA256).Hash + } +} + +function Get-CandidateAdmissionRepositoryRecord([string] $Name, [string] $Path, [switch] $RequireClean) { + $fullPath = [IO.Path]::GetFullPath($Path) + if (-not (Test-Path -LiteralPath (Join-Path $fullPath ".git"))) { + throw "Candidate admission $Name is not a Git worktree: $fullPath" + } + $head = [string](Invoke-CandidateAdmissionGit $fullPath @("rev-parse", "HEAD") | + Select-Object -Last 1) + $tree = [string](Invoke-CandidateAdmissionGit $fullPath @("rev-parse", "HEAD^{tree}") | + Select-Object -Last 1) + $status = @(Invoke-CandidateAdmissionGit $fullPath @( + "status", "--porcelain=v1", "--untracked-files=all" + )) + if ($RequireClean -and $status.Count -ne 0) { + throw "Candidate admission $Name worktree is dirty: $($status -join '; ')" + } + [ordered]@{ + name = $Name + path = $fullPath + head = $head + tree = $tree + status = $status + } +} + +function Assert-WindowsShellCandidateEnvironment { + $environment = [Environment]::GetEnvironmentVariables('Process') + foreach ($name in @( + 'GRAPHCODE_UIA_GATE', + 'GRAPHCODE_UIA_SUPERVISED_FOREGROUND', + 'GRAPHCODE_UIA_EDGE_ACTION_TRACE' + )) { + if ($environment.Contains($name)) { + throw "Candidate admission requires $name to be absent before Windows shell validation." + } + } + if ($environment.Contains('GRAPHCODE_VALIDATION_ASSEMBLY')) { + $assembly = [Environment]::GetEnvironmentVariable('GRAPHCODE_VALIDATION_ASSEMBLY', 'Process') + if ([string]::IsNullOrEmpty($assembly) -or + -not [IO.Path]::IsPathFullyQualified($assembly) -or + -not (Test-Path -LiteralPath $assembly -PathType Leaf)) { + throw "GRAPHCODE_VALIDATION_ASSEMBLY has an explicitly empty or invalid candidate binding." + } + } +} + +function Assert-WindowsShellValidationRootsFresh([string] $Parent) { + $fullParent = [IO.Path]::GetFullPath($Parent) + if (-not (Test-Path -LiteralPath $fullParent -PathType Container)) { return } + $stale = @(Get-ChildItem -LiteralPath $fullParent -Force | + Where-Object { $_.Name -cmatch '^[0-9a-f]{32}$' } | + Sort-Object Name) + if ($stale.Count -ne 0) { + throw "Candidate admission found stale Windows shell validation root(s): " + + (($stale | ForEach-Object FullName) -join ', ') + } +} + +function Write-WindowsShellCandidateAdmission( + [Parameter(Mandatory)][string] $WorkspaceRoot, + [Parameter(Mandatory)][string] $ValidationRoot, + [Parameter(Mandatory)][string[]] $BindingPaths, + [Parameter(Mandatory)][string] $WinghosttyRoot, + [Parameter(Mandatory)][string] $ZmxRoot, + [Parameter(Mandatory)][string] $Zig0152, + [Parameter(Mandatory)][string] $Zig0160, + [string[]] $ManifestPaths = @(), + [string[]] $SourcePaths = @() +) { + Assert-WindowsShellCandidateEnvironment + $workspace = [IO.Path]::GetFullPath($WorkspaceRoot) + $validation = [IO.Path]::GetFullPath($ValidationRoot) + $processEnvironment = [Environment]::GetEnvironmentVariables('Process') + $environment = [ordered]@{} + foreach ($name in @( + 'GRAPHCODE_UIA_GATE', + 'GRAPHCODE_UIA_SUPERVISED_FOREGROUND', + 'GRAPHCODE_UIA_EDGE_ACTION_TRACE', + 'GRAPHCODE_VALIDATION_ASSEMBLY' + )) { + $environment[$name] = [ordered]@{ + present = $processEnvironment.Contains($name) + value = if ($processEnvironment.Contains($name)) { + [Environment]::GetEnvironmentVariable($name, 'Process') + } else { $null } + } + } + $pinsPath = Join-Path $workspace 'graphcode-windows\provider-pins.json' + if (-not (Test-Path -LiteralPath $pinsPath -PathType Leaf)) { + throw "Candidate admission provider pin manifest is missing: $pinsPath" + } + $pins = Read-SemanticSource $pinsPath | ConvertFrom-Json -Depth 20 -ErrorAction Stop + $repository = Get-CandidateAdmissionRepositoryRecord 'workspace' $workspace + $winghostty = Get-CandidateAdmissionRepositoryRecord 'winghostty' $WinghosttyRoot -RequireClean + $zmx = Get-CandidateAdmissionRepositoryRecord 'zmx' $ZmxRoot -RequireClean + if ($winghostty.head -cne [string]$pins.winghostty.sha -or + $zmx.head -cne [string]$pins.zmx.sha) { + throw 'Candidate admission provider worktrees do not match graphcode-windows\provider-pins.json.' + } + + $allManifestPaths = @($ManifestPaths + @($pinsPath) | Sort-Object -Unique) + $allSourcePaths = @($SourcePaths | Sort-Object -Unique) + $allBindingPaths = @($BindingPaths | Sort-Object -Unique) + $tools = @( + (Get-CandidateAdmissionFileRecord 'zig-0.15.2' $Zig0152 $workspace), + (Get-CandidateAdmissionFileRecord 'zig-0.16.0' $Zig0160 $workspace) + ) + $bindings = @($allBindingPaths | ForEach-Object { + Get-CandidateAdmissionFileRecord 'validation-binding' $_ $workspace + }) + $manifests = @($allManifestPaths | ForEach-Object { + Get-CandidateAdmissionFileRecord 'manifest' $_ $workspace + }) + $sources = @($allSourcePaths | ForEach-Object { + Get-CandidateAdmissionFileRecord 'source' $_ $workspace + }) + if ($bindings.Count -eq 0 -or $manifests.Count -eq 0 -or $sources.Count -eq 0) { + throw 'Candidate admission requires binding, manifest and source hashes.' + } + $record = [ordered]@{ + schemaVersion = 1 + environment = $environment + validationRoot = $validation + repository = $repository + providers = [ordered]@{ + winghostty = $winghostty + zmx = $zmx + } + tools = $tools + bindings = $bindings + manifests = $manifests + sources = $sources + } + $path = Join-Path $validation 'candidate-admission.json' + $json = $record | ConvertTo-Json -Depth 30 -Compress + [IO.File]::WriteAllText($path, $json + "`n", [Text.UTF8Encoding]::new($false)) + [pscustomobject]@{ + Path = $path + Sha256 = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash + Json = $json + } +} diff --git a/Tools/windows/SourceReader.ps1 b/Tools/windows/SourceReader.ps1 new file mode 100644 index 000000000..082df03f5 --- /dev/null +++ b/Tools/windows/SourceReader.ps1 @@ -0,0 +1,14 @@ +function ConvertTo-SemanticSourceText([string] $Source) { + return $Source.Replace("`r`n", "`n") +} + +function Read-SemanticSource([string] $Path) { + $fullPath = [IO.Path]::GetFullPath($Path) + $bytes = [IO.File]::ReadAllBytes($fullPath) + if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and + $bytes[2] -eq 0xBF) { + throw [IO.InvalidDataException]::new("Semantic source must be UTF-8 without BOM: $fullPath") + } + $text = [Text.UTF8Encoding]::new($false, $true).GetString($bytes) + return ConvertTo-SemanticSourceText $text +} diff --git a/Tools/windows/Tests/CandidateAdmission.Tests.ps1 b/Tools/windows/Tests/CandidateAdmission.Tests.ps1 new file mode 100644 index 000000000..a30f60e5d --- /dev/null +++ b/Tools/windows/Tests/CandidateAdmission.Tests.ps1 @@ -0,0 +1,197 @@ +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' +. (Join-Path $PSScriptRoot '..\Import-PinnedPester.ps1') + +Describe 'Windows validation candidate admission' { + BeforeAll { + $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path + . (Join-Path $repoRoot 'Tools\windows\CandidateAdmission.ps1') + . (Join-Path $repoRoot 'Tools\windows\SourceReader.ps1') + + function New-AdmissionRepository([string] $Path, [hashtable] $Files) { + $null = New-Item -ItemType Directory -Force -Path $Path + git -C $Path init --initial-branch=main | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'fixture git init failed' } + git -C $Path config user.name 'Admission Fixture' | Out-Null + git -C $Path config user.email 'admission@example.invalid' | Out-Null + foreach ($entry in $Files.GetEnumerator()) { + $file = Join-Path $Path $entry.Key + $null = New-Item -ItemType Directory -Force -Path (Split-Path $file -Parent) + [IO.File]::WriteAllText($file, [string] $entry.Value, [Text.UTF8Encoding]::new($false)) + } + git -C $Path add --all | Out-Null + git -C $Path commit -m fixture | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'fixture git commit failed' } + [pscustomobject]@{ + Head = ((git -C $Path rev-parse HEAD) | Select-Object -Last 1).Trim() + Tree = ((git -C $Path rev-parse 'HEAD^{tree}') | Select-Object -Last 1).Trim() + } + } + } + + BeforeEach { + $environmentNames = @( + 'GRAPHCODE_UIA_GATE', + 'GRAPHCODE_UIA_SUPERVISED_FOREGROUND', + 'GRAPHCODE_UIA_EDGE_ACTION_TRACE', + 'GRAPHCODE_VALIDATION_ASSEMBLY' + ) + $savedEnvironment = @{} + $environment = [Environment]::GetEnvironmentVariables('Process') + foreach ($name in $environmentNames) { + $savedEnvironment[$name] = [ordered]@{ + Present = $environment.Contains($name) + Value = [Environment]::GetEnvironmentVariable($name, 'Process') + } + Remove-Item -LiteralPath "Env:\$name" -ErrorAction SilentlyContinue + } + } + + AfterEach { + foreach ($entry in $savedEnvironment.GetEnumerator()) { + if ($entry.Value.Present) { + [Environment]::SetEnvironmentVariable($entry.Key, $entry.Value.Value, 'Process') + } elseif ([Environment]::GetEnvironmentVariables('Process').Contains($entry.Key)) { + Remove-Item -LiteralPath "Env:\$($entry.Key)" -ErrorAction Stop + } + } + } + + It 'admits only the explicit outer environment membership contract' { + { Assert-WindowsShellCandidateEnvironment } | Should -Not -Throw + $assembly = Join-Path $TestDrive 'validation.dll' + [IO.File]::WriteAllBytes($assembly, [byte[]](1, 2, 3)) + $env:GRAPHCODE_VALIDATION_ASSEMBLY = $assembly + { Assert-WindowsShellCandidateEnvironment } | Should -Not -Throw + $env:GRAPHCODE_VALIDATION_ASSEMBLY = '' + { Assert-WindowsShellCandidateEnvironment } | Should -Throw '*explicitly empty*' + Remove-Item Env:\GRAPHCODE_VALIDATION_ASSEMBLY + + foreach ($name in @( + 'GRAPHCODE_UIA_GATE', + 'GRAPHCODE_UIA_SUPERVISED_FOREGROUND', + 'GRAPHCODE_UIA_EDGE_ACTION_TRACE' + )) { + [Environment]::SetEnvironmentVariable($name, '', 'Process') + { Assert-WindowsShellCandidateEnvironment } | Should -Throw "*$name*absent*" + Remove-Item -LiteralPath "Env:\$name" -ErrorAction Stop + } + } + + It 'refuses stale validation roots without deleting them' { + $parent = Join-Path $TestDrive 'validation-roots' + $stale = Join-Path $parent '0123456789abcdef0123456789abcdef' + $unrelated = Join-Path $parent 'operator-notes' + $null = New-Item -ItemType Directory -Force -Path $stale,$unrelated + { Assert-WindowsShellValidationRootsFresh -Parent $parent } | + Should -Throw '*stale Windows shell validation root*' + Test-Path -LiteralPath $stale | Should -BeTrue + Remove-Item -LiteralPath $stale -Recurse -Force + { Assert-WindowsShellValidationRootsFresh -Parent $parent } | Should -Not -Throw + } + + It 'captures exact deterministic repository, provider, tool, binding and manifest identities' { + $winghostty = New-AdmissionRepository (Join-Path $TestDrive 'winghostty') @{ + 'provider.txt' = 'winghostty' + } + $zmx = New-AdmissionRepository (Join-Path $TestDrive 'zmx') @{ + 'provider.txt' = 'zmx' + } + $pins = [ordered]@{ + winghostty = [ordered]@{ sha = $winghostty.Head } + zmx = [ordered]@{ sha = $zmx.Head } + } | ConvertTo-Json -Compress + $workspace = Join-Path $TestDrive 'workspace' + $candidate = New-AdmissionRepository $workspace @{ + 'src\candidate.cs' = "namespace Fixture {}`n" + 'graphcode-windows\provider-pins.json' = $pins + 'graphcode-windows\build.zig.zon' = ".{ .name = .fixture }`n" + 'Tools\windows\validate.ps1' = "Write-Output 'fixture'`n" + } + $binding = Join-Path $workspace 'binding\ValidationFixtureBindings.dll' + $zig0152 = Join-Path $workspace 'tools\zig-0.15.2\zig.exe' + $zig0160 = Join-Path $workspace 'tools\zig-0.16.0\zig.exe' + $section = Join-Path $workspace 'manifest\sections.json' + foreach ($file in @($binding, $zig0152, $zig0160, $section)) { + $null = New-Item -ItemType Directory -Force -Path (Split-Path $file -Parent) + } + [IO.File]::WriteAllBytes($binding, [byte[]](1, 2, 3)) + [IO.File]::WriteAllBytes($zig0152, [byte[]](2, 3, 4)) + [IO.File]::WriteAllBytes($zig0160, [byte[]](3, 4, 5)) + [IO.File]::WriteAllText($section, '{"section":"fixture"}', [Text.UTF8Encoding]::new($false)) + $validationRoot = Join-Path $TestDrive 'validation-root' + $null = New-Item -ItemType Directory -Path $validationRoot + $arguments = @{ + WorkspaceRoot = $workspace + ValidationRoot = $validationRoot + BindingPaths = @($binding) + WinghosttyRoot = (Join-Path $TestDrive 'winghostty') + ZmxRoot = (Join-Path $TestDrive 'zmx') + Zig0152 = $zig0152 + Zig0160 = $zig0160 + ManifestPaths = @( + (Join-Path $workspace 'graphcode-windows\provider-pins.json'), + $section + ) + SourcePaths = @( + (Join-Path $workspace 'Tools\windows\validate.ps1'), + (Join-Path $workspace 'src\candidate.cs') + ) + } + + $first = Write-WindowsShellCandidateAdmission @arguments + $firstBytes = [IO.File]::ReadAllBytes($first.Path) + if ($firstBytes.Length -ge 3) { + ($firstBytes[0] -eq 0xEF -and $firstBytes[1] -eq 0xBB -and $firstBytes[2] -eq 0xBF) | + Should -BeFalse + } + $manifest = [Text.UTF8Encoding]::new($false, $true).GetString($firstBytes) | + ConvertFrom-Json -Depth 20 + $manifest.repository.head | Should -BeExactly $candidate.Head + $manifest.repository.tree | Should -BeExactly $candidate.Tree + $manifest.environment.GRAPHCODE_UIA_GATE.present | Should -BeFalse + $manifest.environment.GRAPHCODE_UIA_SUPERVISED_FOREGROUND.present | Should -BeFalse + $manifest.environment.GRAPHCODE_UIA_EDGE_ACTION_TRACE.present | Should -BeFalse + $manifest.environment.GRAPHCODE_VALIDATION_ASSEMBLY.present | Should -BeFalse + $manifest.providers.winghostty.head | Should -BeExactly $winghostty.Head + $manifest.providers.zmx.tree | Should -BeExactly $zmx.Tree + @($manifest.tools).Count | Should -Be 2 + @($manifest.bindings).Count | Should -Be 1 + @($manifest.manifests).Count | Should -Be 2 + @($manifest.sources).Count | Should -Be 2 + ($first.Sha256 -cmatch '^[A-F0-9]{64}$') | Should -BeTrue + + Remove-Item -LiteralPath $first.Path -Force + $second = Write-WindowsShellCandidateAdmission @arguments + $second.Sha256 | Should -BeExactly $first.Sha256 + [IO.File]::ReadAllBytes($second.Path) | Should -HaveCount $firstBytes.Length + } +} + +Describe 'Semantic source reader' { + BeforeAll { + $repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path + . (Join-Path $repoRoot 'Tools\windows\SourceReader.ps1') + } + + It 'normalizes LF and CRLF at the semantic boundary without rewriting raw bytes' { + $file = Join-Path $TestDrive 'source.cs' + $lf = "first`nsecond`n" + $crlf = $lf.Replace("`n", "`r`n") + [IO.File]::WriteAllText($file, $crlf, [Text.UTF8Encoding]::new($false)) + $raw = [IO.File]::ReadAllBytes($file) + (Read-SemanticSource -Path $file) | Should -BeExactly $lf + ConvertTo-SemanticSourceText $crlf | Should -BeExactly $lf + ([IO.File]::ReadAllBytes($file) -join ',') | Should -BeExactly ($raw -join ',') + } + + It 'refuses BOM and malformed UTF-8 semantic source' { + $file = Join-Path $TestDrive 'invalid-source.cs' + [IO.File]::WriteAllBytes($file, [byte[]](0xEF, 0xBB, 0xBF, 0x61)) + { Read-SemanticSource -Path $file } | Should -Throw '*BOM*' + [IO.File]::WriteAllBytes($file, [byte[]](0xC3, 0x28)) + { Read-SemanticSource -Path $file } | Should -Throw + } +} diff --git a/Tools/windows/Tests/ValidationIsolation.Tests.ps1 b/Tools/windows/Tests/ValidationIsolation.Tests.ps1 index 085a7fb92..17bee3ae6 100644 --- a/Tools/windows/Tests/ValidationIsolation.Tests.ps1 +++ b/Tools/windows/Tests/ValidationIsolation.Tests.ps1 @@ -7,6 +7,7 @@ $ErrorActionPreference = "Stop" Describe "Windows shell validation profile isolation" { BeforeAll { $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..\..") + . (Join-Path $repoRoot "Tools\windows\CandidateAdmission.ps1") $runnerPath = Join-Path $repoRoot "Tools\windows\validate.ps1" $runnerSource = Get-Content -LiteralPath $runnerPath -Raw $tokens = $null diff --git a/Tools/windows/ValidationRunner/Adapters/PowerShellPayload.cs b/Tools/windows/ValidationRunner/Adapters/PowerShellPayload.cs index 1721e286b..49efe4bb9 100644 --- a/Tools/windows/ValidationRunner/Adapters/PowerShellPayload.cs +++ b/Tools/windows/ValidationRunner/Adapters/PowerShellPayload.cs @@ -45,8 +45,8 @@ public static async Task RunAsync( UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = context.RepositoryRoot, - StandardOutputEncoding = new UTF8Encoding(false, true), - StandardErrorEncoding = new UTF8Encoding(false, true) + StandardOutputEncoding = OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(false, true)), + StandardErrorEncoding = OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(false, true)) }; foreach (var argument in new[] { "-NoLogo", "-NoProfile", "-NonInteractive", "-File", script }.Concat(arguments)) start.ArgumentList.Add(argument); diff --git a/Tools/windows/ValidationRunner/Manifests/ownership.json b/Tools/windows/ValidationRunner/Manifests/ownership.json index be161750e..17b28a259 100644 --- a/Tools/windows/ValidationRunner/Manifests/ownership.json +++ b/Tools/windows/ValidationRunner/Manifests/ownership.json @@ -62,6 +62,12 @@ "minimumCount": 1, "exactCount": 1 }, + { + "id": "ownership.managed.stream-encoding-contract", + "owner": "Ownership", + "minimumCount": 1, + "exactCount": 1 + }, { "id": "ownership.managed.receipt-valid", "owner": "Ownership", @@ -242,6 +248,12 @@ "minimumCount": 1, "exactCount": 1 }, + { + "id": "ownership.managed.raw-codec-bom", + "owner": "Ownership", + "minimumCount": 1, + "exactCount": 1 + }, { "id": "ownership.managed.json-malformed", "owner": "Ownership", diff --git a/Tools/windows/ValidationRunner/Ownership/Adapters/RetentionBoundary.Contracts.ps1 b/Tools/windows/ValidationRunner/Ownership/Adapters/RetentionBoundary.Contracts.ps1 index cf57f1728..1b403bc7a 100644 --- a/Tools/windows/ValidationRunner/Ownership/Adapters/RetentionBoundary.Contracts.ps1 +++ b/Tools/windows/ValidationRunner/Ownership/Adapters/RetentionBoundary.Contracts.ps1 @@ -6,6 +6,7 @@ param( ) . (Join-Path $PSScriptRoot 'AdapterSupport.ps1') +. (Join-Path $RepositoryRoot 'Tools\windows\CandidateAdmission.ps1') $script:OwnershipMockSignals = $true Import-OwnershipBindings $RepositoryRoot $AssemblyPath $consumer = Read-OwnershipProductionAst (Join-Path $RepositoryRoot 'Tools\windows\validate.ps1') @@ -31,7 +32,8 @@ try { $state = @{ root = $null; output = [Collections.Generic.List[string]]::new() } $failure = $null try { - Invoke-WindowsShellValidationIsolation -WorkspaceRoot $fixture -ValidationRootParent (Join-Path $fixture 'isolations') ` + Invoke-WindowsShellValidationIsolation -WorkspaceRoot $fixture ` + -ValidationRootParent (Join-Path $fixture "isolations\$($case.id)") ` -UserProfileRoot (Join-Path $fixture 'profile') -LocalAppDataRoot (Join-Path $fixture 'local') -Action { $state.root = $env:GRAPHCODE_VALIDATION_ROOT Invoke-Native 'controlled actual UIA retention boundary' { diff --git a/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs b/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs index 8dbbacaff..3fee8290c 100644 --- a/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs +++ b/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs @@ -13,11 +13,23 @@ public sealed class OwnedByteStreamCapture private readonly Decoder decoder; private readonly RetentionSignalObserver observer; private readonly StringBuilder text = new(); + private readonly byte[] prefix = new byte[3]; + private int prefixLength; + private bool bomDetected; private DecoderFallbackException? decodingFailure; public Task RawEof { get; } public Task Text { get; } + public static Encoding RequireUtf8NoBom(Encoding? encoding) + { + Encoding selected = (Encoding)(encoding ?? new UTF8Encoding(false, true)).Clone(); + if (selected.CodePage != Encoding.UTF8.CodePage || selected.GetPreamble().Length != 0) + throw new ArgumentException("Owned child output encoding must be UTF-8 without BOM.", nameof(encoding)); + selected.DecoderFallback = DecoderFallback.ExceptionFallback; + return selected; + } + public OwnedByteStreamCapture(Stream input, string path, Encoding? encoding, RetentionSignalObserver observer) { this.input = input; @@ -42,6 +54,14 @@ private async Task PumpAsync() await evidence.WriteAsync(bytes.AsMemory(0, count)).ConfigureAwait(false); await evidence.FlushAsync().ConfigureAwait(false); observer.OnBytes(bytes.AsSpan(0, count)); + if (prefixLength < prefix.Length) + { + int copied = Math.Min(count, prefix.Length - prefixLength); + Array.Copy(bytes, 0, prefix, prefixLength, copied); + prefixLength += copied; + if (prefixLength == prefix.Length) + bomDetected = prefix is [0xef, 0xbb, 0xbf]; + } if (decodingFailure == null) { try @@ -70,6 +90,8 @@ private async Task PumpAsync() private async Task DecodeResultAsync() { await RawEof.ConfigureAwait(false); + if (bomDetected) + throw new InvalidDataException("Owned child output must be UTF-8 without BOM."); if (decodingFailure != null) ExceptionDispatchInfo.Capture(decodingFailure).Throw(); return text.ToString(); } diff --git a/Tools/windows/ValidationRunner/Ownership/OwnedFixture.cs b/Tools/windows/ValidationRunner/Ownership/OwnedFixture.cs index 60ec7aa7f..6baa7f9eb 100644 --- a/Tools/windows/ValidationRunner/Ownership/OwnedFixture.cs +++ b/Tools/windows/ValidationRunner/Ownership/OwnedFixture.cs @@ -20,8 +20,8 @@ public static ProcessStartInfo Command(string mode, string root, params string[] { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = root, - StandardOutputEncoding = new UTF8Encoding(false, true), - StandardErrorEncoding = new UTF8Encoding(false, true) + StandardOutputEncoding = OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(false, true)), + StandardErrorEncoding = OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(false, true)) }; if (Path.GetFileNameWithoutExtension(host).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) start.ArgumentList.Add(Assembly.GetEntryAssembly()!.Location); diff --git a/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs b/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs index 560891071..7a02536bf 100644 --- a/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs +++ b/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs @@ -80,13 +80,14 @@ public sealed class OwnershipSuite : IValidationSuite [ "quote-empty", "quote-trailing-slash", "quote-embedded", "quote-unicode", "quote-nul", "stream-raw", "stream-surrogate-boundary", "stream-no-overwrite", "stream-independent-faults", "stream-shared-deadline", + "stream-encoding-contract", "receipt-valid", "receipt-existing", "receipt-missing", "receipt-file", "receipt-absent", "receipt-duplicate-json", "receipt-foreign-root", "receipt-over-limit", "proof-success", "proof-root-survivor", "proof-job-survivor", "proof-stdout-fault", "proof-stderr-fault", "cleanup-success", "cleanup-root-survivor", "cleanup-job-survivor", "cleanup-stdout-fault", "cleanup-both-stream-faults", "cleanup-primary-error", "cleanup-only-error", "cleanup-original-deadline", "cleanup-later-actions", "cleanup-descendant-unknown", "signal-fragmented", "signal-crlf", "signal-eof", "signal-exact-only", "signal-overlong", - "raw-codec-malformed-eof", "raw-codec-retention-after-malformed", + "raw-codec-malformed-eof", "raw-codec-retention-after-malformed", "raw-codec-bom", "json-malformed", "json-duplicate", "json-nested-duplicate", "json-array", "json-case-sensitive", "frame-fragmented-unicode", "frame-clean-eof", "frame-short-header", "frame-short-body", "frame-zero", "frame-over-limit", "frame-invalid-utf8", "peer-positive-rename", "peer-resume-unchanged", "peer-foreign-owner", "peer-foreign-node", @@ -205,6 +206,14 @@ private static async Task ManagedAsync(string id, string root, string alpha, str } if (id.StartsWith("stream-", StringComparison.Ordinal)) { + if (id == "stream-encoding-contract") + { + Reject(() => OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(true, true))); + Reject(() => OwnedByteStreamCapture.RequireUtf8NoBom(Encoding.Unicode)); + Require(OwnedByteStreamCapture.RequireUtf8NoBom(null).DecoderFallback is DecoderExceptionFallback, + "Default owned output encoding was not strict UTF-8."); + return; + } if (id == "stream-independent-faults") { var first = new IOException("stdout original"); @@ -343,14 +352,18 @@ private static async Task ManagedAsync(string id, string root, string alpha, str if (id.StartsWith("raw-codec-", StringComparison.Ordinal)) { bool withSignal = id == "raw-codec-retention-after-malformed"; - byte[] bytes = withSignal ? [0xc3, 0x28, 10, .. Encoding.UTF8.GetBytes(OwnershipRetention.Sentinel + "\n")] : [0xc3, 0x28]; + byte[] bytes = id == "raw-codec-bom" ? [0xef, 0xbb, 0xbf, 0x7b, 0x7d] : + withSignal ? [0xc3, 0x28, 10, .. Encoding.UTF8.GetBytes(OwnershipRetention.Sentinel + "\n")] : [0xc3, 0x28]; int signals = 0; string path = Path.Combine(root, id + ".log"); using var memory = new MemoryStream(bytes); var capture = new OwnedByteStreamCapture(memory, path, new UTF8Encoding(false, true), new RetentionSignalObserver(() => signals++)); await capture.RawEof.ConfigureAwait(false); - await RejectAsync(async () => { await capture.Text.ConfigureAwait(false); }).ConfigureAwait(false); + if (id == "raw-codec-bom") + await RejectAsync(async () => { await capture.Text.ConfigureAwait(false); }).ConfigureAwait(false); + else + await RejectAsync(async () => { await capture.Text.ConfigureAwait(false); }).ConfigureAwait(false); Require(capture.RawEof.IsCompletedSuccessfully && File.ReadAllBytes(path).SequenceEqual(bytes) && signals == (withSignal ? 1 : 0), "Strict decoding failure lost original bytes, independent raw EOF, or a later live retention marker."); return; @@ -506,12 +519,7 @@ private static async Task NativeAsync(string id, string root, string alpha, stri "Codec rejection did not independently prove raw EOF and safe owned cleanup."); string rawPath = Path.Combine(childRoot, $"owned-{owned.ProcessId}-{owned.CreationFileTime}-stdout.log"); Require(File.ReadAllBytes(rawPath).SequenceEqual(OwnedFixture.BytesForMode(id)), "Original pipe bytes were normalized or lost."); - if (id == "bytes-utf8-bom") - { - Require(result != null && result.StandardOutput.StartsWith('\uFEFF'), "UTF-8 BOM was consumed by capture."); - Reject(() => MultiProjectJson.Parse(result!.StandardOutput), "MULTIPROJECT_JSON"); - } - else if (id is "bytes-utf16-bom" or "bytes-invalid-utf8") + if (id is "bytes-utf8-bom" or "bytes-utf16-bom" or "bytes-invalid-utf8") Require(failure != null, "Non-UTF-8 pipe bytes were accepted by BOM autodetection or replacement."); else Require(result?.StandardOutput == new string('a', 4095) + "\uD83D\uDE80tail", "Supplementary scalar crossing the 4096-byte read boundary changed."); return; diff --git a/Tools/windows/ValidationRunner/Ui/UiRootSourceContracts.ps1 b/Tools/windows/ValidationRunner/Ui/UiRootSourceContracts.ps1 index 8bf8e9835..5a42491fd 100644 --- a/Tools/windows/ValidationRunner/Ui/UiRootSourceContracts.ps1 +++ b/Tools/windows/ValidationRunner/Ui/UiRootSourceContracts.ps1 @@ -4,8 +4,9 @@ param( [Parameter(Mandatory)][string] $AssemblyPath ) $ErrorActionPreference = 'Stop' +. (Join-Path $RepositoryRoot 'Tools\windows\SourceReader.ps1') $uiRoot = Join-Path $RepositoryRoot 'Tools\windows\ValidationRunner\Ui' -$catalogText = [IO.File]::ReadAllText((Join-Path $uiRoot 'source-assertions.json')) +$catalogText = Read-SemanticSource (Join-Path $uiRoot 'source-assertions.json') if ($catalogText.Length -gt 1048576) { throw 'UI source assertion data exceeded its size limit' } $catalog = @($catalogText | ConvertFrom-Json -Depth 100) if ($catalog.Count -ne 58) { throw 'Root UI declarative source assertion count must remain 58' } @@ -27,7 +28,7 @@ $resources = @{} $linkage = @{ verified = $false } function Assert-ProductionSourceLinkage { if ($linkage.verified) { return } - $gateText = [IO.File]::ReadAllText((Join-Path $RepositoryRoot $paths.gate)) + $gateText = Read-SemanticSource (Join-Path $RepositoryRoot $paths.gate) if ($gateText -match '\bclass\s+(GraphCodeUiaGateState|GraphCodeUiaHostInfo|GraphCodeUiaAttribution|GraphCodeMultiProjectRenameNative)\b' -or -not $gateText.Contains('Import-CompiledValidationAssembly.ps1') -or -not $gateText.Contains('-AssemblyPath $validationAssemblyPath -RequiredType $requiredType')) { @@ -47,7 +48,7 @@ function Assert-ProductionSourceLinkage { if (-not $input -or $input.FieldType -ne $bindings.GetType('GraphCode.Windows.UiaInputSafety', $true)) { throw 'Production gate does not use the exact tested shared input component' } - $project = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'Tools\windows\ValidationRunner\Bindings\Windows\WindowsValidationBindings.csproj')) + $project = Read-SemanticSource (Join-Path $RepositoryRoot 'Tools\windows\ValidationRunner\Bindings\Windows\WindowsValidationBindings.csproj') if (-not $project.Contains('Compile Include="..\..\Ui\Production\*.cs"') -or -not $project.Contains('Compile Include="..\..\..\UiaWindowActivation.cs"')) { throw 'Production binding does not compile the actual current shared sources' @@ -58,7 +59,7 @@ function Read-SourceResource([string] $Name) { if (-not $paths.ContainsKey($Name)) { throw "Undeclared UI source resource: $Name" } if (-not $resources.ContainsKey($Name)) { if ($Name -cin @('gate-state', 'input-safety', 'host-info')) { Assert-ProductionSourceLinkage } - $text = [IO.File]::ReadAllText((Join-Path $RepositoryRoot $paths[$Name])) + $text = Read-SemanticSource (Join-Path $RepositoryRoot $paths[$Name]) $resources[$Name] = $text } return $resources[$Name] diff --git a/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 b/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 index 0d0f53126..425c63b80 100644 --- a/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 +++ b/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 @@ -4,13 +4,11 @@ param( [Parameter(Mandatory)][string] $AssemblyPath ) $ErrorActionPreference = 'Stop' -function ConvertTo-SourceLineEndings([string] $Source) { - return $Source.Replace("`r`n", "`n") -} +. (Join-Path $RepositoryRoot 'Tools\windows\SourceReader.ps1') $uiRoot = Join-Path $RepositoryRoot 'Tools\windows\ValidationRunner\Ui' -$activation = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'Tools\windows\UiaWindowActivation.cs')) -$gate = [IO.File]::ReadAllText((Join-Path $uiRoot 'Production\GraphCodeUiaGateState.cs')) -$inputSource = ConvertTo-SourceLineEndings ([IO.File]::ReadAllText((Join-Path $uiRoot 'Production\UiaInputSafety.cs'))) +$activation = Read-SemanticSource (Join-Path $RepositoryRoot 'Tools\windows\UiaWindowActivation.cs') +$gate = Read-SemanticSource (Join-Path $uiRoot 'Production\GraphCodeUiaGateState.cs') +$inputSource = Read-SemanticSource (Join-Path $uiRoot 'Production\UiaInputSafety.cs') $results = [Collections.Generic.List[object]]::new() function Assert-UiContract([bool] $Condition, [string] $Message) { @@ -135,7 +133,7 @@ $rootEvaluator = @($rootAst.FindAll({ param($node) }, $true)) Assert-UiContract ($rootPopup.Count -eq 1 -and $rootEvaluator.Count -eq 1) ` 'Actual declarative popup predicate or evaluator is missing or duplicated' -$gateSource = [IO.File]::ReadAllText((Join-Path $RepositoryRoot 'Tools\windows\uia-live-gate.ps1')) +$gateSource = Read-SemanticSource (Join-Path $RepositoryRoot 'Tools\windows\uia-live-gate.ps1') $rootPopupResults = [Collections.Generic.List[bool]]::new() function Confirm-RootPopupSource([string] $Source) { $rootResources = @{ gate = $gateSource; 'input-safety' = $Source } @@ -170,7 +168,7 @@ foreach ($case in $popupCases) { ' ObserveInput("popup-closed", (uint)inputs.Length, sent);' $lfSource = $inputSource.Replace("`r`n", "`n") foreach ($checkoutSource in @($lfSource, $lfSource.Replace("`n", "`r`n"))) { - $normalizedSource = ConvertTo-SourceLineEndings $checkoutSource + $normalizedSource = ConvertTo-SemanticSourceText $checkoutSource Assert-UiContract ([regex]::Matches($normalizedSource, [regex]::Escape($closureObservation)).Count -eq 1) ` 'LF and CRLF checkouts must identify exactly one production closure observation' Assert-UiContract ((Confirm-PopupSource $normalizedSource) -and (Confirm-RootPopupSource $normalizedSource)) ` diff --git a/Tools/windows/validate.ps1 b/Tools/windows/validate.ps1 index 228fb0105..273ad4531 100644 --- a/Tools/windows/validate.ps1 +++ b/Tools/windows/validate.ps1 @@ -97,6 +97,7 @@ if ($List) { } $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..\..") +. (Join-Path $repoRoot "Tools\windows\CandidateAdmission.ps1") function Resolve-SwiftExecutable { if ($SwiftExecutable) { @@ -370,12 +371,19 @@ function Invoke-WindowsShellValidationIsolation( [string] $UserProfileRoot = $env:USERPROFILE, [string] $LocalAppDataRoot = $env:LOCALAPPDATA ) { + $validationParent = if ($ValidationRootParent) { + [IO.Path]::GetFullPath($ValidationRootParent) + } else { + Join-Path $WorkspaceRoot ".build\windows-shell-validation" + } + Assert-WindowsShellCandidateEnvironment + Assert-WindowsShellValidationRootsFresh -Parent $validationParent $defaultSupport = Join-Path $UserProfileRoot ".graphcode" $defaultLocalAppData = Join-Path $LocalAppDataRoot "GraphCode" $supportBefore = Get-WindowsShellProfileSnapshot $defaultSupport $localAppDataBefore = Get-WindowsShellProfileSnapshot $defaultLocalAppData $validationRoot = if ($ValidationRootParent) { - $parent = [IO.Path]::GetFullPath($ValidationRootParent) + $parent = $validationParent New-Item -ItemType Directory -Force -Path $parent | Out-Null Join-Path $parent ([guid]::NewGuid().ToString("N")) } else { @@ -1229,7 +1237,8 @@ function Invoke-Task([string] $name) { $isolationResults = Invoke-Pester ` -Path @( (Join-Path $repoRoot "Tools\windows\Tests\ValidationIsolation.Tests.ps1"), - (Join-Path $repoRoot "Tools\windows\Tests\CompiledValidationEnvironment.Tests.ps1") + (Join-Path $repoRoot "Tools\windows\Tests\CompiledValidationEnvironment.Tests.ps1"), + (Join-Path $repoRoot "Tools\windows\Tests\CandidateAdmission.Tests.ps1") ) ` -PassThru if ($isolationResults.TotalCount -le 0 -or @@ -1256,31 +1265,14 @@ function Invoke-Task([string] $name) { sessionId = [int]$_.SessionId } }) -Compress -Depth 4)) - $zig0152 = Resolve-ZigVersion "0.15.2" "GRAPHCODE_ZIG0152" - $runShellUnit = $ShellPart -ne "integration" - $runShellIntegration = $ShellPart -ne "unit" - if ($runShellIntegration) { - $swift = Resolve-SwiftExecutable - Initialize-SwiftEnvironment $swift - $daemonRuntime = Build-SwiftReleaseRuntime $swift "shell daemon handoff" - } - $depotRoot = Split-Path (Split-Path $repoRoot -Parent) -Parent - $winghosttyRoot = [Environment]::GetEnvironmentVariable( - "GRAPHCODE_WINGHOSTTY_ROOT" - ) - if (-not $winghosttyRoot) { - $winghosttyRoot = Join-Path $depotRoot "Winghostty-worktrees\host-integration" - } - $zmxRoot = [Environment]::GetEnvironmentVariable("GRAPHCODE_ZMX_ROOT") - if (-not $zmxRoot) { - $zmxRoot = Join-Path $depotRoot "zmx-worktrees\quickchat-hang" - } - if (-not (Test-Path -LiteralPath $winghosttyRoot -PathType Container) -or - -not (Test-Path -LiteralPath $zmxRoot -PathType Container)) { - throw "Windows shell provider worktrees unavailable; real smoke is mandatory." - } - $pins = Get-Content (Join-Path $repoRoot "graphcode-windows\provider-pins.json") -Raw | - ConvertFrom-Json + $providerRoots = Resolve-ProviderRoots "zmx-worktrees\quickchat-hang" "Windows shell validation" + $zig0152 = $providerRoots.Zig0152 + $zig0160 = $providerRoots.Zig0160 + $winghosttyRoot = $providerRoots.Winghostty + $zmxRoot = $providerRoots.Zmx + $pins = Read-SemanticSource ( + Join-Path $repoRoot "graphcode-windows\provider-pins.json" + ) | ConvertFrom-Json if (-not (Test-Path -LiteralPath (Join-Path $winghosttyRoot ".git"))) { throw "Winghostty provider root is not a Git worktree: $winghosttyRoot" } @@ -1292,6 +1284,48 @@ function Invoke-Task([string] $name) { if ($LASTEXITCODE -ne 0 -or $actualWinghosttyPin -ne $pins.winghostty.sha) { throw "Winghostty provider does not match the pinned commit" } + $runShellUnit = $ShellPart -ne "integration" + $runShellIntegration = $ShellPart -ne "unit" + if ($runShellIntegration) { + $swift = Resolve-SwiftExecutable + Initialize-SwiftEnvironment $swift + $daemonRuntime = Build-SwiftReleaseRuntime $swift "shell daemon handoff" + } + $bindingDirectory = Split-Path $env:GRAPHCODE_VALIDATION_ASSEMBLY -Parent + $bindingPaths = @( + $env:GRAPHCODE_VALIDATION_ASSEMBLY, + (Join-Path $bindingDirectory "ValidationFixtureBindings.dll"), + (Join-Path $bindingDirectory "WindowsValidationBindings.dll") + ) | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } + $manifestPaths = @( + (Join-Path $repoRoot "graphcode-windows\provider-pins.json"), + (Join-Path $repoRoot "graphcode-windows\build.zig.zon"), + (Join-Path $repoRoot "graphcode-windows\build.zig"), + (Join-Path $repoRoot "Tools\windows\ValidationRunner\ValidationRunner.csproj"), + @(Get-ChildItem -LiteralPath ( + Join-Path $repoRoot "Tools\windows\ValidationRunner\Manifests" + ) -Filter "*.json" -File | ForEach-Object FullName) + ) + $candidateAdmission = Write-WindowsShellCandidateAdmission ` + -WorkspaceRoot $repoRoot ` + -ValidationRoot $env:GRAPHCODE_VALIDATION_ROOT ` + -BindingPaths $bindingPaths ` + -WinghosttyRoot $winghosttyRoot ` + -ZmxRoot $zmxRoot ` + -Zig0152 $zig0152 ` + -Zig0160 $zig0160 ` + -ManifestPaths $manifestPaths ` + -SourcePaths @( + (Join-Path $repoRoot "Tools\windows\validate.ps1"), + (Join-Path $repoRoot "Tools\windows\CandidateAdmission.ps1"), + (Join-Path $repoRoot "Tools\windows\SourceReader.ps1"), + (Join-Path $repoRoot "Tools\windows\Build-CompiledValidationRunner.ps1"), + (Join-Path $repoRoot "Tools\windows\Import-CompiledValidationAssembly.ps1"), + (Join-Path $repoRoot "Tools\windows\ValidationRunner\Ownership\OwnedChildSupervisor.cs"), + (Join-Path $repoRoot "Tools\windows\ValidationRunner\Ownership\OwnedByteStreamCapture.cs") + ) + Write-Host "WINDOWS_SHELL_CANDIDATE_ADMISSION_SHA256=$($candidateAdmission.Sha256)" + Write-Host "WINDOWS_SHELL_CANDIDATE_ADMISSION_JSON=$($candidateAdmission.Json)" Invoke-Native "Pinned Winghostty host build for App contracts" { Push-Location $winghosttyRoot try { & $zig0152 build -Demit-win32-host=true } finally { Pop-Location } @@ -1324,7 +1358,6 @@ function Invoke-Task([string] $name) { } # The unit part ends here; `break` leaves this switch clause only. if (-not $runShellIntegration) { break } - $zig0160 = Resolve-ZigVersion "0.16.0" "GRAPHCODE_ZIG0160" Invoke-Native "Pinned GraphCode Windows shell build and smoke" { & (Join-Path $repoRoot "Tools\windows\windows-shell.ps1") ` -WinghosttyRoot $winghosttyRoot ` From f23c1e7d4eed1585ed3784780f7a79ab9f5c232f Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Wed, 11 Nov 2026 12:23:27 -0700 Subject: [PATCH 2/4] Enforce UTF-8 owned child capture Reject UTF-16, BOM-prefixed, and OEM capture configurations in both OwnedByteStreamCapture and OwnedChildSupervisor. Bind the native cmd harness to UTF-8 and exercise LF text, invalid encodings, supervisor admission, and raw-byte preservation. RED: Build-CompiledValidationRunner plus ValidationRunner.exe --suite ownership -> ownership.managed.stream-encoding-contract failed before the enforcement fix. GREEN: focused ownership encoding tests -> stream-encoding-contract, raw-codec-bom, and bytes-utf8-bom passed; native harness safety 16/16 passed. REGRESSION: pwsh -NoProfile -File Tools\windows\Invoke-ValidationRunnerContract.ps1 -> complete true, 695 required, 695 passed, 2354 executed, 0 errors. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- ...ityProvider.Native.Tests.Harness.Tests.ps1 | 11 ++--- .../AccessibilityProvider.Native.Tests.ps1 | 8 ++-- .../Ownership/OwnedByteStreamCapture.cs | 3 +- .../Ownership/OwnedChildSupervisor.cs | 2 + .../Ownership/SuiteRegistration.cs | 48 +++++++++++++++++++ 5 files changed, 58 insertions(+), 14 deletions(-) diff --git a/Tools/windows/Tests/AccessibilityProvider.Native.Tests.Harness.Tests.ps1 b/Tools/windows/Tests/AccessibilityProvider.Native.Tests.Harness.Tests.ps1 index 577f61c51..9c09a9919 100644 --- a/Tools/windows/Tests/AccessibilityProvider.Native.Tests.Harness.Tests.ps1 +++ b/Tools/windows/Tests/AccessibilityProvider.Native.Tests.Harness.Tests.ps1 @@ -137,11 +137,8 @@ exit $result $start.CreateNoWindow = $true $start.RedirectStandardOutput = $true $start.RedirectStandardError = $true - [Text.Encoding]::RegisterProvider([Text.CodePagesEncodingProvider]::Instance) - $wrapperEncoding = [Text.Encoding]::GetEncoding([ShellOwnedLaunch]::OemCodePage(), - [Text.EncoderFallback]::ExceptionFallback, [Text.DecoderFallback]::ExceptionFallback) - $start.StandardOutputEncoding = $wrapperEncoding - $start.StandardErrorEncoding = $wrapperEncoding + $start.StandardOutputEncoding = [Text.UTF8Encoding]::new($false, $true) + $start.StandardErrorEncoding = [Text.UTF8Encoding]::new($false, $true) foreach ($argument in @( "-NoProfile", "-File", $wrapper, "-NativeScript", $NativeScriptUnderTest, "-VcVars", $vcvars, @@ -221,10 +218,10 @@ exit $result -not $proof.cleanup.StdoutEof -or -not $proof.cleanup.StderrEof -or -not $proof.cleanup.ResourcesClosed) { throw "Native mock failure did not retain exact exit and successful held cleanup proof" } - if ($proof.stdoutCodePage -ne [ShellOwnedLaunch]::OemCodePage() -or + if ($proof.stdoutCodePage -ne 65001 -or $proof.stderrCodePage -ne $proof.stdoutCodePage) { throw "cmd producer encodings were not bound explicitly" } if ($Stage -ceq "compile" -and -not $output.Contains((Join-Path $fixture "cl.cmd"))) { - throw "Controlled non-ASCII compiler path did not roundtrip through cmd's actual OEM codec" + throw "Controlled non-ASCII compiler path did not roundtrip through cmd's UTF-8 codec" } if ($output -notmatch '\[native-harness\] original PATH restored') { throw "RED: native harness did not restore the exact original PATH after $Stage failure" diff --git a/Tools/windows/Tests/AccessibilityProvider.Native.Tests.ps1 b/Tools/windows/Tests/AccessibilityProvider.Native.Tests.ps1 index 8e099a809..c5952b73e 100644 --- a/Tools/windows/Tests/AccessibilityProvider.Native.Tests.ps1 +++ b/Tools/windows/Tests/AccessibilityProvider.Native.Tests.ps1 @@ -169,6 +169,7 @@ try { # Keep batch source ASCII; pass Unicode paths through cmd arguments. $command = @' @echo off +chcp 65001 >nul cd /d "%~dp0" if errorlevel 1 exit /b %errorlevel% echo [native-uia] stage=vcvars start @@ -204,11 +205,8 @@ exit /b %test_exit% $native.WorkingDirectory = $scratch $native.RedirectStandardOutput = $true $native.RedirectStandardError = $true - [Text.Encoding]::RegisterProvider([Text.CodePagesEncodingProvider]::Instance) - $oemEncoding = [Text.Encoding]::GetEncoding([ShellOwnedLaunch]::OemCodePage(), - [Text.EncoderFallback]::ExceptionFallback, [Text.DecoderFallback]::ExceptionFallback) - $native.StandardOutputEncoding = $oemEncoding - $native.StandardErrorEncoding = $oemEncoding + $native.StandardOutputEncoding = [Text.UTF8Encoding]::new($false, $true) + $native.StandardErrorEncoding = [Text.UTF8Encoding]::new($false, $true) foreach ($argument in @("/d", "/s", "/c", "run-native.cmd")) { $native.ArgumentList.Add($argument) } $native.Environment["GRAPHCODE_NATIVE_VCVARS"] = [IO.Path]::GetFullPath($VcVars) $native.Environment["GRAPHCODE_NATIVE_TEST"] = $test diff --git a/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs b/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs index 3fee8290c..2c447a0fb 100644 --- a/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs +++ b/Tools/windows/ValidationRunner/Ownership/OwnedByteStreamCapture.cs @@ -34,8 +34,7 @@ public OwnedByteStreamCapture(Stream input, string path, Encoding? encoding, Ret { this.input = input; this.observer = observer; - var strict = (Encoding)(encoding ?? new UTF8Encoding(false, true)).Clone(); - strict.DecoderFallback = DecoderFallback.ExceptionFallback; + Encoding strict = RequireUtf8NoBom(encoding); decoder = strict.GetDecoder(); evidence = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite, 4096, true); RawEof = PumpAsync(); diff --git a/Tools/windows/ValidationRunner/Ownership/OwnedChildSupervisor.cs b/Tools/windows/ValidationRunner/Ownership/OwnedChildSupervisor.cs index b79819886..06c1bc003 100644 --- a/Tools/windows/ValidationRunner/Ownership/OwnedChildSupervisor.cs +++ b/Tools/windows/ValidationRunner/Ownership/OwnedChildSupervisor.cs @@ -182,6 +182,8 @@ public static OwnedChildSupervisor Start(ProcessStartInfo start, TimeSpan timeou throw new ArgumentException("Owned launch requires ArgumentList, UseShellExecute=false and closed stdin.", nameof(start)); if (!Path.IsPathFullyQualified(start.FileName) || !File.Exists(start.FileName)) throw new ArgumentException("Owned executable must be an existing absolute path.", nameof(start)); + _ = OwnedByteStreamCapture.RequireUtf8NoBom(start.StandardOutputEncoding); + _ = OwnedByteStreamCapture.RequireUtf8NoBom(start.StandardErrorEncoding); var run = new OwnedChildSupervisor(timeout, artifactRoot); try { diff --git a/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs b/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs index 7a02536bf..6f33ef893 100644 --- a/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs +++ b/Tools/windows/ValidationRunner/Ownership/SuiteRegistration.cs @@ -210,8 +210,56 @@ private static async Task ManagedAsync(string id, string root, string alpha, str { Reject(() => OwnedByteStreamCapture.RequireUtf8NoBom(new UTF8Encoding(true, true))); Reject(() => OwnedByteStreamCapture.RequireUtf8NoBom(Encoding.Unicode)); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Encoding oem = Encoding.GetEncoding(437, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + Require(oem.CodePage == 437, "OEM codec control did not select code page 437."); + Reject(() => OwnedByteStreamCapture.RequireUtf8NoBom(oem)); Require(OwnedByteStreamCapture.RequireUtf8NoBom(null).DecoderFallback is DecoderExceptionFallback, "Default owned output encoding was not strict UTF-8."); + string capturePath = Path.Combine(root, id + ".log"); + const string lf = "first\nsecond\n"; + byte[] bytes = Encoding.UTF8.GetBytes(lf); + var capture = new OwnedByteStreamCapture(new MemoryStream(bytes), capturePath, + new UTF8Encoding(false, true), new RetentionSignalObserver(() => { })); + Require(await capture.Text.ConfigureAwait(false) == lf && + File.ReadAllBytes(capturePath).SequenceEqual(bytes), + "Valid UTF-8 LF capture or raw evidence changed."); + foreach (string invalidName in new[] { "utf16-capture", "bom-capture", "oem-capture" }) + { + Encoding invalid = invalidName switch + { + "utf16-capture" => Encoding.Unicode, + "bom-capture" => new UTF8Encoding(true, true), + _ => oem + }; + Reject(() => new OwnedByteStreamCapture( + new MemoryStream(bytes), Path.Combine(root, id + "-" + invalidName + ".log"), + invalid, new RetentionSignalObserver(() => { }))); + } + foreach ((string name, Encoding output, bool stdout) in new[] + { + ("supervisor-stdout-utf16", Encoding.Unicode, true), + ("supervisor-stderr-bom", new UTF8Encoding(true, true), false), + ("supervisor-stdout-oem", oem, true) + }) + { + string childRoot = Path.Combine(root, id + "-" + name); + Directory.CreateDirectory(childRoot); + ProcessStartInfo start = OwnedFixture.Command("normal", childRoot); + if (stdout) start.StandardOutputEncoding = output; + else start.StandardErrorEncoding = output; + Exception? failure = null; + OwnedChildSupervisor? owned = null; + try { owned = OwnedChildSupervisor.Start(start, TimeSpan.FromSeconds(5), childRoot); } + catch (Exception error) { failure = error; } + finally + { + if (owned != null) + await owned.StopAsync(new InvalidOperationException("RED cleanup")).ConfigureAwait(false); + } + Require(failure is ArgumentException, + $"{name} was admitted by OwnedChildSupervisor."); + } return; } if (id == "stream-independent-faults") From 2e93ee68dbd9cade874a4206287250d55975682e Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Wed, 11 Nov 2026 14:23:33 -0700 Subject: [PATCH 3/4] Flatten candidate admission manifest inputs Normalize nested manifest, binding, and source collections into typed scalar lists before hashing. Emit one record per path and reject newline-concatenated path values. Cover the three-manifest CI shape directly. RED: pwsh -NoProfile -File Tools\windows\Tests\CandidateAdmission.Tests.ps1 -> 5 passed, 1 failed because Get-WindowsShellCandidateManifestPaths was absent. GREEN: CandidateAdmission.Tests.ps1 -> 6 passed, 0 failed; merged isolation preflight -> 51 passed, 0 failed. REGRESSION: Invoke-ValidationRunnerContract.ps1 -> complete true, 695 required, 695 passed, 2354 executed, 0 errors; exact CI shell unit commands -> shards 3/3 PASS. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- Tools/windows/CandidateAdmission.ps1 | 83 +++++++++++++++---- .../Tests/CandidateAdmission.Tests.ps1 | 56 +++++++++++-- Tools/windows/validate.ps1 | 10 +-- 3 files changed, 120 insertions(+), 29 deletions(-) diff --git a/Tools/windows/CandidateAdmission.ps1 b/Tools/windows/CandidateAdmission.ps1 index 81fd0a111..e7de0e5b8 100644 --- a/Tools/windows/CandidateAdmission.ps1 +++ b/Tools/windows/CandidateAdmission.ps1 @@ -80,16 +80,72 @@ function Assert-WindowsShellValidationRootsFresh([string] $Parent) { } } +function Get-WindowsShellCandidateManifestPaths([string] $WorkspaceRoot) { + $workspace = [IO.Path]::GetFullPath($WorkspaceRoot) + $paths = [Collections.Generic.List[string]]::new() + foreach ($relative in @( + 'graphcode-windows\provider-pins.json', + 'graphcode-windows\build.zig.zon', + 'graphcode-windows\build.zig', + 'Tools\windows\ValidationRunner\ValidationRunner.csproj' + )) { + $paths.Add([IO.Path]::GetFullPath((Join-Path $workspace $relative))) + } + $manifestRoot = Join-Path $workspace 'Tools\windows\ValidationRunner\Manifests' + foreach ($manifest in Get-ChildItem -LiteralPath $manifestRoot -Filter '*.json' -File | + Sort-Object FullName) { + $paths.Add($manifest.FullName) + } + return @($paths | Sort-Object -Unique) +} + +function Get-CandidateAdmissionPaths([object[]] $Paths) { + $normalized = [Collections.Generic.List[string]]::new() + $pending = [Collections.Generic.Queue[object]]::new() + foreach ($path in @($Paths)) { $pending.Enqueue($path) } + while ($pending.Count -ne 0) { + $candidate = $pending.Dequeue() + if ($candidate -is [string]) { + if ([string]::IsNullOrEmpty($candidate) -or $candidate -match "[`r`n]") { + throw 'Candidate admission paths must be nonempty scalar strings without embedded line endings.' + } + $normalized.Add($candidate) + continue + } + if ($candidate -is [Collections.IEnumerable]) { + foreach ($entry in $candidate) { $pending.Enqueue($entry) } + continue + } + throw "Candidate admission path collection contains an unsupported value of type '$($candidate.GetType().FullName)'." + } + return @($normalized | Sort-Object -Unique) +} + +function Get-CandidateAdmissionFileRecords( + [Parameter(Mandatory)][string] $Kind, + [Parameter(Mandatory)][object[]] $Paths, + [Parameter(Mandatory)][string] $RelativeRoot +) { + $records = [Collections.Generic.List[object]]::new() + foreach ($path in @(Get-CandidateAdmissionPaths -Paths $Paths)) { + $records.Add((Get-CandidateAdmissionFileRecord ` + -Kind $Kind ` + -Path ([string]$path) ` + -RelativeRoot $RelativeRoot)) + } + return $records.ToArray() +} + function Write-WindowsShellCandidateAdmission( [Parameter(Mandatory)][string] $WorkspaceRoot, [Parameter(Mandatory)][string] $ValidationRoot, - [Parameter(Mandatory)][string[]] $BindingPaths, + [Parameter(Mandatory)][object[]] $BindingPaths, [Parameter(Mandatory)][string] $WinghosttyRoot, [Parameter(Mandatory)][string] $ZmxRoot, [Parameter(Mandatory)][string] $Zig0152, [Parameter(Mandatory)][string] $Zig0160, - [string[]] $ManifestPaths = @(), - [string[]] $SourcePaths = @() + [object[]] $ManifestPaths = @(), + [object[]] $SourcePaths = @() ) { Assert-WindowsShellCandidateEnvironment $workspace = [IO.Path]::GetFullPath($WorkspaceRoot) @@ -122,22 +178,19 @@ function Write-WindowsShellCandidateAdmission( throw 'Candidate admission provider worktrees do not match graphcode-windows\provider-pins.json.' } - $allManifestPaths = @($ManifestPaths + @($pinsPath) | Sort-Object -Unique) - $allSourcePaths = @($SourcePaths | Sort-Object -Unique) - $allBindingPaths = @($BindingPaths | Sort-Object -Unique) + $allManifestPaths = @(Get-CandidateAdmissionPaths -Paths @($ManifestPaths, $pinsPath)) + $allSourcePaths = @(Get-CandidateAdmissionPaths -Paths $SourcePaths) + $allBindingPaths = @(Get-CandidateAdmissionPaths -Paths $BindingPaths) $tools = @( (Get-CandidateAdmissionFileRecord 'zig-0.15.2' $Zig0152 $workspace), (Get-CandidateAdmissionFileRecord 'zig-0.16.0' $Zig0160 $workspace) ) - $bindings = @($allBindingPaths | ForEach-Object { - Get-CandidateAdmissionFileRecord 'validation-binding' $_ $workspace - }) - $manifests = @($allManifestPaths | ForEach-Object { - Get-CandidateAdmissionFileRecord 'manifest' $_ $workspace - }) - $sources = @($allSourcePaths | ForEach-Object { - Get-CandidateAdmissionFileRecord 'source' $_ $workspace - }) + $bindings = @(Get-CandidateAdmissionFileRecords ` + -Kind 'validation-binding' -Paths $allBindingPaths -RelativeRoot $workspace) + $manifests = @(Get-CandidateAdmissionFileRecords ` + -Kind 'manifest' -Paths $allManifestPaths -RelativeRoot $workspace) + $sources = @(Get-CandidateAdmissionFileRecords ` + -Kind 'source' -Paths $allSourcePaths -RelativeRoot $workspace) if ($bindings.Count -eq 0 -or $manifests.Count -eq 0 -or $sources.Count -eq 0) { throw 'Candidate admission requires binding, manifest and source hashes.' } diff --git a/Tools/windows/Tests/CandidateAdmission.Tests.ps1 b/Tools/windows/Tests/CandidateAdmission.Tests.ps1 index a30f60e5d..db68286d1 100644 --- a/Tools/windows/Tests/CandidateAdmission.Tests.ps1 +++ b/Tools/windows/Tests/CandidateAdmission.Tests.ps1 @@ -92,6 +92,36 @@ Describe 'Windows validation candidate admission' { { Assert-WindowsShellValidationRootsFresh -Parent $parent } | Should -Not -Throw } + It 'returns the admission manifest catalog as individual full paths' { + $workspace = Join-Path $TestDrive 'manifest-workspace' + $manifestRoot = Join-Path $workspace 'Tools\windows\ValidationRunner\Manifests' + $null = New-Item -ItemType Directory -Force -Path ( + Join-Path $workspace 'graphcode-windows' + ),$manifestRoot + foreach ($relative in @( + 'graphcode-windows\provider-pins.json', + 'graphcode-windows\build.zig.zon', + 'graphcode-windows\build.zig', + 'Tools\windows\ValidationRunner\ValidationRunner.csproj', + 'Tools\windows\ValidationRunner\Manifests\host.json', + 'Tools\windows\ValidationRunner\Manifests\ownership.json', + 'Tools\windows\ValidationRunner\Manifests\ui.json' + )) { + [IO.File]::WriteAllText( + (Join-Path $workspace $relative), + '{}', + [Text.UTF8Encoding]::new($false) + ) + } + + $paths = @(Get-WindowsShellCandidateManifestPaths -WorkspaceRoot $workspace) + $paths.Count | Should -Be 7 + $paths | ForEach-Object { $_ | Should -BeOfType ([string]) } + $paths | ForEach-Object { [IO.Path]::IsPathFullyQualified($_) | Should -BeTrue } + $paths | ForEach-Object { Test-Path -LiteralPath $_ -PathType Leaf | Should -BeTrue } + $paths | Where-Object { $_ -match "[`r`n]" } | Should -BeNullOrEmpty + } + It 'captures exact deterministic repository, provider, tool, binding and manifest identities' { $winghostty = New-AdmissionRepository (Join-Path $TestDrive 'winghostty') @{ 'provider.txt' = 'winghostty' @@ -113,14 +143,25 @@ Describe 'Windows validation candidate admission' { $binding = Join-Path $workspace 'binding\ValidationFixtureBindings.dll' $zig0152 = Join-Path $workspace 'tools\zig-0.15.2\zig.exe' $zig0160 = Join-Path $workspace 'tools\zig-0.16.0\zig.exe' - $section = Join-Path $workspace 'manifest\sections.json' - foreach ($file in @($binding, $zig0152, $zig0160, $section)) { + $manifestRoot = Join-Path $workspace 'manifest' + $manifests = @( + (Join-Path $manifestRoot 'host.json'), + (Join-Path $manifestRoot 'ownership.json'), + (Join-Path $manifestRoot 'ui.json') + ) + foreach ($file in @($binding, $zig0152, $zig0160) + $manifests) { $null = New-Item -ItemType Directory -Force -Path (Split-Path $file -Parent) } [IO.File]::WriteAllBytes($binding, [byte[]](1, 2, 3)) [IO.File]::WriteAllBytes($zig0152, [byte[]](2, 3, 4)) [IO.File]::WriteAllBytes($zig0160, [byte[]](3, 4, 5)) - [IO.File]::WriteAllText($section, '{"section":"fixture"}', [Text.UTF8Encoding]::new($false)) + foreach ($manifestPath in $manifests) { + [IO.File]::WriteAllText( + $manifestPath, + '{"section":"fixture"}', + [Text.UTF8Encoding]::new($false) + ) + } $validationRoot = Join-Path $TestDrive 'validation-root' $null = New-Item -ItemType Directory -Path $validationRoot $arguments = @{ @@ -133,7 +174,7 @@ Describe 'Windows validation candidate admission' { Zig0160 = $zig0160 ManifestPaths = @( (Join-Path $workspace 'graphcode-windows\provider-pins.json'), - $section + @($manifests) ) SourcePaths = @( (Join-Path $workspace 'Tools\windows\validate.ps1'), @@ -159,7 +200,12 @@ Describe 'Windows validation candidate admission' { $manifest.providers.zmx.tree | Should -BeExactly $zmx.Tree @($manifest.tools).Count | Should -Be 2 @($manifest.bindings).Count | Should -Be 1 - @($manifest.manifests).Count | Should -Be 2 + @($manifest.manifests).Count | Should -Be 4 + @($manifest.manifests | Select-Object -ExpandProperty path | Sort-Object -Unique).Count | + Should -Be 4 + foreach ($manifestPath in $manifests) { + @($manifest.manifests | Where-Object path -ceq $manifestPath).Count | Should -Be 1 + } @($manifest.sources).Count | Should -Be 2 ($first.Sha256 -cmatch '^[A-F0-9]{64}$') | Should -BeTrue diff --git a/Tools/windows/validate.ps1 b/Tools/windows/validate.ps1 index 273ad4531..c802f4811 100644 --- a/Tools/windows/validate.ps1 +++ b/Tools/windows/validate.ps1 @@ -1297,15 +1297,7 @@ function Invoke-Task([string] $name) { (Join-Path $bindingDirectory "ValidationFixtureBindings.dll"), (Join-Path $bindingDirectory "WindowsValidationBindings.dll") ) | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } - $manifestPaths = @( - (Join-Path $repoRoot "graphcode-windows\provider-pins.json"), - (Join-Path $repoRoot "graphcode-windows\build.zig.zon"), - (Join-Path $repoRoot "graphcode-windows\build.zig"), - (Join-Path $repoRoot "Tools\windows\ValidationRunner\ValidationRunner.csproj"), - @(Get-ChildItem -LiteralPath ( - Join-Path $repoRoot "Tools\windows\ValidationRunner\Manifests" - ) -Filter "*.json" -File | ForEach-Object FullName) - ) + $manifestPaths = Get-WindowsShellCandidateManifestPaths -WorkspaceRoot $repoRoot $candidateAdmission = Write-WindowsShellCandidateAdmission ` -WorkspaceRoot $repoRoot ` -ValidationRoot $env:GRAPHCODE_VALIDATION_ROOT ` From 2bfff41be477237e865a79d9d85b6b8fe0a0bd5f Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Wed, 11 Nov 2026 14:53:45 -0700 Subject: [PATCH 4/4] Recognize exact owned sketch modal transitions after popup input Use a pointer-only expected-modal route with retained process, direct owner, class, title, visibility and foreground checks. Return typed completion without Enter or selection fallback; preserve ordinary popup ownership and independent gate modal assertions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens (cherry picked from commit 5beca8de64c692eebd9b25b2c2d277901e47c8ca) --- .../ValidationRunner/Manifests/ui.json | 1 + Tools/windows/ValidationRunner/README.md | 10 ++++ .../Ui/Fixtures/InputFixture.cs | 3 ++ .../Ui/Fixtures/PopupEffectFixture.cs | 22 +++++++-- .../ValidationRunner/Ui/ManagedUiSuite.cs | 44 +++++++++++++++++ .../Ui/Production/GraphCodeUiaGateState.cs | 6 +++ .../Ui/Production/UiaInputSafety.cs | 48 ++++++++++++++++++- .../ValidationRunner/Ui/UiSourceContracts.ps1 | 17 +++++-- .../Ui/source-assertions.json | 2 +- Tools/windows/uia-live-gate.ps1 | 21 ++++++-- 10 files changed, 161 insertions(+), 13 deletions(-) diff --git a/Tools/windows/ValidationRunner/Manifests/ui.json b/Tools/windows/ValidationRunner/Manifests/ui.json index ca8c0a7d1..ac90d434c 100644 --- a/Tools/windows/ValidationRunner/Manifests/ui.json +++ b/Tools/windows/ValidationRunner/Manifests/ui.json @@ -1,6 +1,7 @@ { "units": [ { "id": "ui.navigation.headless-runner-plan", "owner": "Ui", "minimumCount": 14, "exactCount": 14, "requiredGroups": [] }, + { "id": "ui.popup.effect.expected-modal-transition", "owner": "Ui", "minimumCount": 1, "exactCount": 1, "requiredGroups": [] }, { "id": "ui.popup.receipt.cancelled-after-queued-input", "owner": "Ui", "minimumCount": 1, "exactCount": 1, "requiredGroups": [] }, { "id": "ui.navigation.selection-event-controls", "owner": "Ui", "minimumCount": 12, "exactCount": 12, "requiredGroups": ["graph", "quick-chats", "project", "loop", "chat"] }, diff --git a/Tools/windows/ValidationRunner/README.md b/Tools/windows/ValidationRunner/README.md index 6474b5aa8..489874a09 100644 --- a/Tools/windows/ValidationRunner/README.md +++ b/Tools/windows/ValidationRunner/README.md @@ -188,6 +188,16 @@ return. It also checks that disabling tracing preserves the original operation counts. Tracing adds no input, activation, retries or sleeps, and is off unless both flags match exactly. +Known sketch-promotion actions use `ClickPopupMenuItemForModal` with the exact +expected title. After the same two mouse events, this pointer-only route uses +the existing 20-by-10ms observation budget to require a closed popup and the +foreground, enabled, visible `GraphCodeSheetHost` with that exact title, direct +owner and original held process. It returns `ExpectedOwnedModal` plus the HWND, +not inferred menu selection. No Enter or selection fallback is sent on this +route; missing, foreign, stale or mismatched modal identity refuses. Ordinary +popup ownership is unchanged, with a fresh guard before any post-click +selection fallback. The gate still runs its independent modal assertions. + UIA, packaging contracts, shell ownership, and managed/native tests consume those same implementations. The loader verifies the exact file/type, worktree, current source and compiler-reference fingerprints, and loaded module identity. diff --git a/Tools/windows/ValidationRunner/Ui/Fixtures/InputFixture.cs b/Tools/windows/ValidationRunner/Ui/Fixtures/InputFixture.cs index ea5d3c7e7..c8cc56029 100644 --- a/Tools/windows/ValidationRunner/Ui/Fixtures/InputFixture.cs +++ b/Tools/windows/ValidationRunner/Ui/Fixtures/InputFixture.cs @@ -5,6 +5,9 @@ using GraphCode.Windows; namespace GraphCode.Validation.Ui.Fixtures { public sealed class InputFixture : IUiaInputOperations { + public IntPtr WindowOwner(IntPtr window) => throw new InvalidOperationException("Not a modal operation"); + public string WindowClass(IntPtr window) => throw new InvalidOperationException("Not a modal operation"); + public string WindowTitle(IntPtr window) => throw new InvalidOperationException("Not a modal operation"); diff --git a/Tools/windows/ValidationRunner/Ui/Fixtures/PopupEffectFixture.cs b/Tools/windows/ValidationRunner/Ui/Fixtures/PopupEffectFixture.cs index 4239a6378..3a979054b 100644 --- a/Tools/windows/ValidationRunner/Ui/Fixtures/PopupEffectFixture.cs +++ b/Tools/windows/ValidationRunner/Ui/Fixtures/PopupEffectFixture.cs @@ -45,7 +45,8 @@ public uint GetMenuState(IntPtr menu, uint position, uint flags) { } public void Sleep(uint milliseconds) { } public uint SendInput(uint count, Input[] inputs, int size) { - MouseCalls++; Visible = Scenario == "foreign-before-enter" || Scenario == "owned-enter"; + MouseCalls++; Visible = Scenario == "foreign-before-enter" || Scenario == "owned-enter" || + Scenario.StartsWith("modal", StringComparison.Ordinal); if (Scenario == "cancel-after-queued-input") ReturnedCommand = 0; return count; } @@ -56,6 +57,12 @@ public bool PostMessage(IntPtr window, uint message, UIntPtr wparam, IntPtr lpar } public IntPtr GetForegroundWindow() { ForegroundReads++; + if (Scenario.StartsWith("modal", StringComparison.Ordinal) && MouseCalls > 0) { + if (Scenario == "modal-no-transition") return (IntPtr)42; + if (Scenario == "modal-late" && ForegroundReads == 3) return (IntPtr)42; + if (Scenario != "modal-popup-open") Visible = false; + return Scenario == "modal-foreign" ? (IntPtr)99 : (IntPtr)45; + } if (Scenario == "unhilited-metadata-fault" && ForegroundReads == 2) throw new InvalidOperationException("Owned metadata fixture fault"); return Scenario == "foreign-foreground" || @@ -67,14 +74,21 @@ public IntPtr WindowFromPoint(ScreenPoint point) { if (Scenario == "cancel-after-queued-input" && MouseCalls > 0) return (IntPtr)99; return Scenario == "underlying-shell-hit" ? (IntPtr)42 : (IntPtr)44; } - public bool IsRetainedProcessAlive(uint processId) { return processId == 4242 && Scenario != "foreign-owner-all"; } + public bool IsRetainedProcessAlive(uint processId) { + return processId == 4242 && Scenario != "foreign-owner-all" && + !(Scenario == "modal-stale-owner" && MouseCalls > 0); + } public uint WindowProcessId(IntPtr window) { return Scenario == "foreign-owner-all" || window == (IntPtr)99 || + (window == (IntPtr)45 && Scenario == "modal-wrong-pid") || (window == (IntPtr)44 && Scenario == "foreign-hit") ? 7777u : 4242u; } public IntPtr GetAncestor(IntPtr window, uint flags) { return window == (IntPtr)44 ? (IntPtr)43 : window; } - public bool WindowIsVisible(IntPtr window) => IsWindowVisible(window); - public bool WindowIsEnabled(IntPtr window) => throw new InvalidOperationException("Not a popup operation"); + public bool WindowIsVisible(IntPtr window) => window == (IntPtr)45 ? Scenario != "modal-hidden" : IsWindowVisible(window); + public bool WindowIsEnabled(IntPtr window) => window == (IntPtr)45 && Scenario != "modal-disabled"; + public IntPtr WindowOwner(IntPtr window) => Scenario == "modal-wrong-owner" ? (IntPtr)99 : (IntPtr)42; + public string WindowClass(IntPtr window) => Scenario == "modal-wrong-class" ? "Other" : "GraphCodeSheetHost"; + public string WindowTitle(IntPtr window) => Scenario == "modal-wrong-title" ? "Other" : "Promote sketch to Goal"; public IntPtr FocusedControlInDialog(IntPtr window) => throw new InvalidOperationException("Not a popup operation"); public IntPtr FindPopupForMenu(uint processId, IntPtr menu) => throw new InvalidOperationException("Not a popup operation"); public bool ResolvesToControl(IntPtr target, IntPtr owner, ScreenPoint point) => throw new InvalidOperationException("Not a popup operation"); diff --git a/Tools/windows/ValidationRunner/Ui/ManagedUiSuite.cs b/Tools/windows/ValidationRunner/Ui/ManagedUiSuite.cs index 62cac81f9..c4d7b8a24 100644 --- a/Tools/windows/ValidationRunner/Ui/ManagedUiSuite.cs +++ b/Tools/windows/ValidationRunner/Ui/ManagedUiSuite.cs @@ -100,6 +100,50 @@ private static IReadOnlyList CreateCases() foreach (string name in effects) cases.Add(new UiCase($"ui.popup.effect.{name}", () => RunPopupEffect(name), "ValidationRunner.Tests.ps1:1256-1328")); + cases.Add(new UiCase("ui.popup.effect.expected-modal-transition", () => + { + var probe = new PopupEffectFixture(); + var input = new UiaInputSafety(probe); + var method = typeof(UiaInputSafety).GetMethod("ClickPopupMenuItemForModal", + new[] { typeof(IntPtr), typeof(IntPtr), typeof(int), typeof(int), typeof(uint), typeof(string) }); + ActivationCases.Require(method is not null, "RED: missing exact expected-modal popup transition route"); + int subcases = 0; + foreach (string scenario in new[] { "modal", "modal-late", "modal-foreign", "modal-wrong-title", + "modal-wrong-owner", "modal-wrong-class", "modal-disabled", "modal-hidden", "modal-stale-owner", + "modal-wrong-pid", "modal-popup-open", "modal-no-transition", "modal-no-expectation" }) + { + probe.Reset(scenario); + object? hit = null; + Exception? failure = null; + try + { + if (scenario == "modal-no-expectation") + hit = input.ClickPopupMenuItem(new IntPtr(43), new IntPtr(42), 0, 5103, 4242); + else + hit = method!.Invoke(input, new object[] { new IntPtr(43), new IntPtr(42), 0, 5103, 4242u, "Promote sketch to Goal" }); + } + catch (Exception error) { failure = error.GetBaseException(); } + bool accepted = scenario is "modal" or "modal-late"; + ActivationCases.Require((hit is not null) == accepted && (failure is null) == accepted && + probe.MouseCalls == 1 && probe.KeyCalls == 0 && probe.SelectItemCalls == 0, + $"Expected modal transition ownership/input contract differs: {scenario}"); + if (hit is not null) + { + var completion = hit.GetType().GetProperty("Completion")!.GetValue(hit); + var modal = hit.GetType().GetProperty("ModalWindow")!.GetValue(hit); + ActivationCases.Require(completion!.ToString() == "ExpectedOwnedModal" && + (IntPtr)modal! == new IntPtr(45), "Expected modal needs a typed identity receipt"); + } + subcases++; + } + probe.Reset("owned"); + Exception? emptyExpectation = null; + try { method!.Invoke(input, new object[] { new IntPtr(43), new IntPtr(42), 0, 5103, 4242u, "" }); } + catch (Exception error) { emptyExpectation = error.GetBaseException(); } + ActivationCases.Require(emptyExpectation is ArgumentException && probe.MouseCalls == 0 && + probe.KeyCalls == 0 && probe.SelectItemCalls == 0, "Empty modal expectation must refuse before input"); + ActivationCases.Require(subcases == 13, "Expected thirteen controlled transitions plus empty-expectation refusal"); + }, "Actual popup core; exact expected owned modal after pointer input, no native calls")); cases.Add(new UiCase("ui.popup.receipt.cancelled-after-queued-input", () => { string? oldGate = Environment.GetEnvironmentVariable("GRAPHCODE_UIA_GATE"); diff --git a/Tools/windows/ValidationRunner/Ui/Production/GraphCodeUiaGateState.cs b/Tools/windows/ValidationRunner/Ui/Production/GraphCodeUiaGateState.cs index 19f4aed3e..794fb9fde 100644 --- a/Tools/windows/ValidationRunner/Ui/Production/GraphCodeUiaGateState.cs +++ b/Tools/windows/ValidationRunner/Ui/Production/GraphCodeUiaGateState.cs @@ -21,6 +21,9 @@ public static void RegisterClientSideProviderAssembly(System.Reflection.Assembly } private sealed class NativeInputOperations : IUiaInputOperations { + public IntPtr WindowOwner(IntPtr window) { return GraphCodeUiaGateState.WindowOwner(window); } + public string WindowClass(IntPtr window) { return GraphCodeUiaGateState.WindowClass(window); } + public string WindowTitle(IntPtr window) { return GraphCodeUiaGateState.WindowTitle(window); } public bool IsRetainedProcessAlive(uint processId) { return GraphCodeUiaGateState.IsRetainedProcessAlive(processId); } public uint WindowProcessId(IntPtr window) { return GraphCodeUiaGateState.WindowProcessId(window); } public bool WindowIsVisible(IntPtr window) { return GraphCodeUiaGateState.WindowIsVisible(window); } @@ -744,6 +747,9 @@ public static bool IsOwnedPopupInput( ) { return UiaInputSafety.IsOwnedPopupInput(owner, popup, expectedProcessId, popupProcessId, foregroundProcessId, foregroundRoot, pointProcessId, pointRoot, popupVisible); } public static PopupItemHit ClickPopupMenuItem(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId) { return InputSafety.ClickPopupMenuItem(popup, owner, position, commandId, expectedProcessId); } + public static PopupItemHit ClickPopupMenuItemForModal(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId, string expectedModalTitle) { + return InputSafety.ClickPopupMenuItemForModal(popup, owner, position, commandId, expectedProcessId, expectedModalTitle); + } public static PopupItemHit ClickPopupMenuItemStrict(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId) { return InputSafety.ClickPopupMenuItemStrict(popup, owner, position, commandId, expectedProcessId); } private static void RequireOwnedPopupForeground(IntPtr popup, IntPtr owner, uint expectedProcessId) { InputSafety.RequireOwnedPopupForeground(popup, owner, expectedProcessId); } // Sidebar.updateBannerRect/updateBannerAt are pixel-only hit-test geometry with diff --git a/Tools/windows/ValidationRunner/Ui/Production/UiaInputSafety.cs b/Tools/windows/ValidationRunner/Ui/Production/UiaInputSafety.cs index 037ef5583..1632b52d8 100644 --- a/Tools/windows/ValidationRunner/Ui/Production/UiaInputSafety.cs +++ b/Tools/windows/ValidationRunner/Ui/Production/UiaInputSafety.cs @@ -9,6 +9,9 @@ public interface IUiaInputOperations { uint WindowProcessId(IntPtr window); bool WindowIsVisible(IntPtr window); bool WindowIsEnabled(IntPtr window); + IntPtr WindowOwner(IntPtr window); + string WindowClass(IntPtr window); + string WindowTitle(IntPtr window); IntPtr GetForegroundWindow(); IntPtr FocusedControlInDialog(IntPtr window); IntPtr GetAncestor(IntPtr window, uint flags); @@ -66,6 +69,8 @@ public struct KeyInputRecord { public uint Pad0, Pad1; } public sealed class PopupItemHit { + public PopupCompletion Completion { get; set; } + public IntPtr ModalWindow { get; set; } public PopupInputReceipt InputReceipt { get; set; } public int Position, ItemId, Left, Top, Right, Bottom; public int ScreenX, ScreenY, ClientX, ClientY, CursorBeforeX, CursorBeforeY; @@ -73,6 +78,7 @@ public sealed class PopupItemHit { public bool Hilite, UsedKeyboardFallback, UsedSelectItemFallback; public bool HiliteAtEnterFallback, HiliteBeforeEnter; } +public enum PopupCompletion { InputReceiptOnly, ExpectedOwnedModal } public sealed class PopupInputSample { public string Phase { get; set; } public long Timestamp { get; set; } @@ -281,13 +287,19 @@ public static bool IsOwnedPopupInput( public PopupItemHit ClickPopupMenuItem(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId) { return ClickPopupMenuItemCore(popup, owner, position, commandId, expectedProcessId, true); } +public PopupItemHit ClickPopupMenuItemForModal(IntPtr popup, IntPtr owner, int position, int commandId, + uint expectedProcessId, string expectedModalTitle) { + if (String.IsNullOrWhiteSpace(expectedModalTitle)) + throw new ArgumentException("An exact expected modal title is required", nameof(expectedModalTitle)); + return ClickPopupMenuItemCore(popup, owner, position, commandId, expectedProcessId, false, expectedModalTitle); + } public PopupItemHit ClickPopupMenuItemStrict(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId) { var hit = ClickPopupMenuItemCore(popup, owner, position, commandId, expectedProcessId, false); if (hit == null) throw new InvalidOperationException("Strict popup target identity or geometry is invalid; no input was injected"); return hit; } -private PopupItemHit ClickPopupMenuItemCore(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId, bool allowFallback) { +private PopupItemHit ClickPopupMenuItemCore(IntPtr popup, IntPtr owner, int position, int commandId, uint expectedProcessId, bool allowFallback, string expectedModalTitle = null) { PopupInputReceipt receipt = Environment.GetEnvironmentVariable("GRAPHCODE_UIA_GATE") == "1" && Environment.GetEnvironmentVariable("GRAPHCODE_UIA_EDGE_ACTION_TRACE") == "1" ? new PopupInputReceipt() : null; @@ -410,6 +422,29 @@ bool ReadMenuHilite() { } if (!hilite) throw new InvalidOperationException("Popup item did not acknowledge hover before click"); + PopupItemHit CompletedModal() { + if (expectedModalTitle == null) return null; + IntPtr modal = operations.GetForegroundWindow(); + IntPtr root = operations.GetAncestor(modal, 2); + if (root == owner || root == popup) return null; + if (modal == IntPtr.Zero || modal != root || + !operations.IsRetainedProcessAlive(expectedProcessId) || + operations.WindowProcessId(owner) != expectedProcessId || + operations.WindowProcessId(modal) != expectedProcessId || + operations.WindowOwner(modal) != owner || + !String.Equals(operations.WindowClass(modal), "GraphCodeSheetHost", StringComparison.Ordinal) || + !String.Equals(operations.WindowTitle(modal), expectedModalTitle, StringComparison.Ordinal) || + !operations.WindowIsVisible(modal) || !operations.WindowIsEnabled(modal) || + operations.IsWindowVisible(popup) || operations.GetForegroundWindow() != modal || + operations.WindowProcessId(modal) != expectedProcessId || operations.WindowOwner(modal) != owner) + throw new InvalidOperationException("Popup input ownership changed; expected modal identity was not proved"); + return new PopupItemHit { + Completion = PopupCompletion.ExpectedOwnedModal, ModalWindow = modal, InputReceipt = receipt, + Position = position, ItemId = commandId, Left = item.Left, Top = item.Top, Right = item.Right, Bottom = item.Bottom, + ScreenX = screenX, ScreenY = screenY, ClientX = point.X, ClientY = point.Y, + CursorBeforeX = before.X, CursorBeforeY = before.Y, CursorAtX = at.X, CursorAtY = at.Y, Hilite = hilite + }; + } var inputs = new[] { new Input { Type = 0, Mouse = new MouseInput { Flags = 0x0002 } }, new Input { Type = 0, Mouse = new MouseInput { Flags = 0x0004 } } @@ -432,6 +467,16 @@ bool ReadMenuHilite() { ObserveInput("after-send", (uint)inputs.Length, sent); if (sent != inputs.Length) throw new InvalidOperationException(String.Format("SendInput injected {0} of {1} popup mouse events: Win32Error={2}", sent, inputs.Length, Marshal.GetLastWin32Error())); + if (expectedModalTitle != null) { + for (int attempt = 0; attempt < 20; attempt++) { + var completedModal = CompletedModal(); + if (completedModal != null) return completedModal; + operations.Sleep(10); + } + var finalModal = CompletedModal(); + if (finalModal != null) return finalModal; + throw new InvalidOperationException("Popup pointer input did not produce the exact expected owned modal; no fallback input was injected"); + } for (int attempt = 0; attempt < 20 && operations.IsWindowVisible(popup); attempt++) operations.Sleep(10); if (receipt != null && !operations.IsWindowVisible(popup)) ObserveInput("popup-closed", (uint)inputs.Length, sent); @@ -446,6 +491,7 @@ bool ReadMenuHilite() { // item ends TrackPopupMenu with command 0: the popup closes exactly as if // the item had been chosen, but no command reaches the shell. Re-assert // the intended item and prove its hilite immediately before Enter. + RequireOwnedPopupForeground(popup, owner, expectedProcessId); hiliteAtEnterFallback = ReadMenuHilite(); operations.SendMessage(popup, 0x01E5, (UIntPtr)position, IntPtr.Zero); hiliteBeforeEnter = ReadMenuHilite(); diff --git a/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 b/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 index 425c63b80..e4b2e5c5d 100644 --- a/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 +++ b/Tools/windows/ValidationRunner/Ui/UiSourceContracts.ps1 @@ -82,6 +82,7 @@ function Confirm-PopupSource([string] $Source) { try { $default = Read-CSharpMethod $Source 'public PopupItemHit ClickPopupMenuItem(' $strict = Read-CSharpMethod $Source 'public PopupItemHit ClickPopupMenuItemStrict(' + $modal = Read-CSharpMethod $Source 'public PopupItemHit ClickPopupMenuItemForModal(' $click = Read-CSharpMethod $Source 'private PopupItemHit ClickPopupMenuItemCore(' } catch { return $false } if ([regex]::Matches($default, '\bClickPopupMenuItemCore\(').Count -ne 1 -or @@ -91,10 +92,13 @@ function Confirm-PopupSource([string] $Source) { -not $strict.Contains('if (hit == null)') -or -not $strict.Contains('throw new InvalidOperationException("Strict popup target identity or geometry is invalid; no input was injected");') -or -not $strict.Contains('return hit;') -or - ($default + $strict) -match '\b(SendInput|PostMessage|SetForegroundWindow|SetFocus|BringWindowToTop)\(') { return $false } + [regex]::Matches($modal, '\bClickPopupMenuItemCore\(').Count -ne 1 -or + -not $modal.Contains('if (String.IsNullOrWhiteSpace(expectedModalTitle))') -or + -not $modal.Contains('return ClickPopupMenuItemCore(popup, owner, position, commandId, expectedProcessId, false, expectedModalTitle);') -or + ($default + $strict + $modal) -match '\b(SendInput|PostMessage|SetForegroundWindow|SetFocus|BringWindowToTop)\(') { return $false } if ([regex]::Matches($click, '\boperations\.SendInput\(').Count -ne 1 -or - [regex]::Matches($click, 'RequireOwnedPopupForeground\(popup, owner, expectedProcessId\);').Count -ne 2 -or - -not $click.Contains('int commandId, uint expectedProcessId, bool allowFallback)') -or + [regex]::Matches($click, 'RequireOwnedPopupForeground\(popup, owner, expectedProcessId\);').Count -ne 3 -or + -not $click.Contains('int commandId, uint expectedProcessId, bool allowFallback, string expectedModalTitle = null)') -or $click -match '\b(SetForegroundWindow|SetFocus|BringWindowToTop)\(') { return $false } $offset = 0 foreach ($needle in @( @@ -232,11 +236,18 @@ foreach ($case in $popupCases) { @{ from = 'if (hit == null)'; to = 'if (false)' }, @{ from = 'return hit;'; to = 'return ClickPopupMenuItemCore(popup, owner, position, commandId, expectedProcessId, false);' }, @{ from = 'private PopupItemHit ClickPopupMenuItemCore('; to = 'private PopupItemHit UnsharedPopupCore(' } + @{ from = 'expectedProcessId, false, expectedModalTitle);'; to = 'expectedProcessId, true, expectedModalTitle);' } + @{ from = 'if (String.IsNullOrWhiteSpace(expectedModalTitle))'; to = 'if (false)' } )) { Assert-UiContract ($inputSource.Contains($mutation.from)) 'Popup forwarding mutation did not change production source' Assert-UiContract (-not (Confirm-PopupSource $inputSource.Replace($mutation.from, $mutation.to))) ` 'Popup source contract accepted an unshared, fallback-enabled, non-refusing or replayed forwarding route' } + $nativeBindings = Read-SemanticSource (Join-Path $RepositoryRoot 'Tools\windows\ValidationRunner\Ui\Production\GraphCodeUiaGateState.cs') + Assert-UiContract ($nativeBindings.Contains('return InputSafety.ClickPopupMenuItemForModal(popup, owner, position, commandId, expectedProcessId, expectedModalTitle);') -and + $gateSource.Contains('Sketch-ClickMenu $subMenu $case.Command "Promote $title to $($case.Target)"') -and + $gateSource.Contains('$modal = Assert-SketchModal "Promote $title to $($case.Target)"')) ` + 'Known sketch promotion must forward the exact modal expectation and retain independent modal assertions' } } } diff --git a/Tools/windows/ValidationRunner/Ui/source-assertions.json b/Tools/windows/ValidationRunner/Ui/source-assertions.json index 74c00a573..823032db8 100644 --- a/Tools/windows/ValidationRunner/Ui/source-assertions.json +++ b/Tools/windows/ValidationRunner/Ui/source-assertions.json @@ -3406,7 +3406,7 @@ "left": { "right": { "kind": "literal", - "value": "(?s)private PopupItemHit ClickPopupMenuItemCore\\([^)]*bool allowFallback\\)\\s*\\{(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?bool ReadMenuHilite\\(\\)\\s*\\{\\s*rawMenuState = operations\\.GetMenuState\\(menu, \\(uint\\)position, 0x0400\\);\\s*menuStateObserved = true;\\s*if \\(rawMenuState == UInt32\\.MaxValue\\)\\s*throw PopupStateFailure\\(\"Popup menu state unavailable; no further input was injected\"\\);\\s*return \\(rawMenuState & 0x0080\\) != 0;\\s*\\}(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?for \\(int attempt = 0; attempt < 20 && operations\\.IsWindowVisible\\(popup\\); attempt\\+\\+\\) operations\\.Sleep\\(10\\);\\s*(?:if \\(receipt != null && !operations\\.IsWindowVisible\\(popup\\)\\)\\s*ObserveInput\\(\"popup-closed\", \\(uint\\)inputs\\.Length, sent\\);\\s*)?bool keyboardFallback = false;\\s*bool hiliteAtEnterFallback = false;\\s*bool hiliteBeforeEnter = false;\\s*if \\(operations\\.IsWindowVisible\\(popup\\)\\)\\s*\\{\\s*if \\(!allowFallback\\)\\s*throw new InvalidOperationException\\(\"Strict popup remained open after pointer input; no selection or keyboard fallback was emitted\"\\);(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?hiliteAtEnterFallback = ReadMenuHilite\\(\\);\\s*operations\\.SendMessage\\(popup, 0x01E5, \\(UIntPtr\\)position, IntPtr\\.Zero\\);\\s*hiliteBeforeEnter = ReadMenuHilite\\(\\);\\s*\\}\\s*if \\(operations\\.IsWindowVisible\\(popup\\)\\)\\s*\\{\\s*if \\(!hiliteBeforeEnter\\)\\s*throw new InvalidOperationException\\(String\\.Format\\(\"Popup item \\{0\\} was not hilited before the Enter fallback \\(hilite at fallback=\\{1\\}\\)\", commandId, hiliteAtEnterFallback\\)\\);\\s*RequireOwnedPopupForeground\\(popup, owner, expectedProcessId\\);\\s*keyboardFallback =\\s*operations\\.PostMessage\\(popup, 0x0100, \\(UIntPtr\\)0x0D, IntPtr\\.Zero\\)" + "value": "(?s)private PopupItemHit ClickPopupMenuItemCore\\([^)]*bool allowFallback, string expectedModalTitle = null\\)\\s*\\{(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?bool ReadMenuHilite\\(\\)\\s*\\{\\s*rawMenuState = operations\\.GetMenuState\\(menu, \\(uint\\)position, 0x0400\\);\\s*menuStateObserved = true;\\s*if \\(rawMenuState == UInt32\\.MaxValue\\)\\s*throw PopupStateFailure\\(\"Popup menu state unavailable; no further input was injected\"\\);\\s*return \\(rawMenuState & 0x0080\\) != 0;\\s*\\}(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?for \\(int attempt = 0; attempt < 20 && operations\\.IsWindowVisible\\(popup\\); attempt\\+\\+\\) operations\\.Sleep\\(10\\);\\s*(?:if \\(receipt != null && !operations\\.IsWindowVisible\\(popup\\)\\)\\s*ObserveInput\\(\"popup-closed\", \\(uint\\)inputs\\.Length, sent\\);\\s*)?bool keyboardFallback = false;\\s*bool hiliteAtEnterFallback = false;\\s*bool hiliteBeforeEnter = false;\\s*if \\(operations\\.IsWindowVisible\\(popup\\)\\)\\s*\\{\\s*if \\(!allowFallback\\)\\s*throw new InvalidOperationException\\(\"Strict popup remained open after pointer input; no selection or keyboard fallback was emitted\"\\);(?:(?!operations\\.PostMessage\\(popup, 0x0100).)*?hiliteAtEnterFallback = ReadMenuHilite\\(\\);\\s*operations\\.SendMessage\\(popup, 0x01E5, \\(UIntPtr\\)position, IntPtr\\.Zero\\);\\s*hiliteBeforeEnter = ReadMenuHilite\\(\\);\\s*\\}\\s*if \\(operations\\.IsWindowVisible\\(popup\\)\\)\\s*\\{\\s*if \\(!hiliteBeforeEnter\\)\\s*throw new InvalidOperationException\\(String\\.Format\\(\"Popup item \\{0\\} was not hilited before the Enter fallback \\(hilite at fallback=\\{1\\}\\)\", commandId, hiliteAtEnterFallback\\)\\);\\s*RequireOwnedPopupForeground\\(popup, owner, expectedProcessId\\);\\s*keyboardFallback =\\s*operations\\.PostMessage\\(popup, 0x0100, \\(UIntPtr\\)0x0D, IntPtr\\.Zero\\)" }, "left": { "kind": "resource", diff --git a/Tools/windows/uia-live-gate.ps1 b/Tools/windows/uia-live-gate.ps1 index 037a56c4a..1a21e3c56 100644 --- a/Tools/windows/uia-live-gate.ps1 +++ b/Tools/windows/uia-live-gate.ps1 @@ -12658,11 +12658,24 @@ try { cardBounds = $cardRect; canvasBounds = $canvasRect; pans = $pans.ToArray() } } - function Sketch-ClickMenu($menu, [int] $id) { + function Sketch-ClickMenu($menu, [int] $id, [string] $ExpectedModalTitle = "") { $item = @($menu.items | Where-Object { $_.Id -eq $id -and $_.Enabled }) Require ($item.Count -eq 1) "sketch/custody popup missing enabled ${id}: $(Format-PopupMenuItems $menu.items)" - $click = [GraphCodeUiaGateState]::ClickPopupMenuItem($menu.popup, $renameShellWindow, - [int]$item[0].Position, $id, [uint32]$renameProcess.Id) + if ($ExpectedModalTitle) { + Require ($id -in @(5116, 5117, 5118)) "Only sketch promotion commands declare an expected modal" + $click = [GraphCodeUiaGateState]::ClickPopupMenuItemForModal($menu.popup, $renameShellWindow, + [int]$item[0].Position, $id, [uint32]$renameProcess.Id, $ExpectedModalTitle) + Require ($click.Completion.ToString() -ceq "ExpectedOwnedModal" -and $click.ModalWindow -ne [IntPtr]::Zero) ` + "Sketch promotion did not return an exact owned modal completion receipt" + Write-Host ("UIA_SKETCH_MODAL_COMPLETION_EVIDENCE=" + ([ordered]@{ + command = $id; completion = $click.Completion.ToString(); modal = $click.ModalWindow.ToInt64() + owner = $renameShellWindow.ToInt64(); process = $renameProcess.Id; title = $ExpectedModalTitle + keyboardFallback = $click.UsedKeyboardFallback; selectItemFallback = $click.UsedSelectItemFallback + } | ConvertTo-Json -Compress)) + } else { + $click = [GraphCodeUiaGateState]::ClickPopupMenuItem($menu.popup, $renameShellWindow, + [int]$item[0].Position, $id, [uint32]$renameProcess.Id) + } if ($null -ne $click) { Write-Host "UIA_SKETCH_MENU_CLICK command=$id hilite=$($click.Hilite) selectItemFallback=$($click.UsedSelectItemFallback) enterFallback=$($click.UsedKeyboardFallback) hiliteAtEnterFallback=$($click.HiliteAtEnterFallback) hiliteBeforeEnter=$($click.HiliteBeforeEnter)" } @@ -12750,7 +12763,7 @@ try { Require ($subPopup -ne [IntPtr]::Zero) ` "sketch '$title' real Promote to submenu popup did not open by hover or keyboard" $subMenu = @{ popup = $subPopup; items = $subItems } - $menuClick = Sketch-ClickMenu $subMenu $case.Command + $menuClick = Sketch-ClickMenu $subMenu $case.Command "Promote $title to $($case.Target)" $menuClick.submenuRevealed = $submenuRevealed $menuClick.submenuKeyboardReveal = $submenuKeyboardReveal $modal = Assert-SketchModal "Promote $title to $($case.Target)"