Align Companion 1.0.0.13 packaging and guard payload replacement

This commit is contained in:
nick 2026-11-06 22:42:42 +00:00
parent 73ae3140e0
commit 938ffaf351
8 changed files with 142 additions and 30 deletions

View File

@ -11,9 +11,9 @@ $package=Test-DeveloperPackage $PackagePath
$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json
$repo=(Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path
if(!$ExpectedSourceCommit){$ExpectedSourceCommit=(& git -C $repo rev-parse HEAD).Trim();if($LASTEXITCODE -ne 0){throw 'Cannot read the exact setup source revision.'}}
if($ExpectedSourceCommit -notmatch '^[0-9a-f]{40}$' -or $package.version -ne $release.version -or $package.commit -ne $ExpectedSourceCommit){throw 'Release version or exact package source SHA does not match the requested version12 build.'}
if($ExpectedSourceCommit -notmatch '^[0-9a-f]{40}$' -or $package.version -ne $release.version -or $package.commit -ne $ExpectedSourceCommit){throw 'Release version or exact package source SHA does not match the requested build.'}
Invoke-Checked git @('-C',$repo,'merge-base','--is-ancestor',$release.atlasBaseline,$package.commit)
if($release.productCode -eq $release.baselineProductCode -or $release.upgradeCode -ne '{641A087B-9779-458C-B290-BCBBAD49319A}'){throw 'Version12 requires a new major-upgrade ProductCode and the established UpgradeCode.'}
if($release.productCode -in @($release.baselineProductCode,'{0B1E8E22-FCF5-4D9C-99A1-5D0F4BD3210C}') -or $release.upgradeCode -ne '{641A087B-9779-458C-B290-BCBBAD49319A}'){throw 'Version13 requires a new major-upgrade ProductCode and the established UpgradeCode.'}
foreach($relative in @('PlotDirector.WordAddIn.dll','Agent\PlotDirector.Companion.Agent.exe')){
if([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $PackagePath $relative)).FileVersion -ne $release.version){throw "Wrong application bytes/version: $relative"}
}
@ -142,6 +142,7 @@ $signature=Set-AuthenticodeSignature -FilePath $msi -Certificate $cert -HashAlgo
if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "MSI signing failed: $($signature.StatusMessage)"}
$setup=Join-Path $output 'PlotDirectorCompanionSetup.exe'
$generated=Join-Path $work 'SetupRelease.g.cs'
$payloadNames=@($payload | ForEach-Object { $relative=$_.FullName.Substring((Resolve-Path $PackagePath).Path.Length+1); ' @"'+$relative.Replace('"','""')+'"' }) -join ",`n"
@"
using System.Reflection;
[assembly: AssemblyVersion("$($release.version)")]
@ -151,9 +152,12 @@ internal static class SetupRelease {
internal const string MsiVersion = "$($release.msiVersion)";
internal const string ProductCode = "$product";
internal const string UpgradeCode = "$upgrade";
internal static readonly string[] PayloadFiles = new string[] {
$payloadNames
};
}
"@ | Set-Content $generated -Encoding UTF8
Invoke-Checked 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe' @('/nologo','/target:winexe','/platform:x64',('/win32icon:'+$iconPath),('/win32manifest:'+(Join-Path $PSScriptRoot 'Setup.manifest')),('/out:'+$setup),('/resource:'+$msi+',Companion.msi'),'/reference:System.Windows.Forms.dll','/reference:System.Management.dll',$generated,(Join-Path $PSScriptRoot 'InstallerInventory.cs'),(Join-Path $PSScriptRoot 'UpgradePolicy.cs'),(Join-Path $PSScriptRoot 'Setup.cs'))
Invoke-Checked 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe' @('/nologo','/target:winexe','/platform:x64',('/win32icon:'+$iconPath),('/win32manifest:'+(Join-Path $PSScriptRoot 'Setup.manifest')),('/out:'+$setup),('/resource:'+$msi+',Companion.msi'),'/reference:System.Windows.Forms.dll','/reference:System.Management.dll',$generated,(Join-Path $PSScriptRoot 'InstallerInventory.cs'),(Join-Path $PSScriptRoot 'UpgradePolicy.cs'),(Join-Path $PSScriptRoot 'FileCopyPreflight.cs'),(Join-Path $PSScriptRoot 'Setup.cs'))
$signature=Set-AuthenticodeSignature -FilePath $setup -Certificate $cert -HashAlgorithm SHA256
if(!$signature.SignerCertificate -or $signature.SignerCertificate.Thumbprint -ne $cert.Thumbprint -or $signature.Status -notin @('Valid','UnknownError','NotTrusted')){throw "Setup signing failed: $($signature.StatusMessage)"}
$installerCommit=(& git -C $repo rev-parse HEAD).Trim()

