From 42bcb461f1d906fa51fe4a6ee0fa2fc2951e49b1 Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Wed, 11 Nov 2026 17:11:47 -0700 Subject: [PATCH 1/3] Match Windows terminal surface appearance Apply the pinned Winghostty appearance contract and reserve macOS-equivalent terminal padding and split dividers while preserving font and DPI ownership. Signed-off-by: Colin Neilens Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- AGENTS.md | 2 +- Tools/windows/Convert-CanvasPaintArtifact.ps1 | 2 +- Tools/windows/PACKAGING.md | 2 +- .../Tests/PreviewCore.Qualification.ps1 | 1070 ++++++++--------- Tools/windows/Tests/PreviewCore.Tests.ps1 | 994 +++++++-------- Tools/windows/Tests/TerminalGate.Tests.ps1 | 2 +- Tools/windows/Tests/VisualBaseline.Tests.ps1 | 2 +- Tools/windows/Tests/WindowsShell.Tests.ps1 | 2 +- graphcode-windows/README.md | 9 +- graphcode-windows/provider-pins.json | 2 +- graphcode-windows/src/TerminalSurface.zig | 239 +++- .../spikes/windows-terminal-gate/README.md | 2 +- .../windows-terminal-gate/provider-pins.json | 2 +- 13 files changed, 1271 insertions(+), 1059 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cc07de2b..6d68be50 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -347,7 +347,7 @@ These are the single source of truth. Never silently upgrade one. | Swift | 6.3.3 | `.github/workflows/windows-*.yml` (`swift-version: swift-6.3.3-release`), `Tools/windows/bootstrap.ps1` | | Zig (shell) | 0.15.2 | `mise.toml`, `graphcode-windows/build.zig.zon` (`minimum_zig_version`) | | Zig (zmx only) | 0.16.0 | `graphcode-windows/provider-pins.json` | -| Winghostty | `e0a5579f3b470bede72294d661282a391c502ace` | `graphcode-windows/provider-pins.json` | +| Winghostty | `cac8f5f148fd5015d49e81e169ce9006ac7156ea` | `graphcode-windows/provider-pins.json` | | zmx | `785b3fd15dcafd1882b495c831a10f98c201b908` | `graphcode-windows/provider-pins.json` | If a build fails because a tool is missing or the wrong version, rerun diff --git a/Tools/windows/Convert-CanvasPaintArtifact.ps1 b/Tools/windows/Convert-CanvasPaintArtifact.ps1 index 49fd419c..1022b355 100644 --- a/Tools/windows/Convert-CanvasPaintArtifact.ps1 +++ b/Tools/windows/Convert-CanvasPaintArtifact.ps1 @@ -980,7 +980,7 @@ namespace GraphCode.PaintArtifactTests osVersion = [Environment]::OSVersion.Version.ToString() platform = [Environment]::OSVersion.Platform.ToString() zigVersion = "0.15.2" - winghosttyPin = "e0a5579f3b470bede72294d661282a391c502ace" + winghosttyPin = "cac8f5f148fd5015d49e81e169ce9006ac7156ea" pinEvidenceScope = "Expected repository pins; actual Zig executable and Winghostty checkout identity are not measured by the converter." } dimensions = $receipt.dimensions diff --git a/Tools/windows/PACKAGING.md b/Tools/windows/PACKAGING.md index 37156926..acc415f5 100644 --- a/Tools/windows/PACKAGING.md +++ b/Tools/windows/PACKAGING.md @@ -420,7 +420,7 @@ The current accepted public provider commits are: | Provider | Pinned commit | Retained branch | |---|---|---| -| [coneilen/winghostty](https://github.com/coneilen/winghostty/commit/e0a5579f3b470bede72294d661282a391c502ace) | `e0a5579f3b470bede72294d661282a391c502ace` | `graphcode-host` | +| [coneilen/winghostty](https://github.com/coneilen/winghostty/commit/cac8f5f148fd5015d49e81e169ce9006ac7156ea) | `cac8f5f148fd5015d49e81e169ce9006ac7156ea` | `graphcode-host` | | [coneilen/zmx](https://github.com/coneilen/zmx/commit/785b3fd15dcafd1882b495c831a10f98c201b908) | `785b3fd15dcafd1882b495c831a10f98c201b908` | `graphcode-quickchat-hang` | The annotated `graphcode-windows-baseline-2026-09-17` tags remain historical diff --git a/Tools/windows/Tests/PreviewCore.Qualification.ps1 b/Tools/windows/Tests/PreviewCore.Qualification.ps1 index b7f8ade2..46c9c821 100644 --- a/Tools/windows/Tests/PreviewCore.Qualification.ps1 +++ b/Tools/windows/Tests/PreviewCore.Qualification.ps1 @@ -1,535 +1,535 @@ -<# -.SYNOPSIS - Prepares and checks one installed production-daemon/real-backend preview flight. -.DESCRIPTION - Prepare verifies a caller-selected ZIP and creates only an owned synthetic - local project and an unexecuted flight packet. VerifyEvidence checks actual, - reviewed CORE evidence; it does not qualify a preview release or authorize - publication. Upgrade/predecessor, DPI/IME, destructive, tray/recovery and - wider CI/release gates remain in investigation\windows-preview-release-plan.md. - Neither command installs, launches, authenticates, drives UI, or manages - processes/tasks. Backend/version and every live permission are chosen later. - Keep credentials, environment/command-line dumps, foreign UI, and private - code out of the packet and its evidence. Checksums are not publisher trust. -.EXAMPLE - .\PreviewCore.Qualification.ps1 -Command Prepare -Package $zip ` - -ExpectedSource $source -ExpectedSha256 $hash -RunRoot $ownedNewFlightRoot -.EXAMPLE - .\PreviewCore.Qualification.ps1 -Command VerifyEvidence ` - -EvidencePath $completedPacket -ExpectedSource $source -ExpectedSha256 $hash -#> -[CmdletBinding()] -param( - [ValidateSet("Prepare", "VerifyEvidence")] - [string] $Command, - [string] $Package, - [string] $ExpectedSource, - [string] $ExpectedSha256, - [string] $RunRoot, - [string] $EvidencePath, - [switch] $HelpersOnly -) - -$ErrorActionPreference = "Stop" - -function Assert-PreviewCore($condition, [string] $message) { - if (-not $condition) { throw "PreviewCore: $message" } -} - -function Test-PreviewCoreInteger($value) { - return $value -is [int] -or $value -is [long] -} - -function Assert-PreviewCoreHash([string] $value, [int] $length, [string] $label) { - Assert-PreviewCore ($value -cmatch "^[0-9a-f]{$length}$") "invalid $label" -} - -function Assert-PreviewCoreTrue($value, [string] $label) { - Assert-PreviewCore ($value -is [bool] -and $value) "$label must be witnessed true" -} - -function Assert-PreviewCoreFalse($value, [string] $label) { - Assert-PreviewCore ($value -is [bool] -and -not $value) "$label must be explicit false" -} - -function Assert-PreviewCoreText($value, [string] $label) { - Assert-PreviewCore ($value -is [string] -and -not [string]::IsNullOrWhiteSpace($value) -and - $value.Length -le 512 -and $value -notmatch '^(?i:unknown|notexecuted|todo|tbd|n/a)$') "missing or invalid $label" -} - -function Assert-PreviewCorePath([string] $path) { - Assert-PreviewCore ([IO.Path]::IsPathRooted($path) -and $path -notmatch '^\\\\') "owned path must be local and absolute" - $current = [IO.Path]::GetFullPath($path) - while ($current) { - if (Test-Path -LiteralPath $current) { - $item = Get-Item -LiteralPath $current -Force - Assert-PreviewCore (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) "owned path contains a reparse point" - } - $parent = [IO.Directory]::GetParent($current) - $current = if ($parent) { $parent.FullName } else { $null } - } -} - -function Resolve-PreviewCoreChild([string] $root, [string] $relative) { - Assert-PreviewCore ($relative -and $relative -notmatch '[<>:"/|?*\x00-\x1f]' -and - -not [IO.Path]::IsPathRooted($relative) -and - @($relative.Split('\') | Where-Object { $_ -in @("", ".", "..") -or $_ -match '[. ]$' -or - $_ -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$' }).Count -eq 0) "invalid owned relative path" - Assert-PreviewCorePath $root - $fullRoot = [IO.Path]::GetFullPath($root).TrimEnd('\') - $path = [IO.Path]::GetFullPath((Join-Path $fullRoot $relative)) - Assert-PreviewCore ($path.StartsWith($fullRoot + '\', [StringComparison]::OrdinalIgnoreCase)) "evidence escapes owned root" - Assert-PreviewCorePath $path - return $path -} - -function Get-PreviewCoreHash([string] $path) { - Assert-PreviewCorePath $path - Assert-PreviewCore (Test-Path -LiteralPath $path -PathType Leaf) "required owned file is missing" - return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -} - -function Get-PreviewCoreSteps { - @( - "artifact-custody", "installed-production", "production-core", - "actual-backend-terminal", "safe-stop-reopen" - ) -} - -function Get-PreviewCoreChecks([string] $id) { - switch ($id) { - "artifact-custody" { @("independentTagSourceWitness", "unsignedWarning") } - "installed-production" { @("ordinaryScheduledInstall", "productionEndpointReachable") } - "production-core" { @("rendered", "selected", "editorCancelUnchanged") } - "actual-backend-terminal" { @("actualAgent", "readableCurrentPixels", "requiredControls") } - "safe-stop-reopen" { @("intendedLoopStopped", "safeExit") } - } -} - -function New-PreviewCoreFacts([string] $id) { - $facts = [ordered]@{} - foreach ($name in (Get-PreviewCoreChecks $id)) { $facts[$name] = $null } - $textFields = switch ($id) { - "production-core" { @("selectedLoopId", "persistedLoopId", "graphTitle", "sidebarTitle", "checkDescription", "cancelDraft", "cancelBeforeSha256", "cancelAfterSha256") } - "actual-backend-terminal" { @("loopId", "backendKind", "backendVersion", "input", "output1", "output2", "terminalMode") } - "safe-stop-reopen" { @("stoppedLoopId", "stoppedSessionName", "reopenedLoopId", "reopenedTitle", "reopenedCheckDescription") } - } - foreach ($name in $textFields) { $facts[$name] = "" } - if ($id -eq "production-core") { $facts.createdCount = 0 } - if ($id -eq "actual-backend-terminal") { $facts.agentTurns = 0 } - if ($id -in @("production-core", "safe-stop-reopen")) { - $facts.readback = [ordered]@{ path = ""; sha256 = "" } - } - if ($id -eq "actual-backend-terminal") { - $facts.sessionReadback = [ordered]@{ path = ""; sha256 = "" } - } - return $facts -} - -function Assert-PreviewCoreCoverage($observations) { - $rows = @($observations) - Assert-PreviewCore ($rows.Count -eq 5 -and (($rows.id | Sort-Object) -join ',') -ceq - ((Get-PreviewCoreSteps | Sort-Object) -join ',')) "fixed flight observations are missing or duplicated" -} - -function Assert-PreviewCoreRunRoot([string] $root) { - Assert-PreviewCorePath $root - $repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) - $anchor = Join-Path $repo ".build\preview-core" - $full = [IO.Path]::GetFullPath($root) - Assert-PreviewCore ([IO.Path]::GetDirectoryName($full) -ieq $anchor -and - [IO.Path]::GetFileName($full) -cmatch '^flight-[0-9a-f]{32}$') "run root must be a new .build\preview-core\flight-GUID child of this checkout" -} - -function Assert-PreviewCoreArtifact($artifact, [string] $source, [string] $hash) { - Assert-PreviewCoreHash $source 40 "expected source SHA" - Assert-PreviewCoreHash $hash 64 "expected ZIP SHA-256" - Assert-PreviewCore ($artifact.sourceCommit -ceq $source -and $artifact.sha256 -ceq $hash) "candidate identity mismatch" - Assert-PreviewCore ($artifact.version -cmatch '^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z][0-9A-Za-z.]*)?$' -and - $artifact.version -notmatch '(?i)(^|[-.])dev([-.]|$)') "non-dev package version is required" - Assert-PreviewCore ($artifact.tag -ceq "v$($artifact.version)" -or $artifact.tag -ceq $artifact.version) "tag/version mismatch" - Assert-PreviewCore ($artifact.tagCommit -ceq $source) "tag/source mismatch" - Assert-PreviewCoreTrue $artifact.tagMatchesSource "tag/source equality" - Assert-PreviewCoreFalse $artifact.tagMismatchAllowed "tag mismatch override" - Assert-PreviewCore ($artifact.signing -ceq "UNSIGNED (not code signed)") "expected explicit unsigned preview warning" - foreach ($name in @("metadata", "manifest", "providerProvenance", "shell", "daemon", "cli", "zmx")) { - Assert-PreviewCoreHash $artifact.hashes.$name 64 "$name digest" - } - Assert-PreviewCore ($artifact.winghosttyCommit -ceq "e0a5579f3b470bede72294d661282a391c502ace" -and - $artifact.zmxCommit -ceq "785b3fd15dcafd1882b495c831a10f98c201b908") "accepted provider pins changed" -} - -function Get-PreviewCoreArtifact([string] $packageRoot, [string] $source, [string] $hash) { - $metadata = Get-Content -LiteralPath (Resolve-PreviewCoreChild $packageRoot "metadata.json") -Raw | ConvertFrom-Json - $artifact = [ordered]@{ - sourceCommit = $metadata.sourceProvenance.sourceCommit - sha256 = $hash - version = $metadata.version - tag = $metadata.sourceProvenance.tag - tagCommit = $metadata.sourceProvenance.tagCommit - tagMatchesSource = $metadata.sourceProvenance.tagMatchesSource - tagMismatchAllowed = $metadata.sourceProvenance.tagMismatchAllowed - signing = $metadata.signing - winghosttyCommit = $metadata.providerPins.winghostty.sha - zmxCommit = $metadata.providerPins.zmx.sha - hashes = [ordered]@{} - } - $paths = [ordered]@{ - metadata = "metadata.json"; manifest = "manifest.json" - providerProvenance = "provider-provenance.json" - shell = "bin\graphcode-windows.exe"; daemon = "bin\graphcoded.exe" - cli = "bin\graphcode.exe"; zmx = "bin\zmx.exe" - } - foreach ($name in $paths.Keys) { - $artifact.hashes[$name] = Get-PreviewCoreHash (Resolve-PreviewCoreChild $packageRoot $paths[$name]) - } - $artifact = [pscustomobject]$artifact - Assert-PreviewCoreArtifact $artifact $source $hash - return $artifact -} - -function New-PreviewCorePacket($artifact, [string] $root, [string] $scriptHash) { - [ordered]@{ - schemaVersion = 2 - kind = "PackagedProductionCore" - scope = "CoreOnly" - flightId = [guid]::NewGuid().ToString("N") - testOnly = $false - preparedUtc = [DateTime]::UtcNow.ToString("o") - runRoot = $root - qualificationScriptSha256 = $scriptHash - artifact = $artifact - profile = [ordered]@{ - os = ""; build = ""; role = "Unknown"; architecture = ""; shellVersion = "" - nativeLease = ""; ownedAccountIsolationWitnessed = $false - } - backend = [ordered]@{ - kind = ""; version = ""; executableSha256 = ""; permissions = ""; model = "" - approval = ""; authenticationProvisionedInOwnedAccount = $false - } - runtime = [ordered]@{ - daemon = "Unknown"; seededModel = $null; testHooks = $null - installation = "Unknown"; endpoint = ""; loopId = ""; terminalSessionName = ""; backendSessionId = "" - supportDirectory = ""; installDirectory = "" - installedHashes = [ordered]@{ shell = ""; daemon = ""; cli = ""; zmx = "" } - } - custody = [ordered]@{ - build = [ordered]@{ path = ""; sha256 = "" } - reviewer = ""; accepted = $false; reviewedEvidenceIsOwnedAndSanitized = $false - } - observations = @(Get-PreviewCoreSteps | ForEach-Object { - [ordered]@{ - id = $_; status = "NotExecuted"; count = 0; method = "" - note = "Requires actual separately authorized flight evidence." - evidence = @(); facts = New-PreviewCoreFacts $_ - } - }) - } -} - -function Write-PreviewCoreFixture([string] $root) { - foreach ($child in @("project", "support", "install", "evidence", "temp")) { - New-Item -ItemType Directory -Path (Resolve-PreviewCoreChild $root $child) | Out-Null - } - [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "project\alpha.txt"), "A-start-Z-end`n", [Text.UTF8Encoding]::new($false)) - $instructions = @' -PREPARED ONLY. No production core flight has run. -Do not create a loop until backend authentication, capability, synthetic-data -transmission, two fixture turns/credits, and native/installation permissions -are separately approved in an owned test account. Record the actual OS/build -and client/server role; hosted Server evidence does not claim Windows 11 support. - -Use the ordinary installed package and production graphcoded, not a stub, -gate-seeded model, copied zmx workaround, or developer-toolchain fallback. -Open project, create exactly one Turn-based loop using ONE declared backend. -Render/select it; rename to AlphaRenamed; edit Check description to -A-start-Z-end. Change a draft to CancelMustNotPersist, then cancel unchanged. -Opening task: read only alpha.txt; reply with its full line and FlightOutput1. -Native follow-up: Reply with FlightOutput2. Observe real readable replies, -not local echo or queued input. No recurrence/autopilot/additional turns. -Observe readable current pixels and the backend's required interaction. -Stop only this loop's captured terminal session, exit safely, and reopen the -saved project with the same title, Check description and node ID still stopped. -Use real saved LoopGraph/LoopNode JSON (including Codable state), not UI flags. -Record the Windows terminal's actual zmx session name and separately the opaque -backend conversation ID in an owned, sanitized session-readback JSON manifest. -TerminalSurface.openNode attaches the raw node UUID; Swift SurfaceRef daemon -launches use graphcode-UUID. Do not assume those namespaces are equivalent or -hide an actual binding failure with an override. - -Copy only owned, sanitized witnesses beneath evidence. Update qualification.json -with actual facts, positive counts, file hashes, profile/backend identity and -independent build/reviewer references. No credentials, environment, -foreign UI, raw command lines, private code, or synthetic session markers. -CORE_EVIDENCE_COMPLETE means this one observed core flow only, NOT preview -release qualification, publication permission or independent proof of human -assertions. Upgrade/predecessor, rollback/uninstall, DPI/IME, destructive -workspace, tray/interruption, full CI and tester-handoff gates remain external -in investigation\windows-preview-release-plan.md and may remain NotExecuted -here. No missing predecessor blocks CORE; it still blocks the relevant release -gate. Coordinator review and USER release approval remain separate. No cleanup -command deletes retained data or recovery backups. -'@ - [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "FLIGHT.txt"), $instructions, [Text.UTF8Encoding]::new($false)) -} - -function Assert-PreviewCoreEvidence($reference, [string] $root, [switch] $RequirePng) { - Assert-PreviewCoreHash $reference.sha256 64 "evidence SHA-256" - $path = Resolve-PreviewCoreChild $root $reference.path - Assert-PreviewCore ([IO.Path]::GetExtension($path) -in @(".txt", ".json", ".png")) "unsupported evidence file type" - Assert-PreviewCore ((Get-PreviewCoreHash $path) -ceq $reference.sha256) "evidence digest mismatch" - if ([IO.Path]::GetExtension($path) -eq ".png") { - $stream = [IO.File]::OpenRead($path) - try { - $header = New-Object byte[] 8 - $read = $stream.Read($header, 0, 8) - Assert-PreviewCore ($read -eq 8 -and [BitConverter]::ToString($header) -ceq "89-50-4E-47-0D-0A-1A-0A") "invalid owned PNG witness" - } finally { $stream.Dispose() } - } elseif ($RequirePng) { - throw "PreviewCore: native observation requires an owned PNG pixel witness" - } -} - -function Assert-PreviewCoreObservation($observation, [string] $evidenceRoot) { - Assert-PreviewCore ($observation.status -cin @("NotExecuted", "Failed", "Passed")) "invalid observation status" - Assert-PreviewCore ($observation.status -ceq "Passed") "$($observation.id) is $($observation.status)" - Assert-PreviewCore ((Test-PreviewCoreInteger $observation.count) -and - $observation.count -gt 0) "positive integer observation count is required" - $native = $observation.id -in @( - "production-core", "actual-backend-terminal", "safe-stop-reopen" - ) - $method = if ($native) { "NativeManual" } else { "OwnedRuntime" } - Assert-PreviewCore ($observation.method -ceq $method) "$($observation.id) requires $method evidence" - Assert-PreviewCore (@($observation.evidence).Count -gt 0) "observation evidence is missing" - $png = $false - foreach ($reference in $observation.evidence) { - Assert-PreviewCoreEvidence $reference $evidenceRoot - if ([IO.Path]::GetExtension($reference.path) -eq ".png") { $png = $true } - } - Assert-PreviewCore (-not $native -or $png) "native observation requires an owned PNG pixel witness" -} - -function Test-PreviewCoreGuid($value) { - return $value -is [string] -and $value -cmatch '^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$' -} - -function Test-PreviewCoreNumber($value) { - return (Test-PreviewCoreInteger $value) -or $value -is [decimal] -or ($value -is [double] -and - -not [double]::IsNaN($value) -and -not [double]::IsInfinity($value)) -} - -function Assert-PreviewCoreSavedGraph($reference, $packet, [string] $evidenceRoot, [string] $requiredState = "") { - Assert-PreviewCore ([IO.Path]::GetExtension($reference.path) -eq ".json") "persisted graph JSON readback is required" - Assert-PreviewCoreEvidence $reference $evidenceRoot - $graph = Get-Content -LiteralPath (Resolve-PreviewCoreChild $evidenceRoot $reference.path) -Raw | ConvertFrom-Json - $nodes = @($graph.nodes) - $project = (Resolve-PreviewCoreChild $packet.runRoot "project").Replace('\', '/') - Assert-PreviewCore ((Test-PreviewCoreGuid $graph.id) -and $graph.project.path -ieq $project -and - $nodes.Count -eq 1 -and @($graph.edges).Count -eq 0) "readback is not the one-loop owned LoopGraph" - Assert-PreviewCoreText $graph.project.name "persisted project name" - Assert-PreviewCore (Test-PreviewCoreNumber $graph.project.lastOpenedAt) "persisted project timestamp is missing" - $node = $nodes[0] - Assert-PreviewCore ((Test-PreviewCoreGuid $node.id) -and $node.id -ieq $packet.runtime.loopId -and $node.title -ceq "AlphaRenamed" -and - $node.loopType -ceq "turnBased" -and $node.checkDescription -ceq "A-start-Z-end" -and - $node.backend -ceq $packet.backend.kind) "actual persisted graph identity/configuration mismatch" - Assert-PreviewCore (Test-PreviewCoreNumber $node.createdAt) "persisted node timestamp is missing" - # LoopState is a synthesized Codable enum; LoopType/backend are raw strings. - $states = @($node.state.PSObject.Properties) - Assert-PreviewCore ($node.state -is [pscustomobject] -and $states.Count -eq 1 -and - $states[0].Name -cin @("idle", "running", "awaitingInput", "blocked", "succeeded", "failed", "stalled", "waiting", "stopped") -and - $states[0].Value -is [pscustomobject] -and @($states[0].Value.PSObject.Properties).Count -eq 0) "invalid production Codable LoopState" - if ($requiredState) { - Assert-PreviewCore ($states[0].Name -ceq $requiredState) "persisted loop is not $requiredState" - } -} - -function Assert-PreviewCoreSession($reference, $packet, [string] $evidenceRoot) { - Assert-PreviewCore ([IO.Path]::GetExtension($reference.path) -eq ".json") "owned session identity readback JSON is required" - Assert-PreviewCoreEvidence $reference $evidenceRoot - $session = Get-Content -LiteralPath (Resolve-PreviewCoreChild $evidenceRoot $reference.path) -Raw | ConvertFrom-Json - Assert-PreviewCore ($session.loopId -ieq $packet.runtime.loopId -and - $session.terminalSessionName -ceq $packet.runtime.terminalSessionName -and - $session.backendKind -ceq $packet.backend.kind -and - $session.backendExecutableSha256 -ceq $packet.backend.executableSha256 -and - $session.backendSessionId -ceq $packet.runtime.backendSessionId) "owned terminal/backend session identity mismatch" -} - -function Assert-PreviewCoreFacts($packet, [string] $evidenceRoot) { - $loop = $packet.runtime.loopId - foreach ($observation in $packet.observations) { - $f = $observation.facts - $checks = Get-PreviewCoreChecks $observation.id - foreach ($name in $checks) { Assert-PreviewCoreTrue $f.$name "$($observation.id).$name" } - switch ($observation.id) { - "production-core" { - Assert-PreviewCore ((Test-PreviewCoreInteger $f.createdCount) -and $f.createdCount -eq 1) "exactly one intended loop must be created" - Assert-PreviewCore ($f.selectedLoopId -ceq $loop -and $f.persistedLoopId -ceq $loop) "core loop identity changed" - Assert-PreviewCore ($f.graphTitle -ceq "AlphaRenamed" -and $f.sidebarTitle -ceq "AlphaRenamed" -and - $f.checkDescription -ceq "A-start-Z-end" -and $f.cancelDraft -ceq "CancelMustNotPersist") "exact core edit/cancel sentinels are missing" - Assert-PreviewCoreHash $f.cancelBeforeSha256 64 "cancel baseline digest" - Assert-PreviewCore ($f.cancelAfterSha256 -ceq $f.cancelBeforeSha256) "editor cancellation mutated persisted configuration" - Assert-PreviewCoreSavedGraph $f.readback $packet $evidenceRoot - } - "actual-backend-terminal" { - Assert-PreviewCore ($f.loopId -ceq $loop -and $f.backendKind -ceq $packet.backend.kind -and - $f.backendVersion -ceq $packet.backend.version) "actual backend/loop witness mismatch" - Assert-PreviewCore ($f.input -ceq "Reply with FlightOutput2." -and - $f.output1 -cmatch 'A-start-Z-end' -and $f.output1 -cmatch 'FlightOutput1' -and - $f.output2 -ceq "FlightOutput2" -and $f.terminalMode -ceq "default") "actual default-terminal input/output markers are missing" - Assert-PreviewCore ((Test-PreviewCoreInteger $f.agentTurns) -and $f.agentTurns -eq 2) "exactly two approved fixture turns are required" - Assert-PreviewCoreSession $f.sessionReadback $packet $evidenceRoot - } - "safe-stop-reopen" { - Assert-PreviewCore ($f.stoppedLoopId -ceq $loop -and $f.reopenedLoopId -ceq $loop -and - $f.stoppedSessionName -ceq $packet.runtime.terminalSessionName -and - $f.reopenedTitle -ceq "AlphaRenamed" -and $f.reopenedCheckDescription -ceq "A-start-Z-end") "persisted reopen identity/configuration mismatch" - Assert-PreviewCoreSavedGraph $f.readback $packet $evidenceRoot "stopped" - } - } - } -} - -function Assert-PreviewCoreCoreContract($packet, [string] $source, [string] $hash, [string] $evidenceRoot) { - Assert-PreviewCore ((Test-PreviewCoreInteger $packet.schemaVersion) -and $packet.schemaVersion -eq 2 -and - $packet.kind -ceq "PackagedProductionCore" -and $packet.scope -ceq "CoreOnly") "unsupported core-only packet" - Assert-PreviewCoreArtifact $packet.artifact $source $hash - Assert-PreviewCore ($packet.runtime.daemon -ceq "Production" -and - $packet.runtime.installation -ceq "ScheduledTask") "ordinary installed production daemon is required" - Assert-PreviewCoreFalse $packet.runtime.seededModel "seeded model" - Assert-PreviewCoreFalse $packet.runtime.testHooks "test hooks" - Assert-PreviewCore ($packet.runtime.supportDirectory -ieq (Resolve-PreviewCoreChild $packet.runRoot "support") -and - $packet.runtime.installDirectory -ieq (Resolve-PreviewCoreChild $packet.runRoot "install")) "runtime support/install roots are not the captured owned fixture" - foreach ($name in @("shell", "daemon", "cli", "zmx")) { - Assert-PreviewCore ($packet.runtime.installedHashes.$name -ceq $packet.artifact.hashes.$name) "installed $name digest mismatch" - } - Assert-PreviewCoreText $packet.runtime.endpoint "owned production endpoint" - Assert-PreviewCore (Test-PreviewCoreGuid $packet.runtime.loopId) "actual generated loop ID is missing" - # Windows TerminalSurface.openNode attaches the raw node ID, not SurfaceRef's daemon prefix. - Assert-PreviewCore ($packet.runtime.terminalSessionName -ceq $packet.runtime.loopId) "ordinary Windows terminal session name does not match the node ID" - # SessionIDStore persists opaque strings; a conversation ID is not a zmx session name. - Assert-PreviewCoreText $packet.runtime.backendSessionId "observed opaque backend conversation ID" - Assert-PreviewCore ($packet.backend.kind -cin @("copilotCLI", "claudeCode", "codex")) "one supported actual backend is required" - foreach ($name in @("version", "permissions", "model", "approval")) { - Assert-PreviewCoreText $packet.backend.$name "backend $name" - } - Assert-PreviewCoreHash $packet.backend.executableSha256 64 "actual backend executable identity" - $attended = if ($packet.backend.kind -ceq "claudeCode") { "manual" } else { "ask" } - Assert-PreviewCore ($packet.backend.permissions -ceq $attended) "first flight requires attended backend permissions, not bypass/autopilot" - Assert-PreviewCoreTrue $packet.backend.authenticationProvisionedInOwnedAccount "owned backend authentication approval" - Assert-PreviewCore ($packet.profile.role -cin @("Client", "Server") -and - $packet.profile.architecture -ceq "x64" -and $packet.profile.os -cmatch '^Windows\b') "actual Windows x64 client/server profile is missing" - Assert-PreviewCoreTrue $packet.profile.ownedAccountIsolationWitnessed "owned account/home/credential isolation" - foreach ($name in @("os", "build", "shellVersion", "nativeLease")) { - Assert-PreviewCoreText $packet.profile.$name "observed profile $name" - } - $observations = @($packet.observations) - Assert-PreviewCoreCoverage $observations - foreach ($observation in $observations) { Assert-PreviewCoreObservation $observation $evidenceRoot } - Assert-PreviewCoreFacts $packet $evidenceRoot - Assert-PreviewCoreText $packet.custody.reviewer "coordinator reviewer" - Assert-PreviewCoreTrue $packet.custody.accepted "coordinator evidence acceptance" - Assert-PreviewCoreTrue $packet.custody.reviewedEvidenceIsOwnedAndSanitized "owned sanitized evidence review" - Assert-PreviewCoreEvidence $packet.custody.build $evidenceRoot -} - -function Assert-PreviewCoreFlight($packet, [string] $source, [string] $hash, [string] $evidenceRoot) { - Assert-PreviewCoreFalse $packet.testOnly "test-only evidence" - Assert-PreviewCoreCoreContract $packet $source $hash $evidenceRoot -} - -function Get-PreviewCoreOutcome($packet) { - [pscustomobject]@{ - state = $(if ($packet.testOnly) { "CORE_CONTRACT_COMPLETE" } else { "CORE_EVIDENCE_COMPLETE" }) - testOnly = $packet.testOnly - previewReleaseQualified = $false - publicationApproved = $false - profileRole = $packet.profile.role - releasePlan = "investigation\windows-preview-release-plan.md" - } -} - -function Invoke-PreviewCorePackageVerification([string] $path, [string] $root) { - $repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) - $oldTemp = $env:TEMP - $oldTmp = $env:TMP - try { - $env:TEMP = Resolve-PreviewCoreChild $root "temp" - $env:TMP = $env:TEMP - $verification = @(& (Join-Path $repo "Tools\windows\package.ps1") -Command Verify -Package $path) - Assert-PreviewCore (@($verification | Where-Object { $_ -ceq "Package verification: PASS" }).Count -eq 1) "existing package verifier did not report one exact success" - } finally { - $env:TEMP = $oldTemp - $env:TMP = $oldTmp - } -} - -function Invoke-PreviewCorePrepare([string] $archive, [string] $source, [string] $hash, [string] $root) { - Assert-PreviewCoreHash $source 40 "expected source SHA" - Assert-PreviewCoreHash $hash 64 "expected ZIP SHA-256" - Assert-PreviewCore ([IO.Path]::GetExtension($archive) -eq ".zip") "a selected ZIP is required" - Assert-PreviewCore ((Get-PreviewCoreHash $archive) -ceq $hash) "ZIP hash mismatch" - Assert-PreviewCoreRunRoot $root - $root = [IO.Path]::GetFullPath($root) - Assert-PreviewCore (-not (Test-Path -LiteralPath $root)) "run root already exists; refusing to adopt state" - New-Item -ItemType Directory -Path $root -Force | Out-Null - Write-PreviewCoreFixture $root - $ownedZip = Resolve-PreviewCoreChild $root "candidate.zip" - Copy-Item -LiteralPath $archive -Destination $ownedZip - Assert-PreviewCore ((Get-PreviewCoreHash $ownedZip) -ceq $hash) "copied ZIP hash mismatch" - Invoke-PreviewCorePackageVerification $ownedZip $root - $extraction = Resolve-PreviewCoreChild $root "package" - Expand-Archive -LiteralPath $ownedZip -DestinationPath $extraction - $artifact = Get-PreviewCoreArtifact (Resolve-PreviewCoreChild $extraction "GraphCode") $source $hash - $scriptHash = Get-PreviewCoreHash $PSCommandPath - $packet = New-PreviewCorePacket $artifact $root $scriptHash - $json = $packet | ConvertTo-Json -Depth 20 - foreach ($name in @("prepared.json", "qualification.json")) { - [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root $name), $json, [Text.UTF8Encoding]::new($false)) - } - $owner = [ordered]@{ - flightId = $packet.flightId; sourceCommit = $source; zipSha256 = $hash - scriptSha256 = $scriptHash - preparedSha256 = Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "prepared.json") - projectSha256 = Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "project\alpha.txt") - } - [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "owner.json"), - ($owner | ConvertTo-Json), [Text.UTF8Encoding]::new($false)) - Write-Output "PREPARED_NOT_QUALIFIED: 5 CORE observations NotExecuted; no application/backend/native/installer execution" - Write-Output (Resolve-PreviewCoreChild $root "qualification.json") -} - -function Invoke-PreviewCoreVerify([string] $path, [string] $source, [string] $hash) { - Assert-PreviewCorePath $path - $root = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($path)) - Assert-PreviewCoreRunRoot $root - Assert-PreviewCore ([IO.Path]::GetFileName($path) -ceq "qualification.json") "use the owned qualification.json packet" - $owner = Get-Content -LiteralPath (Resolve-PreviewCoreChild $root "owner.json") -Raw | ConvertFrom-Json - $preparedPath = Resolve-PreviewCoreChild $root "prepared.json" - Assert-PreviewCore ((Get-PreviewCoreHash $preparedPath) -ceq $owner.preparedSha256) "prepared packet was modified" - Assert-PreviewCore ($owner.sourceCommit -ceq $source -and $owner.zipSha256 -ceq $hash -and - $owner.scriptSha256 -ceq (Get-PreviewCoreHash $PSCommandPath)) "prepared source/package/checker custody mismatch" - Assert-PreviewCore ((Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "project\alpha.txt")) -ceq - $owner.projectSha256) "owned project baseline changed" - $packet = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json - $prepared = Get-Content -LiteralPath $preparedPath -Raw | ConvertFrom-Json - Assert-PreviewCore ($packet.flightId -ceq $owner.flightId -and $packet.runRoot -ceq $root -and - $packet.qualificationScriptSha256 -ceq $owner.scriptSha256) "packet belongs to a different flight/checker" - Assert-PreviewCore (($packet.artifact | ConvertTo-Json -Depth 10 -Compress) -ceq - ($prepared.artifact | ConvertTo-Json -Depth 10 -Compress)) "prepared artifact identity changed" - Assert-PreviewCoreFlight $packet $source $hash (Resolve-PreviewCoreChild $root "evidence") - $ownedZip = Resolve-PreviewCoreChild $root "candidate.zip" - Assert-PreviewCore ((Get-PreviewCoreHash $ownedZip) -ceq $hash) "retained candidate ZIP hash mismatch" - Invoke-PreviewCorePackageVerification $ownedZip $root - $actualArtifact = Get-PreviewCoreArtifact (Resolve-PreviewCoreChild $root "package\GraphCode") $source $hash - Assert-PreviewCore (($actualArtifact | ConvertTo-Json -Depth 10 -Compress) -ceq - ($prepared.artifact | ConvertTo-Json -Depth 10 -Compress)) "retained packaged payload changed" - $outcome = Get-PreviewCoreOutcome $packet - Write-Output "$($outcome.state): previewReleaseQualified=false; publicationApproved=false; broader release gates remain external; not independent proof of human assertions" -} - -if ($HelpersOnly) { return } -switch ($Command) { - "Prepare" { Invoke-PreviewCorePrepare $Package $ExpectedSource $ExpectedSha256 $RunRoot } - "VerifyEvidence" { Invoke-PreviewCoreVerify $EvidencePath $ExpectedSource $ExpectedSha256 } - default { throw "PreviewCore: specify Prepare or VerifyEvidence; live execution is not supported" } -} +<# +.SYNOPSIS + Prepares and checks one installed production-daemon/real-backend preview flight. +.DESCRIPTION + Prepare verifies a caller-selected ZIP and creates only an owned synthetic + local project and an unexecuted flight packet. VerifyEvidence checks actual, + reviewed CORE evidence; it does not qualify a preview release or authorize + publication. Upgrade/predecessor, DPI/IME, destructive, tray/recovery and + wider CI/release gates remain in investigation\windows-preview-release-plan.md. + Neither command installs, launches, authenticates, drives UI, or manages + processes/tasks. Backend/version and every live permission are chosen later. + Keep credentials, environment/command-line dumps, foreign UI, and private + code out of the packet and its evidence. Checksums are not publisher trust. +.EXAMPLE + .\PreviewCore.Qualification.ps1 -Command Prepare -Package $zip ` + -ExpectedSource $source -ExpectedSha256 $hash -RunRoot $ownedNewFlightRoot +.EXAMPLE + .\PreviewCore.Qualification.ps1 -Command VerifyEvidence ` + -EvidencePath $completedPacket -ExpectedSource $source -ExpectedSha256 $hash +#> +[CmdletBinding()] +param( + [ValidateSet("Prepare", "VerifyEvidence")] + [string] $Command, + [string] $Package, + [string] $ExpectedSource, + [string] $ExpectedSha256, + [string] $RunRoot, + [string] $EvidencePath, + [switch] $HelpersOnly +) + +$ErrorActionPreference = "Stop" + +function Assert-PreviewCore($condition, [string] $message) { + if (-not $condition) { throw "PreviewCore: $message" } +} + +function Test-PreviewCoreInteger($value) { + return $value -is [int] -or $value -is [long] +} + +function Assert-PreviewCoreHash([string] $value, [int] $length, [string] $label) { + Assert-PreviewCore ($value -cmatch "^[0-9a-f]{$length}$") "invalid $label" +} + +function Assert-PreviewCoreTrue($value, [string] $label) { + Assert-PreviewCore ($value -is [bool] -and $value) "$label must be witnessed true" +} + +function Assert-PreviewCoreFalse($value, [string] $label) { + Assert-PreviewCore ($value -is [bool] -and -not $value) "$label must be explicit false" +} + +function Assert-PreviewCoreText($value, [string] $label) { + Assert-PreviewCore ($value -is [string] -and -not [string]::IsNullOrWhiteSpace($value) -and + $value.Length -le 512 -and $value -notmatch '^(?i:unknown|notexecuted|todo|tbd|n/a)$') "missing or invalid $label" +} + +function Assert-PreviewCorePath([string] $path) { + Assert-PreviewCore ([IO.Path]::IsPathRooted($path) -and $path -notmatch '^\\\\') "owned path must be local and absolute" + $current = [IO.Path]::GetFullPath($path) + while ($current) { + if (Test-Path -LiteralPath $current) { + $item = Get-Item -LiteralPath $current -Force + Assert-PreviewCore (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) "owned path contains a reparse point" + } + $parent = [IO.Directory]::GetParent($current) + $current = if ($parent) { $parent.FullName } else { $null } + } +} + +function Resolve-PreviewCoreChild([string] $root, [string] $relative) { + Assert-PreviewCore ($relative -and $relative -notmatch '[<>:"/|?*\x00-\x1f]' -and + -not [IO.Path]::IsPathRooted($relative) -and + @($relative.Split('\') | Where-Object { $_ -in @("", ".", "..") -or $_ -match '[. ]$' -or + $_ -match '^(?i:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$' }).Count -eq 0) "invalid owned relative path" + Assert-PreviewCorePath $root + $fullRoot = [IO.Path]::GetFullPath($root).TrimEnd('\') + $path = [IO.Path]::GetFullPath((Join-Path $fullRoot $relative)) + Assert-PreviewCore ($path.StartsWith($fullRoot + '\', [StringComparison]::OrdinalIgnoreCase)) "evidence escapes owned root" + Assert-PreviewCorePath $path + return $path +} + +function Get-PreviewCoreHash([string] $path) { + Assert-PreviewCorePath $path + Assert-PreviewCore (Test-Path -LiteralPath $path -PathType Leaf) "required owned file is missing" + return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() +} + +function Get-PreviewCoreSteps { + @( + "artifact-custody", "installed-production", "production-core", + "actual-backend-terminal", "safe-stop-reopen" + ) +} + +function Get-PreviewCoreChecks([string] $id) { + switch ($id) { + "artifact-custody" { @("independentTagSourceWitness", "unsignedWarning") } + "installed-production" { @("ordinaryScheduledInstall", "productionEndpointReachable") } + "production-core" { @("rendered", "selected", "editorCancelUnchanged") } + "actual-backend-terminal" { @("actualAgent", "readableCurrentPixels", "requiredControls") } + "safe-stop-reopen" { @("intendedLoopStopped", "safeExit") } + } +} + +function New-PreviewCoreFacts([string] $id) { + $facts = [ordered]@{} + foreach ($name in (Get-PreviewCoreChecks $id)) { $facts[$name] = $null } + $textFields = switch ($id) { + "production-core" { @("selectedLoopId", "persistedLoopId", "graphTitle", "sidebarTitle", "checkDescription", "cancelDraft", "cancelBeforeSha256", "cancelAfterSha256") } + "actual-backend-terminal" { @("loopId", "backendKind", "backendVersion", "input", "output1", "output2", "terminalMode") } + "safe-stop-reopen" { @("stoppedLoopId", "stoppedSessionName", "reopenedLoopId", "reopenedTitle", "reopenedCheckDescription") } + } + foreach ($name in $textFields) { $facts[$name] = "" } + if ($id -eq "production-core") { $facts.createdCount = 0 } + if ($id -eq "actual-backend-terminal") { $facts.agentTurns = 0 } + if ($id -in @("production-core", "safe-stop-reopen")) { + $facts.readback = [ordered]@{ path = ""; sha256 = "" } + } + if ($id -eq "actual-backend-terminal") { + $facts.sessionReadback = [ordered]@{ path = ""; sha256 = "" } + } + return $facts +} + +function Assert-PreviewCoreCoverage($observations) { + $rows = @($observations) + Assert-PreviewCore ($rows.Count -eq 5 -and (($rows.id | Sort-Object) -join ',') -ceq + ((Get-PreviewCoreSteps | Sort-Object) -join ',')) "fixed flight observations are missing or duplicated" +} + +function Assert-PreviewCoreRunRoot([string] $root) { + Assert-PreviewCorePath $root + $repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) + $anchor = Join-Path $repo ".build\preview-core" + $full = [IO.Path]::GetFullPath($root) + Assert-PreviewCore ([IO.Path]::GetDirectoryName($full) -ieq $anchor -and + [IO.Path]::GetFileName($full) -cmatch '^flight-[0-9a-f]{32}$') "run root must be a new .build\preview-core\flight-GUID child of this checkout" +} + +function Assert-PreviewCoreArtifact($artifact, [string] $source, [string] $hash) { + Assert-PreviewCoreHash $source 40 "expected source SHA" + Assert-PreviewCoreHash $hash 64 "expected ZIP SHA-256" + Assert-PreviewCore ($artifact.sourceCommit -ceq $source -and $artifact.sha256 -ceq $hash) "candidate identity mismatch" + Assert-PreviewCore ($artifact.version -cmatch '^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z][0-9A-Za-z.]*)?$' -and + $artifact.version -notmatch '(?i)(^|[-.])dev([-.]|$)') "non-dev package version is required" + Assert-PreviewCore ($artifact.tag -ceq "v$($artifact.version)" -or $artifact.tag -ceq $artifact.version) "tag/version mismatch" + Assert-PreviewCore ($artifact.tagCommit -ceq $source) "tag/source mismatch" + Assert-PreviewCoreTrue $artifact.tagMatchesSource "tag/source equality" + Assert-PreviewCoreFalse $artifact.tagMismatchAllowed "tag mismatch override" + Assert-PreviewCore ($artifact.signing -ceq "UNSIGNED (not code signed)") "expected explicit unsigned preview warning" + foreach ($name in @("metadata", "manifest", "providerProvenance", "shell", "daemon", "cli", "zmx")) { + Assert-PreviewCoreHash $artifact.hashes.$name 64 "$name digest" + } + Assert-PreviewCore ($artifact.winghosttyCommit -ceq "cac8f5f148fd5015d49e81e169ce9006ac7156ea" -and + $artifact.zmxCommit -ceq "785b3fd15dcafd1882b495c831a10f98c201b908") "accepted provider pins changed" +} + +function Get-PreviewCoreArtifact([string] $packageRoot, [string] $source, [string] $hash) { + $metadata = Get-Content -LiteralPath (Resolve-PreviewCoreChild $packageRoot "metadata.json") -Raw | ConvertFrom-Json + $artifact = [ordered]@{ + sourceCommit = $metadata.sourceProvenance.sourceCommit + sha256 = $hash + version = $metadata.version + tag = $metadata.sourceProvenance.tag + tagCommit = $metadata.sourceProvenance.tagCommit + tagMatchesSource = $metadata.sourceProvenance.tagMatchesSource + tagMismatchAllowed = $metadata.sourceProvenance.tagMismatchAllowed + signing = $metadata.signing + winghosttyCommit = $metadata.providerPins.winghostty.sha + zmxCommit = $metadata.providerPins.zmx.sha + hashes = [ordered]@{} + } + $paths = [ordered]@{ + metadata = "metadata.json"; manifest = "manifest.json" + providerProvenance = "provider-provenance.json" + shell = "bin\graphcode-windows.exe"; daemon = "bin\graphcoded.exe" + cli = "bin\graphcode.exe"; zmx = "bin\zmx.exe" + } + foreach ($name in $paths.Keys) { + $artifact.hashes[$name] = Get-PreviewCoreHash (Resolve-PreviewCoreChild $packageRoot $paths[$name]) + } + $artifact = [pscustomobject]$artifact + Assert-PreviewCoreArtifact $artifact $source $hash + return $artifact +} + +function New-PreviewCorePacket($artifact, [string] $root, [string] $scriptHash) { + [ordered]@{ + schemaVersion = 2 + kind = "PackagedProductionCore" + scope = "CoreOnly" + flightId = [guid]::NewGuid().ToString("N") + testOnly = $false + preparedUtc = [DateTime]::UtcNow.ToString("o") + runRoot = $root + qualificationScriptSha256 = $scriptHash + artifact = $artifact + profile = [ordered]@{ + os = ""; build = ""; role = "Unknown"; architecture = ""; shellVersion = "" + nativeLease = ""; ownedAccountIsolationWitnessed = $false + } + backend = [ordered]@{ + kind = ""; version = ""; executableSha256 = ""; permissions = ""; model = "" + approval = ""; authenticationProvisionedInOwnedAccount = $false + } + runtime = [ordered]@{ + daemon = "Unknown"; seededModel = $null; testHooks = $null + installation = "Unknown"; endpoint = ""; loopId = ""; terminalSessionName = ""; backendSessionId = "" + supportDirectory = ""; installDirectory = "" + installedHashes = [ordered]@{ shell = ""; daemon = ""; cli = ""; zmx = "" } + } + custody = [ordered]@{ + build = [ordered]@{ path = ""; sha256 = "" } + reviewer = ""; accepted = $false; reviewedEvidenceIsOwnedAndSanitized = $false + } + observations = @(Get-PreviewCoreSteps | ForEach-Object { + [ordered]@{ + id = $_; status = "NotExecuted"; count = 0; method = "" + note = "Requires actual separately authorized flight evidence." + evidence = @(); facts = New-PreviewCoreFacts $_ + } + }) + } +} + +function Write-PreviewCoreFixture([string] $root) { + foreach ($child in @("project", "support", "install", "evidence", "temp")) { + New-Item -ItemType Directory -Path (Resolve-PreviewCoreChild $root $child) | Out-Null + } + [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "project\alpha.txt"), "A-start-Z-end`n", [Text.UTF8Encoding]::new($false)) + $instructions = @' +PREPARED ONLY. No production core flight has run. +Do not create a loop until backend authentication, capability, synthetic-data +transmission, two fixture turns/credits, and native/installation permissions +are separately approved in an owned test account. Record the actual OS/build +and client/server role; hosted Server evidence does not claim Windows 11 support. + +Use the ordinary installed package and production graphcoded, not a stub, +gate-seeded model, copied zmx workaround, or developer-toolchain fallback. +Open project, create exactly one Turn-based loop using ONE declared backend. +Render/select it; rename to AlphaRenamed; edit Check description to +A-start-Z-end. Change a draft to CancelMustNotPersist, then cancel unchanged. +Opening task: read only alpha.txt; reply with its full line and FlightOutput1. +Native follow-up: Reply with FlightOutput2. Observe real readable replies, +not local echo or queued input. No recurrence/autopilot/additional turns. +Observe readable current pixels and the backend's required interaction. +Stop only this loop's captured terminal session, exit safely, and reopen the +saved project with the same title, Check description and node ID still stopped. +Use real saved LoopGraph/LoopNode JSON (including Codable state), not UI flags. +Record the Windows terminal's actual zmx session name and separately the opaque +backend conversation ID in an owned, sanitized session-readback JSON manifest. +TerminalSurface.openNode attaches the raw node UUID; Swift SurfaceRef daemon +launches use graphcode-UUID. Do not assume those namespaces are equivalent or +hide an actual binding failure with an override. + +Copy only owned, sanitized witnesses beneath evidence. Update qualification.json +with actual facts, positive counts, file hashes, profile/backend identity and +independent build/reviewer references. No credentials, environment, +foreign UI, raw command lines, private code, or synthetic session markers. +CORE_EVIDENCE_COMPLETE means this one observed core flow only, NOT preview +release qualification, publication permission or independent proof of human +assertions. Upgrade/predecessor, rollback/uninstall, DPI/IME, destructive +workspace, tray/interruption, full CI and tester-handoff gates remain external +in investigation\windows-preview-release-plan.md and may remain NotExecuted +here. No missing predecessor blocks CORE; it still blocks the relevant release +gate. Coordinator review and USER release approval remain separate. No cleanup +command deletes retained data or recovery backups. +'@ + [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "FLIGHT.txt"), $instructions, [Text.UTF8Encoding]::new($false)) +} + +function Assert-PreviewCoreEvidence($reference, [string] $root, [switch] $RequirePng) { + Assert-PreviewCoreHash $reference.sha256 64 "evidence SHA-256" + $path = Resolve-PreviewCoreChild $root $reference.path + Assert-PreviewCore ([IO.Path]::GetExtension($path) -in @(".txt", ".json", ".png")) "unsupported evidence file type" + Assert-PreviewCore ((Get-PreviewCoreHash $path) -ceq $reference.sha256) "evidence digest mismatch" + if ([IO.Path]::GetExtension($path) -eq ".png") { + $stream = [IO.File]::OpenRead($path) + try { + $header = New-Object byte[] 8 + $read = $stream.Read($header, 0, 8) + Assert-PreviewCore ($read -eq 8 -and [BitConverter]::ToString($header) -ceq "89-50-4E-47-0D-0A-1A-0A") "invalid owned PNG witness" + } finally { $stream.Dispose() } + } elseif ($RequirePng) { + throw "PreviewCore: native observation requires an owned PNG pixel witness" + } +} + +function Assert-PreviewCoreObservation($observation, [string] $evidenceRoot) { + Assert-PreviewCore ($observation.status -cin @("NotExecuted", "Failed", "Passed")) "invalid observation status" + Assert-PreviewCore ($observation.status -ceq "Passed") "$($observation.id) is $($observation.status)" + Assert-PreviewCore ((Test-PreviewCoreInteger $observation.count) -and + $observation.count -gt 0) "positive integer observation count is required" + $native = $observation.id -in @( + "production-core", "actual-backend-terminal", "safe-stop-reopen" + ) + $method = if ($native) { "NativeManual" } else { "OwnedRuntime" } + Assert-PreviewCore ($observation.method -ceq $method) "$($observation.id) requires $method evidence" + Assert-PreviewCore (@($observation.evidence).Count -gt 0) "observation evidence is missing" + $png = $false + foreach ($reference in $observation.evidence) { + Assert-PreviewCoreEvidence $reference $evidenceRoot + if ([IO.Path]::GetExtension($reference.path) -eq ".png") { $png = $true } + } + Assert-PreviewCore (-not $native -or $png) "native observation requires an owned PNG pixel witness" +} + +function Test-PreviewCoreGuid($value) { + return $value -is [string] -and $value -cmatch '^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$' +} + +function Test-PreviewCoreNumber($value) { + return (Test-PreviewCoreInteger $value) -or $value -is [decimal] -or ($value -is [double] -and + -not [double]::IsNaN($value) -and -not [double]::IsInfinity($value)) +} + +function Assert-PreviewCoreSavedGraph($reference, $packet, [string] $evidenceRoot, [string] $requiredState = "") { + Assert-PreviewCore ([IO.Path]::GetExtension($reference.path) -eq ".json") "persisted graph JSON readback is required" + Assert-PreviewCoreEvidence $reference $evidenceRoot + $graph = Get-Content -LiteralPath (Resolve-PreviewCoreChild $evidenceRoot $reference.path) -Raw | ConvertFrom-Json + $nodes = @($graph.nodes) + $project = (Resolve-PreviewCoreChild $packet.runRoot "project").Replace('\', '/') + Assert-PreviewCore ((Test-PreviewCoreGuid $graph.id) -and $graph.project.path -ieq $project -and + $nodes.Count -eq 1 -and @($graph.edges).Count -eq 0) "readback is not the one-loop owned LoopGraph" + Assert-PreviewCoreText $graph.project.name "persisted project name" + Assert-PreviewCore (Test-PreviewCoreNumber $graph.project.lastOpenedAt) "persisted project timestamp is missing" + $node = $nodes[0] + Assert-PreviewCore ((Test-PreviewCoreGuid $node.id) -and $node.id -ieq $packet.runtime.loopId -and $node.title -ceq "AlphaRenamed" -and + $node.loopType -ceq "turnBased" -and $node.checkDescription -ceq "A-start-Z-end" -and + $node.backend -ceq $packet.backend.kind) "actual persisted graph identity/configuration mismatch" + Assert-PreviewCore (Test-PreviewCoreNumber $node.createdAt) "persisted node timestamp is missing" + # LoopState is a synthesized Codable enum; LoopType/backend are raw strings. + $states = @($node.state.PSObject.Properties) + Assert-PreviewCore ($node.state -is [pscustomobject] -and $states.Count -eq 1 -and + $states[0].Name -cin @("idle", "running", "awaitingInput", "blocked", "succeeded", "failed", "stalled", "waiting", "stopped") -and + $states[0].Value -is [pscustomobject] -and @($states[0].Value.PSObject.Properties).Count -eq 0) "invalid production Codable LoopState" + if ($requiredState) { + Assert-PreviewCore ($states[0].Name -ceq $requiredState) "persisted loop is not $requiredState" + } +} + +function Assert-PreviewCoreSession($reference, $packet, [string] $evidenceRoot) { + Assert-PreviewCore ([IO.Path]::GetExtension($reference.path) -eq ".json") "owned session identity readback JSON is required" + Assert-PreviewCoreEvidence $reference $evidenceRoot + $session = Get-Content -LiteralPath (Resolve-PreviewCoreChild $evidenceRoot $reference.path) -Raw | ConvertFrom-Json + Assert-PreviewCore ($session.loopId -ieq $packet.runtime.loopId -and + $session.terminalSessionName -ceq $packet.runtime.terminalSessionName -and + $session.backendKind -ceq $packet.backend.kind -and + $session.backendExecutableSha256 -ceq $packet.backend.executableSha256 -and + $session.backendSessionId -ceq $packet.runtime.backendSessionId) "owned terminal/backend session identity mismatch" +} + +function Assert-PreviewCoreFacts($packet, [string] $evidenceRoot) { + $loop = $packet.runtime.loopId + foreach ($observation in $packet.observations) { + $f = $observation.facts + $checks = Get-PreviewCoreChecks $observation.id + foreach ($name in $checks) { Assert-PreviewCoreTrue $f.$name "$($observation.id).$name" } + switch ($observation.id) { + "production-core" { + Assert-PreviewCore ((Test-PreviewCoreInteger $f.createdCount) -and $f.createdCount -eq 1) "exactly one intended loop must be created" + Assert-PreviewCore ($f.selectedLoopId -ceq $loop -and $f.persistedLoopId -ceq $loop) "core loop identity changed" + Assert-PreviewCore ($f.graphTitle -ceq "AlphaRenamed" -and $f.sidebarTitle -ceq "AlphaRenamed" -and + $f.checkDescription -ceq "A-start-Z-end" -and $f.cancelDraft -ceq "CancelMustNotPersist") "exact core edit/cancel sentinels are missing" + Assert-PreviewCoreHash $f.cancelBeforeSha256 64 "cancel baseline digest" + Assert-PreviewCore ($f.cancelAfterSha256 -ceq $f.cancelBeforeSha256) "editor cancellation mutated persisted configuration" + Assert-PreviewCoreSavedGraph $f.readback $packet $evidenceRoot + } + "actual-backend-terminal" { + Assert-PreviewCore ($f.loopId -ceq $loop -and $f.backendKind -ceq $packet.backend.kind -and + $f.backendVersion -ceq $packet.backend.version) "actual backend/loop witness mismatch" + Assert-PreviewCore ($f.input -ceq "Reply with FlightOutput2." -and + $f.output1 -cmatch 'A-start-Z-end' -and $f.output1 -cmatch 'FlightOutput1' -and + $f.output2 -ceq "FlightOutput2" -and $f.terminalMode -ceq "default") "actual default-terminal input/output markers are missing" + Assert-PreviewCore ((Test-PreviewCoreInteger $f.agentTurns) -and $f.agentTurns -eq 2) "exactly two approved fixture turns are required" + Assert-PreviewCoreSession $f.sessionReadback $packet $evidenceRoot + } + "safe-stop-reopen" { + Assert-PreviewCore ($f.stoppedLoopId -ceq $loop -and $f.reopenedLoopId -ceq $loop -and + $f.stoppedSessionName -ceq $packet.runtime.terminalSessionName -and + $f.reopenedTitle -ceq "AlphaRenamed" -and $f.reopenedCheckDescription -ceq "A-start-Z-end") "persisted reopen identity/configuration mismatch" + Assert-PreviewCoreSavedGraph $f.readback $packet $evidenceRoot "stopped" + } + } + } +} + +function Assert-PreviewCoreCoreContract($packet, [string] $source, [string] $hash, [string] $evidenceRoot) { + Assert-PreviewCore ((Test-PreviewCoreInteger $packet.schemaVersion) -and $packet.schemaVersion -eq 2 -and + $packet.kind -ceq "PackagedProductionCore" -and $packet.scope -ceq "CoreOnly") "unsupported core-only packet" + Assert-PreviewCoreArtifact $packet.artifact $source $hash + Assert-PreviewCore ($packet.runtime.daemon -ceq "Production" -and + $packet.runtime.installation -ceq "ScheduledTask") "ordinary installed production daemon is required" + Assert-PreviewCoreFalse $packet.runtime.seededModel "seeded model" + Assert-PreviewCoreFalse $packet.runtime.testHooks "test hooks" + Assert-PreviewCore ($packet.runtime.supportDirectory -ieq (Resolve-PreviewCoreChild $packet.runRoot "support") -and + $packet.runtime.installDirectory -ieq (Resolve-PreviewCoreChild $packet.runRoot "install")) "runtime support/install roots are not the captured owned fixture" + foreach ($name in @("shell", "daemon", "cli", "zmx")) { + Assert-PreviewCore ($packet.runtime.installedHashes.$name -ceq $packet.artifact.hashes.$name) "installed $name digest mismatch" + } + Assert-PreviewCoreText $packet.runtime.endpoint "owned production endpoint" + Assert-PreviewCore (Test-PreviewCoreGuid $packet.runtime.loopId) "actual generated loop ID is missing" + # Windows TerminalSurface.openNode attaches the raw node ID, not SurfaceRef's daemon prefix. + Assert-PreviewCore ($packet.runtime.terminalSessionName -ceq $packet.runtime.loopId) "ordinary Windows terminal session name does not match the node ID" + # SessionIDStore persists opaque strings; a conversation ID is not a zmx session name. + Assert-PreviewCoreText $packet.runtime.backendSessionId "observed opaque backend conversation ID" + Assert-PreviewCore ($packet.backend.kind -cin @("copilotCLI", "claudeCode", "codex")) "one supported actual backend is required" + foreach ($name in @("version", "permissions", "model", "approval")) { + Assert-PreviewCoreText $packet.backend.$name "backend $name" + } + Assert-PreviewCoreHash $packet.backend.executableSha256 64 "actual backend executable identity" + $attended = if ($packet.backend.kind -ceq "claudeCode") { "manual" } else { "ask" } + Assert-PreviewCore ($packet.backend.permissions -ceq $attended) "first flight requires attended backend permissions, not bypass/autopilot" + Assert-PreviewCoreTrue $packet.backend.authenticationProvisionedInOwnedAccount "owned backend authentication approval" + Assert-PreviewCore ($packet.profile.role -cin @("Client", "Server") -and + $packet.profile.architecture -ceq "x64" -and $packet.profile.os -cmatch '^Windows\b') "actual Windows x64 client/server profile is missing" + Assert-PreviewCoreTrue $packet.profile.ownedAccountIsolationWitnessed "owned account/home/credential isolation" + foreach ($name in @("os", "build", "shellVersion", "nativeLease")) { + Assert-PreviewCoreText $packet.profile.$name "observed profile $name" + } + $observations = @($packet.observations) + Assert-PreviewCoreCoverage $observations + foreach ($observation in $observations) { Assert-PreviewCoreObservation $observation $evidenceRoot } + Assert-PreviewCoreFacts $packet $evidenceRoot + Assert-PreviewCoreText $packet.custody.reviewer "coordinator reviewer" + Assert-PreviewCoreTrue $packet.custody.accepted "coordinator evidence acceptance" + Assert-PreviewCoreTrue $packet.custody.reviewedEvidenceIsOwnedAndSanitized "owned sanitized evidence review" + Assert-PreviewCoreEvidence $packet.custody.build $evidenceRoot +} + +function Assert-PreviewCoreFlight($packet, [string] $source, [string] $hash, [string] $evidenceRoot) { + Assert-PreviewCoreFalse $packet.testOnly "test-only evidence" + Assert-PreviewCoreCoreContract $packet $source $hash $evidenceRoot +} + +function Get-PreviewCoreOutcome($packet) { + [pscustomobject]@{ + state = $(if ($packet.testOnly) { "CORE_CONTRACT_COMPLETE" } else { "CORE_EVIDENCE_COMPLETE" }) + testOnly = $packet.testOnly + previewReleaseQualified = $false + publicationApproved = $false + profileRole = $packet.profile.role + releasePlan = "investigation\windows-preview-release-plan.md" + } +} + +function Invoke-PreviewCorePackageVerification([string] $path, [string] $root) { + $repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) + $oldTemp = $env:TEMP + $oldTmp = $env:TMP + try { + $env:TEMP = Resolve-PreviewCoreChild $root "temp" + $env:TMP = $env:TEMP + $verification = @(& (Join-Path $repo "Tools\windows\package.ps1") -Command Verify -Package $path) + Assert-PreviewCore (@($verification | Where-Object { $_ -ceq "Package verification: PASS" }).Count -eq 1) "existing package verifier did not report one exact success" + } finally { + $env:TEMP = $oldTemp + $env:TMP = $oldTmp + } +} + +function Invoke-PreviewCorePrepare([string] $archive, [string] $source, [string] $hash, [string] $root) { + Assert-PreviewCoreHash $source 40 "expected source SHA" + Assert-PreviewCoreHash $hash 64 "expected ZIP SHA-256" + Assert-PreviewCore ([IO.Path]::GetExtension($archive) -eq ".zip") "a selected ZIP is required" + Assert-PreviewCore ((Get-PreviewCoreHash $archive) -ceq $hash) "ZIP hash mismatch" + Assert-PreviewCoreRunRoot $root + $root = [IO.Path]::GetFullPath($root) + Assert-PreviewCore (-not (Test-Path -LiteralPath $root)) "run root already exists; refusing to adopt state" + New-Item -ItemType Directory -Path $root -Force | Out-Null + Write-PreviewCoreFixture $root + $ownedZip = Resolve-PreviewCoreChild $root "candidate.zip" + Copy-Item -LiteralPath $archive -Destination $ownedZip + Assert-PreviewCore ((Get-PreviewCoreHash $ownedZip) -ceq $hash) "copied ZIP hash mismatch" + Invoke-PreviewCorePackageVerification $ownedZip $root + $extraction = Resolve-PreviewCoreChild $root "package" + Expand-Archive -LiteralPath $ownedZip -DestinationPath $extraction + $artifact = Get-PreviewCoreArtifact (Resolve-PreviewCoreChild $extraction "GraphCode") $source $hash + $scriptHash = Get-PreviewCoreHash $PSCommandPath + $packet = New-PreviewCorePacket $artifact $root $scriptHash + $json = $packet | ConvertTo-Json -Depth 20 + foreach ($name in @("prepared.json", "qualification.json")) { + [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root $name), $json, [Text.UTF8Encoding]::new($false)) + } + $owner = [ordered]@{ + flightId = $packet.flightId; sourceCommit = $source; zipSha256 = $hash + scriptSha256 = $scriptHash + preparedSha256 = Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "prepared.json") + projectSha256 = Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "project\alpha.txt") + } + [IO.File]::WriteAllText((Resolve-PreviewCoreChild $root "owner.json"), + ($owner | ConvertTo-Json), [Text.UTF8Encoding]::new($false)) + Write-Output "PREPARED_NOT_QUALIFIED: 5 CORE observations NotExecuted; no application/backend/native/installer execution" + Write-Output (Resolve-PreviewCoreChild $root "qualification.json") +} + +function Invoke-PreviewCoreVerify([string] $path, [string] $source, [string] $hash) { + Assert-PreviewCorePath $path + $root = [IO.Path]::GetDirectoryName([IO.Path]::GetFullPath($path)) + Assert-PreviewCoreRunRoot $root + Assert-PreviewCore ([IO.Path]::GetFileName($path) -ceq "qualification.json") "use the owned qualification.json packet" + $owner = Get-Content -LiteralPath (Resolve-PreviewCoreChild $root "owner.json") -Raw | ConvertFrom-Json + $preparedPath = Resolve-PreviewCoreChild $root "prepared.json" + Assert-PreviewCore ((Get-PreviewCoreHash $preparedPath) -ceq $owner.preparedSha256) "prepared packet was modified" + Assert-PreviewCore ($owner.sourceCommit -ceq $source -and $owner.zipSha256 -ceq $hash -and + $owner.scriptSha256 -ceq (Get-PreviewCoreHash $PSCommandPath)) "prepared source/package/checker custody mismatch" + Assert-PreviewCore ((Get-PreviewCoreHash (Resolve-PreviewCoreChild $root "project\alpha.txt")) -ceq + $owner.projectSha256) "owned project baseline changed" + $packet = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json + $prepared = Get-Content -LiteralPath $preparedPath -Raw | ConvertFrom-Json + Assert-PreviewCore ($packet.flightId -ceq $owner.flightId -and $packet.runRoot -ceq $root -and + $packet.qualificationScriptSha256 -ceq $owner.scriptSha256) "packet belongs to a different flight/checker" + Assert-PreviewCore (($packet.artifact | ConvertTo-Json -Depth 10 -Compress) -ceq + ($prepared.artifact | ConvertTo-Json -Depth 10 -Compress)) "prepared artifact identity changed" + Assert-PreviewCoreFlight $packet $source $hash (Resolve-PreviewCoreChild $root "evidence") + $ownedZip = Resolve-PreviewCoreChild $root "candidate.zip" + Assert-PreviewCore ((Get-PreviewCoreHash $ownedZip) -ceq $hash) "retained candidate ZIP hash mismatch" + Invoke-PreviewCorePackageVerification $ownedZip $root + $actualArtifact = Get-PreviewCoreArtifact (Resolve-PreviewCoreChild $root "package\GraphCode") $source $hash + Assert-PreviewCore (($actualArtifact | ConvertTo-Json -Depth 10 -Compress) -ceq + ($prepared.artifact | ConvertTo-Json -Depth 10 -Compress)) "retained packaged payload changed" + $outcome = Get-PreviewCoreOutcome $packet + Write-Output "$($outcome.state): previewReleaseQualified=false; publicationApproved=false; broader release gates remain external; not independent proof of human assertions" +} + +if ($HelpersOnly) { return } +switch ($Command) { + "Prepare" { Invoke-PreviewCorePrepare $Package $ExpectedSource $ExpectedSha256 $RunRoot } + "VerifyEvidence" { Invoke-PreviewCoreVerify $EvidencePath $ExpectedSource $ExpectedSha256 } + default { throw "PreviewCore: specify Prepare or VerifyEvidence; live execution is not supported" } +} diff --git a/Tools/windows/Tests/PreviewCore.Tests.ps1 b/Tools/windows/Tests/PreviewCore.Tests.ps1 index 64085906..ceb6e8d2 100644 --- a/Tools/windows/Tests/PreviewCore.Tests.ps1 +++ b/Tools/windows/Tests/PreviewCore.Tests.ps1 @@ -1,497 +1,497 @@ -[CmdletBinding()] -param( - [ValidateSet("IncompleteFlight", "CoreBoundary", "All")] - [string] $Case = "All" -) - -$ErrorActionPreference = "Stop" -$qualification = Join-Path $PSScriptRoot "PreviewCore.Qualification.ps1" -if (-not (Test-Path -LiteralPath $qualification -PathType Leaf)) { - throw "PreviewCore qualification entrypoint is missing (structural contract RED; no product runtime ran)" -} -. $qualification -HelpersOnly - -$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) -$root = Join-Path $repo (".build\preview-core-contract-" + [guid]::NewGuid().ToString("N")) -$executed = 0 -$oldTemp = $env:TEMP -$oldTmp = $env:TMP - -function New-ContractArtifact { - $hashes = [ordered]@{} - foreach ($name in @("metadata", "manifest", "providerProvenance", "shell", "daemon", "cli", "zmx")) { - $hashes[$name] = "a" * 64 - } - [pscustomobject]@{ - sourceCommit = "b" * 40; sha256 = "c" * 64; version = "1.2.3-alpha" - tag = "v1.2.3-alpha"; tagCommit = "b" * 40 - tagMatchesSource = $true; tagMismatchAllowed = $false - signing = "UNSIGNED (not code signed)" - winghosttyCommit = "e0a5579f3b470bede72294d661282a391c502ace" - zmxCommit = "785b3fd15dcafd1882b495c831a10f98c201b908" - hashes = [pscustomobject]$hashes - } -} - -function New-ContractReference([string] $relative) { - [pscustomobject]@{ path = $relative; sha256 = Get-PreviewCoreHash (Join-Path $root $relative) } -} - -function New-ProductionCoreContract { - $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) | - ConvertTo-Json -Depth 20 | ConvertFrom-Json - $packet.testOnly = $true - $packet.profile.os = "Windows Server (pure contract, not an executed profile)" - $packet.profile.build = "contract-build" - $packet.profile.role = "Server" - $packet.profile.architecture = "x64" - $packet.profile.shellVersion = "contract-shell" - $packet.profile.nativeLease = "test-only; no native lease" - $packet.profile.ownedAccountIsolationWitnessed = $true - $packet.backend.kind = "copilotCLI" - $packet.backend.version = "contract-version; no agent invoked" - $packet.backend.executableSha256 = "e" * 64 - $packet.backend.permissions = "ask" - $packet.backend.model = "backend default" - $packet.backend.approval = "test-only; no credentials or credits granted" - $packet.backend.authenticationProvisionedInOwnedAccount = $true - $packet.runtime.daemon = "Production" - $packet.runtime.installation = "ScheduledTask" - $packet.runtime.seededModel = $false - $packet.runtime.testHooks = $false - $packet.runtime.supportDirectory = Join-Path $root "support" - $packet.runtime.installDirectory = Join-Path $root "install" - $packet.runtime.endpoint = "\\.\pipe\pure-contract-not-a-running-daemon" - $packet.runtime.loopId = "D1111111-1111-4111-8111-111111111111" - $packet.runtime.terminalSessionName = $packet.runtime.loopId - $packet.runtime.backendSessionId = "opaque-conversation-id-not-a-guid" - foreach ($name in @("shell", "daemon", "cli", "zmx")) { - $packet.runtime.installedHashes.$name = $packet.artifact.hashes.$name - } - $prefix = "contract-" + [guid]::NewGuid().ToString("N") - $png = "$prefix.png" - [IO.File]::WriteAllBytes((Join-Path $root $png), [Convert]::FromBase64String( - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lX8AAAAASUVORK5CYII=")) - $build = "$prefix-build.txt" - [IO.File]::WriteAllText((Join-Path $root $build), "Pure contract reference; NOT actual production/build evidence") - $packet.custody.build = New-ContractReference $build - $packet.custody.reviewer = "pure-contract observer, not a real approval" - $packet.custody.accepted = $true - $packet.custody.reviewedEvidenceIsOwnedAndSanitized = $true - # Matches LoopGraph/ProjectRef/LoopNode Codable; this is NOT a captured daemon graph. - $graph = @{ - id = "E2222222-2222-4222-8222-222222222222" - project = @{ path = (Join-Path $root "project").Replace('\', '/'); name = "project"; lastOpenedAt = 42.5 } - edges = @() - nodes = @(@{ - id = $packet.runtime.loopId; title = "AlphaRenamed"; loopType = "turnBased" - backend = $packet.backend.kind; checkDescription = "A-start-Z-end"; createdAt = 42.5 - state = @{ idle = @{} }; pilotState = @{ notPiloted = @{} } - pausesBeforeWritesOnly = $false; attachments = @(); metricHistory = @(); sessionRestarts = 0 - }) - } - $coreGraph = "$prefix-core.json" - [IO.File]::WriteAllText((Join-Path $root $coreGraph), ($graph | ConvertTo-Json -Depth 10)) - $graph.nodes[0].state = @{ stopped = @{} } - $stoppedGraph = "$prefix-stopped.json" - [IO.File]::WriteAllText((Join-Path $root $stoppedGraph), ($graph | ConvertTo-Json -Depth 10)) - $session = "$prefix-session.json" - $binding = @{ - loopId = $packet.runtime.loopId; terminalSessionName = $packet.runtime.terminalSessionName - backendKind = $packet.backend.kind; backendSessionId = $packet.runtime.backendSessionId - backendExecutableSha256 = $packet.backend.executableSha256 - } - [IO.File]::WriteAllText((Join-Path $root $session), ($binding | ConvertTo-Json)) - foreach ($row in $packet.observations) { - $row.status = "Passed"; $row.count = 1 - $row.method = if ($row.id -in @("production-core", "actual-backend-terminal", "safe-stop-reopen")) { "NativeManual" } else { "OwnedRuntime" } - $row.evidence = @((New-ContractReference $png)) - foreach ($check in (Get-PreviewCoreChecks $row.id)) { $row.facts.$check = $true } - switch ($row.id) { - "production-core" { - $row.facts.createdCount = 1; $row.facts.selectedLoopId = $packet.runtime.loopId - $row.facts.persistedLoopId = $packet.runtime.loopId - $row.facts.graphTitle = "AlphaRenamed"; $row.facts.sidebarTitle = "AlphaRenamed" - $row.facts.checkDescription = "A-start-Z-end"; $row.facts.cancelDraft = "CancelMustNotPersist" - $row.facts.readback = New-ContractReference $coreGraph - $row.facts.cancelBeforeSha256 = $row.facts.readback.sha256 - $row.facts.cancelAfterSha256 = $row.facts.cancelBeforeSha256 - } - "actual-backend-terminal" { - $row.facts.loopId = $packet.runtime.loopId; $row.facts.backendKind = $packet.backend.kind - $row.facts.backendVersion = $packet.backend.version; $row.facts.agentTurns = 2 - $row.facts.input = "Reply with FlightOutput2."; $row.facts.output1 = "A-start-Z-end FlightOutput1" - $row.facts.output2 = "FlightOutput2"; $row.facts.terminalMode = "default" - $row.facts.sessionReadback = New-ContractReference $session - } - "safe-stop-reopen" { - $row.facts.stoppedLoopId = $packet.runtime.loopId; $row.facts.reopenedLoopId = $packet.runtime.loopId - $row.facts.stoppedSessionName = $packet.runtime.terminalSessionName - $row.facts.reopenedTitle = "AlphaRenamed"; $row.facts.reopenedCheckDescription = "A-start-Z-end" - $row.facts.readback = New-ContractReference $stoppedGraph - } - } - } - $packet | Add-Member -NotePropertyName externalReleaseEvidence -NotePropertyValue @{ - predecessor = "NotExecuted"; upgrade = "NotExecuted"; rollback = "NotExecuted" - uninstall = "NotExecuted"; dpiIme = "NotExecuted"; destructiveWorkspace = "NotExecuted" - } - return $packet -} - -function Test-Contract([string] $name, [scriptblock] $body) { - & $body - $script:executed++ - Write-Output "CONTRACT CASE: $name" -} - -function Assert-Rejected([scriptblock] $body, [string] $message) { - $failure = $null - try { & $body | Out-Null } catch { $failure = $_ } - if (-not $failure -or $failure.Exception.Message -notlike "*$message*") { - throw "Expected rejection '$message'; actual: $failure" - } -} - -function Assert-Equal($actual, $expected) { - if ($actual -cne $expected) { throw "Expected '$expected', got '$actual'" } -} - -try { - New-Item -ItemType Directory -Path $root -Force | Out-Null - $env:TEMP = $root - $env:TMP = $root - if ($Case -in @("CoreBoundary", "All")) { - Test-Contract "five core observations do not require an upgrade predecessor or release programme" { - $core = @("artifact-custody", "installed-production", "production-core", "actual-backend-terminal", "safe-stop-reopen") - $rows = @($core | ForEach-Object { [pscustomobject]@{ id = $_ } }) - Assert-PreviewCoreCoverage $rows - Assert-Equal ((Get-PreviewCoreSteps | Sort-Object) -join ',') (($core | Sort-Object) -join ',') - } - Test-Contract "production Codable CORE contract accepts unexecuted predecessor without release approval" { - $packet = New-ProductionCoreContract - Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root - Assert-Equal $packet.externalReleaseEvidence.predecessor "NotExecuted" - $outcome = Get-PreviewCoreOutcome $packet - Assert-Equal $outcome.state "CORE_CONTRACT_COMPLETE" - Assert-Equal $outcome.previewReleaseQualified $false - Assert-Equal $outcome.publicationApproved $false - Assert-Equal $outcome.profileRole "Server" - Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test-only evidence" - } - Test-Contract "saved graph must contain production Codable state, not string or missing fixture flags" { - $packet = New-ProductionCoreContract - $ref = @($packet.observations | Where-Object id -eq "production-core")[0].facts.readback - $path = Join-Path $root $ref.path - $graph = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json - $graph.nodes[0].state = "idle" - [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) - $ref.sha256 = Get-PreviewCoreHash $path - Assert-Rejected { Assert-PreviewCoreSavedGraph $ref $packet $root } "production Codable LoopState" - $graph.nodes[0].state = [pscustomobject]@{ idle = [pscustomobject]@{} } - $graph.nodes[0].PSObject.Properties.Remove("createdAt") - [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) - $ref.sha256 = Get-PreviewCoreHash $path - Assert-Rejected { Assert-PreviewCoreSavedGraph $ref $packet $root } "node timestamp" - } - Test-Contract "ordinary terminal namespace and opaque backend ID are separate and bound" { - $packet = New-ProductionCoreContract - Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root - $packet.runtime.terminalSessionName = "graphcode-" + $packet.runtime.loopId - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "ordinary Windows terminal session name" - $packet.runtime.terminalSessionName = $packet.runtime.loopId - $ref = @($packet.observations | Where-Object id -eq "actual-backend-terminal")[0].facts.sessionReadback - $path = Join-Path $root $ref.path - $session = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json - $session.backendSessionId = "unrelated-opaque-id" - [IO.File]::WriteAllText($path, ($session | ConvertTo-Json)) - $ref.sha256 = Get-PreviewCoreHash $path - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "session identity mismatch" - } - Test-Contract "complete core shape still rejects missing or substituted actual backend proof" { - $packet = New-ProductionCoreContract - $terminal = @($packet.observations | Where-Object id -eq "actual-backend-terminal")[0] - $terminal.status = "NotExecuted" - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "actual-backend-terminal is NotExecuted" - $terminal.status = "Passed"; $terminal.count = 0 - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "positive integer observation count" - $terminal.count = 1; $terminal.facts.actualAgent = $false - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "actual-backend-terminal.actualAgent" - } - Test-Contract "stopped state must survive the core reopen snapshot" { - $packet = New-ProductionCoreContract - $ref = @($packet.observations | Where-Object id -eq "safe-stop-reopen")[0].facts.readback - $path = Join-Path $root $ref.path - $graph = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json - $graph.nodes[0].state = [pscustomobject]@{ running = [pscustomobject]@{} } - [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) - $ref.sha256 = Get-PreviewCoreHash $path - Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "persisted loop is not stopped" - } - } - if ($Case -ne "CoreBoundary") { - Test-Contract "NotExecuted cannot qualify" { - $observation = [pscustomobject]@{ - id = "production-core"; status = "NotExecuted"; count = 0 - method = ""; evidence = @(); facts = [pscustomobject]@{} - } - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "production-core is NotExecuted" - } - } - if ($Case -eq "All") { - Test-Contract "Failed cannot qualify" { - $observation = [pscustomobject]@{ id = "production-core"; status = "Failed"; count = 1 } - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "production-core is Failed" - } - Test-Contract "unknown status cannot qualify" { - $observation = [pscustomobject]@{ id = "production-core"; status = "Unknown"; count = 1 } - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "invalid observation status" - } - Test-Contract "zero and string counts cannot qualify" { - foreach ($count in @(0, "1", 1.5)) { - $observation = [pscustomobject]@{ id = "production-core"; status = "Passed"; count = $count } - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "positive integer observation count" - } - Assert-Equal (Test-PreviewCoreInteger ([long]1)) $true - Assert-Equal (Test-PreviewCoreInteger "1") $false - Assert-Equal (Test-PreviewCoreInteger 1.5) $false - } - Test-Contract "hashes and paths are exact" { - Assert-Rejected { Assert-PreviewCoreHash "not-a-hash" 64 "ZIP" } "invalid ZIP" - foreach ($relative in @("..\foreign.txt", "C:\foreign.txt", "\\server\share\file", "a:stream", "a/../b", "", "NUL.txt", "a\COM1", "wild*.txt")) { - Assert-Rejected { Resolve-PreviewCoreChild $root $relative } "invalid owned relative path" - } - Assert-Equal (Resolve-PreviewCoreChild $root "owned.txt") (Join-Path $root "owned.txt") - } - Test-Contract "prepared packet leaves all live observations unexecuted" { - $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) - Assert-Equal @($packet.observations).Count 5 - Assert-Equal @($packet.observations | Where-Object { $_.status -ne "NotExecuted" -or $_.count -ne 0 }).Count 0 - Assert-Equal $packet.backend.version "" - Assert-Equal $packet.runtime.daemon "Unknown" - Assert-Equal $packet.custody.accepted $false - Assert-Equal $packet.scope "CoreOnly" - Assert-Equal ($packet.profile.PSObject.Properties.Name -contains "minimumViewportDip") $false - Assert-Equal ($packet.custody.PSObject.Properties.Name -contains "sourceCI") $false - foreach ($row in $packet.observations) { - foreach ($check in (Get-PreviewCoreChecks $row.id)) { - Assert-Equal $row.facts[$check] $null - } - } - } - Test-Contract "fixture contains public sentinels but no graph or sessions" { - $fixture = Join-Path $root "fixture" - New-Item -ItemType Directory -Path $fixture | Out-Null - Write-PreviewCoreFixture $fixture - Assert-Equal ([IO.File]::ReadAllText((Join-Path $fixture "project\alpha.txt"))) "A-start-Z-end`n" - Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "support") -Force).Count 0 - Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "install") -Force).Count 0 - Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "evidence") -Force).Count 0 - if ([IO.File]::ReadAllText((Join-Path $fixture "FLIGHT.txt")) -notmatch "PREPARED ONLY") { - throw "Flight instructions did not distinguish preparation from qualification" - } - Assert-Rejected { Write-PreviewCoreFixture $fixture } "already exists" - } - Test-Contract "contract-valid artifact is not a production flight" { - $artifact = New-ContractArtifact - Assert-PreviewCoreArtifact $artifact ("b" * 40) ("c" * 64) - $packet = New-PreviewCorePacket $artifact $root ("d" * 64) - $packet.testOnly = $true - Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test-only evidence" - } - foreach ($mutation in @( - @{ Name = "source identity"; Field = "sourceCommit"; Value = ("e" * 40); Error = "candidate identity mismatch" }, - @{ Name = "package identity"; Field = "sha256"; Value = ("e" * 64); Error = "candidate identity mismatch" }, - @{ Name = "tag source"; Field = "tagCommit"; Value = ("e" * 40); Error = "tag/source mismatch" }, - @{ Name = "tag version"; Field = "tag"; Value = "v9.9.9"; Error = "tag/version mismatch" }, - @{ Name = "development version"; Field = "version"; Value = "1.2.3-dev"; Error = "non-dev" }, - @{ Name = "unknown version"; Field = "version"; Value = "unknown"; Error = "non-dev" }, - @{ Name = "mismatch override"; Field = "tagMismatchAllowed"; Value = $true; Error = "tag mismatch override" }, - @{ Name = "string boolean"; Field = "tagMatchesSource"; Value = "true"; Error = "tag/source equality" }, - @{ Name = "missing unsigned declaration"; Field = "signing"; Value = ""; Error = "unsigned preview warning" }, - @{ Name = "provider repin"; Field = "zmxCommit"; Value = ("e" * 40); Error = "provider pins changed" } - )) { - Test-Contract ("reject " + $mutation.Name) { - $artifact = New-ContractArtifact - $artifact.($mutation.Field) = $mutation.Value - Assert-Rejected { Assert-PreviewCoreArtifact $artifact ("b" * 40) ("c" * 64) } $mutation.Error - } - } - Test-Contract "a parseable boolean string is not an approval" { - Assert-Rejected { Assert-PreviewCoreTrue "true" "approval" } "approval must be witnessed true" - Assert-Rejected { Assert-PreviewCoreFalse "false" "seeded model" } "seeded model must be explicit false" - } - Test-Contract "reparse paths are rejected without following their targets" { - $target = Join-Path $root "owned-target" - $junction = Join-Path $root "owned-junction" - New-Item -ItemType Directory -Path $target | Out-Null - New-Item -ItemType Junction -Path $junction -Target $target | Out-Null - try { - Assert-Rejected { Resolve-PreviewCoreChild $root "owned-junction\readback.json" } "reparse point" - } finally { [IO.Directory]::Delete($junction) } - } - Test-Contract "evidence is digest bound, not merely present" { - [IO.File]::WriteAllText((Join-Path $root "witness.txt"), "public pure-contract witness") - $reference = New-ContractReference "witness.txt" - Assert-PreviewCoreEvidence $reference $root - $reference.sha256 = "0" * 64 - Assert-Rejected { Assert-PreviewCoreEvidence $reference $root } "evidence digest mismatch" - } - Test-Contract "native input counts alone cannot qualify" { - $observation = [pscustomobject]@{ - id = "production-core"; status = "Passed"; count = 10 - method = "QueuedInput"; evidence = @((New-ContractReference "witness.txt")) - } - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "requires NativeManual" - $observation.method = "NativeManual" - Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "PNG pixel witness" - } - Test-Contract "unknown PNG bytes cannot become pixel evidence" { - [IO.File]::WriteAllText((Join-Path $root "invalid.png"), "not a screenshot") - Assert-Rejected { Assert-PreviewCoreEvidence (New-ContractReference "invalid.png") $root -RequirePng } "invalid owned PNG" - Assert-Rejected { Assert-PreviewCoreEvidence (New-ContractReference "witness.txt") $root -RequirePng } "PNG pixel witness" - } - Test-Contract "missing and duplicate flight rows cannot qualify" { - $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) - Assert-Equal @(Get-PreviewCoreSteps | Sort-Object -Unique).Count 5 - Assert-PreviewCoreCoverage $packet.observations - $packet.observations = @() - Assert-Rejected { Assert-PreviewCoreCoverage $packet.observations } "missing or duplicated" - $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) - $packet.observations[0].id = $packet.observations[1].id - Assert-Rejected { Assert-PreviewCoreCoverage $packet.observations } "missing or duplicated" - } - Test-Contract "stub and seeded production claims cannot qualify" { - $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) - $packet.runtime.daemon = "Stub" - Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "ordinary installed production daemon" - $packet.runtime.daemon = "Production" - $packet.runtime.installation = "ScheduledTask" - $packet.runtime.seededModel = $true - Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "seeded model" - $packet.runtime.seededModel = $false - $packet.runtime.testHooks = $true - Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test hooks" - } - Test-Contract "pure artifact mismatch does not create a flight root" { - $archive = Join-Path $root "not-a-package.zip" - [IO.File]::WriteAllText($archive, "test-only; not a production package") - $run = Join-Path $repo (".build\preview-core\flight-" + [guid]::NewGuid().ToString("N")) - Assert-Rejected { Invoke-PreviewCorePrepare $archive ("b" * 40) ("0" * 64) $run } "ZIP hash mismatch" - Assert-Equal (Test-Path -LiteralPath $run) $false - } - Test-Contract "run roots cannot adopt external or shared state" { - Assert-Rejected { Assert-PreviewCoreRunRoot $root } "child of this checkout" - Assert-Rejected { Assert-PreviewCoreRunRoot $repo } "child of this checkout" - } - Test-Contract "package snapshot reader binds actual file bytes without claiming verification" { - $snapshot = Join-Path $root "snapshot" - New-Item -ItemType Directory -Path (Join-Path $snapshot "bin") -Force | Out-Null - $artifact = New-ContractArtifact - $metadata = [ordered]@{ - version = $artifact.version; signing = $artifact.signing - providerPins = [ordered]@{ - winghostty = @{ sha = $artifact.winghosttyCommit } - zmx = @{ sha = $artifact.zmxCommit } - } - sourceProvenance = @{ - sourceCommit = $artifact.sourceCommit; tag = $artifact.tag; tagCommit = $artifact.tagCommit - tagMatchesSource = $true; tagMismatchAllowed = $false - } - } - [IO.File]::WriteAllText((Join-Path $snapshot "metadata.json"), ($metadata | ConvertTo-Json -Depth 5)) - foreach ($file in @("manifest.json", "provider-provenance.json", "bin\graphcode-windows.exe", - "bin\graphcoded.exe", "bin\graphcode.exe", "bin\zmx.exe")) { - [IO.File]::WriteAllText((Join-Path $snapshot $file), "test-only snapshot bytes; NOT a verified package") - } - $read = Get-PreviewCoreArtifact $snapshot ("b" * 40) ("c" * 64) - Assert-Equal $read.hashes.daemon (Get-PreviewCoreHash (Join-Path $snapshot "bin\graphcoded.exe")) - [IO.File]::WriteAllText((Join-Path $snapshot "bin\graphcoded.exe"), "different test-only snapshot bytes") - $changed = Get-PreviewCoreArtifact $snapshot ("b" * 40) ("c" * 64) - if ($changed.hashes.daemon -ceq $read.hashes.daemon) { throw "Changed payload bytes were not detected" } - } - Test-Contract "public checker rejects test-only packet before package or runtime access" { - $run = Join-Path $repo (".build\preview-core\flight-" + [guid]::NewGuid().ToString("N")) - Assert-PreviewCoreRunRoot $run - Assert-Equal (Test-Path -LiteralPath $run) $false - New-Item -ItemType Directory -Path $run -Force | Out-Null - try { - Write-PreviewCoreFixture $run - $scriptHash = Get-PreviewCoreHash $qualification - $packet = New-PreviewCorePacket (New-ContractArtifact) $run $scriptHash - $packet.testOnly = $true - foreach ($file in @("prepared.json", "qualification.json")) { - [IO.File]::WriteAllText((Join-Path $run $file), ($packet | ConvertTo-Json -Depth 20)) - } - $owner = @{ - flightId = $packet.flightId; sourceCommit = "b" * 40; zipSha256 = "c" * 64 - scriptSha256 = $scriptHash - preparedSha256 = Get-PreviewCoreHash (Join-Path $run "prepared.json") - projectSha256 = Get-PreviewCoreHash (Join-Path $run "project\alpha.txt") - } - [IO.File]::WriteAllText((Join-Path $run "owner.json"), ($owner | ConvertTo-Json)) - Assert-Rejected { - & $qualification -Command VerifyEvidence -EvidencePath (Join-Path $run "qualification.json") ` - -ExpectedSource ("b" * 40) -ExpectedSha256 ("c" * 64) - } "test-only evidence" - Assert-Equal (Test-Path -LiteralPath (Join-Path $run "candidate.zip")) $false - $owner.preparedSha256 = "0" * 64 - [IO.File]::WriteAllText((Join-Path $run "owner.json"), ($owner | ConvertTo-Json)) - Assert-Rejected { - & $qualification -Command VerifyEvidence -EvidencePath (Join-Path $run "qualification.json") ` - -ExpectedSource ("b" * 40) -ExpectedSha256 ("c" * 64) - } "prepared packet was modified" - } finally { - Remove-Item -LiteralPath $run -Recurse -Force - } - } - Test-Contract "entrypoint has no live or publication mode" { - $tokens = $null - $errors = $null - $ast = [Management.Automation.Language.Parser]::ParseFile($qualification, [ref]$tokens, [ref]$errors) - Assert-Equal $errors.Count 0 - $commands = @($ast.FindAll({ - param($node) - $node -is [Management.Automation.Language.CommandAst] - }, $true) | ForEach-Object { $_.GetCommandName() }) - foreach ($forbidden in @("Start-Process", "Stop-Process", "Add-Type", "Get-CimInstance", "Get-Process", - "Get-WinEvent", "Set-Clipboard", "Get-Clipboard", "Register-ScheduledTask", "schtasks.exe", "gh")) { - Assert-Equal ($commands -contains $forbidden) $false - } - $liveModes = @($ast.FindAll({ - param($node) - $node -is [Management.Automation.Language.StringConstantExpressionAst] -and - $node.Value -cin @("Install", "Upgrade", "Uninstall", "Publish", "Execute", "Run") - }, $true)) - Assert-Equal $liveModes.Count 0 - } - Test-Contract "one existing packaging-contracts hook consumes this pure unit" { - $validation = Join-Path $repo "Tools\windows\validate.ps1" - $tokens = $null - $errors = $null - $ast = [Management.Automation.Language.Parser]::ParseFile($validation, [ref]$tokens, [ref]$errors) - Assert-Equal $errors.Count 0 - $hooks = @($ast.FindAll({ - param($node) - $node -is [Management.Automation.Language.CommandAst] -and - $node.Extent.Text -match '^& \(Join-Path \$repoRoot "Tools\\windows\\Tests\\PreviewCore\.Tests\.ps1"\)$' - }, $true)) - Assert-Equal $hooks.Count 1 - $ancestor = $hooks[0].Parent - while ($ancestor -and $ancestor -isnot [Management.Automation.Language.IfStatementAst]) { - $ancestor = $ancestor.Parent - } - if (-not $ancestor -or $ancestor.Clauses[0].Item1.Extent.Text -cne '$PackagingPart -ne "real"') { - throw "Pure PreviewCore hook must remain inside packaging-contracts selection" - } - } - } - if ($executed -lt 1) { throw "No PreviewCore contract cases executed" } - Write-Output "PREVIEW_CORE_CONTRACTS: executed=$executed; failed=0; testOnly=true; no production flight ran" -} finally { - $env:TEMP = $oldTemp - $env:TMP = $oldTmp - if (Test-Path -LiteralPath $root -PathType Container) { - Remove-Item -LiteralPath $root -Recurse -Force - } -} +[CmdletBinding()] +param( + [ValidateSet("IncompleteFlight", "CoreBoundary", "All")] + [string] $Case = "All" +) + +$ErrorActionPreference = "Stop" +$qualification = Join-Path $PSScriptRoot "PreviewCore.Qualification.ps1" +if (-not (Test-Path -LiteralPath $qualification -PathType Leaf)) { + throw "PreviewCore qualification entrypoint is missing (structural contract RED; no product runtime ran)" +} +. $qualification -HelpersOnly + +$repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..")) +$root = Join-Path $repo (".build\preview-core-contract-" + [guid]::NewGuid().ToString("N")) +$executed = 0 +$oldTemp = $env:TEMP +$oldTmp = $env:TMP + +function New-ContractArtifact { + $hashes = [ordered]@{} + foreach ($name in @("metadata", "manifest", "providerProvenance", "shell", "daemon", "cli", "zmx")) { + $hashes[$name] = "a" * 64 + } + [pscustomobject]@{ + sourceCommit = "b" * 40; sha256 = "c" * 64; version = "1.2.3-alpha" + tag = "v1.2.3-alpha"; tagCommit = "b" * 40 + tagMatchesSource = $true; tagMismatchAllowed = $false + signing = "UNSIGNED (not code signed)" + winghosttyCommit = "cac8f5f148fd5015d49e81e169ce9006ac7156ea" + zmxCommit = "785b3fd15dcafd1882b495c831a10f98c201b908" + hashes = [pscustomobject]$hashes + } +} + +function New-ContractReference([string] $relative) { + [pscustomobject]@{ path = $relative; sha256 = Get-PreviewCoreHash (Join-Path $root $relative) } +} + +function New-ProductionCoreContract { + $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) | + ConvertTo-Json -Depth 20 | ConvertFrom-Json + $packet.testOnly = $true + $packet.profile.os = "Windows Server (pure contract, not an executed profile)" + $packet.profile.build = "contract-build" + $packet.profile.role = "Server" + $packet.profile.architecture = "x64" + $packet.profile.shellVersion = "contract-shell" + $packet.profile.nativeLease = "test-only; no native lease" + $packet.profile.ownedAccountIsolationWitnessed = $true + $packet.backend.kind = "copilotCLI" + $packet.backend.version = "contract-version; no agent invoked" + $packet.backend.executableSha256 = "e" * 64 + $packet.backend.permissions = "ask" + $packet.backend.model = "backend default" + $packet.backend.approval = "test-only; no credentials or credits granted" + $packet.backend.authenticationProvisionedInOwnedAccount = $true + $packet.runtime.daemon = "Production" + $packet.runtime.installation = "ScheduledTask" + $packet.runtime.seededModel = $false + $packet.runtime.testHooks = $false + $packet.runtime.supportDirectory = Join-Path $root "support" + $packet.runtime.installDirectory = Join-Path $root "install" + $packet.runtime.endpoint = "\\.\pipe\pure-contract-not-a-running-daemon" + $packet.runtime.loopId = "D1111111-1111-4111-8111-111111111111" + $packet.runtime.terminalSessionName = $packet.runtime.loopId + $packet.runtime.backendSessionId = "opaque-conversation-id-not-a-guid" + foreach ($name in @("shell", "daemon", "cli", "zmx")) { + $packet.runtime.installedHashes.$name = $packet.artifact.hashes.$name + } + $prefix = "contract-" + [guid]::NewGuid().ToString("N") + $png = "$prefix.png" + [IO.File]::WriteAllBytes((Join-Path $root $png), [Convert]::FromBase64String( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/lX8AAAAASUVORK5CYII=")) + $build = "$prefix-build.txt" + [IO.File]::WriteAllText((Join-Path $root $build), "Pure contract reference; NOT actual production/build evidence") + $packet.custody.build = New-ContractReference $build + $packet.custody.reviewer = "pure-contract observer, not a real approval" + $packet.custody.accepted = $true + $packet.custody.reviewedEvidenceIsOwnedAndSanitized = $true + # Matches LoopGraph/ProjectRef/LoopNode Codable; this is NOT a captured daemon graph. + $graph = @{ + id = "E2222222-2222-4222-8222-222222222222" + project = @{ path = (Join-Path $root "project").Replace('\', '/'); name = "project"; lastOpenedAt = 42.5 } + edges = @() + nodes = @(@{ + id = $packet.runtime.loopId; title = "AlphaRenamed"; loopType = "turnBased" + backend = $packet.backend.kind; checkDescription = "A-start-Z-end"; createdAt = 42.5 + state = @{ idle = @{} }; pilotState = @{ notPiloted = @{} } + pausesBeforeWritesOnly = $false; attachments = @(); metricHistory = @(); sessionRestarts = 0 + }) + } + $coreGraph = "$prefix-core.json" + [IO.File]::WriteAllText((Join-Path $root $coreGraph), ($graph | ConvertTo-Json -Depth 10)) + $graph.nodes[0].state = @{ stopped = @{} } + $stoppedGraph = "$prefix-stopped.json" + [IO.File]::WriteAllText((Join-Path $root $stoppedGraph), ($graph | ConvertTo-Json -Depth 10)) + $session = "$prefix-session.json" + $binding = @{ + loopId = $packet.runtime.loopId; terminalSessionName = $packet.runtime.terminalSessionName + backendKind = $packet.backend.kind; backendSessionId = $packet.runtime.backendSessionId + backendExecutableSha256 = $packet.backend.executableSha256 + } + [IO.File]::WriteAllText((Join-Path $root $session), ($binding | ConvertTo-Json)) + foreach ($row in $packet.observations) { + $row.status = "Passed"; $row.count = 1 + $row.method = if ($row.id -in @("production-core", "actual-backend-terminal", "safe-stop-reopen")) { "NativeManual" } else { "OwnedRuntime" } + $row.evidence = @((New-ContractReference $png)) + foreach ($check in (Get-PreviewCoreChecks $row.id)) { $row.facts.$check = $true } + switch ($row.id) { + "production-core" { + $row.facts.createdCount = 1; $row.facts.selectedLoopId = $packet.runtime.loopId + $row.facts.persistedLoopId = $packet.runtime.loopId + $row.facts.graphTitle = "AlphaRenamed"; $row.facts.sidebarTitle = "AlphaRenamed" + $row.facts.checkDescription = "A-start-Z-end"; $row.facts.cancelDraft = "CancelMustNotPersist" + $row.facts.readback = New-ContractReference $coreGraph + $row.facts.cancelBeforeSha256 = $row.facts.readback.sha256 + $row.facts.cancelAfterSha256 = $row.facts.cancelBeforeSha256 + } + "actual-backend-terminal" { + $row.facts.loopId = $packet.runtime.loopId; $row.facts.backendKind = $packet.backend.kind + $row.facts.backendVersion = $packet.backend.version; $row.facts.agentTurns = 2 + $row.facts.input = "Reply with FlightOutput2."; $row.facts.output1 = "A-start-Z-end FlightOutput1" + $row.facts.output2 = "FlightOutput2"; $row.facts.terminalMode = "default" + $row.facts.sessionReadback = New-ContractReference $session + } + "safe-stop-reopen" { + $row.facts.stoppedLoopId = $packet.runtime.loopId; $row.facts.reopenedLoopId = $packet.runtime.loopId + $row.facts.stoppedSessionName = $packet.runtime.terminalSessionName + $row.facts.reopenedTitle = "AlphaRenamed"; $row.facts.reopenedCheckDescription = "A-start-Z-end" + $row.facts.readback = New-ContractReference $stoppedGraph + } + } + } + $packet | Add-Member -NotePropertyName externalReleaseEvidence -NotePropertyValue @{ + predecessor = "NotExecuted"; upgrade = "NotExecuted"; rollback = "NotExecuted" + uninstall = "NotExecuted"; dpiIme = "NotExecuted"; destructiveWorkspace = "NotExecuted" + } + return $packet +} + +function Test-Contract([string] $name, [scriptblock] $body) { + & $body + $script:executed++ + Write-Output "CONTRACT CASE: $name" +} + +function Assert-Rejected([scriptblock] $body, [string] $message) { + $failure = $null + try { & $body | Out-Null } catch { $failure = $_ } + if (-not $failure -or $failure.Exception.Message -notlike "*$message*") { + throw "Expected rejection '$message'; actual: $failure" + } +} + +function Assert-Equal($actual, $expected) { + if ($actual -cne $expected) { throw "Expected '$expected', got '$actual'" } +} + +try { + New-Item -ItemType Directory -Path $root -Force | Out-Null + $env:TEMP = $root + $env:TMP = $root + if ($Case -in @("CoreBoundary", "All")) { + Test-Contract "five core observations do not require an upgrade predecessor or release programme" { + $core = @("artifact-custody", "installed-production", "production-core", "actual-backend-terminal", "safe-stop-reopen") + $rows = @($core | ForEach-Object { [pscustomobject]@{ id = $_ } }) + Assert-PreviewCoreCoverage $rows + Assert-Equal ((Get-PreviewCoreSteps | Sort-Object) -join ',') (($core | Sort-Object) -join ',') + } + Test-Contract "production Codable CORE contract accepts unexecuted predecessor without release approval" { + $packet = New-ProductionCoreContract + Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root + Assert-Equal $packet.externalReleaseEvidence.predecessor "NotExecuted" + $outcome = Get-PreviewCoreOutcome $packet + Assert-Equal $outcome.state "CORE_CONTRACT_COMPLETE" + Assert-Equal $outcome.previewReleaseQualified $false + Assert-Equal $outcome.publicationApproved $false + Assert-Equal $outcome.profileRole "Server" + Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test-only evidence" + } + Test-Contract "saved graph must contain production Codable state, not string or missing fixture flags" { + $packet = New-ProductionCoreContract + $ref = @($packet.observations | Where-Object id -eq "production-core")[0].facts.readback + $path = Join-Path $root $ref.path + $graph = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json + $graph.nodes[0].state = "idle" + [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) + $ref.sha256 = Get-PreviewCoreHash $path + Assert-Rejected { Assert-PreviewCoreSavedGraph $ref $packet $root } "production Codable LoopState" + $graph.nodes[0].state = [pscustomobject]@{ idle = [pscustomobject]@{} } + $graph.nodes[0].PSObject.Properties.Remove("createdAt") + [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) + $ref.sha256 = Get-PreviewCoreHash $path + Assert-Rejected { Assert-PreviewCoreSavedGraph $ref $packet $root } "node timestamp" + } + Test-Contract "ordinary terminal namespace and opaque backend ID are separate and bound" { + $packet = New-ProductionCoreContract + Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root + $packet.runtime.terminalSessionName = "graphcode-" + $packet.runtime.loopId + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "ordinary Windows terminal session name" + $packet.runtime.terminalSessionName = $packet.runtime.loopId + $ref = @($packet.observations | Where-Object id -eq "actual-backend-terminal")[0].facts.sessionReadback + $path = Join-Path $root $ref.path + $session = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json + $session.backendSessionId = "unrelated-opaque-id" + [IO.File]::WriteAllText($path, ($session | ConvertTo-Json)) + $ref.sha256 = Get-PreviewCoreHash $path + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "session identity mismatch" + } + Test-Contract "complete core shape still rejects missing or substituted actual backend proof" { + $packet = New-ProductionCoreContract + $terminal = @($packet.observations | Where-Object id -eq "actual-backend-terminal")[0] + $terminal.status = "NotExecuted" + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "actual-backend-terminal is NotExecuted" + $terminal.status = "Passed"; $terminal.count = 0 + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "positive integer observation count" + $terminal.count = 1; $terminal.facts.actualAgent = $false + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "actual-backend-terminal.actualAgent" + } + Test-Contract "stopped state must survive the core reopen snapshot" { + $packet = New-ProductionCoreContract + $ref = @($packet.observations | Where-Object id -eq "safe-stop-reopen")[0].facts.readback + $path = Join-Path $root $ref.path + $graph = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json + $graph.nodes[0].state = [pscustomobject]@{ running = [pscustomobject]@{} } + [IO.File]::WriteAllText($path, ($graph | ConvertTo-Json -Depth 10)) + $ref.sha256 = Get-PreviewCoreHash $path + Assert-Rejected { Assert-PreviewCoreCoreContract $packet ("b" * 40) ("c" * 64) $root } "persisted loop is not stopped" + } + } + if ($Case -ne "CoreBoundary") { + Test-Contract "NotExecuted cannot qualify" { + $observation = [pscustomobject]@{ + id = "production-core"; status = "NotExecuted"; count = 0 + method = ""; evidence = @(); facts = [pscustomobject]@{} + } + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "production-core is NotExecuted" + } + } + if ($Case -eq "All") { + Test-Contract "Failed cannot qualify" { + $observation = [pscustomobject]@{ id = "production-core"; status = "Failed"; count = 1 } + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "production-core is Failed" + } + Test-Contract "unknown status cannot qualify" { + $observation = [pscustomobject]@{ id = "production-core"; status = "Unknown"; count = 1 } + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "invalid observation status" + } + Test-Contract "zero and string counts cannot qualify" { + foreach ($count in @(0, "1", 1.5)) { + $observation = [pscustomobject]@{ id = "production-core"; status = "Passed"; count = $count } + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "positive integer observation count" + } + Assert-Equal (Test-PreviewCoreInteger ([long]1)) $true + Assert-Equal (Test-PreviewCoreInteger "1") $false + Assert-Equal (Test-PreviewCoreInteger 1.5) $false + } + Test-Contract "hashes and paths are exact" { + Assert-Rejected { Assert-PreviewCoreHash "not-a-hash" 64 "ZIP" } "invalid ZIP" + foreach ($relative in @("..\foreign.txt", "C:\foreign.txt", "\\server\share\file", "a:stream", "a/../b", "", "NUL.txt", "a\COM1", "wild*.txt")) { + Assert-Rejected { Resolve-PreviewCoreChild $root $relative } "invalid owned relative path" + } + Assert-Equal (Resolve-PreviewCoreChild $root "owned.txt") (Join-Path $root "owned.txt") + } + Test-Contract "prepared packet leaves all live observations unexecuted" { + $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) + Assert-Equal @($packet.observations).Count 5 + Assert-Equal @($packet.observations | Where-Object { $_.status -ne "NotExecuted" -or $_.count -ne 0 }).Count 0 + Assert-Equal $packet.backend.version "" + Assert-Equal $packet.runtime.daemon "Unknown" + Assert-Equal $packet.custody.accepted $false + Assert-Equal $packet.scope "CoreOnly" + Assert-Equal ($packet.profile.PSObject.Properties.Name -contains "minimumViewportDip") $false + Assert-Equal ($packet.custody.PSObject.Properties.Name -contains "sourceCI") $false + foreach ($row in $packet.observations) { + foreach ($check in (Get-PreviewCoreChecks $row.id)) { + Assert-Equal $row.facts[$check] $null + } + } + } + Test-Contract "fixture contains public sentinels but no graph or sessions" { + $fixture = Join-Path $root "fixture" + New-Item -ItemType Directory -Path $fixture | Out-Null + Write-PreviewCoreFixture $fixture + Assert-Equal ([IO.File]::ReadAllText((Join-Path $fixture "project\alpha.txt"))) "A-start-Z-end`n" + Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "support") -Force).Count 0 + Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "install") -Force).Count 0 + Assert-Equal @(Get-ChildItem -LiteralPath (Join-Path $fixture "evidence") -Force).Count 0 + if ([IO.File]::ReadAllText((Join-Path $fixture "FLIGHT.txt")) -notmatch "PREPARED ONLY") { + throw "Flight instructions did not distinguish preparation from qualification" + } + Assert-Rejected { Write-PreviewCoreFixture $fixture } "already exists" + } + Test-Contract "contract-valid artifact is not a production flight" { + $artifact = New-ContractArtifact + Assert-PreviewCoreArtifact $artifact ("b" * 40) ("c" * 64) + $packet = New-PreviewCorePacket $artifact $root ("d" * 64) + $packet.testOnly = $true + Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test-only evidence" + } + foreach ($mutation in @( + @{ Name = "source identity"; Field = "sourceCommit"; Value = ("e" * 40); Error = "candidate identity mismatch" }, + @{ Name = "package identity"; Field = "sha256"; Value = ("e" * 64); Error = "candidate identity mismatch" }, + @{ Name = "tag source"; Field = "tagCommit"; Value = ("e" * 40); Error = "tag/source mismatch" }, + @{ Name = "tag version"; Field = "tag"; Value = "v9.9.9"; Error = "tag/version mismatch" }, + @{ Name = "development version"; Field = "version"; Value = "1.2.3-dev"; Error = "non-dev" }, + @{ Name = "unknown version"; Field = "version"; Value = "unknown"; Error = "non-dev" }, + @{ Name = "mismatch override"; Field = "tagMismatchAllowed"; Value = $true; Error = "tag mismatch override" }, + @{ Name = "string boolean"; Field = "tagMatchesSource"; Value = "true"; Error = "tag/source equality" }, + @{ Name = "missing unsigned declaration"; Field = "signing"; Value = ""; Error = "unsigned preview warning" }, + @{ Name = "provider repin"; Field = "zmxCommit"; Value = ("e" * 40); Error = "provider pins changed" } + )) { + Test-Contract ("reject " + $mutation.Name) { + $artifact = New-ContractArtifact + $artifact.($mutation.Field) = $mutation.Value + Assert-Rejected { Assert-PreviewCoreArtifact $artifact ("b" * 40) ("c" * 64) } $mutation.Error + } + } + Test-Contract "a parseable boolean string is not an approval" { + Assert-Rejected { Assert-PreviewCoreTrue "true" "approval" } "approval must be witnessed true" + Assert-Rejected { Assert-PreviewCoreFalse "false" "seeded model" } "seeded model must be explicit false" + } + Test-Contract "reparse paths are rejected without following their targets" { + $target = Join-Path $root "owned-target" + $junction = Join-Path $root "owned-junction" + New-Item -ItemType Directory -Path $target | Out-Null + New-Item -ItemType Junction -Path $junction -Target $target | Out-Null + try { + Assert-Rejected { Resolve-PreviewCoreChild $root "owned-junction\readback.json" } "reparse point" + } finally { [IO.Directory]::Delete($junction) } + } + Test-Contract "evidence is digest bound, not merely present" { + [IO.File]::WriteAllText((Join-Path $root "witness.txt"), "public pure-contract witness") + $reference = New-ContractReference "witness.txt" + Assert-PreviewCoreEvidence $reference $root + $reference.sha256 = "0" * 64 + Assert-Rejected { Assert-PreviewCoreEvidence $reference $root } "evidence digest mismatch" + } + Test-Contract "native input counts alone cannot qualify" { + $observation = [pscustomobject]@{ + id = "production-core"; status = "Passed"; count = 10 + method = "QueuedInput"; evidence = @((New-ContractReference "witness.txt")) + } + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "requires NativeManual" + $observation.method = "NativeManual" + Assert-Rejected { Assert-PreviewCoreObservation $observation $root } "PNG pixel witness" + } + Test-Contract "unknown PNG bytes cannot become pixel evidence" { + [IO.File]::WriteAllText((Join-Path $root "invalid.png"), "not a screenshot") + Assert-Rejected { Assert-PreviewCoreEvidence (New-ContractReference "invalid.png") $root -RequirePng } "invalid owned PNG" + Assert-Rejected { Assert-PreviewCoreEvidence (New-ContractReference "witness.txt") $root -RequirePng } "PNG pixel witness" + } + Test-Contract "missing and duplicate flight rows cannot qualify" { + $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) + Assert-Equal @(Get-PreviewCoreSteps | Sort-Object -Unique).Count 5 + Assert-PreviewCoreCoverage $packet.observations + $packet.observations = @() + Assert-Rejected { Assert-PreviewCoreCoverage $packet.observations } "missing or duplicated" + $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) + $packet.observations[0].id = $packet.observations[1].id + Assert-Rejected { Assert-PreviewCoreCoverage $packet.observations } "missing or duplicated" + } + Test-Contract "stub and seeded production claims cannot qualify" { + $packet = New-PreviewCorePacket (New-ContractArtifact) $root ("d" * 64) + $packet.runtime.daemon = "Stub" + Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "ordinary installed production daemon" + $packet.runtime.daemon = "Production" + $packet.runtime.installation = "ScheduledTask" + $packet.runtime.seededModel = $true + Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "seeded model" + $packet.runtime.seededModel = $false + $packet.runtime.testHooks = $true + Assert-Rejected { Assert-PreviewCoreFlight $packet ("b" * 40) ("c" * 64) $root } "test hooks" + } + Test-Contract "pure artifact mismatch does not create a flight root" { + $archive = Join-Path $root "not-a-package.zip" + [IO.File]::WriteAllText($archive, "test-only; not a production package") + $run = Join-Path $repo (".build\preview-core\flight-" + [guid]::NewGuid().ToString("N")) + Assert-Rejected { Invoke-PreviewCorePrepare $archive ("b" * 40) ("0" * 64) $run } "ZIP hash mismatch" + Assert-Equal (Test-Path -LiteralPath $run) $false + } + Test-Contract "run roots cannot adopt external or shared state" { + Assert-Rejected { Assert-PreviewCoreRunRoot $root } "child of this checkout" + Assert-Rejected { Assert-PreviewCoreRunRoot $repo } "child of this checkout" + } + Test-Contract "package snapshot reader binds actual file bytes without claiming verification" { + $snapshot = Join-Path $root "snapshot" + New-Item -ItemType Directory -Path (Join-Path $snapshot "bin") -Force | Out-Null + $artifact = New-ContractArtifact + $metadata = [ordered]@{ + version = $artifact.version; signing = $artifact.signing + providerPins = [ordered]@{ + winghostty = @{ sha = $artifact.winghosttyCommit } + zmx = @{ sha = $artifact.zmxCommit } + } + sourceProvenance = @{ + sourceCommit = $artifact.sourceCommit; tag = $artifact.tag; tagCommit = $artifact.tagCommit + tagMatchesSource = $true; tagMismatchAllowed = $false + } + } + [IO.File]::WriteAllText((Join-Path $snapshot "metadata.json"), ($metadata | ConvertTo-Json -Depth 5)) + foreach ($file in @("manifest.json", "provider-provenance.json", "bin\graphcode-windows.exe", + "bin\graphcoded.exe", "bin\graphcode.exe", "bin\zmx.exe")) { + [IO.File]::WriteAllText((Join-Path $snapshot $file), "test-only snapshot bytes; NOT a verified package") + } + $read = Get-PreviewCoreArtifact $snapshot ("b" * 40) ("c" * 64) + Assert-Equal $read.hashes.daemon (Get-PreviewCoreHash (Join-Path $snapshot "bin\graphcoded.exe")) + [IO.File]::WriteAllText((Join-Path $snapshot "bin\graphcoded.exe"), "different test-only snapshot bytes") + $changed = Get-PreviewCoreArtifact $snapshot ("b" * 40) ("c" * 64) + if ($changed.hashes.daemon -ceq $read.hashes.daemon) { throw "Changed payload bytes were not detected" } + } + Test-Contract "public checker rejects test-only packet before package or runtime access" { + $run = Join-Path $repo (".build\preview-core\flight-" + [guid]::NewGuid().ToString("N")) + Assert-PreviewCoreRunRoot $run + Assert-Equal (Test-Path -LiteralPath $run) $false + New-Item -ItemType Directory -Path $run -Force | Out-Null + try { + Write-PreviewCoreFixture $run + $scriptHash = Get-PreviewCoreHash $qualification + $packet = New-PreviewCorePacket (New-ContractArtifact) $run $scriptHash + $packet.testOnly = $true + foreach ($file in @("prepared.json", "qualification.json")) { + [IO.File]::WriteAllText((Join-Path $run $file), ($packet | ConvertTo-Json -Depth 20)) + } + $owner = @{ + flightId = $packet.flightId; sourceCommit = "b" * 40; zipSha256 = "c" * 64 + scriptSha256 = $scriptHash + preparedSha256 = Get-PreviewCoreHash (Join-Path $run "prepared.json") + projectSha256 = Get-PreviewCoreHash (Join-Path $run "project\alpha.txt") + } + [IO.File]::WriteAllText((Join-Path $run "owner.json"), ($owner | ConvertTo-Json)) + Assert-Rejected { + & $qualification -Command VerifyEvidence -EvidencePath (Join-Path $run "qualification.json") ` + -ExpectedSource ("b" * 40) -ExpectedSha256 ("c" * 64) + } "test-only evidence" + Assert-Equal (Test-Path -LiteralPath (Join-Path $run "candidate.zip")) $false + $owner.preparedSha256 = "0" * 64 + [IO.File]::WriteAllText((Join-Path $run "owner.json"), ($owner | ConvertTo-Json)) + Assert-Rejected { + & $qualification -Command VerifyEvidence -EvidencePath (Join-Path $run "qualification.json") ` + -ExpectedSource ("b" * 40) -ExpectedSha256 ("c" * 64) + } "prepared packet was modified" + } finally { + Remove-Item -LiteralPath $run -Recurse -Force + } + } + Test-Contract "entrypoint has no live or publication mode" { + $tokens = $null + $errors = $null + $ast = [Management.Automation.Language.Parser]::ParseFile($qualification, [ref]$tokens, [ref]$errors) + Assert-Equal $errors.Count 0 + $commands = @($ast.FindAll({ + param($node) + $node -is [Management.Automation.Language.CommandAst] + }, $true) | ForEach-Object { $_.GetCommandName() }) + foreach ($forbidden in @("Start-Process", "Stop-Process", "Add-Type", "Get-CimInstance", "Get-Process", + "Get-WinEvent", "Set-Clipboard", "Get-Clipboard", "Register-ScheduledTask", "schtasks.exe", "gh")) { + Assert-Equal ($commands -contains $forbidden) $false + } + $liveModes = @($ast.FindAll({ + param($node) + $node -is [Management.Automation.Language.StringConstantExpressionAst] -and + $node.Value -cin @("Install", "Upgrade", "Uninstall", "Publish", "Execute", "Run") + }, $true)) + Assert-Equal $liveModes.Count 0 + } + Test-Contract "one existing packaging-contracts hook consumes this pure unit" { + $validation = Join-Path $repo "Tools\windows\validate.ps1" + $tokens = $null + $errors = $null + $ast = [Management.Automation.Language.Parser]::ParseFile($validation, [ref]$tokens, [ref]$errors) + Assert-Equal $errors.Count 0 + $hooks = @($ast.FindAll({ + param($node) + $node -is [Management.Automation.Language.CommandAst] -and + $node.Extent.Text -match '^& \(Join-Path \$repoRoot "Tools\\windows\\Tests\\PreviewCore\.Tests\.ps1"\)$' + }, $true)) + Assert-Equal $hooks.Count 1 + $ancestor = $hooks[0].Parent + while ($ancestor -and $ancestor -isnot [Management.Automation.Language.IfStatementAst]) { + $ancestor = $ancestor.Parent + } + if (-not $ancestor -or $ancestor.Clauses[0].Item1.Extent.Text -cne '$PackagingPart -ne "real"') { + throw "Pure PreviewCore hook must remain inside packaging-contracts selection" + } + } + } + if ($executed -lt 1) { throw "No PreviewCore contract cases executed" } + Write-Output "PREVIEW_CORE_CONTRACTS: executed=$executed; failed=0; testOnly=true; no production flight ran" +} finally { + $env:TEMP = $oldTemp + $env:TMP = $oldTmp + if (Test-Path -LiteralPath $root -PathType Container) { + Remove-Item -LiteralPath $root -Recurse -Force + } +} diff --git a/Tools/windows/Tests/TerminalGate.Tests.ps1 b/Tools/windows/Tests/TerminalGate.Tests.ps1 index 01d539b1..04452b67 100644 --- a/Tools/windows/Tests/TerminalGate.Tests.ps1 +++ b/Tools/windows/Tests/TerminalGate.Tests.ps1 @@ -239,7 +239,7 @@ foreach ($provider in @("winghostty", "zmx")) { } Assert-Contract ($pins.schemaVersion -eq 1) "provider pin schema is not 1" Assert-Contract ($pins.winghostty.sha -eq - "e0a5579f3b470bede72294d661282a391c502ace") "Winghostty SHA is not exact" + "cac8f5f148fd5015d49e81e169ce9006ac7156ea") "Winghostty SHA is not exact" Assert-Contract ($pins.zmx.sha -eq "785b3fd15dcafd1882b495c831a10f98c201b908") "zmx SHA is not exact" Assert-Contract ($pins.winghostty.remoteUrl -eq diff --git a/Tools/windows/Tests/VisualBaseline.Tests.ps1 b/Tools/windows/Tests/VisualBaseline.Tests.ps1 index a579887c..cc4bd8e9 100644 --- a/Tools/windows/Tests/VisualBaseline.Tests.ps1 +++ b/Tools/windows/Tests/VisualBaseline.Tests.ps1 @@ -399,7 +399,7 @@ try { providers = @{ zmx = @{ sha256 = ('4' * 64); pin = '785b3fd15dcafd1882b495c831a10f98c201b908' artifact = '.graphcode-tools\providers\zmx\zig-out\bin\zmx.exe' } - winghostty = @{ sha256 = ('5' * 64); pin = 'e0a5579f3b470bede72294d661282a391c502ace' + winghostty = @{ sha256 = ('5' * 64); pin = 'cac8f5f148fd5015d49e81e169ce9006ac7156ea' artifact = '.graphcode-tools\providers\winghostty\zig-out\lib\winghostty-win32-host.lib' } } renderer = @{ uiaGate = $false; daemonSupervisorHook = $false } diff --git a/Tools/windows/Tests/WindowsShell.Tests.ps1 b/Tools/windows/Tests/WindowsShell.Tests.ps1 index 69b705bc..2e159ceb 100644 --- a/Tools/windows/Tests/WindowsShell.Tests.ps1 +++ b/Tools/windows/Tests/WindowsShell.Tests.ps1 @@ -785,7 +785,7 @@ $pins = Get-Content -LiteralPath (Join-Path $shellRoot "provider-pins.json") -Ra ConvertFrom-Json Assert-Contract ($pins.schemaVersion -eq 1) "provider pin schema is not 1" Assert-Contract ($pins.winghostty.sha -eq - "e0a5579f3b470bede72294d661282a391c502ace") "Winghostty pin changed" + "cac8f5f148fd5015d49e81e169ce9006ac7156ea") "Winghostty pin changed" Assert-Contract ($pins.zmx.sha -eq "785b3fd15dcafd1882b495c831a10f98c201b908") "zmx pin changed" Assert-Contract ($pins.winghostty.remoteUrl -eq diff --git a/graphcode-windows/README.md b/graphcode-windows/README.md index 5dc6cf5e..fd5d36de 100644 --- a/graphcode-windows/README.md +++ b/graphcode-windows/README.md @@ -145,6 +145,13 @@ changes, and continues to provide logical 96-DPI 8x16 cell metrics for grid geometry and hit testing. Applying the monitor ratio through both mechanisms would scale the terminal twice. +Every created surface also applies the macOS terminal appearance contract +through the same pinned provider: `#0A0C0B` at 0.80 background opacity and 2 +logical points of background-colored padding on every edge. Winghostty owns +point-to-device-pixel conversion for that padding at the monitor DPI. Split +pane geometry reserves one logical point between adjacent child HWNDs and the +terminal chrome paints that seam once; child surfaces never overlap it. + The provider verifies exact installed face selection before using a configured family and retains Consolas as its final legacy fallback. GraphCode does not currently install these fonts. Unit and provider integration tests therefore @@ -156,7 +163,7 @@ coverage, antialiasing appearance, or visual parity. ### Terminal VT parser and glyph snapshots The public `libghostty-vt` C API from the existing Winghostty pin -`e0a5579f3b470bede72294d661282a391c502ace` is the production default. Set +`cac8f5f148fd5015d49e81e169ce9006ac7156ea` is the production default. Set `GRAPHCODE_EXPERIMENTAL_TERMINAL_VT=0` before startup only as a rollback to the limited legacy parser; an absent variable or exactly `1` enables Ghostty VT. Other values, including an empty value, fail workspace initialization with diff --git a/graphcode-windows/provider-pins.json b/graphcode-windows/provider-pins.json index d21eb96e..b502bdfb 100644 --- a/graphcode-windows/provider-pins.json +++ b/graphcode-windows/provider-pins.json @@ -3,7 +3,7 @@ "winghostty": { "repository": "coneilen/winghostty", "remoteUrl": "https://github.com/coneilen/winghostty.git", - "sha": "e0a5579f3b470bede72294d661282a391c502ace", + "sha": "cac8f5f148fd5015d49e81e169ce9006ac7156ea", "artifact": "zig-out/lib/winghostty-win32-host.lib", "minimumZig": "0.15.2" }, diff --git a/graphcode-windows/src/TerminalSurface.zig b/graphcode-windows/src/TerminalSurface.zig index b41a86d1..ff3e6fce 100644 --- a/graphcode-windows/src/TerminalSurface.zig +++ b/graphcode-windows/src/TerminalSurface.zig @@ -32,6 +32,9 @@ const terminal_font_fallbacks = [_][*c]const u8{ const terminal_font_point_size: f32 = 13.0 * 0.9; const terminal_font_cell_width_ratio: f32 = 0.6; const terminal_font_weight: u32 = 400; +const terminal_background_rgb: u32 = 0x000A0C0B; +const terminal_background_opacity: f32 = 0.80; +const terminal_padding_points: f32 = 2.0; fn terminalFontConfig() c.winghostty_font_config { var config: c.winghostty_font_config = undefined; @@ -62,6 +65,31 @@ fn applyTerminalFontConfig(surface: *c.winghostty_surface) !void { try applyTerminalFontConfigWith(surface, c.winghostty_surface_set_font_config); } +fn terminalAppearanceConfig() c.winghostty_appearance_config { + var config: c.winghostty_appearance_config = undefined; + c.winghostty_appearance_config_init(&config); + config.background_rgb = terminal_background_rgb; + config.background_opacity = terminal_background_opacity; + config.padding_top = terminal_padding_points; + config.padding_right = terminal_padding_points; + config.padding_bottom = terminal_padding_points; + config.padding_left = terminal_padding_points; + return config; +} + +fn applyTerminalAppearanceConfigWith( + surface: *c.winghostty_surface, + comptime set_appearance_config: anytype, +) !void { + var config = terminalAppearanceConfig(); + if (set_appearance_config(surface, &config) != c.WINGHOSTTY_OK) + return error.WinghosttyAppearanceConfigFailed; +} + +fn applyTerminalAppearanceConfig(surface: *c.winghostty_surface) !void { + try applyTerminalAppearanceConfigWith(surface, c.winghostty_surface_set_appearance_config); +} + const GridSize = struct { cols: u16, rows: u16, @@ -89,6 +117,26 @@ fn gridSizeForBounds( }; } +fn gridSizeForTerminalBounds( + width: u32, + height: u32, + metrics: c.winghostty_cell_metrics, + dpi: u32, +) error{GridTooLarge}!GridSize { + if (width == 0 or height == 0) return gridSizeForBounds(width, height, metrics); + const padding: u32 = @intCast(Dpi.scale( + @intFromFloat(terminal_padding_points), + dpi, + )); + const horizontal_padding = @min(@as(u64, padding) * 2, @as(u64, width - 1)); + const vertical_padding = @min(@as(u64, padding) * 2, @as(u64, height - 1)); + return gridSizeForBounds( + width - @as(u32, @intCast(horizontal_padding)), + height - @as(u32, @intCast(vertical_padding)), + metrics, + ); +} + fn resizedCellBuffer( allocator: std.mem.Allocator, old_cells: []const c.winghostty_terminal_cell, @@ -178,8 +226,17 @@ fn paneBounds( const horizontal = direction == .horizontal; const available_height = height - tab_bar_height; const span = if (horizontal) width else available_height; - const first = @divTrunc(@as(i64, span) * @as(i64, @intCast(position)), @as(i64, @intCast(pane_count))); - const next = @divTrunc(@as(i64, span) * @as(i64, @intCast(position + 1)), @as(i64, @intCast(pane_count))); + const divider_pixels: i64 = Dpi.scale(1, dpi); + const divider_total = divider_pixels * @as(i64, @intCast(pane_count - 1)); + const available_span: i64 = span; + if (available_span <= divider_total) { + return .{ .x = origin_x, .y = origin_y, .width = 0, .height = 0 }; + } + const content_span = available_span - divider_total; + const first = @divTrunc(content_span * @as(i64, @intCast(position)), @as(i64, @intCast(pane_count))) + + divider_pixels * @as(i64, @intCast(position)); + const next = @divTrunc(content_span * @as(i64, @intCast(position + 1)), @as(i64, @intCast(pane_count))) + + divider_pixels * @as(i64, @intCast(position)); const pane_width = if (horizontal) next - first else width; // LoopWorkspaceView.swift:318-331 puts a header inside each split-tree leaf, // including vertically stacked panes, rather than reserving one per tab. @@ -194,6 +251,38 @@ fn paneBounds( }; } +fn paneDividerBounds( + origin_x: i32, + origin_y: i32, + width: i32, + height: i32, + dpi: u32, + direction: WorkspaceLayout.Direction, + position: usize, + pane_count: usize, +) ?c.RECT { + if (position + 1 >= pane_count) return null; + const pane = paneBounds(origin_x, origin_y, width, height, dpi, direction, position, pane_count); + if (pane.width == 0 or pane.height == 0) return null; + const divider = Dpi.scale(1, dpi); + if (direction == .horizontal) { + const left = pane.x + @as(i32, @intCast(pane.width)); + return .{ + .left = left, + .top = origin_y + Dpi.scale(Tokens.tab_bar_height, dpi), + .right = left + divider, + .bottom = origin_y + height, + }; + } + const top = pane.y + @as(i32, @intCast(pane.height)); + return .{ + .left = origin_x, + .top = top, + .right = origin_x + width, + .bottom = top + divider, + }; +} + const ParserState = enum { normal, escape, csi, osc }; const input_queue_capacity: usize = 64; const input_queue_max_bytes: usize = 1024 * 1024; @@ -1626,6 +1715,10 @@ pub const Workspace = struct { self.destroySurface(index); return err; }; + applyTerminalAppearanceConfig(self.surfaces[index].surface.?) catch |err| { + self.destroySurface(index); + return err; + }; self.surfaces[index].destroyed = false; self.surfaces[index].destroying = false; @@ -1791,6 +1884,10 @@ pub const Workspace = struct { self.destroySurface(index); return err; }; + applyTerminalAppearanceConfig(self.surfaces[index].surface.?) catch |err| { + self.destroySurface(index); + return err; + }; self.surfaces[index].destroyed = false; self.surfaces[index].destroying = false; @@ -2406,8 +2503,19 @@ pub const Workspace = struct { paintChromeGlyph(hdc, bounds, chromeGlyph(index), self.dpi); } const selected = self.layout.selectedConst() orelse return; - for (selected.panes.items, 0..) |_, position| + for (selected.panes.items, 0..) |_, position| { if (self.paneHeaderChrome(position)) |header| paintPaneHeader(hdc, header, self.dpi); + if (paneDividerBounds( + self.layout_origin_x, + self.layout_origin_y, + self.layout_width, + self.layout_height, + self.dpi, + selected.split_direction, + position, + selected.panes.items.len, + )) |divider| fillRect(hdc, divider, Tokens.canvas_grid_line); + } } pub fn paintLoopBar( @@ -2709,7 +2817,7 @@ pub const Workspace = struct { position, tab.panes.items.len, ); - return gridSizeForBounds(bounds.width, bounds.height, metrics); + return gridSizeForTerminalBounds(bounds.width, bounds.height, metrics, self.dpi); } return self.workspaceGridSize(); } @@ -2725,7 +2833,7 @@ pub const Workspace = struct { 0, 1, ); - return gridSizeForBounds(bounds.width, bounds.height, self.fallbackCellMetrics()); + return gridSizeForTerminalBounds(bounds.width, bounds.height, self.fallbackCellMetrics(), self.dpi); } fn splitGridSize(self: *const Workspace, direction: WorkspaceLayout.Direction) !GridSize { @@ -2742,7 +2850,7 @@ pub const Workspace = struct { position, count, ); - return gridSizeForBounds(bounds.width, bounds.height, self.fallbackCellMetrics()); + return gridSizeForTerminalBounds(bounds.width, bounds.height, self.fallbackCellMetrics(), self.dpi); } fn resizeSurfaceGrid(self: *Workspace, index: usize, size: GridSize) !void { @@ -2767,7 +2875,12 @@ pub const Workspace = struct { fn syncPaneGrid(self: *Workspace, index: usize, bounds: c.winghostty_rect, comptime resize_grid: anytype) void { if (bounds.width == 0 or bounds.height == 0) return; const slot = &self.surfaces[index]; - const requested_size = gridSizeForBounds(bounds.width, bounds.height, slot.cell_metrics) catch |err| { + const requested_size = gridSizeForTerminalBounds( + bounds.width, + bounds.height, + slot.cell_metrics, + self.dpi, + ) catch |err| { std.debug.print("Terminal grid bounds rejected pane={d} error={s}\n", .{ index, @errorName(err), @@ -7550,6 +7663,45 @@ test "terminal font config application reports provider refusal" { try std.testing.expectEqual(@as(usize, 2), Probe.calls); } +test "terminal appearance config matches macOS background and padding" { + const config = terminalAppearanceConfig(); + + try std.testing.expectEqual(@as(u32, 0x000A0C0B), config.background_rgb); + try std.testing.expectApproxEqAbs(@as(f32, 0.80), config.background_opacity, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 2.0), config.padding_top, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 2.0), config.padding_right, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 2.0), config.padding_bottom, 0.0001); + try std.testing.expectApproxEqAbs(@as(f32, 2.0), config.padding_left, 0.0001); +} + +test "terminal appearance config application reports provider refusal" { + const Probe = struct { + var calls: usize = 0; + var result: c.winghostty_result = c.WINGHOSTTY_OK; + + fn set( + _: *c.winghostty_surface, + _: *const c.winghostty_appearance_config, + ) callconv(.c) c.winghostty_result { + calls += 1; + return result; + } + }; + const surface: *c.winghostty_surface = @ptrFromInt(0x1000); + + Probe.calls = 0; + Probe.result = c.WINGHOSTTY_OK; + try applyTerminalAppearanceConfigWith(surface, Probe.set); + try std.testing.expectEqual(@as(usize, 1), Probe.calls); + + Probe.result = c.WINGHOSTTY_INVALID_ARGUMENT; + try std.testing.expectError( + error.WinghosttyAppearanceConfigFailed, + applyTerminalAppearanceConfigWith(surface, Probe.set), + ); + try std.testing.expectEqual(@as(usize, 2), Probe.calls); +} + fn fillRect(hdc: c.HDC, bounds: c.RECT, color: u32) void { const brush = c.CreateSolidBrush(color); if (brush == null) return; @@ -8188,7 +8340,8 @@ test "workspace chrome vertical splits reserve a header above every terminal" { for (0..count) |position| { const bounds = paneBounds(10, 20, 801, 401, Dpi.base_dpi, .vertical, position, count); try std.testing.expect(bounds.width > 0 and bounds.height > 0); - try std.testing.expectEqual(previous_bottom, bounds.y - Tokens.pane_header_height); + const divider = if (position == 0) 0 else Dpi.scale(1, Dpi.base_dpi); + try std.testing.expectEqual(previous_bottom + divider, bounds.y - Tokens.pane_header_height); previous_bottom = bounds.y + @as(i32, @intCast(bounds.height)); } try std.testing.expectEqual(@as(i32, 421), previous_bottom); @@ -8771,7 +8924,10 @@ test "workspace chrome pane headers follow selected layout and focus instead of try std.testing.expect(!left.focused and right.focused); try std.testing.expectEqual(@as(i32, 220), left.bounds.left); try std.testing.expectEqual(@as(i32, 620), left.bounds.right); - try std.testing.expectEqual(left.bounds.right, right.bounds.left); + try std.testing.expectEqual(left.bounds.right + Dpi.scale(1, Dpi.base_dpi), right.bounds.left); + const divider = paneDividerBounds(220, 80, 801, 401, Dpi.base_dpi, .horizontal, 0, 2).?; + try std.testing.expectEqual(left.bounds.right, divider.left); + try std.testing.expectEqual(right.bounds.left, divider.right); try std.testing.expectEqual(@as(i32, 1021), right.bounds.right); try std.testing.expectEqual(@as(i32, 117), left.bounds.top); try std.testing.expectEqual(@as(i32, Tokens.pane_header_height), left.bounds.bottom - left.bounds.top); @@ -8860,6 +9016,24 @@ test "pane geometry derives a terminal grid from actual cell metrics" { try std.testing.expectEqual(GridSize{ .cols = 60, .rows = 12 }, size); } +test "terminal grid reserves the provider's macOS padding at monitor DPI" { + const metrics = c.winghostty_cell_metrics{ + .font_width = 8, + .font_height = 16, + .cell_width = 8, + .cell_height = 16, + .baseline = 13, + }; + try std.testing.expectEqual( + GridSize{ .cols = 100, .rows = 20 }, + try gridSizeForTerminalBounds(804, 324, metrics, 96), + ); + try std.testing.expectEqual( + GridSize{ .cols = 99, .rows = 19 }, + try gridSizeForTerminalBounds(804, 324, metrics, 192), + ); +} + test "pane geometry clamps sub-cell bounds to one cell and ignores unset metrics" { try std.testing.expectEqual( GridSize{ .cols = 1, .rows = 1 }, @@ -8937,17 +9111,48 @@ test "pane attach and resize commands carry geometry outside terminal input" { try std.testing.expectEqualStrings("graphcode-session-a", canonical[2]); } -test "pane bounds partition available area without losing remainder pixels" { +test "pane bounds reserve one macOS divider point and preserve remainder pixels" { const left = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .horizontal, 0, 2); const right = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .horizontal, 1, 2); try std.testing.expectEqual(@as(i32, 10), left.x); try std.testing.expectEqual(@as(u32, 400), left.width); - try std.testing.expectEqual(@as(i32, 410), right.x); - try std.testing.expectEqual(@as(u32, 401), right.width); + try std.testing.expectEqual(@as(i32, 411), right.x); + try std.testing.expectEqual(@as(u32, 400), right.width); try std.testing.expectEqual(@as(u32, 341), left.height); try std.testing.expectEqual(@as(u32, 341), right.height); } +test "vertical pane bounds reserve one macOS divider point" { + const top = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .vertical, 0, 2); + const bottom = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .vertical, 1, 2); + const available_height = 400 - Tokens.tab_bar_height; + + try std.testing.expectEqual(@as(i32, 20 + Tokens.tab_bar_height + Tokens.pane_header_height), top.y); + try std.testing.expectEqual(@as(u32, 159), top.height); + try std.testing.expectEqual(top.y + @as(i32, @intCast(top.height + Tokens.pane_header_height + 1)), bottom.y); + try std.testing.expectEqual(@as(u32, 159), bottom.height); + try std.testing.expectEqual( + @as(u32, @intCast(available_height - 1)), + top.height + bottom.height + 2 * Tokens.pane_header_height, + ); +} + +test "pane divider bounds scale with DPI and remain outside child surfaces" { + const horizontal = paneDividerBounds(10, 20, 801, 400, Dpi.base_dpi, .horizontal, 0, 2).?; + const left = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .horizontal, 0, 2); + const right = paneBounds(10, 20, 801, 400, Dpi.base_dpi, .horizontal, 1, 2); + try std.testing.expectEqual(left.x + @as(i32, @intCast(left.width)), horizontal.left); + try std.testing.expectEqual(right.x, horizontal.right); + try std.testing.expectEqual(@as(i32, 1), horizontal.right - horizontal.left); + + const vertical = paneDividerBounds(10, 20, 801, 400, 192, .vertical, 0, 2).?; + const top = paneBounds(10, 20, 801, 400, 192, .vertical, 0, 2); + const bottom = paneBounds(10, 20, 801, 400, 192, .vertical, 1, 2); + try std.testing.expectEqual(top.y + @as(i32, @intCast(top.height)), vertical.top); + try std.testing.expectEqual(bottom.y - Dpi.scale(Tokens.pane_header_height, 192), vertical.bottom); + try std.testing.expectEqual(Dpi.scale(1, 192), vertical.bottom - vertical.top); +} + test "pane bounds ignore zero or unavailable client geometry" { const bounds = paneBounds(0, 0, 0, 0, Dpi.base_dpi, .horizontal, 0, 1); try std.testing.expectEqual(@as(u32, 0), bounds.width); @@ -8997,8 +9202,8 @@ test "minimize and restore to the same pane size does not queue a resize" { const original = paneBounds( 0, 0, - 960, - Tokens.tab_bar_height + Tokens.pane_header_height + 640, + 964, + Tokens.tab_bar_height + Tokens.pane_header_height + 648, Dpi.base_dpi, .horizontal, 0, @@ -9031,11 +9236,11 @@ test "minimize and restore to a new pane size queues one resize for the new grid 1, ); workspace.syncPaneGrid(0, restored, Workspace.resizeSurfaceGridState); - try std.testing.expectEqual(GridSize{ .cols = 100, .rows = 20 }, workspace.surfaces[0].grid); - try std.testing.expectEqual(GridSize{ .cols = 100, .rows = 20 }, workspace.surfaces[0].pending_resize_size.?); + try std.testing.expectEqual(GridSize{ .cols = 99, .rows = 19 }, workspace.surfaces[0].grid); + try std.testing.expectEqual(GridSize{ .cols = 99, .rows = 19 }, workspace.surfaces[0].pending_resize_size.?); workspace.syncPaneGrid(0, restored, Workspace.resizeSurfaceGridState); - try std.testing.expectEqual(GridSize{ .cols = 100, .rows = 20 }, workspace.surfaces[0].pending_resize_size.?); + try std.testing.expectEqual(GridSize{ .cols = 99, .rows = 19 }, workspace.surfaces[0].pending_resize_size.?); } test "terminal grid resizing reallocates pane cells and keeps legacy output in bounds" { diff --git a/investigation/spikes/windows-terminal-gate/README.md b/investigation/spikes/windows-terminal-gate/README.md index 60230243..c24c2d3f 100644 --- a/investigation/spikes/windows-terminal-gate/README.md +++ b/investigation/spikes/windows-terminal-gate/README.md @@ -10,7 +10,7 @@ session/ConPTY lifetime. `provider-pins.json` records the accepted provider commits: -- Winghostty `e0a5579f3b470bede72294d661282a391c502ace` +- Winghostty `cac8f5f148fd5015d49e81e169ce9006ac7156ea` - zmx `785b3fd15dcafd1882b495c831a10f98c201b908` Both commits are publicly reachable in the `coneilen` provider repositories. diff --git a/investigation/spikes/windows-terminal-gate/provider-pins.json b/investigation/spikes/windows-terminal-gate/provider-pins.json index 26f5fa6f..0941613a 100644 --- a/investigation/spikes/windows-terminal-gate/provider-pins.json +++ b/investigation/spikes/windows-terminal-gate/provider-pins.json @@ -3,7 +3,7 @@ "winghostty": { "repository": "coneilen/winghostty", "remoteUrl": "https://github.com/coneilen/winghostty.git", - "sha": "e0a5579f3b470bede72294d661282a391c502ace", + "sha": "cac8f5f148fd5015d49e81e169ce9006ac7156ea", "artifact": "zig-out/lib/winghostty-win32-host.lib", "minimumZig": "0.15.2" }, From 7bb522bab8b36132953c50277729ae80ea8866d5 Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Thu, 12 Nov 2026 00:13:49 -0700 Subject: [PATCH 2/3] Normalize exact connector snapshots and preserve final refusal evidence Keep Actual Size separate, bound Fit Canvas normalization, require material owned card intersections, and retain final snapshot and screenshot diagnostics. Cover visible-after-fit and never-visible refusal with controlled pure tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- Tools/windows/ValidationRunner/README.md | 9 ++ .../Ui/MixedPolicyContracts.ps1 | 37 ++++++ .../Ui/UiDerivedContracts.ps1 | 6 + Tools/windows/uia-live-gate.ps1 | 106 ++++++++++++++++-- 4 files changed, 149 insertions(+), 9 deletions(-) diff --git a/Tools/windows/ValidationRunner/README.md b/Tools/windows/ValidationRunner/README.md index 489874a0..5360288f 100644 --- a/Tools/windows/ValidationRunner/README.md +++ b/Tools/windows/ValidationRunner/README.md @@ -172,6 +172,15 @@ Overview, Quick Chats and other owners select neither of those rows. The `ownership.mixed-ui-policy` suite checks all 32 surface/owner/selection combinations without changing the independent roster, card, metadata, bounds or foreign-owner requirements. +Connector drag snapshots retain the separate Actual Size action and require at +least an 8-by-8 physical-pixel intersection of each exact owned card with both +graph and client bounds. Geometry-only failures may invoke the existing owned +Fit Canvas action at most twice during the existing 40-observation convergence +budget. Each observation reconnects and recaptures the exact IDs; no zero-area +or foreign snapshot is accepted. Final refusal saves the attempt index, fit +count, graph/client bounds, both card captures, decision and a uniquely named +owned-window PNG with byte count/hash before throwing. Capture failures remain +explicit and do not replace the original connector refusal. With both process flags `GRAPHCODE_UIA_GATE=1` and `GRAPHCODE_UIA_EDGE_ACTION_TRACE=1`, popup input emits diff --git a/Tools/windows/ValidationRunner/Ui/MixedPolicyContracts.ps1 b/Tools/windows/ValidationRunner/Ui/MixedPolicyContracts.ps1 index 35c04867..30d7fd24 100644 --- a/Tools/windows/ValidationRunner/Ui/MixedPolicyContracts.ps1 +++ b/Tools/windows/ValidationRunner/Ui/MixedPolicyContracts.ps1 @@ -29,6 +29,7 @@ foreach ($productionPath in @('Stub-Daemon.ps1', 'uia-live-gate.ps1')) { ($node.Name -like '*-MultiProject*' -or $node.Name -cin @( 'ConvertTo-SketchCanonicalJson', 'Test-RetryableUiaError', 'Test-UpdateBannerClickTarget', 'Get-DynamicProjectCardSnapshotDecision', 'Get-ConnectorDragSnapshotDecision', + 'Wait-ConnectorVisibleSnapshot', 'Get-WorkspaceTabMountDecision', 'Get-UiaSelectionEventDecision')) }, $true)) { # Keep the actual helper's file-backed loader rooted at its production directory. @@ -403,6 +404,42 @@ Invoke-Mixed 3635 'selected-project-roster-and-physical-connector-snapshots' { $d=Get-ConnectorDragSnapshotDecision $cutoff $expected 4242 $connectorGraph $client $false Assert-Mixed ($d.ready -and ($d.targetCenter -join ',') -ceq '1514,461' -and -not $d.targetCenterVisible -and ($d.targetPoint -join ',') -ceq '1339,461') 'Actual Size cutoff did not use visible card intersection' + foreach ($scenario in @('already-visible', 'visible-after-fit', 'never-visible')) { + $state = @{ reads = 0; fits = 0; saved = $null; pauses = 0 } + $failure = $null + try { + $snapshot = Wait-ConnectorVisibleSnapshot { + $state.reads++ + $cards = Copy-MultiProjectValue $fitted + if ($scenario -ceq 'never-visible' -or ($scenario -ceq 'visible-after-fit' -and $state.fits -eq 0)) { + $cards[0].bounds = @(1600,552,1790,630) + $cards[1].bounds = @(1908,552,2114,630) + } + $sliver = Copy-MultiProjectValue $fitted + $sliver[1].bounds = @(1412,552,1618,630) + $sliverDecision = Get-ConnectorDragSnapshotDecision $sliver $expected 4242 $connectorGraph $client $false + Assert-Mixed (-not $sliverDecision.ready -and $sliverDecision.failure -ceq 'cards-insufficient-visible-intersection') ` + 'A two-pixel target sliver must not qualify as a material connector intersection' + return [ordered]@{ + captures = $cards; graphBounds = $connectorGraph; clientBounds = $client + decision = Get-ConnectorDragSnapshotDecision $cards $expected 4242 $connectorGraph $client $false + } + } { $state.fits++ } { param($record) $state.saved = $record } ` + { $state.pauses++ } -MaximumAttempts 4 -MaximumNormalizations 2 + } catch { $failure = $_ } + if ($scenario -ceq 'never-visible') { + Assert-Mixed ($null -ne $failure -and $state.reads -eq 4 -and $state.fits -eq 2 -and + $state.saved.attempt -eq 4 -and $state.saved.normalizations -eq 2 -and + $state.saved.snapshot.captures.Count -eq 2 -and + $state.saved.snapshot.decision.failure -ceq 'cards-outside-viewport' -and + $state.saved.snapshot.graphBounds.Count -eq 4 -and $state.saved.snapshot.clientBounds.Count -eq 4) ` + 'Never-visible connector must persist the final exact snapshot and refuse after bounded normalization' + } else { + $fits = if ($scenario -ceq 'visible-after-fit') { 1 } else { 0 } + Assert-Mixed ($null -eq $failure -and $snapshot.decision.ready -and $state.fits -eq $fits -and + $null -eq $state.saved) 'Connector must reacquire and prove visibility after bounded fit' + } + } foreach($mutation in @('wrong-connector','wrong-target','wrong-process','logical-card-space','logical-client-space','preexisting-dialog')) { $candidate=Copy-MultiProjectValue $fitted;$candidateClient=@($client);$dialog=$false switch($mutation){wrong-connector{$candidate[0].automationId='canvas-card-wrong-source'} wrong-target{$candidate[1].name='Wrong target'} diff --git a/Tools/windows/ValidationRunner/Ui/UiDerivedContracts.ps1 b/Tools/windows/ValidationRunner/Ui/UiDerivedContracts.ps1 index 340adce2..289fc66b 100644 --- a/Tools/windows/ValidationRunner/Ui/UiDerivedContracts.ps1 +++ b/Tools/windows/ValidationRunner/Ui/UiDerivedContracts.ps1 @@ -399,6 +399,12 @@ Invoke-Derived 'ui.root.source.line-7027' { '\[GraphCodeUiaGateState\]::PostMouseDragMoveAt\(', '\$visibleTargetBounds = @\(')) { Assert-Derived ($source -match $pattern) 'Connector physical-screen/clipped target contract missing' } + foreach ($literal in @('function Wait-ConnectorVisibleSnapshot(', '[ValidateRange(0, 2)][int] $MaximumNormalizations = 2', + '$connectorConvergence = Wait-ConnectorVisibleSnapshot', '$fit = Find-FragmentByIdWithRetry $root "fit-canvas" $rawWalker', + 'UIA_CONNECTOR_FINAL_FAILURE_EVIDENCE=', 'Save-UiaShellWindowCapture $shellWindow $png', + '[IO.FileMode]::CreateNew', 'cards-insufficient-visible-intersection')) { + Assert-Derived ($source.Contains($literal)) 'Connector bounded normalization/final evidence contract missing' + } } $null = [IO.Directory]::CreateDirectory($ArtifactRoot) [IO.File]::WriteAllText((Join-Path $ArtifactRoot 'ui-derived-results.json'), ($results | ConvertTo-Json -Depth 8), [Text.UTF8Encoding]::new($false)) diff --git a/Tools/windows/uia-live-gate.ps1 b/Tools/windows/uia-live-gate.ps1 index 1a21e3c5..0ba4320c 100644 --- a/Tools/windows/uia-live-gate.ps1 +++ b/Tools/windows/uia-live-gate.ps1 @@ -2495,6 +2495,13 @@ function Get-ConnectorDragSnapshotDecision( $clientBounds[3] -le $clientBounds[1]) { return & $reject "client-bounds" } + foreach ($card in $cardDecision.cards) { + $width = [Math]::Min($card.bounds[2], [Math]::Min($graphBounds[2], $clientBounds[2])) - + [Math]::Max($card.bounds[0], [Math]::Max($graphBounds[0], $clientBounds[0])) + $height = [Math]::Min($card.bounds[3], [Math]::Min($graphBounds[3], $clientBounds[3])) - + [Math]::Max($card.bounds[1], [Math]::Max($graphBounds[1], $clientBounds[1])) + if ($width -lt 8 -or $height -lt 8) { return & $reject "cards-insufficient-visible-intersection" } + } $source = $cardDecision.cards[0] $target = $cardDecision.cards[1] $sourcePoint = @( @@ -2542,6 +2549,37 @@ function Get-ConnectorDragSnapshotDecision( } } +function Wait-ConnectorVisibleSnapshot( + [scriptblock] $Observe, + [scriptblock] $Normalize, + [scriptblock] $PersistFailure, + [scriptblock] $Pause, + [ValidateRange(1, 40)][int] $MaximumAttempts = 40, + [ValidateRange(0, 2)][int] $MaximumNormalizations = 2 +) { + $normalizations = 0 + for ($attempt = 1; $attempt -le $MaximumAttempts; $attempt++) { + $snapshot = & $Observe + if ($snapshot.decision.ready) { + return [ordered]@{ snapshot = $snapshot; decision = $snapshot.decision + attempt = $attempt; normalizations = $normalizations } + } + if ($attempt -lt $MaximumAttempts -and $normalizations -lt $MaximumNormalizations -and + $snapshot.decision.failure -cin @("cards-outside-viewport", "source-point-outside", "target-not-visible", + "cards-insufficient-visible-intersection")) { + & $Normalize + $normalizations++ + } + if ($attempt -lt $MaximumAttempts) { & $Pause } + } + $record = [ordered]@{ attempt = $attempt - 1; normalizations = $normalizations; snapshot = $snapshot } + $failure = [InvalidOperationException]::new( + "connector drag did not converge on exact visible endpoints: $($snapshot.decision.failure)") + try { & $PersistFailure $record } + catch { $failure.Data["ConnectorFailureEvidenceError"] = $_.Exception } + throw $failure +} + # A modal teardown (e.g. dismissing the update-offer dialog via SendCommand) # rebuilds the shell's fragment tree, and a $root captured before that teardown # can become a permanently dead reference - not a transient blip that @@ -7547,10 +7585,9 @@ try { } Write-Host ("UIA_COMPOSITE_NAVIGATION_EVIDENCE=" + ($compositeNavigationEvidence | ConvertTo-Json -Compress)) - # Keep the established Actual Size hover-paint proof, but do not use the full - # target rectangle's centre: at DPI192 the second card extends past the live - # client/graph right edge. Reconnect after normalization, freeze exact card - # bounds, and choose the centre of the target's visible card intersection. + # Exercise Actual Size independently of connector normalization. If its viewport + # excludes the exact cards, use the existing Fit Canvas action before freezing + # endpoints; a full target rectangle's centre can still be outside at high DPI. $connectorActual = Find-FragmentByIdWithRetry $root "actual-size" $rawWalker Require (($null -ne $connectorActual) -and ($connectorActual.Current.ProcessId -eq $process.Id) -and @@ -7566,7 +7603,8 @@ try { $connectorDecision = $null $connectorProjectCards = @() $connectorCaptures = @() - for ($attempt = 0; $attempt -lt 40; $attempt++) { + $connectorConvergence = Wait-ConnectorVisibleSnapshot { + $root = Wait-ForRootReconnect $process @($rawWalker, $controlWalker) $connectorProbe = Wait-ForGraphChildren $root $rawWalker ` { $_.Current.AutomationId -cin @($dynamicProjectExpected | ForEach-Object { $_.automationId }) } ` { param($items) $items.Count -eq 2 } 1 0 @@ -7582,7 +7620,13 @@ try { $connectorCaptures = @($connectorProjectCards | ForEach-Object { Get-DynamicProjectCardCapture $_ }) + for ($index = 0; $index -lt 2; $index++) { + Require ($connectorCaptures[$index].automationId -ceq $dynamicProjectExpected[$index].automationId -and + $connectorCaptures[$index].name -ceq $dynamicProjectExpected[$index].name -and + $connectorCaptures[$index].processId -eq $process.Id) "connector normalization refused foreign or changed card identity" + } $connectorGraphBounds = $graph.Current.BoundingRectangle + $connectorClientBounds = @([GraphCodeUiaGateState]::ClientScreenBounds($shellWindow)) $preexistingEdgeDialog = [GraphCodeUiaGateState]::FindVisibleOwnedSheetByContentClass( [uint32]$process.Id, $shellWindow, "GraphCodeNativeForm" ) -ne [IntPtr]::Zero @@ -7593,16 +7637,60 @@ try { [double]$connectorGraphBounds.Right, [double]$connectorGraphBounds.Bottom ) $connectorClientBounds $preexistingEdgeDialog - if ($connectorDecision.ready) { break } + return [ordered]@{ + graph = $graph; cards = $connectorProjectCards; captures = $connectorCaptures + graphBounds = @([double]$connectorGraphBounds.Left, [double]$connectorGraphBounds.Top, + [double]$connectorGraphBounds.Right, [double]$connectorGraphBounds.Bottom) + clientBounds = $connectorClientBounds; decision = $connectorDecision + } } - Start-Sleep -Milliseconds 100 + return [ordered]@{ captures = @(); graphBounds = @(); clientBounds = $connectorClientBounds + decision = [ordered]@{ ready = $false; failure = "missing-exact-cards" } } + } { $root = Wait-ForRootReconnect $process @($rawWalker, $controlWalker) + $fit = Find-FragmentByIdWithRetry $root "fit-canvas" $rawWalker + Require ($null -ne $fit -and $fit.Current.ProcessId -eq $process.Id -and + $fit.Current.IsEnabled -and -not $fit.Current.IsOffscreen) "connector normalization lost its owned Fit Canvas action" + $fit.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke() + } { + param($record) + $stem = Join-Path $script:uiaAttributionDirectory ("connector-final-" + [guid]::NewGuid().ToString("N")) + $png = $stem + ".png" + $captureError = $null + try { $capture = Save-UiaShellWindowCapture $shellWindow $png } + catch { $capture = "capture-error"; $captureError = $_.Exception.ToString() } + $evidence = [ordered]@{ + attempt = $record.attempt; normalizations = $record.normalizations; processId = $process.Id + window = $shellWindow.ToInt64(); expected = $dynamicProjectExpected + graphBounds = $record.snapshot.graphBounds; clientBounds = $record.snapshot.clientBounds + cards = $record.snapshot.captures; decision = $record.snapshot.decision + screenshot = [ordered]@{ path = $png; state = $capture; error = $captureError } + } + if ($capture -ceq "saved") { + $evidence.screenshot.bytes = (Get-Item -LiteralPath $png).Length + $evidence.screenshot.sha256 = (Get-FileHash -LiteralPath $png -Algorithm SHA256).Hash + } + $bytes = [Text.UTF8Encoding]::new($false).GetBytes(($evidence | ConvertTo-Json -Depth 10)) + $file = [IO.File]::Open($stem + ".json", [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read) + try { $file.Write($bytes, 0, $bytes.Length) } finally { $file.Dispose() } + Write-Host ("UIA_CONNECTOR_FINAL_FAILURE_EVIDENCE=" + ($evidence | ConvertTo-Json -Depth 10 -Compress)) + Require ($capture -ceq "saved" -and $evidence.screenshot.bytes -gt 0) "connector failure screenshot bytes unavailable: $capture" + } { Start-Sleep -Milliseconds 100 } + $connectorDecision = $connectorConvergence.decision + $connectorCaptures = $connectorConvergence.snapshot.captures + $connectorProjectCards = $connectorConvergence.snapshot.cards + $graph = $connectorConvergence.snapshot.graph + $connectorClientBounds = $connectorConvergence.snapshot.clientBounds + $connectorGraphBounds = [pscustomobject]@{ + Left = $connectorConvergence.snapshot.graphBounds[0]; Top = $connectorConvergence.snapshot.graphBounds[1] + Right = $connectorConvergence.snapshot.graphBounds[2]; Bottom = $connectorConvergence.snapshot.graphBounds[3] } Require (($null -ne $connectorDecision) -and $connectorDecision.ready) ` "connector drag did not converge on exact visible DPI192 endpoints: $($connectorDecision.failure)" Write-Host ("UIA_CONNECTOR_DRAG_EVIDENCE=" + ([ordered]@{ - normalizedBy = "actual-size" - attempts = $attempt + 1 + normalizedBy = $(if ($connectorConvergence.normalizations) { "actual-size-then-fit-canvas" } else { "actual-size" }) + normalizations = $connectorConvergence.normalizations + attempts = $connectorConvergence.attempt processId = $process.Id sourceCardId = $connectorDecision.sourceCardId targetCardId = $connectorDecision.targetCardId From 03e8df80d73ef711b14232ed8d568a7cfb266d03 Mon Sep 17 00:00:00 2001 From: Colin Neilens Date: Thu, 12 Nov 2026 01:10:10 -0700 Subject: [PATCH 3/3] Fix WireTargeting fixture DPI setup Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Signed-off-by: Colin Neilens --- .../windows/Tests/ValidationRunner.Tests.ps1 | 4 +-- Tools/windows/Tests/WireTargeting.Tests.ps1 | 26 ++++++++++++++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/Tools/windows/Tests/ValidationRunner.Tests.ps1 b/Tools/windows/Tests/ValidationRunner.Tests.ps1 index d8f24448..308c3583 100644 --- a/Tools/windows/Tests/ValidationRunner.Tests.ps1 +++ b/Tools/windows/Tests/ValidationRunner.Tests.ps1 @@ -6095,9 +6095,9 @@ $wireTargetingSummaries=@($wireTargetingOutput|Where-Object { }) if ($wireTargetingSummaries.Count -ne 1) {throw 'RED: wire targeting count missing or duplicated'} $wireTargetingSummary=ConvertFrom-Json $wireTargetingSummaries[0] -if ($wireTargetingSummary.executed -ne 56 -or $wireTargetingSummary.passed -ne 56 -or +if ($wireTargetingSummary.executed -ne 75 -or $wireTargetingSummary.passed -ne 75 -or $wireTargetingSummary.failed -ne 0 -or $wireTargetingSummary.skipped -ne 0) { - throw 'RED: wire targeting requires all 56 contracts without skips' + throw 'RED: wire targeting requires all 75 contracts without skips' } $agentCommandOutput = @(& $pwsh -NoProfile -File ( Join-Path $PSScriptRoot "Invoke-AgentCommand.Tests.ps1")) diff --git a/Tools/windows/Tests/WireTargeting.Tests.ps1 b/Tools/windows/Tests/WireTargeting.Tests.ps1 index d1974d4f..38c417a5 100644 --- a/Tools/windows/Tests/WireTargeting.Tests.ps1 +++ b/Tools/windows/Tests/WireTargeting.Tests.ps1 @@ -296,9 +296,13 @@ public static class WireFixture { '@ $root=[IntPtr]::Zero;$hostWindow=[IntPtr]::Zero;$content=[IntPtr]::Zero try { - $root=[WireFixture]::Create([IntPtr]::Zero,$false,'wire fixture owner') - $hostWindow=[WireFixture]::Create($root,$false,'wire fixture sheet') - $content=[WireFixture]::Create($hostWindow,$true,'wire fixture content') + $fixtureDpiContext=[WireFixture]::SetThreadDpiAwarenessContext([IntPtr](-4)) + Assert-WireCase ($fixtureDpiContext -ne [IntPtr]::Zero) 'Fixture PMv2 setup failed.' + try { + $root=[WireFixture]::Create([IntPtr]::Zero,$false,'wire fixture owner') + $hostWindow=[WireFixture]::Create($root,$false,'wire fixture sheet') + $content=[WireFixture]::Create($hostWindow,$true,'wire fixture content') + } finally {$null=[WireFixture]::SetThreadDpiAwarenessContext($fixtureDpiContext)} if ($LegacyBehavior) { Test-WireCase 'owned child form is observable, not just a top-level class' { $actual=[CapUiaGateState]::FindTopLevel('WireTargetFixtureContent',[uint32]$PID) @@ -560,15 +564,29 @@ try { $previous=[WireFixture]::SetThreadDpiAwarenessContext([IntPtr](-1)) try { $before=[WireFixture]::GetThreadDpiAwarenessContext() + $activePrevious=[WireFixture]::SetThreadDpiAwarenessContext([IntPtr](-4)) + Assert-WireCase ($activePrevious -ne [IntPtr]::Zero) 'Drag PMv2 observation setup failed.' + try {$retainedDpiContext=[WireFixture]::GetThreadDpiAwarenessContext()} + finally { + $restored=[WireFixture]::SetThreadDpiAwarenessContext($activePrevious) + Assert-WireCase ($restored -ne [IntPtr]::Zero) 'Drag PMv2 observation restore failed.' + } $receipt=[CapNative]::PostPointerDragScreen($hostWindow,($b[0]+10),($b[1]+10),($b[0]+15),($b[1]+15)) Assert-WireCase ($receipt.Start.ClientX -eq 10 -and $receipt.Start.ClientY -eq 10 -and $receipt.End.ClientX -eq 15 -and $receipt.End.ClientY -eq 15 -and + $receipt.End.ClientX-$receipt.Start.ClientX -eq 5 -and + $receipt.End.ClientY-$receipt.Start.ClientY -eq 5 -and + $receipt.End.ScreenX-$receipt.Start.ScreenX -eq 5 -and + $receipt.End.ScreenY-$receipt.Start.ScreenY -eq 5 -and $receipt.Start.MovePosted -and $receipt.Start.DownPosted -and $receipt.HeldMovePosted -and $receipt.End.UpPosted -and $receipt.Start.Recipient -eq $hostWindow.ToInt64() -and $receipt.End.Recipient -eq $hostWindow.ToInt64() -and + $receipt.Start.DpiContext -eq $retainedDpiContext -and + $receipt.End.DpiContext -eq $retainedDpiContext -and + $receipt.Delivery -ceq 'POSTED_WINDOW_MESSAGES_NOT_PHYSICAL_POINTER' -and [WireFixture]::GetThreadDpiAwarenessContext() -eq $before) ` - "Drag receipt/DPI restore failed: $($receipt|ConvertTo-Json -Depth 10 -Compress); before=$before; after=$([WireFixture]::GetThreadDpiAwarenessContext())" + "Drag receipt/DPI restore failed: $($receipt|ConvertTo-Json -Depth 10 -Compress); retained=$retainedDpiContext; before=$before; after=$([WireFixture]::GetThreadDpiAwarenessContext())" } finally {$null=[WireFixture]::SetThreadDpiAwarenessContext($previous)} } foreach ($failureIndex in 0..3) {