Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
feat(release): add macOS Intel and Linux ARM64 build candidates (#50)
澄潭52700e912dd2
diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.ymlnew file mode 100644index 00000000..abe69c93--- /dev/null+++ b/.github/workflows/build-release.yml@@ -0,0 +1,89 @@+name: build-release-candidates++on:+ workflow_dispatch:++permissions:+ contents: read++jobs:+ build:+ strategy:+ fail-fast: false+ matrix:+ include:+ - target: aarch64-apple-darwin+ runner: macos-15+ - target: x86_64-apple-darwin+ runner: macos-15-intel+ - target: x86_64-unknown-linux-gnu+ runner: ubuntu-22.04+ - target: aarch64-unknown-linux-gnu+ runner: ubuntu-22.04-arm+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 120+ env:+ CARGO_NET_GIT_FETCH_WITH_CLI: 'true'+ CARGO_INCREMENTAL: '0'+ RUSTC_WRAPPER: sccache+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - name: Linux build prerequisites+ if: runner.os == 'Linux'+ run: sudo apt-get update && sudo apt-get install --yes cmake clang pkg-config libssl-dev binutils+ - name: Mac build prerequisites+ if: runner.os == 'macOS'+ run: command -v cmake >/dev/null || brew install cmake+ - uses: actions/setup-python@v5+ with:+ python-version: '3.12'+ - uses: actions/setup-node@v4+ with:+ node-version: '22'+ - uses: mozilla-actions/[email protected]+ - name: Prepare pinned CPA source+ run: |+ repository=$(python3 -c 'import json; print(json.load(open("vendor/cpa/source.json"))["repository"])')+ revision=$(python3 -c 'import json; print(json.load(open("vendor/cpa/source.json"))["commit"])')+ git init "$RUNNER_TEMP/cpa"+ git -C "$RUNNER_TEMP/cpa" fetch --depth=1 "$repository" "$revision"+ git -C "$RUNNER_TEMP/cpa" checkout --detach FETCH_HEAD+ - uses: actions/setup-go@v5+ with:+ go-version-file: ${{ runner.temp }}/cpa/go.mod+ cache: false+ - name: Repository Rust toolchain+ env:+ RELEASE_TARGET: ${{ matrix.target }}+ run: rustup show active-toolchain && rustup target add "$RELEASE_TARGET"+ - uses: actions/cache@v4+ with:+ path: |+ ~/.cargo/registry+ ~/.cargo/git+ key: release-sources-${{ matrix.target }}-${{ hashFiles('Cargo.lock') }}+ - name: Build and verify the exact candidate+ env:+ RELEASE_TARGET: ${{ matrix.target }}+ run: |+ python3 scripts/ci-run.py --name release-candidate --expected-sha "$GITHUB_SHA" \+ --timeout 6600 --plan release-platforms --phase final -- \+ python3 scripts/build-release.py --target "$RELEASE_TARGET" \+ --cpa-source-repo "$RUNNER_TEMP/cpa"+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: release-${{ matrix.target }}-${{ github.sha }}-${{ github.run_attempt }}+ path: |+ target/release-candidate/**/assets/*+ target/release-candidate/**/result.json+ target/release-candidate/**/build.log+ target/release-candidate/**/*.provenance.json+ target/desktop-package/**/result.json+ target/desktop-package/**/build.log+ artifacts/ci+ if-no-files-found: error+ retention-days: 14diff --git a/.github/workflows/website.yml b/.github/workflows/website.ymlindex a466c6cc..0e0eea39 100644--- a/.github/workflows/website.yml+++ b/.github/workflows/website.yml@@ -8,6 +8,10 @@ on:- 'experiments/**'- 'decision-extensions/**'- 'scripts/collect-third-party-licenses.py'+ - 'scripts/build-cpa.py'+ - 'scripts/build-release.py'+ - 'scripts/test-build-release.py'+ - '.github/workflows/build-release.yml'- 'scripts/install-standalone.py'- 'scripts/package-desktop.py'- 'scripts/package-standalone.py'@@ -26,6 +30,10 @@ on:- 'experiments/**'- 'decision-extensions/**'- 'scripts/collect-third-party-licenses.py'+ - 'scripts/build-cpa.py'+ - 'scripts/build-release.py'+ - 'scripts/test-build-release.py'+ - '.github/workflows/build-release.yml'- 'scripts/install-standalone.py'- 'scripts/package-desktop.py'- 'scripts/package-standalone.py'@@ -73,6 +81,7 @@ jobs:run: |python3 scripts/test-third-party-licenses.pypython3 scripts/test-build-cpa.py+ python3 scripts/test-build-release.pypython3 scripts/test-package-desktop.pypython3 scripts/test-standalone-install.py- uses: actions/upload-artifact@v4diff --git a/apps/website/tests/install-script.test.mjs b/apps/website/tests/install-script.test.mjsindex d3429113..2742802a 100644--- a/apps/website/tests/install-script.test.mjs+++ b/apps/website/tests/install-script.test.mjs@@ -27,13 +27,15 @@ const manifest = { schema: 'hiroute.website.releases/v2', releases: [{notes: { zh: '版本。', en: 'Release.' }, artifacts: [standalone, armStandalone],}] };-test('generated installer selects the immutable stable manifest and does not start services', () => {+for (const [machine, expected] of [['x86_64', standalone], ['aarch64', armStandalone], ['arm64', armStandalone]]) {+test(`generated installer selects the ${machine} stable manifest without starting services`, t => {const script = generateLinuxInstallScript(manifest);const root = fs.mkdtempSync(path.join(os.tmpdir(), 'hiroute-install-script-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));const bin = path.join(root, 'bin');fs.mkdirSync(bin);const log = path.join(root, 'calls.log');- fs.writeFileSync(path.join(bin, 'uname'), '#!/bin/sh\n[ "${1:-}" = "-s" ] && echo Linux || echo x86_64\n', { mode: 0o755 });+ fs.writeFileSync(path.join(bin, 'uname'), `#!/bin/sh\n[ "\${1:-}" = "-s" ] && echo Linux || echo ${machine}\n`, { mode: 0o755 });fs.writeFileSync(path.join(bin, 'curl'), '#!/bin/sh\nprintf "curl %s\\n" "$*" >> "$INSTALL_TEST_LOG"\nwhile [ "$#" -gt 0 ]; do [ "$1" = "-o" ] && { shift; printf "# fixture\\n" > "$1"; exit 0; }; shift; done\nexit 1\n', { mode: 0o755 });fs.writeFileSync(path.join(bin, 'python3'), '#!/bin/sh\nprintf "python3 %s\\n" "$*" >> "$INSTALL_TEST_LOG"\n', { mode: 0o755 });const result = spawnSync('/bin/sh', [], {@@ -44,11 +46,12 @@ test('generated installer selects the immutable stable manifest and does not staassert.equal(result.status, 0, result.stderr);const calls = fs.readFileSync(log, 'utf8');assert.match(calls, /curl .*https:\/\/hiroute\.ai\/install\/standalone\.py/);- assert.ok(calls.includes(`install --manifest-url https://hiroute.ai/releases/1.2.3/${standalone.manifest_filename}`));+ assert.ok(calls.includes(`install --manifest-url https://hiroute.ai/releases/1.2.3/${expected.manifest_filename}`));assert.ok(script.includes(`https://hiroute.ai/releases/1.2.3/${armStandalone.manifest_filename}`));assert.doesNotMatch(calls, /service start/);assert.match(result.stdout, /No service was started automatically/);});+}test('generated installer fails closed when no stable package exists for the host', () => {const script = generateLinuxInstallScript({ schema: manifest.schema, releases: [] });diff --git a/apps/website/tests/releases.test.mjs b/apps/website/tests/releases.test.mjsindex 26ac49db..6e7c29d7 100644--- a/apps/website/tests/releases.test.mjs+++ b/apps/website/tests/releases.test.mjs@@ -60,6 +60,21 @@ test('standalone artifacts publish an archive and companion package manifest', ([standalone.filename, standalone.manifest_filename]);});+test('one release accepts both Mac architectures and both Linux architectures', () => {+ const intel = { ...artifact, architecture: 'x86_64', filename: artifact.filename.replace('arm64', 'x86_64') };+ const arm = { ...standalone, architecture: 'aarch64', target: 'aarch64-unknown-linux-gnu',+ filename: standalone.filename.replace('x86_64', 'aarch64'),+ manifest_filename: standalone.manifest_filename.replace('x86_64', 'aarch64') };+ const value = structuredClone(manifest);+ value.releases[0].artifacts = [artifact, intel, standalone, arm];+ assert.equal(validateReleaseManifest(value), value);+ assert.equal(value.releases[0].artifacts.flatMap(a => artifactAssets(value.releases[0], a)).length, 6);+ const identity = { version: release.version, revision, architecture: 'x86_64',+ distribution: 'controlled-trial', dmg_sha256: intel.sha256,+ integrity: 'green', mounted_components: 'green', detach: 'green' };+ assert.equal(verifyDesktopIdentity(value.releases[0], intel, identity, revision), identity);+});+test('public release manifest rejects mismatched distribution, duplicate and unsafe artifacts', () => {const copy = value => structuredClone(value);for (const mutate of [diff --git a/docs/code-map/README.md b/docs/code-map/README.mdindex 1efd6370..855cb47c 100644--- a/docs/code-map/README.md+++ b/docs/code-map/README.md@@ -28,6 +28,7 @@ results in the relevant run record.| Delegate, read, cancel or continue a Worker task | [Worker lifecycle and native differences](worker-context.md#follow-a-task-through-its-owners) | [Delegation](../../tools/product-e2e/tests/worker_delegation.rs), [read/Continue](../../tools/product-e2e/tests/worker_read.rs) || Inspect sessions, content, cost and competence | [Observation owners](architecture.md#observation-and-conversation-boundaries), [decision attribution](decision-foundation.md#observation-and-public-consumers) | [Session queries](../../crates/observation/src/query_v2/sessions_tests.rs), [stage summaries](../../crates/observation/src/store/tests/plan_quality/summary.rs) || Manage the service through CLI or Desktop | [client-core](../../crates/client-core/src), [CLI](../../crates/cli/src), [Desktop host](../../apps/desktop/src-tauri/src), [daemon control](../../crates/daemon/src/control) | [Real control process](../../tools/product-e2e/tests/control_shell.rs), [Desktop test map](../../apps/desktop/tests/README.md) |+| Build macOS / Linux release installers for either architecture | [Release candidate entry](../../scripts/build-release.py), [build and publication guide](../release-builds.md) | [Package-to-publication contract](../../scripts/test-build-release.py); final publishing remains in [release.yml](../../.github/workflows/release.yml) |## Read across boundariesdiff --git a/docs/github-actions-validation.md b/docs/github-actions-validation.mdindex 869191c6..1713dfa4 100644--- a/docs/github-actions-validation.md+++ b/docs/github-actions-validation.md@@ -10,6 +10,7 @@ GitHub Actions runs on the checked-out commit through `scripts/ci-run.py`.| `p0-gateway-gates.yml` | Manual, reusable | Linux listener build, neutral loopback, H1/H2 lifecycle, replay/privacy tests, contract checks, benchmark harness smoke || `gateway-core-dedicated.yml` | Manual or reusable | Hosted Linux production stability and socket churn || `p0-gateway-final-gates.yml` | Manual | Aggregate the three current hosted workflows |+| `build-release.yml` | Manual, exact dispatch SHA | Native macOS ARM64/Intel DMGs and Linux x86_64/ARM64 archives; uploads candidate assets and integrity evidence for the existing release publisher |Normal Rust checks select the organization `Default` runner group with the`cncf-ubuntu-16-64-x86` label. The organization must permit this public repository@@ -78,7 +79,9 @@ maintainer validation; hosted benchmark smoke is not fixed-machine performance eThe hosted Rust checks exclude `hiroute-desktop`. Frontend build/tests do notprove native Tauri interaction. macOS Desktop remains on the existing local-validation path; these workflows provide no Windows or ARM validation evidence.+validation path. The separate [release candidate workflow](release-builds.md)+builds native macOS and Linux packages on both architectures; it does not change+the backend test matrix. Windows is outside that release matrix.Real-provider credentials and separately provisioned production E2E fixtures arenot supplied by this CI setup. Existing failing checks remain failures, notexpected-red success or waived gates.diff --git a/docs/release-builds.md b/docs/release-builds.mdnew file mode 100644index 00000000..219220ce--- /dev/null+++ b/docs/release-builds.md@@ -0,0 +1,68 @@+# Release candidate builds++The release scope is two macOS Desktop DMGs (`arm64`, `x86_64`) and two Linux+headless archives (`x86_64`, `aarch64`). Windows and Linux Desktop are outside this+build entry. All components of one release must come from the same clean,+committed source revision, with CPA built from `vendor/cpa/source.json` and its+checked patch.++The candidate builder must reject a host/target mismatch, dirty source, external+Cargo targets, inconsistent component versions and wrong-architecture binaries.+It must retain a separate output directory for every attempt, use checkout-local+`target/` and the existing shared build lock, and preserve logs on failure.+The existing website release manifest remains the sole publication catalog;+candidate metadata is input for review, never an automatically published release.++## Build locally++Use the intended native platform with the repository Rust toolchain, Node 22++(Desktop and packaging regression checks), Go matching the pinned CPA source,+sccache and native build tools (including `readelf` on Linux).+The CPA checkout must contain the commit in `vendor/cpa/source.json`; its current+branch does not select the source. Invoke from the clean candidate checkout:++```sh+python3 scripts/build-release.py \+ --target x86_64-apple-darwin --cpa-source-repo /path/to/CLIProxyAPI++python3 scripts/build-release.py \+ --target aarch64-unknown-linux-gnu --cpa-source-repo /path/to/CLIProxyAPI+```++The same entry accepts `aarch64-apple-darwin` and `x86_64-unknown-linux-gnu`.+macOS candidates keep the existing macOS 15 minimum and self-signed trial+distribution. Developer ID signing and cross-building on a Mac remain available+through [package-desktop.py](../scripts/package-desktop.py) as documented in the+[macOS installation guide](macos-installation.md); the matrix entry uses native+hosts so its probes execute on the selected architecture.++Each attempt is retained under `target/release-candidate/SHA/TARGET/ROUND/`.+`assets/` contains the DMG or archive plus companion manifest; `result.json`+records the full source revision, host, checks, timing, and the measured+`website_artifact` row. `build.log` retains subprocess output. No installer is+uploaded, no user installation is changed, and no product service is started.++## Hosted build and publication++Run the **build-release-candidates** workflow on the public candidate branch.+Every matrix job checks out the dispatch's exact `github.sha`, uses a native+runner and uploads its own assets and evidence. Linux uses Ubuntu 22.04 to avoid+implicitly raising the distribution's glibc baseline to a newer runner image.+The Linux result records ELF dependencies and symbol versions for checking the+deployment image's library requirements.++1. Require all four matrix jobs to succeed for the same SHA. Keep the exact source+ commit available; internal master and an exported public commit may differ.+2. Download each job's `assets/` and `result.json`. Use the measured+ `website_artifact` rows in a new release record in+ `apps/website/data/releases.json`, with the intended version/channel/date/notes.+ Preserve historical records and regenerate website content twice, checking+ that the second run introduces no difference.+3. Merge the reviewed website manifest into public `main`, tag the exact built+ source SHA, and attach the exact candidate assets to that GitHub Release.+ The existing [publish-release workflow](../.github/workflows/release.yml)+ verifies tag/package identity and digests, then publishes OSS/site links and+ proposes the [release contract snapshot](release-contracts.md).++The build workflow only stores Actions artifacts. It does not publish a GitHub+Release, alter the stable catalog, or replace any immutable distribution object.diff --git a/docs/release-contracts.md b/docs/release-contracts.mdindex 6e6f4774..780f15f1 100644--- a/docs/release-contracts.md+++ b/docs/release-contracts.md@@ -38,6 +38,10 @@ published 0.1.0 records remain immutable historical facts, while 0.2.0 is the fi## Publication and retry+Prepare the macOS ARM64/Intel and Linux x86_64/ARM64 assets with the+[release candidate builder](release-builds.md). It supplies measured website+artifact rows; this workflow consumes the reviewed catalog and published bytes.+[Release workflow](../.github/workflows/release.yml) verifies the published assets andpackage identities, then publishes the installers/site. Only after those jobs succeed does`record-contracts` call [the PR publisher](../.github/scripts/release-contract-pr.sh).diff --git a/scripts/build-cpa.py b/scripts/build-cpa.pyindex fab2170a..36adc824 100644--- a/scripts/build-cpa.py+++ b/scripts/build-cpa.py@@ -13,6 +13,7 @@ REPO = Path(__file__).resolve().parent.parentPIN = REPO / "vendor/cpa/source.json"TARGETS = {"x86_64-unknown-linux-gnu": ("linux", "amd64"),+ "aarch64-unknown-linux-gnu": ("linux", "arm64"),"aarch64-apple-darwin": ("darwin", "arm64"),"x86_64-apple-darwin": ("darwin", "amd64"),}diff --git a/scripts/build-release.py b/scripts/build-release.pynew file mode 100644index 00000000..fa5a6f7c--- /dev/null+++ b/scripts/build-release.py@@ -0,0 +1,190 @@+#!/usr/bin/env python3+"""Build one native release candidate; never publish or modify an installation."""+import argparse+from datetime import datetime, timezone+import importlib.util+import json+import os+from pathlib import Path+import platform+import re+import shutil+import struct+import subprocess+import sys+import tempfile+import time++sys.dont_write_bytecode = True+REPO = Path(__file__).resolve().parent.parent+TARGETS = (+ "aarch64-apple-darwin", "x86_64-apple-darwin",+ "x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu",+)+++def module(name):+ spec = importlib.util.spec_from_file_location(name.replace("-", "_"), REPO / "scripts" / f"{name}.py")+ value = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(value)+ return value+++def host_target():+ arch = {"arm64": "aarch64", "AMD64": "x86_64"}.get(platform.machine(), platform.machine())+ suffix = {"Darwin": "apple-darwin", "Linux": "unknown-linux-gnu"}.get(platform.system())+ return f"{arch}-{suffix}"+++def inspect_elf(path, target):+ with path.open("rb") as stream:+ header = stream.read(20)+ machine = {"x86_64-unknown-linux-gnu": 62, "aarch64-unknown-linux-gnu": 183}[target]+ if (len(header) != 20 or header[:6] != b"\x7fELF\x02\x01"+ or struct.unpack_from("<H", header, 18)[0] != machine):+ raise ValueError(f"binary architecture differs from {target}: {path.name}")+++class Candidate:+ def __init__(self, target, source_repo):+ self.target = target+ self.source_repo = source_repo.resolve(strict=True)+ self.revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=REPO, text=True).strip()+ parent = REPO / "target/release-candidate" / self.revision / target+ parent.mkdir(parents=True, exist_ok=True)+ self.output = Path(tempfile.mkdtemp(prefix=datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ-"), dir=parent))+ self.result = {"revision": self.revision, "target": target,+ "host": {"system": platform.system(), "architecture": platform.machine(),+ "libc": platform.libc_ver()},+ "status": "failed", "timings": []}+ self.environment = dict(os.environ, RUSTC_WRAPPER="sccache", CARGO_INCREMENTAL="0",+ HIROUTE_BUILD_SOURCE_SHA=self.revision)++ def run(self, *arguments, env=None, timeout=None):+ started = time.monotonic()+ print(f"Running {Path(str(arguments[0])).name} {' '.join(map(str, arguments[1:3]))}", file=sys.stderr, flush=True)+ result = subprocess.run(list(map(str, arguments)), cwd=REPO, env=env or self.environment,+ text=True, capture_output=True, timeout=timeout)+ self.result["timings"].append({"command": list(map(str, arguments[:3])),+ "seconds": round(time.monotonic() - started, 3),+ "exit_code": result.returncode})+ with (self.output / "build.log").open("a") as log:+ log.write(f"$ {' '.join(map(str, arguments))}\n{result.stdout}{result.stderr}\n")+ result.check_returncode()+ return result.stdout.strip()++ def script(self, name, *args):+ return self.run(sys.executable, REPO / "scripts" / f"{name}.py", *args)++ def preflight(self):+ if self.target not in TARGETS or host_target() != self.target:+ raise ValueError(f"native host required for {self.target}; host is {host_target()}")+ if self.run("git", "status", "--porcelain", "--untracked-files=normal"):+ raise ValueError("build requires a clean committed candidate")+ if any(key in os.environ for key in ("CARGO_TARGET_DIR", "CARGO_BUILD_TARGET_DIR")):+ raise ValueError("external Cargo targets are forbidden")+ self.version = json.loads((REPO / "apps/desktop/src-tauri/tauri.conf.json").read_text())["version"]+ module("package-desktop").validate_release_versions(self.version)+ metadata = json.loads(self.run("cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"))+ if Path(metadata["target_directory"]).resolve() != REPO / "target":+ raise ValueError("Cargo config must use checkout-local target/")+ self.result["version"] = self.version+ self.result["toolchain"] = {name: self.run(name, "--version") for name in ("cargo", "rustc")}++ def desktop(self):+ arch = "arm64" if self.target.startswith("aarch64-") else "x86_64"+ result = json.loads(self.script("package-desktop", "build", "--arch", arch,+ "--cpa-source-repo", self.source_repo))+ if (result["revision"] != self.revision or result["version"] != self.version+ or result["architecture"] != arch or result["distribution"] != "controlled-trial"):+ raise ValueError("desktop package differs from candidate identity")+ self.result["desktop_result"] = result+ dmg = Path(result["dmg"])+ artifact = {"kind": "desktop", "platform": "macOS", "architecture": arch,+ "format": "dmg", "minimum_os": module("package-desktop").MINIMUM_MACOS,+ "distribution": "self-signed", "filename": dmg.name,+ "sha256": module("package-desktop").digest(dmg), "size": dmg.stat().st_size}+ if artifact["sha256"] != result["dmg_sha256"]:+ raise ValueError("desktop DMG changed after verification")+ return artifact, [dmg]++ def standalone(self):+ cpa = self.output / "cliproxyapi"+ provenance = json.loads(self.script("build-cpa", "--source-repo", self.source_repo,+ "--target", self.target, "--output", cpa))+ pin = module("build-cpa").pinned_source()[0]+ # The helper version probe has no service side effects and no user config.+ with tempfile.TemporaryDirectory(prefix="hiroute-release-probe-") as directory:+ probe = self.run(cpa, "--help", env={"HOME": directory, "PATH": "/usr/bin:/bin",+ "TMPDIR": directory}, timeout=60)+ match = re.search(r"CLIProxyAPI Version: ([^,]+), Commit: ([0-9a-f]{7,40}), BuiltAt: ([^\r\n]+)", probe)+ if not match or match[1] != pin["version"] or not pin["commit"].startswith(match[2]) or match[3] != pin["built_at"]:+ raise ValueError("CPA release version/commit/build date mismatch")+ self.run("cargo", "build", "--locked", "--release", "--target", self.target,+ "-p", "hiroute-cli", "-p", "hiroute-daemon", "--bin", "hiroute", "--bin", "hirouted")+ binaries = REPO / "target" / self.target / "release"+ for binary in (binaries / "hiroute", binaries / "hirouted", cpa):+ inspect_elf(binary, self.target)+ self.result["linux_dependencies"] = {+ name: self.run("readelf", "--dynamic", "--version-info", binaries / name)+ for name in ("hiroute", "hirouted")}+ notices = self.output / "notices"+ self.script("collect-third-party-licenses", "--cargo-target", self.target,+ "--cpa-source-repo", self.source_repo, "--output", notices)+ packaged = json.loads(self.script(+ "package-standalone", "build", "--version", self.version, "--revision", self.revision,+ "--target", self.target, "--hiroute", binaries / "hiroute", "--hirouted", binaries / "hirouted",+ "--cpa-binary", cpa, "--cpa-version", pin["version"], "--cpa-license", cpa.with_suffix(".LICENSE"),+ "--notices", notices, "--output", self.output))+ archive, manifest = Path(packaged["archive"]), Path(packaged["manifest"])+ packager = module("package-standalone")+ verified = packager.verify(manifest, archive)+ if any(verified[key] != expected for key, expected in (+ ("revision", self.revision), ("version", self.version), ("target", self.target))):+ raise ValueError("standalone package differs from candidate identity")+ self.result["cpa_source"] = provenance+ artifact = {"kind": "standalone", "platform": "Linux", "architecture": self.target.split("-")[0],+ "target": self.target, "format": "tar.gz", "distribution": "unsigned",+ **verified["archive"], "manifest_filename": manifest.name,+ "manifest_sha256": packager.digest(manifest), "manifest_size": manifest.stat().st_size}+ return artifact, [archive, manifest]++ def build(self):+ try:+ self.preflight()+ if self.target.endswith("apple-darwin"):+ artifact, files = self.desktop() # The Desktop packager owns its existing lock.+ else:+ module("package-desktop").ensure_sccache_server()+ with module("local-rust").Store().locked(REPO):+ artifact, files = self.standalone()+ assets = self.output / "assets"+ assets.mkdir()+ for path in files:+ shutil.copyfile(path, assets / path.name)+ self.result.update(status="completed", package_integrity="green",+ website_artifact=artifact, assets=str(assets))+ return self.result+ except Exception as error:+ self.result["error"] = str(error)+ raise+ finally:+ (self.output / "result.json").write_text(json.dumps(self.result, indent=2) + "\n")+ print(f"Candidate evidence: {self.output}", file=sys.stderr)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--target", choices=TARGETS, required=True)+ parser.add_argument("--cpa-source-repo", type=Path, required=True)+ args = parser.parse_args()+ try:+ print(json.dumps(Candidate(args.target, args.cpa_source_repo).build(), indent=2))+ return 0+ except (OSError, ValueError, subprocess.SubprocessError) as error:+ print(str(error), file=sys.stderr)+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test-build-cpa.py b/scripts/test-build-cpa.pyindex a4026df1..7ea8dd30 100644--- a/scripts/test-build-cpa.py+++ b/scripts/test-build-cpa.py@@ -2,6 +2,7 @@"""Deterministic CPA build-output regressions."""import importlib.util+import jsonimport osfrom pathlib import Pathimport stat@@ -21,6 +22,39 @@ spec.loader.exec_module(builder)class BuildOutputTests(unittest.TestCase):+ def test_every_release_target_builds_the_pinned_go_architecture(self):+ targets = {+ "aarch64-unknown-linux-gnu": ("linux", "arm64"),+ "x86_64-unknown-linux-gnu": ("linux", "amd64"),+ "aarch64-apple-darwin": ("darwin", "arm64"),+ "x86_64-apple-darwin": ("darwin", "amd64"),+ }+ pin, _ = builder.pinned_source()+ for target, expected in targets.items():+ with self.subTest(target=target), tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ output = root / "out/cliproxyapi"+ calls = []++ def invoke(command, cwd=None, env=None, **kwargs):+ calls.append(command)+ if command[0] == "tar":+ (Path(command[-1]) / "LICENSE").write_text("fixture license")+ elif command[0] == "go":+ self.assertEqual((env["GOOS"], env["GOARCH"]), expected)+ self.assertEqual(env["CGO_ENABLED"], "0")+ self.assertIn(pin["commit"], command[command.index("-ldflags") + 1])+ Path(command[command.index("-o") + 1]).write_bytes(target.encode())+ return subprocess.CompletedProcess(command, 0)++ with patch.object(builder.subprocess, "run", side_effect=invoke), \+ patch.object(builder.subprocess, "check_output", side_effect=[b"archive", "binary: go1.fixture"]):+ result = builder.build(root / "source", target, output)+ self.assertEqual(result["target"], target)+ self.assertEqual(result["commit"], pin["commit"])+ self.assertEqual(json.loads(output.with_suffix(".provenance.json").read_text()), result)+ self.assertEqual([command[0] for command in calls], ["tar", "git", "go"])+def test_generated_files_have_distribution_safe_modes_under_shared_umask(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory)diff --git a/scripts/test-build-release.py b/scripts/test-build-release.pynew file mode 100644index 00000000..228843c5--- /dev/null+++ b/scripts/test-build-release.py@@ -0,0 +1,197 @@+#!/usr/bin/env python3+"""Release preparation regressions using real package and publication consumers."""+from contextlib import nullcontext, redirect_stdout+import importlib.util+import io+import json+import os+from pathlib import Path+import struct+import subprocess+import sys+import tempfile+import unittest+from unittest.mock import patch++sys.dont_write_bytecode = True+REPO = Path(__file__).resolve().parent.parent+spec = importlib.util.spec_from_file_location("build_release", REPO / "scripts/build-release.py")+builder = importlib.util.module_from_spec(spec)+spec.loader.exec_module(builder)+MODULES = {name: builder.module(name) for name in ("package-desktop", "package-standalone", "build-cpa", "local-rust")}+++def elf(path, machine):+ path.parent.mkdir(parents=True, exist_ok=True)+ header = bytearray(64)+ header[:6] = b"\x7fELF\x02\x01"+ struct.pack_into("<H", header, 18, machine)+ path.write_bytes(header)+ path.chmod(0o755)+++class CandidateTests(unittest.TestCase):+ def setUp(self):+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.source = self.root / "cpa-source"+ self.source.mkdir()+ self.addCleanup(patch.stopall)+ patch.object(builder, "REPO", self.root).start()+ patch.object(builder, "module", side_effect=MODULES.__getitem__).start()+ self.target = "aarch64-unknown-linux-gnu"+ patch.object(builder, "host_target", side_effect=lambda: self.target).start()+ with patch.object(builder.subprocess, "check_output", return_value="a" * 40):+ self.candidate = builder.Candidate(self.target, self.source)+ self.version = json.loads((REPO / "apps/desktop/src-tauri/tauri.conf.json").read_text())["version"]+ config = self.root / "apps/desktop/src-tauri/tauri.conf.json"+ config.parent.mkdir(parents=True)+ config.write_text(json.dumps({"version": self.version}))+ for relative in ("LICENSE", "docs/standalone-cli.md", "assets/skills/hiroute-management/SKILL.md"):+ path = self.root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes((REPO / relative).read_bytes())+ path.chmod(0o644)+ self.commands = []++ def command(self, *args, **kwargs):+ self.commands.append(args)+ if args[:2] == ("git", "status"):+ return ""+ if args[:2] == ("cargo", "metadata"):+ return json.dumps({"target_directory": str(self.root / "target")})+ if args[0] in ("cargo", "rustc") and args[1] == "--version":+ return "fixture toolchain"+ if args[:2] == ("cargo", "build"):+ self.assertIn("--locked", args)+ self.assertEqual(args[args.index("--target") + 1], self.target)+ for name in ("hiroute", "hirouted"):+ elf(self.root / "target" / self.target / "release" / name, 183)+ return ""+ if args[-1] == "--help":+ pin = MODULES["build-cpa"].pinned_source()[0]+ return f'CLIProxyAPI Version: {pin["version"]}, Commit: {pin["commit"]}, BuiltAt: {pin["built_at"]}'+ if args[0] == "readelf":+ return "fixture ELF dependencies"+ self.fail(f"unexpected command: {args}")++ def script(self, name, *args):+ if name == "build-cpa":+ output = Path(args[args.index("--output") + 1])+ elf(output, 183)+ output.with_suffix(".LICENSE").write_text("fixture CPA license")+ output.with_suffix(".LICENSE").chmod(0o644)+ return json.dumps({"target": self.target})+ if name == "collect-third-party-licenses":+ notices = Path(args[args.index("--output") + 1])+ notices.mkdir()+ (notices / "THIRD-PARTY-LICENSES.txt").write_text("fixture notices")+ (notices / "third-party-licenses.json").write_text(json.dumps({+ "schema": "hiroute.third-party-licenses/v1", "inputs": {},+ "packages": [{"name": "fixture"}], "documents": [{"name": "fixture"}],+ }))+ for path in notices.iterdir():+ path.chmod(0o644)+ return "{}"+ if name == "package-standalone":+ packager = MODULES["package-standalone"]+ output = io.StringIO()+ with redirect_stdout(output), patch.object(packager, "REPO", self.root):+ packager.build(packager.parser().parse_args(list(map(str, args))))+ return output.getvalue()+ self.fail(f"unexpected script: {name}")++ def test_arm64_candidate_is_consumed_by_existing_release_verifier(self):+ with patch.object(self.candidate, "run", side_effect=self.command), \+ patch.object(self.candidate, "script", side_effect=self.script), \+ patch.object(MODULES["package-desktop"], "ensure_sccache_server"), \+ patch.object(MODULES["local-rust"], "Store") as store:+ store.return_value.locked.return_value = nullcontext()+ result = self.candidate.build()+ self.assertEqual(result["status"], "completed")+ self.assertEqual(result["website_artifact"]["architecture"], "aarch64")+ artifacts = list(Path(result["assets"]).iterdir())+ self.assertEqual(len(artifacts), 2)+ catalog = self.root / "releases.json"+ catalog.write_text(json.dumps({"schema": "hiroute.website.releases/v2", "releases": [{+ "version": self.version, "channel": "stable", "published_at": "2026-10-08T00:00:00Z",+ "notes": {"zh": "测试", "en": "Fixture"}, "artifacts": [result["website_artifact"]],+ }]}))+ command = ["node", str(REPO / "apps/website/scripts/release-manifest.mjs"), "verify-assets",+ str(catalog), "--tag", f"v{self.version}", "--revision", "a" * 40,+ "--asset-dir", result["assets"]]+ verified = subprocess.run(command, text=True, capture_output=True)+ self.assertEqual(verified.returncode, 0, verified.stderr)+ self.assertIn("2 release asset(s) verified", verified.stdout)+ archive = next(path for path in artifacts if path.name.endswith(".tar.gz"))+ archive.write_bytes(b"tampered")+ self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)++ def test_elf_architecture_rejects_mislabelled_and_non_elf_binaries(self):+ binary = self.root / "binary"+ for target, machine in ((self.target, 183), ("x86_64-unknown-linux-gnu", 62)):+ elf(binary, machine)+ builder.inspect_elf(binary, target)+ with self.assertRaisesRegex(ValueError, "architecture differs"):+ builder.inspect_elf(binary, "x86_64-unknown-linux-gnu" if machine == 183 else self.target)+ for data in (b"", b"not ELF" * 5, b"\x7fELF\x01\x01" + b"\x00" * 58):+ binary.write_bytes(data)+ with self.assertRaises(ValueError):+ builder.inspect_elf(binary, self.target)++ def test_preflight_rejects_dirty_source_wrong_host_and_external_targets(self):+ with patch.object(self.candidate, "run", side_effect=self.command):+ self.candidate.preflight()+ with patch.object(builder, "host_target", return_value="x86_64-unknown-linux-gnu"):+ with self.assertRaisesRegex(ValueError, "native host"):+ self.candidate.preflight()+ for key in ("CARGO_TARGET_DIR", "CARGO_BUILD_TARGET_DIR"):+ with patch.dict(os.environ, {key: "/tmp/external"}), self.assertRaisesRegex(ValueError, "external Cargo"):+ self.candidate.preflight()+ with patch.object(self.candidate, "run", return_value=" M source.rs"), self.assertRaisesRegex(ValueError, "clean committed"):+ self.candidate.preflight()++ def test_cargo_config_cannot_redirect_the_candidate_target(self):+ def redirected(*args, **kwargs):+ if args[:2] == ("cargo", "metadata"):+ return json.dumps({"target_directory": str(self.root / "external-target")})+ return self.command(*args, **kwargs)+ with patch.object(self.candidate, "run", side_effect=redirected):+ with self.assertRaisesRegex(ValueError, "checkout-local"):+ self.candidate.preflight()++ def test_failed_build_keeps_revision_bound_evidence_without_assets(self):+ with patch.object(self.candidate, "preflight", side_effect=ValueError("fixture failure")):+ with self.assertRaisesRegex(ValueError, "fixture failure"):+ self.candidate.build()+ result = json.loads((self.candidate.output / "result.json").read_text())+ self.assertEqual(result["revision"], "a" * 40)+ self.assertEqual(result["status"], "failed")+ self.assertNotIn("website_artifact", result)+ self.assertFalse((self.candidate.output / "assets").exists())++ def test_intel_desktop_uses_existing_packager_and_preserves_identity(self):+ self.candidate.target = "x86_64-apple-darwin"+ self.candidate.version = self.version+ dmg = self.root / f"HiRoute-{self.version}-aaaaaaaaaaaa-macos-x86_64-trial.dmg"+ dmg.write_bytes(b"fixture mounted and verified DMG")+ packaged = {"revision": "a" * 40, "version": self.version, "architecture": "x86_64",+ "distribution": "controlled-trial", "dmg": str(dmg),+ "dmg_sha256": MODULES["package-desktop"].digest(dmg)}+ with patch.object(self.candidate, "script", return_value=json.dumps(packaged)) as run:+ artifact, files = self.candidate.desktop()+ self.assertEqual(files, [dmg])+ self.assertEqual(artifact["architecture"], "x86_64")+ self.assertEqual(artifact["minimum_os"], "15.0")+ self.assertEqual(run.call_args.args, ("package-desktop", "build", "--arch", "x86_64",+ "--cpa-source-repo", self.source))+ for field, value in (("revision", "b" * 40), ("architecture", "arm64"), ("version", "99.0.0"),+ ("dmg_sha256", "0" * 64)):+ with patch.object(self.candidate, "script", return_value=json.dumps({**packaged, field: value})):+ with self.assertRaises(ValueError):+ self.candidate.desktop()+++if __name__ == "__main__":+ unittest.main()diff --git a/scripts/test-plan.py b/scripts/test-plan.pyindex 0b7d348e..019ef037 100644--- a/scripts/test-plan.py+++ b/scripts/test-plan.py@@ -44,6 +44,13 @@ PI_WORKER_BRIDGE_TEST = "crates/daemon/src/delegation/profile/pi_worker_bridge.tPI_SDK_CONTRACT_TEST = "crates/integrations/src/agents/pi_sdk_contract.test.mjs"INTEGRATION_SKILL = ".agents/skills/hiroute-integrate/SKILL.md"WEBSITE_TOOLING = {".github/workflows/website.yml", ".github/workflows/release.yml"}+RELEASE_BUILD_TESTS = ("test-build-cpa.py", "test-build-release.py", "test-package-desktop.py",+ "test-standalone-install.py", "test-third-party-licenses.py")+RELEASE_BUILD_TOOLING = {".github/workflows/build-release.yml", "scripts/build-release.py",+ "scripts/build-cpa.py", "scripts/package-desktop.py",+ "scripts/package-standalone.py", "scripts/install-standalone.py",+ "scripts/collect-third-party-licenses.py",+ *("scripts/" + name for name in RELEASE_BUILD_TESTS)}WEBSITE_PREFIXES = ("apps/website/", ".github/scripts/", "news/", "experiments/")RELEASE_CONTRACT_TOOLING = {"scripts/release-contracts.py", "scripts/test-release-contracts.py","scripts/test-release-contract-pr.py", ".github/scripts/release-contract-pr.sh",@@ -304,8 +311,12 @@ def select(paths, full=False):worker_fixture_tooling = Falsevalidation_tooling = Falserelease_contract_tooling = False+ release_build_tooling = Falsetargets = set()for path in sorted(set(paths)):+ if path in RELEASE_BUILD_TOOLING:+ release_build_tooling = True+ continueif path in PRODUCT_GUIDES:continue # Navigation-only guide; not embedded in a product binary.if path in WORKER_FIXTURE_TOOLING:@@ -426,6 +437,8 @@ def select(paths, full=False):"--", "--exact"])if selection_tooling:commands.append(["python3", "scripts/test-test-plan.py"])+ if full or release_build_tooling:+ commands.extend([["python3", "scripts/" + name] for name in RELEASE_BUILD_TESTS])product_checks = worker_product_checks(paths)if full or worker_fixture_tooling or product_checks:commands.append(["python3", "scripts/test-agent-product-support.py"])diff --git a/scripts/test-test-plan.py b/scripts/test-test-plan.pyindex 0fed037d..5b21ddc7 100644--- a/scripts/test-test-plan.py+++ b/scripts/test-test-plan.py@@ -329,6 +329,20 @@ class SelectionTests(unittest.TestCase):self.assertFalse(result["native_required"])self.assertIn(["python3", "scripts/test-contract-convergence.py"], result["commands"])+ def test_release_build_tooling_selects_packaging_consumers(self):+ for path in plan.RELEASE_BUILD_TOOLING:+ with self.subTest(path=path):+ result = plan.select([path])+ self.assertEqual(result["mode"], "affected")+ self.assertFalse(result["rust"])+ self.assertFalse(result["frontend"])+ for test in plan.RELEASE_BUILD_TESTS:+ self.assertIn(["python3", "scripts/" + test], result["commands"])+ self.assertTrue(plan.select(["scripts/build-release.py", "crates/daemon/src/lib.rs"])["rust"])+ self.assertTrue(plan.select(["vendor/cpa/source.json"])["rust"])+ for test in plan.RELEASE_BUILD_TESTS:+ self.assertIn(["python3", "scripts/" + test], plan.select([], full=True)["commands"])+def test_release_contract_updates_select_their_checks_without_product_builds(self):for path in sorted(plan.RELEASE_CONTRACT_TOOLING | {"contracts/releases/v9.0.0.json"}):with self.subTest(path=path):