Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(memory): distribute companion from GitHub releases (#1994)

Call Whitebb70e063d003
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index bd6ab030d..21b304e42 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -407,6 +407,7 @@ jobs:
path: release-automation
sparse-checkout: |
scripts/github_release.py
+ scripts/release_package_version.py
tests/test_memory_distribution.py
sparse-checkout-cone-mode: false
@@ -445,6 +446,7 @@ jobs:
GH_TOKEN: ${{ github.token }}
shell: bash
run: |
+ set -euo pipefail
TAG="${{ needs.resolve-tag.outputs.tag }}"
python release-automation/scripts/github_release.py ensure-draft \
--repo "$GITHUB_REPOSITORY" \
@@ -452,35 +454,46 @@ jobs:
--title "$TAG" \
--notes "Release assets for $TAG."
- # Runtime archives + manifests are IMMUTABLE per tag and must NOT be
- # re-clobbered. Builds are normalized and pinned, but the wheel published
- # to PyPI is itself immutable. Replacing any hosted runtime byte after that
- # point would desync the wheel's manifest and break integrity checks.
- #
- # Verify immutability BEFORE mutating ANY release asset (including dist/*), so a
- # mismatch fails the job without having already replaced the wheel/sdist. Upload
- # each runtime asset only if absent; if it already exists, require byte-identity.
+ # All artifacts are immutable per tag, including the GitHub-only
+ # companion. Compare every existing byte BEFORE uploading anything.
existing="$(gh release view "$TAG" --repo "${GITHUB_REPOSITORY}" --json assets --jq '.assets[].name')"
tmp="$(mktemp -d)"
+ trap 'rm -r -- "$tmp"' EXIT
runtime_to_upload=()
+ package_to_upload=()
+ package_paths=(
+ dist/avibe_os-*.whl dist/avibe_os-*.tar.gz
+ dist/avibe_memory-*.whl dist/avibe_memory-*.tar.gz
+ )
+ # The existing v3.0.x shim remains part of those releases only.
+ for path in dist/vibe_remote-*.whl dist/vibe_remote-*.tar.gz; do
+ if [ -e "$path" ]; then package_paths+=("$path"); fi
+ done
for path in \
runtime-artifacts/vibe-show-runtime-node-*.tgz \
runtime-artifacts/show-runtime-manifest.json \
runtime-artifacts/memory-runtime-*.tar.gz \
- runtime-artifacts/memory-runtime-manifest.json; do
+ runtime-artifacts/memory-runtime-manifest.json \
+ "${package_paths[@]}"; do
+ if [ ! -s "$path" ]; then
+ echo "::error::Missing or empty release asset: $path" >&2
+ exit 1
+ fi
name="$(basename "$path")"
if grep -qxF "$name" <<<"$existing"; then
- rm -f "$tmp/$name"
gh release download "$TAG" --repo "${GITHUB_REPOSITORY}" --pattern "$name" --dir "$tmp" --clobber
if cmp -s "$tmp/$name" "$path"; then
echo "Release asset '$name' already present and byte-identical; skipping (immutable per tag)."
else
echo "::error::Release asset '$name' already exists for $TAG but differs from this run's build." >&2
- echo "::error::Overwriting it would desync the release from the PyPI wheel's manifest. Cut a NEW version instead of re-running the release." >&2
+ echo "::error::Published package and runtime bytes are immutable; cut a new version." >&2
exit 1
fi
else
- runtime_to_upload+=("$path")
+ case "$path" in
+ runtime-artifacts/*) runtime_to_upload+=("$path") ;;
+ *) package_to_upload+=("$path") ;;
+ esac
fi
done
@@ -488,8 +501,9 @@ jobs:
if [ "${#runtime_to_upload[@]}" -gt 0 ]; then
gh release upload "$TAG" --repo "${GITHUB_REPOSITORY}" "${runtime_to_upload[@]}"
fi
- # Python distributions are safe to refresh (PyPI itself is skip-existing).
- gh release upload "$TAG" --repo "${GITHUB_REPOSITORY}" dist/* --clobber
+ if [ "${#package_to_upload[@]}" -gt 0 ]; then
+ gh release upload "$TAG" --repo "${GITHUB_REPOSITORY}" "${package_to_upload[@]}"
+ fi
- name: Upload artifacts
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6
@@ -497,40 +511,11 @@ jobs:
name: dist
path: dist/
- publish-avibe-memory:
- needs:
- - build
- - finalize-github-release
- runs-on: ubuntu-latest
- environment: pypi-avibe-memory
- permissions:
- id-token: write # Required for trusted publishing
- steps:
- - name: Download artifacts
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
- with:
- name: dist
- path: dist/
-
- - name: Keep avibe-memory distributions only
- shell: bash
- run: |
- find dist -type f ! \( -name 'avibe_memory-*' -o -name 'avibe-memory-*' \) -delete
- test -n "$(find dist -maxdepth 1 -type f -name 'avibe_memory-*.whl' -print -quit)"
- test -n "$(find dist -maxdepth 1 -type f -name 'avibe_memory-*.tar.gz' -print -quit)"
-
- - name: Publish avibe-memory to PyPI
- uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1
- with:
- skip-existing: true
- # Uses trusted publishing (OIDC), no API token needed
- # Configure at: https://pypi.org/manage/project/avibe-memory/settings/publishing/
-
- verify-avibe-memory-pypi:
+ verify-avibe-memory-release:
needs:
- resolve-tag
- build
- - publish-avibe-memory
+ - finalize-github-release
runs-on: ubuntu-latest
steps:
- name: Checkout
@@ -549,59 +534,38 @@ jobs:
name: dist
path: dist/
- - name: Verify PyPI serves the exact avibe-memory wheel
+ - name: Verify public GitHub companion distributions
shell: bash
env:
RELEASE_TAG: ${{ needs.resolve-tag.outputs.tag }}
run: |
set -euo pipefail
- shopt -s nullglob
-
- staged_wheels=(dist/avibe_memory-*.whl)
- if [ "${#staged_wheels[@]}" -ne 1 ]; then
- echo "::error::Expected exactly one staged avibe-memory wheel, found ${#staged_wheels[@]}." >&2
- exit 1
- fi
-
package_version="$(python scripts/release_package_version.py "$RELEASE_TAG")"
- download_dir="$RUNNER_TEMP/avibe-memory-pypi"
- mkdir -p "$download_dir"
-
- for attempt in {1..12}; do
- find "$download_dir" -mindepth 1 -maxdepth 1 -type f -delete
- if python -m pip --isolated download \
- --index-url https://pypi.org/simple \
- --disable-pip-version-check \
- --no-deps \
- --no-cache-dir \
- --only-binary=:all: \
- --dest "$download_dir" \
- "avibe-memory==$package_version"; then
- public_wheels=("$download_dir"/avibe_memory-*.whl)
- if [ "${#public_wheels[@]}" -ne 1 ]; then
- echo "::error::Expected exactly one public avibe-memory wheel, found ${#public_wheels[@]}." >&2
- exit 1
- fi
- if cmp -s "${staged_wheels[0]}" "${public_wheels[0]}"; then
- echo "PyPI serves the exact staged avibe-memory wheel for $package_version."
- exit 0
- fi
- echo "::error::PyPI already serves a non-identical avibe-memory wheel for $package_version." >&2
- exit 1
- fi
-
- if [ "$attempt" -eq 12 ]; then
- echo "::error::PyPI did not serve the avibe-memory wheel for $package_version after $attempt attempts." >&2
+ download_dir="$(mktemp -d "$RUNNER_TEMP/avibe-memory-release.XXXXXXXX")"
+ trap 'rm -r -- "$download_dir"' EXIT
+ for asset in "avibe_memory-${package_version}-py3-none-any.whl" "avibe_memory-${package_version}.tar.gz"; do
+ test -s "dist/$asset"
+ # Anonymous HTTPS fetch proves availability to end-user installers,
+ # not merely to the workflow's authenticated GitHub identity.
+ # Fresh public URLs may briefly return 404. Retry only this
+ # idempotent download, within finite attempt and time bounds.
+ curl --fail --location --retry 5 --retry-all-errors --retry-delay 2 \
+ --retry-max-time 60 --connect-timeout 10 --max-time 30 \
+ --proto '=https' --proto-redir '=https' \
+ --output "$download_dir/$asset" \
+ "https://github.com/${GITHUB_REPOSITORY}/releases/download/${RELEASE_TAG}/${asset}"
+ if ! cmp -s "dist/$asset" "$download_dir/$asset"; then
+ echo "::error::GitHub serves a non-identical companion asset: $asset" >&2
exit 1
fi
- sleep 10
done
+ echo "GitHub serves both exact staged companion distributions for $package_version."
publish-avibe-os:
needs:
- build
- finalize-github-release
- - verify-avibe-memory-pypi
+ - verify-avibe-memory-release
runs-on: ubuntu-latest
environment: pypi
permissions:
diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.yml
index f84467f40..021059d05 100644
--- a/.github/workflows/release_ai.yml
+++ b/.github/workflows/release_ai.yml
@@ -690,26 +690,35 @@ jobs:
temporary="$(mktemp -d)"
trap 'rm -rf "$temporary"' EXIT
runtime_to_upload=()
- runtime_paths=(
+ package_to_upload=()
+ asset_paths=(
dist/vibe-show-runtime-node-*.tgz
dist/show-runtime-manifest.json
dist/memory-runtime-*.tar.gz
dist/memory-runtime-manifest.json
+ dist/avibe_os-*.whl dist/avibe_os-*.tar.gz
+ dist/avibe_memory-*.whl dist/avibe_memory-*.tar.gz
)
- for path in "${runtime_paths[@]}"; do
- if [ ! -f "$path" ]; then
- echo "::error::Missing GitHub-only runtime release asset: $path" >&2
+ # Packages and runtimes share the same immutable publication boundary.
+ # Validate every existing byte before uploading even a missing asset.
+ for path in "${asset_paths[@]}"; do
+ if [ ! -s "$path" ]; then
+ echo "::error::Missing or empty GitHub-only release asset: $path" >&2
exit 1
fi
name="$(basename "$path")"
if grep -qxF "$name" <<<"$existing"; then
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" --pattern "$name" --dir "$temporary" --clobber
if ! cmp -s "$temporary/$name" "$path"; then
- echo "::error::Immutable runtime asset '$name' differs for $TAG; cut a new version." >&2
+ echo "::error::Immutable release asset '$name' differs for $TAG; cut a new version." >&2
exit 1
fi
else
- runtime_to_upload+=("$path")
+ case "$name" in
+ vibe-show-runtime-node-*.tgz|show-runtime-manifest.json|memory-runtime-*.tar.gz|memory-runtime-manifest.json)
+ runtime_to_upload+=("$path") ;;
+ *) package_to_upload+=("$path") ;;
+ esac
fi
done
@@ -719,19 +728,9 @@ jobs:
gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" "${runtime_to_upload[@]}"
fi
- package_assets=()
- for path in dist/*; do
- case "$(basename "$path")" in
- vibe-show-runtime-node-*.tgz|show-runtime-manifest.json|memory-runtime-*.tar.gz|memory-runtime-manifest.json)
- ;;
- *) package_assets+=("$path") ;;
- esac
- done
- if [ "${#package_assets[@]}" -eq 0 ]; then
- echo "::error::No Python release assets were built." >&2
- exit 1
+ if [ "${#package_to_upload[@]}" -gt 0 ]; then
+ gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" "${package_to_upload[@]}"
fi
- gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" "${package_assets[@]}" --clobber
python scripts/github_release.py finalize \
--repo "$GITHUB_REPOSITORY" \
diff --git a/docs/plans/memory-github-distribution.md b/docs/plans/memory-github-distribution.md
new file mode 100644
index 000000000..a763f93bb
--- /dev/null
+++ b/docs/plans/memory-github-distribution.md
@@ -0,0 +1,67 @@
+# Memory as a GitHub Release companion
+
+## Decision and scope
+
+The owner approved GitHub-only distribution of the optional Memory package on
+2026-09-16. Core remains on PyPI. This replaces the separate Memory PyPI
+publisher, not Memory itself. The root owns implementation, gated integration,
+and gated publication. The owner explicitly chose replacement of the partially
+published GitHub v3.1.0 on 2026-09-16, not a new version. That one-time operation
+must preserve prior publication evidence and reconfirm PyPI absence before
+withdrawal. Generic workflows still reject changed existing assets; they do
+not implement withdrawal or an overwrite bypass. This change does not install
+or restart local Avibe.
+
+## Invariants
+
+- Both workflows still build and validate both wheel/sdist pairs and all runtime
+ assets. The companion requires exactly the same normalized core version.
+- Core metadata has no Memory index dependency. The old `memory` extra remains
+ an empty compatibility spelling; enabling Memory uses the existing package
+ reconciler, not Python extras.
+- A PyPI core install selects the companion wheel at official `v<version>`.
+ Official tags must use that canonical normalized spelling; the shared
+ publication owner rejects aliases before any release mutation, even when
+ a workflow dispatch builds older source. Existing official tags are canonical.
+ An exact core wheel from this repository's GitHub Release selects its same
+ tag, including `gh-v` previews. Forward upgrades derive this from their
+ target artifact, never the currently installed preview's origin.
+ Public dev versions follow the same rule as other releases: index installs
+ use the canonical official tag, and a verified GitHub wheel retains its
+ exact origin. A dev suffix is not source provenance or proof of availability.
+ Unrecognized origins cannot redirect Memory; the canonical official URL
+ remains the fallback. Existing preflights must resolve the actual pair
+ before activation. Local-version and source-build guards remain unchanged.
+- Every install/preflight command uses the explicit companion source. Missing
+ assets fail before activating a new installation; there is no PyPI fallback
+ for Memory, new updater, rollback protocol, or runtime preparation.
+- Official release order is complete published GitHub assets, anonymous public
+ byte verification of the companion wheel and sdist, then core PyPI.
+ Anonymous download propagation (including transient 404) has bounded
+ retries. Successfully downloaded but different bytes fail immediately.
+- Both upload workflows compare all existing package/runtime bytes before any
+ asset upload, retain identical assets, and upload only missing assets.
+ Artifact filenames use normalized package versions; release URLs retain the
+ original supported tag spelling.
+- Existing source/editable workflows remain local and preserve the new Memory
+ subprocess-lifecycle fix and dependency floor.
+
+## Migration boundary
+
+Older released updaters request Memory from PyPI before the new core can run.
+They cannot be transparently repaired by new code. Users of that path must
+update core through the official installer/core-only installation entry first.
+On the next normal startup, enabled Memory uses the existing reconciler to
+obtain the matching GitHub companion. Disabled Memory remains core-only.
+Do not promise every old client's in-place update works. The released 3.0.13
+core-only first hop is exercised separately; the next startup must obtain
+Memory through its GitHub URL, not the package index.
+
+## Validation
+
+Exercise source selection, false origins, exact and forward pip/uv plans,
+preflight failure, core-only installs, and existing reconciliation behavior.
+Build genuine wheel/sdist pairs at the proposed release version and run the
+artifact-bound matrix with no skipped cases. Real isolated resolver tests must
+place Memory outside the index and preserve exact peer selection in the
+presence of newer decoys. Keep Windows/runtime/build/release CI gates.
diff --git a/docs/plans/memory-plugin-isolation-refactor.md b/docs/plans/memory-plugin-isolation-refactor.md
index 6989311f7..ccf9978e9 100644
--- a/docs/plans/memory-plugin-isolation-refactor.md
+++ b/docs/plans/memory-plugin-isolation-refactor.md
@@ -6,6 +6,9 @@
>
> `docs/MEMORY.md` is the current product contract. This plan records the
> completed isolation waves and their retained boundaries.
+> The PyPI/extra distribution mechanics recorded here are superseded by
+> [Memory as a GitHub Release companion](memory-github-distribution.md);
+> the isolation, lazy loading, startup convergence, and data boundaries remain.
## Decision
diff --git a/docs/plans/memory-wave3c-release-migration-contract.md b/docs/plans/memory-wave3c-release-migration-contract.md
index cdf176ec7..f5861808e 100644
--- a/docs/plans/memory-wave3c-release-migration-contract.md
+++ b/docs/plans/memory-wave3c-release-migration-contract.md
@@ -50,13 +50,12 @@ finalizer:
6. `Release (AI Notes)` may update the Draft notes and assets, but it never
publishes an official release.
7. `Publish to PyPI` verifies the exact notes run and the asset-complete Draft,
- then publishes the GitHub Release before either distribution reaches PyPI.
-8. Publish only `avibe-memory` through its trusted-publishing environment with
- skip-existing semantics. Retry a direct PyPI wheel download without
- dependencies or cache and byte-compare it with the staged wheel. An existing
- non-identical wheel fails closed.
+ then publishes the GitHub Release before core reaches PyPI.
+8. Fetch the companion wheel and sdist anonymously from that GitHub Release
+ and byte-compare both with the staged artifacts. Missing or non-identical
+ public bytes fail closed. Memory is not published to PyPI.
9. Publish only `avibe-os` through its existing trusted-publishing environment
- after the public `avibe-memory` wheel verification succeeds.
+ after public GitHub companion verification succeeds.
A release failure resumes through the same tag and Draft only when all existing
runtime bytes are identical. It does not mint a replacement identity, publish
@@ -128,10 +127,8 @@ window, and the retained backup remains tied to one exact manifest hash.
- Do not pre-create or manually edit an official `v*` GitHub Release; the
annotated tag and workflows own release state.
-- Before the first `avibe-memory` publication, configure its PyPI
- pending/trusted publisher for repository `avibe-bot/avibe`, workflow
- `publish.yml`, and GitHub environment `pypi-avibe-memory`. This external
- configuration is a required operator action and is not performed by CI.
+- Memory is a GitHub-only companion; no Memory PyPI publisher is needed.
+ Core retains its existing trusted publisher.
- Do not overwrite a mismatched runtime asset, weaken a digest, bypass the
public re-fetch, or continue to PyPI before the GitHub Release is published.
- Do not classify policy exclusions as recoverable missing bytes.
diff --git a/docs/plans/preview-install-convergence.md b/docs/plans/preview-install-convergence.md
index 5fa3cdbd9..fee4eac04 100644
--- a/docs/plans/preview-install-convergence.md
+++ b/docs/plans/preview-install-convergence.md
@@ -2,6 +2,10 @@
> Status: implemented (scenario MEMORY-INDEP-027)
>
+> Historical implementation record. The origin-aware preview behavior remains;
+> the official PyPI companion assumptions below are superseded by
+> [Memory as a GitHub Release companion](memory-github-distribution.md).
+>
> Scope: a `gh-v*` preview install or preview-to-preview upgrade is one
> copyable `uv tool install` command for the core wheel; the Memory companion
> converges automatically afterward. No CLI surface changes. The official
diff --git a/hatch_build.py b/hatch_build.py
index beaa6a662..cabdc5c56 100644
--- a/hatch_build.py
+++ b/hatch_build.py
@@ -12,7 +12,6 @@ ROUTER_PATH = "vibe/show_router.tsx"
_VALIDATION = run_path(str(Path(__file__).parent / "scripts" / "show_runtime_manifest_asset.py"))
validate_manifest_bytes = _VALIDATION["validate_manifest_bytes"]
validate_manifest_file = _VALIDATION["validate_manifest_file"]
-pin_peer_dependency = run_path(str(Path(__file__).parent / "hatch_exact_peer.py"))["pin_peer_dependency"]
class CustomBuildHook(BuildHookInterface):
@@ -44,10 +43,3 @@ class CustomBuildHook(BuildHookInterface):
validate_manifest_bytes(content)
except ValueError as exc:
raise RuntimeError(f"Built wheel contains an invalid {MANIFEST_WHEEL_PATH}: {exc}") from exc
- pin_peer_dependency(
- artifact_path,
- project_name="avibe-os",
- peer_name="avibe-memory",
- package_version=self.metadata.version,
- peer_extra="memory",
- )
diff --git a/packaging/avibe-memory/README.md b/packaging/avibe-memory/README.md
index 8c9b3debe..a65ab8f22 100644
--- a/packaging/avibe-memory/README.md
+++ b/packaging/avibe-memory/README.md
@@ -1,23 +1,17 @@
# avibe-memory
`avibe-memory` is the optional in-process Memory implementation for `avibe-os`.
-Install it through the host extra so the resolver selects a compatible pair:
+It is distributed only as a same-version GitHub Release wheel and sdist, not
+on PyPI. Install core normally and enable Memory in Avibe; the existing
+Dependencies reconciler obtains its matching companion from GitHub.
-```console
-pip install "avibe-os[memory]"
-```
+Every built companion requires `avibe-os==X` at its own normalized version X.
+Core has no indexed Memory dependency. Its empty `memory` extra is retained
+only as a compatibility spelling; it does not install the companion.
-The `3.0.x` package line implements Memory runtime protocol `1`. Every built
-wheel and sdist requires the peer distribution at exactly the same normalized
-version: `avibe-memory==X` requires `avibe-os==X`, and the `memory` extra on
-`avibe-os==X` requires `avibe-memory==X`. This is the same identity used by the
-Dependencies readiness check.
-
-The source projects retain the `>=3.0.14.dev0,<3.1` compatibility window so a
-source or editable checkout can use an available development peer before that
-exact version is published. The Hatch build hooks replace that development
-range in every publishable artifact and fail the build unless the resulting
-metadata contains the reciprocal exact pin.
+The companion source retains the `>=3.0.14.dev0,<4` compatibility window for
+source/editable development. Its Hatch build hook replaces that range in every
+publishable artifact and fails unless the metadata contains the exact core pin.
## Distribution contract
@@ -36,19 +30,22 @@ An official release follows this forward-only order:
1. Verify the runtime assets, both distribution pairs, and their shared version.
2. Finalize the asset-complete GitHub Release before any PyPI publication.
-3. Publish `avibe-memory` with trusted publishing and skip-existing semantics.
-4. Retry a no-dependency, no-cache PyPI download and require its wheel to be
- byte-identical to the staged wheel.
+3. Download the public GitHub companion wheel and sdist anonymously over HTTPS.
+4. Require the wheel to be byte-identical to the staged wheel and likewise
+ require exact sdist bytes.
5. Publish `avibe-os` only after that verification succeeds.
A `gh-v*` GitHub-only release attaches both wheel/sdist pairs and the existing
runtime assets without publishing either distribution to PyPI.
-The first official publication requires the PyPI pending/trusted publisher for
-project `avibe-memory` to match repository `avibe-bot/avibe`, workflow
-`publish.yml`, and GitHub environment `pypi-avibe-memory`. That external
-configuration is an operator prerequisite; the repository workflow does not
-create it.
+No Memory PyPI account, project, or trusted publisher is required.
+
+Older Avibe versions may request Memory from PyPI during their built-in update,
+before new code can run. Migrate through the official core-only installer first,
+then start the updated core normally; enabled Memory is reconciled from the
+matching GitHub Release. Do not use an old `avibe-os[memory]` upgrade request as
+the migration path. GitHub-installed previews retain their original tag through
+PEP 610; index-installed core uses its official `v<version>` release.
The package split changes distribution ownership only. The installed import
path remains `avibe_memory`, the host keeps its fixed loader and protocol
diff --git a/packaging/avibe-memory/pyproject.toml b/packaging/avibe-memory/pyproject.toml
index bc18375f4..1e8a78166 100644
--- a/packaging/avibe-memory/pyproject.toml
+++ b/packaging/avibe-memory/pyproject.toml
@@ -24,7 +24,7 @@ classifiers = [
]
dependencies = [
"psutil>=7.1.0",
- "avibe-os>=3.0.14.dev0,<3.1",
+ "avibe-os>=3.0.14.dev0,<4",
]
[project.urls]
diff --git a/pyproject.toml b/pyproject.toml
index 0ab74c8a7..400eb5b07 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -79,9 +79,9 @@ dependencies = [
]
[project.optional-dependencies]
-memory = [
- "avibe-memory>=3.0.14.dev0,<3.1",
-]
+# Compatibility spelling only. Enabled Memory is reconciled from the matching
+# GitHub Release; it is not a separately indexed dependency.
+memory = []
[project.urls]
Homepage = "https://github.com/avibe-bot/avibe"
@@ -169,6 +169,3 @@ dev = [
"pytest>=9.0.3",
"pytest-asyncio>=1.4.0",
]
-
-[tool.uv.sources]
-avibe-memory = { path = "packaging/avibe-memory" }
diff --git a/scripts/github_release.py b/scripts/github_release.py
index 1a4d48a39..e67d79f76 100644
--- a/scripts/github_release.py
+++ b/scripts/github_release.py
@@ -11,12 +11,16 @@ import sys
import time
from dataclasses import asdict, dataclass
from pathlib import Path
+from runpy import run_path
from typing import Any, Sequence
from urllib.parse import quote
NOTES_READY_MARKER_PREFIX = "<!-- avibe:release-notes=ready source="
_SHA_RE = re.compile(r"[0-9a-f]{40}")
+package_version_from_release_tag = run_path(
+ str(Path(__file__).with_name("release_package_version.py"))
+)["package_version_from_release_tag"]
class ReleaseError(RuntimeError):
@@ -122,6 +126,15 @@ def _notes_arguments(*, notes: str | None, notes_file: Path | None) -> list[str]
raise ReleaseError("Release notes or a release notes file is required")
+def _validate_publication_tag(tag: str) -> None:
+ # This module is workflow-owned, even when a dispatch builds older tagged
+ # sources. An old producer must not bypass the current publication policy.
+ try:
+ package_version_from_release_tag(tag)
+ except ValueError as exc:
+ raise ReleaseError(str(exc)) from exc
+
+
def ensure_draft(
*,
repo: str,
@@ -130,6 +143,7 @@ def ensure_draft(
notes: str | None,
notes_file: Path | None,
) -> ReleaseState:
+ _validate_publication_tag(tag)
existing = get_release(repo, tag)
if existing is not None:
return existing
@@ -273,6 +287,7 @@ def finalize_release(
prerelease: bool,
latest: str,
) -> ReleaseState:
+ _validate_publication_tag(tag)
if get_release(repo, tag) is None:
raise ReleaseError(f"Cannot finalize missing GitHub Release {tag}")
diff --git a/scripts/release_package_version.py b/scripts/release_package_version.py
index fc8084f7f..36f24f118 100644
--- a/scripts/release_package_version.py
+++ b/scripts/release_package_version.py
@@ -9,9 +9,9 @@ from collections.abc import Sequence
_VERSION_PATTERN = re.compile(
- r"^[0-9]+\.[0-9]+\.[0-9]+"
- r"(?:(?:[.-]?(?:a|b|rc|dev))[0-9]+)?"
- r"(?:\.post[0-9]+)?$"
+ r"^(?P<release>[0-9]+\.[0-9]+\.[0-9]+)"
+ r"(?:[.-]?(?P<phase>a|b|rc|dev)(?P<phase_number>[0-9]+))?"
+ r"(?:\.post(?P<post_number>[0-9]+))?$"
)
@@ -24,9 +24,25 @@ def package_version_from_release_tag(tag: str) -> str:
else:
raise ValueError("release tag must start with 'v' or 'gh-v'")
- if not _VERSION_PATTERN.fullmatch(version):
+ match = _VERSION_PATTERN.fullmatch(version)
+ if not match or (match["phase"] == "dev" and match["post_number"] is not None):
raise ValueError(f"release tag does not contain a supported package version: {tag!r}")
- return version
+ # This bounded tag grammar is normalized without third-party dependencies:
+ # the helper also runs before build dependencies have been installed.
+ # Keep the original tag for release URLs, but use Hatch/PEP 440 spelling
+ # for distribution versions and filenames.
+ result = ".".join(str(int(part)) for part in match["release"].split("."))
+ if match["phase"]:
+ separator = "." if match["phase"] == "dev" else ""
+ result += f"{separator}{match['phase']}{int(match['phase_number'])}"
+ if match["post_number"] is not None:
+ result += f".post{int(match['post_number'])}"
+ if normalized.startswith("v") and normalized != f"v{result}":
+ raise ValueError(
+ f"official release tag must use canonical spelling v{result}; "
+ "index-installed core resolves its Memory companion by that exact tag"
+ )
+ return result
def main(argv: Sequence[str] | None = None) -> int:
diff --git a/tests/e2e/github_release_fixture.py b/tests/e2e/github_release_fixture.py
new file mode 100644
index 000000000..4c096f430
--- /dev/null
+++ b/tests/e2e/github_release_fixture.py
@@ -0,0 +1,109 @@
+"""HTTPS asset supplier for the disposable released-client upgrade test.
+
+No product URL override is used. Only the disposable container maps github.com
+to this server and trusts its test CA; installed package code remains intact.
+"""
+
+from __future__ import annotations
+
+import argparse
+from functools import partial
+import hashlib
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from importlib.metadata import Distribution
+import json
+from pathlib import Path
+import ssl
+import subprocess
+import zipfile
+
+
+def create_certificate(directory: Path, *, hostname: str = "github.com") -> tuple[Path, Path, Path]:
+ """Create ephemeral test credentials, never a developer-machine trust entry."""
+ directory.mkdir(parents=True, exist_ok=True)
+ ca = directory / "ca.pem"
+ cert = directory / "server.pem"
+ key = directory / "server.key"
+ extensions = directory / "server.ext"
+ extensions.write_text(
+ f"subjectAltName=DNS:{hostname}\nbasicConstraints=critical,CA:FALSE\n"
+ "keyUsage=critical,digitalSignature,keyEncipherment\n"
+ "extendedKeyUsage=serverAuth\nsubjectKeyIdentifier=hash\n"
+ "authorityKeyIdentifier=keyid,issuer\n",
+ encoding="utf-8",
+ )
+ commands = [
+ ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2",
+ "-subj", "/CN=Avibe disposable upgrade fixture CA",
+ "-addext", "basicConstraints=critical,CA:TRUE",
+ "-addext", "keyUsage=critical,keyCertSign,cRLSign",
+ "-keyout", str(directory / "ca.key"), "-out", str(ca)],
+ ["req", "-new", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={hostname}",
+ "-keyout", str(key), "-out", str(directory / "server.csr")],
+ ["x509", "-req", "-days", "2", "-in", str(directory / "server.csr"),
+ "-CA", str(ca), "-CAkey", str(directory / "ca.key"), "-CAcreateserial",
+ "-extfile", str(extensions), "-out", str(cert)],
+ ]
+ for command in commands:
+ subprocess.run(["openssl", *command], check=True, capture_output=True, timeout=30)
+ return ca, cert, key
+
+
+def verify_installed_companion(distribution: Distribution, wheel: Path, url: str) -> None:
+ """Verify exact origin AND installed bytes without requiring optional hashes."""
+ record = json.loads(distribution.read_text("direct_url.json"))
+ assert record["url"] == url, "Installed companion has a different origin"
+ archive = record.get("archive_info")
+ assert isinstance(archive, dict), "Wheel origin requires archive_info"
+ hashes = archive.get("hashes", {})
+ assert isinstance(hashes, dict), "archive_info.hashes must be a dictionary"
+ reported = dict(hashes)
+ if "hash" in archive:
+ assert isinstance(archive["hash"], str), "archive_info.hash must be a string"
+ algorithm, separator, digest = archive["hash"].partition("=")
+ assert separator and algorithm and digest, "Malformed legacy archive hash"
+ if "hashes" in archive:
+ assert hashes.get(algorithm) == digest, "Conflicting archive hashes"
+ reported[algorithm] = digest
+ contents = wheel.read_bytes()
+ for algorithm, digest in reported.items():
+ assert hashlib.new(algorithm, contents).hexdigest() == digest, "Wrong archive digest"
+
+ # PEP610 permits empty archive_info (uv emits it for an unhashed URL).
+ # Independently inspect what was installed, including code and metadata.
+ # RECORD is rewritten by installers to add their own generated files.
+ with zipfile.ZipFile(wheel) as source:
+ payload = [
+ entry.filename for entry in source.infolist()
+ if not entry.is_dir() and not entry.filename.endswith(".dist-info/RECORD")
+ ]
+ assert any(name.startswith("avibe_memory/") for name in payload), "Missing companion payload"
+ for name in payload:
+ installed = Path(distribution.locate_file(name))
+ assert installed.is_file(), f"Missing installed companion file: {name}"
+ assert installed.read_bytes() == source.read(name), f"Changed installed companion file: {name}"
+
+
+def make_server(root: Path, cert: Path, key: Path, *, port: int = 0, handler=None) -> ThreadingHTTPServer:
+ server = ThreadingHTTPServer(
+ ("127.0.0.1", port), handler or partial(SimpleHTTPRequestHandler, directory=str(root)),
+ )
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(cert, key)
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ return server
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, required=True)
+ parser.add_argument("--cert", type=Path, required=True)
+ parser.add_argument("--key", type=Path, required=True)
+ parser.add_argument("--port", type=int, default=443)
+ args = parser.parse_args()
+ with make_server(args.root, args.cert, args.key, port=args.port) as server:
+ server.serve_forever()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/e2e/test_upgrade_command.py b/tests/e2e/test_upgrade_command.py
index cff5796db..154b83a43 100644
--- a/tests/e2e/test_upgrade_command.py
+++ b/tests/e2e/test_upgrade_command.py
@@ -3,18 +3,26 @@
from __future__ import annotations
import hashlib
+import http.client
+from importlib.metadata import Distribution
import json
import os
import shlex
import shutil
+import socket
+import ssl
import subprocess
import sys
import tempfile
+import threading
import urllib.request
+import zipfile
from pathlib import Path
import pytest
+from tests.e2e.github_release_fixture import create_certificate, make_server, verify_installed_companion
+
REPO_ROOT = Path(__file__).resolve().parents[2]
BASE_IMAGE = os.environ.get("VIBE_UPGRADE_TEST_IMAGE", "debian:trixie-slim")
@@ -24,6 +32,10 @@ INITIAL_RELEASE_WHEEL_URL = (
)
INITIAL_RELEASE_WHEEL_SHA256 = "994adbfd23228ea387f0479db8a4efe0ef121847bd04efa550486203a6b03542"
TEST_RELEASE_VERSION = "9999.0.0"
+MEMORY_RELEASE_PATH = (
+ f"/avibe-bot/avibe/releases/download/v{TEST_RELEASE_VERSION}/"
+ f"avibe_memory-{TEST_RELEASE_VERSION}-py3-none-any.whl"
+)
_UPGRADE_WAIT_HELPERS = r"""
report_upgrade_failure() {
@@ -152,6 +164,171 @@ def _docker_available() -> bool:
return result.returncode == 0
+def test_github_companion_supplier_uses_verified_https_outside_the_index(tmp_path):
+ ca, cert, key = create_certificate(tmp_path / "fixture CA 中文")
+ root = tmp_path / "github assets"
+ asset = root / MEMORY_RELEASE_PATH.lstrip("/")
+ asset.parent.mkdir(parents=True)
+ asset.write_bytes(b"fixture companion")
+ server = make_server(root, cert, key)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ # Connect locally without changing host DNS/trust. Hostname verification
+ # is still for the real URL selected by the unmodified package planner.
+ trusted = ssl.create_default_context(cafile=str(ca))
+ for context, hostname in (
+ (ssl.create_default_context(), "github.com"), (trusted, "wrong.example"),
+ ):
+ with socket.create_connection(server.server_address, timeout=5) as raw:
+ with pytest.raises(ssl.SSLCertVerificationError):
+ context.wrap_socket(raw, server_hostname=hostname)
+ for path, expected_status in ((MEMORY_RELEASE_PATH, 200), ("/missing.whl", 404)):
+ with socket.create_connection(server.server_address, timeout=5) as raw:
+ with trusted.wrap_socket(raw, server_hostname="github.com") as connection:
+ connection.sendall(f"GET {path} HTTP/1.1\r\nHost: github.com\r\nConnection: close\r\n\r\n".encode())
+ response = http.client.HTTPResponse(connection)
+ response.begin()
+ assert response.status == expected_status
+ data = response.read()
+ if expected_status == 200:
+ assert data == asset.read_bytes()
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
[email protected](scope="module")
+def provenance_wheel(tmp_path_factory):
+ return _build_test_wheel(
+ tmp_path_factory.mktemp("companion-provenance"), TEST_RELEASE_VERSION,
+ project=REPO_ROOT / "packaging" / "avibe-memory", distribution="avibe_memory",
+ )
+
+
+def installed_companion(tmp_path, provenance_wheel):
+ site = tmp_path / "installed 中文"
+ with zipfile.ZipFile(provenance_wheel) as archive:
+ archive.extractall(site)
+ metadata = next(site.glob("*.dist-info"))
+ return Distribution.at(metadata), metadata / "direct_url.json"
+
+
[email protected]("encoding", ["absent", "empty", "hashes", "legacy", "both", "sha512"])
+def test_installed_companion_checks_bytes_with_optional_pep610_hashes(
+ provenance_wheel, installed_companion, encoding,
+):
+ distribution, origin_path = installed_companion
+ original = provenance_wheel.read_bytes()
+ digest = hashlib.sha256(original).hexdigest()
+ archive = {
+ "absent": {}, "empty": {"hashes": {}}, "hashes": {"hashes": {"sha256": digest}},
+ "legacy": {"hash": f"sha256={digest}"},
+ "both": {"hashes": {"sha256": digest}, "hash": f"sha256={digest}"},
+ "sha512": {"hashes": {"sha512": hashlib.sha512(original).hexdigest()}},
+ }[encoding]
+ url = "https://github.com/exact.whl"
+ origin_path.write_text(json.dumps({"url": url, "archive_info": archive}))
+ verify_installed_companion(distribution, provenance_wheel, url)
+ assert provenance_wheel.read_bytes() == original
+
+
[email protected]("failure", [
+ "wrong-url", "missing-archive", "invalid-archive", "invalid-hashes", "invalid-legacy",
+ "wrong-hash", "conflicting-hash", "missing-reciprocal-hash",
+])
+def test_installed_companion_rejects_wrong_or_malformed_provenance(
+ provenance_wheel, installed_companion, failure,
+):
+ distribution, origin_path = installed_companion
+ digest = hashlib.sha256(provenance_wheel.read_bytes()).hexdigest()
+ url = "https://github.com/exact.whl"
+ record = {"url": url, "archive_info": {}}
+ if failure == "wrong-url":
+ record["url"] = "https://wrong.example/exact.whl"
+ elif failure == "missing-archive":
+ del record["archive_info"]
+ else:
+ record["archive_info"] = {
+ "invalid-archive": None, "invalid-hashes": {"hashes": None},
+ "invalid-legacy": {"hash": None}, "wrong-hash": {"hashes": {"sha256": "bad"}},
+ "conflicting-hash": {"hashes": {"sha256": digest}, "hash": "sha256=bad"},
+ "missing-reciprocal-hash": {"hashes": {}, "hash": f"sha256={digest}"},
+ }[failure]
+ origin_path.write_text(json.dumps(record))
+ with pytest.raises(AssertionError):
+ verify_installed_companion(distribution, provenance_wheel, url)
+
+
[email protected]("changed", [True, False], ids=["changed", "missing"])
[email protected]("member", [
+ "avibe_memory/__init__.py", "vibe/memory_runtime_manifest.json",
+ f"avibe_memory-{TEST_RELEASE_VERSION}.dist-info/METADATA",
+])
+def test_installed_companion_rejects_different_payload_even_without_archive_hash(
+ provenance_wheel, installed_companion, changed, member,
+):
+ distribution, origin_path = installed_companion
+ url = "https://github.com/exact.whl"
+ origin_path.write_text(json.dumps({"url": url, "archive_info": {}}))
+ original = provenance_wheel.read_bytes()
+ installed = Path(distribution.locate_file(member))
+ if changed:
+ installed.write_bytes(b"changed bytes")
+ else:
+ installed.unlink()
+ with pytest.raises(AssertionError, match="installed companion file"):
+ verify_installed_companion(distribution, provenance_wheel, url)
+ assert provenance_wheel.read_bytes() == original
+
+
[email protected]("installer", ["pip", "uv"])
+def test_real_installer_provenance_and_payload_from_https(
+ tmp_path, provenance_wheel, installer,
+):
+ ca, cert, key = create_certificate(tmp_path / "TLS 中文", hostname="localhost")
+ server = make_server(provenance_wheel.parent, cert, key)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ environment = tmp_path / "isolated env 中文"
+ subprocess.run(
+ [sys.executable, "-m", "venv", str(environment)],
+ check=True, capture_output=True, timeout=60,
+ )
+ python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ url = f"https://localhost:{server.server_port}/{provenance_wheel.name}"
+ env = {**os.environ, "SSL_CERT_FILE": str(ca), "PIP_CERT": str(ca),
+ "UV_NATIVE_TLS": "true", "NO_PROXY": "localhost,127.0.0.1",
+ "no_proxy": "localhost,127.0.0.1"}
+ if installer == "uv":
+ uv = shutil.which("uv")
+ assert uv, "The regression job must supply uv"
+ command = [uv, "pip", "install", "--python", str(python), "--no-cache"]
+ else:
+ command = [str(python), "-m", "pip", "install", "--no-cache-dir"]
+ result = subprocess.run(
+ [*command, "--no-deps", "--no-index", url], env=env,
+ capture_output=True, text=True, timeout=90,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ verification = (
+ "from importlib.metadata import distribution; from pathlib import Path; from runpy import run_path; "
+ f"verify=run_path({str(REPO_ROOT / 'tests/e2e/github_release_fixture.py')!r})['verify_installed_companion']; "
+ f"verify(distribution('avibe-memory'), Path({str(provenance_wheel)!r}), {url!r})"
+ )
+ result = subprocess.run(
+ [str(python), "-c", verification], capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
def _build_test_wheel(
fixtures_dir: Path,
version: str,
@@ -326,6 +503,22 @@ def test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generation():
distribution="avibe_memory",
)
assert memory_wheel_path.exists()
+ # The index contains ONLY core. Memory must be obtained from the exact
+ # HTTPS URL selected by installed, unmodified production code.
+ core_index = fixtures_dir / "core-index"
+ core_index.mkdir()
+ shutil.copy2(wheel_path, core_index / wheel_path.name)
+ github_root = fixtures_dir / "github"
+ memory_asset = github_root / MEMORY_RELEASE_PATH.lstrip("/")
+ memory_asset.parent.mkdir(parents=True)
+ shutil.move(memory_wheel_path, memory_asset)
+ create_certificate(fixtures_dir / "tls")
+ verify_memory_origin = (
+ "from importlib.metadata import distribution; from pathlib import Path; from runpy import run_path; "
+ "verify=run_path('/work/tests/e2e/github_release_fixture.py')['verify_installed_companion']; "
+ f"verify(distribution('avibe-memory'), Path('/fixtures/github{MEMORY_RELEASE_PATH}'), "
+ f"'https://github.com{MEMORY_RELEASE_PATH}')"
+ )
memory_payload = {
"enabled": True,
@@ -382,13 +575,28 @@ def test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generation():
"AVIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json vibe check-update",
'"$upgraded_python" -c "import importlib.util; from config.v2_config import V2Config; '
"assert V2Config.load().memory.enabled; assert importlib.util.find_spec('avibe_memory') is None\"",
- "export UV_FIND_LINKS=/fixtures",
- "export PIP_FIND_LINKS=/fixtures",
+ "export UV_FIND_LINKS=/fixtures/core-index",
+ "export PIP_FIND_LINKS=/fixtures/core-index",
+ # Restrict the fixture DNS/CA changes to this disposable
+ # container, after all genuine old-version downloads/upgrade.
+ # Keep normal CA roots for unrelated package dependencies.
+ "cat /etc/ssl/certs/ca-certificates.crt /fixtures/tls/ca.pem > /tmp/fixture-ca.pem",
+ "export SSL_CERT_FILE=/tmp/fixture-ca.pem",
+ "export PIP_CERT=/tmp/fixture-ca.pem",
+ "export NO_PROXY=github.com,127.0.0.1,localhost",
+ "export no_proxy=\"$NO_PROXY\"",
+ "printf '\\n127.0.0.1 github.com\\n' >> /etc/hosts",
+ '("$upgraded_python" /work/tests/e2e/github_release_fixture.py '
+ "--root /fixtures/github --cert /fixtures/tls/server.pem --key /fixtures/tls/server.key "
+ "> /tmp/github-fixture.log 2>&1 &)",
+ f'wait_until 30 1 "fixture HTTPS supplier" curl --silent --fail --cacert /fixtures/tls/ca.pem '
+ f'--output /dev/null https://github.com{MEMORY_RELEASE_PATH}',
'"$upgraded_launcher"',
f'wait_until 120 1 "avibe-memory {TEST_RELEASE_VERSION} to become available" memory_runtime_ready',
'"$current_python" -c "from config.v2_config import V2Config; '
f"from importlib.metadata import version; assert V2Config.load().memory.enabled; assert version('avibe-os') == '{TEST_RELEASE_VERSION}'; "
f"assert version('avibe-memory') == '{TEST_RELEASE_VERSION}'\"",
+ f'"$current_python" -c {shlex.quote(verify_memory_origin)}',
'test "$current_python" != "$upgraded_python"',
'"$upgraded_python" -c "import certifi, importlib.util; from pathlib import Path; '
"assert Path(certifi.where()).is_file(); assert importlib.util.find_spec('vibe.api') is not None; "
diff --git a/tests/test_github_release.py b/tests/test_github_release.py
index 02b673b79..1226bab37 100644
--- a/tests/test_github_release.py
+++ b/tests/test_github_release.py
@@ -14,6 +14,22 @@ TAG = "v3.0.14"
SOURCE_SHA = "a" * 40
[email protected]("tag", ["v3.2.0-rc1", "v03.02.00", "v3.2.0.post01"])
[email protected]("operation", ["ensure", "notes", "finalize"])
+def test_noncanonical_official_tag_fails_before_any_release_request(monkeypatch, tmp_path, tag, operation):
+ def forbidden(*args, **kwargs):
+ pytest.fail("Invalid publication identity must fail before any GitHub request")
+
+ monkeypatch.setattr(github_release, "_run_gh", forbidden)
+ with pytest.raises(github_release.ReleaseError, match="canonical spelling"):
+ if operation == "ensure":
+ github_release.ensure_draft(repo=REPO, tag=tag, title=tag, notes="notes", notes_file=None)
+ elif operation == "notes":
+ github_release.update_notes(repo=REPO, tag=tag, title=tag, notes_file=tmp_path / "notes.md")
+ else:
+ github_release.finalize_release(repo=REPO, tag=tag, prerelease=True, latest="false")
+
+
def _completed(
arguments: list[str],
*,
@@ -451,10 +467,7 @@ def test_release_workflows_stage_then_finalize_once() -> None:
assert "--run-sha \"${{ needs.resolve-tag.outputs.workflow_sha }}\"" in publish
assert "--source-sha \"${{ needs.resolve-tag.outputs.source_sha }}\"" in publish
assert "python scripts/github_release.py finalize" in publish
- memory_publish = publish.split(" publish-avibe-memory:", 1)[1].split(
- " verify-avibe-memory-pypi:", 1
- )[0]
- memory_verify = publish.split(" verify-avibe-memory-pypi:", 1)[1].split(
+ memory_verify = publish.split(" verify-avibe-memory-release:", 1)[1].split(
" publish-avibe-os:", 1
)[0]
avibe_publish = publish.split(" publish-avibe-os:", 1)[1].split(
@@ -463,10 +476,10 @@ def test_release_workflows_stage_then_finalize_once() -> None:
legacy_publish = publish.split(" publish-vibe-remote:", 1)[1].split(
" finalize-github-release:", 1
)[0]
- assert "- finalize-github-release" in memory_publish
- assert "environment: pypi-avibe-memory" in memory_publish
- assert "- publish-avibe-memory" in memory_verify
- assert "- verify-avibe-memory-pypi" in avibe_publish
+ assert "publish-avibe-memory:" not in publish
+ assert "environment: pypi-avibe-memory" not in publish
+ assert "- finalize-github-release" in memory_verify
+ assert "- verify-avibe-memory-release" in avibe_publish
assert "- finalize-github-release" in avibe_publish
assert "- finalize-github-release" in legacy_publish
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 9e88a9515..2dcb960f7 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -3361,21 +3361,40 @@ def test_memory_package_dependency_job_targets_the_running_version_wherever_it_c
)
[email protected]("tag,direct", [
+ (f"v{REPAIR_VERSION}", False),
+ ("v3.2.0a1", False),
+ ("v3.2.0b1", False),
+ ("v3.2.0rc1", False),
+ ("v3.2.0.dev0", False),
+ ("v3.2.0.dev1", False),
+ ("v3.2.0.post1", False),
+ (f"gh-v{REPAIR_VERSION}", True),
+ ("gh-v3.2.0.dev1", True),
+ ("gh-v03.02.00dev01", True),
+ ("v3.2.0.dev1", True),
+])
def test_memory_indep_027_preview_repair_installs_the_release_that_published_it(
- monkeypatch,
+ monkeypatch, tmp_path, tag, direct,
) -> None:
- """MEMORY-INDEP-027: a core-only preview install converges from its own release.
+ """A core-only install converges from the corresponding GitHub Release.
- A `gh-v*` release publishes the wheel pair as release assets and nothing to
- an index, so this builds the real plan rather than a recorded call: what
- matters is the command an installer would actually run.
+ MEMORY-INDEP-027 retains its preview-origin coverage. The PyPI-core case
+ additionally verifies the same consuming startup path without a direct URL.
"""
- current_version = REPAIR_VERSION
+ from scripts.release_package_version import package_version_from_release_tag
+
+ current_version = package_version_from_release_tag(tag)
+ release = f"https://github.com/avibe-bot/avibe/releases/download/{tag}/"
+ origin = f"{release}avibe_os-{current_version}-py3-none-any.whl" if direct else None
calls: dict[str, object] = {}
- monkeypatch.setattr("vibe.upgrade._recorded_install_origin", lambda _package: RELEASE_CORE_URL)
- monkeypatch.setattr(api, "_memory_package_repair_rejection", lambda **_kwargs: None)
- monkeypatch.setattr(api, "_published_running_version", lambda: current_version)
+ monkeypatch.setattr("vibe.upgrade._recorded_install_origin", lambda _package: origin)
+ monkeypatch.setattr("vibe.__version__", current_version)
+ monkeypatch.setattr(api, "_load_memory_requirement", lambda: api._MemoryRequirementProjection(True, "required"))
+ monkeypatch.setattr(api, "_inspect_memory_package_metadata", lambda: api._MemoryPackageMetadata(0, None))
+ monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)
+ monkeypatch.setattr(api, "_memory_package_auto_repair_state_path", lambda: tmp_path / "repair.json")
monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/bin/vibe")
monkeypatch.setattr(api, "get_safe_cwd", lambda: "/safe")
monkeypatch.setattr(api, "restart_is_pending", lambda: False)
@@ -3403,7 +3422,7 @@ def test_memory_indep_027_preview_repair_installs_the_release_that_published_it(
assert result["ok"] is True
assert result["restarting"] is True
plan = calls["plan"]
- release = f"https://github.com/avibe-bot/avibe/releases/download/gh-v{current_version}/"
+ core_spec = origin or f"{api.PACKAGE_NAME}=={current_version}"
commands = [
command
for command in (plan.command, plan.preflight_command, plan.preflight_fallback_command)
@@ -3411,14 +3430,45 @@ def test_memory_indep_027_preview_repair_installs_the_release_that_published_it(
]
assert len(commands) >= 2, "the repair resolves the pair before it installs it"
for command in commands:
- assert f"{release}avibe_os-{current_version}-py3-none-any.whl" in command
+ assert core_spec in command
assert f"avibe-memory @ {release}avibe_memory-{current_version}-py3-none-any.whl" in command
- # An index pin here is the bug: PyPI never served this version, so the
- # install fails and spends one of the bounded repair attempts.
- assert f"{api.PACKAGE_NAME}=={current_version}" not in command
+ # Memory never falls back to an index, even when core uses one.
assert f"{api.MEMORY_PACKAGE_NAME}=={current_version}" not in command
[email protected]("version,origin,build_kind", [
+ ("3.2.0.dev1+local", None, "package"),
+ ("3.2.0+local", None, "package"),
+ ("invalid", None, "package"),
+ ("3.2.0.dev1", None, "source"),
+ ("3.2.0", None, "source"),
+ ("3.2.0.dev1+local", "https://github.com/avibe-bot/avibe/releases/download/gh-v3.2.0.dev1+local/avibe_os-3.2.0.dev1+local-py3-none-any.whl", "package"),
+ ("3.2.0.dev1", "https://github.com/avibe-bot/avibe/releases/download/gh-v3.2.0.dev1/avibe_os-3.2.0.dev1-py3-none-any.whl", "source"),
+])
+def test_local_or_source_build_cannot_enter_memory_repair(
+ monkeypatch, tmp_path, version, origin, build_kind,
+):
+ monkeypatch.setattr("vibe.__version__", version)
+ monkeypatch.setattr("vibe.upgrade._recorded_install_origin", lambda _: origin)
+ monkeypatch.setattr(api, "_load_memory_requirement", lambda: api._MemoryRequirementProjection(True, "required"))
+ monkeypatch.setattr(api, "_inspect_memory_package_metadata", lambda: api._MemoryPackageMetadata(0, None))
+ monkeypatch.delenv("VIBE_BUILD_METADATA_PATH", raising=False)
+ if build_kind == "source":
+ # An unreadable source marker must never become a package install.
+ monkeypatch.setenv("VIBE_BUILD_METADATA_PATH", str(tmp_path / "missing-source.json"))
+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", Mock(side_effect=ImportError("missing")))
+ monkeypatch.setattr(api, "atomic_upgrade_lock", nullcontext)
+ build = Mock(side_effect=AssertionError("operator-only build must not plan an install"))
+ monkeypatch.setattr(api, "build_upgrade_plan", build)
+ result = api._prepare_memory_package_job(automatic=True)
+ assert result["ok"] is False
+ assert result["action_class"] == "operator_only"
+ assert result["reason"] == (
+ "memory_package_source_build" if build_kind == "source" else "memory_package_unpublished_build"
+ )
+ build.assert_not_called()
+
+
def test_memory_package_dependency_job_fails_closed_when_restart_cannot_be_scheduled(
monkeypatch,
tmp_path,
diff --git a/tests/test_memory_distribution.py b/tests/test_memory_distribution.py
index 54fb289f7..cdea8f26f 100644
--- a/tests/test_memory_distribution.py
+++ b/tests/test_memory_distribution.py
@@ -31,7 +31,7 @@ except ModuleNotFoundError: # pragma: no cover - Python 3.10 compatibility
ROOT = Path(__file__).resolve().parents[1]
MEMORY_PROJECT = ROOT / "packaging" / "avibe-memory"
-COMPATIBILITY = SpecifierSet(">=3.0.14.dev0,<3.1")
+COMPATIBILITY = SpecifierSet(">=3.0.14.dev0,<4")
PACKAGE_CONTRACT_VERSION = Version("3.0.99rc1")
WORKFLOW_DIR = ROOT / ".github" / "workflows"
@@ -243,10 +243,10 @@ def test_source_metadata_preserves_the_developer_compatibility_window() -> None:
host = _project(ROOT / "pyproject.toml")
memory = _project(MEMORY_PROJECT / "pyproject.toml")
- memory_requirement = _requirement(host["optional-dependencies"]["memory"], "avibe-memory")
host_requirement = _requirement(memory["dependencies"], "avibe-os")
- assert memory_requirement.specifier == COMPATIBILITY
+ assert host["optional-dependencies"]["memory"] == []
+ assert not any(canonicalize_name(Requirement(value).name) == "avibe-memory" for value in host["dependencies"])
assert host_requirement.specifier == COMPATIBILITY
@@ -269,25 +269,24 @@ def test_pr_artifact_build_uses_an_explicit_prerelease_contract_version() -> Non
def test_publishable_metadata_without_the_peer_contract_fails_closed(tmp_path: Path) -> None:
- wheel = tmp_path / "avibe_os-3.0.99rc1-py3-none-any.whl"
- dist_info = "avibe_os-3.0.99rc1.dist-info"
+ wheel = tmp_path / "avibe_memory-3.0.99rc1-py3-none-any.whl"
+ dist_info = "avibe_memory-3.0.99rc1.dist-info"
with zipfile.ZipFile(wheel, "w") as archive:
archive.writestr(
f"{dist_info}/METADATA",
- "Metadata-Version: 2.4\nName: avibe-os\nVersion: 3.0.99rc1\n\n",
+ "Metadata-Version: 2.4\nName: avibe-memory\nVersion: 3.0.99rc1\n\n",
)
archive.writestr(
f"{dist_info}/RECORD",
f"{dist_info}/METADATA,,\n{dist_info}/RECORD,,\n",
)
- with pytest.raises(RuntimeError, match="exactly one avibe-memory dependency"):
+ with pytest.raises(RuntimeError, match="exactly one avibe-os dependency"):
pin_peer_dependency(
str(wheel),
- project_name="avibe-os",
- peer_name="avibe-memory",
+ project_name="avibe-memory",
+ peer_name="avibe-os",
package_version="3.0.99rc1",
- peer_extra="memory",
)
assert not wheel.exists()
@@ -299,7 +298,7 @@ def test_distribution_release_contract_is_forward_only_and_memory_first() -> Non
)
assert "asset-complete GitHub Release" in contract
- assert "Publish `avibe-memory`" in contract
+ assert "not on PyPI" in contract
assert "byte-identical to the staged wheel" in contract
assert "Publish `avibe-os` only after that verification succeeds" in contract
assert "forward-only" in contract
@@ -365,10 +364,12 @@ def test_github_only_release_uploads_both_distribution_pairs() -> None:
release_upload = _step(release_job, "Create GitHub-only Release")["run"]
assert artifact_upload["with"]["path"] == "dist/"
- assert "for path in dist/*" in release_upload
- assert 'package_assets+=("$path")' in release_upload
+ assert "dist/avibe_os-*.whl dist/avibe_os-*.tar.gz" in release_upload
+ assert "dist/avibe_memory-*.whl dist/avibe_memory-*.tar.gz" in release_upload
+ assert 'package_to_upload+=("$path")' in release_upload
assert 'gh release upload "$TAG"' in release_upload
- assert '"${package_assets[@]}" --clobber' in release_upload
+ assert '"${package_to_upload[@]}"' in release_upload
+ assert not any("--clobber" in line for line in release_upload.splitlines() if "gh release upload" in line)
def test_official_draft_uploads_both_verified_distribution_pairs() -> None:
@@ -379,33 +380,34 @@ def test_official_draft_uploads_both_verified_distribution_pairs() -> None:
assert names.index("Verify Python distribution asset matrix") < names.index(
"Upload GitHub release assets"
)
- assert 'gh release upload "$TAG" --repo "${GITHUB_REPOSITORY}" dist/* --clobber' in release_upload
+ assert "dist/avibe_os-*.whl dist/avibe_os-*.tar.gz" in release_upload
+ assert "dist/avibe_memory-*.whl dist/avibe_memory-*.tar.gz" in release_upload
+ assert 'gh release upload "$TAG" --repo "${GITHUB_REPOSITORY}" "${package_to_upload[@]}"' in release_upload
+ assert not any("--clobber" in line for line in release_upload.splitlines() if "gh release upload" in line)
-def test_official_release_publishes_and_verifies_memory_before_core() -> None:
+def test_official_release_verifies_public_github_memory_before_core() -> None:
jobs = _workflow("publish.yml")["jobs"]
assert {"build", "finalize-github-release"} <= _needs(
- jobs["publish-avibe-memory"]
+ jobs["verify-avibe-memory-release"]
)
- assert jobs["publish-avibe-memory"]["environment"] == "pypi-avibe-memory"
- assert "publish-avibe-memory" in _needs(jobs["verify-avibe-memory-pypi"])
- assert "verify-avibe-memory-pypi" in _needs(jobs["publish-avibe-os"])
+ assert "publish-avibe-memory" not in jobs
+ assert "verify-avibe-memory-pypi" not in jobs
+ assert "verify-avibe-memory-release" in _needs(jobs["publish-avibe-os"])
assert "finalize-github-release" in _needs(jobs["publish-avibe-os"])
verify = _step(
- jobs["verify-avibe-memory-pypi"],
- "Verify PyPI serves the exact avibe-memory wheel",
+ jobs["verify-avibe-memory-release"],
+ "Verify public GitHub companion distributions",
)["run"]
for fragment in (
- "for attempt in {1..12}",
- "python -m pip --isolated download",
- "--index-url https://pypi.org/simple",
- "--no-deps",
- "--no-cache-dir",
- "--only-binary=:all:",
- 'cmp -s "${staged_wheels[0]}" "${public_wheels[0]}"',
- "PyPI already serves a non-identical avibe-memory wheel",
+ "curl --fail --location --retry 5",
+ "avibe_memory-${package_version}-py3-none-any.whl",
+ "avibe_memory-${package_version}.tar.gz",
+ 'cmp -s "dist/$asset" "$download_dir/$asset"',
+ "https://github.com/${GITHUB_REPOSITORY}/releases/download/${RELEASE_TAG}/${asset}",
+ "GitHub serves a non-identical companion asset",
):
assert fragment in verify
@@ -413,12 +415,6 @@ def test_official_release_publishes_and_verifies_memory_before_core() -> None:
@pytest.mark.parametrize(
("job_name", "keep_step", "allowed", "excluded"),
[
- (
- "publish-avibe-memory",
- "Keep avibe-memory distributions only",
- "avibe_memory-*",
- "avibe_os-*",
- ),
(
"publish-avibe-os",
"Keep avibe-os distributions only",
@@ -497,21 +493,18 @@ def test_built_distributions_have_independent_contents_and_exact_peer_metadata()
for metadata in (core_metadata, core_sdist_metadata):
assert Version(metadata["Version"]) == core_version
- memory_requirement = _requirement(metadata.get_all("Requires-Dist") or [], "avibe-memory")
- assert str(memory_requirement.specifier) == f"=={core_version}"
- assert memory_requirement.marker is not None
- assert memory_requirement.marker.evaluate({"extra": "memory"})
- assert not memory_requirement.marker.evaluate({"extra": "not-memory"})
+ assert all(
+ canonicalize_name(Requirement(value).name) != "avibe-memory"
+ for value in metadata.get_all("Requires-Dist") or []
+ )
for metadata in (memory_metadata, memory_sdist_metadata):
assert Version(metadata["Version"]) == memory_version
host_requirement = _requirement(metadata.get_all("Requires-Dist") or [], "avibe-os")
assert str(host_requirement.specifier) == f"=={memory_version}"
assert host_requirement.marker is None
- core_build_requirement = _requirement(core_sdist_project["optional-dependencies"]["memory"], "avibe-memory")
memory_build_requirement = _requirement(memory_sdist_project["dependencies"], "avibe-os")
- assert str(core_build_requirement.specifier) == f"=={core_version}"
- assert core_build_requirement.marker is None
+ assert core_sdist_project["optional-dependencies"]["memory"] == []
assert str(memory_build_requirement.specifier) == f"=={memory_version}"
assert memory_build_requirement.marker is None
for pyproject in (core_sdist_pyproject, memory_sdist_pyproject):
@@ -605,7 +598,7 @@ def test_core_sdist_installs_and_mirrors_builtin_skills_without_a_checkout(tmp_p
)
-def test_memory_extra_resolves_and_installs_the_same_version_pair(tmp_path: Path) -> None:
+def test_explicit_companion_resolves_and_installs_the_same_version_pair(tmp_path: Path) -> None:
core_wheel = _wheel_path("AVIBE_CORE_WHEEL")
memory_wheel = _wheel_path("AVIBE_MEMORY_WHEEL")
core_version = Version(_wheel_metadata(core_wheel)[1]["Version"])
@@ -649,7 +642,8 @@ def test_memory_extra_resolves_and_installs_the_same_version_pair(tmp_path: Path
str(core_wheel.parent),
"--find-links",
str(memory_wheel.parent),
- f"avibe-os[memory]=={core_version}",
+ f"avibe-os=={core_version}",
+ f"avibe-memory @ {memory_wheel.as_uri()}",
cwd=tmp_path,
)
_run(
@@ -663,7 +657,7 @@ def test_memory_extra_resolves_and_installs_the_same_version_pair(tmp_path: Path
)
-def test_memory_extra_resolves_and_installs_from_both_sdists(tmp_path: Path) -> None:
+def test_explicit_companion_resolves_and_installs_from_both_sdists(tmp_path: Path) -> None:
core_wheel = _wheel_path("AVIBE_CORE_WHEEL")
memory_wheel = _wheel_path("AVIBE_MEMORY_WHEEL")
core_sdist = _sdist_path(core_wheel, "avibe_os")
@@ -676,7 +670,6 @@ def test_memory_extra_resolves_and_installs_from_both_sdists(tmp_path: Path) ->
package_links = tmp_path / "package-links"
package_links.mkdir()
- shutil.copy2(memory_sdist, package_links / memory_sdist.name)
_write_minimal_wheel(package_links, "avibe-memory", str(decoy_version))
build_links = tmp_path / "build-links"
_provision_build_requirement_wheelhouse((core_pyproject, memory_pyproject), build_links)
@@ -710,7 +703,8 @@ def test_memory_extra_resolves_and_installs_from_both_sdists(tmp_path: Path) ->
str(package_links),
"--find-links",
str(build_links),
- f"avibe-os[memory] @ {core_sdist.as_uri()}",
+ f"avibe-os @ {core_sdist.as_uri()}",
+ f"avibe-memory @ {memory_sdist.as_uri()}",
]
assert "--no-build-isolation" not in install_command
assert install_command.count("--find-links") == 2
diff --git a/tests/test_memory_process.py b/tests/test_memory_process.py
index 57b5692fd..a9b22010f 100644
--- a/tests/test_memory_process.py
+++ b/tests/test_memory_process.py
@@ -45,7 +45,8 @@ class _ReleasedSyncHost:
self.signals: list[tuple[dict[int, float], int | None]] = []
def capture(self, pid: int):
- return _TestReference(self, pid) if pid in self.children else None
+ # Absence belongs to the fake generation table, not the host PID table.
+ return _TestReference(self, pid)
def inspect_identity(self, pid: int):
return self.parent if pid == 99 else self.children.get(pid)
@@ -102,7 +103,8 @@ class _SidecarHost:
self.signals: list[dict[int, float]] = []
def capture(self, pid: int):
- return _TestReference(self, pid) if pid in self.children else None
+ # None means unresolved capture to production, not known fake absence.
+ return _TestReference(self, pid)
def inspect_identity(self, pid: int):
return self.children.get(pid)
@@ -145,6 +147,43 @@ created_at is not None and created_at.is_running()
return not self.live(identities)
[email protected](params=[False, True], ids=["system-pid-absent", "system-pid-present"])
+def system_pid_presence(request, monkeypatch):
+ """Synthetic ownership must not depend on unrelated host processes."""
+ probes = []
+
+ def pid_exists(pid):
+ probes.append(pid)
+ return request.param
+
+ monkeypatch.setattr("avibe_memory.process.psutil.pid_exists", pid_exists)
+ yield
+ assert probes == [], f"synthetic process fixture queried host PIDs: {probes}"
+
+
[email protected]("host_type", [_SidecarHost, _ReleasedSyncHost])
+def test_fake_host_capture_retains_absent_and_replaced_generations(
+ host_type, system_pid_presence,
+):
+ from avibe_memory.process import _reference_state
+
+ host = host_type()
+ absent = host.capture(451)
+ assert _reference_state(absent, 451) is False
+
+ host.children[451] = _ProcessIdentity(stamp=10.5, cmdline=("fake-child",), uid=None)
+ assert _reference_state(absent, 451) is False
+ live = host.capture(451)
+ assert _reference_state(live, 451) is True
+
+ host.children[451] = _ProcessIdentity(stamp=11.5, cmdline=("replacement",), uid=None)
+ assert _reference_state(live, 451) is False
+ replacement = host.capture(451)
+ assert _reference_state(replacement, 451) is True
+ host.children.clear()
+ assert _reference_state(replacement, 451) is False
+
+
def _sidecar_record(home: Path) -> tuple[Path, dict[str, object]]:
provider_root = home / "memory" / "everos-root"
socket_path = home / "memory" / ".rt" / "everos.sock"
@@ -402,7 +441,9 @@ async def test_sidecar_reaper_does_not_signal_unverifiable_identity(
@pytest.mark.asyncio
-async def test_sidecar_reaper_fails_closed_on_unverifiable_tree(tmp_path: Path) -> None:
+async def test_sidecar_reaper_fails_closed_on_unverifiable_tree(
+ tmp_path: Path, system_pid_presence,
+) -> None:
home = tmp_path / "home"
provider_root = home / "memory" / "everos-root"
provider_root.mkdir(mode=0o700, parents=True)
@@ -428,6 +469,7 @@ async def test_sidecar_reaper_fails_closed_on_unverifiable_tree(tmp_path: Path)
async def test_released_sync_reaper_retires_gone_ownership(
tmp_path: Path,
state: str,
+ system_pid_presence,
) -> None:
home = tmp_path / "home"
provider_root = home / "memory" / "everos-root"
@@ -484,6 +526,7 @@ async def test_released_sync_reaper_stops_exact_live_child(
@pytest.mark.asyncio
async def test_released_sync_reaper_sweeps_exact_helper_after_leader_exits(
tmp_path: Path,
+ system_pid_presence,
) -> None:
home = tmp_path / "home"
provider_root = home / "memory" / "everos-root"
diff --git a/tests/test_memory_upgrade_packaged.py b/tests/test_memory_upgrade_packaged.py
index 4469def13..1dc9b40ec 100644
--- a/tests/test_memory_upgrade_packaged.py
+++ b/tests/test_memory_upgrade_packaged.py
@@ -4,6 +4,9 @@ import os
import shutil
import subprocess
import sys
+import threading
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
@@ -65,7 +68,7 @@ def _venv(path: Path) -> Path:
@pytest.fixture(scope="module")
def packaged_release_wheels(tmp_path_factory: pytest.TempPathFactory) -> Path:
wheelhouse = tmp_path_factory.mktemp("packaged-release-wheels")
- for version in ("3.0.14", "3.0.15"):
+ for version in ("3.0.14", "3.0.15", "3.0.15.dev1"):
_build_release_wheels(version, wheelhouse)
return wheelhouse
@@ -150,6 +153,53 @@ def _plan_env(wheelhouse: Path) -> dict[str, str]:
}
+def companion_release(tmp_path: Path, wheelhouse: Path, monkeypatch, request):
+ """Memory is served as an HTTP release asset, never from the package index."""
+
+ assets = tmp_path / "release assets 中文"
+ version = getattr(request, "param", "3.0.15")
+ tag = assets / f"v{version}"
+ tag.mkdir(parents=True)
+ wheel = next(wheelhouse.glob(f"avibe_memory-{version}-*.whl"))
+ shutil.move(wheel, tag / wheel.name)
+ # Core and ordinary dependencies remain in the simulated package index.
+ server = ThreadingHTTPServer(
+ ("127.0.0.1", 0), partial(SimpleHTTPRequestHandler, directory=str(assets))
+ )
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ base = f"http://127.0.0.1:{server.server_port}"
+ monkeypatch.setattr("vibe.upgrade.RELEASE_DOWNLOAD_BASE_URL", base)
+ try:
+ yield tag / wheel.name, f"{base}/v{version}/{wheel.name}"
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def _assert_installed_index_core_admission(python: Path, version: str, tmp_path: Path) -> None:
+ """Read the actual installed API; index installs carry no PEP610 origin."""
+
+ env = {**os.environ, "AVIBE_HOME": str(tmp_path / "admission-home"), "PYTHONPATH": ""}
+ env.pop("VIBE_BUILD_METADATA_PATH", None)
+ result = subprocess.run(
+ [str(python), "-c", """
+import sys
+from importlib.metadata import distribution
+from vibe import api
+from vibe.upgrade import release_asset_specs
+version = sys.argv[1]
+assert distribution("avibe-os").read_text("direct_url.json") is None
+assert release_asset_specs(version) is None
+assert api._published_running_version() == version
+""", version],
+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=60,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
@pytest.mark.integration
def test_memory_indep_021_packaged_core_only_status_blocks_optional_imports(
tmp_path: Path,
@@ -217,10 +267,12 @@ assert not any(
@pytest.mark.integration
[email protected]("companion_release", ["3.0.15", "3.0.15.dev1"], indirect=True)
def test_packaged_memory_shape_survives_synchronous_upgrade(
tmp_path: Path,
packaged_dependency_seed: Path,
wheelhouse: Path,
+ companion_release,
) -> None:
"""Run the public planner and executor across a paired package upgrade."""
@@ -233,22 +285,25 @@ def test_packaged_memory_shape_survives_synchronous_upgrade(
env = _plan_env(wheelhouse)
assert _installed_versions(python)["avibe-os"] == "3.0.14"
assert _installed_versions(python)["avibe-memory"] == "3.0.14"
+ target_version = companion_release[0].parent.name.removeprefix("v")
forward = build_upgrade_plan(
python_executable=str(python),
base_env=env,
memory_enabled=True,
memory_package=True,
- target_version="3.0.15",
+ target_version=target_version,
package_spec="avibe-os",
)
- assert "avibe-os[memory]" in forward.command
- assert "avibe-memory==3.0.15" in forward.command
+ assert "avibe-os" in forward.command
+ assert f"avibe-memory @ {companion_release[1]}" in forward.command
+ assert not list(wheelhouse.glob(f"avibe_memory-{target_version}-*.whl"))
result = execute_upgrade_plan(forward, cwd=tmp_path, capture_output=True, text=True, check=False, timeout=600)
assert result.returncode == 0, result.stdout + result.stderr
upgraded = _installed_versions(python)
- assert upgraded["avibe-os"] == "3.0.15"
- assert upgraded["avibe-memory"] == "3.0.15"
+ assert upgraded["avibe-os"] == target_version
+ assert upgraded["avibe-memory"] == target_version
+ _assert_installed_index_core_admission(python, target_version, tmp_path)
@pytest.mark.integration
@@ -272,19 +327,22 @@ def test_packaged_core_only_upgrade_preserves_core_only_shape(
@pytest.mark.integration
[email protected]("companion_release", ["3.0.15", "3.0.15.dev1"], indirect=True)
def test_packaged_missing_memory_fails_before_install(
- tmp_path: Path, packaged_dependency_seed: Path, wheelhouse: Path
+ tmp_path: Path, packaged_dependency_seed: Path, wheelhouse: Path, companion_release,
) -> None:
python = _venv(tmp_path / "missing-memory-venv")
_install_initial(python, wheelhouse, memory=True, dependency_seed=packaged_dependency_seed)
for wheel in wheelhouse.glob("avibe_memory-*.whl"):
wheel.unlink()
+ companion_release[0].unlink()
+ target_version = companion_release[0].parent.name.removeprefix("v")
plan = build_upgrade_plan(
python_executable=str(python),
base_env=_plan_env(wheelhouse),
memory_enabled=True,
memory_package=True,
- target_version="3.0.15",
+ target_version=target_version,
package_spec="avibe-os",
)
result = execute_upgrade_plan(plan, cwd=tmp_path, capture_output=True, text=True, check=False, timeout=600)
@@ -292,3 +350,88 @@ def test_packaged_missing_memory_fails_before_install(
versions = _installed_versions(python)
assert versions["avibe-os"] == "3.0.14"
assert versions["avibe-memory"] == "3.0.14"
+
+
[email protected]("companion_release", ["3.0.15", "3.0.15.dev1"], indirect=True)
+def test_core_only_bootstrap_then_exact_github_companion_repair(
+ tmp_path: Path, packaged_dependency_seed: Path, wheelhouse: Path, companion_release,
+) -> None:
+ """The migration entry installs core first; new code can then add Memory."""
+
+ python = _venv(tmp_path / "bootstrap-venv")
+ _install_initial(python, wheelhouse, memory=False, dependency_seed=packaged_dependency_seed)
+ target_version = companion_release[0].parent.name.removeprefix("v")
+ core = build_upgrade_plan(
+ python_executable=str(python), base_env=_plan_env(wheelhouse),
+ memory_package=False, package_spec=f"avibe-os=={target_version}",
+ )
+ result = execute_upgrade_plan(core, cwd=tmp_path, capture_output=True, text=True, timeout=600)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert _installed_versions(python)["avibe-os"] == target_version
+ assert "avibe-memory" not in _installed_versions(python)
+ _assert_installed_index_core_admission(python, target_version, tmp_path)
+ repair = build_upgrade_plan(
+ python_executable=str(python), base_env=_plan_env(wheelhouse),
+ version=target_version, memory_package=True,
+ )
+ assert f"avibe-memory @ {companion_release[1]}" in repair.command
+ result = execute_upgrade_plan(repair, cwd=tmp_path, capture_output=True, text=True, timeout=600)
+ assert result.returncode == 0, result.stdout + result.stderr
+ versions = _installed_versions(python)
+ assert versions["avibe-os"] == versions["avibe-memory"] == target_version
+
+
[email protected]("missing", [False, True])
[email protected]("companion_release", ["3.0.15", "3.0.15.dev1"], indirect=True)
+def test_packaged_uv_upgrade_uses_github_companion_before_activation(
+ tmp_path: Path, packaged_dependency_seed: Path, wheelhouse: Path, companion_release,
+ monkeypatch, missing: bool,
+) -> None:
+ uv = shutil.which("uv")
+ assert uv, "the packaged upgrade job must provide uv"
+ for artifact in packaged_dependency_seed.iterdir():
+ if not artifact.name.lower().startswith(("avibe_os-", "avibe_memory-")):
+ shutil.copy2(artifact, wheelhouse / artifact.name)
+ tools = tmp_path / "old" / "uv" / "tools"
+ binaries = tmp_path / "old" / "bin"
+ env = {
+ **os.environ,
+ "UV_TOOL_DIR": str(tools), "UV_TOOL_BIN_DIR": str(binaries),
+ "UV_NO_INDEX": "1", "UV_FIND_LINKS": str(wheelhouse),
+ "UV_PYTHON": sys.executable,
+ }
+ initial = subprocess.run(
+ [
+ uv, "tool", "install", "avibe-os==3.0.14",
+ "--with", str(next(wheelhouse.glob("avibe_memory-3.0.14-*.whl"))),
+ ],
+ env=env, cwd=tmp_path, capture_output=True, text=True, timeout=600,
+ )
+ assert initial.returncode == 0, initial.stdout + initial.stderr
+ python = _python(tools / "avibe-os")
+ launcher = binaries / ("vibe.exe" if os.name == "nt" else "vibe")
+ original_launcher = launcher.read_bytes()
+ monkeypatch.setattr("vibe.upgrade.atomic_uv_install_root", lambda: tmp_path / "candidate-generations")
+ if missing:
+ companion_release[0].unlink()
+ target_version = companion_release[0].parent.name.removeprefix("v")
+ plan = build_upgrade_plan(
+ python_executable=str(python), uv_path=uv, vibe_path=str(launcher),
+ base_env=env, memory_package=True, target_version=target_version,
+ package_spec="avibe-os",
+ )
+ assert plan.activation is not None and not plan.preflight_error
+ assert f"avibe-memory @ {companion_release[1]}" in plan.command
+ result = execute_upgrade_plan(plan, cwd=tmp_path, capture_output=True, text=True, timeout=600)
+ assert (result.returncode == 0) is not missing, result.stdout + result.stderr
+ assert launcher.read_bytes() == original_launcher
+ old = _installed_versions(python)
+ assert old["avibe-os"] == old["avibe-memory"] == "3.0.14"
+ if not missing:
+ candidate = _installed_versions(_python(Path(plan.env["UV_TOOL_DIR"]) / "avibe-os"))
+ assert candidate["avibe-os"] == candidate["avibe-memory"] == target_version
+ _assert_installed_index_core_admission(
+ _python(Path(plan.env["UV_TOOL_DIR"]) / "avibe-os"), target_version, tmp_path,
+ )
diff --git a/tests/test_release_package_version.py b/tests/test_release_package_version.py
index 44eeda8f9..010406a34 100644
--- a/tests/test_release_package_version.py
+++ b/tests/test_release_package_version.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from pathlib import Path
import pytest
+from packaging.version import Version
from scripts.release_package_version import package_version_from_release_tag
@@ -14,13 +15,41 @@ from scripts.release_package_version import package_version_from_release_tag
("v3.0.10rc1", "3.0.10rc1"),
("gh-v3.0.10rc1", "3.0.10rc1"),
("gh-v4.1.0b2", "4.1.0b2"),
+ ("v3.2.0rc1", "3.2.0rc1"),
+ ("gh-v3.2.0-rc1", "3.2.0rc1"),
+ ("gh-v3.2.0.rc01", "3.2.0rc1"),
+ ("gh-v03.02.00-dev01", "3.2.0.dev1"),
+ ("v3.2.0.post1", "3.2.0.post1"),
+ ("gh-v3.2.0-a01.post02", "3.2.0a1.post2"),
],
)
def test_package_version_from_release_tag(tag: str, expected: str) -> None:
assert package_version_from_release_tag(tag) == expected
[email protected]("tag", ["", "3.0.10rc1", "release-v3.0.10", "gh-vnext"])
[email protected]("prefix", ["v", "gh-v"])
[email protected]("release", ["3.1.0", "03.02.001"])
[email protected]("phase", ["a", "b", "rc", "dev"])
[email protected]("separator", ["", ".", "-"])
[email protected]("number", ["0", "01", "12"])
+def test_supported_tag_grammar_matches_build_backend_normalization(
+ prefix, release, phase, separator, number,
+) -> None:
+ version = f"{release}{separator}{phase}{number}"
+ for suffix in (["", ".post01"] if phase != "dev" else [""]):
+ spelling = version + suffix
+ canonical = str(Version(spelling))
+ if prefix == "v" and spelling != canonical:
+ with pytest.raises(ValueError, match="canonical spelling"):
+ package_version_from_release_tag(prefix + spelling)
+ else:
+ assert package_version_from_release_tag(prefix + spelling) == canonical
+
+
+ "tag",
+ ["", "3.0.10rc1", "release-v3.0.10", "gh-vnext", "v3.1.0dev1.post2", "v3.1.0+local"],
+)
def test_package_version_from_release_tag_rejects_unsupported_tags(tag: str) -> None:
with pytest.raises(ValueError):
package_version_from_release_tag(tag)
diff --git a/tests/test_release_verification.py b/tests/test_release_verification.py
index da65282d5..8e7303f27 100644
--- a/tests/test_release_verification.py
+++ b/tests/test_release_verification.py
@@ -1,14 +1,20 @@
from __future__ import annotations
import json
+from http.server import BaseHTTPRequestHandler
import os
from pathlib import Path
+import shlex
import subprocess
import sys
+import shutil
+import threading
import pytest
import yaml
+from tests.e2e.github_release_fixture import create_certificate, make_server
+
ROOT = Path(__file__).resolve().parents[1]
WORKFLOWS = (
@@ -17,6 +23,290 @@ WORKFLOWS = (
)
[email protected]("failure", [None, "missing-wheel", "missing-sdist", "mismatch", "unpublished"])
+ ("tag", "version"),
+ [("v3.1.0", "3.1.0"), ("v3.2.0rc1", "3.2.0rc1"),
+ ("gh-v3.2.0-rc1", "3.2.0rc1"), ("gh-v3.2.0.dev01", "3.2.0.dev1")],
+)
+def test_public_companion_gate_checks_both_exact_assets_without_auth(tmp_path, failure, tag, version):
+ workspace = tmp_path / "public release 中文"
+ dist = workspace / "dist"
+ scripts = workspace / "scripts"
+ binaries = tmp_path / "bin"
+ runtime_tmp = tmp_path / "runner temp"
+ for directory in (dist, scripts, binaries, runtime_tmp):
+ directory.mkdir(parents=True)
+ shutil.copy2(ROOT / "scripts/release_package_version.py", scripts)
+ assets = {
+ f"avibe_memory-{version}-py3-none-any.whl": b"companion wheel",
+ f"avibe_memory-{version}.tar.gz": b"companion sdist",
+ }
+ for name, data in assets.items():
+ (dist / name).write_bytes(data)
+ if failure in {"missing-wheel", "missing-sdist"}:
+ suffix = ".whl" if failure == "missing-wheel" else ".tar.gz"
+ next(dist.glob(f"*{suffix}")).unlink()
+ (binaries / "python").symlink_to(sys.executable)
+ curl = binaries / "curl"
+ curl.write_text(
+ f"#!{sys.executable}\n"
+ "import json, pathlib, sys\n"
+ "args = sys.argv[1:]\n"
+ "assert not any('authorization' in arg.lower() for arg in args)\n"
+ "url = args[-1]\n"
+ f"assert url.startswith('https://github.com/avibe-bot/avibe/releases/download/{tag}/')\n"
+ "with pathlib.Path('fetches.jsonl').open('a') as log: log.write(json.dumps(url) + '\\n')\n"
+ f"sys.exit(22) if {failure == 'unpublished'!r} else None\n"
+ "asset = url.rsplit('/', 1)[1]\n"
+ f"data = {assets!r}[asset]\n"
+ f"data = b'wrong' if {failure == 'mismatch'!r} else data\n"
+ "pathlib.Path(args[args.index('--output') + 1]).write_bytes(data)\n",
+ encoding="utf-8",
+ )
+ curl.chmod(0o755)
+ command = _step(
+ _job("publish.yml", "verify-avibe-memory-release"),
+ "Verify public GitHub companion distributions",
+ )["run"]
+ result = subprocess.run(
+ ["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", command],
+ cwd=workspace,
+ env={
+ **os.environ,
+ "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "RUNNER_TEMP": str(runtime_tmp),
+ "RELEASE_TAG": tag,
+ "GITHUB_REPOSITORY": "avibe-bot/avibe",
+ },
+ capture_output=True, text=True, timeout=15,
+ )
+ assert (result.returncode == 0) is (failure is None), result.stdout + result.stderr
+ assert not list(runtime_tmp.iterdir())
+ if failure is None:
+ fetches = [json.loads(line) for line in (workspace / "fetches.jsonl").read_text().splitlines()]
+ assert {url.rsplit("/", 1)[1] for url in fetches} == set(assets)
+ for path in dist.iterdir():
+ assert path.read_bytes() == assets[path.name]
+
+
[email protected]("availability", ["transient-404", "permanent-404", "wrong-bytes"])
+def test_public_gate_with_real_curl_retries_availability_but_never_integrity(tmp_path, availability):
+ workspace = tmp_path / "published 中文"
+ dist = workspace / "dist"
+ scripts = workspace / "scripts"
+ binaries = tmp_path / "bin"
+ temporary = tmp_path / "runner temp"
+ for directory in (dist, scripts, binaries, temporary):
+ directory.mkdir(parents=True)
+ shutil.copy2(ROOT / "scripts/release_package_version.py", scripts)
+ assets = {
+ "avibe_memory-3.1.0-py3-none-any.whl": b"exact wheel bytes",
+ "avibe_memory-3.1.0.tar.gz": b"exact sdist bytes",
+ }
+ for name, data in assets.items():
+ (dist / name).write_bytes(data)
+ attempts = {}
+
+ class ReleaseHandler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ assert self.headers["Host"] == "github.com"
+ assert self.headers.get("Authorization") is None
+ prefix = "/avibe-bot/avibe/releases/download/v3.1.0/"
+ assert self.path.startswith(prefix)
+ name = self.path.removeprefix(prefix)
+ attempts[name] = attempts.get(name, 0) + 1
+ missing = availability == "permanent-404" or (
+ availability == "transient-404" and attempts[name] == 1
+ )
+ body = b"not yet public" if missing else assets[name]
+ if availability == "wrong-bytes":
+ body = b"incorrect successful download"
+ self.send_response(404 if missing else 200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ ca, cert, key = create_certificate(tmp_path / "TLS 中文")
+ server = make_server(tmp_path, cert, key, handler=ReleaseHandler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ actual_curl = shutil.which("curl")
+ assert actual_curl
+ curl = binaries / "curl"
+ # Redirect only the test connection, never the requested URL or TLS
+ # hostname. Execute actual curl with the workflow's unchanged options.
+ curl.write_text(
+ "#!/bin/sh\nexec " + shlex.join([
+ actual_curl, "--disable", "--noproxy", "*", "--cacert", str(ca),
+ "--connect-to", f"github.com:443:127.0.0.1:{server.server_port}",
+ ]) + ' "$@"\n', encoding="utf-8",
+ )
+ curl.chmod(0o755)
+ (binaries / "python").symlink_to(sys.executable)
+ command = _step(_job("publish.yml", "verify-avibe-memory-release"),
+ "Verify public GitHub companion distributions")["run"]
+ result = subprocess.run(
+ ["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", command],
+ cwd=workspace,
+ env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "RUNNER_TEMP": str(temporary), "RELEASE_TAG": "v3.1.0",
+ "GITHUB_REPOSITORY": "avibe-bot/avibe"},
+ capture_output=True, text=True, timeout=45,
+ )
+ assert (result.returncode == 0) is (availability == "transient-404"), result.stderr
+ if availability == "transient-404":
+ assert attempts == {name: 2 for name in assets}
+ else:
+ assert attempts == {
+ "avibe_memory-3.1.0-py3-none-any.whl": 6 if availability == "permanent-404" else 1,
+ }
+ assert {p.name: p.read_bytes() for p in dist.iterdir()} == assets
+ assert not list(temporary.iterdir())
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
[email protected](("workflow_name", "job_name", "checkout_name", "workflow_ref"), WORKFLOWS)
[email protected]("tag", ["v3.2.0-rc1", "v03.02.00"])
+def test_noncanonical_official_tags_fail_before_artifact_construction(
+ tmp_path, workflow_name, job_name, checkout_name, workflow_ref, tag,
+):
+ scripts = tmp_path / "scripts"
+ scripts.mkdir()
+ shutil.copy2(ROOT / "scripts/release_package_version.py", scripts)
+ binaries = tmp_path / "bin"
+ binaries.mkdir()
+ (binaries / "python").symlink_to(sys.executable)
+ command = _step(_job(workflow_name, job_name), "Pin package version to release tag")["run"]
+ result = subprocess.run(
+ ["bash", "-e", "-o", "pipefail", "-c", command + "\ntouch artifact-construction-reached"],
+ cwd=tmp_path, env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "RELEASE_TAG": tag, "GITHUB_ENV": str(tmp_path / "github-env")},
+ capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode != 0
+ assert "canonical spelling" in result.stderr
+ assert not (tmp_path / "artifact-construction-reached").exists()
+ assert not (tmp_path / "github-env").exists()
+
[email protected]("workflow_name", ["publish.yml", "release_ai.yml"])
+ "state",
+ ["empty", "identical", "partial", "core-mismatch", "memory-wheel-mismatch",
+ "memory-sdist-mismatch", "runtime-mismatch", "missing-wheel", "empty-sdist", "read-failure"],
+)
+def test_upload_protects_all_existing_bytes_before_any_write(tmp_path, workflow_name, state):
+ workspace = tmp_path / "release source 中文"
+ dist = workspace / "dist"
+ runtime = workspace / ("runtime-artifacts" if workflow_name == "publish.yml" else "dist")
+ binaries = tmp_path / "bin"
+ temporary = tmp_path / "temp"
+ for path in {workspace, dist, runtime, binaries, temporary}:
+ path.mkdir(parents=True, exist_ok=True)
+ packages = {
+ f"{package}-3.1.0{suffix}": f"{package}{suffix}".encode()
+ for package in ("avibe_os", "avibe_memory")
+ for suffix in ("-py3-none-any.whl", ".tar.gz")
+ }
+ if workflow_name == "publish.yml":
+ # Preserve the optional legacy package upload path too.
+ packages["vibe_remote-3.0.14-py3-none-any.whl"] = b"legacy shim"
+ runtimes = {
+ **{f"vibe-show-runtime-node-{platform}.tgz": platform.encode()
+ for platform in ("linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64")},
+ **{f"memory-runtime-1.2.3-{platform}.tar.gz": platform.encode()
+ for platform in ("linux-x64", "linux-arm64", "darwin-arm64")},
+ "show-runtime-manifest.json": b"show manifest",
+ "memory-runtime-manifest.json": b"memory manifest",
+ }
+ for directory, assets in ((dist, packages), (runtime, runtimes)):
+ for name, data in assets.items():
+ (directory / name).write_bytes(data)
+ all_assets = {**packages, **runtimes}
+ existing = dict(all_assets) if state == "identical" else {}
+ if state not in {"empty", "identical"}:
+ existing = {name: all_assets[name] for name in (
+ "avibe_os-3.1.0-py3-none-any.whl", "avibe_memory-3.1.0-py3-none-any.whl",
+ "avibe_memory-3.1.0.tar.gz", "show-runtime-manifest.json",
+ )}
+ mismatch = {
+ "core-mismatch": "avibe_os-3.1.0-py3-none-any.whl",
+ "memory-wheel-mismatch": "avibe_memory-3.1.0-py3-none-any.whl",
+ "memory-sdist-mismatch": "avibe_memory-3.1.0.tar.gz",
+ "runtime-mismatch": "show-runtime-manifest.json",
+ }.get(state)
+ if mismatch:
+ existing[mismatch] = b"already published different bytes"
+ if state == "missing-wheel":
+ (dist / "avibe_memory-3.1.0-py3-none-any.whl").unlink()
+ if state == "empty-sdist":
+ (dist / "avibe_memory-3.1.0.tar.gz").write_bytes(b"")
+
+ # Only gh and the metadata helper are simulated; run the complete upload
+ # shell, including real file comparisons, globs, temp cleanup and ordering.
+ gh = binaries / "gh"
+ gh.write_text(
+ f"#!{sys.executable}\n"
+ "import json, pathlib, sys\n"
+ "args = sys.argv[1:]\n"
+ f"existing = {existing!r}\n"
+ "with pathlib.Path('events.jsonl').open('a') as stream:\n"
+ " stream.write(json.dumps(args) + '\\n')\n"
+ "if args[1] == 'view':\n"
+ f" sys.exit(1) if {state == 'read-failure'!r} else None\n"
+ " print('\\n'.join(existing))\n"
+ "elif args[1] == 'download':\n"
+ " name = args[args.index('--pattern') + 1]\n"
+ " (pathlib.Path(args[args.index('--dir') + 1]) / name).write_bytes(existing[name])\n"
+ "elif args[1] == 'upload':\n"
+ " assert '--clobber' not in args\n"
+ " for path in args[args.index('--repo') + 2:]:\n"
+ " assert pathlib.Path(path).name not in existing\n"
+ " assert pathlib.Path(path).is_file()\n"
+ "else: raise AssertionError(args)\n",
+ encoding="utf-8",
+ )
+ gh.chmod(0o755)
+ python = binaries / "python"
+ python.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ python.chmod(0o755)
+ if workflow_name == "publish.yml":
+ command = _step(_job(workflow_name, "build"), "Upload GitHub release assets")["run"]
+ command = command.replace("${{ needs.resolve-tag.outputs.tag }}", "v3.1.0")
+ else:
+ command = _step(_job(workflow_name, "release"), "Create GitHub-only Release")["run"]
+ command = command.replace("${{ steps.tag.outputs.tag }}", "gh-v3.1.0")
+ command = command.replace("${{ steps.release_type.outputs.prerelease }}", "true")
+ result = subprocess.run(
+ ["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", command],
+ cwd=workspace, env={**os.environ, "PATH": f"{binaries}{os.pathsep}{os.environ['PATH']}",
+ "TMPDIR": str(temporary), "GITHUB_REPOSITORY": "avibe-bot/avibe"},
+ capture_output=True, text=True, timeout=20,
+ )
+ success = state in {"empty", "identical", "partial"}
+ assert (result.returncode == 0) is success, result.stdout + result.stderr
+ events = [json.loads(line) for line in (workspace / "events.jsonl").read_text().splitlines()]
+ uploads = [event for event in events if event[1] == "upload"]
+ if not success:
+ assert not uploads
+ else:
+ uploaded = [Path(path).name for event in uploads for path in event[event.index("--repo") + 2:]]
+ assert len(uploaded) == len(set(uploaded))
+ assert set(uploaded) == set(all_assets) - set(existing)
+ if uploads:
+ first_upload = events.index(uploads[0])
+ assert all(event[1] != "download" for event in events[first_upload:])
+ kinds = [name in packages for name in uploaded]
+ assert kinds == sorted(kinds), "Runtime uploads must complete before package uploads"
+ assert not list(temporary.iterdir())
+
def _job(workflow_name: str, job_name: str) -> dict:
workflow = yaml.safe_load((ROOT / ".github/workflows" / workflow_name).read_text(encoding="utf-8"))
return workflow["jobs"][job_name]
@@ -50,6 +340,7 @@ def test_release_verification_is_workflow_owned_after_tagged_artifacts_are_built
expected_files = {"tests/test_memory_distribution.py"}
if workflow_name == "publish.yml":
expected_files.add("scripts/github_release.py")
+ expected_files.add("scripts/release_package_version.py")
assert set(checkout["with"]["sparse-checkout"].splitlines()) == expected_files
assert steps.index(source) < steps.index(build) < steps.index(checkout) < steps.index(verify)
assert all(not step.get("if") and not step.get("continue-on-error") for step in (checkout, verify))
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 663e82554..f4426bd99 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -958,9 +958,14 @@ def test_an_exact_plan_never_asks_for_an_upgrade_and_always_forces_the_install(m
assert FORCES_THE_INSTALL[plan.method] in plan.command
-def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monkeypatch):
- # The repair reaches an index by default. A caller that names no install
- # source gets exactly the pins it got before install sources existed.
+def _official_memory(version):
+ return (
+ "avibe-memory @ https://github.com/avibe-bot/avibe/releases/download/"
+ f"v{version}/avibe_memory-{version}-py3-none-any.whl"
+ )
+
+
+def test_an_exact_memory_plan_uses_the_official_companion_without_a_source(monkeypatch):
monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)
monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)
@@ -980,7 +985,7 @@ def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monk
"install",
"avibe-os==3.0.10",
"--with",
- "avibe-memory==3.0.10",
+ _official_memory("3.0.10"),
"--force",
]
assert uv_plan.preflight_command == [
@@ -991,7 +996,7 @@ def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monk
"--python",
"/tmp/.local/share/uv/tools/avibe-os/bin/python",
"avibe-os==3.0.10",
- "avibe-memory==3.0.10",
+ _official_memory("3.0.10"),
]
assert uv_plan.activation is not None
assert uv_plan.env["UV_TOOL_DIR"] != "/tmp/.local/share/uv/tools"
@@ -1013,7 +1018,7 @@ def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monk
"install",
"--force-reinstall",
"avibe-os==3.0.10",
- "avibe-memory==3.0.10",
+ _official_memory("3.0.10"),
]
assert pip_plan.preflight_command == [
"/usr/bin/python3",
@@ -1024,7 +1029,7 @@ def test_an_exact_memory_plan_names_both_index_pins_when_no_source_is_given(monk
PIP_DOWNLOAD_DEST_PLACEHOLDER,
"--no-deps",
"avibe-os==3.0.10",
- "avibe-memory==3.0.10",
+ _official_memory("3.0.10"),
]
@@ -1049,7 +1054,7 @@ def test_the_companion_comes_from_the_release_core_was_installed_from(monkeypatc
assert release_asset_specs(PREVIEW_VERSION) == (PREVIEW_CORE_URL, PREVIEW_MEMORY_URL)
-def test_an_official_prerelease_on_pypi_keeps_its_index_pins(monkeypatch):
+def test_an_official_prerelease_on_pypi_keeps_core_on_its_index(monkeypatch):
# `publish.yml` accepts official `vX.Y.ZrcN` tags and publishes them to
# PyPI. Such a build carries a version indistinguishable from a `gh-v*`
# one, so only its origin can say that `gh-v3.0.16rc1` was never created.
@@ -1098,7 +1103,7 @@ def test_one_normalization_matches_the_origin_and_names_the_companion(monkeypatc
(PREVIEW_CORE_URL, "not-a-version"),
],
)
-def test_an_origin_that_cannot_name_this_pair_keeps_index_pins(monkeypatch, origin, version):
+def test_an_origin_that_cannot_name_this_pair_cannot_redirect_repair(monkeypatch, origin, version):
_installed_from(monkeypatch, origin)
assert release_asset_specs(version) is None
@@ -1196,10 +1201,7 @@ def test_an_exact_plan_installs_the_named_sources_instead_of_index_pins(monkeypa
assert FORCES_THE_INSTALL[plan.method] in plan.command
-def test_a_forward_upgrade_keeps_index_pins_and_admits_no_install_source(monkeypatch):
- # A forward upgrade resolves whichever release is newest, so there is no
- # known release to name. Ignoring a source here would report an install
- # from the release that never happened.
+def test_a_forward_upgrade_uses_target_companion_and_rejects_exact_source_overrides(monkeypatch):
monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)
forward = {
"python_executable": "/usr/bin/python3",
@@ -1209,8 +1211,8 @@ def test_a_forward_upgrade_keeps_index_pins_and_admits_no_install_source(monkeyp
}
plan = build_upgrade_plan(**forward)
- assert "avibe-os[memory]==3.1.0" in plan.command
- assert "avibe-memory==3.1.0" in plan.command
+ assert "avibe-os==3.1.0" in plan.command
+ assert _official_memory("3.1.0") in plan.command
for sources in (
{"core_spec": PREVIEW_CORE_URL},
@@ -1306,6 +1308,7 @@ def test_a_forward_upgrade_on_an_undamaged_install_is_left_to_the_installer(monk
# agree with the code, so there is nothing to force -- the count of
# distributions is not by itself a disagreement.
("two distributions provide it and both agree", ["avibe-os", "vibe-remote"], "3.0.11", "3.0.11"),
+ ("public dev metadata agrees", ["avibe-os"], "3.2.0.dev1", "3.2.0.dev1"),
# A regression build. Its version describes a tree, not a release, so a
# disagreement with published metadata is expected rather than evidence.
("the running version names no release", ["avibe-os"], "3.0.11", "0.0.0.dev0+abc1234"),
@@ -2218,7 +2221,7 @@ def test_cmd_upgrade_metadata_failure_uses_exact_memory_artifact(monkeypatch, tm
assert cli.cmd_upgrade() == 0
assert "Attempting upgrade anyway..." in capsys.readouterr().out
- assert "avibe-memory==3.1.0" in calls["plan"].command
+ assert _official_memory("3.1.0") in calls["plan"].command
def test_cmd_upgrade_metadata_failure_refuses_unversioned_memory_source(monkeypatch, capsys):
@@ -2282,8 +2285,8 @@ def test_memory_enabled_forward_plan_locks_memory_to_target_release(monkeypatch)
package_spec="avibe-os>=3.1,<3.2",
)
- target = "avibe-os[memory]<3.2,>=3.1"
- memory = "avibe-memory==3.1.0"
+ target = "avibe-os>=3.1,<3.2"
+ memory = _official_memory("3.1.0")
assert plan.command == ["/usr/bin/python3", "-m", "pip", "install", "--upgrade", target, memory]
assert plan.preflight_command == [
"/usr/bin/python3",
@@ -2344,7 +2347,7 @@ def test_memory_enabled_forward_plan_derives_target_from_versioned_spec(
package_spec=package_spec,
)
- memory_pin = f"avibe-memory=={target_version}"
+ memory_pin = _official_memory(target_version)
assert memory_pin in plan.command
assert plan.preflight_command is not None and memory_pin in plan.preflight_command
assert plan.preflight_fallback_command is not None and memory_pin in plan.preflight_fallback_command
@@ -2371,8 +2374,8 @@ def test_exact_package_spec_overrides_conflicting_memory_target(monkeypatch, pac
for command in (plan.command, plan.preflight_command, plan.preflight_fallback_command):
assert command is not None
- assert "avibe-memory==3.2.0" in command
- assert "avibe-memory==3.1.0" not in command
+ assert _official_memory("3.2.0") in command
+ assert _official_memory("3.1.0") not in command
def test_uv_exact_artifact_overrides_conflicting_memory_target(monkeypatch):
@@ -2389,11 +2392,11 @@ def test_uv_exact_artifact_overrides_conflicting_memory_target(monkeypatch):
package_spec="/fixtures/avibe_os-3.2.0-py3-none-any.whl",
)
- assert "avibe-memory==3.2.0" in plan.command
- assert "avibe-memory==3.1.0" not in plan.command
+ assert _official_memory("3.2.0") in plan.command
+ assert _official_memory("3.1.0") not in plan.command
assert plan.preflight_command is not None
- assert "avibe-memory==3.2.0" in plan.preflight_command
- assert "avibe-memory==3.1.0" not in plan.preflight_command
+ assert _official_memory("3.2.0") in plan.preflight_command
+ assert _official_memory("3.1.0") not in plan.preflight_command
@pytest.mark.parametrize(
@@ -2415,7 +2418,7 @@ def test_named_package_spec_accepts_compatible_memory_target(monkeypatch, packag
package_spec=package_spec,
)
- assert "avibe-memory==3.1.4" in plan.command
+ assert _official_memory("3.1.4") in plan.command
def test_named_package_spec_rejects_incompatible_memory_target(monkeypatch):
@@ -2629,8 +2632,8 @@ def test_uv_forward_plan_locks_memory_to_target_release(monkeypatch):
package_spec="avibe-os>=3.1,<3.2",
)
- target = "avibe-os[memory]<3.2,>=3.1"
- memory = "avibe-memory==3.1.0"
+ target = "avibe-os>=3.1,<3.2"
+ memory = _official_memory("3.1.0")
assert plan.command == [
"/usr/bin/uv",
"tool",
@@ -2668,9 +2671,9 @@ def test_explicit_memory_install_keeps_exact_package_version(monkeypatch):
assert "avibe-os==3.0.14" in plan.command
assert "avibe-os[memory]" not in " ".join(plan.command)
- assert "avibe-memory==3.0.14" in plan.command
+ assert _official_memory("3.0.14") in plan.command
assert plan.preflight_command is not None
- assert "avibe-memory==3.0.14" in plan.preflight_command
+ assert _official_memory("3.0.14") in plan.preflight_command
@pytest.mark.parametrize("launcher", (None, "/tmp/uv/tools/avibe-os/bin/vibe"))
@@ -2689,21 +2692,174 @@ def test_exact_uv_repair_without_a_stable_launcher_fails_before_mutation(monkeyp
run.assert_not_called()
-def test_with_memory_extra_preserves_vcs_url_and_local_specs(tmp_path, monkeypatch):
- from vibe.upgrade import _with_memory_extra
[email protected]("spec", [PREVIEW_CORE_URL, f"avibe-os @ {PREVIEW_CORE_URL}"])
+def test_forward_github_preview_preserves_target_release_not_installed_origin(monkeypatch, spec):
+ _installed_from(monkeypatch, PREVIEW_CORE_URL.replace("rc1", "rc0"))
+ monkeypatch.setattr(vibe_upgrade, "find_uv_binary", lambda **_: None)
+ plan = build_upgrade_plan(memory_package=True, package_spec=spec, target_version="3.1.1")
+ for command in (plan.command, plan.preflight_command, plan.preflight_fallback_command):
+ assert spec in command
+ assert f"avibe-memory @ {PREVIEW_MEMORY_URL}" in command
+ assert not any("[memory]" in item for item in command)
+
+
+def test_forward_index_target_does_not_inherit_current_preview_origin(monkeypatch):
+ _installed_from(monkeypatch, PREVIEW_CORE_URL)
+ monkeypatch.setattr(vibe_upgrade, "find_uv_binary", lambda **_: None)
+ plan = build_upgrade_plan(memory_package=True, package_spec="avibe-os", target_version="3.1.1")
+ assert _official_memory("3.1.1") in plan.command
+ assert not any("gh-v" in item for item in plan.command)
+
+
+ "tag", [
+ "v3.1.0", "v3.2.0a1", "v3.2.0b1", "v3.2.0rc1", "v3.2.0.dev1",
+ "v3.2.0.post1", "gh-v3.2.0-rc1", "gh-v03.02.00",
+ ],
+)
+def test_publication_tag_producer_and_installed_memory_consumer_select_same_directory(tag):
+ from scripts.release_package_version import package_version_from_release_tag
- assert _with_memory_extra("git+https://example.test/avibe.git@abc123#subdirectory=src") == (
- "avibe-os[memory] @ git+https://example.test/avibe.git@abc123#subdirectory=src"
+ version = package_version_from_release_tag(tag)
+ base = "https://github.com/avibe-bot/avibe/releases/download"
+ core = (
+ f"{base}/{tag}/avibe_os-{version}-py3-none-any.whl"
+ if tag.startswith("gh-v") else f"avibe-os=={version}"
+ )
+ assert vibe_upgrade.memory_release_spec(version, core) == (
+ f"{base}/{tag}/avibe_memory-{version}-py3-none-any.whl"
)
- assert _with_memory_extra("https://example.test/avibe.whl") == "avibe-os[memory] @ https://example.test/avibe.whl"
- assert _with_memory_extra("file:///tmp/avibe.whl") == "avibe-os[memory] @ file:///tmp/avibe.whl"
- assert _with_memory_extra("/fixtures/avibe.whl") == "avibe-os[memory] @ file:///fixtures/avibe.whl"
- monkeypatch.chdir(tmp_path)
- relative_artifact = Path("dist/avibe.whl")
- assert _with_memory_extra(str(relative_artifact)) == (
- f"avibe-os[memory] @ {(tmp_path / relative_artifact).resolve().as_uri()}"
+
[email protected]("version", ["3.1.1.dev1+local", "3.1.1+local", "bad"])
+def test_memory_asset_source_rejects_unpublished_versions(version):
+ with pytest.raises(ValueError, match="published target"):
+ vibe_upgrade.memory_release_spec(version, "avibe-os")
+
+
+ "v3.1.0", "v3.2.0a1", "v3.2.0b1", "v3.2.0rc1", "v3.2.0.dev0",
+ "v3.2.0.dev1", "v3.2.0.post1",
+])
[email protected]("method", ["pip", "uv"])
[email protected]("selection", ["exact", "forward-pin", "forward-latest"])
+def test_official_index_release_reaches_every_install_command(
+ monkeypatch, tmp_path, tag, method, selection,
+):
+ from scripts.release_package_version import package_version_from_release_tag
+
+ version = package_version_from_release_tag(tag)
+ # No PEP610 record is the normal index-install shape, including dev.
+ _installed_from(monkeypatch, None)
+ assert release_asset_specs(version) is None
+ monkeypatch.setattr(vibe_upgrade, "is_uv_tool_install", lambda _: method == "uv")
+ monkeypatch.setattr(vibe_upgrade, "is_legacy_uv_tool_install", lambda _: False)
+ monkeypatch.setattr(vibe_upgrade, "find_uv_binary", lambda **_: "/usr/bin/uv" if method == "uv" else None)
+ monkeypatch.setattr(vibe_upgrade, "atomic_uv_install_root", lambda: tmp_path / "generations")
+ core = "avibe-os" if selection == "forward-latest" else f"avibe-os=={version}"
+ source = {"version": version} if selection == "exact" else {
+ "package_spec": core, "target_version": version,
+ }
+ plan = build_upgrade_plan(
+ python_executable="/fixture/bin/python",
+ vibe_path=str(tmp_path / "bin" / "vibe"),
+ base_env={"PATH": "/usr/bin"},
+ memory_package=True,
+ **source,
)
+ assert plan.method == method
+ assert plan.preflight_error is None
+ assert (plan.activation is not None) is (method == "uv")
+ commands = [c for c in (plan.command, plan.preflight_command, plan.preflight_fallback_command) if c]
+ assert len(commands) >= 2
+ memory = f"avibe-memory @ {vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/{tag}/avibe_memory-{version}-py3-none-any.whl"
+ for command in commands:
+ assert core in command
+ assert memory in command
+ assert not any("[memory]" in item or item.startswith("avibe-memory==") for item in command)
+
+
+ "gh-v3.2.0.dev1", "gh-v3.2.0-dev1", "gh-v03.02.00dev01", "v3.2.0.dev1",
+])
[email protected]("method", ["pip", "uv"])
[email protected]("exact", [False, True], ids=["forward", "exact"])
[email protected]("named", [False, True], ids=["raw-url", "named-url"])
+def test_published_dev_origin_reaches_every_install_command(
+ monkeypatch, tmp_path, tag, method, exact, named,
+):
+ from scripts.release_package_version import package_version_from_release_tag
+
+ version = package_version_from_release_tag(tag)
+ directory = f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/{tag}"
+ core = f"{directory}/avibe_os-{version}-py3-none-any.whl"
+ memory = f"{directory}/avibe_memory-{version}-py3-none-any.whl"
+ _installed_from(monkeypatch, core)
+ assert release_asset_specs(version) == (core, memory)
+ assert vibe_upgrade.memory_release_spec(version, core) == memory
+
+ # A forward plan must use the selected target, not this older installed
+ # origin. This exercises the artifact-version gate as well as URL selection.
+ _installed_from(monkeypatch, PREVIEW_CORE_URL)
+ monkeypatch.setattr(vibe_upgrade, "is_uv_tool_install", lambda _: method == "uv")
+ monkeypatch.setattr(vibe_upgrade, "is_legacy_uv_tool_install", lambda _: False)
+ monkeypatch.setattr(vibe_upgrade, "find_uv_binary", lambda **_: "/usr/bin/uv" if method == "uv" else None)
+ monkeypatch.setattr(vibe_upgrade, "atomic_uv_install_root", lambda: tmp_path / "generations")
+ launcher = tmp_path / "bin" / "vibe"
+ spec = f"avibe-os @ {core}" if named else core
+ source = {"version": version, "core_spec": spec} if exact else {
+ "package_spec": spec, "target_version": "9.0.0",
+ }
+ plan = build_upgrade_plan(
+ python_executable="/fixture/bin/python",
+ vibe_path=str(launcher),
+ base_env={"PATH": "/usr/bin"},
+ memory_package=True,
+ **source,
+ )
+ assert plan.method == method
+ assert plan.preflight_error is None
+ assert (plan.activation is not None) is (method == "uv")
+ commands = [c for c in (plan.command, plan.preflight_command, plan.preflight_fallback_command) if c]
+ assert len(commands) >= 2
+ for command in commands:
+ assert spec in command
+ assert f"avibe-memory @ {memory}" in command
+ assert not any("9.0.0" in item or "[memory]" in item for item in command)
+
+
[email protected]("version,origin", [
+ ("3.2.0.dev1", None),
+ ("3.2.0.dev1", "/tmp/avibe_os-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", "file:///tmp/avibe_os-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", "https://example.test/avibe_os-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", "https://github.com/other/repo/releases/download/gh-v3.2.0.dev1/avibe_os-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev2/avibe_os-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev1/avibe_memory-3.2.0.dev1-py3-none-any.whl"),
+ ("3.2.0.dev1", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev1/avibe_os-3.2.0.dev1.tar.gz"),
+ ("3.2.0.dev1", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev1/avibe_os-3.2.0.dev1-py3-none-any.whl?other=1"),
+ ("3.2.0.dev1", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev1/avibe_os-3.2.0.dev1-py3-none-any.whl#other"),
+ ("3.2.0.dev1+local", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0.dev1+local/avibe_os-3.2.0.dev1+local-py3-none-any.whl"),
+ ("3.2.0+local", f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/gh-v3.2.0+local/avibe_os-3.2.0+local-py3-none-any.whl"),
+])
+def test_unrecognized_origin_cannot_redirect_the_memory_companion(monkeypatch, version, origin):
+ _installed_from(monkeypatch, origin)
+ assert release_asset_specs(version) is None
+ for spec in ([origin, f"avibe-os @ {origin}"] if origin else ["avibe-os", f"avibe-os=={version}"]):
+ if "+local" in version:
+ with pytest.raises(ValueError, match="published target"):
+ vibe_upgrade.memory_release_spec(version, spec)
+ with pytest.raises(ValueError, match="target release version"):
+ build_upgrade_plan(memory_package=True, package_spec=spec, target_version=version)
+ else:
+ # Public dev versions have the same canonical fallback as stable
+ # releases. A false origin never supplies a preview tag or host.
+ assert vibe_upgrade.memory_release_spec(version, spec) == (
+ f"{vibe_upgrade.RELEASE_DOWNLOAD_BASE_URL}/v{version}/"
+ f"avibe_memory-{version}-py3-none-any.whl"
+ )
+ plan = build_upgrade_plan(memory_package=True, package_spec=spec, target_version=version)
+ assert _official_memory(version) in plan.command
def test_get_safe_cwd_returns_absolute_existing_dir():
diff --git a/uv.lock b/uv.lock
index 17d0b080a..624883da1 100644
--- a/uv.lock
+++ b/uv.lock
@@ -294,20 +294,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f6/22/91616fe707a5c5510de2cac9b046a30defe7007ba8a0c04f9c08f27df312/audioop_lts-0.2.2-cp314-cp314t-win_arm64.whl", hash = "sha256:b492c3b040153e68b9fdaff5913305aaaba5bb433d8a7f73d5cf6a64ed3cc1dd", size = 25206, upload-time = "2025-08-05T16:43:16.444Z" },
]
-[[package]]
-name = "avibe-memory"
-source = { directory = "packaging/avibe-memory" }
-dependencies = [
- { name = "avibe-os" },
- { name = "psutil" },
-]
-
-[package.metadata]
-requires-dist = [
- { name = "avibe-os", specifier = ">=3.0.14.dev0,<3.1" },
- { name = "psutil", specifier = ">=7.1.0" },
-]
-
[[package]]
name = "avibe-os"
source = { editable = "." }
@@ -345,11 +331,6 @@ dependencies = [
{ name = "uvicorn", extra = ["standard"] },
]
-[package.optional-dependencies]
-memory = [
- { name = "avibe-memory" },
-]
-
[package.dev-dependencies]
dev = [
{ name = "jsonschema" },
@@ -364,7 +345,6 @@ requires-dist = [
{ name = "alembic", specifier = ">=1.13.0" },
{ name = "anyio", specifier = ">=4.0.0" },
{ name = "apscheduler", specifier = ">=3.10.4" },
- { name = "avibe-memory", marker = "extra == 'memory'", directory = "packaging/avibe-memory" },
{ name = "claude-agent-sdk", specifier = ">=0.2.93" },
{ name = "cryptography", specifier = ">=42.0" },
{ name = "discord-py", specifier = ">=2.4.0" },
diff --git a/vibe/api.py b/vibe/api.py
index 43ef74393..54065eef8 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8818,8 +8818,10 @@ def _published_running_version() -> str | None:
version = Version(__version__)
except InvalidVersion:
return None
- if version.is_devrelease or version.local is not None:
+ if version.local is not None:
return None
+ # Official index releases include dev versions. Source deployment is
+ # rejected independently by readiness; a dev suffix is not provenance.
return str(version)
@@ -9795,12 +9797,9 @@ def _prepare_memory_package_job(*, automatic: bool = False) -> dict:
if restart_only:
result = {"ok": True}
else:
- # A GitHub-only release publishes its pair as release assets and
- # nothing to an index, so pinning it by name would resolve
- # against a PyPI that never served this version and spend an
- # attempt on an install that cannot succeed. This asks where
- # core actually came from; an index install answers `None` and
- # keeps its pins.
+ # Preserve an exact GitHub core origin (including previews).
+ # Otherwise core keeps its index pin and the planner selects
+ # Memory from that version's official GitHub Release.
asset_specs = release_asset_specs(current_version)
plan = build_upgrade_plan(
version=current_version,
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index b90c8bf4f..a48831e52 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -53,14 +53,9 @@ logger = logging.getLogger(__name__)
PACKAGE_NAME = CORE_PACKAGE_NAME
LEGACY_PACKAGE_NAME = LEGACY_CORE_PACKAGE_NAME
MEMORY_PACKAGE_NAME = SHAPE_MEMORY_PACKAGE_NAME
-MEMORY_EXTRA_NAME = "memory"
PIP_DOWNLOAD_DEST_PLACEHOLDER = "{avibe-pip-download-destination}"
-# A GitHub-only pre-release publishes its wheels as release assets and nothing
-# to PyPI, so an install taken from one can only be repaired from that same
-# release. Which release that is comes from the installer's own PEP 610 record,
-# never from the version string: `publish.yml` accepts official `vX.Y.ZrcN`
-# tags and publishes them to PyPI, so a pre-release version says nothing about
-# where its wheels live.
+# Core is on PyPI; Memory is a same-version GitHub Release companion. A recorded
+# GitHub core origin preserves its exact release tag, including gh-v previews.
RELEASE_DOWNLOAD_BASE_URL = "https://github.com/avibe-bot/avibe/releases/download"
DEFAULT_UPDATE_METADATA_URL = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"
@@ -1110,9 +1105,10 @@ def _distributions_providing_this_package() -> list[str]:
def _providers_recording_a_published_release() -> list[tuple[str, str]]:
"""Every distribution providing this package, with the release it records.
- Unpublished recordings are dropped rather than reported. A `dev` or local
- version records the tree it was built from, so it can neither confirm nor
- contradict a released one, and an environment that answers nothing at all --
+ Local-version recordings are dropped rather than reported. They identify
+ a source tree rather than a public release, so they can neither confirm nor
+ contradict a released one. Public dev versions can be published just like
+ other prereleases. An environment that answers nothing at all --
no provider, unreadable metadata, nothing published -- comes back empty. Both
callers read empty as "no evidence", never as evidence of disagreement.
"""
@@ -1189,12 +1185,12 @@ def get_current_uv_tool_dir(python_executable: str | None = None) -> str | None:
def _names_a_published_release(version: str) -> bool:
- """Whether an index could serve `version`, as opposed to it naming this tree.
+ """Whether the version alone can identify a release for an index install.
- A development build's version describes the tree it was built from rather
- than anything published: PEP 440 spells that as a `dev` segment, a local
- segment (`+<sha>`), or both, and the regression builder emits exactly that
- shape.
+ Public dev versions are supported by the official release producer too.
+ Only local labels identify source builds; a dev suffix is not provenance.
+ Eligibility does not prove availability: installer preflights must still
+ resolve the matching core/companion pair before activation.
Asking the property instead of listing the strings is what stops the next
unlisted shape from costing the same attempt. Unparseable reads as
@@ -1205,29 +1201,7 @@ def _names_a_published_release(version: str) -> bool:
match = _VERSION_RE.match(version)
if match is None:
return False
- return not (match.group("dev") or match.group("local"))
-
-
-def _with_memory_extra(package_spec: str) -> str:
- """Add the Memory extra without corrupting URL or local path specs."""
-
- if package_spec.startswith(("git+", "hg+", "svn+", "bz+", "http://", "https://", "file://")):
- return f"{PACKAGE_NAME}[{MEMORY_EXTRA_NAME}] @ {package_spec}"
- try:
- requirement = Requirement(package_spec)
- except InvalidRequirement:
- artifact_uri = Path(package_spec).expanduser().resolve().as_uri()
- return f"{PACKAGE_NAME}[{MEMORY_EXTRA_NAME}] @ {artifact_uri}"
-
- extras = sorted({*requirement.extras, MEMORY_EXTRA_NAME})
- rendered = f"{requirement.name}[{','.join(extras)}]"
- if requirement.url:
- rendered += f" @ {requirement.url}"
- else:
- rendered += str(requirement.specifier)
- if requirement.marker:
- rendered += f"; {requirement.marker}"
- return rendered
+ return not match.group("local")
def _published_version(value: str | None) -> str | None:
@@ -1312,31 +1286,21 @@ def _recorded_install_origin(package_name: str) -> str | None:
def release_asset_specs(version: str) -> tuple[str, str] | None:
- """The wheel pair this install came from, or `None` if an index serves it.
-
- A version string cannot answer this. `publish.yml` accepts official
- `vX.Y.ZrcN` tags and publishes them to PyPI, so a pre-release may well be
- on an index, while a `gh-v*` build carrying the identical version is on no
- index at all. Treating every pre-release as GitHub-only would point the
- official one at a tag that was never created.
-
- The installer already recorded the answer. When core came from a release
- asset of this repository, the pair is repaired from that same release —
- the one it demonstrably came from, rather than one derived from a naming
- convention. Every other origin, an index install included, returns `None`
- and keeps its index pins.
-
- The recorded URL must name this exact running version, so a stale or
- mismatched record cannot drive the repair to a different pair.
- """
+ """Preserve a verified GitHub core origin during an exact package repair."""
+
+ return _release_asset_pair(version, _recorded_install_origin(PACKAGE_NAME))
- origin = _recorded_install_origin(PACKAGE_NAME)
+
+def _release_asset_pair(version: str, origin: str | None) -> tuple[str, str] | None:
if not origin:
return None
try:
- normalized = str(Version(version))
+ parsed_version = Version(version)
except InvalidVersion:
return None
+ if parsed_version.local is not None:
+ return None
+ normalized = str(parsed_version)
prefix = f"{RELEASE_DOWNLOAD_BASE_URL}/"
if not origin.startswith(prefix):
return None
@@ -1346,7 +1310,14 @@ def release_asset_specs(version: str) -> tuple[str, str] | None:
if len(segments) != 2:
return None
tag, asset = segments
- if not tag or tag in {".", ".."}:
+ if not tag.startswith(("v", "gh-v")):
+ return None
+ tag_version = tag.removeprefix("gh-").removeprefix("v")
+ try:
+ normalized_tag_version = str(Version(tag_version))
+ except InvalidVersion:
+ return None
+ if normalized_tag_version != normalized:
return None
if asset != f"{_wheel_distribution(PACKAGE_NAME)}-{normalized}-py3-none-any.whl":
return None
@@ -1357,6 +1328,32 @@ def release_asset_specs(version: str) -> tuple[str, str] | None:
)
+def memory_release_spec(version: str, core_spec: str) -> str:
+ """Name the companion explicitly, without consulting a package index.
+
+ PyPI core releases use official v-tags. An explicitly selected core wheel
+ from this repository preserves its own tag instead (including previews).
+ Other artifact origins cannot redirect the companion to an untrusted host.
+ """
+
+ try:
+ requirement = Requirement(core_spec)
+ except InvalidRequirement:
+ origin = core_spec
+ else:
+ origin = requirement.url
+ pair = _release_asset_pair(version, origin)
+ if pair:
+ return pair[1]
+ normalized = _published_version(version)
+ if normalized is None:
+ raise ValueError("A Memory install requires a published target release version")
+ return (
+ f"{RELEASE_DOWNLOAD_BASE_URL}/v{normalized}/"
+ f"{_wheel_distribution(MEMORY_PACKAGE_NAME)}-{normalized}-py3-none-any.whl"
+ )
+
+
def pinned_package_spec(
version: str,
*,
@@ -1400,13 +1397,9 @@ def build_upgrade_plan(
replace the ordinary upgrade request and force the installer so the matching
optional distribution is applied even when core is already satisfied.
- `core_spec` and `memory_spec` name where to fetch that exact pair when it
- was never published to an index — a preview release's own wheel URLs. They
- replace the two pins and change nothing else, so the resulting plan is the
- same operation against a different source. A forward upgrade resolves the
- newest release rather than a known one and has no such source to name, so
- passing either without `version` is rejected instead of ignored: a spec that
- silently does nothing would read as applied.
+ Memory always comes from the target's GitHub Release, not an index.
+ Exact repairs may supply the recorded core/companion pair. Forward plans
+ derive the companion from the selected target version and core artifact.
"""
if (core_spec or memory_spec) and not version:
@@ -1439,9 +1432,7 @@ def build_upgrade_plan(
if target_version is None:
raise ValueError("A Memory-preserving upgrade requires a target release version")
uv_binary = find_uv_binary(uv_path=uv_path, base_env=base_env)
- if not version and include_memory and f"[{MEMORY_EXTRA_NAME}]" not in package_spec:
- package_spec = _with_memory_extra(package_spec)
- memory_target = memory_version if version else target_version
+ memory_target = (memory_version or version) if version else target_version
# The URL form stays a named requirement so every installer still reads it
# as "this distribution, from here" rather than as an anonymous artifact.
pinned_memory_spec = None
@@ -1449,7 +1440,7 @@ def build_upgrade_plan(
if memory_spec:
pinned_memory_spec = f"{MEMORY_PACKAGE_NAME} @ {memory_spec}"
elif memory_target:
- pinned_memory_spec = f"{MEMORY_PACKAGE_NAME}=={memory_target}"
+ pinned_memory_spec = f"{MEMORY_PACKAGE_NAME} @ {memory_release_spec(memory_target, package_spec)}"
if is_uv_tool_install(executable) and uv_binary:
env = dict(base_env or os.environ)