Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(maintenance): add upstream dependency upgrade path (#2690)
Call White4a8feaf5ec06
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 7e2601eb9..8f16691fa 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -7,14 +7,82 @@ updates:day: mondaytime: "09:00"timezone: Asia/Shanghai+ open-pull-requests-limit: 3groups:- github-actions:+ github-actions-minor-patch:patterns:- "*"update-types:- minor- patch- ignore:- - dependency-name: "*"++ - package-ecosystem: npm+ directory: /ui+ schedule:+ interval: weekly+ day: monday+ time: "09:00"+ timezone: Asia/Shanghai+ open-pull-requests-limit: 3+ groups:+ ui-npm-minor-patch:+ patterns:+ - "*"+ update-types:+ - minor+ - patch++ - package-ecosystem: npm+ directory: /desktop+ schedule:+ interval: weekly+ day: monday+ time: "09:00"+ timezone: Asia/Shanghai+ open-pull-requests-limit: 3+ groups:+ desktop-npm-minor-patch:+ patterns:+ - "*"+ update-types:+ - minor+ - patch++ - package-ecosystem: cargo+ directory: /desktop+ schedule:+ interval: weekly+ day: monday+ time: "09:00"+ timezone: Asia/Shanghai+ open-pull-requests-limit: 3+ groups:+ desktop-cargo-minor-patch:+ patterns:+ - "*"update-types:- - version-update:semver-major+ - minor+ - patch++ # Dependabot's uv ecosystem can update the declared Python requirements and+ # uv.lock together. `increase` makes declaration-bound maintenance explicit;+ # review still rejects lock-only drift. Keep the Claude SDK on its explicit+ # runtime path: it bundles a CLI and has a separate Windows wheel constraint.+ - package-ecosystem: uv+ directory: /+ schedule:+ interval: weekly+ day: monday+ time: "09:00"+ timezone: Asia/Shanghai+ open-pull-requests-limit: 3+ versioning-strategy: increase+ groups:+ python-uv-minor-patch:+ patterns:+ - "*"+ update-types:+ - minor+ - patch+ ignore:+ - dependency-name: claude-agent-sdkdiff --git a/.github/workflows/model-hub-engine-release-guard.yml b/.github/workflows/model-hub-engine-release-guard.ymlindex 0f048ee16..a6ca749f0 100644--- a/.github/workflows/model-hub-engine-release-guard.yml+++ b/.github/workflows/model-hub-engine-release-guard.yml@@ -32,9 +32,28 @@ jobs:steps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5+ - name: Resolve manifest Go toolchain+ id: go_pin+ shell: bash+ run: |+ set -euo pipefail+ raw_go_version="$(+ python3 scripts/model_hub_engine_release_guard.py \+ --manifest vibe/model_hub_runtime/cliproxyapi_manifest.json \+ go-version+ )"+ case "$raw_go_version" in+ go[0-9]*.[0-9]*.[0-9]*) go_version="${raw_go_version#go}" ;;+ *)+ echo "release guard returned an invalid Go version: $raw_go_version" >&2+ exit 1+ ;;+ esac+ printf 'go_version=%s\n' "$go_version" >> "$GITHUB_OUTPUT"+- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6with:- go-version: "1.26.9"+ go-version: ${{ steps.go_pin.outputs.go_version }}- name: Build and verify patched source assetsrun: |diff --git a/AGENTS.md b/AGENTS.mdindex e2ffc38e1..2168b3439 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -191,6 +191,11 @@ Source-of-truth rule:### Planning and Documentation+For recurring upstream dependency work, use the canonical playbook at+`docs/maintenance/upstream-dependency-maintenance.md`; keep detection,+candidate preparation, focused validation, and owner-held release boundaries+there rather than expanding this index.+- for complex or ambiguous tasks, record the plan in `docs/plans/` (background,goal, solution, todo items) and update it when scope changes materially- ask before choosing a direction only when an ambiguity would change thediff --git a/docs/maintenance/upstream-dependency-maintenance.md b/docs/maintenance/upstream-dependency-maintenance.mdnew file mode 100644index 000000000..2a9545b41--- /dev/null+++ b/docs/maintenance/upstream-dependency-maintenance.md@@ -0,0 +1,392 @@+# Upstream dependency maintenance playbook++This is the operational playbook for preparing upstream dependency upgrades in+Avibe. It is designed for one weekly Harness Task and explicit on-demand runs;+it is not a new GitHub scheduler or a universal dependency registry.++## Operating contract++- Prepare one reviewed candidate per dependency at a time. Coalesce repeated+ upstream releases into the latest exact candidate instead of opening a trial+ for every upstream tag.+- Read the current owner Sessions, Runs, Watches, and open PRs before starting.+ Skip a dependency whose candidate is actively owned by another Session or PR+ (in particular, do not compete with the CPA v8.0.29 work in PR #2680). Record+ the owner-held skip in the run report and continue with independent lanes.+- Record exact upstream version/tag, immutable source commit, source URL, patch+ order and checksums before building. Never use `latest`, floating URLs, fake+ digests, or a digest copied from a previous candidate.+- Reuse the existing builder, release guard, manifests, workflows, Runs and+ Watches. A runtime candidate gets focused checks plus exactly one relevant+ local Incus regression E2E. Exploratory checks are evidence, not extra adoption+ gates, unless they expose a reproducible contract failure.+- A successful candidate may prepare or update a PR and carry it through review+ and CI. Merge, official publication, release/tag creation, packaged pin+ adoption, and host rollout remain owner-held. Publish replacement assets before+ changing a packaged manifest.+- No-change runs are silent. Report only a prepared candidate/PR, an owner-held+ conflict, a concrete exception, or a failed required check.++The Task uses the existing Avibe Harness Agent/Runs/Watches. Do not add a+scheduled GitHub workflow, daemon, or live Task in a dependency PR.++## Weekly or on-demand procedure++1. **Preflight ownership.** Inspect `vibe data query` for live Sessions and+ Runs, `vibe watch list`, and `gh pr list --state open`. Do not touch another+ owner's dirty worktree or candidate branch. If a matching owner PR is live,+ coalesce into that work only when its owner explicitly accepts the handoff;+ otherwise report and skip.+2. **Detect exact drift.** Read the owning manifest/declaration and the current+ upstream release/tag API. Resolve the tag to an immutable commit or release+ asset set. Compare version, source identity, patch applicability, license,+ platform set, archive size, and SHA-256. Detection is not completion: a+ usable result is a prepared, tested upgrade PR or a specific exception.+3. **Prepare one candidate.** Use the dependency-specific path below. Keep+ candidate manifests, receipts, offline manifests, and downloaded artifacts in+ a temporary directory outside the exact release-asset directory.+4. **Run focused validation.** Run the owning builder/guard tests and the+ narrow checks for changed boundaries. For a runtime bump, run one relevant+ local Incus E2E through `scripts/incus_regression.py`; use the repository+ runner and preserve the environment. Never hide a failure with retries or a+ larger timeout.+5. **Prepare or update one PR.** Include exact source identity and digests,+ patch decisions, focused results, the single E2E result, and known+ exceptions. Use the normal PR delivery loop: non-draft PR, exact-head Codex+ review, CI, and zero unresolved threads. Do not merge.+6. **Continue safely.** Keep one combined PR/CI Watch for the lane. A patch+ conflict, build failure, E2E failure, missing support contract, or+ non-reproducible asset is an exception report, not a reason to create a+ trial matrix. Stop at the smallest reproducible boundary and name the next+ owner action.++## Dependency-specific paths++### CPA / Model Hub engine++Source of truth and consumers:++- packaged identity: `vibe/model_hub_runtime/cliproxyapi_manifest.json`;+- compatibility patches and ordered metadata:+ `patches/model-hub-cpa-*/README.md` and the patch files;+- candidate builder: `scripts/build_model_hub_engine.py`;+- unchanged byte/asset guard:+ `scripts/model_hub_engine_release_guard.py`;+- relevant contract checks: `tests/test_model_hub_engine_build.py` and+ `tests/test_model_hub_engine_release_guard.py`;+- relevant local regression: the existing installed-service Model Hub+ acceptance in `tests/e2e/test_model_hub_service_acceptance.py`, run once with+ a candidate manifest and synthetic loopback upstreams.++Preparation:++1. Resolve the upstream CPA release tag to its exact source commit. Start from+ the current patch set, apply patches in recorded order with+ `git apply --check`, and remove a patch only when its README drop condition+ and the upstream source both prove it is no longer needed.+2. Create a temporary candidate manifest outside the output directory. It keeps+ the exact source identity, build metadata, ordered patch entries, version,+ `asset_release_tag`, and the six Avibe-owned planned URLs, but contains no+ `size_bytes`, `sha256`, or `binary_sha256` fields. Do not edit the packaged+ manifest for this step.+3. Use the first-class candidate mode, which reuses the strict build/archive loop and+ official builder flags. The builder records the effective fixed settings+ (`CGO_ENABLED=0`, `-trimpath`, and `-buildvcs=false`) in the generated+ manifest. Candidate metadata may omit those fields, in which case the fixed+ invocation values are recorded; contradictory values fail before any target+ build. Strict mode keeps rejecting mismatched pinned bytes.++ The builder also gives both strict and candidate builds one controlled Go+ environment: `GO111MODULE=on`, `GOENV=off`, `GOTOOLCHAIN=local`,+ `GOWORK=off`, `GOFIPS140=off`, `GODEBUG`/`GOFLAGS`/`GOEXPERIMENT` empty,+ and the documented baseline architecture levels+ (`GOAMD64=v1` or `GOARM64=v8.0`, with other architecture-level variables+ cleared). It preserves only cache/download settings that do not change build+ identity. The exact Go version is recorded in the candidate manifest and is+ validated in its `goX.Y.Z` form. The publication workflow keeps that form+ for manifest/builder comparison, then strips only the `go` prefix at the+ `setup-go` adapter so the action receives bare `X.Y.Z`; it fails closed if+ the validated value is missing or malformed.++ ```bash+ python3 scripts/build_model_hub_engine.py \+ --candidate \+ --manifest "$TMP/cpa-candidate-manifest.json" \+ "$TMP/cpa-candidate-assets"+ ```++ The output directory must be fresh and contain only the six archives, six+ checksum sidecars, and the generated `model-hub-engine-manifest.json`.+ Candidate mode computes all six real archive sizes, archive hashes, binary+ hashes, and owned planned URLs, then runs the same release-asset verifier.+ It does not publish, call `gh`, or modify the packaged manifest.+4. Before the installed-service E2E, resolve the actual test-owned Incus+ container platform through the existing `Runner`/`tenant_exec` helpers. Do+ not use the host architecture. Keep `ACCEPTANCE_PYTHON` pointed at the+ normal-wheel, test-only venv (never `/opt/avibe/venv`), and ask the installed+ Avibe code for both its raw runtime tag and its canonical Model Hub asset:++ ```python+ import shlex+ from pathlib import Path++ probe = runner.run(+ tenant_exec(+ target,+ f"cd /tmp && {ACCEPTANCE_PYTHON} -I -c "+ + shlex.quote(+ "import sys; "+ "from pathlib import Path; "+ "from core.managed_runtime import runtime_platform_tag; "+ "from vibe.model_hub_runtime.installer import EngineRuntimeManager; "+ "paths = [Path(__import__('core').__file__).resolve(), "+ "Path(__import__('vibe').__file__).resolve()]; "+ "prefix = Path(sys.prefix).resolve(); "+ "assert all(prefix == path or prefix in path.parents for path in paths), "+ "(prefix, paths); "+ "print(runtime_platform_tag()); "+ "print(EngineRuntimeManager(offline=True).host_platform()); "+ "print(prefix); "+ "print(*paths, sep='\\n')"+ ),+ ),+ capture=True,+ )+ raw_platform, asset_platform, prefix, *module_paths = probe.stdout.strip().splitlines()+ if asset_platform not in {"linux-amd64", "linux-arm64"}:+ raise SystemExit(f"unsupported Incus Model Hub platform: {raw_platform} -> {asset_platform}")+ if not module_paths or any(+ not (Path(path).resolve() == Path(prefix).resolve()+ or Path(prefix).resolve() in Path(path).resolve().parents)+ for path in module_paths+ ):+ raise SystemExit("platform probe did not import the candidate normal wheel")+ ```++ The installer is the source of truth for these aliases: `linux-x64` selects+ `linux-amd64`, and `linux-arm64` selects `linux-arm64`. Any other normalized+ platform fails before an archive is selected or transferred. Select exactly+ the matching generated asset, preserving its version and recorded digests;+ never select by the host or by a hard-coded arm64 example.++ Create an offline manifest outside the exact asset directory. Use one name+ consistently from generation through transfer and installation. Set+ `CANDIDATE_MANIFEST` to the generated manifest and `OFFLINE_MANIFEST` to+ `$TMP/model-hub-engine-offline-manifest.json` before running this fragment:++ ```python+ import hashlib+ import json+ import os+ from pathlib import Path++ OFFLINE_MANIFEST_NAME = "model-hub-engine-offline-manifest.json"+ CONTAINER_ASSET_DIR = "/tmp/avibe-candidate-assets"+ source = Path(os.environ["CANDIDATE_MANIFEST"])+ asset_dir = source.parent+ destination = Path(os.environ["OFFLINE_MANIFEST"])+ source_payload = json.loads(source.read_text(encoding="utf-8"))+ offline_payload = json.loads(source.read_text(encoding="utf-8"))+ selected = next(item for item in source_payload["assets"] if item["platform"] == asset_platform)+ archive = asset_dir / Path(selected["url"]).name+ if archive.stat().st_size != selected["size_bytes"]:+ raise SystemExit(f"candidate archive size mismatch: {archive}")+ if hashlib.sha256(archive.read_bytes()).hexdigest() != selected["sha256"]:+ raise SystemExit(f"candidate archive digest mismatch: {archive}")+ offline_selected = next(+ item for item in offline_payload["assets"] if item["platform"] == asset_platform+ )+ offline_selected["url"] = (Path(CONTAINER_ASSET_DIR) / archive.name).as_uri()+ destination.write_text(json.dumps(offline_payload, indent=2) + "\n", encoding="utf-8")+ ```++ Transfer exactly `archive` and `destination` to the same container-owned+ directory with `Runner.run(tenant_exec(...), input_bytes=...)`, verifying+ each input SHA-256 before writing it. For example, the existing acceptance+ harness can use this transfer shape without raw lifecycle commands:++ ```python+ runner.run(tenant_exec(target, f"mkdir -p {shlex.quote(CONTAINER_ASSET_DIR)}"))+ for source_path, remote_path in (+ (archive, f"{CONTAINER_ASSET_DIR}/{archive.name}"),+ (destination, f"{CONTAINER_ASSET_DIR}/{OFFLINE_MANIFEST_NAME}"),+ ):+ data = source_path.read_bytes()+ digest = hashlib.sha256(data).hexdigest()+ write_code = (+ "from pathlib import Path; import hashlib, sys; "+ f"p=Path({remote_path!r}); data=sys.stdin.buffer.read(); "+ f"assert hashlib.sha256(data).hexdigest()=={digest!r}; p.write_bytes(data)"+ )+ runner.run(+ tenant_exec(target, "python3 -c " + shlex.quote(write_code)),+ input_bytes=data,+ )+ ```++ The bounded procedure rehearsal must use synthetic local manifest/archive+ metadata for all three cases before the real E2E: `linux-x64` ->+ `linux-amd64`, `linux-arm64` -> `linux-arm64`, and an unsupported spelling+ such as `linux-riscv64` -> explicit failure. Assert that only the selected+ asset URL changes, the selected archive's size and SHA-256 are preserved,+ and unsupported input performs no transfer. This is a contract check, not a+ second live E2E. Do not publish the planned Avibe URL and do not touch the+ runner service.+5. Verify the generated manifest again if a separate step consumes it:++ ```bash+ python3 scripts/model_hub_engine_release_guard.py \+ --manifest "$TMP/cpa-candidate-assets/model-hub-engine-manifest.json" \+ verify --asset-dir "$TMP/cpa-candidate-assets"+ ```++6. Run the focused builder/guard tests, then run the existing installed-service+ acceptance once with+ `VIBE_MODEL_HUB_ENGINE_MANIFEST_PATH=/tmp/avibe-candidate-assets/model-hub-engine-offline-manifest.json`+ (and the candidate normal wheel) against synthetic loopback upstreams. Record+ the real result and prepare the PR with the candidate manifest/patch+ metadata. The existing release workflow remains the publication/recovery+ authority; do not change the packaged pin or publish from candidate mode.++Strict pinned mode remains the recovery and publication path: it must verify+bytes against the checked-in manifest and reject mismatched archives. A+candidate's output manifest is new evidence, not permission to adopt it.++### `claude-agent-sdk`++This is a runtime dependency, not an ordinary bulk update. It bundles a Claude+Code CLI and has a separate Windows wheel constraint in `pyproject.toml`.+Dependabot excludes it from the generic `uv` lane.++When an explicit SDK candidate is requested:++1. inspect both the declarations in `pyproject.toml` and the corresponding+ `uv.lock` entries, including the Windows marker;+2. record the SDK version and bundled CLI version exactly;+3. run the existing installed-service Claude path with a fresh home,+ loopback/fake credentials, and the relevant local Incus E2E once;+4. update the declaration and lock together only after the runtime evidence is+ understood; preserve the Windows constraint or report an upstream wheel+ exception;+5. keep startup failures visible. Do not turn an SDK startup timeout into a+ passing result by increasing timeouts or adding retries.++### Git runtime++The active path is the manual build workflow and its manifest, not Dependabot:++- version/source/checksum inputs and Avibe hardening are in+ `.github/workflows/build-git.yml`;+- the consumed pinned output is `vibe/git_runtime_manifest.json`;+- release verification/recovery is `.github/workflows/git-runtime-release-guard.yml`+ and `scripts/git_runtime_release_guard.py`;+- the mirror follows published releases through+ `.github/workflows/release-mirror.yml`.++Resolve the upstream kernel.org tarball and SHA-256, update the workflow input+and manifest as one candidate, build the four supported platforms, run the Git+runtime guard and focused tests, then run one relevant local Incus runtime+check. Publication and packaged adoption remain owner-held.++### tmux runtime++The manifest is `vibe/tmux_runtime_manifest.json`; the current build entry point+is `.github/workflows/build-tmux.yml`. That workflow still packages scaffold+placeholders and explicitly refuses publication. This is a real support+exception, not a successful upgrade path:++- do not publish or adopt a tmux candidate from the scaffold;+- report the missing cross-build contract (real static/relocatable tmux with+ utf8proc, terminfo, archive and binary verification);+- only after that contract exists, update the exact manifest and run its focused+ checks plus one relevant local regression.++### ripgrep and cloudflared++These are upstream release-asset consumers, not source builds in this repo:++- `vibe/ripgrep_runtime_manifest.json` pins version, release URLs, archive+ format, size, archive SHA-256, binary SHA-256, and binary path;+- `vibe/cloudflared_runtime_manifest.json` carries the same contract for its+ tarballs or raw binaries;+- `.github/workflows/release-mirror.yml` mirrors published releases and is the+ availability guard.++For either dependency, resolve the upstream release, update every platform+entry with exact immutable asset names and digests, run the existing manifest+and runtime-consumer tests, and perform one relevant local Incus check. If an+upstream asset changes format, platform coverage, signing, or binary path,+report that contract exception instead of silently broadening the installer.++### Desktop toolchains++The active desktop inputs are explicit source manifests:++- `desktop/runtime-sources.json` pins the private Python build, Node archive,+ npm version, and the Show Runtime manifest;+- `desktop/cua-driver/sources.json` pins the CUA driver release, source commit,+ tool snapshot checksum, platform asset checksum, and patch contract;+- `desktop/scripts/build-runtime-bundle.py` downloads with SHA-256 checks,+ exports the frozen Python requirements, installs with required hashes, and+ builds the relocatable bundle;+- `desktop/cua-driver/PATCHES.md` records when the CUA patch may be dropped;+- focused checks include `tests/test_desktop_runtime_bundle_builder.py` and+ the existing desktop package/update checks.++For a Python/Node/npm candidate, update the exact URLs and hashes together,+rebuild the affected target bundle, verify the expected npm and Show Runtime+identity, and run one relevant desktop smoke/regression path. For a CUA driver+candidate, resolve the release tag and source commit, refresh the tool snapshot+and patch applicability, rebuild the helper, and verify the macOS raw-click and+parent-liveness contracts. A missing Windows or macOS build/signing contract is+an explicit exception; do not fill it with a placeholder archive.++## Ordinary dependency automation++`.github/dependabot.yml` covers:++- ordinary npm dependencies in `/ui` and `/desktop`;+- the desktop Cargo workspace in `/desktop`;+- the root `uv` ecosystem, with `versioning-strategy: increase` so the lane+ explicitly targets declaration-bound maintenance while updating `uv.lock`+ when applicable.++A uv PR is accepted only when it contains a meaningful `pyproject.toml`+requirement change together with the corresponding `uv.lock` update; a lock-only+change is an exception, not ordinary declaration maintenance. The lock is+consumed by desktop packaging and focused frozen-lock jobs, while most ordinary+lint installs use `uv pip install --system -e . --group dev` and resolve the+project declarations directly.++Minor and patch updates are grouped per ecosystem. Major updates remain+individual, reviewable PRs. Each lane has a small open-PR limit and no+auto-merge. `claude-agent-sdk` is ignored by the generic `uv` lane because its+bundled CLI and Windows marker require the runtime path above. Dependabot does+not open sibling-repository PRs in this lane.++## Canonical Harness Task message++Use this as the Task body after the playbook and a dry run have been reviewed;+the implementation PR does not create or enable the live schedule:++```text+Run the Avibe upstream dependency maintenance playbook at+ docs/maintenance/upstream-dependency-maintenance.md.++Cadence: every Monday at 09:00 Asia/Shanghai, plus on-demand manual runs.+Inspect live Sessions/PRs first and skip owner-held candidates (especially+CPA2680). Coalesce to one candidate per dependency. For each actual drift,+resolve exact source/version/asset digests, prepare a focused upgrade PR, run+its focused checks and exactly one relevant local Incus regression E2E for+runtime bumps, and keep one combined PR/CI Watch through review and CI.++Do not spam when there is no change. Report only a prepared/tested PR, an+owner-held skip, or a concrete exception such as patch conflict, failed E2E,+missing builder/support contract, or non-reproducible bytes. Never merge,+publish, change a packaged pin, restart a host, or create sibling-repo PRs;+those remain owner-held.+```++An on-demand run uses the same message and cadence rules; only the trigger+changes. The task's success condition is prepared, tested, reviewable work or+a concrete exception—not a version-detection notification.diff --git a/scripts/build_model_hub_engine.py b/scripts/build_model_hub_engine.pyindex 08d6df1ac..96e19e38a 100644--- a/scripts/build_model_hub_engine.py+++ b/scripts/build_model_hub_engine.py@@ -21,6 +21,7 @@ from typing import Any, Mapping, SequenceREPO_ROOT = Path(__file__).resolve().parents[1]DEFAULT_MANIFEST = REPO_ROOT / "vibe" / "model_hub_runtime" / "cliproxyapi_manifest.json"DEFAULT_SOURCE_REPOSITORY = "https://github.com/router-for-me/CLIProxyAPI.git"+OWNED_RELEASE_ROOT = "https://github.com/avibe-bot/avibe/releases/download"TARGETS = {"darwin-arm64": ("darwin", "arm64", "darwin_aarch64"),@@ -31,17 +32,88 @@ TARGETS = {"windows-arm64": ("windows", "arm64", "windows_aarch64"),}DOCUMENT_MEMBERS = ("LICENSE", "README.md", "README_CN.md", "config.example.yaml")+_FIXED_BUILD_SETTINGS = {+ "cgo_enabled": False,+ "trimpath": True,+ "buildvcs": False,+}+_GO_ARCHITECTURE_LEVEL_VARS = (+ "GO386",+ "GOAMD64",+ "GOARM",+ "GOARM64",+ "GOMIPS",+ "GOMIPS64",+ "GOPPC64",+ "GORISCV64",+ "GOWASM",+)+_GO_BUILD_CONTROL_ENV = {+ "GO111MODULE": "on",+ "GOENV": "off",+ "GOFLAGS": "",+ "GOEXPERIMENT": "",+ "GOFIPS140": "off",+ "GODEBUG": "",+ "GOTOOLCHAIN": "local",+ "GOWORK": "off",+ "GO_EXTLINK_ENABLED": "0",+}class BuildError(RuntimeError):"""Raised when a pinned Model Hub source build cannot be trusted."""+def _controlled_go_environment(+ *,+ goos: str | None = None,+ goarch: str | None = None,+ base_environment: Mapping[str, str] | None = None,+) -> dict[str, str]:+ """Return the reproducible Go environment used by version and build commands.++ The variables below are the Go toolchain's documented build/toolchain controls;+ caches, module downloads, and the caller's PATH remain available. Ambient+ architecture levels, flags, experiments, workspace discovery, persisted Go+ configuration, and automatic toolchain switching do not belong to a recorded+ six-platform build identity.+ """++ environment = dict(base_environment) if base_environment is not None else os.environ.copy()+ for name in (*_GO_ARCHITECTURE_LEVEL_VARS, "GOOS", "GOARCH", "CGO_ENABLED"):+ environment.pop(name, None)+ environment.update(_GO_BUILD_CONTROL_ENV)+ if goos is None or goarch is None:+ return environment+ if goarch == "amd64":+ environment["GOAMD64"] = "v1"+ elif goarch == "arm64":+ environment["GOARM64"] = "v8.0"+ else: # pragma: no cover - TARGETS currently contains only these architectures.+ raise BuildError(f"unsupported Model Hub Go architecture: {goarch}")+ environment.update({"GOOS": goos, "GOARCH": goarch, "CGO_ENABLED": "0"})+ return environment+++def _candidate_build_metadata(build_metadata: Mapping[str, Any]) -> dict[str, Any]:+ """Normalize omitted fixed settings and reject contradictory candidate input."""++ effective = dict(build_metadata)+ for field, expected in _FIXED_BUILD_SETTINGS.items():+ if field in build_metadata and build_metadata[field] != expected:+ raise BuildError(+ f"candidate Model Hub build metadata {field} contradicts the fixed build setting"+ )+ effective[field] = expected+ return effective++def _go_toolchain_version(output: str) -> str:fields = output.split()if len(fields) < 3 or fields[:2] != ["go", "version"] or not fields[2].startswith("go"):raise BuildError("Go toolchain identity is unreadable")- if re.fullmatch(r"go[0-9]+(?:\.[0-9]+){1,2}", fields[2]) is None:+ if re.fullmatch(r"go[0-9]+\.[0-9]+\.[0-9]+", fields[2]) is None:raise BuildError("Go toolchain version is not stable")return fields[2]@@ -118,11 +190,15 @@ def _binary_name(platform: str) -> str:return "cli-proxy-api.exe" if TARGETS[platform][0] == "windows" else "cli-proxy-api"-def _pinned_patches(build_metadata: Mapping[str, Any]) -> list[Path]:+def _pinned_patches(+ build_metadata: Mapping[str, Any],+ *,+ allow_empty: bool = False,+) -> list[Path]:"""Return the manifest's patches in apply order, each checked against its digest."""recorded = build_metadata.get("patches")- if not isinstance(recorded, list) or not recorded:+ if not isinstance(recorded, list) or (not recorded and not allow_empty):raise BuildError("Model Hub manifest compatibility patch identity is invalid")patches: list[Path] = []for item in recorded:@@ -193,6 +269,42 @@ def _asset_name(version: str, platform: str) -> str:return f"CLIProxyAPI_{version.removeprefix('v')}_{TARGETS[platform][2]}.tar.gz"+def _candidate_asset_urls(payload: Mapping[str, Any]) -> dict[str, str]:+ """Validate candidate asset identity without accepting untrusted digests."""++ raw_assets = payload.get("assets")+ if not isinstance(raw_assets, list):+ raise BuildError("candidate Model Hub engine manifest assets must be a list")+ expected_tag = payload.get("asset_release_tag")+ version = payload.get("version")+ if not isinstance(expected_tag, str) or not expected_tag:+ raise BuildError("candidate Model Hub engine manifest asset release tag is missing")+ if not isinstance(version, str) or not version:+ raise BuildError("candidate Model Hub engine manifest version is missing")++ urls: dict[str, str] = {}+ for item in raw_assets:+ if not isinstance(item, dict):+ raise BuildError("candidate Model Hub engine manifest asset is invalid")+ platform = item.get("platform")+ if platform not in TARGETS or platform in urls:+ raise BuildError("candidate Model Hub engine manifest platform set is invalid")+ if any(key in item for key in ("size_bytes", "sha256", "binary_sha256")):+ raise BuildError(+ "candidate Model Hub engine manifest must not contain pinned asset digests"+ )+ expected_url = (+ f"{OWNED_RELEASE_ROOT}/{expected_tag}/{_asset_name(version, platform)}"+ )+ url = item.get("url", expected_url)+ if url != expected_url:+ raise BuildError(f"candidate Model Hub engine asset URL is not Avibe-owned: {platform}")+ urls[platform] = url+ if set(urls) != set(TARGETS):+ raise BuildError("candidate Model Hub engine manifest platform set is invalid")+ return urls++def _native_target() -> str | None:goos = {"Darwin": "darwin", "Linux": "linux", "Windows": "windows"}.get(platform.system())goarch = {@@ -242,12 +354,19 @@ def build_source_release(manifest_path: Path,output_dir: Path,*,+ candidate: bool = False,source_repository: str = DEFAULT_SOURCE_REPOSITORY,go_binary: str = "go",) -> Path:- """Build all pinned targets and return the checked-in manifest path."""+ """Build a pinned release or a freshly-digested candidate manifest.+ Candidate mode accepts source/patch metadata and owned planned asset URLs,+ but never trusts or requires asset digests from the input. It writes a new+ manifest containing the bytes produced by this build before running the+ same release guard used by strict pinned mode.+ """payload = _load_manifest(manifest_path)+ candidate_urls = _candidate_asset_urls(payload) if candidate else Noneoutput_dir = output_dir.resolve()if output_dir.exists():if not output_dir.is_dir() or output_dir.is_symlink() or any(output_dir.iterdir()):@@ -258,7 +377,8 @@ def build_source_release(build_metadata = payload.get("build")if not isinstance(build_metadata, dict):build_metadata = {}- patches = _pinned_patches(build_metadata)+ effective_build_metadata = _candidate_build_metadata(build_metadata) if candidate else build_metadata+ patches = _pinned_patches(build_metadata, allow_empty=candidate)source_date_epoch = build_metadata.get("source_date_epoch", 0)if isinstance(source_date_epoch, bool) or not isinstance(source_date_epoch, int) or source_date_epoch < 0:raise BuildError("Model Hub build source_date_epoch is invalid")@@ -270,8 +390,16 @@ def build_source_release(source_sha=str(payload["source_sha"]),patches=patches,)- go_version = _go_toolchain_version(_run([go_binary, "version"], cwd=checkout))+ go_environment = _controlled_go_environment()+ go_version = _go_toolchain_version(+ _run([go_binary, "version"], cwd=checkout, env=go_environment)+ )pinned_go_version = build_metadata.get("go_version")+ if candidate and (+ not isinstance(pinned_go_version, str)+ or re.fullmatch(r"go[0-9]+\.[0-9]+\.[0-9]+", pinned_go_version) is None+ ):+ raise BuildError("candidate Model Hub build must record an exact go_version")if isinstance(pinned_go_version, str) and pinned_go_version and go_version != pinned_go_version:raise BuildError(f"Go toolchain {go_version} differs from pinned manifest toolchain {pinned_go_version}"@@ -283,13 +411,10 @@ def build_source_release(build_dir = Path(temporary) / "artifacts" / platformbuild_dir.mkdir(parents=True)binary = build_dir / _binary_name(platform)- environment = os.environ.copy()- environment.update(- {- "CGO_ENABLED": "0",- "GOOS": goos,- "GOARCH": goarch,- }+ environment = _controlled_go_environment(+ goos=goos,+ goarch=goarch,+ base_environment=go_environment,)_run([@@ -326,10 +451,14 @@ def build_source_release(generated_assets.append({"platform": platform,- "url": next(- item["url"]- for item in payload["assets"]- if isinstance(item, dict) and item.get("platform") == platform+ "url": (+ candidate_urls[platform]+ if candidate_urls is not None+ else next(+ item["url"]+ for item in payload["assets"]+ if isinstance(item, dict) and item.get("platform") == platform+ )),"size_bytes": archive_path.stat().st_size,"sha256": _sha256(archive_path),@@ -343,7 +472,22 @@ def build_source_release()generated_manifest = output_dir / "model-hub-engine-manifest.json"- generated_manifest.write_bytes(manifest_path.read_bytes())+ if candidate:+ candidate_payload = dict(payload)+ candidate_payload["assets"] = generated_assets+ candidate_payload["build"] = effective_build_metadata+ generated_manifest.write_text(+ json.dumps(candidate_payload, indent=2) + "\n",+ encoding="utf-8",+ )+ verification_manifest = generated_manifest+ else:+ # The checked-in manifest is the publication contract. A generated+ # manifest may describe what this runner produced, but it must not+ # replace the pinned sizes, digests, or metadata used by installed+ # clients.+ generated_manifest.write_bytes(manifest_path.read_bytes())+ verification_manifest = manifest_path# Import lazily so the builder can be unit-tested without importing the# network-facing release guard during source preparation.@@ -354,10 +498,9 @@ def build_source_release(raisefrom model_hub_engine_release_guard import verify_release_assets- # The checked-in manifest is the publication contract. A generated- # manifest may describe what this runner produced, but it must not replace- # the pinned sizes, digests, or metadata used by installed clients.- verify_release_assets(manifest_path, output_dir)+ # Candidate mode uses the same release guard, but verifies the freshly+ # generated manifest rather than the checked-in pinned contract.+ verify_release_assets(verification_manifest, output_dir)return generated_manifest@@ -366,6 +509,11 @@ def _build_parser() -> argparse.ArgumentParser:parser.add_argument("--manifest", type=Path, default=DEFAULT_MANIFEST)parser.add_argument("--source-repository", default=DEFAULT_SOURCE_REPOSITORY)parser.add_argument("--go", default="go", dest="go_binary")+ parser.add_argument(+ "--candidate",+ action="store_true",+ help="write a freshly-digested candidate manifest instead of checking pinned digests",+ )parser.add_argument("output_dir", type=Path)return parser@@ -376,6 +524,7 @@ def main(argv: list[str] | None = None) -> int:generated_manifest = build_source_release(args.manifest,args.output_dir,+ candidate=args.candidate,source_repository=args.source_repository,go_binary=args.go_binary,)diff --git a/scripts/model_hub_engine_release_guard.py b/scripts/model_hub_engine_release_guard.pyindex 15c469074..d00c2f7ce 100755--- a/scripts/model_hub_engine_release_guard.py+++ b/scripts/model_hub_engine_release_guard.py@@ -45,6 +45,7 @@ ASSET_TAG_RE = re.compile(VERSION_RE = re.compile(r"v[0-9]+\.[0-9]+\.[0-9]+")SHA256_RE = re.compile(r"[0-9a-f]{64}")SOURCE_SHA_RE = re.compile(r"[0-9a-f]{40}")+GO_VERSION_RE = re.compile(r"go[0-9]+\.[0-9]+\.[0-9]+")MAX_ARCHIVE_BYTES = 256 * 1024 * 1024@@ -88,6 +89,20 @@ def _required_string(payload: dict, key: str, context: str) -> str:return value+def manifest_go_version(manifest_path: Path) -> str:+ """Return the exact stable Go pin used by source publication and recovery."""++ try:+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise ReleaseGuardError(f"cannot read Model Hub engine manifest: {exc}") from exc+ build = payload.get("build") if isinstance(payload, dict) else None+ version = build.get("go_version") if isinstance(build, dict) else None+ if not isinstance(version, str) or GO_VERSION_RE.fullmatch(version) is None:+ raise ReleaseGuardError("Model Hub engine manifest build.go_version must be an exact stable Go version")+ return version++def load_release_spec(manifest_path: Path) -> ReleaseSpec:try:manifest_bytes = manifest_path.read_bytes()@@ -396,6 +411,10 @@ def _build_parser() -> argparse.ArgumentParser:fetch_source.add_argument("--output-dir", type=Path, required=True)verify = subparsers.add_parser("verify", help="Verify a materialized release directory.")verify.add_argument("--asset-dir", type=Path, required=True)+ subparsers.add_parser(+ "go-version",+ help="Print and validate the exact stable Go version recorded in the manifest.",+ )publish_draft = subparsers.add_parser("publish-draft", help="Repair and verify a draft using manifest-pinned assets before publication.",)@@ -413,6 +432,9 @@ def main(argv: list[str] | None = None) -> int:spec = fetch_upstream_assets(args.manifest, args.output_dir)elif args.command == "publish-draft":spec = publish_draft_release(args.manifest, args.asset_dir, repository=args.repo)+ elif args.command == "go-version":+ print(manifest_go_version(args.manifest))+ return 0else:spec = verify_release_assets(args.manifest, args.asset_dir)except ReleaseGuardError as exc:diff --git a/tests/test_dependabot_config.py b/tests/test_dependabot_config.pynew file mode 100644index 000000000..41cd4b18f--- /dev/null+++ b/tests/test_dependabot_config.py@@ -0,0 +1,42 @@+from __future__ import annotations++from pathlib import Path++import yaml+++ROOT = Path(__file__).resolve().parents[1]+++def _updates() -> list[dict]:+ payload = yaml.safe_load((ROOT / ".github/dependabot.yml").read_text(encoding="utf-8"))+ assert payload["version"] == 2+ return payload["updates"]+++def test_dependabot_covers_ordinary_ecosystems_with_reviewable_update_policy() -> None:+ updates = _updates()+ assert [(item["package-ecosystem"], item["directory"]) for item in updates] == [+ ("github-actions", "/"),+ ("npm", "/ui"),+ ("npm", "/desktop"),+ ("cargo", "/desktop"),+ ("uv", "/"),+ ]++ for item in updates:+ assert item["schedule"] == {+ "interval": "weekly",+ "day": "monday",+ "time": "09:00",+ "timezone": "Asia/Shanghai",+ }+ assert item["open-pull-requests-limit"] == 3+ assert set(item["groups"][next(iter(item["groups"]))]["update-types"]) == {"minor", "patch"}+ assert "auto-merge" not in item+ assert "automerge" not in item++ uv = updates[-1]+ assert uv["package-ecosystem"] == "uv"+ assert uv["versioning-strategy"] == "increase"+ assert uv["ignore"] == [{"dependency-name": "claude-agent-sdk"}]diff --git a/tests/test_model_hub_engine_build.py b/tests/test_model_hub_engine_build.pyindex 061022db8..c09cf0bd7 100644--- a/tests/test_model_hub_engine_build.py+++ b/tests/test_model_hub_engine_build.py@@ -89,6 +89,17 @@ def _manifest(tmp_path: Path, *, source_sha: str, patches: list[Path]) -> Path:return path+def _candidate_manifest(tmp_path: Path, *, source_sha: str, patches: list[Path]) -> Path:+ path = _manifest(tmp_path, source_sha=source_sha, patches=patches)+ payload = json.loads(path.read_text(encoding="utf-8"))+ payload["assets"] = [+ {"platform": asset["platform"], "url": asset["url"]}+ for asset in payload["assets"]+ ]+ path.write_text(json.dumps(payload), encoding="utf-8")+ return path++@pytest.mark.parametrize(("patch_mode", "wrong_pinned_size"),[("pinned", False), ("pinned", True), ("changed", False)],@@ -224,3 +235,241 @@ def test_build_source_release_applies_patches_in_order_and_materializes_six_targ)guard.verify_release_assets(manifest, output)+++def test_candidate_mode_writes_real_digests_and_owned_urls_without_pinned_hashes(+ tmp_path: Path,+ monkeypatch,+) -> None:+ source = tmp_path / "source"+ (source / "cmd" / "server").mkdir(parents=True)+ for name, data in FIXTURE_DOCUMENTS.items():+ (source / name).write_bytes(data)+ subprocess.run(["git", "init", "--quiet", str(source)], check=True)+ subprocess.run(+ ["git", "-C", str(source), "config", "user.email", "[email protected]"],+ check=True,+ )+ subprocess.run(+ ["git", "-C", str(source), "config", "user.name", "Test"],+ check=True,+ )+ subprocess.run(["git", "-C", str(source), "add", "."], check=True)+ subprocess.run(["git", "-C", str(source), "commit", "--quiet", "-m", "fixture"], check=True)+ source_sha = subprocess.check_output(+ ["git", "-C", str(source), "rev-parse", "HEAD"],+ text=True,+ ).strip()+ patches = [+ _patch(+ tmp_path / "first.patch",+ "diff --git a/patched-marker.txt b/patched-marker.txt",+ "new file mode 100644",+ "--- /dev/null",+ "+++ b/patched-marker.txt",+ "@@ -0,0 +1 @@",+ "+patched",+ ),+ _patch(+ tmp_path / "second.patch",+ "diff --git a/patched-marker.txt b/patched-marker.txt",+ "--- a/patched-marker.txt",+ "+++ b/patched-marker.txt",+ "@@ -1 +1 @@",+ "-patched",+ "+patched twice",+ ),+ ]+ manifest = _candidate_manifest(tmp_path, source_sha=source_sha, patches=patches)+ monkeypatch.setattr(builder, "REPO_ROOT", tmp_path)+ for name, value in {+ "GO386": "softfloat",+ "GOAMD64": "v4",+ "GOARM": "7,hardfloat",+ "GOARM64": "v9.5,lse,crypto",+ "GOMIPS": "softfloat",+ "GOMIPS64": "softfloat",+ "GOPPC64": "power10",+ "GORISCV64": "rva23u64",+ "GOWASM": "satconv",+ "GOFLAGS": "-tags=hostile",+ "GOEXPERIMENT": "hostile",+ "GOFIPS140": "v1.0.0",+ "GODEBUG": "hostile=1",+ "GO111MODULE": "off",+ "GO_EXTLINK_ENABLED": "1",+ "GOTOOLCHAIN": "auto",+ "GOWORK": "hostile.work",+ }.items():+ monkeypatch.setenv(name, value)+ commands: list[tuple[list[str], dict[str, str] | None]] = []+ real_run = builder._run++ def fake_run(command, *, cwd=None, env=None):+ commands.append((list(command), dict(env) if env is not None else None))+ if command[:2] == ["go", "version"]:+ return "go version go1.26.0 darwin/arm64\n"+ if command[:2] == ["go", "build"]:+ marker = cwd / "patched-marker.txt"+ if marker.exists():+ assert marker.read_text(encoding="utf-8") == "patched twice\n"+ binary = Path(command[command.index("-o") + 1])+ binary.write_bytes(FIXTURE_BINARY)+ return ""+ if Path(command[0]).name.startswith("cli-proxy-api") and command[1:] == ["--help"]:+ return "CLIProxyAPI Version: v7.3.16, Commit: fixture\n"+ return real_run(command, cwd=cwd, env=env)++ monkeypatch.setattr(builder, "_run", fake_run)+ candidate_bytes = manifest.read_bytes()+ malformed = json.loads(candidate_bytes)+ malformed["assets"][0]["sha256"] = "0" * 64+ manifest.write_text(json.dumps(malformed), encoding="utf-8")+ with pytest.raises(builder.BuildError, match="must not contain pinned asset digests"):+ builder.build_source_release(+ manifest,+ tmp_path / "rejected-candidate-output",+ candidate=True,+ source_repository=str(source),+ go_binary="go",+ )+ manifest.write_bytes(candidate_bytes)+ missing_toolchain = json.loads(candidate_bytes)+ missing_toolchain["build"].pop("go_version")+ manifest.write_text(json.dumps(missing_toolchain), encoding="utf-8")+ with pytest.raises(builder.BuildError, match="must record an exact go_version"):+ builder.build_source_release(+ manifest,+ tmp_path / "missing-toolchain-output",+ candidate=True,+ source_repository=str(source),+ go_binary="go",+ )+ manifest.write_bytes(candidate_bytes)++ output = tmp_path / "candidate-output"+ generated_manifest = builder.build_source_release(+ manifest,+ output,+ candidate=True,+ source_repository=str(source),+ go_binary="go",+ )++ candidate_payload = json.loads(manifest.read_text(encoding="utf-8"))+ generated_payload = json.loads(generated_manifest.read_text(encoding="utf-8"))+ assert all(+ not any(key in asset for key in ("size_bytes", "sha256", "binary_sha256"))+ for asset in candidate_payload["assets"]+ )+ assert generated_payload["build"]["cgo_enabled"] is False+ assert generated_payload["build"]["trimpath"] is True+ assert generated_payload["build"]["buildvcs"] is False+ assert {env["GOFLAGS"] for command, env in commands if command[:2] == ["go", "build"]} == {""}+ assert {env["GOEXPERIMENT"] for command, env in commands if command[:2] == ["go", "build"]} == {""}+ assert {env["GOFIPS140"] for command, env in commands if command[:2] == ["go", "build"]} == {"off"}+ assert {env["GODEBUG"] for command, env in commands if command[:2] == ["go", "build"]} == {""}+ assert {env["GO111MODULE"] for command, env in commands if command[:2] == ["go", "build"]} == {"on"}+ assert {env["GO_EXTLINK_ENABLED"] for command, env in commands if command[:2] == ["go", "build"]} == {"0"}+ assert {env["GOENV"] for command, env in commands if command[:2] == ["go", "build"]} == {"off"}+ assert {env["GOTOOLCHAIN"] for command, env in commands if command[:2] == ["go", "build"]} == {"local"}+ assert {env["GOWORK"] for command, env in commands if command[:2] == ["go", "build"]} == {"off"}+ for command, env in commands:+ if command[:2] != ["go", "build"]:+ continue+ expected_level = "GOAMD64" if env["GOARCH"] == "amd64" else "GOARM64"+ expected_value = "v1" if expected_level == "GOAMD64" else "v8.0"+ assert env[expected_level] == expected_value+ assert all(+ env.get(name) is None+ for name in builder._GO_ARCHITECTURE_LEVEL_VARS+ if name != expected_level+ )+ version_envs = [+ env for command, env in commands if command[:2] == ["go", "version"]+ ]+ assert version_envs+ assert all(env["GOENV"] == "off" for env in version_envs)+ assert all(env["GOTOOLCHAIN"] == "local" for env in version_envs)+ assert all(env["GO111MODULE"] == "on" for env in version_envs)+ assert {asset["platform"] for asset in generated_payload["assets"]} == set(FIXTURE_TARGETS)+ assert generated_payload["assets"] != candidate_payload["assets"]+ for asset in generated_payload["assets"]:+ archive = output / Path(asset["url"]).name+ assert asset["url"].startswith(+ f"{guard.OWNED_RELEASE_ROOT}/{generated_payload['asset_release_tag']}/"+ )+ assert asset["size_bytes"] == archive.stat().st_size+ assert asset["sha256"] == hashlib.sha256(archive.read_bytes()).hexdigest()+ with tarfile.open(archive, "r:gz") as bundle:+ binary = bundle.extractfile(asset["bin_path"])+ assert binary is not None+ assert asset["binary_sha256"] == hashlib.sha256(binary.read()).hexdigest()++ assert guard.verify_release_assets(generated_manifest, output).version == "v7.3.16"++ patchless = json.loads(candidate_bytes)+ patchless["build"]["patches"] = []+ manifest.write_text(json.dumps(patchless), encoding="utf-8")+ patchless_output = tmp_path / "patchless-candidate-output"+ patchless_manifest = builder.build_source_release(+ manifest,+ patchless_output,+ candidate=True,+ source_repository=str(source),+ go_binary="go",+ )+ assert guard.verify_release_assets(patchless_manifest, patchless_output).version == "v7.3.16"+++ ("field", "value"),+ [("cgo_enabled", True), ("trimpath", False), ("buildvcs", True)],+)+def test_candidate_rejects_contradictory_fixed_build_metadata(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ field: str,+ value: bool,+) -> None:+ source = tmp_path / "source"+ (source / "cmd" / "server").mkdir(parents=True)+ for name, data in FIXTURE_DOCUMENTS.items():+ (source / name).write_bytes(data)+ subprocess.run(["git", "init", "--quiet", str(source)], check=True)+ subprocess.run(+ ["git", "-C", str(source), "config", "user.email", "[email protected]"],+ check=True,+ )+ subprocess.run(+ ["git", "-C", str(source), "config", "user.name", "Test"],+ check=True,+ )+ subprocess.run(["git", "-C", str(source), "add", "."], check=True)+ subprocess.run(["git", "-C", str(source), "commit", "--quiet", "-m", "fixture"], check=True)+ source_sha = subprocess.check_output(+ ["git", "-C", str(source), "rev-parse", "HEAD"],+ text=True,+ ).strip()+ manifest = _candidate_manifest(tmp_path, source_sha=source_sha, patches=[])+ payload = json.loads(manifest.read_text(encoding="utf-8"))+ payload["build"][field] = value+ manifest.write_text(json.dumps(payload), encoding="utf-8")+ monkeypatch.setattr(builder, "REPO_ROOT", tmp_path)+ commands: list[list[str]] = []++ def unexpected_run(command, *, cwd=None, env=None):+ del cwd, env+ commands.append(list(command))+ raise AssertionError("candidate metadata should fail before invoking a command")++ monkeypatch.setattr(builder, "_run", unexpected_run)+ with pytest.raises(builder.BuildError, match=field):+ builder.build_source_release(+ manifest,+ tmp_path / f"rejected-{field}",+ candidate=True,+ source_repository=str(source),+ go_binary="go",+ )+ assert commands == []diff --git a/tests/test_model_hub_engine_release_guard.py b/tests/test_model_hub_engine_release_guard.pyindex bed6f5068..65f28b578 100644--- a/tests/test_model_hub_engine_release_guard.py+++ b/tests/test_model_hub_engine_release_guard.py@@ -4,7 +4,10 @@ import gzipimport hashlibimport ioimport json+import os+import shutilimport subprocess+import sysimport tarfilefrom pathlib import Path@@ -84,6 +87,136 @@ def _fake_download(remote: dict[str, bytes]):return download+def test_manifest_go_version_cli_accepts_alternate_stable_pin(tmp_path: Path) -> None:+ manifest_path, _owned, _built = _manifest(tmp_path)+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["build"] = {"go_version": "go1.27.1"}+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")++ result = subprocess.run(+ [+ sys.executable,+ str(guard.REPO_ROOT / "scripts/model_hub_engine_release_guard.py"),+ "--manifest",+ str(manifest_path),+ "go-version",+ ],+ check=False,+ capture_output=True,+ text=True,+ )++ assert result.returncode == 0+ assert result.stdout.strip() == "go1.27.1"+++ "build",+ [{}, {"go_version": "1.27.1"}, {"go_version": "go1.27"}, {"go_version": "go1.27.1-beta1"}],+)+def test_manifest_go_version_cli_rejects_missing_or_nonstable_pin(tmp_path: Path, build: dict) -> None:+ manifest_path, _owned, _built = _manifest(tmp_path)+ payload = json.loads(manifest_path.read_text(encoding="utf-8"))+ payload["build"] = build+ manifest_path.write_text(json.dumps(payload), encoding="utf-8")++ result = subprocess.run(+ [+ sys.executable,+ str(guard.REPO_ROOT / "scripts/model_hub_engine_release_guard.py"),+ "--manifest",+ str(manifest_path),+ "go-version",+ ],+ check=False,+ capture_output=True,+ text=True,+ )++ assert result.returncode == 1+ assert "exact stable Go version" in result.stderr+++def _run_workflow_go_pin_step(tmp_path: Path, build: dict | None) -> tuple[subprocess.CompletedProcess[str], bytes, bytes]:+ import yaml++ workflow = yaml.safe_load(+ (guard.REPO_ROOT / ".github/workflows/model-hub-engine-release-guard.yml").read_text(+ encoding="utf-8"+ )+ )+ steps = workflow["jobs"]["build-patched-source"]["steps"]+ producer = next(step for step in steps if step.get("id") == "go_pin")["run"]+ staged = tmp_path / "workflow"+ (staged / "scripts").mkdir(parents=True)+ (staged / "vibe/model_hub_runtime").mkdir(parents=True)+ shutil.copy2(+ guard.REPO_ROOT / "scripts/model_hub_engine_release_guard.py",+ staged / "scripts/model_hub_engine_release_guard.py",+ )+ manifest = staged / "vibe/model_hub_runtime/cliproxyapi_manifest.json"+ payload = {"build": build} if build is not None else {}+ manifest.write_text(json.dumps(payload) + "\n", encoding="utf-8")+ before = manifest.read_bytes()+ output = staged / "github-output"+ environment = os.environ.copy()+ environment["GITHUB_OUTPUT"] = str(output)+ result = subprocess.run(+ ["bash", "-euo", "pipefail", "-c", producer],+ cwd=staged,+ env=environment,+ check=False,+ capture_output=True,+ text=True,+ )+ return result, output.read_bytes() if output.exists() else b"", before+++def test_publication_workflow_produces_bare_go_semver_for_setup_go(tmp_path: Path) -> None:+ import yaml++ workflow = yaml.safe_load(+ (guard.REPO_ROOT / ".github/workflows/model-hub-engine-release-guard.yml").read_text(+ encoding="utf-8"+ )+ )+ steps = workflow["jobs"]["build-patched-source"]["steps"]+ resolve_index = next(index for index, step in enumerate(steps) if step.get("id") == "go_pin")+ resolve = steps[resolve_index]+ setup_index = next(+ index for index, step in enumerate(steps) if str(step.get("uses", "")).startswith("actions/setup-go@")+ )+ setup = steps[setup_index]++ assert resolve_index < setup_index+ assert "raw_go_version" in resolve["run"]+ assert "${raw_go_version#go}" in resolve["run"]+ assert setup["with"]["go-version"] == "${{ steps.go_pin.outputs.go_version }}"+ assert 'go-version: "1.26.9"' not in (guard.REPO_ROOT / ".github/workflows/model-hub-engine-release-guard.yml").read_text(+ encoding="utf-8"+ )++ for raw_version, expected in (("go1.26.9", "1.26.9"), ("go1.27.1", "1.27.1")):+ result, output, before = _run_workflow_go_pin_step(tmp_path / raw_version, {"go_version": raw_version})+ assert result.returncode == 0, result.stderr+ assert output == f"go_version={expected}\n".encode()+ assert before == (tmp_path / raw_version / "workflow/vibe/model_hub_runtime/cliproxyapi_manifest.json").read_bytes()+++ "build",+ [None, {}, {"go_version": "1.27.1"}, {"go_version": "go1.27"}, {"go_version": "go1.27.1-beta1"}],+)+def test_publication_workflow_rejects_invalid_go_pin_without_consumer_output(+ tmp_path: Path,+ build: dict | None,+) -> None:+ result, output, before = _run_workflow_go_pin_step(tmp_path, build)+ assert result.returncode != 0+ assert output == b""+ assert before == (tmp_path / "workflow/vibe/model_hub_runtime/cliproxyapi_manifest.json").read_bytes()++def test_fetch_owned_release_materializes_exact_verified_assets(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,