The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Give release Python sole ownership of App Installer descriptors
ethernet690316c589f0
diff --git a/apps/desktop/scripts/gen-appinstaller.mjs b/apps/desktop/scripts/gen-appinstaller.mjsdeleted file mode 100644index 078d88fbc00..00000000000--- a/apps/desktop/scripts/gen-appinstaller.mjs+++ /dev/null@@ -1,71 +0,0 @@-#!/usr/bin/env node-// gen-appinstaller.mjs — generate the Windows App Installer (.appinstaller)-// file for an out-of-store MSIX channel feed.-//-// The out-of-store distribution is App Installer owned: each stable/canary-// channel dir under the feed host holds a universal .msixbundle plus an-// .appinstaller that (a) installs the bundle and (b) records the .appinstaller-// URI as the package's update source, so the OS can re-check it on launch.-//-// The identity comes from product-identity.cjs via scripts/msix-shared.mjs-// (the SAME single derivation as the package manifest), so the-// .appinstaller's MainBundle Name/Publisher always match the bundle's-// manifest. `store` has no appinstaller (the Store owns its distribution).-//-// Pure buildAppInstaller() lives in scripts/msix-shared.mjs and is-// unit-tested; this module is the CLI wrapper:-// node apps/desktop/scripts/gen-appinstaller.mjs --out <file> --base-url <url>-// Reads HERMES_DESKTOP_VARIANT (bundled|light), HERMES_PAYLOAD_TAG (channel)-// and package.json (version) like the rest of the build.-import fs from 'node:fs'-import path from 'node:path'-import { fileURLToPath, pathToFileURL } from 'node:url'--import { appIdentity, buildAppInstaller } from '../../../scripts/msix-shared.mjs'--const desktop = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')--const isCli = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href--if (isCli) {- // node strips the first '--' (and an immediately-following option) for its- // own use; --out lands as a BARE arg. Parse space-separated flag pairs,- // not --flag=value, so the CLI survives that mangling.- const args = process.argv.slice(2)- const flagValue = (name) => {- for (let i = 0; i < args.length - 1; i += 1) {- if (args[i] === name) return args[i + 1]- }- return undefined- }- const out = flagValue('--out')- const baseUrl = flagValue('--base-url') || process.env.CLOUDFLARE_R2_PUBLIC_URL-- if (!out || !baseUrl) {- console.error('[gen-appinstaller] --out=<file> and --base-url=<url> (or CLOUDFLARE_R2_PUBLIC_URL) are required')- process.exit(1)- }-- const { identity, version, name } = appIdentity(desktop, process.env.HERMES_PAYLOAD_TAG)- if (!identity.channel) {- console.error('[gen-appinstaller] Store and commit builds have no App Installer feed')- process.exit(1)- }-- const canary = /-canary/.test(process.env.HERMES_PAYLOAD_TAG || '')- const variantDir = identity.light ? 'light/' : ''- const ch = canary ? 'canary' : 'stable'- const channelPath = `win32/${variantDir}${ch}`-- const xml = buildAppInstaller({- baseUrl: String(baseUrl).replace(/\/+$/, ''),- variantChannelPath: channelPath,- identityName: identity.msixAppIdWithOrg,- version,- bundleFilename: `${name}-${version}-win.msixbundle`- })-- fs.mkdirSync(path.dirname(out), { recursive: true })- fs.writeFileSync(out, xml)- console.log(`[gen-appinstaller] wrote ${out} (${channelPath}/${name}-${version}-win.msixbundle)`)-}diff --git a/apps/desktop/scripts/gen-appinstaller.test.mjs b/apps/desktop/scripts/gen-appinstaller.test.mjsdeleted file mode 100644index 129e12607c5..00000000000--- a/apps/desktop/scripts/gen-appinstaller.test.mjs+++ /dev/null@@ -1,59 +0,0 @@-// gen-appinstaller — the .appinstaller document for an out-of-store channel.-// The identity inside must match the package manifest (same derivation), and-// the bundle/package URLs must resolve under the feed host.-import assert from 'node:assert/strict'--import { describe, test } from 'vitest'--import { OUT_OF_STORE_PUBLISHER, buildAppInstaller } from '../../../scripts/msix-shared.mjs'--describe('buildAppInstaller', () => {- const base = {- baseUrl: 'https://updates.example.com',- variantChannelPath: 'win32/stable',- identityName: 'NousResearch.HermesBundled',- version: '0.3.0.0',- bundleFilename: 'HermesBundled-0.3.0.0-win.msixbundle'- }-- test('pins the same publisher as the out-of-store manifest (ATS cert subject)', () => {- const xml = buildAppInstaller(base)- assert.match(xml, /Publisher="CN=Nous Research Inc\., O=Nous Research Inc\., L=Austin, S=Texas, C=US"/)- assert.equal(OUT_OF_STORE_PUBLISHER, 'CN=Nous Research Inc., O=Nous Research Inc., L=Austin, S=Texas, C=US')- })-- test('MainBundle points at the package bytes and self URI stays on the published channel descriptor', () => {- const xml = buildAppInstaller(base)- assert.match(xml, /<MainBundle\s/)- assert.doesNotMatch(xml, /<MainPackage\s/)- assert.match(xml, /Uri="https:\/\/updates\.example\.com\/win32\/stable\/HermesBundled-0\.3\.0\.0-win\.msixbundle"/)- const descriptor = /<AppInstaller\s+Uri="([^"]+)"/.exec(xml)[1]- assert.equal(descriptor, `${base.baseUrl}/${base.variantChannelPath}/stable.appinstaller`)- const next = buildAppInstaller({ ...base, version: '0.3.1.0', bundleFilename: 'next.msixbundle' })- assert.equal(/<AppInstaller\s+Uri="([^"]+)"/.exec(next)[1], descriptor)- })-- test('MainBundle Name equals the package identity; version matches everywhere', () => {- const xml = buildAppInstaller(base)- assert.match(xml, /Name="NousResearch\.HermesBundled"/)- const versionCount = (xml.match(/Version="0\.3\.0\.0"/g) || []).length- // AppInstaller Version + MainBundle Version = 2 occurrences.- assert.equal(versionCount, 2)- })-- test('UpdateSettings keeps the OS prompt off (the in-app checker owns the prompt)', () => {- const xml = buildAppInstaller(base)- assert.match(xml, /<OnLaunch HoursBetweenUpdateChecks="12" \/>/)- assert.doesNotMatch(xml, /ShowPrompt=/)- })-- test('a variant channel path with a trailing slash still resolves under the host', () => {- const xml = buildAppInstaller({ ...base, variantChannelPath: 'win32/canary/' })- assert.match(xml, /https:\/\/updates\.example\.com\/win32\/canary\//)- })-- test('reserved XML characters in identity values are escaped', () => {- const xml = buildAppInstaller({ ...base, identityName: 'A&B<App>' })- assert.match(xml, /Name="A&B<App>"/)- })-})diff --git a/apps/desktop/scripts/msix-shared.test.mjs b/apps/desktop/scripts/msix-shared.test.mjsindex fceddc18cf0..5c094cc423c 100644--- a/apps/desktop/scripts/msix-shared.test.mjs+++ b/apps/desktop/scripts/msix-shared.test.mjs@@ -89,16 +89,3 @@ test('legacy 8-digit canary stamp still computes minutes (midnight of that day)'const minutes = msix.canaryBuildMinutesFor('v0.27.2-canary.20260801', base)assert.equal(minutes, 0)})--test('buildAppInstaller pins the derived 4-part version everywhere', () => {- const xml = msix.buildAppInstaller({- baseUrl: 'https://updates.example.com',- variantChannelPath: 'win32/canary',- identityName: 'NousResearch.HermesBundled',- version: '0.27.2.1234',- bundleFilename: 'HermesBundled-0.27.2.1234-win.msixbundle'- })- assert.match(xml, /Uri="https:\/\/updates\.example\.com\/win32\/canary\/HermesBundled-0\.27\.2\.1234-win\.msixbundle"/)- const versionCount = (xml.match(/Version="0\.27\.2\.1234"/g) || []).length- assert.equal(versionCount, 2)-})diff --git a/apps/desktop/scripts/side-by-side.windows.test.mjs b/apps/desktop/scripts/side-by-side.windows.test.mjsindex c4c744c9480..33c557ebd51 100644--- a/apps/desktop/scripts/side-by-side.windows.test.mjs+++ b/apps/desktop/scripts/side-by-side.windows.test.mjs@@ -48,7 +48,7 @@ async function nativeProof() {'apps/desktop/product-identity.cjs', 'apps/desktop/electron-builder.config.cjs','apps/desktop/package.json', 'apps/desktop/update-feed.cjs', 'apps/desktop/update-feed.json','apps/desktop/assets/msix-manifest.xml',- ...['before-build', 'gen-msix-manifest', 'gen-appinstaller', 'mac-sign', 'payload-digests', 'write-build-stamp', 'utils']+ ...['before-build', 'gen-msix-manifest', 'mac-sign', 'payload-digests', 'write-build-stamp', 'utils'].map(name => `apps/desktop/scripts/${name}.mjs`),'scripts/msix-shared.mjs', 'scripts/release-content-types.json', 'scripts/build/python.mjs',]@@ -159,13 +159,24 @@ foreach ($asset in @(@('Square44x44Logo.png',44,44), @('Square150x150Logo.png',1}}const descriptor = path.join(root, `${label}.appinstaller`)- const generated = run(process.execPath, [path.join(desktop, 'scripts/gen-appinstaller.mjs'), '--out', descriptor, '--base-url', 'https://example.invalid/fixture'], { cwd: work, env: childEnv })- if (flavorEnv.HERMES_BUILD_COMMIT) {- check(generated.status !== 0 && !fs.existsSync(descriptor), `${label}: commit build emitted App Installer feed`)- check(facts.config.publish === null, `${label}: commit build config still publishes`)+ if (facts.identity.channel) {+ const publisher = attribute(roundtrip, 'Identity', 'Publisher')+ const selfUri = `https://example.invalid/fixture/${facts.identity.channel}.appinstaller`+ const artifactUri = `https://example.invalid/fixture/${facts.app.name}-${version}-win.msixbundle`+ checked(process.env.HERMES_PYTHON || 'python', [+ '-m', 'scripts.bundles.release_artifacts', 'appinstaller', '--root', root, '--out', descriptor,+ '--identity', name, '--publisher', publisher, '--version', version,+ '--self-uri', selfUri, '--artifact-uri', artifactUri,+ ], { cwd: repo, env: childEnv })+ const feed = fs.readFileSync(descriptor, 'utf8')+ check(attribute(feed, 'MainBundle', 'Name') === name, `${label}: App Installer targets another family`)+ check(attribute(feed, 'MainBundle', 'Publisher') === publisher, `${label}: App Installer changed publisher`)+ check(attribute(feed, 'MainBundle', 'Version') === version, `${label}: App Installer changed version`)+ check(attribute(feed, 'AppInstaller', 'Uri') === selfUri, `${label}: App Installer changed subscription`)+ check(attribute(feed, 'MainBundle', 'Uri') === artifactUri, `${label}: App Installer changed artifact`)} else {- assert.equal(generated.status, 0, generated.output)- check(attribute(fs.readFileSync(descriptor, 'utf8'), 'MainBundle', 'Name') === name, `${label}: App Installer targets another family`)+ check(!fs.existsSync(descriptor), `${label}: commit build emitted App Installer feed`)+ check(facts.config.publish === null, `${label}: commit build config still publishes`)}const row = { label, name, version, aliases, packageDir, cliName: facts.identity.cliName, commit: flavorEnv.HERMES_BUILD_COMMIT || null }rows.push(row)diff --git a/docs/stable-releases.md b/docs/stable-releases.mdindex 5cbd350c4fc..25c5b956f61 100644--- a/docs/stable-releases.md+++ b/docs/stable-releases.md@@ -153,6 +153,16 @@ in JavaScript or PowerShell. These adapters consume release facts rather thanreimplementing the release gate. Gate jobs use only Python's standard library;they do not install the application or the JS workspace to report a verdict.+`scripts.bundles.release_artifacts` owns App Installer XML and feed publication.+Its serializer takes explicit package identity, publisher, version, subscription+URI and artifact URI. Stable promotion uses the accepted candidate metadata;+canary publication verifies the native bundle manifest against the adapter's+expected identity before uploading the bundle, then the descriptor. Native SDK+bundling/signing stays in `stage-msixbundle.mjs`. Store and commit builds stop+before that feed handoff; `stable-store` submits the verified candidate without+rebuilding it. Native acceptance uses the same Python serializer, including its+12-hour on-launch check policy.+Signing and publication credentials stay in their protected job environments.The source CI call does not inherit deployment secrets. Configure the existingrelease-signing and container-publish environments before running this pipeline.diff --git a/scripts/bundles/release_artifacts.py b/scripts/bundles/release_artifacts.pyindex 01588c0960f..7dc580d63d7 100644--- a/scripts/bundles/release_artifacts.py+++ b/scripts/bundles/release_artifacts.py@@ -181,20 +181,59 @@ def publish(manifest: dict, root: Path, public_base: str) -> None:put(tag=manifest["tag"], key=f"releases/termux/stable/{rel}", file=file, key_is_full=True, immutable=True)+def write_appinstaller(out: Path, *, identity: str, publisher: str, version: str,+ self_uri: str, artifact_uri: str) -> None:+ """Serialize verified package facts; callers own channel/acceptance policy."""+ if not all((identity, publisher, version, self_uri, artifact_uri)):+ raise ValueError("Explicit identity, publisher, version, self URI and artifact URI are required")+ ns = "http://schemas.microsoft.com/appx/appinstaller/2017/2"+ ET.register_namespace("", ns)+ descriptor = ET.Element(f"{{{ns}}}AppInstaller", {"Uri": self_uri, "Version": version})+ ET.SubElement(descriptor, f"{{{ns}}}MainBundle", {+ "Name": identity, "Publisher": publisher, "Version": version, "Uri": artifact_uri,+ })+ settings = ET.SubElement(descriptor, f"{{{ns}}}UpdateSettings")+ ET.SubElement(settings, f"{{{ns}}}OnLaunch", {"HoursBetweenUpdateChecks": "12"})+ out.parent.mkdir(parents=True, exist_ok=True)+ ET.ElementTree(descriptor).write(out, encoding="utf-8", xml_declaration=True)+++def publish_canary_appinstaller(root: Path, *, tag: str, variant: str, bundle: Path,+ identity: str, publisher: str, version: str, public_base: str) -> None:+ """Native SDK work is complete; verify its identity before writing a feed."""+ from scripts.releases.r2 import put++ if not re.fullmatch(r"v\d+\.\d+\.\d+-canary\.20\d{6}(?:\d{6})?", tag or ""):+ raise ValueError("Only canary feeds publish directly; stable requires accepted candidates")+ if variant not in ("bundled", "light"):+ raise ValueError("Store and commit builds have no App Installer feed")+ if not public_base:+ raise ValueError("Public feed base URL is required")+ with zipfile.ZipFile(bundle) as archive:+ native = ET.fromstring(archive.read("AppxMetadata/AppxBundleManifest.xml")).find("{*}Identity")+ for attr, expected in (("Name", identity), ("Publisher", publisher), ("Version", version)):+ if native is None or native.get(attr) != expected:+ raise ValueError(f"Universal bundle {attr} does not match its expected identity")+ directory = f"releases/win32/{'light/' if variant == 'light' else ''}canary"+ base = public_base.rstrip("/")+ descriptor = root / "canary.appinstaller"+ write_appinstaller(descriptor, identity=identity, publisher=publisher, version=version,+ self_uri=f"{base}/{directory}/{descriptor.name}",+ artifact_uri=f"{base}/{directory}/{bundle.name}")+ # A failed upload or HEAD verification leaves the previous pointer intact.+ put(tag=tag, key=f"{directory}/{bundle.name}", file=bundle, key_is_full=True, immutable=True)+ put(tag=tag, key=f"{directory}/{descriptor.name}", file=descriptor, key_is_full=True)++def promote(manifest: dict, root: Path, public_base: str) -> None:from scripts.releases.r2 import put, finalizematerialize(manifest, root, public_base=public_base)windows = next(r for r in manifest["packages"] if r["platform"] == "windows")uri = f"{public_base.rstrip('/')}/releases/win32/stable/stable.appinstaller"- ns = "http://schemas.microsoft.com/appx/appinstaller/2017/2"- ET.register_namespace("", ns)- descriptor = ET.Element(f"{{{ns}}}AppInstaller", {"Uri": uri, "Version": windows["version"]})- ET.SubElement(descriptor, f"{{{ns}}}MainBundle", {"Name": windows["identity"], "Publisher": windows["publisher"], "Version": windows["version"], "Uri": windows["artifact"]["url"]})- settings = ET.SubElement(descriptor, f"{{{ns}}}UpdateSettings")- ET.SubElement(settings, f"{{{ns}}}OnLaunch", {"HoursBetweenUpdateChecks": "12"})appinstaller = root / "stable.appinstaller"- ET.ElementTree(descriptor).write(appinstaller, encoding="utf-8", xml_declaration=True)+ write_appinstaller(appinstaller, identity=windows["identity"], publisher=windows["publisher"],+ version=windows["version"], self_uri=uri, artifact_uri=windows["artifact"]["url"])apt = root / "apt"indexes = sorted(p for p in apt.rglob("*") if p.is_file() and not p.relative_to(apt).as_posix().startswith("pool/") and "/by-hash/" not in p.relative_to(apt).as_posix())indexes.sort(key=lambda p: p.name == "InRelease")@@ -218,7 +257,7 @@ def promote(manifest: dict, root: Path, public_base: str) -> None:def main(argv: list[str] | None = None) -> None:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("command", choices=["record", "assemble", "publish", "promote", "materialize"])+ parser.add_argument("command", choices=["record", "assemble", "publish", "promote", "materialize", "appinstaller", "publish-appinstaller"])parser.add_argument("--platform", choices=["windows", "macos", "termux"])parser.add_argument("--arch")parser.add_argument("--root", type=Path, required=True)@@ -227,7 +266,24 @@ def main(argv: list[str] | None = None) -> None:parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA"))parser.add_argument("--public-base", default=os.environ.get("CLOUDFLARE_R2_PUBLIC_URL"))parser.add_argument("--store-only", action="store_true")+ for name in ("identity", "publisher", "version", "self-uri", "artifact-uri"):+ parser.add_argument(f"--{name}")+ parser.add_argument("--variant", choices=["bundled", "light"])+ parser.add_argument("--bundle", type=Path)args = parser.parse_args(argv)+ if args.command == "publish-appinstaller":+ if not args.bundle:+ parser.error("publish-appinstaller requires --bundle")+ publish_canary_appinstaller(args.root, tag=args.tag, variant=args.variant, bundle=args.bundle,+ identity=args.identity, publisher=args.publisher, version=args.version,+ public_base=args.public_base)+ return+ if args.command == "appinstaller":+ if not args.out:+ parser.error("appinstaller requires --out")+ write_appinstaller(args.out, identity=args.identity, publisher=args.publisher,+ version=args.version, self_uri=args.self_uri, artifact_uri=args.artifact_uri)+ returnif args.command == "record":record(args.platform, args.arch, args.root, args.tag, args.commit, args.out)elif args.command == "assemble":diff --git a/scripts/msix-shared.mjs b/scripts/msix-shared.mjsindex 70a31f3da00..bf3baf23e46 100644--- a/scripts/msix-shared.mjs+++ b/scripts/msix-shared.mjs@@ -1,10 +1,5 @@-// msix-shared.mjs — the shared MSIX-distribution building blocks used by-// BOTH the out-of-store feed generator (apps/desktop/scripts/gen-appinstaller.mjs)-// and the release job that stages the feed (scripts/stage-msixbundle.mjs).-//-// The two call sites must agree on every name/URL that Windows keys on — the-// .appinstaller's MainBundle identity and the bundle URI — so the XML-// builder and the version/filename derivations live here, once.+// Native MSIX identity/version derivation and artifact content types.+// App Installer XML and feed publication belong to scripts.bundles.release_artifacts.import fs from 'node:fs'import path from 'node:path'@@ -50,52 +45,6 @@ export function contentTypeFor(filename) {return undefined}-/**- * @param {unknown} value any value to XML-escape- * @returns {string}- */-function escapeAttr(value) {- return String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')-}--/**- * Build an .appinstaller document for a channel.- *- * @param {{- * baseUrl: string // feed host root (no trailing slash)- * variantChannelPath: string // e.g. "win32/", "win32/light/", "win32/canary/"- * identityName: string // package Identity Name (e.g. "NousResearch.HermesBundled")- * version: string // 4-part MSIX version, e.g. "1.2.3.0"- * bundleFilename: string // the universal .msixbundle filename in the feed dir- * descriptorFilename?: string // defaults to the channel's .appinstaller name- * }} o- * @returns {string} the .appinstaller XML- */-export function buildAppInstaller(o) {- const directory = [o.baseUrl.replace(/\/+$/, ''), o.variantChannelPath.replace(/^\/+|\/+$/g, '')].filter(Boolean).join('/')- const bundleUrl = `${directory}/${o.bundleFilename}`- const descriptor = o.descriptorFilename || `${o.variantChannelPath.replace(/\/+$/, '').split('/').pop()}.appinstaller`- const appinstallerUri = `${directory}/${descriptor}`-- return [- '<?xml version="1.0" encoding="utf-8"?>',- '<AppInstaller',- ` Uri="${escapeAttr(appinstallerUri)}"`,- ` Version="${escapeAttr(o.version)}"`,- ' xmlns="http://schemas.microsoft.com/appx/appinstaller/2017/2">',- ' <MainBundle',- ` Name="${escapeAttr(o.identityName)}"`,- ` Publisher="${escapeAttr(OUT_OF_STORE_PUBLISHER)}"`,- ` Version="${escapeAttr(o.version)}"`,- ` Uri="${escapeAttr(bundleUrl)}" />`,- ' <UpdateSettings>',- ' <OnLaunch HoursBetweenUpdateChecks="12" />',- ' </UpdateSettings>',- '</AppInstaller>',- ''- ].join('\n')-}-// The canary tag base + embedded UTC stamp: v0.27.2-canary.20260829034013// (8- or 14-digit; the shorter legacy form is midnight of that day). The// base is the next PATCH over the newest stable, so the first three MSIXdiff --git a/scripts/stage-msixbundle.mjs b/scripts/stage-msixbundle.mjsindex aa1734907e6..9ca82001eb1 100644--- a/scripts/stage-msixbundle.mjs+++ b/scripts/stage-msixbundle.mjs@@ -1,35 +1,17 @@#!/usr/bin/env node-// stage-msixbundle.mjs — the out-of-store MSIX distribution job.-//-// Runs on a Windows runner of the release workflow AFTER all legs built-// (needs: build). Two responsibilities:-//-// 1. OUT-OF-STORE FEED: bundle the x64 + arm64 per-arch .msix into one-// universal .msixbundle, sign the bundle envelope, write the per-channel-// .appinstaller, and upload both to the win32 feed dirs — bundle FIRST,-// .appinstaller pointer LAST (a failed bundle upload leaves the previous-// feed intact):-// releases/win32/<stable|canary>/<name>-<ver>.win.msixbundle-// releases/win32/<stable|canary>/stable.appinstaller (or canary.*)-// The .appinstaller is the install + auto-update entry point; the bundle-// is what the OS installs and swaps on update. Per-arch .msix files stay-// in the immutable releases/tag/<tag>/ archive (uploaded by the legs).-//-// 2. STORE ARCHIVE: re-upload the Store-submission .msix files (built by-// the win legs, prefixed Store-) to the tag archive. The Store is the-// distribution for those — they never touch a feed dir.-//-// Usage (win runner, bash):-// node scripts/stage-msixbundle.mjs --tag vX.Y.Z [--variant bundled|light]-// Reads HERMES_DESKTOP_VARIANT (bundled|light) from the environment; the-// workflow runs this job once per variant.+// Native Windows adapter: bundle x64 + arm64 MSIX packages and sign the+// envelope. Candidate/commit modes stop at the artifact. Canary releases hand+// the completed bundle and expected identity to release Python, which verifies+// the manifest and publishes the bundle before its App Installer pointer.+// Usage: node scripts/stage-msixbundle.mjs --tag vX.Y.Z --candidate+// node scripts/stage-msixbundle.mjs --tag vX.Y.Z-canary.STAMPimport { execFileSync } from 'node:child_process'import fs from 'node:fs'import path from 'node:path'import { fileURLToPath } from 'node:url'import { parseArgs } from 'node:util'-import { appIdentity, buildAppInstaller } from './msix-shared.mjs'+import { appIdentity, OUT_OF_STORE_PUBLISHER } from './msix-shared.mjs'import { ensureWindowsBundleTools } from '../apps/desktop/scripts/windows-bundle-tools.mjs'@@ -94,8 +76,6 @@ if (process.platform !== 'win32') {const canary = /-canary\./.test(tag)if (!commitBuild && !canary && !candidate) throw new Error('Stable bundles must use the staged stable-release workflow')-const channel = canary ? 'canary' : 'stable'-const channelDir = `releases/win32/${variant === 'light' ? 'light/' : ''}${channel}`const desktop = path.join(REPO_ROOT, 'apps', 'desktop')const releaseDir = path.join(desktop, 'release')@@ -193,44 +173,10 @@ if (commitBuild) {process.exit(0)}-// ── 2. .appinstaller + uploads ─────────────────────────────────────────────-const baseUrl = String(process.env.CLOUDFLARE_R2_PUBLIC_URL || '').replace(/\/+$/, '')-if (!baseUrl) {- console.error('[stage-msixbundle] CLOUDFLARE_R2_PUBLIC_URL is required (feed dir URLs come from it)')- process.exit(1)-}--const appinstaller = buildAppInstaller({- baseUrl,- variantChannelPath: channelDir,- identityName: identity.msixAppIdWithOrg,- version,- bundleFilename: `${name}-${version}-win.msixbundle`-})-const appinstallerName = `${channel}.appinstaller`-fs.writeFileSync(path.join(releaseDir, appinstallerName), appinstaller)--const upload = (key, file, keyIsFull = true) => {- // NOTE: no fs.readFileSync here — the msixbundle can exceed Node's 2GiB- // buffer limit (ERR_FS_FILE_TOO_LARGE). scripts.releases.r2 put reads + hashes- // the file itself; log the size via stat instead.- const { size } = fs.statSync(file)- console.log(`[stage-msixbundle] upload ${key} (${size} bytes)`)- // Feed-dir keys are FULL object keys (releases/win32/<ch>/…) — pass- // --key-is-full so r2 put does NOT wrap them under releases/tag/<tag>/.- // scripts.releases.r2 put derives Content-Type from the key extension.- execFileSync(process.env.HERMES_PYTHON || 'python', ['-m', 'scripts.releases.r2', 'put', '--tag', tag, '--key', key, '--file', file, ...(keyIsFull ? ['--key-is-full'] : [])], {- cwd: REPO_ROOT,- stdio: 'inherit'- })-}--// C22 ordering: bundle FIRST, pointer LAST. scripts.releases.r2 PUTs then-// HEAD-verifies the remote content-length — a failed/short upload throws-// and aborts this job before the pointer is written.-upload(`${channelDir}/${name}-${version}-win.msixbundle`, bundle)-upload(`${channelDir}/${appinstallerName}`, path.join(releaseDir, appinstallerName))--// The Store-submission .msix files were already uploaded to the tag archive-// by the win legs (Store- prefix); nothing for this job to re-upload.+// Python owns descriptor serialization, identity verification and publication.+execFileSync(process.env.HERMES_PYTHON || 'python', [+ '-m', 'scripts.bundles.release_artifacts', 'publish-appinstaller',+ '--root', releaseDir, '--bundle', bundle, '--tag', tag, '--variant', variant,+ '--identity', identity.msixAppIdWithOrg, '--publisher', OUT_OF_STORE_PUBLISHER, '--version', version,+], { cwd: REPO_ROOT, stdio: 'inherit' })console.log('[stage-msixbundle] done — feed manifests + bundle staged')diff --git a/tests/install/e2e-assets/windows-bundled-helpers.mjs b/tests/install/e2e-assets/windows-bundled-helpers.mjsindex 0ada4665cb5..ef19feacc4f 100644--- a/tests/install/e2e-assets/windows-bundled-helpers.mjs+++ b/tests/install/e2e-assets/windows-bundled-helpers.mjs@@ -1,22 +1,17 @@-// 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.+// Windows packaged-app acceptance helpers. Release Python owns descriptor XML;+// msix-shared supplies the expected publisher and content types. --msix-shared+// selects the checkout whose release module and native facts are under test.//// 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>+// --identity <name> --publisher <subject> --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 { execFileSync } from 'node:child_process'import path from 'node:path'import http from 'node:http'import { pathToFileURL, fileURLToPath } from 'node:url'@@ -158,24 +153,6 @@ export function feedLayout(feedDir, manifest) {}}-/**- * 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)@@ -214,34 +191,15 @@ async function main() {}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)+ const base = flags['base-url'].replace(/\/+$/, '')+ execFileSync(process.env.HERMES_PYTHON || 'python', [+ '-m', 'scripts.bundles.release_artifacts', 'appinstaller', '--root', feed, '--out', outPath,+ '--identity', flags.identity, '--publisher', flags.publisher, '--version', flags.version,+ '--self-uri', `${base}/${flags['descriptor-filename'] || 'update.appinstaller'}`,+ '--artifact-uri', `${base}/${flags.bundle}`,+ ], { cwd: path.resolve(path.dirname(msixShared), '..'), stdio: 'inherit' })console.log(JSON.stringify({ ok: true, path: outPath }))return}diff --git a/tests/install/e2e-assets/windows-bundled-helpers.test.mjs b/tests/install/e2e-assets/windows-bundled-helpers.test.mjsindex d03e51ec067..a062cb229a7 100644--- a/tests/install/e2e-assets/windows-bundled-helpers.test.mjs+++ b/tests/install/e2e-assets/windows-bundled-helpers.test.mjs@@ -1,17 +1,17 @@// 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).+// Windows packaged-app E2E arm. Pure manifest validation plus real descriptor+// CLI calls through the release Python module; no Windows installation needed.//// node --test tests/install/e2e-assets/windows-bundled-helpers.test.mjsimport { test } from 'node:test'+import { execFileSync } from 'node:child_process'+import { fileURLToPath } from 'node:url'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'+import { validateBundledManifest, fourPartNewer, feedLayout } 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'@@ -132,10 +132,21 @@ test('feedLayout stages per-side bundles and one swapped descriptor, rejecting cassert.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')+test('native acceptance descriptor CLI uses explicit publisher and a stable subscription across upgrades', () => {+ const feed = fs.mkdtempSync(path.join(os.tmpdir(), 'wbh-descriptor-'))+ try {+ for (const version of ['1.2.3.0', '1.2.4.31']) {+ execFileSync(process.execPath, [fileURLToPath(new URL('./windows-bundled-helpers.mjs', import.meta.url)),+ 'descriptor', '--feed', feed, '--base-url', 'http://127.0.0.1:9',+ '--identity', 'Fixture.App', '--publisher', 'CN=Fixture & "Team"',+ '--version', version, '--bundle', `${version}.msixbundle`, '--descriptor-filename', 'update.appinstaller',+ ])+ const xml = fs.readFileSync(path.join(feed, 'update.appinstaller'), 'utf8')+ assert.match(xml, /Publisher="CN=Fixture & "Team""/)+ assert.match(xml, /Uri="http:\/\/127.0.0.1:9\/update.appinstaller"/)+ assert.ok(xml.includes(`Uri="http://127.0.0.1:9/${version}.msixbundle"`))+ assert.equal((xml.match(new RegExp(`Version="${version.replaceAll('.', '\\.')}"`, 'g')) || []).length, 2)+ assert.match(xml, /HoursBetweenUpdateChecks="12"/)+ }+ } finally { fs.rmSync(feed, { recursive: true, force: true }) }})diff --git a/tests/install/windows-bundled-e2e.ps1 b/tests/install/windows-bundled-e2e.ps1index b2bde460ccc..718bda39d9c 100644--- a/tests/install/windows-bundled-e2e.ps1+++ b/tests/install/windows-bundled-e2e.ps1@@ -79,7 +79,7 @@ try {}$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')+ Run-Node @($Helper, 'descriptor', '--feed', $Feed, '--base-url', $baseUrl, '--identity', $Side.identity, '--publisher', $Side.publisher, '--version', $Side.version, '--bundle', $File, '--descriptor-filename', 'update.appinstaller')}Descriptor $m.old 'old.msixbundle'$descriptor = Join-Path $Feed 'update.appinstaller'diff --git a/tests/scripts/test_appinstaller.py b/tests/scripts/test_appinstaller.pynew file mode 100644index 00000000000..d4724fc8706--- /dev/null+++ b/tests/scripts/test_appinstaller.py@@ -0,0 +1,80 @@+"""App Installer descriptors bind explicit package facts to explicit feed URLs."""+import subprocess+import sys+import xml.etree.ElementTree as ET+from pathlib import Path++import pytest++from scripts.bundles import release_artifacts as artifacts+from tests.scripts.test_release_r2 import r2_server # noqa: F401++[email protected]('variant', ['bundled', 'light'])+def test_canary_publication_verifies_native_identity_and_uploads_bundle_before_pointer(tmp_path, r2_server, variant):+ import zipfile++ tag, version = 'v1.2.4-canary.20260902000000', '1.2.4.1440'+ identity, publisher = f'Fixture.{variant}.Canary', 'CN=Fixture & Team'+ bundle = tmp_path / 'app.msixbundle'+ manifest = ET.Element('Bundle')+ ET.SubElement(manifest, 'Identity', {'Name': identity, 'Publisher': publisher, 'Version': version})+ with zipfile.ZipFile(bundle, 'w') as archive:+ archive.writestr('AppxMetadata/AppxBundleManifest.xml', ET.tostring(manifest))+ base = 'https://releases.example'+ directory = f"releases/win32/{'light/' if variant == 'light' else ''}canary"+ pointer = f'{directory}/canary.appinstaller'+ args = ['publish-appinstaller', '--root', str(tmp_path), '--tag', tag, '--variant', variant,+ '--bundle', str(bundle), '--identity', identity, '--publisher', publisher, '--version', version,+ '--public-base', base]+ artifacts.main(args)+ assert r2_server.store[f'{directory}/{bundle.name}'][0] == bundle.read_bytes()+ descriptor = ET.fromstring(r2_server.store[pointer][0])+ assert descriptor.attrib == {'Uri': f'{base}/{pointer}', 'Version': version}+ assert descriptor.find('{*}MainBundle').attrib == {+ 'Name': identity, 'Publisher': publisher, 'Version': version, 'Uri': f'{base}/{directory}/{bundle.name}',+ }+ requests = [(method, path.rsplit('/', 1)[-1]) for method, path, _ in r2_server.requests]+ assert requests.index(('HEAD', bundle.name)) < requests.index(('PUT', 'canary.appinstaller'))+ previous = r2_server.store[pointer]+ for option, bad in [('--identity', 'Wrong'), ('--publisher', 'CN=Wrong'), ('--version', '9.9.9.0'),+ ('--tag', 'v1.2.4'), ('--tag', 'a' * 40), ('--variant', 'store')]:+ invalid = list(args)+ invalid[invalid.index(option) + 1] = bad+ r2_server.requests.clear()+ with pytest.raises((ValueError, SystemExit)):+ artifacts.main(invalid)+ assert not r2_server.requests+ assert r2_server.store[pointer] == previous++ # Fail a real immutable upload by occupying its name with different bytes.+ r2_server.store[f'{directory}/{bundle.name}'] = (b'other bundle', 'application/msixbundle')+ r2_server.requests.clear()+ with pytest.raises(ValueError, match='checksum mismatch'):+ artifacts.main(args)+ assert not any(method == 'PUT' and path.endswith('canary.appinstaller')+ for method, path, _ in r2_server.requests)+ assert r2_server.store[pointer] == previous++[email protected]('channel', ['stable', 'canary', 'light/stable', 'light/canary'])+def test_descriptor_cli_preserves_package_facts_and_subscription_uri(tmp_path, channel):+ identity, publisher = 'Product&<"test">', 'CN=Publisher & "Team"'+ self_uri = f'https://releases.example/releases/win32/{channel}/update.appinstaller?a=1&b=2'+ out = tmp_path / 'descriptor.appinstaller'+ for version in ['1.2.3.0', '1.2.4.31']:+ artifact_uri = f'https://releases.example/releases/tag/v{version}/app.msixbundle?a=1&b=2'+ subprocess.run([+ sys.executable, '-m', 'scripts.bundles.release_artifacts', 'appinstaller',+ '--root', str(tmp_path), '--out', str(out), '--identity', identity,+ '--publisher', publisher, '--version', version,+ '--self-uri', self_uri, '--artifact-uri', artifact_uri,+ ], cwd=Path(__file__).resolve().parents[2], check=True)+ descriptor = ET.parse(out).getroot()+ assert descriptor.tag == '{http://schemas.microsoft.com/appx/appinstaller/2017/2}AppInstaller'+ assert descriptor.attrib == {'Uri': self_uri, 'Version': version}+ assert descriptor.find('{*}MainBundle').attrib == {+ 'Name': identity, 'Publisher': publisher, 'Version': version, 'Uri': artifact_uri,+ }+ assert descriptor.find('{*}UpdateSettings/{*}OnLaunch').attrib == {'HoursBetweenUpdateChecks': '12'}+ assert descriptor.find('{*}MainPackage') is Nonediff --git a/tests/scripts/test_release_promotion.py b/tests/scripts/test_release_promotion.pyindex 8d51688c05a..38005c50ddd 100644--- a/tests/scripts/test_release_promotion.py+++ b/tests/scripts/test_release_promotion.py@@ -2,6 +2,7 @@import hashlibimport ioimport json+import xml.etree.ElementTree as ETfrom pathlib import Pathimport pytest@@ -57,7 +58,13 @@ def test_publish_and_promote_use_the_same_content_before_any_channel_write(tmp_passert events[0] == 'mac-feed'assert events[-1] == 'releases/termux/stable/dists/hermes-stable/InRelease'assert 'releases/win32/stable/stable.appinstaller' in r2_server.store- assert b'/releases/tag/v1.2.3/app.msixbundle' in r2_server.store['releases/win32/stable/stable.appinstaller'][0]+ descriptor = ET.fromstring(r2_server.store['releases/win32/stable/stable.appinstaller'][0])+ windows = next(row for row in packages if row['platform'] == 'windows')+ assert descriptor.attrib == {'Uri': f'{base}/releases/win32/stable/stable.appinstaller', 'Version': windows['version']}+ assert descriptor.find('{*}MainBundle').attrib == {+ 'Name': windows['identity'], 'Publisher': windows['publisher'],+ 'Version': windows['version'], 'Uri': windows['artifact']['url'],+ }events.clear()content['app.msixbundle'] = b'changed artifact'