Skip to content

The agent that grows with you

test(install-e2e): wire native bundled update routes and receipts

ethernet925bcc0d2239
diff --git a/.github/workflows/install-e2e-macos-run.yml b/.github/workflows/install-e2e-macos-run.yml
index 89b42a79641..15ed09b6455 100644
--- a/.github/workflows/install-e2e-macos-run.yml
+++ b/.github/workflows/install-e2e-macos-run.yml
@@ -178,13 +178,16 @@ jobs:
# run anywhere native coverage would be fake.
bundled-e2e:
name: packaged bundle (open-app-update)
- if: inputs.bundle-manifest-url != ''
+ if: inputs.install-method == 'packaged-app' && inputs.update-method == 'open-app-update'
runs-on: ${{ inputs.bundle-arch == 'x64' && 'macos-15-intel' || 'macos-15' }}
timeout-minutes: ${{ inputs.timeout-minutes }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Install driver dependencies
+ run: npm ci --ignore-scripts --no-audit --no-fund
+
- name: Start screen recording
uses: ./.github/actions/e2e-screen-record
with:
@@ -194,19 +197,21 @@ jobs:
- name: Install OLD signed bundle (${{ inputs.install-ref }})
run: |
set -euo pipefail
- tests/install/macos-bundled-e2e.sh --phase install \
- --manifest-url '${{ inputs.bundle-manifest-url }}' \
- --arch '${{ inputs.bundle-arch }}'
+ bash tests/install/macos-bundled-e2e.sh --phase install \
+ --manifest-url "$BUNDLE_MANIFEST" --arch "$BUNDLE_ARCH"
env:
+ BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
+ BUNDLE_ARCH: ${{ inputs.bundle-arch }}
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
- name: Update to NEW via About -> Update now (${{ inputs.bundle-arch }})
run: |
set -euo pipefail
- tests/install/macos-bundled-e2e.sh --phase update \
- --manifest-url '${{ inputs.bundle-manifest-url }}' \
- --arch '${{ inputs.bundle-arch }}'
+ bash tests/install/macos-bundled-e2e.sh --phase update \
+ --manifest-url "$BUNDLE_MANIFEST" --arch "$BUNDLE_ARCH"
env:
+ BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
+ BUNDLE_ARCH: ${{ inputs.bundle-arch }}
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
- name: Stop screen recording
diff --git a/.github/workflows/install-e2e-windows-run.yml b/.github/workflows/install-e2e-windows-run.yml
index 223ae9f6ab6..534a6e35e08 100644
--- a/.github/workflows/install-e2e-windows-run.yml
+++ b/.github/workflows/install-e2e-windows-run.yml
@@ -77,11 +77,61 @@ on:
required: false
type: number
default: 60
+ bundle-manifest-url:
+ type: string
+ default: ''
+ bundle-arch:
+ type: string
+ default: x64
permissions:
contents: read
jobs:
+ bundled-e2e:
+ name: packaged bundle (open-app-update)
+ if: inputs.install-method == 'packaged-app' && inputs.update-method == 'open-app-update'
+ runs-on: ${{ inputs.bundle-arch == 'arm64' && 'windows-11-arm' || 'windows-2025' }}
+ timeout-minutes: ${{ inputs.timeout-minutes }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Install driver dependencies and verify helpers
+ shell: pwsh
+ run: |
+ npm ci --ignore-scripts --no-audit --no-fund
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+ node --test tests/install/e2e-assets/windows-bundled-helpers.test.mjs
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+ - name: Start recording
+ uses: ./.github/actions/e2e-screen-record
+ with:
+ mode: start
+ output: ${{ runner.temp }}/hermes-bundled-update-recording.mkv
+ - name: Install, update and observe native relaunch
+ shell: pwsh
+ env:
+ BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
+ BUNDLE_ARCH: ${{ inputs.bundle-arch }}
+ run: |
+ powershell -NoProfile -ExecutionPolicy Bypass -File tests/install/windows-bundled-e2e.ps1 -ManifestUrl $env:BUNDLE_MANIFEST -Arch $env:BUNDLE_ARCH
+ if ($LASTEXITCODE) { exit $LASTEXITCODE }
+ - name: Stop recording
+ if: always()
+ uses: ./.github/actions/e2e-screen-record
+ with:
+ mode: stop
+ output: ${{ runner.temp }}/hermes-bundled-update-recording.mkv
+ - name: Upload native acceptance evidence
+ if: always()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: install-e2e-logs-${{ inputs.leg-id }}-bundle-${{ inputs.bundle-arch }}
+ path: |
+ ${{ runner.temp }}/hermes-bundled-update/proof/
+ ${{ runner.temp }}/hermes-bundled-update/home/logs/
+ ${{ runner.temp }}/hermes-bundled-update-recording.mkv
+ if-no-files-found: error
+ retention-days: 14
e2e:
# Short static name on purpose: name expressions render UNEXPANDED on
# skipped jobs.
diff --git a/.github/workflows/install-e2e.yml b/.github/workflows/install-e2e.yml
index 84817d4dbb6..b299c86c49a 100644
--- a/.github/workflows/install-e2e.yml
+++ b/.github/workflows/install-e2e.yml
@@ -51,7 +51,15 @@ on:
required: false
type: choice
default: all
- options: [all, both, update, installer, windows-desktop, macos-desktop]
+ options: [all, both, update, installer, windows-desktop, macos-desktop, bundled, windows-bundled, macos-bundled]
+ windows-bundle-manifest:
+ description: 'HTTPS manifest pinning signed Windows OLD/NEW msixbundles; NEW must match this ref.'
+ type: string
+ default: ''
+ macos-bundle-manifest:
+ description: 'HTTPS manifest pinning signed macOS OLD/NEW app ZIPs; NEW must match this ref.'
+ type: string
+ default: ''
tag-count:
description: 'How many release tags to sample (newest, oldest, and a spread between).'
required: false
@@ -162,6 +170,58 @@ jobs:
--tags '${{ needs.pick-releases.outputs.tags }}' \
--format markdown >> "$GITHUB_STEP_SUMMARY"
+ bundle-inputs:
+ name: Validate pinned bundle transitions
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ windows: ${{ steps.inputs.outputs.windows }}
+ macos: ${{ steps.inputs.outputs.macos }}
+ windows-arch: ${{ steps.inputs.outputs.windows-arch }}
+ macos-arch: ${{ steps.inputs.outputs.macos-arch }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - id: inputs
+ env:
+ BUNDLE_WINDOWS_MANIFEST: ${{ inputs.windows-bundle-manifest }}
+ BUNDLE_MACOS_MANIFEST: ${{ inputs.macos-bundle-manifest }}
+ BUNDLE_ROUTE: ${{ inputs.route }}
+ run: |
+ npm ci --ignore-scripts --no-audit --no-fund
+ node tests/install/e2e-assets/bundle-plan.mjs
+
+ windows-bundled:
+ name: ${{ matrix.name }}
+ if: inputs.windows-bundle-manifest != '' && contains(fromJSON('["all", "bundled", "windows-bundled"]'), inputs.route)
+ needs: bundle-inputs
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJSON(needs.bundle-inputs.outputs.windows) }}
+ uses: ./.github/workflows/install-e2e-windows-run.yml
+ with:
+ install-method: packaged-app
+ update-method: open-app-update
+ install-ref: ${{ matrix.install_ref }}
+ leg-id: ${{ matrix.leg_id }}
+ bundle-manifest-url: ${{ inputs.windows-bundle-manifest }}
+ bundle-arch: ${{ needs.bundle-inputs.outputs.windows-arch }}
+
+ macos-bundled:
+ name: ${{ matrix.name }}
+ if: inputs.macos-bundle-manifest != '' && contains(fromJSON('["all", "bundled", "macos-bundled"]'), inputs.route)
+ needs: bundle-inputs
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJSON(needs.bundle-inputs.outputs.macos) }}
+ uses: ./.github/workflows/install-e2e-macos-run.yml
+ with:
+ install-method: packaged-app
+ update-method: open-app-update
+ install-ref: ${{ matrix.install_ref }}
+ leg-id: ${{ matrix.leg_id }}
+ bundle-manifest-url: ${{ inputs.macos-bundle-manifest }}
+ bundle-arch: ${{ needs.bundle-inputs.outputs.macos-arch }}
+
linux:
name: ${{ matrix.name }}
# The update/installer route choices map to the linux update methods;
@@ -247,7 +307,7 @@ jobs:
report:
name: Result chart
if: always()
- needs: [leg-player, pick-releases, linux, windows, macos]
+ needs: [leg-player, pick-releases, linux, windows, macos, bundle-inputs, windows-bundled, macos-bundled]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
diff --git a/apps/desktop/scripts/gen-appinstaller.test.mjs b/apps/desktop/scripts/gen-appinstaller.test.mjs
index b3ac0b9c2fc..129e12607c5 100644
--- a/apps/desktop/scripts/gen-appinstaller.test.mjs
+++ b/apps/desktop/scripts/gen-appinstaller.test.mjs
@@ -43,7 +43,8 @@ describe('buildAppInstaller', () => {
test('UpdateSettings keeps the OS prompt off (the in-app checker owns the prompt)', () => {
const xml = buildAppInstaller(base)
- assert.match(xml, /<OnLaunch HoursBetweenUpdateChecks="12" ShowPrompt="false" \/>/)
+ assert.match(xml, /<OnLaunch HoursBetweenUpdateChecks="12" \/>/)
+ assert.doesNotMatch(xml, /ShowPrompt=/)
})
test('a variant channel path with a trailing slash still resolves under the host', () => {
diff --git a/scripts/msix-shared.mjs b/scripts/msix-shared.mjs
index ea4489ba409..e21fd247604 100644
--- a/scripts/msix-shared.mjs
+++ b/scripts/msix-shared.mjs
@@ -173,7 +173,7 @@ export function buildAppInstaller(o) {
` Version="${escapeAttr(o.version)}"`,
` Uri="${escapeAttr(bundleUrl)}" />`,
' <UpdateSettings>',
- ' <OnLaunch HoursBetweenUpdateChecks="12" ShowPrompt="false" />',
+ ' <OnLaunch HoursBetweenUpdateChecks="12" />',
' </UpdateSettings>',
'</AppInstaller>',
''
diff --git a/tests-js/windows-bundled-helpers.test.mjs b/tests-js/windows-bundled-helpers.test.mjs
new file mode 100644
index 00000000000..1a80ee53300
--- /dev/null
+++ b/tests-js/windows-bundled-helpers.test.mjs
@@ -0,0 +1,9 @@
+import { execFileSync } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { expect, test } from 'vitest'
+
+test('Windows packaged-update helper contracts run in the ordinary JS lane', () => {
+ const suite = fileURLToPath(new URL('../tests/install/e2e-assets/windows-bundled-helpers.test.mjs', import.meta.url))
+ const output = execFileSync(process.execPath, ['--test', suite], { encoding: 'utf8', timeout: 30_000 })
+ expect(output).toMatch(/(?:fail 0|# fail 0)/)
+})
diff --git a/tests/install/e2e-assets/mac-bundled-feed.mjs b/tests/install/e2e-assets/mac-bundled-feed.mjs
index 560f4f5e7ff..26c9ec94b47 100644
--- a/tests/install/e2e-assets/mac-bundled-feed.mjs
+++ b/tests/install/e2e-assets/mac-bundled-feed.mjs
@@ -20,7 +20,7 @@ import { createHash } from 'node:crypto'
import fs from 'node:fs'
import path from 'node:path'
import { createReadStream } from 'node:fs'
-import { pipeline } from 'node:stream/promises'
+
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
@@ -31,12 +31,7 @@ const { darwinFeed } = require('../../../apps/desktop/update-feed.cjs')
* and must never be read whole into memory. */
export async function sha512Base64(filePath) {
const hash = createHash('sha512')
- await pipeline(createReadStream(filePath), async function* (source) {
- for await (const chunk of source) {
- hash.update(chunk)
- yield chunk
- }
- })
+ for await (const chunk of createReadStream(filePath)) hash.update(chunk)
return hash.digest('base64')
}
diff --git a/tests/install/e2e-assets/windows-bundled-drive-update.ps1 b/tests/install/e2e-assets/windows-bundled-drive-update.ps1
new file mode 100644
index 00000000000..20b6c66a7c4
--- /dev/null
+++ b/tests/install/e2e-assets/windows-bundled-drive-update.ps1
@@ -0,0 +1,202 @@
+# ============================================================================
+# windows-bundled-drive-update.ps1 — drive the REAL in-app update surface of
+# the INSTALLED (MSIX) desktop app via UI Automation.
+# ============================================================================
+# The packaged arm's whole point: a real user trigger starts the update
+# against the controlled feed. No Playwright Electron-driver attach (the
+# package must run AS INSTALLED, not from a checkout), so this helper drives
+# UIA exactly like the reference technique (package-update-acceptance.md):
+# the installed Electron UI exposes text and controls once Chromium's
+# accessibility engages for a UIA client.
+#
+# Sequence, each step polled with screenshots into -ProofDir:
+# 1. find the Hermes window (by process id, NOT window-title guesswork)
+# 2. click the in-app update trigger: the "Update now" button (i18n 'en'
+# updates-overlay: "A new version of Hermes is ready. Update now and
+# Windows will finish it for you."). Names matched case-insensitively
+# on 'update' for the button the app owns; NEVER an internal apply call.
+# 3. when the OS App Installer confirmation window appears, click its
+# Update/Install button (UpdateSettings OnLaunch ShowPrompt=false means
+# it usually does NOT appear; tolerate both).
+# 4. wait for the app processes to exit (the hand-off quits the app) —
+# exit 0 = the trigger was clicked by THIS driver and the app exited.
+#
+# The driver never launches a new app instance: proving the NEW process
+# without driver launch is the parent driver's job (windows-bundled-e2e.ps1).
+# ============================================================================
+
+param(
+ [Parameter(Mandatory = $true)][int]$OldProcessId,
+ [Parameter(Mandatory = $true)][string]$ProofDir,
+ [string]$ResultPath = "",
+ # How long to keep looking for the in-app button (the app may still be
+ # booting its backend when the driver starts).
+ [int]$ButtonTimeoutSec = 300,
+ # How long to wait for the App Installer confirmation dialog, if the OS
+ # shows one at all.
+ [int]$ConfirmTimeoutSec = 120,
+ # How long to wait for the app processes to exit after the click.
+ [int]$ExitTimeoutSec = 600
+)
+
+$ErrorActionPreference = "Stop"
+if ($env:GITHUB_ACTIONS -ne 'true') { throw 'Disposable CI runner required' }
+$oldProcess = Get-Process -Id $OldProcessId
+$oldBirth = $oldProcess.StartTime
+$ProcessName = $oldProcess.ProcessName
+[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
+
+Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes
+Add-Type -AssemblyName System.Windows.Forms, System.Drawing
+
+New-Item -ItemType Directory -Path $ProofDir -Force | Out-Null
+if (-not $ResultPath) { $ResultPath = Join-Path $ProofDir "drive-update-result.json" }
+
+function Save-Shot([string]$Name) {
+ try {
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
+ $bmp = New-Object System.Drawing.Bitmap($b.Width, $b.Height)
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
+ $g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size)
+ $bmp.Save((Join-Path $ProofDir "$Name.png"), [System.Drawing.Imaging.ImageFormat]::Png)
+ $g.Dispose(); $bmp.Dispose()
+ } catch { Write-Host " [uia] screenshot $Name failed: $($_.Exception.Message)" }
+}
+
+function Get-AppPids {
+ $current = Get-Process -Id $OldProcessId -ErrorAction SilentlyContinue
+ if ($current -and $current.StartTime -eq $oldBirth) { return @($OldProcessId) }
+ return @()
+}
+
+# UIA element helpers --------------------------------------------------------
+
+function Find-AppWindow {
+ param([int[]]$Pids)
+ if (-not $Pids -or $Pids.Count -eq 0) { return $null }
+ $root = [System.Windows.Automation.AutomationElement]::RootElement
+ $cond = New-Object System.Windows.Automation.PropertyCondition(
+ [System.Windows.Automation.AutomationElement]::ProcessIdProperty, $Pids[0])
+ # The process hosts several top-level windows (main + hidden helpers);
+ # prefer one with a window handle (visible).
+ $wins = $root.FindAll([System.Windows.Automation.TreeScope]::Children, $cond)
+ foreach ($w in $wins) {
+ if ($w.Current.NativeWindowHandle -ne 0) { return $w }
+ }
+ if ($wins.Count -gt 0) { return $wins[0] }
+ return $null
+}
+
+function Find-InvokableButton {
+ # Depth-first walk for a button whose Name matches one of the regexes.
+ param($Root, [string[]]$Patterns)
+ $cond = New-Object System.Windows.Automation.PropertyCondition(
+ [System.Windows.Automation.AutomationElement]::ControlTypeProperty,
+ [System.Windows.Automation.ControlType]::Button)
+ $buttons = $Root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)
+ foreach ($b in $buttons) {
+ $name = ""
+ try { $name = $b.Current.Name } catch {}
+ if (-not $name) { continue }
+ foreach ($pat in $Patterns) {
+ if ($name -match $pat) { return @{ Element = $b; Name = $name } }
+ }
+ }
+ return $null
+}
+
+function Invoke-Button($Element) {
+ $invoke = $null
+ if ($Element.TryGetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern, [ref]$invoke)) {
+ $invoke.Invoke()
+ return $true
+ }
+ # Fall back to a legacy click through the legacy pattern.
+ $legacy = $null
+ if ($Element.TryGetCurrentPattern([System.Windows.Automation.LegacyIAccessiblePattern]::Pattern, [ref]$legacy)) {
+ try { $legacy.DoDefaultAction(); return $true } catch {}
+ }
+ return $false
+}
+
+# 1. the in-app Update trigger ------------------------------------------------
+
+Write-Host "[uia] waiting for the $ProcessName window and its Update now button (up to ${ButtonTimeoutSec}s) ..."
+$pids = Get-AppPids
+if ($pids.Count -eq 0) { throw "no $ProcessName process is running - the install phase must leave the OLD app running" }
+
+$deadline = (Get-Date).AddSeconds($ButtonTimeoutSec)
+$clicked = $null
+while ((Get-Date) -lt $deadline -and -not $clicked) {
+ $pids = Get-AppPids
+ $win = Find-AppWindow -Pids $pids
+ if ($win) {
+ $hit = Find-InvokableButton -Root $win -Patterns @(
+ '^Update now', # en: the packaged overlay's primary action
+ 'Update Hermes', # en settings: About surface
+ '^Update$'
+ )
+ if ($hit) {
+ Save-Shot "01-before-update-click"
+ Write-Host " [uia] clicking button '$($hit.Name)'"
+ if (Invoke-Button $hit.Element) { $clicked = $hit } else { Write-Host " [uia] invoke pattern unavailable; retrying" }
+ } else {
+ # Use the visible settings flow; never call the updater bridge.
+ $navigation = Find-InvokableButton -Root $win -Patterns @('^Open settings$', '^About$', '^Check now$', 'choose a provider later')
+ if ($navigation) { [void](Invoke-Button $navigation.Element) }
+ }
+ }
+ if (-not $clicked) { Start-Sleep -Seconds 3 }
+}
+if (-not $clicked) {
+ Save-Shot "zz-no-update-button"
+ throw "never found an invokable Update button in the $ProcessName UI after $ButtonTimeoutSec s"
+}
+Write-Host " [uia] in-app update trigger clicked: $($clicked.Name)"
+
+# 2. the OS App Installer confirmation, if the OS shows one -------------------
+
+Write-Host "[uia] watching for an App Installer confirmation (up to ${ConfirmTimeoutSec}s) ..."
+$cDeadline = (Get-Date).AddSeconds($ConfirmTimeoutSec)
+$confirmed = $false
+while ((Get-Date) -lt $cDeadline -and -not $confirmed) {
+ $installer = Get-Process -Name "AppInstaller" -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($installer) {
+ $root = [System.Windows.Automation.AutomationElement]::RootElement
+ $cond = New-Object System.Windows.Automation.PropertyCondition(
+ [System.Windows.Automation.AutomationElement]::ProcessIdProperty, $installer.Id)
+ $win = $root.FindFirst([System.Windows.Automation.TreeScope]::Children, $cond)
+ if ($win) {
+ $hit = Find-InvokableButton -Root $win -Patterns @('^Update$', '^Install$', '^(Reinstall|Update) .*')
+ if ($hit) {
+ Save-Shot "02-appinstaller-confirm"
+ Write-Host " [uia] App Installer dialog: clicking '$($hit.Name)'"
+ if (Invoke-Button $hit.Element) { $confirmed = $true }
+ }
+ }
+ }
+ # The app quits before App Installer opens; keep watching its confirmation.
+ Start-Sleep -Seconds 3
+}
+if ($confirmed) { Write-Host " [uia] App Installer confirmation clicked" }
+else { Write-Host " [uia] no App Installer dialog appeared (OnLaunch ShowPrompt=false + real source registration): ok" }
+Save-Shot "03-after-trigger"
+
+# 3. wait for the app to exit (the hand-off quits it; never kill it here) -----
+
+Write-Host "[uia] waiting for $ProcessName to exit (up to ${ExitTimeoutSec}s) ..."
+$eDeadline = (Get-Date).AddSeconds($ExitTimeoutSec)
+while ((Get-Date) -lt $eDeadline) {
+ if ((Get-AppPids).Count -eq 0) {
+ Save-Shot "04-app-exited"
+ Write-Host " [uia] OLD app exited for the package swap"
+ @{ ok = $true; clicked = $clicked.Name; appInstallerConfirmed = [bool]$confirmed; exited = $true } |
+ ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8
+ exit 0
+ }
+ Start-Sleep -Seconds 5
+}
+Save-Shot "zz-app-never-exited"
+@{ ok = $false; clicked = $clicked.Name; appInstallerConfirmed = [bool]$confirmed; exited = $false } |
+ ConvertTo-Json | Set-Content -LiteralPath $ResultPath -Encoding UTF8
+throw "the $ProcessName process never exited after the update trigger ($ExitTimeoutSec s) - a surviving process would hold package files during the swap"
diff --git a/tests/install/e2e-assets/windows-bundled-helpers.mjs b/tests/install/e2e-assets/windows-bundled-helpers.mjs
new file mode 100644
index 00000000000..0ada4665cb5
--- /dev/null
+++ b/tests/install/e2e-assets/windows-bundled-helpers.mjs
@@ -0,0 +1,295 @@
+// windows-bundled-helpers.mjs — pure helpers + small CLI for the Windows
+// packaged-app (MSIX / App Installer) E2E arm (tests/install/windows-bundled-e2e.ps1).
+//
+// Everything OS-visible here derives from the PRODUCTION builders in
+// scripts/msix-shared.mjs (buildAppInstaller, OUT_OF_STORE_PUBLISHER,
+// contentTypeFor) so the test feed cannot drift from the real feed. The
+// production module's path is a CLI arg (--msix-shared) so the primary
+// checkout's copy (with the parent-owned MainBundle/descriptorFilename
+// support) is used read-only; the in-repo file is the fallback.
+//
+// CLI (space-separated flag pairs — `node script.mjs -- --flag value` also
+// works; see the repo AGENTS note on Node eating `--` args):
+// node windows-bundled-helpers.mjs validate-manifest --manifest <path> --msix-shared <path>
+// node windows-bundled-helpers.mjs descriptor --feed <dir> --base-url <url>
+// --identity <name> --version <4-part> --bundle <filename>
+// [--descriptor-filename update.appinstaller] [--msix-shared <path>]
+// node windows-bundled-helpers.mjs serve --feed <dir> --port-file <path>
+
+import fs from 'node:fs'
+import path from 'node:path'
+import http from 'node:http'
+import { pathToFileURL, fileURLToPath } from 'node:url'
+
+// ── pure helpers (unit-tested in windows-bundled-helpers.test.mjs) ──────────
+
+const MANIFEST_SIDES = ['old', 'new']
+const REQUIRED_SIDE_FIELDS = ['tag', 'version', 'commit', 'identity', 'publisher', 'applicationId']
+const REQUIRED_ARTIFACT_FIELDS = ['url', 'sha256']
+const SUPPORTED_ARCHES = ['x64', 'arm64']
+const COMMIT_RE = /^[0-9a-f]{40}$/
+const SHA256_RE = /^[0-9a-fA-F]{64}$/
+const FOUR_PART_RE = /^\d{1,5}\.\d{1,5}\.\d{1,5}\.\d{1,5}$/
+
+/**
+ * True when 4-part MSIX version `a` is strictly newer than `b`
+ * (numeric, component-wise; MSIX swaps require strict monotonicity).
+ * @param {string} a
+ * @param {string} b
+ * @returns {boolean}
+ */
+export function fourPartNewer(a, b) {
+ if (!FOUR_PART_RE.test(a) || !FOUR_PART_RE.test(b)) return false
+ const pa = a.split('.').map(Number)
+ const pb = b.split('.').map(Number)
+ for (let i = 0; i < 4; i++) {
+ if (pa[i] !== pb[i]) return pa[i] > pb[i]
+ }
+ return false
+}
+
+/**
+ * Validate the parent-owned resolver's normalized bundle-inputs manifest
+ * (schema1). `expectedPublisher` is injected by the caller from the
+ * production OUT_OF_STORE_PUBLISHER so the rule binds at runtime, and
+ * `artifactPathsExist` (default true) lets unit tests pass without files.
+ *
+ * @param {unknown} raw parsed manifest JSON
+ * @param {{ expectedPublisher: string, arch?: string, artifactPathsExist?: boolean }} o
+ * @returns {{ ok: boolean, errors: string[] }}
+ */
+export function validateBundledManifest(raw, o) {
+ const errors = []
+ const arch = o.arch || 'x64'
+ const m = raw
+ if (!m || typeof m !== 'object' || Array.isArray(m)) {
+ return { ok: false, errors: ['manifest is not an object'] }
+ }
+ if (m.schema !== 1) errors.push(`schema: expected 1, got ${JSON.stringify(m.schema)}`)
+ if (m.platform !== 'windows') errors.push(`platform: expected "windows", got ${JSON.stringify(m.platform)}`)
+ if (!SUPPORTED_ARCHES.includes(arch)) errors.push(`arch "${arch}" not supported (${SUPPORTED_ARCHES.join('|')})`)
+ if (m.arch !== arch) errors.push(`arch: expected "${arch}", got ${JSON.stringify(m.arch)}`)
+
+ for (const side of MANIFEST_SIDES) {
+ const s = m?.[side]
+ if (!s || typeof s !== 'object') {
+ errors.push(`${side}: missing`)
+ continue
+ }
+ for (const f of REQUIRED_SIDE_FIELDS) {
+ if (typeof s[f] !== 'string' || !s[f]) errors.push(`${side}.${f}: missing or not a string`)
+ }
+ if (typeof s.version === 'string' && !FOUR_PART_RE.test(s.version)) {
+ errors.push(`${side}.version: "${s.version}" is not a 4-part MSIX version`)
+ }
+ if (typeof s.commit === 'string' && !COMMIT_RE.test(s.commit)) {
+ errors.push(`${side}.commit: "${s.commit}" is not a 40-hex commit`)
+ }
+ const art = s.artifact
+ if (!art || typeof art !== 'object') {
+ errors.push(`${side}.artifact: missing`)
+ } else {
+ for (const f of REQUIRED_ARTIFACT_FIELDS) {
+ if (typeof art[f] !== 'string' || !art[f]) errors.push(`${side}.artifact.${f}: missing or not a string`)
+ }
+ if (typeof art.sha256 === 'string' && !SHA256_RE.test(art.sha256)) {
+ errors.push(`${side}.artifact.sha256: not 64 hex chars`)
+ }
+ if (typeof art.path !== 'string' || !art.path) {
+ // The parent resolver writes artifact.path (the downloaded, verified
+ // local file). Its absence means the contract regressed — fail loudly
+ // rather than serving an unverified package.
+ errors.push(`${side}.artifact.path: missing (parent resolver must write the downloaded local path)`)
+ } else if (o.artifactPathsExist !== false && !fs.existsSync(art.path)) {
+ errors.push(`${side}.artifact.path: "${art.path}" does not exist`)
+ }
+ }
+ }
+
+ if (m?.old?.publisher && m?.new?.publisher && m.old.publisher !== m.new.publisher) {
+ errors.push('old.publisher and new.publisher disagree — one manifest, one identity')
+ }
+ for (const side of MANIFEST_SIDES) {
+ if (m?.[side]?.publisher && m[side].publisher !== o.expectedPublisher) {
+ errors.push(`${side}.publisher does not equal the production OUT_OF_STORE_PUBLISHER — refusing to serve a package the OS would reject`)
+ }
+ }
+ if (m?.old?.identity && m?.new?.identity && m.old.identity !== m.new.identity) {
+ errors.push('old.identity and new.identity disagree — an App Installer update swaps within ONE identity')
+ }
+ if (m?.old?.applicationId && m?.new?.applicationId && m.old.applicationId !== m.new.applicationId) {
+ errors.push('old.applicationId and new.applicationId disagree')
+ }
+ if (
+ m?.old?.version && m?.new?.version &&
+ FOUR_PART_RE.test(m.old.version) && FOUR_PART_RE.test(m.new.version) &&
+ !fourPartNewer(m.new.version, m.old.version)
+ ) {
+ errors.push(`new.version ${m.new.version} is not strictly newer than old.version ${m.old.version}`)
+ }
+ if (m?.old?.commit && m?.old?.commit === m?.new?.commit) {
+ errors.push('old.commit equals new.commit — no update to prove')
+ }
+
+ return { ok: errors.length === 0, errors }
+}
+
+/**
+ * The feed layout for one manifest: per-side bundle file name (served under
+ * <feedUrl>/<side>/) and the single swapped descriptor path.
+ * @param {string} feedDir
+ * @param {{ old: { artifact: { path: string } }, new: { artifact: { path: string } } }} manifest
+ * @returns {{ oldBundlePath: string, newBundlePath: string, oldBundleName: string, newBundleName: string, descriptorPath: string }}
+ */
+export function feedLayout(feedDir, manifest) {
+ const oldBundleName = path.basename(manifest.old.artifact.path)
+ const newBundleName = path.basename(manifest.new.artifact.path)
+ if (oldBundleName === newBundleName) {
+ // Same filename at the same URL would leave App Installer's cache (and
+ // any human reading the feed) unable to tell the swap happened.
+ throw new Error(`old and new bundle filenames collide: ${oldBundleName} — stage per-side dirs`)
+ }
+ return {
+ oldBundlePath: path.join(feedDir, 'old', oldBundleName),
+ newBundlePath: path.join(feedDir, 'new', newBundleName),
+ oldBundleName,
+ newBundleName,
+ descriptorPath: path.join(feedDir, 'update.appinstaller')
+ }
+}
+
+/**
+ * The arguments for the production buildAppInstaller for one feed side.
+ * variantChannelPath is '' — the side is folded into baseUrl (context
+ * contract), and the descriptor Uri is the optional descriptorFilename
+ * (parent-owned fix; defaults to the bundle filename with .appinstaller).
+ * @param {{ baseUrl: string, identityName: string, version: string, bundleFilename: string, descriptorFilename?: string }} o
+ */
+export function descriptorArgs(o) {
+ return {
+ baseUrl: o.baseUrl,
+ variantChannelPath: '',
+ identityName: o.identityName,
+ version: o.version,
+ bundleFilename: o.bundleFilename,
+ ...(o.descriptorFilename ? { descriptorFilename: o.descriptorFilename } : {})
+ }
+}
+
+/** Load the production msix-shared module from an explicit path. */
+export async function loadMsixShared(msixSharedPath) {
+ const resolved = path.resolve(msixSharedPath)
+ if (!fs.existsSync(resolved)) {
+ throw new Error(`production msix-shared.mjs not found at ${resolved} — pass --msix-shared`)
+ }
+ return import(pathToFileURL(resolved).href)
+}
+
+// ── CLI ──────────────────────────────────────────────────────────────────────
+
+function parseArgs(argv) {
+ const out = {}
+ for (let i = 0; i < argv.length; i += 2) {
+ out[String(argv[i]).replace(/^--/, '')] = argv[i + 1]
+ }
+ return out
+}
+
+async function main() {
+ const argv = process.argv[2] === '--' ? process.argv.slice(3) : process.argv.slice(2)
+ const cmd = argv[0]
+ const flags = parseArgs(argv.slice(1))
+ const msixShared = flags['msix-shared'] ||
+ path.resolve(fileURLToPath(new URL('../../../scripts/msix-shared.mjs', import.meta.url)))
+
+ if (cmd === 'validate-manifest') {
+ const shared = await loadMsixShared(msixShared)
+ const manifest = JSON.parse(fs.readFileSync(flags.manifest, 'utf8'))
+ const result = validateBundledManifest(manifest, {
+ expectedPublisher: shared.OUT_OF_STORE_PUBLISHER,
+ arch: flags.arch || undefined
+ })
+ console.log(JSON.stringify(result))
+ process.exit(result.ok ? 0 : 1)
+ }
+
+ if (cmd === 'descriptor') {
+ const shared = await loadMsixShared(msixShared)
+ if (typeof shared.buildAppInstaller !== 'function') {
+ throw new Error('production buildAppInstaller missing — contract regression')
+ }
+ const xml = shared.buildAppInstaller(descriptorArgs({
+ baseUrl: flags['base-url'],
+ identityName: flags.identity,
+ version: flags.version,
+ bundleFilename: flags.bundle,
+ descriptorFilename: flags['descriptor-filename'] || undefined
+ }))
+ // CONTRACT CHECK: the descriptor's own Uri must be the descriptor
+ // filename (the OS registers THIS uri as the update source), not a
+ // derived-from-bundle name. If the parent's descriptorFilename support
+ // is missing, the derived Uri would be <bundle>.appinstaller instead.
+ if (flags['descriptor-filename']) {
+ const m = /Uri="([^"]+)"/.exec(xml)
+ if (!m || !m[1].endsWith(flags['descriptor-filename'])) {
+ throw new Error(
+ `buildAppInstaller ignored descriptorFilename: Uri=${m ? m[1] : '(none)'} ` +
+ `does not end with ${flags['descriptor-filename']} — parent msix-shared fix required`
+ )
+ }
+ }
+ const feed = path.resolve(flags.feed)
+ fs.mkdirSync(path.dirname(path.resolve(flags.out || path.join(feed, 'update.appinstaller'))), { recursive: true })
+ const outPath = flags.out || path.join(feed, 'update.appinstaller')
+ fs.writeFileSync(outPath, xml)
+ console.log(JSON.stringify({ ok: true, path: outPath }))
+ return
+ }
+
+ if (cmd === 'serve') {
+ const shared = await loadMsixShared(msixShared)
+ const feed = path.resolve(flags.feed)
+ fs.mkdirSync(feed, { recursive: true })
+ const server = http.createServer((req, res) => {
+ let urlPath
+ try { urlPath = decodeURIComponent((req.url || '/').split('?')[0]) }
+ catch { res.writeHead(400).end('bad path'); return }
+ const rel = urlPath.replace(/^\/+/, '')
+ const target = path.resolve(feed, rel)
+ if (!target.startsWith(feed + path.sep) && target !== feed) {
+ res.writeHead(403).end('forbidden')
+ return
+ }
+ fs.stat(target, (err, stat) => {
+ if (err || !stat.isFile()) {
+ console.log(`[feed] 404 ${urlPath}`)
+ res.writeHead(404).end('not found')
+ return
+ }
+ const mime = shared.contentTypeFor(path.basename(target)) || 'application/octet-stream'
+ res.writeHead(200, { 'Content-Type': mime, 'Content-Length': stat.size, 'Cache-Control': 'no-store' })
+ const stream = fs.createReadStream(target)
+ stream.on('error', () => res.destroy())
+ res.on('close', () => stream.destroy())
+ stream.pipe(res)
+ console.log(`[feed] 200 ${urlPath} (${mime})`)
+ })
+ })
+ server.listen(0, '127.0.0.1', () => {
+ const url = `http://127.0.0.1:${server.address().port}`
+ fs.writeFileSync(flags['port-file'], url)
+ console.log(`[feed] serving ${feed} at ${url}`)
+ })
+ return
+ }
+
+ console.error('usage: validate-manifest | descriptor | serve (see file header)')
+ process.exit(2)
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().catch(err => {
+ console.error(err && err.stack || String(err))
+ process.exit(1)
+ })
+}
diff --git a/tests/install/e2e-assets/windows-bundled-helpers.test.mjs b/tests/install/e2e-assets/windows-bundled-helpers.test.mjs
new file mode 100644
index 00000000000..d03e51ec067
--- /dev/null
+++ b/tests/install/e2e-assets/windows-bundled-helpers.test.mjs
@@ -0,0 +1,141 @@
+// windows-bundled-helpers — unit tests for the pure helpers of the
+// Windows packaged-app E2E arm. node:test, no production imports needed:
+// the publisher rule takes the production constant as injected data (the
+// driver binds it to OUT_OF_STORE_PUBLISHER at runtime, from the same
+// module it builds the feed descriptors with).
+//
+// node --test tests/install/e2e-assets/windows-bundled-helpers.test.mjs
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+
+import { validateBundledManifest, fourPartNewer, feedLayout, descriptorArgs } from './windows-bundled-helpers.mjs'
+
+const PUB = 'CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US'
+const OTHER_PUB = 'CN=Someone Else'
+
+function side(over = {}) {
+ return {
+ tag: 'v0.3.0',
+ version: '0.3.0.0',
+ commit: 'a'.repeat(40),
+ identity: 'NousResearch.HermesBundled',
+ publisher: PUB,
+ applicationId: 'Hermes',
+ artifact: {
+ url: 'https://example.invalid/HermesBundled-0.3.0.0-win.msixbundle',
+ sha256: 'b'.repeat(64),
+ path: 'C:/staging/old/HermesBundled-0.3.0.0-win.msixbundle'
+ },
+ ...over
+ }
+}
+
+function manifest(over = {}) {
+ return { schema: 1, platform: 'windows', arch: 'x64', old: side(), new: side({ tag: 'v0.4.0', version: '0.4.0.0', commit: 'c'.repeat(40), artifact: { url: 'https://example.invalid/HermesBundled-0.4.0.0-win.msixbundle', sha256: 'd'.repeat(64), path: 'C:/staging/new/HermesBundled-0.4.0.0-win.msixbundle' } }), ...over }
+}
+
+function validate(m, extra = {}) {
+ return validateBundledManifest(m, { expectedPublisher: PUB, artifactPathsExist: false, ...extra })
+}
+
+test('a well-formed schema1 windows manifest validates', () => {
+ const r = validate(manifest())
+ assert.deepEqual(r, { ok: true, errors: [] })
+})
+
+test('rejects wrong schema, platform, and arch', () => {
+ assert.ok(!validate(manifest({ schema: 2 })).ok)
+ assert.ok(!validate(manifest({ platform: 'macos' })).ok)
+ assert.ok(!validate(manifest({ arch: 'arm64' })).ok)
+ assert.ok(validate(manifest({ arch: 'arm64' }), { arch: 'arm64' }).ok)
+})
+
+test('rejects a publisher that is not the production OUT_OF_STORE_PUBLISHER', () => {
+ const m = manifest()
+ m.old.publisher = OTHER_PUB
+ const r = validate(m)
+ assert.ok(!r.ok)
+ assert.ok(r.errors.some(e => e.includes('OUT_OF_STORE_PUBLISHER')))
+})
+
+test('rejects side/identity/applicationId disagreement', () => {
+ const m = manifest()
+ m.new.identity = 'NousResearch.Other'
+ assert.ok(!validate(m).ok)
+ const m2 = manifest()
+ m2.new.applicationId = 'Other'
+ assert.ok(!validate(m2).ok)
+ const m3 = manifest()
+ m3.new.publisher = OTHER_PUB
+ const r3 = validate(m3)
+ assert.ok(r3.errors.some(e => e.includes('old.publisher and new.publisher disagree')))
+})
+
+test('rejects non-monotonic versions and 3-part versions', () => {
+ const m = manifest()
+ m.new.version = '0.3.0.0'
+ assert.ok(validate(m).errors.some(e => e.includes('strictly newer')))
+ const m2 = manifest()
+ m2.old.version = '0.3.0'
+ assert.ok(validate(m2).errors.some(e => e.includes('4-part')))
+})
+
+test('rejects missing artifact fields and a fabricated artifact (no path)', () => {
+ const m = manifest()
+ delete m.new.artifact.path
+ assert.ok(validate(m).errors.some(e => e.includes('artifact.path')))
+ const m2 = manifest()
+ m2.old.artifact.sha256 = 'zz'
+ assert.ok(validate(m2).errors.some(e => e.includes('sha256')))
+ const m3 = manifest()
+ m3.new.artifact.url = ''
+ assert.ok(validate(m3).errors.some(e => e.includes('artifact.url')))
+})
+
+test('rejects old == new commit', () => {
+ const m = manifest()
+ m.new.commit = m.old.commit
+ assert.ok(validate(m).errors.some(e => e.includes('no update to prove')))
+})
+
+test('artifactPathsExist=true requires the downloaded file on disk', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wbh-'))
+ const p = path.join(dir, 'bundle.msixbundle')
+ fs.writeFileSync(p, 'x')
+ const m = manifest()
+ m.old.artifact.path = p
+ m.new.artifact.path = path.join(dir, 'new.msixbundle')
+ fs.writeFileSync(m.new.artifact.path, 'x')
+ assert.ok(validate(m, { artifactPathsExist: true }).ok)
+ m.old.artifact.path = path.join(dir, 'missing.msixbundle')
+ assert.ok(!validate(m, { artifactPathsExist: true }).ok)
+})
+
+test('fourPartNewer: numeric, component-wise, strict', () => {
+ assert.equal(fourPartNewer('0.4.0.0', '0.3.9.9'), true)
+ assert.equal(fourPartNewer('1.2.3.10', '1.2.3.9'), true)
+ assert.equal(fourPartNewer('0.3.0.0', '0.3.0.0'), false)
+ assert.equal(fourPartNewer('0.2.9.9', '0.3.0.0'), false)
+ assert.equal(fourPartNewer('0.3.0', '0.2.0.0'), false)
+})
+
+test('feedLayout stages per-side bundles and one swapped descriptor, rejecting collisions', () => {
+ const l = feedLayout('feed', manifest())
+ assert.ok(l.oldBundlePath.includes(`${path.sep}old${path.sep}`))
+ assert.ok(l.newBundlePath.includes(`${path.sep}new${path.sep}`))
+ assert.ok(l.descriptorPath.endsWith(`update.appinstaller`) || l.descriptorPath.endsWith('update.appinstaller'))
+ const m = manifest()
+ m.new.artifact.path = m.old.artifact.path
+ assert.throws(() => feedLayout('feed', m), /collide/)
+})
+
+test('descriptorArgs pass the contract shape (empty channel path, optional descriptor filename)', () => {
+ assert.deepEqual(descriptorArgs({ baseUrl: 'http://127.0.0.1:9/old', identityName: 'I', version: '0.3.0.0', bundleFilename: 'b.msixbundle' }), {
+ baseUrl: 'http://127.0.0.1:9/old', variantChannelPath: '', identityName: 'I', version: '0.3.0.0', bundleFilename: 'b.msixbundle'
+ })
+ const withD = descriptorArgs({ baseUrl: 'u', identityName: 'I', version: 'v', bundleFilename: 'b', descriptorFilename: 'update.appinstaller' })
+ assert.equal(withD.descriptorFilename, 'update.appinstaller')
+})
diff --git a/tests/install/macos-bundled-e2e.sh b/tests/install/macos-bundled-e2e.sh
index 119f3ad0f2b..3c19bee15fb 100644
--- a/tests/install/macos-bundled-e2e.sh
+++ b/tests/install/macos-bundled-e2e.sh
@@ -64,7 +64,7 @@ case "$ARCH" in arm64|x64) ;; *) echo "error: --arch must be arm64 or x64" >&2;
# Native CI-only guard: this leg runs real signed bundles, real codesign
# and real Squirrel.Mac, so it is meaningful only on a macOS CI runner.
[ "$(uname -s)" = "Darwin" ] || { echo "error: this driver runs on macOS only" >&2; exit 1; }
-[ -n "${GITHUB_ACTIONS:-}" ] || { echo "error: this driver is CI-only (GITHUB_ACTIONS required)" >&2; exit 1; }
+[ "${GITHUB_ACTIONS:-}" = true ] || { echo "error: this driver is CI-only (GITHUB_ACTIONS required)" >&2; exit 1; }
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
ASSETS="$REPO_ROOT/tests/install/e2e-assets"
@@ -191,8 +191,7 @@ phase_install() {
[ -n "$found" ] || fail "no .app inside the OLD release zip"
local old_app="$WORK_ROOT/apps/Hermes.app"
mv "$found" "$old_app"
- # curl/unzip'd files carry no quarantine attr, but belt and braces.
- xattr -dr com.apple.quarantine "$old_app" 2>/dev/null || true
+
local old_app_bin
old_app_bin="$(derive_app_bin "$old_app")"
ok "OLD bundle installed at $old_app (executable: $(basename "$old_app_bin"))"
@@ -406,7 +405,7 @@ phase_update() {
|| fail "isolated user-state marker did not survive the update"
ok "isolated user state survived"
- step "PASS: packaged $new_tag -> $new_version via the real About -> Update now route"
+ step "PASS: packaged $(manifest_side old tag) -> $new_tag via the real About -> Update now route"
}
case "$PHASE" in
diff --git a/tests/install/windows-bundled-e2e.ps1 b/tests/install/windows-bundled-e2e.ps1
new file mode 100644
index 00000000000..b2bde460ccc
--- /dev/null
+++ b/tests/install/windows-bundled-e2e.ps1
@@ -0,0 +1,163 @@
+# Native package replacement acceptance. Never run on a developer desktop.
+param(
+ [Parameter(Mandatory=$true)][string]$ManifestUrl,
+ [ValidateSet('x64','arm64')][string]$Arch = 'x64'
+)
+$ErrorActionPreference = 'Stop'
+Set-StrictMode -Version Latest
+if ($env:GITHUB_ACTIONS -ne 'true' -or $env:OS -ne 'Windows_NT') { throw 'Disposable Windows Actions runner required' }
+$Repo = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..'))
+$Assets = Join-Path $PSScriptRoot 'e2e-assets'
+$Work = Join-Path $env:RUNNER_TEMP 'hermes-bundled-update'
+if (Test-Path $Work) { throw "Refusing to reuse $Work" }
+$Proof = Join-Path $Work 'proof'
+New-Item -ItemType Directory -Path $Proof -Force | Out-Null
+$env:HERMES_HOME = Join-Path $Work 'home'
+New-Item -ItemType Directory -Path $env:HERMES_HOME | Out-Null
+$env:HERMES_DESKTOP_USER_DATA = Join-Path $Work 'electron-user-data'
+$env:HERMES_DESKTOP_FEED_BASE_URL = ''
+$Node = (Get-Command node.exe).Source
+function Run-Node([string[]]$Argv) {
+ & $Node @Argv
+ if ($LASTEXITCODE -ne 0) { throw "Node failed: $($Argv[0])" }
+}
+Run-Node @((Join-Path $Assets 'bundle-inputs.mjs'), '--manifest-url', $ManifestUrl, '--platform', 'windows', '--arch', $Arch, '--out', $Work)
+$ManifestPath = Join-Path $Work 'bundle-inputs.json'
+$m = Get-Content -Raw -LiteralPath $ManifestPath | ConvertFrom-Json
+Run-Node @((Join-Path $Assets 'windows-bundled-helpers.mjs'), 'validate-manifest', '--manifest', $ManifestPath, '--arch', $Arch)
+if (Get-AppxPackage -Name $m.old.identity) { throw 'Package identity is already installed; refusing to modify it' }
+Add-Type -AssemblyName System.IO.Compression.FileSystem
+function Assert-Bundle($Side) {
+ $artifact = $Side.artifact.path
+ if ((Get-FileHash -Algorithm SHA256 -LiteralPath $artifact).Hash.ToLowerInvariant() -cne $Side.artifact.sha256) { throw 'Bundle hash mismatch' }
+ $signature = Get-AuthenticodeSignature -LiteralPath $artifact
+ if ($signature.Status -ne 'Valid') { throw "Bundle signature invalid: $($signature.Status)" }
+ $zip = [IO.Compression.ZipFile]::OpenRead($artifact)
+ try {
+ $entry = $zip.GetEntry('AppxMetadata/AppxBundleManifest.xml')
+ if (-not $entry) { throw 'Not an MSIX bundle' }
+ $reader = New-Object IO.StreamReader($entry.Open())
+ try { [xml]$xml = $reader.ReadToEnd() } finally { $reader.Dispose() }
+ if ($xml.Bundle.Identity.Name -cne $Side.identity -or $xml.Bundle.Identity.Publisher -cne $Side.publisher -or $xml.Bundle.Identity.Version -cne $Side.version) { throw 'Bundle identity disagrees with pinned manifest' }
+ if (-not @($xml.Bundle.Packages.Package | Where-Object { $_.Architecture -eq $Arch }).Count) { throw 'Requested architecture absent from bundle' }
+ } finally { $zip.Dispose() }
+}
+Assert-Bundle $m.old
+Assert-Bundle $m.new
+
+function Installed($Side) {
+ $packages = @(Get-AppxPackage -Name $Side.identity)
+ if ($packages.Count -ne 1) { throw 'Expected exactly one installed package' }
+ $pkg = $packages[0]
+ if ($pkg.Version.ToString() -cne $Side.version -or $pkg.Publisher -cne $Side.publisher -or $pkg.Architecture.ToString() -ine $Arch) { throw 'Installed package identity/version/architecture mismatch' }
+ $stampPath = Join-Path $pkg.InstallLocation 'app\resources\install-stamp.json'
+ $stamp = Get-Content -Raw -LiteralPath $stampPath | ConvertFrom-Json
+ if ($stamp.commit -cne $Side.commit -or $stamp.tag -cne $Side.tag -or $stamp.payload -cne 'bundled') { throw 'Installed payload provenance mismatch' }
+ $xml = Get-AppxPackageManifest -Package $pkg.PackageFullName
+ $application = @($xml.Package.Applications.Application | Where-Object { $_.Id -ceq $Side.applicationId })
+ if ($application.Count -ne 1) { throw 'Installed applicationId missing' }
+ $exe = Join-Path $pkg.InstallLocation $application[0].Executable
+ if (-not (Test-Path -LiteralPath $exe)) { throw 'Installed executable missing' }
+ return @{ package=$pkg; exe=$exe; stamp=$stamp }
+}
+function Main-Processes([string]$Exe) {
+ return @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $Exe })
+}
+$Feed = Join-Path $Work 'feed'
+New-Item -ItemType Directory -Path $Feed | Out-Null
+Copy-Item -LiteralPath $m.old.artifact.path -Destination (Join-Path $Feed 'old.msixbundle')
+Copy-Item -LiteralPath $m.new.artifact.path -Destination (Join-Path $Feed 'new.msixbundle')
+$PortFile = Join-Path $Work 'feed-url'
+$Helper = Join-Path $Assets 'windows-bundled-helpers.mjs'
+$server = Start-Process -FilePath $Node -ArgumentList @('"'+$Helper+'"', 'serve', '--feed', '"'+$Feed+'"', '--port-file', '"'+$PortFile+'"') -PassThru -RedirectStandardOutput (Join-Path $Proof 'feed.log') -RedirectStandardError (Join-Path $Proof 'feed-error.log')
+$installed = $false
+try {
+ $deadline = (Get-Date).AddSeconds(20)
+ while (-not (Test-Path $PortFile)) {
+ if ($server.HasExited -or (Get-Date) -gt $deadline) { throw 'Feed failed to start' }
+ Start-Sleep -Milliseconds 200
+ }
+ $baseUrl = (Get-Content -Raw $PortFile).Trim()
+ function Descriptor($Side, [string]$File) {
+ Run-Node @($Helper, 'descriptor', '--feed', $Feed, '--base-url', $baseUrl, '--identity', $Side.identity, '--version', $Side.version, '--bundle', $File, '--descriptor-filename', 'update.appinstaller')
+ }
+ Descriptor $m.old 'old.msixbundle'
+ $descriptor = Join-Path $Feed 'update.appinstaller'
+ Add-AppxPackage -AppInstallerFile $descriptor
+ $installed = $true
+ $old = Installed $m.old
+ # Pin a real OS-registered update source before launching the application.
+ $old.package | Select-Object Name, Version, Publisher, Architecture, InstallLocation | ConvertTo-Json | Set-Content (Join-Path $Proof 'old-package.json')
+ $marker = Join-Path $env:HERMES_HOME 'bundle-state-marker'
+ $witness = [Guid]::NewGuid().ToString()
+ Set-Content -LiteralPath $marker -Value $witness
+ $python = (Get-Command python.exe).Source
+ $verifier = Join-Path $Assets 'verify-plugin-preservation.py'
+ & $python $verifier seed --home $env:HERMES_HOME --external (Join-Path $Work 'external-plugin')
+ if ($LASTEXITCODE -ne 0) { throw 'Plugin seed failed' }
+ & $python $verifier snapshot --home $env:HERMES_HOME --out (Join-Path $Work 'plugins-before.json')
+ if ($LASTEXITCODE -ne 0) { throw 'Plugin snapshot failed' }
+ # This is the only app launch performed by the driver: OLD, from its registered package.
+ Start-Process -FilePath $old.exe -ArgumentList '--force-renderer-accessibility' | Out-Null
+ $deadline = (Get-Date).AddMinutes(3)
+ do {
+ $oldRows = Main-Processes $old.exe
+ if ($oldRows.Count) { break }
+ Start-Sleep -Seconds 1
+ } while ((Get-Date) -lt $deadline)
+ if ($oldRows.Count -ne 1) { throw 'Could not identify the old installed app process' }
+ $oldProcess = $oldRows[0]
+ $oldProcess | Select-Object ProcessId, CreationDate, ExecutablePath | ConvertTo-Json | Set-Content (Join-Path $Proof 'old-process.json')
+ Descriptor $m.new 'new.msixbundle'
+ & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Assets 'windows-bundled-drive-update.ps1') -OldProcessId $oldProcess.ProcessId -ProofDir $Proof -ResultPath (Join-Path $Proof 'click.json')
+ if ($LASTEXITCODE -ne 0) { throw 'Real in-app update trigger failed' }
+ $click = Get-Content -Raw (Join-Path $Proof 'click.json') | ConvertFrom-Json
+ if (-not $click.ok -or -not $click.exited) { throw 'In-app trigger receipt is not successful' }
+ $deadline = (Get-Date).AddMinutes(15)
+ $new = $null; $newRows = @()
+ do {
+ $pkg = Get-AppxPackage -Name $m.new.identity
+ if ($pkg -and $pkg.Version.ToString() -ceq $m.new.version) {
+ $new = Installed $m.new
+ $newRows = Main-Processes $new.exe
+ if ($newRows.Count -eq 1) { break }
+ }
+ Start-Sleep -Seconds 2
+ } while ((Get-Date) -lt $deadline)
+ if (-not $new -or $newRows.Count -ne 1) { throw 'Native update did not automatically relaunch the new package' }
+ $newProcess = $newRows[0]
+ if ($newProcess.CreationDate -le $oldProcess.CreationDate) { throw 'New process was not created after OLD' }
+ $stale = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($old.package.InstallLocation + '\', [StringComparison]::OrdinalIgnoreCase) })
+ if ($stale.Count) { throw 'Old payload processes remain alive' }
+ $healthy = $false
+ $deadline = (Get-Date).AddMinutes(3)
+ do {
+ $payloadRoot = Join-Path $new.package.InstallLocation 'app\resources\agent-payload'
+ $payloadProcesses = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($payloadRoot + '\', [StringComparison]::OrdinalIgnoreCase) })
+ foreach ($proc in $payloadProcesses) {
+ foreach ($connection in @(Get-NetTCPConnection -State Listen -OwningProcess $proc.ProcessId -ErrorAction SilentlyContinue)) {
+ try {
+ $response = Invoke-WebRequest -UseBasicParsing -Uri "http://127.0.0.1:$($connection.LocalPort)/api/health" -TimeoutSec 2
+ if ($response.StatusCode -eq 200) { $healthy=$true; $response.Content | Set-Content (Join-Path $Proof 'backend-health.json'); break }
+ } catch { }
+ }
+ if ($healthy) { break }
+ }
+ if (-not $healthy) { Start-Sleep -Seconds 2 }
+ } while (-not $healthy -and (Get-Date) -lt $deadline)
+ if (-not $healthy) { throw 'New packaged backend never returned HTTP 200 health' }
+ & $python $verifier verify --home $env:HERMES_HOME --snapshot (Join-Path $Work 'plugins-before.json') --report (Join-Path $Proof 'plugin-preservation.json')
+ if ($LASTEXITCODE -ne 0) { throw 'Plugin preservation failed' }
+ if ((Get-Content -Raw $marker).Trim() -cne $witness) { throw 'User-state witness changed' }
+ @{ ok=$true; oldVersion=$m.old.version; newVersion=$m.new.version; oldPid=$oldProcess.ProcessId; oldBirth=$oldProcess.CreationDate; newPid=$newProcess.ProcessId; newBirth=$newProcess.CreationDate; newPath=$newProcess.ExecutablePath; stamp=$new.stamp; automaticRelaunch=$true } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $Proof 'acceptance.json')
+} finally {
+ if (-not $server.HasExited) { Stop-Process -Id $server.Id -ErrorAction SilentlyContinue }
+ # Disposable runner teardown only, scoped to the package installed by this leg.
+ if ($installed) {
+ $pkg = Get-AppxPackage -Name $m.old.identity
+ if ($pkg) {
+ Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($pkg.InstallLocation + '\', [StringComparison]::OrdinalIgnoreCase) } | ForEach-Object { Stop-Process -Id $_.ProcessId -ErrorAction SilentlyContinue }
+ Remove-AppxPackage -Package $pkg.PackageFullName
+ }
+ }
+}