View File

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
// Qualification uses disposable fixtures, never the installed application lock.
public static class CompanionFileCopyPreflight
{
public static FileStream AcquireAgentGuard(string stateDirectory, int session)
{
Directory.CreateDirectory(stateDirectory);
// Same lock as TrayApplication.Run prevents a shortcut/sign-in restart
// while an explicitly authorised installer is replacing the payload.
return File.Open(Path.Combine(stateDirectory, "agent-" + session + ".lock"),
FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
public static void Verify(string home, IEnumerable<string> files, Action<string> log)
{
string root = Path.GetFullPath(home).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
foreach (string relative in files)
{
string path = Path.GetFullPath(Path.Combine(root, relative));
if (!path.StartsWith(root, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException("Payload path escapes the installation directory.");
try
{
try { File.GetAttributes(path); }
catch (FileNotFoundException) { continue; }
catch (DirectoryNotFoundException) { continue; }
// OPEN_EXISTING: check replacement access without writing bytes,
// truncating, renaming, deleting or changing permissions.
using (File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { }
}
catch (Exception ex)
{
if (!(ex is IOException) && !(ex is UnauthorizedAccessException)) throw;
int error = Marshal.GetHRForException(ex) & 0xffff;
log("Payload replacement preflight failed: " + path + "; Windows error=" + error);
throw new IOException("Cannot replace Companion file: " + path +
" (Windows error " + error + "). Exit the Companion tray app and close Word, then retry. " +
"If it persists, retain the setup log. No registration or MSI changes were attempted; " +
"do not delete the installation folder or change permissions.", ex);
}
}
log("Existing payload passed non-writing replacement preflight.");
}
}

View File

@ -1,9 +1,9 @@
# Complete per-user Windows installer — version12 candidate
# Complete per-user Windows installer — version13 candidate
Run **PlotDirectorCompanionSetup.exe** from normal File Explorer after closing Word.
It contains the MSI and both application components; no adjacent payload folder is
needed. `Release.json` deliberately selects application **1.0.0.12**, MSI **1.0.12**,
and Atlas baseline `be88c1d068a4c384c5db348238ac78704b6f73e9`. The exact clean
needed. `Release.json` deliberately selects application **1.0.0.13**, MSI **1.0.13**,
and Atlas baseline `73ae3140e0be5efd2ca8fff60d3a301788d3b206`. The exact clean
build SHA must match `package.json` and `-ExpectedSourceCommit` (defaults to HEAD).
This is a packaging candidate, not a claim of installed Windows acceptance.
@ -26,6 +26,19 @@ produce a specific error; they are not installed or repaired automatically.
## Installation contract
- Version13 uses ProductCode `{A5831E49-6675-4BCA-9A3D-E03C992F4A13}` with
the established UpgradeCode. Its transactional older-product range includes both
version10 and version12; same-version13 uses the existing maintenance path.
Version12-specific notes below describe the preserved historical correction.
- Before registration/VSTO/MSI changes, setup stops only the exact installed tray
executable in this session, holds its existing singleton lock against restart,
and checks every existing candidate payload file for replacement access without
writing bytes. Locked/read-only/inaccessible files stop setup with their path and
Windows error; permissions and installed files are not changed to bypass errors.
The guard releases on failure and before launching the upgraded tray. Regression
tests use disposable locked/read-only files, never the installed application.
This hardens the reported copy-failure path; an actual MSI upgrade, including
any transient lock or rollback-security failure, still needs human acceptance.
- Per-user MSI, no ALLUSERS property; limited-privilege summary flag, compressed CAB.
- `%LOCALAPPDATA%\Programs\PlotDirector Companion` contains VSTO and `Agent`.
- Start menu opens the control centre; the current user's Startup shortcut starts

View File

@ -1,9 +1,9 @@
{
"version": "1.0.0.12",
"msiVersion": "1.0.12",
"productCode": "{0B1E8E22-FCF5-4D9C-99A1-5D0F4BD3210C}",
"version": "1.0.0.13",
"msiVersion": "1.0.13",
"productCode": "{A5831E49-6675-4BCA-9A3D-E03C992F4A13}",
"upgradeCode": "{641A087B-9779-458C-B290-BCBBAD49319A}",
"atlasBaseline": "be88c1d068a4c384c5db348238ac78704b6f73e9",
"atlasBaseline": "73ae3140e0be5efd2ca8fff60d3a301788d3b206",
"baselineProductCode": "{98F46939-764D-407F-BD1F-1D88315D010A}",
"baselineSetupSha256": "9526E3781EB2EF9936132786E1E2242633349933A553E93E7A7D0B038160A7FF"
}

View File

@ -26,6 +26,7 @@ internal static class Setup
[STAThread] private static int Main(string[] args)
{
Application.EnableVisualStyles();
FileStream upgradeGuard = null;
try
{
// A packaged caller's HKCU/LocalAppData writes are invisible to normal Word.
@ -54,6 +55,11 @@ internal static class Setup
CompanionInstallerInventory.RequireCurrentUser(family, SetupRelease.MsiVersion);
if (!args.Contains("--install") && MessageBox.Show("Install PlotDirector Companion " + Version + " for your Windows account?\n\nIncludes the Word add-in, tray application, Start menu shortcut and launch at Windows sign-in. No manuscripts or application data will be removed.", "PlotDirector Companion Setup", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return 2;
StopOwnAgent();
upgradeGuard = CompanionFileCopyPreflight.AcquireAgentGuard(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Companion"),
Process.GetCurrentProcess().SessionId);
var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "PlotDirector Companion");
CompanionFileCopyPreflight.Verify(home, SetupRelease.PayloadFiles, Write);
BackupRegistration(state);
RemoveOldDeployment(state);
var cache = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "PlotDirector", "Setup", Version);
@ -80,7 +86,6 @@ internal static class Setup
MsiEnableLog(0x1fff, Path.Combine(state, "windows-installer-local-feature.log"), 0);
return MsiConfigureFeature(SetupRelease.ProductCode, "Complete", 3);
}, Write);
var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "PlotDirector Companion");
var manifest = Path.Combine(home, "PlotDirector.WordAddIn.vsto");
var agent = Path.Combine(home, "Agent", "PlotDirector.Companion.Agent.exe");
var wordVersion = FileVersionInfo.GetVersionInfo(Path.Combine(home, "PlotDirector.WordAddIn.dll")).FileVersion;
@ -105,12 +110,14 @@ internal static class Setup
// Only migrate an existing server preference, never credentials or diagnostic logs.
var oldSettings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Packages", "OpenAI.Codex_2p2nqsd0c76g0", "LocalCache", "Local", "PlotDirector", "Companion", "server-url.txt");
if (!File.Exists(Path.Combine(settings, "server-url.txt")) && File.Exists(oldSettings)) File.Copy(oldSettings, Path.Combine(settings, "server-url.txt"));
upgradeGuard.Dispose(); upgradeGuard = null;
Process.Start(new ProcessStartInfo(agent, "--open") { UseShellExecute = true });
Write("Installed both components; Word restart verification still required.");
MessageBox.Show("PlotDirector Companion " + Version + " is installed.\n\nOpen Word and choose PlotDirector > Open Companion.\nThe tray app also starts at Windows sign-in.\n\nUninstall using Windows Settings > Apps > PlotDirector Companion. Your application state and documents are retained.", "PlotDirector Companion Setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
return 0;
}
catch (Exception ex) { if (log != null) Write(ex.ToString()); MessageBox.Show(ex.Message, "PlotDirector Companion Setup — stopped", MessageBoxButtons.OK, MessageBoxIcon.Error); return 1; }
finally { if (upgradeGuard != null) upgradeGuard.Dispose(); }
}
private static void CheckPrerequisites()
{
@ -131,8 +138,8 @@ internal static class Setup
{
if (p.SessionId != Process.GetCurrentProcess().SessionId) continue;
var path = p.MainModule.FileName;
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar;
if (!path.StartsWith(local, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("A Companion agent is running from another location. Exit it using its tray menu and rerun setup.");
var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "PlotDirector Companion", "Agent", "PlotDirector.Companion.Agent.exe");
if (!String.Equals(path, expected, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("A Companion agent is running from another location. Exit it using its tray menu and rerun setup.");
Write("Stopping this session's Companion for upgrade: " + path); p.Kill(); if (!p.WaitForExit(5000)) throw new InvalidOperationException("Companion did not stop.");
}
}

View File

@ -9,7 +9,7 @@ Assert-Payload ($inventory.version -eq $release.version -and $inventory.publishe
foreach($name in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.manifest')){
[xml]$xml=Get-Content -Raw (Join-Path $PackagePath $name)
$identity=$xml.SelectSingleNode('/*/*[local-name()="assemblyIdentity"]')
Assert-Payload ($identity.version -eq $release.version -and $identity.processorArchitecture -eq 'msil') "$name identity is version12 AnyCPU"
Assert-Payload ($identity.version -eq $release.version -and $identity.processorArchitecture -eq 'msil') "$name identity matches release AnyCPU"
foreach($node in $xml.SelectNodes('//*[local-name()="X509Certificate"]')){
$certificate=[Security.Cryptography.X509Certificates.X509Certificate2]::new([Convert]::FromBase64String($node.InnerText))
try{Assert-Payload ($certificate.Thumbprint -eq $inventory.certificateThumbprint) "$name embeds the existing developer certificate"}finally{$certificate.Dispose()}
@ -26,7 +26,7 @@ foreach($name in @('PlotDirector.WordAddIn.vsto','PlotDirector.WordAddIn.dll.man
[xml]$deployment=Get-Content -Raw (Join-Path $PackagePath 'PlotDirector.WordAddIn.vsto')
Assert-Payload ($deployment.SelectSingleNode('/*/*[local-name()="description"]').GetAttribute('publisher','urn:schemas-microsoft-com:asm.v2') -eq 'Nick Beckley') 'Signed VSTO deployment publisher is Nick Beckley'
foreach($relative in @('PlotDirector.WordAddIn.dll','Agent\PlotDirector.Companion.Agent.exe','Agent\PlotDirector.Companion.Agent.dll')){
Assert-Payload ([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $PackagePath $relative)).FileVersion -eq $release.version) "Application file version is 1.0.0.12: $relative"
Assert-Payload ([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $PackagePath $relative)).FileVersion -eq $release.version) "Application file version matches release: $relative"
}
# These SDK class libraries deliberately retain their default stable assembly
# version. Their exact build bytes are pinned by package.json and the signed
@ -40,11 +40,12 @@ Assert-Payload ([BitConverter]::ToUInt16($agent,$pe+4) -eq 0x8664) 'Published tr
Add-Type -Path (Join-Path $PSScriptRoot 'InstallerInventory.cs')
$sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$fixture=[CompanionInstalledProduct]::new();$fixture.ProductCode=$release.baselineProductCode;$fixture.Context=2;$fixture.UserSid=$sid;$fixture.Version='1.0.10'
[CompanionInstallerInventory]::RequireCurrentUser(@($fixture),'1.0.12');$checks.Add('Native context guard accepts the existing current-user version10 upgrade')
[CompanionInstallerInventory]::RequireCurrentUser(@($fixture),$release.msiVersion);$checks.Add('Native context guard accepts the existing current-user version10 upgrade')
$fixture.Version='1.0.12';[CompanionInstallerInventory]::RequireCurrentUser(@($fixture),$release.msiVersion);$checks.Add('Native context guard accepts the working current-user version12 upgrade')
foreach($test in @('machine','foreign-user','newer-version')){
$fixture.Context=2;$fixture.UserSid=$sid;$fixture.Version='1.0.10'
switch($test){'machine'{$fixture.Context=4};'foreign-user'{$fixture.UserSid='S-1-5-18'};'newer-version'{$fixture.Version='1.0.13'}}
$refused=$false;try{[CompanionInstallerInventory]::RequireCurrentUser(@($fixture),'1.0.12')}catch{$refused=$true}
switch($test){'machine'{$fixture.Context=4};'foreign-user'{$fixture.UserSid='S-1-5-18'};'newer-version'{$fixture.Version='1.0.'+(([version]$release.msiVersion).Build+1)}}
$refused=$false;try{[CompanionInstallerInventory]::RequireCurrentUser(@($fixture),$release.msiVersion)}catch{$refused=$true}
Assert-Payload $refused "Native context guard refuses $test without mutation"
}
@{sourceCommit=$inventory.commit;version=$inventory.version;passed=$checks} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $ReportPath -Encoding UTF8

View File

@ -50,10 +50,10 @@ $verify=Join-Path $SetupDirectory 'verification'
if(Test-Path $verify){throw 'Verification output already exists; reuse the existing report instead of repeating qualification.'}
New-Item -ItemType Directory -Path $verify | Out-Null
$msi=Join-Path $SetupDirectory 'PlotDirectorCompanion.msi';$exe=Join-Path $SetupDirectory 'PlotDirectorCompanionSetup.exe'
Assert-Package ($package.version -eq $release.version -and $evidence.applicationCommit -eq $package.commit) 'Exact version12 payload source and setup evidence agree'
Assert-Package ($package.version -eq $release.version -and $evidence.applicationCommit -eq $package.commit) 'Exact release payload source and setup evidence agree'
Assert-Package ((Get-FileHash $exe).Hash -eq $evidence.setupSha256 -and (Get-FileHash $msi).Hash -eq $evidence.msiSha256) 'Final EXE and MSI hashes agree with build evidence'
$assembly=[Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe))
Assert-Package ($assembly.GetName().Version.ToString() -eq $release.version -and [Diagnostics.FileVersionInfo]::GetVersionInfo($exe).FileVersion -eq $release.version) 'Bootstrapper assembly and file versions are 1.0.0.12'
Assert-Package ($assembly.GetName().Version.ToString() -eq $release.version -and [Diagnostics.FileVersionInfo]::GetVersionInfo($exe).FileVersion -eq $release.version) 'Bootstrapper assembly and file versions match the release'
$embedded=Join-Path $verify 'embedded.msi';$source=$assembly.GetManifestResourceStream('Companion.msi');$dest=[IO.File]::Create($embedded);try{$source.CopyTo($dest)}finally{$source.Dispose();$dest.Dispose()}
Assert-Package ((Get-FileHash $embedded).Hash -eq (Get-FileHash $msi).Hash) 'EXE embeds the exact signed MSI with no external payload dependency'
[xml]$manifest=[CompanionPackageStreams]::Manifest($exe)
@ -69,7 +69,7 @@ $database=Invoke-Com $installer 'OpenDatabase' @($msi,0);$baseline=Invoke-Com $i
$tables=@{};foreach($table in @('Property','File','Component','Directory','Registry','Shortcut','Upgrade','InstallExecuteSequence','InstallUISequence','Media','RemoveFile','LaunchCondition','Feature','FeatureComponents')){$tables[$table]=@(Read-Table $database $table)}
$properties=@{};foreach($row in $tables.Property){$properties[$row.Property]=$row.Value}
$oldProperties=@{};foreach($row in @(Read-Table $baseline 'Property')){$oldProperties[$row.Property]=$row.Value}
Assert-Package ($properties.ProductVersion -eq '1.0.12' -and $properties.COMPANIONVERSION -eq '1.0.0.12' -and $properties.SOURCECOMMIT -eq $package.commit) 'MSI version and source metadata match the final application'
Assert-Package ($properties.ProductVersion -eq $release.msiVersion -and $properties.COMPANIONVERSION -eq $release.version -and $properties.SOURCECOMMIT -eq $package.commit) 'MSI version and source metadata match the final application'
Assert-Package ($properties.ProductCode -eq $release.productCode -and $properties.ProductCode -ne $oldProperties.ProductCode -and $properties.UpgradeCode -eq $oldProperties.UpgradeCode) 'Major upgrade changes ProductCode and preserves the qualified version10 UpgradeCode'
Assert-Package (!$properties.ContainsKey('ALLUSERS') -and $properties.MSIINSTALLPERUSER -eq '1' -and @($tables.LaunchCondition | Where-Object Condition -eq 'NOT ALLUSERS').Count -eq 1) 'MSI is authored strictly per-user'
$summary=Get-Com $database 'SummaryInformation' @(0)
@ -96,6 +96,8 @@ foreach($file in $tables.File){
}
$expectedRuntime=@($package.files | Where-Object {$_.path -notlike '*.pdb'}).Count+1
Assert-Package ($installed.Count -eq $expectedRuntime -and @(Get-ChildItem $expanded -File).Count -eq $installed.Count) 'CAB includes the complete runtime inventory plus package.json, without symbols or extra state'
$preflightFiles=$assembly.GetType('SetupRelease',$true).GetField('PayloadFiles',[Reflection.BindingFlags]'Static,NonPublic').GetValue($null)
Assert-Package (@(Compare-Object @($installed.path | ForEach-Object {$_.Replace('/','\')}) @($preflightFiles)).Count -eq 0) 'Replacement preflight inventory exactly matches every embedded MSI payload path'
$registry=$tables.Registry
Assert-Package (@($registry | Where-Object {$_.Root -ne '1' -or $_.Key -notin @('Software\Microsoft\Office\Word\Addins\PlotDirector.WordAddIn','Software\PlotDirector\Companion')}).Count -eq 0) 'All MSI registry writes are limited to exact Companion HKCU keys'
Assert-Package (@($registry | Where-Object {$_.Name -eq 'Manifest' -and $_.Value -eq 'file:///[INSTALLDIR]PlotDirector.WordAddIn.vsto|vstolocal'}).Count -eq 1 -and @($registry | Where-Object {$_.Name -eq 'LoadBehavior' -and $_.Value -eq '#3'}).Count -eq 1) 'Word registration uses signed local manifest and LoadBehavior3'
@ -105,8 +107,8 @@ $sequence=@{};foreach($row in $tables.InstallExecuteSequence){$sequence[$row.Act
Assert-Package ($sequence.InstallInitialize -lt $sequence.RemoveExistingProducts -and $sequence.RemoveExistingProducts -lt $sequence.InstallFiles -and $sequence.InstallFiles -lt $sequence.InstallFinalize) 'Older MSI removal is transactional and precedes new files'
Assert-Package (@(@('RemoveFiles','RemoveRegistryValues','RemoveShortcuts','RegisterProduct','PublishProduct') | Where-Object {!$sequence.ContainsKey($_)}).Count -eq 0) 'Standard MSI installation and unified removal actions are present'
$older=@($tables.Upgrade | Where-Object ActionProperty -eq 'OLDPRODUCTS');$newer=@($tables.Upgrade | Where-Object ActionProperty -eq 'NEWERPRODUCTS')
Assert-Package ($older.Count -eq 1 -and $older[0].VersionMax -eq '1.0.12' -and [int]$older[0].Attributes -eq 0 -and $older[0].Remove -eq 'ALL') 'Upgrade range includes version10 without migrating advertised feature state'
Assert-Package ($newer.Count -eq 1 -and $newer[0].VersionMin -eq '1.0.12' -and [int]$newer[0].Attributes -eq 2 -and @($tables.LaunchCondition | Where-Object Condition -eq 'Installed OR NOT NEWERPRODUCTS').Count -eq 1) 'Newer versions are detected without removal and blocked from downgrade'
Assert-Package ($older.Count -eq 1 -and $older[0].VersionMax -eq $release.msiVersion -and [int]$older[0].Attributes -eq 0 -and $older[0].Remove -eq 'ALL') 'Upgrade range includes version10 without migrating advertised feature state'
Assert-Package ($newer.Count -eq 1 -and $newer[0].VersionMin -eq $release.msiVersion -and [int]$newer[0].Attributes -eq 2 -and @($tables.LaunchCondition | Where-Object Condition -eq 'Installed OR NOT NEWERPRODUCTS').Count -eq 1) 'Newer versions are detected without removal and blocked from downgrade'
$runtime=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.runtimeconfig.json') | ConvertFrom-Json
$deps=Get-Content -Raw (Join-Path $PackagePath 'Agent\PlotDirector.Companion.Agent.deps.json') | ConvertFrom-Json
Assert-Package ($runtime.runtimeOptions.tfm -eq 'net10.0' -and @($runtime.runtimeOptions.frameworks | Where-Object name -eq 'Microsoft.WindowsDesktop.App').Count -eq 1 -and $deps.runtimeTarget.name -like '*/win-x64') 'Tray depends on existing .NET10 Windows Desktop x64 runtime'

View File

@ -5,6 +5,7 @@ param(
[Parameter(Mandatory)][string]$ReportPath
)
$ErrorActionPreference='Stop'
$release=Get-Content -Raw (Join-Path $PSScriptRoot 'Release.json') | ConvertFrom-Json
$checks=[Collections.Generic.List[string]]::new()
function Assert-Upgrade([bool]$condition,[string]$message){if(!$condition){throw "Upgrade regression failed: $message"};$checks.Add($message)}
function Com($object,[string]$member,[object[]]$arguments,[switch]$Property){$values=@(foreach($v in $arguments){$v.PSObject.BaseObject});$flags=if($Property){[Reflection.BindingFlags]::GetProperty}else{[Reflection.BindingFlags]::InvokeMethod};$object.GetType().InvokeMember($member,$flags,$null,$object,$values)}
@ -33,21 +34,21 @@ $failed=Authoring $installer (Join-Path $FailedSetupDirectory 'PlotDirectorCompa
$corrected=Authoring $installer (Join-Path $CorrectedSetupDirectory 'PlotDirectorCompanion.msi')
Assert-Upgrade ($failed.problems.Count -eq 4) 'Negative control: original released version12 MSI fails all four local-install invariants'
Assert-Upgrade ($corrected.problems.Count -eq 0) 'Corrected MSI cannot inherit the recorded advertised feature selection'
Assert-Upgrade ($failed.properties.ProductCode -eq $corrected.properties.ProductCode -and $corrected.properties.ProductVersion -eq '1.0.12') 'Existing partially registered version12 remains repairable under the same product identity'
Assert-Upgrade ($failed.properties.ProductCode -ne $corrected.properties.ProductCode -and $corrected.properties.ProductCode -eq $release.productCode -and $corrected.properties.ProductVersion -eq $release.msiVersion) 'New release has its own major-upgrade identity, distinct from the failed version12 package'
$exe=Join-Path $CorrectedSetupDirectory 'PlotDirectorCompanionSetup.exe'
$assembly=[Reflection.Assembly]::Load([IO.File]::ReadAllBytes($exe))
$policy=$assembly.GetType('CompanionUpgradePolicy',$true)
foreach($scenario in @(@{name='version10 advertised-feature major upgrade';registered=$false},@{name='partially registered version12 repair';registered=$true})){
foreach($scenario in @(@{name='version10 advertised-feature major upgrade';registered=$false},@{name='same-release advertised repair';registered=$true})){
# Invoke only the compiled pure policy, never Setup.Main or any MSI API action.
$properties=[string]$policy.GetMethod('InstallProperties').Invoke($null,@([bool]$scenario.registered))
Assert-Upgrade ($properties -match '(^| )ADDLOCAL=Complete( |$)' -and $properties -match 'REINSTALLMODE=vamus' -and $properties -notmatch 'ADVERTISE=') "Compiled bootstrapper requests local files: $($scenario.name)"
Assert-Upgrade (($properties -match 'REINSTALL=ALL') -eq [bool]$scenario.registered) "Compiled bootstrapper chooses correct repair mode: $($scenario.name)"
}
foreach($versions in @(@{word='1.0.0.10';agent='1.0.0.10'},@{word='1.0.0.12';agent='1.0.0.10'},@{word='1.0.0.10';agent='1.0.0.12'})){
$message=$null;try{$policy.GetMethod('VerifyVersions').Invoke($null,@('1.0.0.12',$versions.word,$versions.agent))}catch{$message=$_.Exception.GetBaseException().Message}
Assert-Upgrade ($message -like '*Expected 1.0.0.12*' -and $message.Contains('Word add-in detected '+$versions.word) -and $message.Contains('tray executable detected '+$versions.agent)) "Strict check rejects and diagnoses old/mixed files: $($versions.word) / $($versions.agent)"
foreach($versions in @(@{word='1.0.0.10';agent='1.0.0.10'},@{word='1.0.0.12';agent='1.0.0.12'},@{word=$release.version;agent='1.0.0.10'},@{word='1.0.0.10';agent=$release.version})){
$message=$null;try{$policy.GetMethod('VerifyVersions').Invoke($null,@($release.version,$versions.word,$versions.agent))}catch{$message=$_.Exception.GetBaseException().Message}
Assert-Upgrade ($message.Contains('Expected '+$release.version) -and $message.Contains('Word add-in detected '+$versions.word) -and $message.Contains('tray executable detected '+$versions.agent)) "Strict check rejects and diagnoses old/mixed files: $($versions.word) / $($versions.agent)"
}
$null=$policy.GetMethod('VerifyVersions').Invoke($null,@('1.0.0.12','1.0.0.12','1.0.0.12'));$checks.Add('Strict check accepts matching version12 files')
$null=$policy.GetMethod('VerifyVersions').Invoke($null,@($release.version,$release.version,$release.version));$checks.Add('Strict check accepts matching release files')
$transition=$policy.GetMethod('EnsureLocalFeature')
$query=[Func[int]]{$script:stateValue};$logger=[Action[string]]{param($message)}
foreach($initial in @(1,2,4)){
@ -70,5 +71,41 @@ $bootstrap=Get-Content -Raw (Join-Path $PSScriptRoot 'Setup.cs')
Assert-Upgrade ($bootstrap.IndexOf('CompanionUpgradePolicy.EnsureLocalFeature(') -lt $bootstrap.IndexOf('CompanionUpgradePolicy.VerifyVersions(') -and $bootstrap.Contains('MsiConfigureFeature(SetupRelease.ProductCode, "Complete", 3)')) 'Bootstrapper wires explicit native Local configuration before strict version validation'
$required=@('PlotDirector.WordAddIn.dll','PlotDirector.Companion.Agent.exe')
foreach($name in $required){$file=@($corrected.files | Where-Object {($_.FileName -split '\|')[-1] -eq $name});Assert-Upgrade ($file.Count -eq 1 -and @($corrected.components | Where-Object {$_.Component_ -eq $file[0].Component_ -and $_.Feature_ -eq 'Complete'}).Count -eq 1) "Required file belongs to the locally selected Complete feature: $name"}
@{passed=$checks;rejectedOriginalAuthoring=$failed.problems;correctedSetupSha256=(Get-FileHash $exe).Hash;scope='Read-only MSI tables and compiled pure policy only. No installed upgrade was executed.'} | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ReportPath -Encoding UTF8
$copy=$assembly.GetType('CompanionFileCopyPreflight',$true)
$verifyCopy=$copy.GetMethod('Verify');$guardMethod=$copy.GetMethod('AcquireAgentGuard')
$scratch=Join-Path ([IO.Path]::GetTempPath()) ('PlotDirector-copy-regression-'+[guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $scratch | Out-Null
$dll=Join-Path $scratch 'Microsoft.Office.Tools.Common.dll'
[IO.File]::WriteAllBytes($dll,[byte[]](1,2,3,4));$originalHash=(Get-FileHash $dll).Hash
try {
$null=$verifyCopy.Invoke($null,@($scratch,[string[]]@('Microsoft.Office.Tools.Common.dll','missing.dll'),$logger))
Assert-Upgrade ((Get-FileHash $dll).Hash -eq $originalHash) 'Replacement preflight accepts unlocked/missing payload without changing bytes'
$locked=[IO.File]::Open($dll,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::Read)
try {
$message=$null;try{$null=$verifyCopy.Invoke($null,@($scratch,[string[]]@('Microsoft.Office.Tools.Common.dll'),$logger))}catch{$message=$_.Exception.ToString()}
Assert-Upgrade ($message -like '*Microsoft.Office.Tools.Common.dll*Windows error 32*No registration or MSI changes*') 'Actual Windows sharing lock on the reported DLL blocks setup before registration/MSI changes'
} finally {$locked.Dispose()}
[IO.File]::SetAttributes($dll,[IO.FileAttributes]::ReadOnly)
try {
$message=$null;try{$null=$verifyCopy.Invoke($null,@($scratch,[string[]]@('Microsoft.Office.Tools.Common.dll'),$logger))}catch{$message=$_.Exception.ToString()}
Assert-Upgrade ($message -like '*Windows error 5*No registration or MSI changes*') 'Read-only replacement refusal reports access denied without relaxing permissions'
} finally {[IO.File]::SetAttributes($dll,[IO.FileAttributes]::Normal)}
$guard=$guardMethod.Invoke($null,@($scratch,7))
try {
$blocked=$false;try{$race=[IO.File]::Open((Join-Path $scratch 'agent-7.lock'),[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None);$race.Dispose()}catch{$blocked=$true}
Assert-Upgrade $blocked 'Installer holds the existing tray singleton contract against shortcut/sign-in restart during copying'
} finally {$guard.Dispose()}
$next=$guardMethod.Invoke($null,@($scratch,7));$next.Dispose()
Assert-Upgrade ((Get-FileHash $dll).Hash -eq $originalHash) 'Singleton guard releases for later tray launch and payload bytes remain unchanged'
} finally {
# Only these exact generated fixture files, never the installed application.
Remove-Item -LiteralPath $dll,(Join-Path $scratch 'agent-7.lock') -Force
Remove-Item -LiteralPath $scratch
}
$releaseType=$assembly.GetType('SetupRelease',$true)
$names=$releaseType.GetField('PayloadFiles',[Reflection.BindingFlags]'Static,NonPublic').GetValue($null)
Assert-Upgrade ($names.Count -eq $corrected.files.Count -and $names -contains 'Microsoft.Office.Tools.Common.dll' -and $names -contains 'Agent\PlotDirector.Companion.Agent.exe') 'Compiled replacement preflight inventory covers the whole MSI payload including the failed DLL and tray'
Assert-Upgrade ($bootstrap.IndexOf('CompanionFileCopyPreflight.Verify(') -lt $bootstrap.IndexOf('BackupRegistration(state)') -and $bootstrap.IndexOf('CompanionFileCopyPreflight.Verify(') -lt $bootstrap.IndexOf('RemoveOldDeployment(state)') -and $bootstrap.IndexOf('CompanionFileCopyPreflight.Verify(') -lt $bootstrap.IndexOf('MsiInstallProduct(msi, properties)')) 'Copy preflight precedes registration and all VSTO/MSI mutation'
Assert-Upgrade ($bootstrap.Contains('finally { if (upgradeGuard != null) upgradeGuard.Dispose(); }') -and $bootstrap.IndexOf('upgradeGuard.Dispose(); upgradeGuard = null;') -lt $bootstrap.IndexOf('Process.Start(new ProcessStartInfo(agent')) 'Singleton guard releases on failure and before the installed tray is started'
@{passed=$checks;rejectedOriginalAuthoring=$failed.problems;correctedSetupSha256=(Get-FileHash $exe).Hash;scope='Read-only MSI tables, compiled policy and disposable Windows file-lock fixtures only. No installed upgrade was executed.'} | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $ReportPath -Encoding UTF8
Write-Output "PASS exact advertised-feature upgrade regression: $($checks.Count) assertions; original package rejected, corrected package accepted without installation."