Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(memory): promote companion runtime architecture to master (#1802)
rkrkrkkb486124b101e
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 293ed07fb..f7e44db13 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -24,6 +24,7 @@ jobs:cache: "pip"cache-dependency-path: |pyproject.toml+ packaging/avibe-memory/pyproject.tomluv.lock- name: Run pre-commit (ruff)run: |@@ -34,6 +35,10 @@ jobs:runs-on: ubuntu-lateststeps:- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5+ with:+ # Both distributions use VCS-derived versions; a shallow PR merge+ # checkout falls back to 0.1.dev1 instead of the 3.0 release line.+ fetch-depth: 0- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5with:@@ -56,15 +61,24 @@ jobs:cache: "pip"cache-dependency-path: |pyproject.toml+ packaging/avibe-memory/pyproject.tomluv.lock- name: Build package artifactenv:GITHUB_TOKEN: ${{ github.token }}+ AVIBE_PACKAGE_CONTRACT_VERSION: 3.0.99rc1+ SETUPTOOLS_SCM_PRETEND_VERSION: 3.0.99rc1+ SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS: 3.0.99rc1+ SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY: 3.0.99rc1run: |- pip install build+ pip install -e . build hatchling hatch-vcs pytestpython scripts/prepare_local_show_runtime_manifest.py- python -m build --wheel+ python -m build --outdir memory-dist packaging/avibe-memory+ python -m build+ AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)" \+ AVIBE_MEMORY_WHEEL="$(ls memory-dist/avibe_memory-*.whl)" \+ pytest tests/test_memory_distribution.py -v- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6with:@@ -264,6 +278,17 @@ jobs:GITHUB_TOKEN: ${{ github.token }}run: python scripts/prepare_local_show_runtime_manifest.py+ - name: Run packaged Memory package-shape smoke+ run: |+ set -o pipefail+ test -f vibe/show_runtime_manifest.json+ output="$RUNNER_TEMP/memory-upgrade-packaged.log"+ pytest tests/test_memory_upgrade_packaged.py -m integration -v -ra | tee "$output"+ if grep -Eq '(^|[[:space:]])[0-9]+ skipped|SKIPPED' "$output"; then+ echo "Packaged Memory upgrade smoke must not skip."+ exit 1+ fi+- name: Run install and upgrade regressionsrun: |docker infodiff --git a/.github/workflows/memory-runtime-release-guard.yml b/.github/workflows/memory-runtime-release-guard.ymlindex 0b67c20d1..2f5f195ec 100644--- a/.github/workflows/memory-runtime-release-guard.yml+++ b/.github/workflows/memory-runtime-release-guard.yml@@ -44,25 +44,25 @@ jobs:mkdir -p "$candidate_dir": > "$records_file": > "$excluded_file"- while IFS= read -r candidate_tag; do+ while IFS=$'\t' read -r candidate_tag manifest_owner wheel_pattern; dorm -rf "$candidate_dir"mkdir -p "$candidate_dir"if ! gh release download "$candidate_tag" --repo "$GITHUB_REPOSITORY" \- --pattern 'avibe_os-*.whl' --dir "$candidate_dir" >/dev/null 2>&1; then+ --pattern "$wheel_pattern" --dir "$candidate_dir" >/dev/null 2>&1; thenjq -nc --arg release_tag "$candidate_tag" \- --arg reason "published wheel could not be downloaded" \+ --arg reason "published $manifest_owner wheel could not be downloaded" \'{release_tag: $release_tag, reason: $reason}' >> "$excluded_file"continuefiset +e- CANDIDATE_TAG="$candidate_tag" CANDIDATE_DIR="$candidate_dir" \+ CANDIDATE_TAG="$candidate_tag" CANDIDATE_DIR="$candidate_dir" WHEEL_PATTERN="$wheel_pattern" \python3 - <<'PY'import jsonimport osimport zipfilefrom pathlib import Path- wheels = sorted(Path(os.environ["CANDIDATE_DIR"]).glob("avibe_os-*.whl"))+ wheels = sorted(Path(os.environ["CANDIDATE_DIR"]).glob(os.environ["WHEEL_PATTERN"]))if len(wheels) != 1:raise SystemExit(1)with zipfile.ZipFile(wheels[0]) as wheel:@@ -77,12 +77,19 @@ jobs:PYmanifest_status=$?set -e- # Wheels without a manifest predate Memory Runtime and are not scope exclusions.+ # Only legacy core wheels may predate Memory Runtime. Once the+ # Memory wheel exists, it is authoritative and must not fall back.if [ "$manifest_status" -eq 4 ]; then+ if [ "$manifest_owner" = "avibe-os" ]; then+ continue+ fi+ jq -nc --arg release_tag "$candidate_tag" \+ --arg reason "$manifest_owner wheel does not contain a self-pinned published manifest" \+ '{release_tag: $release_tag, reason: $reason}' >> "$excluded_file"continueelif [ "$manifest_status" -ne 0 ]; thenjq -nc --arg release_tag "$candidate_tag" \- --arg reason "wheel does not contain a self-pinned published manifest" \+ --arg reason "$manifest_owner wheel does not contain a valid self-pinned published manifest" \'{release_tag: $release_tag, reason: $reason}' >> "$excluded_file"continuefi@@ -97,7 +104,9 @@ jobs:set -eif [ "$policy_status" -eq 0 ]; thenjq -nc --arg release_tag "$candidate_tag" --arg sha256 "$manifest_sha" \- '{release_tag: $release_tag, sha256: $sha256}' >> "$records_file"+ --arg manifest_owner "$manifest_owner" --arg wheel_pattern "$wheel_pattern" \+ '{release_tag: $release_tag, sha256: $sha256, manifest_owner: $manifest_owner,+ wheel_pattern: $wheel_pattern}' >> "$records_file"elif [ "$policy_status" -eq 2 ]; thenpolicy_reason="$(jq -r '.error // "manifest excluded by policy"' <<<"$policy_output")"jq -nc --arg release_tag "$candidate_tag" --arg reason "$policy_reason" \@@ -108,7 +117,15 @@ jobs:fidone < <(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" \- --jq '.[] | select(any(.assets[]?; (.name | startswith("avibe_os-")) and (.name | endswith(".whl")))) | .tag_name'+ --jq '+ .[] |+ if any(.assets[]?; (.name | startswith("avibe_memory-")) and (.name | endswith(".whl"))) then+ [.tag_name, "avibe-memory", "avibe_memory-*.whl"] | @tsv+ elif any(.assets[]?; (.name | startswith("avibe_os-")) and (.name | endswith(".whl"))) then+ [.tag_name, "avibe-os", "avibe_os-*.whl"] | @tsv+ else+ empty+ end')RECORDS_FILE="$records_file" EXCLUDED_FILE="$excluded_file" python3 - <<'PY'import json@@ -172,6 +189,8 @@ jobs:GH_TOKEN: ${{ github.token }}RELEASE_TAG: ${{ matrix.manifest.release_tag }}EXPECTED_SHA256: ${{ matrix.manifest.sha256 }}+ MANIFEST_OWNER: ${{ matrix.manifest.manifest_owner }}+ WHEEL_PATTERN: ${{ matrix.manifest.wheel_pattern }}shell: bashrun: |set -euo pipefail@@ -179,17 +198,18 @@ jobs:rm -rf "$manifest_dir"mkdir -p "$manifest_dir"gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \- --pattern 'avibe_os-*.whl' --dir "$manifest_dir" >/dev/null+ --pattern "$WHEEL_PATTERN" --dir "$manifest_dir" >/dev/nullCANDIDATE_TAG="$RELEASE_TAG" CANDIDATE_DIR="$manifest_dir" \+ MANIFEST_OWNER="$MANIFEST_OWNER" WHEEL_PATTERN="$WHEEL_PATTERN" \python3 - <<'PY'import jsonimport osimport zipfilefrom pathlib import Path- wheels = sorted(Path(os.environ["CANDIDATE_DIR"]).glob("avibe_os-*.whl"))+ wheels = sorted(Path(os.environ["CANDIDATE_DIR"]).glob(os.environ["WHEEL_PATTERN"]))if len(wheels) != 1:- raise SystemExit("expected exactly one avibe_os wheel")+ raise SystemExit(f"expected exactly one {os.environ['MANIFEST_OWNER']} wheel")with zipfile.ZipFile(wheels[0]) as wheel:manifest = wheel.read("vibe/memory_runtime_manifest.json")payload = json.loads(manifest)diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex fe5bce816..e30865887 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -256,6 +256,7 @@ jobs:PACKAGE_VERSION="$(python scripts/release_package_version.py "$RELEASE_TAG")"echo "SETUPTOOLS_SCM_PRETEND_VERSION=$PACKAGE_VERSION" >> "$GITHUB_ENV"echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=$PACKAGE_VERSION" >> "$GITHUB_ENV"+ echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY=$PACKAGE_VERSION" >> "$GITHUB_ENV"- name: Verify Show Runtime release assetsrun: |@@ -299,8 +300,29 @@ jobs:- name: Install build and test dependenciesrun: pip install -e . build pytest- - name: Build package- run: python -m build+ - name: Build Python distributions+ run: |+ python -m build --outdir dist packaging/avibe-memory+ python -m build++ - name: Verify Python distribution asset matrix+ run: |+ python - <<'PY'+ from pathlib import Path++ patterns = (+ "avibe_memory-*.whl",+ "avibe_memory-*.tar.gz",+ "avibe_os-*.whl",+ "avibe_os-*.tar.gz",+ )+ for pattern in patterns:+ matches = sorted(Path("dist").glob(pattern))+ if len(matches) != 1:+ raise SystemExit(+ f"Expected exactly one release asset matching {pattern}, found {len(matches)}"+ )+ PY- name: Build 3.0 compatibility legacy PyPI shimshell: bash@@ -319,31 +341,51 @@ jobs:import zipfilefrom pathlib import Path- wheels = [+ core_wheels = [wheelfor wheel in sorted(Path("dist").glob("*.whl"))if wheel.name.startswith("avibe_os-")]- if len(wheels) != 1:- raise SystemExit(f"Expected exactly one avibe-os wheel, found {len(wheels)}")+ memory_wheels = [+ wheel+ for wheel in sorted(Path("dist").glob("*.whl"))+ if wheel.name.startswith("avibe_memory-")+ ]+ if len(core_wheels) != 1:+ raise SystemExit(f"Expected exactly one avibe-os wheel, found {len(core_wheels)}")+ if len(memory_wheels) != 1:+ raise SystemExit(f"Expected exactly one avibe-memory wheel, found {len(memory_wheels)}")- with zipfile.ZipFile(wheels[0]) as wheel:- names = set(wheel.namelist())+ with zipfile.ZipFile(core_wheels[0]) as wheel:+ core_names = set(wheel.namelist())archives = {- name for name in names+ name for name in core_namesif name.startswith("vibe/show_runtime/") and name.endswith(".tgz")}if archives:raise SystemExit("Wheel unexpectedly contains Show Runtime archives:\n" + "\n".join(sorted(archives)))- if "vibe/show_runtime_manifest.json" not in names:+ if "vibe/show_runtime_manifest.json" not in core_names:raise SystemExit("Wheel is missing vibe/show_runtime_manifest.json")- if any(name.startswith("vibe/memory_runtime/") for name in names):+ if any(name.startswith("vibe/memory_runtime/") for name in core_names):raise SystemExit("Wheel unexpectedly contains Memory Runtime archives")- if "vibe/memory_runtime_manifest.json" not in names:- raise SystemExit("Wheel is missing vibe/memory_runtime_manifest.json")+ if "vibe/memory_runtime_manifest.json" in core_names:+ raise SystemExit("avibe-os wheel unexpectedly owns the Memory Runtime manifest")++ with zipfile.ZipFile(memory_wheels[0]) as wheel:+ memory_names = set(wheel.namelist())+ if "vibe/memory_runtime_manifest.json" not in memory_names:+ raise SystemExit("avibe-memory wheel is missing vibe/memory_runtime_manifest.json")+ if any(name.startswith("vibe/memory_runtime/") for name in memory_names):+ raise SystemExit("avibe-memory wheel unexpectedly contains Memory Runtime archives")PY+ - name: Verify distribution package matrix+ run: |+ AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)" \+ AVIBE_MEMORY_WHEEL="$(ls dist/avibe_memory-*.whl)" \+ pytest tests/test_memory_distribution.py -v+- name: Run Memory Runtime release guard before publicationrun: |rm -rf memory-release-guard-assets@@ -430,10 +472,111 @@ jobs:name: distpath: 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:+ needs:+ - resolve-tag+ - build+ - publish-avibe-memory+ runs-on: ubuntu-latest+ steps:+ - name: Checkout+ uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5+ with:+ ref: ${{ needs.resolve-tag.outputs.tag }}++ - name: Setup Python+ uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6+ with:+ python-version: "3.12"++ - name: Download staged distributions+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8+ with:+ name: dist+ path: dist/++ - name: Verify PyPI serves the exact avibe-memory wheel+ 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+ exit 1+ fi+ sleep 10+ done+publish-avibe-os:needs:- build- finalize-github-release+ - verify-avibe-memory-pypiruns-on: ubuntu-latestenvironment: pypipermissions:@@ -449,7 +592,8 @@ jobs:shell: bashrun: |find dist -type f ! \( -name 'avibe_os-*' -o -name 'avibe-os-*' \) -delete- test -n "$(find dist -maxdepth 1 -type f -name 'avibe_os-*' -print -quit)"+ test -n "$(find dist -maxdepth 1 -type f -name 'avibe_os-*.whl' -print -quit)"+ test -n "$(find dist -maxdepth 1 -type f -name 'avibe_os-*.tar.gz' -print -quit)"- name: Publish avibe-os to PyPIuses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # release/v1diff --git a/.github/workflows/release_ai.yml b/.github/workflows/release_ai.ymlindex 9a24116cd..55f95c850 100644--- a/.github/workflows/release_ai.yml+++ b/.github/workflows/release_ai.yml@@ -200,12 +200,33 @@ jobs:PACKAGE_VERSION="$(python scripts/release_package_version.py "$RELEASE_TAG")"echo "SETUPTOOLS_SCM_PRETEND_VERSION=$PACKAGE_VERSION" >> "$GITHUB_ENV"echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=$PACKAGE_VERSION" >> "$GITHUB_ENV"+ echo "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY=$PACKAGE_VERSION" >> "$GITHUB_ENV"- - name: Build Python package+ - name: Build Python distributionsrun: |- pip install build+ pip install -e . build pytest+ python -m build --outdir dist packaging/avibe-memorypython -m build+ - name: Verify Python distribution asset matrix+ run: |+ python - <<'PY'+ from pathlib import Path++ patterns = (+ "avibe_memory-*.whl",+ "avibe_memory-*.tar.gz",+ "avibe_os-*.whl",+ "avibe_os-*.tar.gz",+ )+ for pattern in patterns:+ matches = sorted(Path("dist").glob(pattern))+ if len(matches) != 1:+ raise SystemExit(+ f"Expected exactly one release asset matching {pattern}, found {len(matches)}"+ )+ PY+- name: Verify bundled runtime manifestsrun: |python - <<'PY'@@ -213,30 +234,46 @@ jobs:import zipfilefrom pathlib import Path- wheels = sorted(Path("dist").glob("*.whl"))- if len(wheels) != 1:- raise SystemExit(f"Expected exactly one wheel, found {len(wheels)}")+ core_wheels = sorted(Path("dist").glob("avibe_os-*.whl"))+ memory_wheels = sorted(Path("dist").glob("avibe_memory-*.whl"))+ if len(core_wheels) != 1:+ raise SystemExit(f"Expected exactly one avibe-os wheel, found {len(core_wheels)}")+ if len(memory_wheels) != 1:+ raise SystemExit(f"Expected exactly one avibe-memory wheel, found {len(memory_wheels)}")- with zipfile.ZipFile(wheels[0]) as wheel:- names = set(wheel.namelist())+ with zipfile.ZipFile(core_wheels[0]) as wheel:+ core_names = set(wheel.namelist())archives = {- name for name in names+ name for name in core_namesif name.startswith("vibe/show_runtime/") and name.endswith(".tgz")}if archives:raise SystemExit("Wheel unexpectedly contains Show Runtime archives:\n" + "\n".join(sorted(archives)))- if "vibe/show_runtime_manifest.json" not in names:+ if "vibe/show_runtime_manifest.json" not in core_names:raise SystemExit("Wheel is missing vibe/show_runtime_manifest.json")- if any(name.startswith("vibe/memory_runtime/") for name in names):+ if any(name.startswith("vibe/memory_runtime/") for name in core_names):raise SystemExit("Wheel unexpectedly contains Memory Runtime archives")- if "vibe/memory_runtime_manifest.json" not in names:- raise SystemExit("Wheel is missing vibe/memory_runtime_manifest.json")+ if "vibe/memory_runtime_manifest.json" in core_names:+ raise SystemExit("avibe-os wheel unexpectedly owns the Memory Runtime manifest")++ with zipfile.ZipFile(memory_wheels[0]) as wheel:+ memory_names = set(wheel.namelist())+ if "vibe/memory_runtime_manifest.json" not in memory_names:+ raise SystemExit("avibe-memory wheel is missing vibe/memory_runtime_manifest.json")+ if any(name.startswith("vibe/memory_runtime/") for name in memory_names):+ raise SystemExit("avibe-memory wheel unexpectedly contains Memory Runtime archives")print("vibe/show_runtime_manifest.json")print("vibe/memory_runtime_manifest.json")PY+ - name: Verify distribution package matrix+ run: |+ AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)" \+ AVIBE_MEMORY_WHEEL="$(ls dist/avibe_memory-*.whl)" \+ pytest tests/test_memory_distribution.py -v+- name: Run Memory Runtime release guard for GitHub-only assetsshell: bashrun: |diff --git a/AGENTS.md b/AGENTS.mdindex e5f2b5f9c..d8cb321c5 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -177,6 +177,15 @@ Persisted-shape rule:- a schema change must load older releases' files via migration or safedegradation (a broken optional-feature section disables that feature andwarns; startup never fails), with load fixtures covering the released shapes+- Memory package upgrades are forward-only: success follows the ordinary restart+ path, while install, upgrade, or restart failures are structured terminal+ results and do not prevent a later explicit attempt. Do not add automatic+ package rollback, rollback plans, lifecycle reservations, quarantine, Gate 5+ verification, or recovery bootstrap.+- Memory Runtime manifest/hash/fetch/verify and backup safeguards protect+ published artifact availability. They are not installed-package rollback+ machinery; existing backup creation and manual restore primitives remain+ manual recovery tools.Source-of-truth rule:@@ -218,6 +227,11 @@ Source-of-truth rule:- the GitHub Codex bot is the review gate: after every push confirm a reviewof the new head starts, comment `@codex review` if none appears, and treat atrigger as accepted only once the bot reacts 👀 to that comment+- only an explicit owner decision may make Codex findings advisory for an+ architecture/spec-only PR: findings inform owner decision-completeness+ certification instead of requiring edits until zero findings. This is a+ per-PR exception; ordinary documentation and every product/test code PR retain+ the normal exact-head Codex clean/pass, CI, and zero-unresolved-thread gates.- a bot pass is either an authenticated Codex-bot issue comment with the passphrase and exact reviewed commit, or a head-bound Codex-bot `+1` captured asnew waiter activity after the prior review was terminal; close-out requiresdiff --git a/core/memory/__init__.py b/avibe_memory/__init__.pysimilarity index 92%rename from core/memory/__init__.pyrename to avibe_memory/__init__.pyindex f5f0c910c..f7aeb6476 100644--- a/core/memory/__init__.py+++ b/avibe_memory/__init__.py@@ -62,8 +62,8 @@ __all__ = []if TYPE_CHECKING:- from core.memory.module import MemoryModule as MemoryModule- from core.memory.types import (+ from avibe_memory.module import MemoryModule as MemoryModule+ from avibe_memory.types import (CaptureAccepted as CaptureAccepted,CaptureAttachment as CaptureAttachment,CaptureDuplicate as CaptureDuplicate,@@ -94,9 +94,9 @@ def __getattr__(name: str) -> Any:"""Load public compatibility exports without penalizing leaf imports."""if name == "MemoryModule":- value = getattr(import_module("core.memory.module"), name)+ value = getattr(import_module("avibe_memory.module"), name)elif name in _TYPE_EXPORTS:- value = getattr(import_module("core.memory.types"), name)+ value = getattr(import_module("avibe_memory.types"), name)else:raise AttributeError(f"module {__name__!r} has no attribute {name!r}")globals()[name] = valuediff --git a/core/memory/admission.py b/avibe_memory/admission.pysimilarity index 89%rename from core/memory/admission.pyrename to avibe_memory/admission.pyindex 5897f83dd..ae4ddcf15 100644--- a/core/memory/admission.py+++ b/avibe_memory/admission.py@@ -22,21 +22,9 @@ import loggingimport timefrom typing import Protocol-from core.memory.admission_metadata import (- MEMORY_CLI_ADMITTED_METADATA as MEMORY_CLI_ADMITTED_METADATA,- MEMORY_ORDINARY_TEXT_METADATA as MEMORY_ORDINARY_TEXT_METADATA,- MEMORY_USER_ID_METADATA as MEMORY_USER_ID_METADATA,- admitted_user_id as admitted_user_id,- is_cli_admitted as is_cli_admitted,- is_ordinary_text as is_ordinary_text,- merge_identity as merge_identity,-)-from core.memory.attachments import workbench_capture_attachments-from core.memory.im_attachments import (- IM_ATTACHMENT_CAPTURE_PLATFORMS,- select_memory_attachments,-)-from core.memory.types import CaptureAttachment, CaptureRequest, CaptureSkipped+from avibe_memory.attachments import workbench_capture_attachments+from avibe_memory.types import CaptureAttachment, CaptureRequest, CaptureSkipped+from vibe.memory_contract import IM_ATTACHMENT_CAPTURE_PLATFORMSlogger = logging.getLogger(__name__)@@ -52,8 +40,6 @@ class PrincipalDirectory(Protocol):def principal_for_user_key(self, user_key: str) -> str: ...- def project_for_workdir(self, workdir: str) -> str: ...-class UserBindingDirectory(Protocol):"""Answers whether an IM user is bound to this install and still enabled."""@@ -86,7 +72,6 @@ class InboundTurnFacts:attachment_capture_status: object = Noneattachment_config_generation: object = Noneattachment_selection: object = None- memory_enabled: bool = Falseclass CaptureAdmission:@@ -126,7 +111,7 @@ class CaptureAdmission:"""Return the default Memory project. User turns do not use workdir."""del facts- from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID+ from vibe.memory_project_ids import DEFAULT_MEMORY_PROJECT_IDreturn DEFAULT_MEMORY_PROJECT_ID@@ -153,8 +138,7 @@ class CaptureAdmission:platform = self.platform_of(facts)return bool(- _asserted_true(facts.memory_enabled)- and platform in IM_ATTACHMENT_CAPTURE_PLATFORMS+ platform in IM_ATTACHMENT_CAPTURE_PLATFORMSand _nonempty_str(facts.message_id)and _nonempty_str(facts.session_id)and _asserted_true(facts.is_ordinary_attachment)@@ -165,8 +149,6 @@ class CaptureAdmission:def decide(self, facts: InboundTurnFacts) -> CaptureRequest | CaptureSkipped:"""Turn one classified turn into the capture it earns, or a skip."""- if not _asserted_true(facts.memory_enabled):- return CaptureSkipped(reason="memory_disabled")platform = self.platform_of(facts)if platform is None:return CaptureSkipped(reason="memory_access_denied")@@ -208,9 +190,7 @@ class CaptureAdmission:try:selection = facts.attachment_selectionif selection is None:- # Production IM callers precompute selection off the- # event loop. This fallback serves direct callers only.- selection = select_memory_attachments(facts.attachment_lease) # type: ignore[arg-type]+ raise ValueError("attachment preparation unavailable")except Exception as error:logger.warning("memory_attachment_selection_failed "diff --git a/core/memory/artifact.py b/avibe_memory/artifact.pysimilarity index 99%rename from core/memory/artifact.pyrename to avibe_memory/artifact.pyindex 0d7c13dc3..0cf9a6e51 100644--- a/core/memory/artifact.py+++ b/avibe_memory/artifact.py@@ -32,7 +32,7 @@ from core.managed_runtime import (write_json_atomic,)from core.process_isolation import isolated_subprocess_kwargs-from core.memory.confined_filesystem import (+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,create_confined_file,ensure_private_directory,@@ -42,12 +42,12 @@ from core.memory.confined_filesystem import (remove_confined_path,replace_confined,)-from core.memory.artifact_contract import (+from avibe_memory.artifact_contract import (EMBEDDED_PYTHON_VERSION,EVEROS_VERSION,run_cold_artifact_admission,)-from core.memory.provider_root import (+from avibe_memory.provider_root import (PROVIDER_ROOT_CONTROL_FILES,ROOT_SENTINEL_FILENAME,ProviderRoot,@@ -55,8 +55,6 @@ from core.memory.provider_root import (ProviderRootMetadata,ProviderRootState,)--PACKAGE_LOCK_SHA256 = "e6acc17e4c0969563d380326e90134965af0822259bb4a9adb4d54433e9737fe"RUNTIME_BUILDER_UV_VERSION = "0.9.18"ARTIFACT_ADMISSION_REVISION = 1@@ -73,7 +71,7 @@ _SPEC = ManagedRuntimeSpec(default_bin_path="bin/python",)_SCRUBBER_ADMISSION_SCRIPT = (- "from core.memory.secret_scrubber import install_error_scrubbers\n"+ "from avibe_memory.secret_scrubber import install_error_scrubbers\n""install_error_scrubbers()\n")_SCRUBBER_ADMISSION_TIMEOUT_SECONDS = 30@@ -922,7 +920,7 @@ class MemoryArtifactManager(ManagedRuntimeManager):def _admit_error_scrubbers(self, binary: Path) -> str | None:"""Prove the child can install mandatory diagnostic scrubbers before launch."""- source_root = Path(__file__).resolve().parents[2]+ source_root = Path(__file__).resolve().parents[1]try:with tempfile.TemporaryDirectory(prefix="avibe-memory-admission-") as home:child_home = Path(home)diff --git a/core/memory/artifact_contract.py b/avibe_memory/artifact_contract.pysimilarity index 97%rename from core/memory/artifact_contract.pyrename to avibe_memory/artifact_contract.pyindex ca21d5d0f..9cb4a2fba 100644--- a/core/memory/artifact_contract.py+++ b/avibe_memory/artifact_contract.py@@ -8,7 +8,7 @@ import timefrom dataclasses import dataclassfrom pathlib import Path-from core.memory.modality import pinned_modality_contract_script+from avibe_memory.modality import pinned_modality_contract_scriptEVEROS_VERSION = "1.2.3"diff --git a/core/memory/attachments.py b/avibe_memory/attachments.pysimilarity index 99%rename from core/memory/attachments.pyrename to avibe_memory/attachments.pyindex e41f73380..ba2d6abc5 100644--- a/core/memory/attachments.py+++ b/avibe_memory/attachments.py@@ -21,8 +21,8 @@ from core.inbound_attachment_lease import (leased_attachment_records,open_leased_attachment_record,)-from core.memory import modality as memory_modality-from core.memory.confined_filesystem import (+from avibe_memory import modality as memory_modality+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,SpilledDirectoryOrder,@@ -30,19 +30,16 @@ from core.memory.confined_filesystem import (open_confined_directory,required_no_follow_flag,)-from core.memory.types import (+from avibe_memory.types import (CaptureAttachment,MemoryContentKind,MemoryErrorCode,)+from vibe.memory_contract import IM_ATTACHMENT_CAPTURE_PLATFORMSMAX_PINNED_ATTACHMENTS = 8MAX_PINNED_ATTACHMENT_BYTES = 25 * 1024 * 1024MAX_PINNED_BUNDLE_BYTES = 100 * 1024 * 1024-IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset(- {"slack", "discord", "telegram", "lark", "wechat"}-)-_COPY_CHUNK_BYTES = 1024 * 1024_MAX_ATTACHMENT_NAME_BYTES = 512_MAX_FILE_URI_BYTES = 8 * 1024diff --git a/avibe_memory/capture_adapter.py b/avibe_memory/capture_adapter.pynew file mode 100644index 000000000..ad0009914--- /dev/null+++ b/avibe_memory/capture_adapter.py@@ -0,0 +1,542 @@+"""Optional-package-owned best-effort capture facade."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, replace+from typing import Any, Protocol++from avibe_memory.admission import (+ CaptureAdmission,+ InboundTurnFacts,+ PrincipalDirectory,+ normalize_attachment_config_generation,+)+from avibe_memory.im_attachments import select_memory_attachments+from avibe_memory.types import CaptureAccepted, CaptureRequest, CaptureSkipped+from core.attachment_telemetry import log_attachment_capture+from core.blocking import run_blocking+from core.memory_adapter import MemoryEvent, SessionArchived, SessionReset, TurnAccepted+++logger = logging.getLogger(__name__)+MAX_PENDING_CAPTURE_EVENTS = 256+++def _record_attachment_capture(platform: str, total: int, captured: int) -> None:+ try:+ log_attachment_capture(platform, total, captured)+ except BaseException:+ logger.debug("Memory attachment capture telemetry failed", exc_info=True)+++class CaptureModule(Protocol):+ def reserve_capture_capacity(self) -> object: ...++ def release_capture_capacity(self, reservation: object) -> None: ...++ def reserve_capture_admission(+ self,+ *,+ principal_id: str,+ project_id: str,+ session_id: str,+ ) -> object: ...++ def cancel_capture_reservation(self, reservation: object) -> None: ...++ def capture_admission(+ self,+ *,+ principal_id: str,+ project_id: str,+ session_id: str,+ reservation: object,+ ) -> Any: ...++ async def capture(+ self,+ request: CaptureRequest,+ *,+ source_lease: object = None,+ admission: object = None,+ capacity_reservation: object = None,+ ) -> object: ...++ def offer_barrier(self, session_id: str) -> object: ...++ async def wait_writer_idle_for_tests(self, *, timeout_seconds: float = 5.0) -> None: ...+++class _UserBindings:+ def __init__(self, is_enabled_user: Callable[[str, str], bool]) -> None:+ self._is_enabled_user = is_enabled_user++ def is_enabled_user(self, platform: str, user_id: str) -> bool:+ return self._is_enabled_user(platform, user_id)+++@dataclass(slots=True)+class _QueuedTurn:+ event: TurnAccepted+ module: CaptureModule+ capacity: object+ lease: object | None+ active: bool = True+ task_owned: bool = False+ attachment_capture_recorded: bool = False++ def record_attachment_capture(self, captured: int = 0) -> None:+ if self.attachment_capture_recorded:+ return+ event = self.event+ if event.platform == "avibe" or not event.files:+ return+ self.attachment_capture_recorded = True+ _record_attachment_capture(+ str(event.platform),+ len(event.files),+ captured,+ )++ def release(self) -> None:+ if not self.active:+ return+ self.record_attachment_capture()+ self.active = False+ _release(self.lease)+ try:+ self.module.release_capture_capacity(self.capacity)+ except BaseException:+ pass+++@dataclass(slots=True)+class _CaptureOwnership:+ item: _QueuedTurn+ reservation: object+ active: bool = True++ def release(self) -> None:+ if not self.active:+ return+ self.active = False+ try:+ self.item.module.cancel_capture_reservation(self.reservation)+ except BaseException:+ pass+ self.item.release()+++class EnabledMemoryAdapter:+ """Own capture admission, preparation, scheduling, and cleanup."""++ def __init__(+ self,+ *,+ module: CaptureModule | None,+ principals: PrincipalDirectory,+ is_enabled_user: Callable[[str, str], bool],+ lifecycle_snapshot_matches: Callable[[str, object], bool],+ acquire_lifecycle_admission: Callable[[str], Awaitable[object]],+ attachment_capture_status: Callable[[], Awaitable[str]],+ attachment_config_generation: Callable[[], int | None],+ attachment_selector: Callable[[object], object] = select_memory_attachments,+ max_pending_events: int = MAX_PENDING_CAPTURE_EVENTS,+ ) -> None:+ self._module = module+ self._admission = CaptureAdmission(+ principals=principals,+ bindings=_UserBindings(is_enabled_user),+ )+ self._lifecycle_snapshot_matches = lifecycle_snapshot_matches+ self._acquire_lifecycle_admission = acquire_lifecycle_admission+ self._attachment_capture_status = attachment_capture_status+ self._attachment_config_generation = attachment_config_generation+ self._attachment_selector = attachment_selector+ self._task_factory: Callable[..., asyncio.Task[Any]] | None = None+ self._queue: asyncio.Queue[MemoryEvent | _QueuedTurn] = asyncio.Queue(+ maxsize=max_pending_events+ )+ self._worker_task: asyncio.Task[None] | None = None+ self._capture_tasks: set[asyncio.Task[None]] = set()+ self._capture_tasks_by_session: dict[str, set[asyncio.Task[None]]] = {}+ self._registration_open = False++ def bind_module(self, module: CaptureModule) -> None:+ """Bind the recovered store once without changing facade identity."""++ if self._module is not None and self._module is not module:+ raise RuntimeError("Memory capture facade is already bound")+ self._module = module++ @property+ def capture_tasks(self) -> set[asyncio.Task[None]]:+ return set(self._capture_tasks)++ def start(+ self,+ *,+ task_factory: Callable[..., asyncio.Task[Any]] | None = None,+ ) -> bool:+ """Schedule the sole preparation worker before the host can offer work."""++ if task_factory is not None:+ if self._task_factory is not None and self._task_factory != task_factory:+ raise RuntimeError("Memory capture scheduler is already bound")+ self._task_factory = task_factory+ factory = self._task_factory+ if self._module is None or factory is None:+ return False+ if self._worker_task is not None and not self._worker_task.done():+ return True+ self._registration_open = True+ pending = self._run()+ try:+ self._worker_task = factory(+ pending,+ name="memory-capture-dispatcher",+ )+ except BaseException:+ pending.close()+ self._registration_open = False+ return False+ return True++ def offer(self, event: MemoryEvent, /) -> None:+ """Retain and enqueue using only closed facts and in-memory decisions."""++ queued: MemoryEvent | _QueuedTurn | None = None+ try:+ worker = self._worker_task+ module = self._module+ if (+ not self._registration_open+ or module is None+ or worker is None+ or worker.done()+ ):+ return+ if isinstance(event, TurnAccepted):+ if not _valid_turn(event):+ return+ capacity = module.reserve_capture_capacity()+ if isinstance(capacity, str):+ if event.platform != "avibe" and event.files:+ _record_attachment_capture(+ str(event.platform),+ len(event.files),+ 0,+ )+ return+ lease = None+ if event.attachment_lease is not None:+ try:+ lease = event.attachment_lease.retain()+ except BaseException:+ lease = None+ queued = _QueuedTurn(event, module, capacity, lease)+ elif isinstance(event, (SessionReset, SessionArchived)):+ if not isinstance(event.session_id, str) or not event.session_id:+ return+ queued = event+ else:+ return+ self._queue.put_nowait(queued)+ queued = None+ except BaseException:+ if isinstance(queued, _QueuedTurn):+ queued.release()++ async def _run(self) -> None:+ current: _QueuedTurn | None = None+ try:+ while True:+ item = await self._queue.get()+ try:+ if isinstance(item, _QueuedTurn):+ current = item+ await self._prepare_and_schedule(item)+ current = None+ else:+ module = self._module+ if module is not None:+ module.offer_barrier(item.session_id)+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.warning("Memory capture preparation failed", exc_info=True)+ if isinstance(item, _QueuedTurn):+ item.release()+ current = None+ finally:+ self._queue.task_done()+ finally:+ if current is not None and not current.task_owned:+ current.release()++ async def _prepare_and_schedule(self, item: _QueuedTurn) -> None:+ event = item.event+ if not self._matches(event):+ item.release()+ return+ facts = InboundTurnFacts(+ platform=event.platform,+ user_id=event.user_id,+ message_id=event.message_id,+ session_id=event.session_id,+ text=event.text,+ files=list(event.files),+ is_dm=event.is_dm,+ is_ordinary_text=event.is_ordinary_text,+ is_ordinary_attachment=event.is_ordinary_attachment,+ attachment_lease=item.lease,+ attachment_capture_status="unavailable",+ attachment_config_generation=None,+ attachment_selection=None,+ )+ if event.platform != "avibe" and event.files:+ authorized = await run_blocking(+ self._admission.admits_attachment_turn,+ facts,+ )+ if not authorized:+ item.release()+ return+ attachment_status: object = "unavailable"+ generation: object = None+ attachment_selection: object = None+ if event.platform != "avibe" and event.files and item.lease is not None:+ try:+ generation = normalize_attachment_config_generation(+ self._attachment_config_generation()+ )+ except Exception:+ generation = None+ if generation is not None:+ try:+ attachment_status = await self._attachment_capture_status()+ except Exception:+ attachment_status = "unavailable"+ if attachment_status == "ready":+ try:+ attachment_selection = await run_blocking(+ self._attachment_selector,+ item.lease,+ )+ except Exception as error:+ logger.warning(+ "memory_attachment_selection_failed "+ "platform=%s count=%d error_type=%s",+ event.platform,+ len(event.files),+ type(error).__name__,+ )+ attachment_status = "unavailable"+ generation = None+ facts = replace(+ facts,+ attachment_capture_status=attachment_status,+ attachment_config_generation=generation,+ attachment_selection=attachment_selection,+ )+ decision = await run_blocking(self._admission.decide, facts)+ if isinstance(decision, CaptureSkipped) or not self._matches(event):+ item.release()+ return+ request = self._validate_attachment_generation(decision)+ if request is None:+ item.release()+ return+ try:+ reservation = item.module.reserve_capture_admission(+ principal_id=request.principal_id,+ project_id=request.project_id,+ session_id=request.session_id,+ )+ except BaseException:+ item.release()+ return+ ownership = _CaptureOwnership(item, reservation)+ pending = self._run_capture(item, request, ownership)+ task: asyncio.Task[Any] | None = None+ try:+ factory = self._task_factory+ if factory is None:+ raise RuntimeError("Memory capture scheduler is not bound")+ task = factory(pending, name="memory-capture")+ item.task_owned = True+ self._track_capture_task(task, request.session_id, ownership)+ except BaseException:+ if task is None:+ pending.close()+ else:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ ownership.release()+ return++ def _validate_attachment_generation(+ self,+ request: CaptureRequest,+ ) -> CaptureRequest | None:+ if not request.attachments:+ return request+ try:+ observed = normalize_attachment_config_generation(+ self._attachment_config_generation()+ )+ except Exception:+ observed = None+ if observed == request.attachment_config_generation:+ return request+ if not request.text.strip():+ return None+ return replace(+ request,+ attachments=(),+ attachment_config_generation=None,+ )++ async def _run_capture(+ self,+ item: _QueuedTurn,+ request: CaptureRequest,+ ownership: _CaptureOwnership,+ ) -> None:+ lifecycle_admission = None+ try:+ lifecycle_admission = await self._acquire_lifecycle_admission(+ request.session_id+ )+ if not self._registration_open or not self._matches(item.event):+ return+ async with item.module.capture_admission(+ principal_id=request.principal_id,+ project_id=request.project_id,+ session_id=request.session_id,+ reservation=ownership.reservation,+ ) as admission:+ if not self._registration_open or not self._matches(item.event):+ return+ result = await item.module.capture(+ request,+ source_lease=item.lease,+ admission=admission,+ capacity_reservation=item.capacity,+ )+ if item.event.platform != "avibe" and item.event.files:+ captured = (+ result.captured_attachment_count+ if isinstance(result, CaptureAccepted)+ else 0+ )+ item.record_attachment_capture(captured)+ finally:+ _release(lifecycle_admission)+ ownership.release()++ def _matches(self, event: TurnAccepted) -> bool:+ try:+ return self._lifecycle_snapshot_matches(+ event.session_id,+ event.lifecycle_snapshot,+ )+ except Exception:+ return False++ def _track_capture_task(+ self,+ task: asyncio.Task[None],+ session_id: str,+ ownership: _CaptureOwnership,+ ) -> None:+ if not self._registration_open:+ task.cancel()+ self._capture_tasks.add(task)+ self._capture_tasks_by_session.setdefault(session_id, set()).add(task)++ def done(completed: asyncio.Task[None]) -> None:+ try:+ completed.result()+ except asyncio.CancelledError:+ pass+ except Exception:+ logger.warning("Memory capture task failed", exc_info=True)+ ownership.release()+ self._capture_tasks.discard(completed)+ bucket = self._capture_tasks_by_session.get(session_id)+ if bucket is not None:+ bucket.discard(completed)+ if not bucket:+ self._capture_tasks_by_session.pop(session_id, None)++ task.add_done_callback(done)++ def abandon_memory_captures_for_session(self, session_id: str) -> None:+ for task in tuple(self._capture_tasks_by_session.get(session_id, ())):+ task.cancel()++ def quiesce_memory_capture_tasks(self) -> None:+ self._registration_open = False++ def cancel_memory_capture_tasks_nowait(self) -> None:+ worker = self._worker_task+ if worker is not None:+ worker.cancel()+ for task in tuple(self._capture_tasks):+ task.cancel()++ async def cancel_memory_capture_tasks(self) -> None:+ self.quiesce_memory_capture_tasks()+ worker = self._worker_task+ if worker is not None:+ worker.cancel()+ await asyncio.gather(worker, return_exceptions=True)+ self._worker_task = None+ tasks = tuple(self._capture_tasks)+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ while True:+ try:+ item = self._queue.get_nowait()+ except asyncio.QueueEmpty:+ break+ if isinstance(item, _QueuedTurn):+ item.release()+ self._queue.task_done()++ async def wait_idle_for_tests(self, *, timeout_seconds: float = 5.0) -> None:+ async def wait() -> None:+ await self._queue.join()+ while self._capture_tasks:+ await asyncio.sleep(0)+ module = self._module+ if module is not None:+ await module.wait_writer_idle_for_tests(+ timeout_seconds=timeout_seconds+ )++ await asyncio.wait_for(wait(), timeout=timeout_seconds)+++def _valid_turn(event: TurnAccepted) -> bool:+ return bool(+ isinstance(event.session_id, str)+ and event.session_id+ and isinstance(event.text, str)+ and isinstance(event.files, tuple)+ )+++def _release(resource: object) -> None:+ release = getattr(resource, "release", None)+ if not callable(release):+ return+ try:+ release()+ except BaseException:+ passdiff --git a/core/memory/confined_filesystem.py b/avibe_memory/confined_filesystem.pysimilarity index 100%rename from core/memory/confined_filesystem.pyrename to avibe_memory/confined_filesystem.pydiff --git a/core/memory/data_reset.py b/avibe_memory/data_reset.pysimilarity index 99%rename from core/memory/data_reset.pyrename to avibe_memory/data_reset.pyindex 5e3bd2381..aa73325e0 100644--- a/core/memory/data_reset.py+++ b/avibe_memory/data_reset.py@@ -12,7 +12,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom config import paths-from core.memory.confined_filesystem import (+from avibe_memory.confined_filesystem import (ConfinedRemovalProgress,remove_confined_path,)diff --git a/core/memory/everos.py b/avibe_memory/everos.pysimilarity index 99%rename from core/memory/everos.pyrename to avibe_memory/everos.pyindex 343b23f11..0278f4d09 100644--- a/core/memory/everos.py+++ b/avibe_memory/everos.py@@ -18,7 +18,7 @@ from urllib.parse import urlsplitimport httpx-from core.memory.types import (+from avibe_memory.types import (CaptureAttachment,MAX_MEMORY_LIST_PAGE_SIZE,MemoryErrorCode,@@ -34,7 +34,7 @@ from core.memory.types import (MemoryPreflightDiagnostic,MAX_AGENTIC_TIMEOUT_SECONDS,)-from core.memory.observations import (+from avibe_memory.observations import (AddAck,AddRejected,AddResult,@@ -260,6 +260,7 @@ class EverOSPort:multimodal_model: str | None = None,multimodal_api_key: str | None = None,processing_health_check: Callable[[], Awaitable[bool]] | None = None,+ runtime_active: Callable[[], bool] | None = None,sidecar_timeout_seconds: float = _SIDECAR_TIMEOUT_SECONDS,add_timeout_seconds: float = _ADD_TIMEOUT_SECONDS,flush_timeout_seconds: float = _FLUSH_TIMEOUT_SECONDS,@@ -284,6 +285,7 @@ class EverOSPort:self._multimodal_model = _optional_string(multimodal_model)self._multimodal_api_key = _optional_string(multimodal_api_key)self._processing_health_check = processing_health_check+ self._runtime_active = runtime_active or (lambda: True)self._sidecar_timeout_seconds = _positive_timeout(sidecar_timeout_seconds, _SIDECAR_TIMEOUT_SECONDS)self._add_timeout_seconds = _positive_timeout(add_timeout_seconds, _ADD_TIMEOUT_SECONDS)self._flush_timeout_seconds = _positive_timeout(flush_timeout_seconds, _FLUSH_TIMEOUT_SECONDS)@@ -428,6 +430,13 @@ class EverOSPort:) -> tuple[int, bytes | None]:"""Return the HTTP verdict even when its body is unusable."""+ try:+ runtime_active = bool(self._runtime_active())+ except Exception:+ runtime_active = False+ if not runtime_active:+ raise MemoryProviderSystemFailure("memory_operation_in_progress")+started = time.monotonic()transport = httpx.AsyncHTTPTransport(uds=str(self._socket_path))try:diff --git a/core/memory/everos_insight/__init__.py b/avibe_memory/everos_insight/__init__.pysimilarity index 100%rename from core/memory/everos_insight/__init__.pyrename to avibe_memory/everos_insight/__init__.pydiff --git a/core/memory/everos_insight/reader.py b/avibe_memory/everos_insight/reader.pysimilarity index 92%rename from core/memory/everos_insight/reader.pyrename to avibe_memory/everos_insight/reader.pyindex 20a9cd1a5..568d59323 100644--- a/core/memory/everos_insight/reader.py+++ b/avibe_memory/everos_insight/reader.py@@ -6,8 +6,8 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, TypeAlias-from core.memory.native_processing_record import NativeProcessingRecordReader-from core.memory.processing_record import ProcessingSourceObservations+from avibe_memory.native_processing_record import NativeProcessingRecordReader+from avibe_memory.processing_record import ProcessingSourceObservationsMemoryReadScope: TypeAlias = tuple[str, str]diff --git a/core/memory/im_attachments.py b/avibe_memory/im_attachments.pysimilarity index 92%rename from core/memory/im_attachments.pyrename to avibe_memory/im_attachments.pyindex 7420392df..21e7cd5f9 100644--- a/core/memory/im_attachments.py+++ b/avibe_memory/im_attachments.py@@ -11,14 +11,14 @@ from core.inbound_attachment_lease import (leased_attachment_records,open_leased_attachment_record,)-from core.memory.attachments import (- IM_ATTACHMENT_CAPTURE_PLATFORMS,+from avibe_memory.attachments import (MAX_PINNED_ATTACHMENTS,MAX_PINNED_ATTACHMENT_BYTES,MAX_PINNED_BUNDLE_BYTES,)-from core.memory.modality import classify_pinned_attachment-from core.memory.types import CaptureAttachment+from avibe_memory.modality import classify_pinned_attachment+from avibe_memory.types import CaptureAttachment+from vibe.memory_contract import IM_ATTACHMENT_CAPTURE_PLATFORMSAttachmentSkipReason = Literal[diff --git a/core/memory/migrations/0001_initial.sql b/avibe_memory/migrations/0001_initial.sqlsimilarity index 100%rename from core/memory/migrations/0001_initial.sqlrename to avibe_memory/migrations/0001_initial.sqldiff --git a/core/memory/migrations/__init__.py b/avibe_memory/migrations/__init__.pysimilarity index 100%rename from core/memory/migrations/__init__.pyrename to avibe_memory/migrations/__init__.pydiff --git a/core/memory/modality.py b/avibe_memory/modality.pysimilarity index 98%rename from core/memory/modality.pyrename to avibe_memory/modality.pyindex 8d2fc6977..d05d66f8c 100644--- a/core/memory/modality.py+++ b/avibe_memory/modality.py@@ -14,7 +14,7 @@ converter stay out of the live allowlist:- video is still unimplemented in the pinned EverOS parser- Office, iWork, ODF, and RTF need LibreOffice conversion-Kept dependency-light on purpose: ``core.memory.sidecar`` imports this from the+Kept dependency-light on purpose: ``avibe_memory.sidecar`` imports this from theruntime child process, which runs with a minimal environment."""@@ -24,7 +24,7 @@ import codecsimport osfrom pathlib import Path-from core.memory.types import MemoryContentKind+from avibe_memory.types import MemoryContentKindSUPPORTED_ATTACHMENT_EXTENSIONS: frozenset[str] = frozenset(diff --git a/core/memory/module.py b/avibe_memory/module.pysimilarity index 98%rename from core/memory/module.pyrename to avibe_memory/module.pyindex 3ddfd3252..cf8c11f20 100644--- a/core/memory/module.py+++ b/avibe_memory/module.py@@ -19,32 +19,32 @@ from time import monotonicfrom typing import TYPE_CHECKING, Any, AsyncIterator, Literal, TypeVarfrom config import paths-from core.memory.blocking import run_blocking-from core.memory.attachments import (+from core.blocking import run_blocking+from avibe_memory.attachments import (AttachmentCleanupUnprovenError,AttachmentPinError,AttachmentPinStore,PinnedBundle,)-from core.memory.provider_root import ProviderRoot-from core.memory.everos import (+from avibe_memory.provider_root import ProviderRoot+from avibe_memory.everos import (AgenticRecallTelemetry,MemoryProviderFailure,MemoryProviderPort,)-from core.memory.project_ids import (+from vibe.memory_project_ids import (is_new_stored_memory_project_id,is_persisted_memory_project_id,is_writable_memory_project_id,)-from core.memory.store import (+from avibe_memory.store import (MemoryStore,VolatileAdmission,derive_assistant_memory_owner_id,is_memory_owner_id,is_principal_id,)-from core.memory.types import (+from avibe_memory.types import (CaptureAccepted,CaptureAttachment,CaptureDuplicate,@@ -71,7 +71,7 @@ from core.memory.types import (RecallResult,is_memory_error_code,)-from core.memory.writer import (+from avibe_memory.writer import (BestEffortMemoryWriter,CaptureOfferOutcome,WriterReservation,@@ -168,6 +168,7 @@ class MemoryModule:disk_free_bytes: Callable[[], int] | None = None,provider_root: Path | None = None,provider_root_owner: ProviderRoot | None = None,+ runtime_active: Callable[[], bool] | None = None,processing_event: Callable[..., Awaitable[bool]] | None = None,ambiguous_stop_reap: Callable[[], Awaitable[bool] | bool] | None = None,writer: BestEffortMemoryWriter | None = None,@@ -185,6 +186,7 @@ class MemoryModule:)self._provider_root = provider_root or (self._effective_home / "memory" / "everos-root")self._provider_root_key = os.path.abspath(os.fspath(self._provider_root))+ self._runtime_active = runtime_active or (lambda: True)self.provider_root = provider_root_owner or ProviderRoot(self._provider_root,effective_home=self._effective_home,@@ -197,7 +199,6 @@ class MemoryModule:tuple[str, str, str], _CaptureReservation] = {}self._invalid_capture_admission_lock = asyncio.Lock()- self._retired = Falseattachments_available = Falseself._attachment_store: AttachmentPinStore | None = Nonetry:@@ -233,18 +234,6 @@ class MemoryModule:return self._writer.attachments_enabled- @property- def retired(self) -> bool:- """Whether this captured module has been permanently tombstoned."""-- return self._retired-- def retire(self) -> None:- """Permanently close this module to stale callers before root deletion."""-- self._retired = True- self._writer.pause_intake()-@asynccontextmanagerasync def lifecycle(self) -> AsyncIterator[None]:"""Serialize an ordinary module lifecycle transition."""@@ -352,12 +341,10 @@ class MemoryModule:) -> CaptureReceipt:"""Validate and persist one source capture without touching the provider."""- if self._retired:+ if not self._owns_runtime():return CaptureSkipped(reason="memory_operation_in_progress")if not self._is_enabled():return CaptureSkipped(reason="memory_disabled")- if self._retired:- return CaptureSkipped(reason="memory_operation_in_progress")reservation = capacity_reservationif reservation is None:@@ -524,12 +511,10 @@ class MemoryModule:capacity_reservation: WriterReservation,) -> CaptureReceipt:async with self._root_lifecycle_lock():- if self._retired:+ if not self._owns_runtime():return CaptureSkipped(reason="memory_operation_in_progress")if not self._is_enabled():return CaptureSkipped(reason="memory_disabled")- if self._retired:- return CaptureSkipped(reason="memory_operation_in_progress")if not isinstance(request, CaptureRequest):return await self._skipped_with_missed("memory_invalid_input")@@ -557,6 +542,12 @@ class MemoryModule:capacity_reservation=capacity_reservation,)+ def _owns_runtime(self) -> bool:+ try:+ return bool(self._runtime_active())+ except Exception:+ return False+def _capture_lock_for_request(self, request: object) -> asyncio.Lock:if not isinstance(request, CaptureRequest):return self._invalid_capture_admission_lock@@ -828,7 +819,7 @@ class MemoryModule:return OperationFailed(error="memory_access_denied")if not is_new_stored_memory_project_id(project_id):return OperationFailed(error="memory_access_denied")- if self._retired:+ if not self._owns_runtime():return OperationFailed(error="memory_operation_in_progress")agentic_started = (@@ -1084,7 +1075,7 @@ class MemoryModule:return OperationFailed(error="memory_access_denied")if not is_new_stored_memory_project_id(project_id):return OperationFailed(error="memory_access_denied")- if self._retired:+ if not self._owns_runtime():return OperationFailed(error="memory_operation_in_progress")async with self._lifecycle_lock:@@ -1173,7 +1164,7 @@ class MemoryModule:return result- if self._retired:+ if not self._owns_runtime():yield unavailable("memory_operation_in_progress")returnremaining = deadline - monotonic()@@ -1189,7 +1180,7 @@ class MemoryModule:yield unavailable("memory_provider_timeout")returntry:- if self._retired:+ if not self._owns_runtime():yield unavailable("memory_operation_in_progress")returntry:@@ -1232,7 +1223,7 @@ class MemoryModule:or origin not in ("user", "agent")):return OperationFailed(error="memory_invalid_input")- if self._retired:+ if not self._owns_runtime():return OperationFailed(error="memory_operation_in_progress")return None@@ -1536,7 +1527,7 @@ class MemoryModule:return _utf8_bytes("\0".join((value.name, value.uri, value.ext))) is not Nonedef _is_enabled(self) -> bool:- if self._retired:+ if not self._owns_runtime():return Falsetry:value = self._enabled_source() if callable(self._enabled_source) else self._enabled_sourcediff --git a/core/memory/native_processing_record.py b/avibe_memory/native_processing_record.pysimilarity index 99%rename from core/memory/native_processing_record.pyrename to avibe_memory/native_processing_record.pyindex f73d3bbe5..e5df07265 100644--- a/core/memory/native_processing_record.py+++ b/avibe_memory/native_processing_record.py@@ -14,13 +14,13 @@ from typing import Any, TypeAliasimport yaml-from core.memory.processing_record import (+from avibe_memory.processing_record import (ProcessingSourceObservations,SourceObservation,)-from core.memory.project_ids import is_persisted_memory_project_id-from core.memory.secret_scrubber import scrub_text-from core.memory.store import (+from vibe.memory_project_ids import is_persisted_memory_project_id+from avibe_memory.secret_scrubber import scrub_text+from avibe_memory.store import (derive_assistant_memory_owner_id,is_memory_owner_id,is_principal_id,diff --git a/core/memory/observations.py b/avibe_memory/observations.pysimilarity index 100%rename from core/memory/observations.pyrename to avibe_memory/observations.pydiff --git a/core/memory/process.py b/avibe_memory/process.pysimilarity index 99%rename from core/memory/process.pyrename to avibe_memory/process.pyindex 5230dbb06..d913276f9 100644--- a/core/memory/process.py+++ b/avibe_memory/process.py@@ -31,8 +31,8 @@ except ModuleNotFoundError: # pragma: no cover - Python 3.10import psutilfrom config import paths-from core.memory.attachments import attachment_pin_root-from core.memory.confined_filesystem import (+from avibe_memory.attachments import attachment_pin_root+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,create_confined_file,@@ -42,13 +42,13 @@ from core.memory.confined_filesystem import (remove_anchored_entry,required_no_follow_flag,)-from core.memory.everos import (+from avibe_memory.everos import (EverOSPort,MULTIMODAL_EXPLICIT_ENV,PROCESSING_PROBE_MAX_DEADLINE_SECONDS,processing_probe_deadline_seconds,)-from core.memory.secret_scrubber import scrub_text+from avibe_memory.secret_scrubber import scrub_textlogger = logging.getLogger(__name__)@@ -116,7 +116,11 @@ _SAFETY_MONITOR_INTERVAL_SECONDS = 0.2_TREE_INSPECTION_INTERVAL_SECONDS = 1.0_SIDECAR_RECORD_FILENAME = "everos.sidecar.json"_SIDECAR_RECORD_MAX_BYTES = 4 * 1024-_SIDECAR_ENTRYPOINT_MODULE = "core.memory.sidecar"+_SIDECAR_ENTRYPOINT_MODULE = "avibe_memory.sidecar"+_RELEASED_SIDECAR_ENTRYPOINT_MODULE = "core.memory.sidecar"+_SIDECAR_ENTRYPOINT_MODULES = frozenset(+ {_SIDECAR_ENTRYPOINT_MODULE, _RELEASED_SIDECAR_ENTRYPOINT_MODULE}+)_PROVIDER_LOCK_PREFIX = "cascade-rebuild-"_SYNC_RECORD_PREFIX = "cascade-sync-"_SYNC_RECORD_MAX_BYTES = 16 * 1024@@ -2193,7 +2197,7 @@ def _memory_child_environment("PATH": f"{python.parent}:/usr/bin:/bin","PYTHONNOUSERSITE": "1","PYTHONUNBUFFERED": "1",- "PYTHONPATH": str(Path(__file__).resolve().parents[2]),+ "PYTHONPATH": str(Path(__file__).resolve().parents[1]),"XDG_CACHE_HOME": str(child_home / ".cache"),"XDG_CONFIG_HOME": str(child_home / ".config"),"XDG_DATA_HOME": str(child_home / ".local" / "share"),@@ -2727,17 +2731,18 @@ def _disclosed_process_environment(process: psutil.Process) -> Mapping[str, str]def _cmdline_serves_socket(cmdline: tuple[str, ...], socket_path: Path) -> bool:- if _SIDECAR_ENTRYPOINT_MODULE not in cmdline or "--uds" not in cmdline:+ if not _SIDECAR_ENTRYPOINT_MODULES.intersection(cmdline) or "--uds" not in cmdline:return Falseindex = cmdline.index("--uds")return index + 1 < len(cmdline) and _paths_match(cmdline[index + 1], socket_path)def _cmdline_is_sidecar(cmdline: tuple[str, ...]) -> bool:- return len(cmdline) == 5 and cmdline[1:4] == (- "-m",- _SIDECAR_ENTRYPOINT_MODULE,- "--uds",+ return (+ len(cmdline) == 5+ and cmdline[1] == "-m"+ and cmdline[2] in _SIDECAR_ENTRYPOINT_MODULES+ and cmdline[3] == "--uds")@@ -2754,13 +2759,10 @@ def _cmdline_matches_role(return Falseif role == _SIDECAR_ROLE:return (- cmdline[1:4]- == (- "-m",- _SIDECAR_ENTRYPOINT_MODULE,- "--uds",- )- and len(cmdline) == 5+ len(cmdline) == 5+ and cmdline[1] == "-m"+ and cmdline[2] in _SIDECAR_ENTRYPOINT_MODULES+ and cmdline[3] == "--uds"and _paths_match(cmdline[4], socket_path))if role == _RELEASED_SYNC_ROLE:diff --git a/core/memory/processing_record.py b/avibe_memory/processing_record.pysimilarity index 97%rename from core/memory/processing_record.pyrename to avibe_memory/processing_record.pyindex a22da4d76..46f361c16 100644--- a/core/memory/processing_record.py+++ b/avibe_memory/processing_record.py@@ -9,10 +9,10 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Any, Literal, TypeVar-from core.memory.everos import ProviderHealthSnapshot-from core.memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS-from core.memory.module import PROVIDER_READ_TIMEOUT_SECONDS-from core.memory.types import MemoryFailureLogEntry+from avibe_memory.everos import ProviderHealthSnapshot+from avibe_memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS+from avibe_memory.module import PROVIDER_READ_TIMEOUT_SECONDS+from avibe_memory.types import MemoryFailureLogEntrySourceStatus = Literal["available", "partial", "stale", "unknown", "unavailable"]@@ -37,10 +37,6 @@ PROCESSING_RECORD_WORK_TIMEOUT_SECONDS = (* PROCESSING_RECORD_SQLITE_BOUND_SECONDS,))-PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS = (- PROCESSING_RECORD_WORK_TIMEOUT_SECONDS- + PROCESSING_RECORD_TRANSPORT_MARGIN_SECONDS-)_AwaitResult = TypeVar("_AwaitResult")diff --git a/core/memory/provider_root.py b/avibe_memory/provider_root.pysimilarity index 99%rename from core/memory/provider_root.pyrename to avibe_memory/provider_root.pyindex 9c0f6d4d5..b7e2570d8 100644--- a/core/memory/provider_root.py+++ b/avibe_memory/provider_root.py@@ -10,7 +10,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Protocol-from core.memory.confined_filesystem import (+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,SpilledDirectoryOrder,diff --git a/core/memory/runtime.py b/avibe_memory/runtime.pysimilarity index 78%rename from core/memory/runtime.pyrename to avibe_memory/runtime.pyindex ce7c30503..f07c33610 100644--- a/core/memory/runtime.py+++ b/avibe_memory/runtime.py@@ -12,22 +12,25 @@ import loggingimport osimport sqlite3import stat+import threadingimport time+import weakref+from itertools import countfrom concurrent.futures import CancelledError as FutureCancelledErrorfrom concurrent.futures import Future as ThreadFuturefrom concurrent.futures import TimeoutError as FutureTimeoutError-from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Mapping+from collections.abc import AsyncIterator, Awaitable, Callable, Coroutine, Iterable, Mappingfrom contextlib import asynccontextmanagerfrom dataclasses import asdict, dataclass, replacefrom datetime import datetime, timezonefrom pathlib import Path-from typing import Any, Literal+from typing import Any, Literal, TypeVarfrom config import pathsfrom config.v2_config import (MemoryConfig,)-from core.memory.artifact import (+from avibe_memory.artifact import (EVEROS_VERSION,MemoryArtifactCandidate,MemoryArtifactPort,@@ -35,31 +38,31 @@ from core.memory.artifact import (MemoryRuntimeActivationError,get_memory_artifact_manager,)-from core.memory.attachments import IM_ATTACHMENT_CAPTURE_PLATFORMS-from core.memory.blocking import run_blocking-from core.memory.confined_filesystem import (+from core.blocking import run_blocking+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,PrivateSqliteDatabase,remove_confined_path,required_no_follow_flag,)-from core.memory.data_reset import MemoryDataResetResult, reset_memory_data_roots-from core.memory.everos import (+from avibe_memory.data_reset import MemoryDataResetResult, reset_memory_data_roots+from avibe_memory.everos import (EverOSPort,MemoryProviderFailure,ProviderHealthSnapshot,)-from core.memory.everos_insight import MemoryInsightPaths, MemoryInsightReader-from core.memory.module import MemoryModule, MemorySessionLifecycleBusyError-from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLease-from core.memory.process import EverOSProcessSettings-from core.memory.supervisor import (+from avibe_memory.everos_insight import MemoryInsightPaths, MemoryInsightReader+from avibe_memory.module import MemoryModule, MemorySessionLifecycleBusyError+from config.memory_operation_lock import MemoryOperationBusy, MemoryOperationLease+from avibe_memory.process import EverOSProcessSettings+from avibe_memory.supervisor import (EverOSSupervisor,EverOSSupervisorFactory,EverOSSupervisorStatus,)-from core.memory.processing_record import (+from vibe.memory_contract import IM_ATTACHMENT_CAPTURE_PLATFORMS+from avibe_memory.processing_record import (AnomalyProjection,FailureLogObservation,MaintenanceProjection,@@ -73,18 +76,21 @@ from core.memory.processing_record import (RuntimeHealthProjection,SourceObservation,)-from core.memory.provider_root import (+from avibe_memory.provider_root import (ProviderRoot,ProviderRootError,ProviderRootMetadata,ProviderRootRollback,)-from core.memory.project_ids import (+from vibe.memory_project_ids import (DEFAULT_MEMORY_PROJECT_ID,MEMORY_SEARCH_ALL_PROJECTS,)-from core.memory.store import MemoryStore, is_principal_id-from core.memory.types import (+from avibe_memory.store import MemoryStore, is_principal_id+from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTES+from core.memory_adapter import DisabledMemoryAdapter, MemoryCaptureAdapter+from avibe_memory.capture_adapter import EnabledMemoryAdapter+from avibe_memory.types import (MAX_MEMORY_LIST_PAGE_SIZE,MemoryFailureLogEntry,MemoryItem,@@ -103,21 +109,38 @@ from core.memory.types import (memory_item_payload,memory_list_page_payload,)+from vibe.memory_contract import MemoryRuntimeBusyError, MemoryStoreUnavailableError+logger = logging.getLogger(__name__)ProcessingEvent = Callable[[Literal["fault", "recovered"], Literal["credential", "engine"] | None, str, int],Awaitable[bool],]+_LifecycleResult = TypeVar("_LifecycleResult")ARTIFACT_ACTIVATION_TIMEOUT_SECONDS = 90.0+MEMORY_CAPTURE_CLOSE_TIMEOUT_SECONDS = 3.0+MEMORY_LOCAL_CLOSE_TIMEOUT_SECONDS = 5.0+MEMORY_PROVIDER_CLOSE_TIMEOUT_SECONDS = 7.0+MEMORY_CLOSE_TIMEOUT_SECONDS = 15.0_MEMORY_LIST_CURSOR_VERSION = 3-MEMORY_LIST_CURSOR_MAX_BYTES = 8192_MEMORY_LIST_PROVIDER_PAGE_SIZE = 20_MEMORY_LIST_PROVIDER_MAX_PAGE = 1_000_000_MEMORY_LIST_AGGREGATE_TIMEOUT_SECONDS = 20.0_WAKE_LEASE_RETRY_DELAYS_SECONDS = (0.0, 0.25, 0.5, 1.0, 2.0)+_ATTACHMENT_CONFIG_EPOCHS = count(1)+_RUNTIME_ROOTS_LOCK = threading.Lock()+_RUNTIME_ROOTS: weakref.WeakValueDictionary[str, MemoryRuntime] = (+ weakref.WeakValueDictionary()+)+++class _RuntimeRootOwnership:+ def __init__(self, owner: MemoryRuntime) -> None:+ self.owner = owner+ self.close_proved = False@asynccontextmanager@@ -136,11 +159,10 @@ async def _concurrent_episode_lists(@dataclass(frozen=True, slots=True)class _ProcessingRuntimeSnapshot:- revision: int+ attachment_config_epoch: inttransition_active: boolenabled: boolstore_available: bool- retired: boolclosing: boolsupervisor: EverOSSupervisorStatusruntime_error: str | None@@ -152,7 +174,7 @@ class _ProcessingRuntimeSnapshot:return "memory_sidecar_unavailable"if maintenance_reason is not None:return maintenance_reason- if self.retired or self.transition_active or self.closing:+ if self.transition_active or self.closing:return "busy"if not self.supervisor.running:return self.runtime_error or "memory_sidecar_unavailable"@@ -168,50 +190,22 @@ class _ProcessingRuntimeSnapshot:return "memory_store_unavailable"if maintenance_reason is not None:return maintenance_reason- if self.retired or self.transition_active or self.closing:+ if self.transition_active or self.closing:return "busy"return Nonedef same_lifecycle(self, other: _ProcessingRuntimeSnapshot) -> bool:return (- self.revision == other.revision+ self.attachment_config_epoch == other.attachment_config_epochand self.transition_active == other.transition_activeand self.enabled == other.enabledand self.store_available == other.store_available- and self.retired == other.retiredand self.closing == other.closingand self.supervisor == other.supervisorand self.runtime_error == other.runtime_error)-class _LifecycleGenerationLock:- """Publish reconcile transitions without making health readers wait."""-- def __init__(self, on_transition: Callable[[], None]) -> None:- self._lock = asyncio.Lock()- self._on_transition = on_transition-- async def acquire(self) -> bool:- acquired = await self._lock.acquire()- self._on_transition()- return acquired-- def release(self) -> None:- self._lock.release()- self._on_transition()-- def locked(self) -> bool:- return self._lock.locked()-- async def __aenter__(self) -> _LifecycleGenerationLock:- await self.acquire()- return self-- async def __aexit__(self, *_exc: object) -> None:- self.release()--def _source_observation_payload(source: SourceObservation) -> dict[str, Any]:return {"status": source.status,@@ -286,10 +280,6 @@ class _UnavailableMemoryModule:_UNAVAILABLE_MODULE = _UnavailableMemoryModule()-class MemoryStoreUnavailableError(RuntimeError):- """Raised when the local Memory store cannot be used safely."""--def create_memory_runtime(config: MemoryConfig,*,@@ -299,6 +289,10 @@ def create_memory_runtime(processing_event: ProcessingEvent | None = None,insight_reader: MemoryInsightReader | None = None,on_config_settled: Callable[[MemoryConfig], None] | None = None,+ is_enabled_user: Callable[[str, str], bool] | None = None,+ lifecycle_snapshot_matches: Callable[[str, object], bool] | None = None,+ acquire_lifecycle_admission: Callable[[str], Awaitable[object]] | None = None,+ _root_ownership: _RuntimeRootOwnership | None = None,) -> MemoryRuntime:"""Construct Memory without allowing store failures to stop Avibe.@@ -314,6 +308,10 @@ def create_memory_runtime(processing_event=processing_event,insight_reader=insight_reader,on_config_settled=on_config_settled,+ is_enabled_user=is_enabled_user,+ lifecycle_snapshot_matches=lifecycle_snapshot_matches,+ acquire_lifecycle_admission=acquire_lifecycle_admission,+ _root_ownership=_root_ownership,)@@ -331,6 +329,10 @@ class MemoryRuntime:processing_event: ProcessingEvent | None = None,insight_reader: MemoryInsightReader | None = None,on_config_settled: Callable[[MemoryConfig], None] | None = None,+ is_enabled_user: Callable[[str, str], bool] | None = None,+ lifecycle_snapshot_matches: Callable[[str, object], bool] | None = None,+ acquire_lifecycle_admission: Callable[[str], Awaitable[object]] | None = None,+ _root_ownership: _RuntimeRootOwnership | None = None,) -> None:self._config = configself._wake_config = deepcopy(config)@@ -338,52 +340,81 @@ class MemoryRuntime:effective_home or paths.get_vibe_remote_dir())self._effective_home = self._filesystem_root.physical_home- self._artifact_manager: MemoryArtifactPort = artifact_manager or get_memory_artifact_manager()- self._provider_root_owner = ProviderRoot(- self._provider_root,- effective_home=self._effective_home,- )- self._supervisor_factory: EverOSSupervisorFactory = (- supervisor_factory or EverOSSupervisor- )- self._processing_event = processing_event- self._on_config_settled = on_config_settled- # The controller-side port only talks to the private UDS. Credentials- # enter an EverOSPort only inside the owned child probe/sidecar.- self._provider = EverOSPort(self._socket_path)- self._runtime_error: str | None = None- self._released_ownership_blocked = False- self._needs_repair_reason: str | None = (- "memory_legacy_recovery_required"- if config.legacy_needs_repair- else None- )- self._lifecycle_revision = 0- self._reconcile_lock = _LifecycleGenerationLock(self._advance_lifecycle_revision)- self._wake_task: asyncio.Task[dict[str, Any]] | None = None- self._artifact_activation_task: asyncio.Task[None] | None = None- self._closing = False- self._activation_loop: asyncio.AbstractEventLoop | None = None- self._artifact_installing = False- self._retired = False- self._closed = False- self._store: MemoryStore | None = None- self._module: MemoryModule | None = None- self._store_error: Exception | None = None- self._insight_reader_override = insight_reader- self._insight_reader: MemoryInsightReader | None = None- self._supervisor = self._supervisor_factory(- provider_root=self._provider_root,- effective_home=self._effective_home,- socket_path=self._socket_path,- on_ready=self._current_sidecar_ready,- on_unavailable=self._current_sidecar_unavailable,- on_recover=self._recover_current_sidecar,- )- self._processing_record = MemoryProcessingRecord(- self._processing_record_port()- )- self._open_store(store)+ self._root_key = os.path.normcase(os.path.abspath(os.fspath(self._provider_root)))+ self._pending_root_ownership = _root_ownership+ self._reset_root_ownership: _RuntimeRootOwnership | None = None+ with _RUNTIME_ROOTS_LOCK:+ owner = _RUNTIME_ROOTS.get(self._root_key)+ if _root_ownership is None:+ if owner is not None:+ raise MemoryRuntimeBusyError(+ "Memory provider root is already owned by a live runtime"+ )+ _RUNTIME_ROOTS[self._root_key] = self+ elif owner is not _root_ownership.owner or not _root_ownership.close_proved:+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ try:+ self._artifact_manager: MemoryArtifactPort = artifact_manager or get_memory_artifact_manager()+ self._provider_root_owner = ProviderRoot(+ self._provider_root,+ effective_home=self._effective_home,+ )+ self._supervisor_factory: EverOSSupervisorFactory = (+ supervisor_factory or EverOSSupervisor+ )+ self._processing_event = processing_event+ self._on_config_settled = on_config_settled+ self._is_enabled_user = is_enabled_user+ self._lifecycle_snapshot_matches = lifecycle_snapshot_matches+ self._acquire_lifecycle_admission = acquire_lifecycle_admission+ self._capture_adapter: MemoryCaptureAdapter = DisabledMemoryAdapter()+ self._capture_task_factory: Callable[..., asyncio.Task[Any]] | None = None+ self._compose_capture_adapter(None)+ # The controller-side port only talks to the private UDS. Credentials+ # enter an EverOSPort only inside the owned child probe/sidecar.+ self._provider = EverOSPort(+ self._socket_path,+ runtime_active=self._runtime_active,+ )+ self._attachment_config_epoch = next(_ATTACHMENT_CONFIG_EPOCHS)+ self._runtime_error: str | None = None+ self._released_ownership_blocked = False+ self._needs_repair_reason: str | None = (+ "memory_legacy_recovery_required"+ if config.legacy_needs_repair+ else None+ )+ self._reconcile_lock = asyncio.Lock()+ self._wake_task: asyncio.Task[dict[str, Any]] | None = None+ self._artifact_activation_task: asyncio.Task[None] | None = None+ self._artifact_install_task: asyncio.Task[dict[str, Any]] | None = None+ self._closing = False+ self._activation_loop: asyncio.AbstractEventLoop | None = None+ self._artifact_installing = False+ self._close_task: asyncio.Task[None] | None = None+ self._close_phase_tasks: dict[str, asyncio.Task[None]] = {}+ self._store: MemoryStore | None = None+ self._module: MemoryModule | None = None+ self._store_error: Exception | None = None+ self._insight_reader_override = insight_reader+ self._insight_reader: MemoryInsightReader | None = None+ self._supervisor = self._supervisor_factory(+ provider_root=self._provider_root,+ effective_home=self._effective_home,+ socket_path=self._socket_path,+ on_ready=self._current_sidecar_ready,+ on_unavailable=self._current_sidecar_unavailable,+ on_recover=self._recover_current_sidecar,+ )+ self._processing_record = MemoryProcessingRecord(+ self._processing_record_port()+ )+ self._open_store(store)+ except BaseException:+ with _RUNTIME_ROOTS_LOCK:+ if _RUNTIME_ROOTS.get(self._root_key) is self:+ _RUNTIME_ROOTS.pop(self._root_key, None)+ raisedef _open_store(self, store: MemoryStore | None = None) -> bool:"""Open the local store and build the module, absorbing any failure.@@ -405,6 +436,7 @@ class MemoryRuntime:enabled=lambda: self._config.enabled,provider_root=self._provider_root,provider_root_owner=self._provider_root_owner,+ runtime_active=self._runtime_active,processing_event=self._processing_event,ambiguous_stop_reap=self._settle_ambiguous_provider_outcome,effective_home=self._effective_home,@@ -420,6 +452,14 @@ class MemoryRuntime:return Falseself._store = openedself._module = module+ self._compose_capture_adapter(module)+ factory_loop = getattr(self._capture_task_factory, "__self__", None)+ try:+ running_loop = asyncio.get_running_loop()+ except RuntimeError:+ running_loop = None+ if factory_loop is running_loop and running_loop is not None:+ self.start_capture_adapter()if self._legacy_clear_state_exists(opened):self._needs_repair_reason = "memory_legacy_recovery_required"if self._needs_repair_reason is not None:@@ -496,7 +536,37 @@ class MemoryRuntime:def available(self) -> bool:"""Whether the local store opened. False keeps every read closed."""- return self._module is not None and not self._retired+ return self._module is not None and not self._closing++ @property+ def closing(self) -> bool:+ return self._closing++ def _runtime_active(self) -> bool:+ with _RUNTIME_ROOTS_LOCK:+ return not self._closing and _RUNTIME_ROOTS.get(self._root_key) is self++ def _require_lifecycle_work(self) -> None:+ if self._closing or not self._runtime_active():+ raise MemoryRuntimeBusyError("Memory runtime authority was revoked")++ def _replace_provider(self, provider: EverOSPort) -> None:+ self._provider = provider+ self._attachment_config_epoch = next(_ATTACHMENT_CONFIG_EPOCHS)+ self.module.replace_provider(provider)++ async def _lifecycle_checkpoint(+ self,+ operation: Coroutine[Any, Any, _LifecycleResult],+ ) -> _LifecycleResult:+ try:+ self._require_lifecycle_work()+ except BaseException:+ operation.close()+ raise+ result = await operation+ self._require_lifecycle_work()+ return result@propertydef needs_repair(self) -> bool:@@ -528,45 +598,45 @@ class MemoryRuntime:if self._module is not None:self._module.pause_claims()- async def settle_after_data_loss(self) -> None:- """Rotate data authority after the owned process has stopped.-- Stable scope identity and the project catalog stay in place. The- Controller calls this only inside its destructive operation lease.- """+ def _proved_root_ownership(self, candidate: object) -> _RuntimeRootOwnership:+ ownership = self._reset_root_ownership+ with _RUNTIME_ROOTS_LOCK:+ if (+ candidate is not ownership+ or ownership is None+ or ownership.owner is not self+ or not ownership.close_proved+ or _RUNTIME_ROOTS.get(self._root_key) is not self+ ):+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ return ownership- if not self._closed or self._store is None:+ async def settle_after_data_loss(self, root_ownership: object) -> None:+ if self._store is None:raise RuntimeError("Memory runtime must be closed before data settlement")+ self._proved_root_ownership(root_ownership)await asyncio.to_thread(self._store.settle_after_data_loss)- def reset_mutable_data(self) -> MemoryDataResetResult:+ def reset_mutable_data(self, root_ownership: object) -> MemoryDataResetResult:"""Reset the fixed mutable roots pinned by this runtime."""- if not self._closed:- raise RuntimeError("Memory runtime must be closed before data reset")+ self._proved_root_ownership(root_ownership)return reset_memory_data_roots(self._effective_home)- @property- def retired(self) -> bool:- """Whether this aggregate has been permanently retired."""-- return self._retired-- @property- def closed(self) -> bool:- """Whether the last close attempt completed all cleanup steps."""-- return self._closed-@propertydef effective_home(self) -> Path:"""Return the pinned home used by this aggregate's mutable state."""return self._effective_home- def replacement(self, config: MemoryConfig) -> MemoryRuntime:+ def replacement(+ self,+ config: MemoryConfig,+ root_ownership: object,+ ) -> MemoryRuntime:"""Construct the next aggregate without exposing owned dependencies."""+ ownership = self._proved_root_ownership(root_ownership)return create_memory_runtime(config,artifact_manager=self._artifact_manager,@@ -575,17 +645,61 @@ class MemoryRuntime:processing_event=self._processing_event,insight_reader=self._insight_reader_override,on_config_settled=self._on_config_settled,+ is_enabled_user=self._is_enabled_user,+ lifecycle_snapshot_matches=self._lifecycle_snapshot_matches,+ acquire_lifecycle_admission=self._acquire_lifecycle_admission,+ _root_ownership=ownership,)- def retire(self) -> None:- """Tombstone this aggregate and its module before mutable roots die."""-- self._retired = True+ def begin_root_ownership_handoff(self) -> object:+ self.begin_close()+ if self._reset_root_ownership is None:+ with _RUNTIME_ROOTS_LOCK:+ if _RUNTIME_ROOTS.get(self._root_key) is not self:+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ self._reset_root_ownership = _RuntimeRootOwnership(self)+ return self._reset_root_ownership++ def accept_root_ownership(self) -> None:+ ownership = self._pending_root_ownership+ if ownership is None:+ return+ with _RUNTIME_ROOTS_LOCK:+ if (+ _RUNTIME_ROOTS.get(self._root_key) is not ownership.owner+ or not ownership.close_proved+ ):+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ _RUNTIME_ROOTS[self._root_key] = self+ ownership.owner._reset_root_ownership = None+ self._pending_root_ownership = None++ def release_root_ownership(self, root_ownership: object) -> None:+ self._proved_root_ownership(root_ownership)+ with _RUNTIME_ROOTS_LOCK:+ if _RUNTIME_ROOTS.get(self._root_key) is not self:+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ _RUNTIME_ROOTS.pop(self._root_key, None)+ self._reset_root_ownership = None++ def release_retained_root_ownership(self) -> None:+ ownership = self._reset_root_ownership+ if ownership is not None:+ self.release_root_ownership(ownership)++ def begin_close(self) -> None:+ if self._closing:+ returnself._closing = Trueself._supervisor.begin_close()- if self._module is not None:- self._module.retire()- self._advance_lifecycle_revision()+ self._activation_loop = None+ adapter = self._capture_adapter+ quiesce = getattr(adapter, "quiesce_memory_capture_tasks", None)+ if callable(quiesce):+ quiesce()+ cancel_nowait = getattr(adapter, "cancel_memory_capture_tasks_nowait", None)+ if callable(cancel_nowait):+ cancel_nowait()def artifact_admitted(self) -> bool:"""Return whether the pinned artifact is valid for a reset admission."""@@ -600,33 +714,54 @@ class MemoryRuntime:except Exception:return False- async def activate_fresh(self, config: MemoryConfig) -> dict[str, Any]:- """Activate a newly constructed aggregate without re-reading old intent."""-- if self._retired:- return {"ok": False, "error": "memory_operation_in_progress"}- if not self.available:- return {"ok": False, "error": "memory_store_unavailable"}- self._activation_loop = asyncio.get_running_loop()- self.module.pause_claims()- async with self._reconcile_lock:- async with self.module.lifecycle():- result = await self._reconcile_locked(- config,- claims_already_paused=True,- skip_embedding_guard=True,- resume_claims_on_failure=False,- )- if result.get("ok") is True:- # Fresh runtimes start fenced while the child is proved;- # settled recovery must leave ordinary capture admission open.- self.module.resume_claims()- return result-@propertydef module(self) -> MemoryModule | _UnavailableMemoryModule:return self._module if self._module is not None else _UNAVAILABLE_MODULE+ @property+ def capture_adapter(self) -> MemoryCaptureAdapter:+ return self._capture_adapter++ def start_capture_adapter(+ self,+ *,+ task_factory: Callable[..., asyncio.Task[Any]] | None = None,+ ) -> bool:+ if task_factory is not None:+ if (+ self._capture_task_factory is not None+ and self._capture_task_factory != task_factory+ ):+ raise RuntimeError("Memory capture scheduler is already bound")+ self._capture_task_factory = task_factory+ start = getattr(self._capture_adapter, "start", None)+ return bool(+ callable(start)+ and start(task_factory=self._capture_task_factory)+ )++ def _compose_capture_adapter(self, module: MemoryModule | None) -> None:+ if isinstance(self._capture_adapter, EnabledMemoryAdapter):+ if module is not None:+ self._capture_adapter.bind_module(module)+ return+ if (+ not callable(self._is_enabled_user)+ or not callable(self._lifecycle_snapshot_matches)+ or not callable(self._acquire_lifecycle_admission)+ ):+ return++ self._capture_adapter = EnabledMemoryAdapter(+ module=module,+ principals=self,+ is_enabled_user=self._is_enabled_user,+ lifecycle_snapshot_matches=self._lifecycle_snapshot_matches,+ acquire_lifecycle_admission=self._acquire_lifecycle_admission,+ attachment_capture_status=self.attachment_capture_status,+ attachment_config_generation=self.attachment_capture_config_generation,+ )+def _unavailable(self) -> MemoryStoreUnavailableError:"""Build the error the read surfaces raise, chained to the real cause."""@@ -657,27 +792,33 @@ class MemoryRuntime:)async def _processing_record_operator(self, user_key: str) -> str:- if not self.available:- raise self._unavailable()- return await run_blocking(self._store.principal_for_user_key, user_key)+ return await self.resolve_principal_for_user_key(user_key)- def _advance_lifecycle_revision(self) -> None:- self._lifecycle_revision += 1+ async def _run_local_observation(+ self,+ operation: Callable[[], _LifecycleResult],+ ) -> _LifecycleResult:+ module = self._module+ if module is None:+ raise self._unavailable()+ async with module.lifecycle():+ if self._module is not module:+ raise self._unavailable()+ self._require_lifecycle_work()+ return await run_blocking(operation)def _processing_runtime_snapshot(self) -> _ProcessingRuntimeSnapshot:module = self._modulereturn _ProcessingRuntimeSnapshot(- revision=self._lifecycle_revision,+ attachment_config_epoch=self._attachment_config_epoch,transition_active=self._reconcile_lock.locked(),enabled=self._config.enabled,store_available=module is not None,- retired=bool(module and module.retired),closing=self._closing,supervisor=self._supervisor.status,runtime_error=self._runtime_error,)-def _configure_insight_reader(self, config: MemoryConfig) -> None:if self._insight_reader_override is not None:self._insight_reader = self._insight_reader_override@@ -725,6 +866,7 @@ class MemoryRuntime:"""Best-effort compatibility cleanup for ordinary non-destructive flows."""async with self._reconcile_lock:+ self._require_lifecycle_work()was_blocked = self._released_ownership_blockedtry:required_no_follow_flag()@@ -733,7 +875,9 @@ class MemoryRuntime:self._released_ownership_blocked = Trueself._runtime_error = "memory_sidecar_unavailable"return False- reconciled = await self._supervisor.reconcile_orphans()+ reconciled = await self._lifecycle_checkpoint(+ self._supervisor.reconcile_orphans()+ )if not reconciled and self._supervisor.status.retains_configuration:# The current supervisor-owned child is not released ownership.reconciled = True@@ -747,9 +891,11 @@ class MemoryRuntime:async def reconcile(self, config: MemoryConfig) -> dict[str, Any]:"""Apply persisted config without restarting the Avibe service."""- if self._retired:+ try:+ self._require_lifecycle_work()+ return await self._reconcile(config)+ except MemoryRuntimeBusyError:return {"ok": False, "error": "memory_operation_in_progress"}- return await self._reconcile(config)async def _reconcile(self, config: MemoryConfig) -> dict[str, Any]:"""Run one reconciliation owned by the public lifecycle operation."""@@ -758,7 +904,8 @@ class MemoryRuntime:# sidecar is exactly the boot that may face one from the run before it.# Takes and releases the reconcile lock itself; the lock this method# acquires later is a separate, sequential acquisition.- if not await self._reconcile_released_ownership():+ reconciled = await self._reconcile_released_ownership()+ if not reconciled:return {"ok": False,"state": "needs_repair" if self.needs_repair else "degraded",@@ -770,6 +917,7 @@ class MemoryRuntime:self._config = configif not config.enabled:async with self._reconcile_lock:+ self._require_lifecycle_work()self._wake_config = deepcopy(config)return {"ok": True, "state": "disabled"}if not self._open_store():@@ -779,26 +927,33 @@ class MemoryRuntime:"state": "needs_repair" if self.needs_repair else "degraded","error": self._runtime_error or "memory_store_unavailable",}+ self.start_capture_adapter()async with self._reconcile_lock:+ self._require_lifecycle_work()self._activation_loop = asyncio.get_running_loop()if self._artifact_installing:return {"ok": False, "error": "memory_runtime_install_failed"}async with self.module.lifecycle():+ self._require_lifecycle_work()result = await self._reconcile_locked(config)if result.get("ok") is True:+ self._require_lifecycle_work()self._wake_config = deepcopy(config)return resultasync def _disable_locked(self, config: MemoryConfig) -> dict[str, Any]:"""Stop every active Memory component without consulting maintenance state."""+ self._require_lifecycle_work()self.module.pause_claims()self._config = configself._configure_insight_reader(config)- self._provider = EverOSPort(self._socket_path)- self.module.replace_provider(self._provider)- await self._close_writer()- await self._supervisor.stop()+ self._replace_provider(EverOSPort(+ self._socket_path,+ runtime_active=self._runtime_active,+ ))+ await self._lifecycle_checkpoint(self._close_writer())+ await self._lifecycle_checkpoint(self._supervisor.stop())self._runtime_error = Nonereturn {"ok": True, "state": "disabled"}@@ -812,6 +967,7 @@ class MemoryRuntime:) -> dict[str, Any]:"""Reconcile while both controller and module lifecycle locks are held."""+ self._require_lifecycle_work()if self.needs_repair:if not config.enabled:result = await self._disable_locked(config)@@ -826,8 +982,8 @@ class MemoryRuntime:"error": reason,}self.module.pause_claims()- await self._close_writer()- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._close_writer())+ await self._lifecycle_checkpoint(self._supervisor.stop())self._config = deepcopy(config)self._wake_config = deepcopy(config)self._runtime_error = self._needs_repair_reason@@ -846,8 +1002,8 @@ class MemoryRuntime:)if cloud_identity_changed:self.module.pause_claims()- await self._close_writer()- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._close_writer())+ await self._lifecycle_checkpoint(self._supervisor.stop())self._config = deepcopy(config)self._wake_config = deepcopy(config)self._runtime_error = "memory_loss_confirmation_required"@@ -862,13 +1018,15 @@ class MemoryRuntime:# a pause, never a fallback to saved custom providers. Capture can# keep queuing while claims and the old sidecar stay fenced.self.module.pause_claims()- await self._close_writer()- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._close_writer())+ await self._lifecycle_checkpoint(self._supervisor.stop())self._config = deepcopy(config)self._wake_config = deepcopy(config)self._configure_insight_reader(config)- self._provider = EverOSPort(self._socket_path)- self.module.replace_provider(self._provider)+ self._replace_provider(EverOSPort(+ self._socket_path,+ runtime_active=self._runtime_active,+ ))self._runtime_error = "memory_capability_unavailable"return {"ok": True,@@ -885,16 +1043,22 @@ class MemoryRuntime:if embedding_changed:# Fence and join volatile writer work before inspecting provider# state, so no old-embedding call can cross this boundary.- if not await self.module.quiesce_claims():+ quiesced = await self._lifecycle_checkpoint(self.module.quiesce_claims())+ if not quiesced:if resume_claims_on_failure:self._defer_wake_until_writer_closed()self._runtime_error = "memory_loss_confirmation_required"return {"ok": False, "state": "degraded", "error": self._runtime_error}claims_paused = True- if not await self._embedding_change_is_admissible(self._config, config):+ admissible = await self._lifecycle_checkpoint(+ self._embedding_change_is_admissible(self._config, config)+ )+ if not admissible:restored = Falseif resume_claims_on_failure:- restored = await self._restore_provisional_claims(previous_config)+ restored = await self._lifecycle_checkpoint(+ self._restore_provisional_claims(previous_config)+ )if not restored:self._runtime_error = "memory_loss_confirmation_required"return {@@ -912,10 +1076,16 @@ class MemoryRuntime:candidate_provider = EverOSPort(self._socket_path,processing_health_check=self._processing_healthy,+ runtime_active=self._runtime_active,+ )+ python = await self._lifecycle_checkpoint(+ asyncio.to_thread(self._artifact_manager.resolve_python))- python = await asyncio.to_thread(self._artifact_manager.resolve_python)if python is None:- error = _runtime_error_for_status(await asyncio.to_thread(self._artifact_manager.status))+ status = await self._lifecycle_checkpoint(+ asyncio.to_thread(self._artifact_manager.status)+ )+ error = _runtime_error_for_status(status)if not self._supervisor.status.retains_configuration:# No retained supervisor can run now or relaunch with the prior# settings, including one that exhausted its wake budget.@@ -924,39 +1094,54 @@ class MemoryRuntime:self._config = configself._runtime_error = errorif claims_paused and resume_claims_on_failure:- await self._restore_provisional_claims(previous_config)+ await self._lifecycle_checkpoint(+ self._restore_provisional_claims(previous_config)+ )return {"ok": False, "error": error}- if not await self._probe_processing(python, config):+ processing_ready = await self._lifecycle_checkpoint(+ self._probe_processing(python, config)+ )+ if not processing_ready:error = "memory_processing_failed"if not self._supervisor.status.running:self._runtime_error = errorif claims_paused and resume_claims_on_failure:- await self._restore_provisional_claims(previous_config)+ await self._lifecycle_checkpoint(+ self._restore_provisional_claims(previous_config)+ )return {"ok": False, "error": error}# Every enabled reconciliation receives a fresh process. Endpoint,# model, and key changes belong exclusively in its allowlisted child# environment and must never leave an old sidecar running.- if not claims_paused and not await self.module.quiesce_claims():+ quiesced = claims_paused or await self._lifecycle_checkpoint(+ self.module.quiesce_claims()+ )+ if not quiesced:if resume_claims_on_failure:self._defer_wake_until_writer_closed()self._runtime_error = "memory_runtime_busy"return {"ok": False, "state": "degraded", "error": self._runtime_error}- await self._close_writer()- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._close_writer())+ await self._lifecycle_checkpoint(self._supervisor.stop())self._config = configself._configure_insight_reader(config)- self._provider = candidate_provider- self.module.replace_provider(self._provider)+ self._replace_provider(candidate_provider)try:- meta = await asyncio.to_thread(self._store.ensure_meta)+ meta = await self._lifecycle_checkpoint(+ asyncio.to_thread(self._store.ensure_meta)+ )active_metadata = self._active_provider_root_metadata()- await run_blocking(- self._provider_root_owner.ensure,- meta,- active_metadata,+ await self._lifecycle_checkpoint(+ run_blocking(+ self._provider_root_owner.ensure,+ meta,+ active_metadata,+ ))+ except MemoryRuntimeBusyError:+ raiseexcept Exception as exc:if _local_data_failure_requires_repair(exc):self._needs_repair_reason = "memory_local_data_unusable"@@ -969,17 +1154,16 @@ class MemoryRuntime:return {"ok": False, "state": state, "error": self._runtime_error}settings = _process_settings(config)- try:- started = await self._supervisor.wake(+ started = await self._lifecycle_checkpoint(+ self._supervisor.wake(python,settings,- provider_root_guard=lambda: self._provider_root_owner.require_owned(+ provider_root_guard=lambda: self._require_current_provider_root(meta,active_metadata,),)- except BaseException:- raise+ )if not started:self._runtime_error = "memory_sidecar_unavailable"return {"ok": False, "state": "degraded", "error": self._runtime_error}@@ -1066,7 +1250,7 @@ class MemoryRuntime:reader = self._insight_readerif reader is None:raise self._unavailable()- observation = await run_blocking(reader.source_observation)+ observation = await self._run_local_observation(reader.source_observation)after = self._processing_runtime_snapshot()current_reason = after.local_observation_reason(maintenance_reason)if not after.same_lifecycle(before) or current_reason is not None:@@ -1087,16 +1271,21 @@ class MemoryRuntime:observation: MaintenanceObservation,) -> MaintenanceResult:del operator_ref+ reason = self._processing_runtime_snapshot().local_observation_reason(+ observation.block_reason+ )data_exists = True- if self.available:+ if reason is None:try:- data_exists = await asyncio.to_thread(self._provider_data_exists_strict)+ data_exists = await self._run_local_observation(+ self._provider_data_exists_strict+ )except Exception:- data_exists = True+ reason = "busy"return MaintenanceResult(data_exists=data_exists,- can_delete_data=observation.can_delete_data,- error=observation.block_reason,+ can_delete_data=observation.can_delete_data and reason is None,+ error=reason,)async def processing_record_payload(@@ -1177,7 +1366,7 @@ class MemoryRuntime:or not self._module.attachment_intake_enabled):return None- return self._lifecycle_revision+ return self._attachment_config_epochasync def failure_log_payload(self,@@ -1221,10 +1410,10 @@ class MemoryRuntime:raise self._unavailable()return self._store.principal_for_user_key(user_key)- def project_for_workdir(self, workdir: str) -> str:- if not self.available:- raise self._unavailable()- return self._store.project_for_workdir(workdir)+ async def resolve_principal_for_user_key(self, user_key: str) -> str:+ return await self._run_local_observation(+ lambda: self._store.principal_for_user_key(user_key)+ )def offer_barrier(self, raw_session_id: str) -> str:"""Offer a non-blocking provider barrier for lifecycle transitions."""@@ -1297,7 +1486,7 @@ class MemoryRuntime:):return {"status": "failed", "error": "memory_invalid_input"}try:- projects = await run_blocking(self.list_memory_projects, principal_id)+ projects = await self.list_memory_projects(principal_id)except Exception:return {"status": "failed", "error": "memory_store_unavailable"}if not projects:@@ -1731,10 +1920,10 @@ class MemoryRuntime:},)- def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:- if not self.available:- return (DEFAULT_MEMORY_PROJECT_ID,)- return self._store.list_memory_projects(principal_id)+ async def list_memory_projects(self, principal_id: str) -> tuple[str, ...]:+ return await self._run_local_observation(+ lambda: self._store.list_memory_projects(principal_id)+ )async def search_payload(self,@@ -1781,7 +1970,7 @@ class MemoryRuntime:if policy.mode == "agentic" or policy.include_current_session:return OperationFailed(error="memory_invalid_input")deadline = time.monotonic() + 20.0- projects = await run_blocking(self.list_memory_projects, principal_id)+ projects = await self.list_memory_projects(principal_id)if not projects:projects = (DEFAULT_MEMORY_PROJECT_ID,)collected: list[MemoryItem] = []@@ -1896,28 +2085,40 @@ class MemoryRuntime:self,operation: Callable[[], dict[str, Any]],) -> dict[str, Any]:- async with self.module.lifecycle():- return await run_blocking(operation)+ return await self._run_local_observation(operation)- async def install_artifact(self) -> dict[str, Any]:+ async def install_artifact(+ self,+ *,+ operation_lease_held: bool = False,+ ) -> dict[str, Any]:"""Install or repair the admitted EverOS artifact."""lease = MemoryOperationLease(self._effective_home)+ lease_acquired = operation_lease_heldtry:- await run_blocking(lease.acquire)+ self._require_lifecycle_work()+ if not operation_lease_held:+ await run_blocking(+ lease.acquire,+ on_cancel_result=lambda _result: lease.release(),+ )+ lease_acquired = Truereturn await self._install_artifact_with_lease()- except MemoryOperationBusy:+ except (MemoryOperationBusy, MemoryRuntimeBusyError):return {"ok": False,"reason": "memory_operation_in_progress","download_error": None,}finally:- await run_blocking(lease.release)+ if not operation_lease_held and lease_acquired:+ await run_blocking(lease.release)async def _install_artifact_with_lease(self) -> dict[str, Any]:self._activation_loop = asyncio.get_running_loop()async with self._reconcile_lock:+ self._require_lifecycle_work()if self._artifact_installing:return {"ok": False,@@ -1932,9 +2133,23 @@ class MemoryRuntime:}self._artifact_installing = True+ install = asyncio.create_task(+ run_blocking(self._artifact_manager.ensure, force=True),+ name="memory-artifact-install",+ )+ self._artifact_install_task = install+ install.add_done_callback(self._finish_artifact_install)try:- payload = await run_blocking(self._artifact_manager.ensure, force=True)- except asyncio.CancelledError:+ payload = await asyncio.shield(install)+ self._require_lifecycle_work()+ except asyncio.CancelledError as cancellation:+ while not install.done():+ try:+ await asyncio.shield(install)+ except (asyncio.CancelledError, Exception):+ pass+ raise cancellation+ except MemoryRuntimeBusyError:raiseexcept Exception:logger.exception("Memory artifact install failed")@@ -1943,10 +2158,6 @@ class MemoryRuntime:"reason": "memory_runtime_install_failed","download_error": None,}- finally:- async with self._reconcile_lock:- self._artifact_installing = False-if not isinstance(payload, dict):return {"ok": False,@@ -1961,6 +2172,10 @@ class MemoryRuntime:"download_error": download_error if isinstance(download_error, dict) else None,}+ def _finish_artifact_install(self, task: asyncio.Task[dict[str, Any]]) -> None:+ if self._artifact_install_task is task:+ self._artifact_installing = False+async def wake(self,*,@@ -1968,7 +2183,7 @@ class MemoryRuntime:) -> dict[str, Any]:"""Validate the artifact and non-destructively wake the existing root."""- if self._closing or self._retired:+ if self._closing:return {"ok": False,"state": self.runtime_state(),@@ -1981,12 +2196,7 @@ class MemoryRuntime:for delay_seconds in _WAKE_LEASE_RETRY_DELAYS_SECONDS:if delay_seconds:await asyncio.sleep(delay_seconds)- if self._closing or self._retired:- return {- "ok": False,- "state": self.runtime_state(),- "error": "memory_operation_in_progress",- }+ self._require_lifecycle_work()try:await run_blocking(lease.acquire,@@ -1995,6 +2205,7 @@ class MemoryRuntime:except MemoryOperationBusy:continuelease_acquired = True+ self._require_lifecycle_work()breakif not lease_acquired:self._runtime_error = "memory_operation_in_progress"@@ -2016,13 +2227,17 @@ class MemoryRuntime:self._wake_config.enabledand not self.availableand not self.needs_repair- and not await run_blocking(self._open_store)):- return {- "ok": False,- "state": "needs_repair" if self.needs_repair else "degraded",- "error": self._runtime_error or "memory_store_unavailable",- }+ opened = await self._lifecycle_checkpoint(+ run_blocking(self._open_store)+ )+ if not opened:+ return {+ "ok": False,+ "state": "needs_repair" if self.needs_repair else "degraded",+ "error": self._runtime_error or "memory_store_unavailable",+ }+ self.start_capture_adapter()if self.needs_repair:return {"ok": False,@@ -2035,26 +2250,37 @@ class MemoryRuntime:"state": "disabled","error": "memory_disabled",}- if not await run_blocking(self.artifact_admitted):+ artifact_admitted = await self._lifecycle_checkpoint(+ run_blocking(self.artifact_admitted)+ )+ if not artifact_admitted:if self.available:async with self._reconcile_lock, self.module.lifecycle():+ self._require_lifecycle_work()self.module.pause_claims()- if not await self.module.quiesce_claims(timeout_seconds=5.0):+ quiesced = await self._lifecycle_checkpoint(+ self.module.quiesce_claims(timeout_seconds=5.0)+ )+ if not quiesced:return {"ok": False,"state": "degraded","error": "memory_runtime_busy",}- await self._close_writer()+ await self._lifecycle_checkpoint(self._close_writer())try:- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._supervisor.stop())+ except MemoryRuntimeBusyError:+ raiseexcept Exception:return {"ok": False,"state": "degraded","error": "memory_wake_failed",}- installed = await self._install_artifact_with_lease()+ installed = await self._lifecycle_checkpoint(+ self._install_artifact_with_lease()+ )if installed.get("ok") is not True:self._runtime_error = str(installed.get("reason") or "memory_wake_failed"@@ -2072,7 +2298,14 @@ class MemoryRuntime:"error": self._runtime_error,}async with self._reconcile_lock:+ self._require_lifecycle_work()return await self._wake_locked()+ except MemoryRuntimeBusyError:+ return {+ "ok": False,+ "state": self.runtime_state(),+ "error": "memory_operation_in_progress",+ }except MemoryOperationBusy:return {"ok": False, "error": "memory_operation_in_progress"}except Exception as exc:@@ -2103,7 +2336,7 @@ class MemoryRuntime:def _current_sidecar_unavailable(self) -> None:"""Project supervisor-owned crash state into Memory policy."""- if self._closing or self._retired or self.needs_repair:+ if self._closing or self.needs_repair:returnself.module.pause_claims()self._runtime_error = "memory_sidecar_unavailable"@@ -2128,6 +2361,7 @@ class MemoryRuntime:return await self.wake()async def preflight(self, config: MemoryConfig | None = None) -> dict[str, Any]:+ self._require_lifecycle_work()candidate = deepcopy(config or self._config)processing = candidate.runtime_processing()provider = EverOSPort(@@ -2159,14 +2393,14 @@ class MemoryRuntime:if processing.multimodalelse None),+ runtime_active=self._runtime_active,)- return (await provider.preflight()).payload()+ return (await self._lifecycle_checkpoint(provider.preflight())).payload()async def _wake_locked(self) -> dict[str, Any]:"""Wake the admitted sidecar while preserving the existing data root."""- if self._closing or self._retired:- return {"ok": False, "error": "memory_operation_in_progress"}+ self._require_lifecycle_work()if self.needs_repair:return {"ok": False,@@ -2186,17 +2420,24 @@ class MemoryRuntime:replay = deepcopy(self._wake_config)if not replay.enabled:return {"ok": False, "state": "disabled", "error": "memory_disabled"}- python = await asyncio.to_thread(self._artifact_manager.resolve_python)+ python = await self._lifecycle_checkpoint(+ asyncio.to_thread(self._artifact_manager.resolve_python)+ )if python is None:self._runtime_error = "memory_wake_failed"return {"ok": False, "state": "degraded", "error": self._runtime_error}async with self.module.lifecycle():+ self._require_lifecycle_work()self.module.pause_claims()try:- quiesced = await self.module.quiesce_claims(timeout_seconds=5.0)+ quiesced = await self._lifecycle_checkpoint(+ self.module.quiesce_claims(timeout_seconds=5.0)+ )if quiesced:- await self._close_writer()+ await self._lifecycle_checkpoint(self._close_writer())+ except MemoryRuntimeBusyError:+ raiseexcept Exception:quiesced = Falseif not quiesced:@@ -2204,7 +2445,9 @@ class MemoryRuntime:return {"ok": False, "state": "degraded", "error": self._runtime_error}try:- await self._supervisor.stop()+ await self._lifecycle_checkpoint(self._supervisor.stop())+ except MemoryRuntimeBusyError:+ raiseexcept Exception:logger.exception("Memory wake could not prove the old sidecar stopped")self._runtime_error = "memory_wake_failed"@@ -2212,19 +2455,25 @@ class MemoryRuntime:self._config = replayself._configure_insight_reader(replay)- self._provider = EverOSPort(+ self._replace_provider(EverOSPort(self._socket_path,processing_health_check=self._processing_healthy,- )- self.module.replace_provider(self._provider)+ runtime_active=self._runtime_active,+ ))try:- meta = await asyncio.to_thread(self._store.ensure_meta)+ meta = await self._lifecycle_checkpoint(+ asyncio.to_thread(self._store.ensure_meta)+ )active_metadata = self._active_provider_root_metadata()- await run_blocking(- self._provider_root_owner.ensure,- meta,- active_metadata,+ await self._lifecycle_checkpoint(+ run_blocking(+ self._provider_root_owner.ensure,+ meta,+ active_metadata,+ ))+ except MemoryRuntimeBusyError:+ raiseexcept Exception as exc:if _local_data_failure_requires_repair(exc):self._needs_repair_reason = "memory_local_data_unusable"@@ -2236,14 +2485,18 @@ class MemoryRuntime:return {"ok": False, "state": state, "error": self._runtime_error}try:- started = await self._supervisor.wake(- python,- _process_settings(replay),- provider_root_guard=lambda: self._provider_root_owner.require_owned(- meta,- active_metadata,- ),+ started = await self._lifecycle_checkpoint(+ self._supervisor.wake(+ python,+ _process_settings(replay),+ provider_root_guard=lambda: self._require_current_provider_root(+ meta,+ active_metadata,+ ),+ ))+ except MemoryRuntimeBusyError:+ raiseexcept Exception as exc:self._runtime_error = _degraded_runtime_reason(exc,@@ -2258,8 +2511,9 @@ class MemoryRuntime:for delay in (0.0, 0.25, 0.5, 1.0):if delay:await asyncio.sleep(delay)+ self._require_lifecycle_work()try:- await self._provider.health_snapshot()+ await self._lifecycle_checkpoint(self._provider.health_snapshot())readiness_error = Nonebreakexcept MemoryProviderFailure as failure:@@ -2272,106 +2526,140 @@ class MemoryRuntime:return {"ok": False, "state": "degraded", "error": readiness_error}self._runtime_error = None+ self._require_lifecycle_work()self.module.resume_claims()self._resume_writer()return {"ok": True, "state": "running"}- async def close(self) -> None:- self._closing = True- self._supervisor.begin_close()- self._activation_loop = None- self._advance_lifecycle_revision()-- cancellation: asyncio.CancelledError | None = None- wake = self._wake_task- if wake is not None and wake is not asyncio.current_task():- if not wake.done():- wake.cancel()- cancellation = await self._join_shutdown_task(wake)- try:- wake.result()- except (Exception, asyncio.CancelledError):- pass-- cleanup = asyncio.create_task(- self._close_owned_runtime(),- name="memory-runtime-close",+ async def close(+ self,+ *,+ timeout_seconds: float = MEMORY_CLOSE_TIMEOUT_SECONDS,+ root_ownership: object | None = None,+ ) -> None:+ if root_ownership is not None and root_ownership is not self._reset_root_ownership:+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ self.begin_close()+ task = self._close_task+ if task is None or task.done() and (+ task.cancelled() or task.exception() is not None+ ):+ task = asyncio.create_task(+ self._close_once(max(0.0, timeout_seconds)),+ name="memory-runtime-close",+ )+ self._close_task = task+ await asyncio.shield(task)+ return+ await asyncio.wait_for(+ asyncio.shield(task),+ timeout=max(0.0, timeout_seconds),)- cleanup_cancellation = await self._join_shutdown_task(cleanup)- cancellation = cancellation or cleanup_cancellation- cleanup_error: BaseException | None = None- try:- cleanup.result()- except BaseException as error:- cleanup_error = error- if cancellation is not None:- if cleanup_error is not None:- logger.error(- "Memory runtime cleanup failed while close was cancelled: %s",- cleanup_error,- )- raise cancellation- if cleanup_error is not None:- raise cleanup_error- @staticmethod- async def _join_shutdown_task(- task: asyncio.Task[Any],- ) -> asyncio.CancelledError | None:- """Join one shutdown-owned task without abandoning it on cancellation."""-- cancellation: asyncio.CancelledError | None = None- current = asyncio.current_task()- while not task.done():- try:- await asyncio.shield(task)- except asyncio.CancelledError as error:- if current is not None and current.cancelling():- cancellation = cancellation or error- except BaseException:- break- return cancellation+ async def _close_once(self, timeout_seconds: float) -> None:+ loop = asyncio.get_running_loop()+ deadline = loop.time() + timeout_seconds+ phases = (+ (self._cancel_capture_tasks, MEMORY_CAPTURE_CLOSE_TIMEOUT_SECONDS, "capture cancellation"),+ (self._close_local_runtime, MEMORY_LOCAL_CLOSE_TIMEOUT_SECONDS, "local cleanup"),+ (self._supervisor.close, MEMORY_PROVIDER_CLOSE_TIMEOUT_SECONDS, "provider stop"),+ )+ remaining_weight = sum(weight for _operation, weight, _label in phases)+ failures: list[str] = []+ for operation, weight, label in phases:+ remaining = max(0.0, deadline - loop.time())+ if not await self._run_bounded_close_phase(+ operation,+ timeout_seconds=remaining * weight / remaining_weight,+ label=label,+ ):+ failures.append(label)+ remaining_weight -= weight+ if failures:+ raise RuntimeError(f"Memory {failures[-1]} did not prove completion")+ self._artifact_manager.set_activation_coordinator(None)+ ownership = self._reset_root_ownership+ if ownership is None:+ with _RUNTIME_ROOTS_LOCK:+ if _RUNTIME_ROOTS.get(self._root_key) is self:+ _RUNTIME_ROOTS.pop(self._root_key, None)+ else:+ with _RUNTIME_ROOTS_LOCK:+ if _RUNTIME_ROOTS.get(self._root_key) is not self:+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ ownership.close_proved = True++ async def _cancel_capture_tasks(self) -> None:+ cancel_capture = getattr(+ self._capture_adapter,+ "cancel_memory_capture_tasks",+ None,+ )+ if callable(cancel_capture):+ await cancel_capture()- async def _close_owned_runtime(self) -> None:- """Finish ordinary shutdown after runtime ownership is released."""+ async def _run_bounded_close_phase(+ self,+ operation: Callable[[], Awaitable[None]],+ *,+ timeout_seconds: float,+ label: str,+ ) -> bool:+ task = self._close_phase_tasks.get(label)+ if task is None or (+ task.done() and (task.cancelled() or task.exception() is not None)+ ):+ task = asyncio.create_task(operation(), name=f"memory-close-{label}")+ self._close_phase_tasks[label] = task+ await asyncio.sleep(0)+ done, _pending = await asyncio.wait({task}, timeout=timeout_seconds)+ if task not in done:+ logger.error(+ "Memory %s exceeded its %.3fs close budget",+ label,+ timeout_seconds,+ )+ task.cancel()+ return False+ try:+ task.result()+ except BaseException:+ logger.error(+ "Memory %s failed during close",+ label,+ exc_info=True,+ )+ return False+ return True- cleanup_error: BaseException | None = None- for task in (self._artifact_activation_task,):- if task is None or task is asyncio.current_task():- continue- try:- await asyncio.shield(task)- except asyncio.CancelledError:- raise- except Exception:- pass+ async def _close_local_runtime(self) -> None:+ await self._join_close_task(self._artifact_install_task)+ await self._join_close_task(self._wake_task, cancel=True)+ await self._join_close_task(self._artifact_activation_task)if self._module is not None:self._module.pause_claims()- try:- await self._close_writer()- except BaseException as error:- cleanup_error = error- async with self._module.provider_root_lifecycle():- try:- if (- self._retired- and not await self._module.quiesce_claims_for_destructive_reset()- ):- raise RuntimeError(- "Memory writer did not quiesce during retired close"- )- await self._module.close_writer()- except BaseException as error:- cleanup_error = cleanup_error or error+ async with self._module.destructive_lifecycle():+ if not await self._module.quiesce_claims_for_destructive_reset():+ raise RuntimeError("Memory writer did not quiesce during close")+ await self._module.close_writer()++ @staticmethod+ async def _join_close_task(+ task: asyncio.Task[Any] | None,+ *,+ cancel: bool = False,+ ) -> None:+ if task is None or task is asyncio.current_task():+ return+ if cancel and not task.done():+ task.cancel()try:- await self._supervisor.close()- except BaseException as error:- cleanup_error = cleanup_error or error- self._artifact_manager.set_activation_coordinator(None)- if cleanup_error is not None:- raise cleanup_error- self._closed = True- self._advance_lifecycle_revision()+ await asyncio.shield(task)+ except asyncio.CancelledError:+ if (current := asyncio.current_task()) is not None and current.cancelling():+ raise+ except Exception:+ passdef _active_provider_root_metadata(self) -> ProviderRootMetadata:provider_root_format = (@@ -2390,6 +2678,14 @@ class MemoryRuntime:),)+ def _require_current_provider_root(+ self,+ meta: object,+ active_metadata: ProviderRootMetadata,+ ) -> None:+ self._require_lifecycle_work()+ self._provider_root_owner.require_owned(meta, active_metadata)+def _coordinate_artifact_activation(self,candidate: MemoryArtifactCandidate,@@ -2587,7 +2883,7 @@ class MemoryRuntime:"""Prove old ownership ended and reuse the settled runtime when requested."""await self._supervisor.stop()- if recover and not self._closing and not self._retired:+ if recover and not self._closing:self._defer_wake_until_writer_closed()return Truediff --git a/core/memory/schema.sql b/avibe_memory/schema.sqlsimilarity index 100%rename from core/memory/schema.sqlrename to avibe_memory/schema.sqldiff --git a/core/memory/schema_v2.sql b/avibe_memory/schema_v2.sqlsimilarity index 100%rename from core/memory/schema_v2.sqlrename to avibe_memory/schema_v2.sqldiff --git a/core/memory/secret_scrubber.py b/avibe_memory/secret_scrubber.pysimilarity index 100%rename from core/memory/secret_scrubber.pyrename to avibe_memory/secret_scrubber.pydiff --git a/core/memory/sidecar.py b/avibe_memory/sidecar.pysimilarity index 97%rename from core/memory/sidecar.pyrename to avibe_memory/sidecar.pyindex 04c3c348d..b830dbddb 100644--- a/core/memory/sidecar.py+++ b/avibe_memory/sidecar.py@@ -17,15 +17,15 @@ from pathlib import Pathfrom typing import Any, Literalfrom urllib.parse import unquote, urlparse-from core.memory.artifact import EVEROS_VERSION-from core.memory.project_ids import (+from avibe_memory.artifact import EVEROS_VERSION+from vibe.memory_project_ids import (is_new_stored_memory_project_id,is_persisted_memory_project_id,)-from core.memory.secret_scrubber import install_error_scrubbers-from core.memory.modality import SUPPORTED_ATTACHMENT_EXTENSIONS-from core.memory.store import is_memory_owner_id-from core.memory.types import (+from avibe_memory.secret_scrubber import install_error_scrubbers+from avibe_memory.modality import SUPPORTED_ATTACHMENT_EXTENSIONS+from avibe_memory.store import is_memory_owner_id+from avibe_memory.types import (MAX_AGENTIC_TIMEOUT_SECONDS,MAX_MEMORY_LIST_PAGE_SIZE,MAX_MEMORY_SEARCH_RESULTS,@@ -497,7 +497,7 @@ def _valid_session(value: object) -> bool:def _processing_healthy_from_child_environment() -> bool:"""Run fixed authenticated probes only inside the scrubbed owned child."""- from core.memory.everos import EverOSPort, MULTIMODAL_EXPLICIT_ENV+ from avibe_memory.everos import EverOSPort, MULTIMODAL_EXPLICIT_ENVmultimodal_kwargs: dict[str, str | None] = {}if os.environ.get(MULTIMODAL_EXPLICIT_ENV) == "1":diff --git a/core/memory/store.py b/avibe_memory/store.pysimilarity index 98%rename from core/memory/store.pyrename to avibe_memory/store.pyindex 45b49a26a..a8f80a1dd 100644--- a/core/memory/store.py+++ b/avibe_memory/store.py@@ -16,7 +16,7 @@ from pathlib import Pathfrom typing import Literalfrom config import paths-from core.memory.confined_filesystem import (+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,create_confined_file,@@ -24,7 +24,7 @@ from core.memory.confined_filesystem import (open_and_harden_confined_regular_file,open_confined_regular_file,)-from core.memory.project_ids import (+from vibe.memory_project_ids import (DEFAULT_MEMORY_PROJECT_ID,MAX_NAMED_MEMORY_PROJECTS,is_legacy_memory_project_id,@@ -32,7 +32,7 @@ from core.memory.project_ids import (is_persisted_memory_project_id,is_writable_memory_project_id,)-from core.memory.types import MemoryErrorCode, ProviderSessionRef+from avibe_memory.types import MemoryErrorCode, ProviderSessionRefMEMORY_STORE_FILENAME = "memory.sqlite"MEMORY_STORE_DIRNAME = "memory"@@ -230,10 +230,6 @@ class MemoryStore:with self._transaction() as conn:return derive_principal_id(self._ensure_meta(conn).scope_key, user_key)- def project_for_workdir(self, workdir: str) -> str:- with self._transaction() as conn:- return derive_project_id(self._ensure_meta(conn).scope_key, workdir)-def source_message_digest(self, source_message_id: str) -> str:if not isinstance(source_message_id, str) or not source_message_id or "\x00" in source_message_id:raise ValueError("invalid Memory source message")diff --git a/core/memory/supervisor.py b/avibe_memory/supervisor.pysimilarity index 99%rename from core/memory/supervisor.pyrename to avibe_memory/supervisor.pyindex 5b0c25d9d..3f5a6c1dc 100644--- a/core/memory/supervisor.py+++ b/avibe_memory/supervisor.py@@ -11,7 +11,7 @@ from pathlib import Pathimport timefrom typing import Literal, Protocol-from core.memory.process import (+from avibe_memory.process import (EverOSProcess,EverOSProcessFactory,EverOSProcessPort,diff --git a/core/memory/types.py b/avibe_memory/types.pysimilarity index 62%rename from core/memory/types.pyrename to avibe_memory/types.pyindex d1056eeab..585999aa8 100644--- a/core/memory/types.py+++ b/avibe_memory/types.py@@ -3,18 +3,22 @@from __future__ import annotationsimport json-import mathfrom dataclasses import dataclassfrom typing import Any, Literal, TypeAlias+from vibe.memory_contract import (+ CLOSED_MEMORY_ERROR_CODES,+ MAX_AGENTIC_TIMEOUT_SECONDS as MAX_AGENTIC_TIMEOUT_SECONDS,+ MAX_MEMORY_LIST_PAGE_SIZE as MAX_MEMORY_LIST_PAGE_SIZE,+ MAX_MEMORY_SEARCH_RESULTS as MAX_MEMORY_SEARCH_RESULTS,+ MemoryErrorCode,+ RecallPolicy,+ is_memory_error_code,+)+MemoryKind = Literal["profile", "episode", "fact"]MemoryOrigin = Literal["user", "agent"]RecallMode = Literal["auto", "keyword", "vector", "hybrid", "agentic"]-MAX_AGENTIC_TIMEOUT_SECONDS = 30.0-# Pinned EverOS 1.2.3 request bounds. Keep every Avibe entry point aligned-# with the provider contract instead of layering a smaller product limit on top.-MAX_MEMORY_SEARCH_RESULTS = 100-MAX_MEMORY_LIST_PAGE_SIZE = 100MemoryContentKind = Literal["image", "audio", "doc", "pdf", "html", "email"]MemoryFailureKind = Literal["boot_recovery",@@ -22,88 +26,6 @@ MemoryFailureKind = Literal["distillation_rejected","result_unknown",]-MemoryErrorCode = Literal[- "memory_disabled",- "memory_invalid_input",- "memory_access_denied",- "memory_input_too_large",- "memory_queue_full",- "memory_low_disk_space",- "memory_store_unavailable",- "memory_runtime_missing",- "memory_runtime_unsupported",- "memory_runtime_install_failed",- "memory_reconcile_failed",- "memory_wake_failed",- "memory_runtime_busy",- "memory_permission_denied",- "memory_disk_unavailable",- "memory_sidecar_unavailable",- "memory_provider_timeout",- "memory_provider_response_invalid",- "memory_capability_unavailable",- "memory_processing_failed",- "memory_loss_confirmation_required",- "memory_local_data_unusable",- "memory_legacy_recovery_required",- "memory_embedding_unavailable",- "memory_llm_unavailable",- "memory_rerank_unavailable",- "memory_multimodal_unavailable",- "memory_repair_failed",- "memory_repair_not_required",- "memory_delete_data_failed",- "memory_reconfigure_failed",- "memory_operation_in_progress",-]--# Transport vocabulary, wider than the persistable one: errors such as-# ``memory_access_denied``, ``memory_reconcile_failed``, and-# ``memory_wake_failed`` never reaches a stored ``last_error`` column.-CLOSED_MEMORY_ERROR_CODES = frozenset(- {- "memory_disabled",- "memory_invalid_input",- "memory_access_denied",- "memory_input_too_large",- "memory_queue_full",- "memory_low_disk_space",- "memory_store_unavailable",- "memory_runtime_missing",- "memory_runtime_unsupported",- "memory_runtime_install_failed",- "memory_reconcile_failed",- "memory_wake_failed",- "memory_runtime_busy",- "memory_permission_denied",- "memory_disk_unavailable",- "memory_sidecar_unavailable",- "memory_provider_timeout",- "memory_provider_response_invalid",- "memory_capability_unavailable",- "memory_processing_failed",- "memory_loss_confirmation_required",- "memory_local_data_unusable",- "memory_legacy_recovery_required",- "memory_embedding_unavailable",- "memory_llm_unavailable",- "memory_rerank_unavailable",- "memory_multimodal_unavailable",- "memory_repair_failed",- "memory_repair_not_required",- "memory_delete_data_failed",- "memory_reconfigure_failed",- "memory_operation_in_progress",- }-)---def is_memory_error_code(value: object) -> bool:- """Return whether *value* is a closed Memory error code."""-- return isinstance(value, str) and value in CLOSED_MEMORY_ERROR_CODES--@dataclass(frozen=True)class MemoryPreflightDiagnostic:side: Literal["embedding", "llm", "rerank", "multimodal"]@@ -458,106 +380,6 @@ def memory_list_page_payload(result: MemoryListPage) -> dict[str, Any]:}-@dataclass(frozen=True)-class RecallPolicy:- """One bounded, single-run provider-neutral recall decision request."""-- mode: RecallMode = "hybrid"- max_results: int = 8- include_profile: bool = True- include_current_session: bool = False- timeout_seconds: float | None = None- max_model_calls: int | None = None- cost_budget_tokens: int | None = None-- def __post_init__(self) -> None:- if self.mode not in {"auto", "keyword", "vector", "hybrid", "agentic"}:- raise ValueError("invalid recall mode")- if (- isinstance(self.max_results, bool)- or not isinstance(self.max_results, int)- or not 1 <= self.max_results <= MAX_MEMORY_SEARCH_RESULTS- ):- raise ValueError("invalid recall result limit")- if type(self.include_profile) is not bool or type(self.include_current_session) is not bool:- raise ValueError("invalid recall include policy")- if self.mode == "agentic":- if (- self.timeout_seconds is None- or isinstance(self.timeout_seconds, bool)- or not isinstance(self.timeout_seconds, (int, float))- or not math.isfinite(float(self.timeout_seconds))- or not 0 < float(self.timeout_seconds) <= MAX_AGENTIC_TIMEOUT_SECONDS- or isinstance(self.max_model_calls, bool)- or not isinstance(self.max_model_calls, int)- or not 1 <= self.max_model_calls <= 4- or isinstance(self.cost_budget_tokens, bool)- or not isinstance(self.cost_budget_tokens, int)- or not 1 <= self.cost_budget_tokens <= 32_000- ):- raise ValueError("agentic recall requires bounded budgets")- elif any(- value is not None- for value in (- self.timeout_seconds,- self.max_model_calls,- self.cost_budget_tokens,- )- ):- raise ValueError("non-agentic recall cannot carry agentic budgets")-- @classmethod- def from_payload(cls, value: object) -> "RecallPolicy":- if not isinstance(value, dict):- raise ValueError("invalid recall policy")- allowed = {- "mode",- "max_results",- "include_profile",- "include_current_session",- "timeout_seconds",- "max_model_calls",- "cost_budget_tokens",- }- if not set(value).issubset(allowed):- raise ValueError("invalid recall policy")- mode = value.get("mode", "hybrid")- budget_fields = {- "timeout_seconds",- "max_model_calls",- "cost_budget_tokens",- }- if mode == "agentic":- if not {"max_results", *budget_fields}.issubset(value):- raise ValueError("agentic recall requires explicit budgets")- elif set(value).intersection(budget_fields):- raise ValueError("non-agentic recall cannot carry agentic budgets")- return cls(- mode=mode,- max_results=value.get("max_results", 8),- include_profile=value.get("include_profile", True),- include_current_session=value.get("include_current_session", False),- timeout_seconds=value.get("timeout_seconds"),- max_model_calls=value.get("max_model_calls"),- cost_budget_tokens=value.get("cost_budget_tokens"),- )-- def payload(self) -> dict[str, object]:- payload: dict[str, object] = {- "mode": self.mode,- "max_results": self.max_results,- "include_profile": self.include_profile,- "include_current_session": self.include_current_session,- }- if self.mode == "agentic":- payload.update(- timeout_seconds=self.timeout_seconds,- max_model_calls=self.max_model_calls,- cost_budget_tokens=self.cost_budget_tokens,- )- return payload--@dataclass(frozen=True)class RecallItems:items: tuple[MemoryItem, ...]diff --git a/core/memory/writer.py b/avibe_memory/writer.pysimilarity index 96%rename from core/memory/writer.pyrename to avibe_memory/writer.pyindex 098743d81..d46e1699d 100644--- a/core/memory/writer.py+++ b/avibe_memory/writer.py@@ -11,9 +11,9 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Literal-from core.memory.attachments import AttachmentPinError, AttachmentPinStore, PinnedBundle-from core.memory.blocking import run_blocking-from core.memory.everos import (+from avibe_memory.attachments import AttachmentPinError, AttachmentPinStore, PinnedBundle+from core.blocking import run_blocking+from avibe_memory.everos import (AddAck,AddRejected,FlushRejected,@@ -26,9 +26,9 @@ from core.memory.everos import (ProviderCapture,attachment_add_rejection_proves_no_write,)-from core.memory.observations import AddResult, FlushResult-from core.memory.store import MemoryStore, VolatileAdmission-from core.memory.types import CaptureAttachment, ProviderSessionRef+from avibe_memory.observations import AddResult, FlushResult+from avibe_memory.store import MemoryStore, VolatileAdmission+from avibe_memory.types import CaptureAttachment, ProviderSessionReflogger = logging.getLogger(__name__)@@ -323,7 +323,7 @@ class BestEffortMemoryWriter:return "queued"async def quiesce(self, *, timeout_seconds: float = 30.0) -> bool:- """Join current generation admissions for authority-changing transitions."""+ """Join current admissions for authority-changing transitions."""self.pause_intake()loop = asyncio.get_running_loop()@@ -464,6 +464,9 @@ class BestEffortMemoryWriter:self._queued_items = max(0, self._queued_items - 1)async def _deliver(self, item: _CaptureItem) -> None:+ if not self._enabled():+ await self._cleanup_item(item)+ returncapture = item.captureattachments = capture.attachmentsif item.bundle is not None and self._attachment_store is not None:@@ -488,6 +491,9 @@ class BestEffortMemoryWriter:)attempt = 0while attempt < MAX_ATTEMPTS:+ if not self._enabled():+ await self._cleanup_item(item)+ returnattempt += 1self._active_provider_calls += 1try:@@ -552,6 +558,9 @@ class BestEffortMemoryWriter:returnasync def _success(self, item: _CaptureItem, *, extracted: bool) -> None:+ if not self._enabled():+ await self._cleanup_item(item)+ returntry:await run_blocking(self._store.mark_capture_success)except Exception:@@ -576,6 +585,9 @@ class BestEffortMemoryWriter:await self._cleanup_item(item)async def _terminal_failure(self, item: _CaptureItem, error: str) -> None:+ if not self._enabled():+ await self._cleanup_item(item)+ returntry:await run_blocking(self._store.set_last_error, error)except Exception:@@ -626,6 +638,9 @@ class BestEffortMemoryWriter:continueresult: FlushResult | None = Nonefor attempt in range(1, MAX_ATTEMPTS + 1):+ if not self._enabled():+ self._pending.pop(key, None)+ returnself._active_provider_calls += 1try:result = await self._provider.flush(ref)@@ -706,6 +721,8 @@ class BestEffortMemoryWriter:returnasync def _ambiguous_outcome(self, _error: str, *, recover: bool = True) -> None:+ if not self._enabled():+ returnself._unavailable = Trueself._intake_paused = Trueself._pending.clear()diff --git a/core/memory/operation_lock.py b/config/memory_operation_lock.pysimilarity index 98%rename from core/memory/operation_lock.pyrename to config/memory_operation_lock.pyindex aea764b3e..d91fcf355 100644--- a/core/memory/operation_lock.py+++ b/config/memory_operation_lock.py@@ -1,4 +1,4 @@-"""Cross-process admission for destructive Memory operations."""+"""Cross-process admission for host-owned destructive Memory operations."""from __future__ import annotationsdiff --git a/config/v2_config.py b/config/v2_config.pyindex e75ac9800..4fc847ace 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -3677,6 +3677,16 @@ class V2Config:# Non-persisted diagnostics from disk migration/recovery. They let callers# surface a repair notice without weakening the strict write validator.load_warnings: ClassVar[tuple[str, ...]] = ()+ recovered_sections: ClassVar[tuple[str, ...]] = ()+ whole_config_recovery: ClassVar[bool] = False++ @property+ def memory_required(self) -> bool | None:+ """Return the persisted Memory requirement, or None when unreadable."""++ if self.whole_config_recovery:+ return None+ return bool(self.memory.enabled)@classmethoddef default(cls) -> "V2Config":@@ -3720,6 +3730,8 @@ class V2Config:logger.error("%s (backup=%s)", warning, backup)config = cls.default()config.load_warnings = (warning,)+ config.recovered_sections = ()+ config.whole_config_recovery = Truereturn configtry:@@ -3730,6 +3742,8 @@ class V2Config:logger.error("%s (backup=%s)", warning, backup)config = cls.default()config.load_warnings = (warning,)+ config.recovered_sections = ()+ config.whole_config_recovery = Truereturn configif not isinstance(payload, dict):@@ -3738,12 +3752,15 @@ class V2Config:logger.error("%s (backup=%s)", warning, backup)config = cls.default()config.load_warnings = (warning,)+ config.recovered_sections = ()+ config.whole_config_recovery = Truereturn configmigrated_payload, migrated, migration_warnings = _migrate_config_payload_on_load(payload)candidate = migrated_payloadrecovery_warnings: list[str] = []recovered_sections: set[str] = set()+ whole_config_recovery = Falsewhile True:try:config = cls.from_payload(candidate)@@ -3761,12 +3778,14 @@ class V2Config:logger.error("%s", warning)config = cls.default()recovery_warnings.append(warning)+ whole_config_recovery = Truebreakif not _reset_recoverable_config_section(candidate, section, field_name):warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"logger.error("%s", warning)config = cls.default()recovery_warnings.append(warning)+ whole_config_recovery = Truebreakrecovered_sections.add(recovered)recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")@@ -3810,6 +3829,8 @@ class V2Config:backup,)config.load_warnings = all_warnings+ config.recovered_sections = tuple(sorted(recovered_sections))+ config.whole_config_recovery = whole_config_recoveryreturn config@classmethoddiff --git a/core/memory_telemetry.py b/core/attachment_telemetry.pysimilarity index 67%rename from core/memory_telemetry.pyrename to core/attachment_telemetry.pyindex c479fcb7a..978e82fb9 100644--- a/core/memory_telemetry.py+++ b/core/attachment_telemetry.py@@ -1,8 +1,4 @@-"""Scrub-safe Memory attachment telemetry.--This leaf stays above the eager ``core.memory`` package because importing that-package loads SQLite-backed modules and breaks native-session lightweight imports.-"""+"""Scrub-safe attachment capture telemetry owned by the host."""from __future__ import annotations@@ -11,7 +7,7 @@ import logging# Preserve the existing observability channel while keeping this helper free of# admission and IM dependencies.-logger = logging.getLogger("core.memory.admission")+logger = logging.getLogger("avibe_memory.admission")def log_attachment_capture(diff --git a/core/memory/blocking.py b/core/blocking.pysimilarity index 96%rename from core/memory/blocking.pyrename to core/blocking.pyindex bd830d390..018735b58 100644--- a/core/memory/blocking.py+++ b/core/blocking.py@@ -1,4 +1,4 @@-"""Cancellation-safe execution for blocking Memory operations."""+"""Cancellation-safe execution for blocking host operations."""from __future__ import annotationsdiff --git a/core/controller.py b/core/controller.pyindex c41077920..43faf1ce4 100644--- a/core/controller.py+++ b/core/controller.py@@ -1,16 +1,18 @@"""Core controller that coordinates between modules and handlers"""+from __future__ import annotations+import asyncioimport concurrent.futuresimport jsonimport loggingimport threading-import time-from collections.abc import Awaitable, Callable+from collections.abc import AsyncIterator, Awaitable, Callable+from contextlib import asynccontextmanagerfrom copy import deepcopy-from dataclasses import dataclass, replace+from dataclasses import replacefrom pathlib import Path-from typing import Optional, Dict, Any, TypeVar+from typing import TYPE_CHECKING, Optional, Dict, Anyfrom config import pathsfrom config.platform_registry import get_platform_descriptorfrom config.v2_config import (@@ -40,6 +42,12 @@ from core.audio_asr import AudioAsrServicefrom core.message_context import build_context_session_keyfrom core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.message_output import MessageOutput+from core.memory_adapter import (+ DisabledCaptureReceipt,+ DisabledMemoryAdapter,+ MemoryCaptureAdapter,+ SessionArchived,+)from core.processing_indicator import ProcessingIndicatorServicefrom core.run_settlement import SETTLED_BY_NO_TERMINAL_RESULTfrom core.runtime_commands import RuntimeCommandWatcher@@ -52,26 +60,36 @@ from core.show_git import ShowGitCheckpointServicefrom core.update_checker import UpdateCheckerfrom core.watches import ManagedWatchServicefrom core.vibe_agents import VibeAgent, VibeAgentStore-from core.memory import CaptureAccepted, CaptureReceipt, CaptureRequest, CaptureSkipped-import core.memory.admission as memory_admission-from core.memory.admission import (- WORKBENCH_PLATFORM,- CaptureAdmission,- InboundTurnFacts,- admitted_user_id,-)-from core.memory.blocking import run_blocking-from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLease-from core.memory_telemetry import log_attachment_capture+from core.blocking import run_blocking+from config.memory_operation_lock import MemoryOperationBusy, MemoryOperationLease+from core.memory_loader import load_memory_runtimefrom vibe.i18n import get_supported_languages, t as i18n_t+from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryRuntimeBusyError,+ MemoryStoreUnavailableError,+)from vibe.runtime import mark_service_instance_started+if TYPE_CHECKING:+ from avibe_memory.admission import CaptureAdmission, InboundTurnFacts+ from avibe_memory.runtime import MemoryRuntime+ from avibe_memory.types import CaptureReceipt, CaptureRequest+logger = logging.getLogger(__name__)_RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS = 10.0-_MemorySessionLifecycleResult = TypeVar("_MemorySessionLifecycleResult")+_MEMORY_SHUTDOWN_BUDGET_SECONDS = 15.0+_DISABLED_MEMORY_CLEANUP_WAIT_SECONDS = 1.0++def _load_memory_capture_types() -> tuple[type, type, type]:+ """Resolve implementation receipt types only on an enabled capture path."""+ from avibe_memory import CaptureAccepted, CaptureRequest, CaptureSkipped++ return CaptureAccepted, CaptureRequest, CaptureSkippeddef _memory_reconfigure_changes_identity(expected_config: MemoryConfig,candidate_config: MemoryConfig,@@ -91,40 +109,6 @@ def _memory_reconfigure_changes_identity()-@dataclass-class _MemoryAttachmentCaptureReservation:- """Single-owner bridge from SessionTurn registration to Memory execution."""-- module: object- token: object | None- config_generation: int | None- capacity_token: object | None = None- capacity_outcome: str | None = None- active: bool = True-- def release(self) -> None:- if not self.active:- return- self.active = False- if self.token is not None:- cancel = getattr(self.module, "cancel_capture_reservation", None)- if callable(cancel):- cancel(self.token)- release_capacity = getattr(self.module, "release_capture_capacity", None)- if callable(release_capacity) and self.capacity_token is not None:- release_capacity(self.capacity_token)-- @property- def capacity_full(self) -> bool:- return self.capacity_outcome == "full"-- @property- def capacity_blocked(self) -> bool:- """Whether admission must drop the capture before scheduling it."""-- return self.capacity_outcome in {"full", "unavailable", "disabled"}--class _SettingsUserBindings:"""Answer Memory's binding question from the per-platform settings stores."""@@ -296,12 +280,14 @@ class Controller:self._runtime_work_shutdown_grace_seconds = (_RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS)+ self._memory_shutdown_budget_seconds = _MEMORY_SHUTDOWN_BUDGET_SECONDSself.enabled_platforms = list(getattr(config, "enabled_platforms", lambda: [config.platform])())self.primary_platform = getattr(getattr(config, "platforms", None), "primary", config.platform)self._reconcile_lock: Optional[asyncio.Lock] = Noneself._removed_im_clients: Dict[str, BaseIMClient] = {}self._memory_scopes_by_session: Dict[str, tuple[str, str]] = {}self._memory_cli_facts_by_session: Dict[str, InboundTurnFacts] = {}+ self._memory_implementation_cli_sessions: set[str] = set()# Session tracking (must be initialized before handlers)self.claude_sessions: Dict[str, Any] = {}@@ -397,6 +383,8 @@ class Controller:self._trace_retention_cancel_event: Optional[threading.Event] = Noneself._trace_retention_future: Optional[Any] = Noneself._memory_reconcile_task: Optional[asyncio.Task] = None+ self._memory_disabled_cleanup_task: Optional[asyncio.Task] = None+ self._memory_disabled_cleanup_unproved = Falseself._memory_replacement_gate = asyncio.Lock()self._memory_destructive_tasks: set[asyncio.Task[dict[str, Any]]] = set()self._memory_destructive_quiescing = False@@ -559,16 +547,20 @@ class Controller:self.native_session_service = Noneself.processing_indicator = ProcessingIndicatorService(self)self.audio_asr_service = AudioAsrService(self.config)- # The runtime serves controller UDS reads/capture and the shared- # private-IM Memory admission path.- from core.memory.runtime import create_memory_runtime-- self.memory_runtime = create_memory_runtime(- getattr(self.config, "memory", None) or MemoryConfig(),- processing_event=self._log_memory_processing_event,- on_config_settled=self._adopt_settled_memory_config,- )- self.memory_module = self.memory_runtime.module+ memory_config = getattr(self.config, "memory", None) or MemoryConfig()+ self.memory_adapter: MemoryCaptureAdapter = DisabledMemoryAdapter()+ self.memory_runtime = None+ self.memory_module = None+ self._memory_implementation_error: MemoryImplementationUnavailableError | MemoryImplementationIncompatibleError | None = None+ if memory_config.enabled:+ try:+ self.memory_runtime = self._create_memory_runtime(memory_config)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ self._memory_implementation_error = exc+ logger.warning("Memory implementation unavailable during startup: %s", exc)+ else:+ self.memory_module = self.memory_runtime.module+ self.memory_adapter = self.memory_runtime.capture_adapterself._migrate_discord_guild_scope_from_config()# Migrate legacy per-channel language into global config@@ -592,6 +584,30 @@ class Controller:self.config.memory = deepcopy(memory_config)+ def _create_memory_runtime(+ self,+ memory_config: MemoryConfig,+ *,+ allow_disabled: bool = False,+ ):+ """Load the optional Memory implementation only for an enabled runtime."""++ return load_memory_runtime(+ memory_config,+ allow_disabled=allow_disabled,+ processing_event=self._log_memory_processing_event,+ on_config_settled=self._adopt_settled_memory_config,+ is_enabled_user=_SettingsUserBindings(+ getattr(self, "platform_settings_managers", None)+ ).is_enabled_user,+ lifecycle_snapshot_matches=(+ self.session_turns.session_lifecycle_snapshot_matches+ ),+ acquire_lifecycle_admission=(+ self.session_turns.acquire_lifecycle_admission+ ),+ )+@staticmethoddef _derive_primary_platform(config) -> str:enabled = list(getattr(config, "enabled_platforms", lambda: [getattr(config, "platform", "slack")])())@@ -771,36 +787,735 @@ class Controller:"states": states,}- async def reconcile_memory(self, memory_config: MemoryConfig) -> dict[str, Any]:- """Hot-apply persisted Memory settings without destructive fallback."""+ async def _await_disabled_memory_cleanup(self) -> None:+ cleanup_task = getattr(self, "_memory_disabled_cleanup_task", None)+ if cleanup_task is not None and not cleanup_task.done():+ wait_seconds = max(+ 0.0,+ float(+ getattr(+ self,+ "_memory_disabled_cleanup_wait_seconds",+ _DISABLED_MEMORY_CLEANUP_WAIT_SECONDS,+ )+ ),+ )+ try:+ await asyncio.wait_for(+ asyncio.shield(cleanup_task),+ timeout=wait_seconds,+ )+ except asyncio.TimeoutError as exc:+ raise MemoryStoreUnavailableError(+ "Disabled Memory cleanup is still in progress"+ ) from exc++ def _start_memory_capture_adapter(self, runtime: "MemoryRuntime") -> bool:+ """Bind every capture task to the Controller-owned event loop."""+ loop = getattr(self, "_loop", None)+ if loop is None:+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ return False+ if loop.is_closed():+ return False+ return runtime.start_capture_adapter(task_factory=loop.create_task)++ async def _try_memory_operation_lease(+ self,+ effective_home: Path | None = None,+ ) -> MemoryOperationLease | None:+ lease = MemoryOperationLease(effective_home)+ try:+ await run_blocking(+ lease.acquire,+ on_cancel_result=lambda _result: lease.release(),+ )+ except MemoryOperationBusy:+ return None+ return lease++ @asynccontextmanager+ async def _memory_operation(self, effective_home: Path | None = None):+ lease = await self._try_memory_operation_lease(effective_home)+ try:+ yield lease+ finally:+ if lease is not None:+ await run_blocking(lease.release)++ def _retry_memory_runtime(+ self,+ memory_config: MemoryConfig,+ *,+ allow_disabled: bool = False,+ ) -> "MemoryRuntime":+ try:+ runtime = self._create_memory_runtime(+ memory_config,+ **({"allow_disabled": True} if allow_disabled else {}),+ )+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ self._memory_implementation_error = exc+ raise+ self._memory_implementation_error = None+ return runtime++ async def _close_unpublished_memory_runtime(+ self,+ runtime: "MemoryRuntime",+ ) -> None:+ runtime.begin_close()+ try:+ await runtime.close()+ except BaseException:+ async with self._memory_replacement_lock():+ if getattr(self, "memory_runtime", None) is None:+ self.memory_adapter = DisabledMemoryAdapter()+ self.memory_runtime = runtime+ self.memory_module = None+ raise++ async def _settle_retained_memory_runtime(+ self,+ runtime: "MemoryRuntime",+ ) -> bool:+ async with self._memory_replacement_lock():+ if getattr(self, "memory_runtime", None) is not runtime:+ return False+ try:+ await runtime.close()+ runtime.release_retained_root_ownership()+ except Exception:+ return False+ return await self._clear_memory_runtime(runtime)++ @asynccontextmanager+ async def _memory_mutation_runtime(+ self,+ memory_config: MemoryConfig,+ *,+ allow_disabled: bool = False,+ settle_closing: bool = True,+ ) -> AsyncIterator[tuple["MemoryRuntime" | None, bool]]:async with self._memory_replacement_lock():runtime = getattr(self, "memory_runtime", None)- if runtime is None:- return {"ok": False, "state": "degraded", "error": "memory_store_unavailable"}- result = await runtime.reconcile(memory_config)+ async with self._memory_operation(+ getattr(runtime, "effective_home", None)+ ) as lease:+ if lease is None:+ yield None, False+ return+ async with self._memory_replacement_lock():+ if getattr(self, "memory_runtime", None) is not runtime:+ yield None, False+ return+ if settle_closing and runtime is not None and bool(getattr(runtime, "closing", False)):+ if not await self._settle_retained_memory_runtime(runtime):+ yield None, False+ return+ runtime = None+ created = runtime is None+ if created:+ try:+ runtime = self._retry_memory_runtime(+ memory_config,+ allow_disabled=allow_disabled,+ )+ except MemoryRuntimeBusyError:+ yield None, False+ return+ yield runtime, created++ async def _attach_memory_runtime(+ self,+ runtime: "MemoryRuntime",+ *,+ capture_enabled: bool,+ previous: "MemoryRuntime" | None = None,+ ) -> None:+ async with self._memory_replacement_lock():+ current = getattr(self, "memory_runtime", None)+ if (+ previous is None and current is not None and current is not runtime+ ) or previous is not None and current is not previous:+ raise RuntimeError("A different Memory runtime is already owned")+ accept_ownership = getattr(runtime, "accept_root_ownership", None)+ if callable(accept_ownership):+ accept_ownership()+ self.memory_runtime = runtimeself.memory_module = runtime.module- if result.get("ok") is True:- self.config.memory = memory_config- return result+ self._memory_implementation_error = None+ if capture_enabled:+ self._start_memory_capture_adapter(runtime)+ self.memory_adapter = (+ runtime.capture_adapter+ if capture_enabled+ else DisabledMemoryAdapter()+ )- async def capture_memory(self, request: CaptureRequest) -> CaptureReceipt:- """Capture through the replacement gate so stale modules cannot write."""+ async def _detach_memory_runtime(+ self,+ runtime: "MemoryRuntime" | None = None,+ *,+ disabled_config: MemoryConfig | None = None,+ ) -> "MemoryRuntime" | None:+ async with self._memory_replacement_lock():+ current = getattr(self, "memory_runtime", None)+ if runtime is not None and current is not runtime:+ return None+ self.memory_adapter = DisabledMemoryAdapter()+ if disabled_config is not None:+ self.config.memory = disabled_config+ if current is not None:+ current.begin_close()+ self.memory_module = None+ return current++ async def _clear_memory_runtime(self, runtime: "MemoryRuntime") -> bool:+ async with self._memory_replacement_lock():+ if getattr(self, "memory_runtime", None) is not runtime:+ return False+ self.memory_runtime = None+ self.memory_module = None+ return True++ async def _retire_memory_runtime_for_reset(+ self,+ runtime: "MemoryRuntime",+ *,+ allow_unpublished: bool,+ ) -> object | None:+ async with self._memory_replacement_lock():+ current = getattr(self, "memory_runtime", None)+ if current is not runtime and not (allow_unpublished and current is None):+ return None+ self.memory_adapter = DisabledMemoryAdapter()+ ownership = runtime.begin_root_ownership_handoff()+ self.memory_runtime = runtime+ self.memory_module = None+ return ownership++ async def _activate_memory_replacement(+ self,+ previous: "MemoryRuntime",+ config: MemoryConfig,+ root_ownership: object,+ ) -> tuple["MemoryRuntime", dict[str, Any]]:+ fresh = previous.replacement(config, root_ownership)+ await self._attach_memory_runtime(+ fresh,+ capture_enabled=True,+ previous=previous,+ )+ return fresh, await fresh.wake(operation_lease_held=True)- observed_runtime = getattr(self, "memory_runtime", None)- if observed_runtime is None or getattr(observed_runtime, "retired", False):- return CaptureSkipped(reason="memory_operation_in_progress")+ async def _memory_runtime_for_operation(self) -> "MemoryRuntime":+ await self._await_disabled_memory_cleanup()async with self._memory_replacement_lock():+ if not self.config.memory.enabled:+ raise MemoryStoreUnavailableError("Memory is disabled")runtime = getattr(self, "memory_runtime", None)- if (- runtime is not observed_runtime- or runtime is None- or getattr(runtime, "retired", False)- ):+ implementation_error = getattr(self, "_memory_implementation_error", None)+ if runtime is None and implementation_error is not None:+ raise implementation_error+ if runtime is None:+ raise MemoryStoreUnavailableError("Memory runtime is unavailable")+ return runtime++ async def preflight_memory(self, memory_config: MemoryConfig) -> dict[str, Any]:+ """Preflight a candidate without activating capture on a disabled host."""++ async with self._memory_mutation_runtime(memory_config) as runtime_context:+ runtime, created = runtime_context+ if runtime is None:+ return {"ok": False, "error": "memory_operation_in_progress"}+ try:+ return await runtime.preflight(memory_config)+ except MemoryRuntimeBusyError:+ return {"ok": False, "error": "memory_operation_in_progress"}+ finally:+ if created:+ await self._close_unpublished_memory_runtime(runtime)++ async def install_memory_runtime(self) -> dict[str, Any]:+ """Install the managed artifact through Controller runtime ownership."""++ async with self._memory_mutation_runtime(+ self.config.memory,+ allow_disabled=True,+ ) as runtime_context:+ runtime, created = runtime_context+ if runtime is None:+ return {+ "ok": False,+ "reason": "memory_operation_in_progress",+ "download_error": None,+ }+ try:+ return await runtime.install_artifact(operation_lease_held=True)+ finally:+ if created:+ await self._close_unpublished_memory_runtime(runtime)++ async def reconcile_memory(self, memory_config: MemoryConfig) -> dict[str, Any]:+ """Hot-apply persisted Memory settings without destructive fallback."""++ if not memory_config.enabled:+ busy = {+ "ok": False,+ "state": "disabled",+ "error": "memory_operation_in_progress",+ }+ async with self._memory_replacement_lock():+ runtime = getattr(self, "memory_runtime", None)+ async with self._memory_operation(+ getattr(runtime, "effective_home", None)+ ) as lease:+ if lease is None:+ return busy+ async with self._memory_replacement_lock():+ if getattr(self, "memory_runtime", None) is not runtime:+ return busy+ self.memory_adapter = DisabledMemoryAdapter()+ self.config.memory = memory_config+ if runtime is not None:+ runtime.begin_close()+ self.memory_module = None+ if runtime is not None and not await self._settle_retained_memory_runtime(+ runtime+ ):+ return busy+ await self._recheck_disabled_memory_cleanup()+ return {"ok": True, "state": "disabled"}++ async with self._memory_mutation_runtime(memory_config) as runtime_context:+ runtime, created = runtime_context+ if runtime is None:+ return {"ok": False, "error": "memory_operation_in_progress"}+ if created:+ try:+ await self._attach_memory_runtime(runtime, capture_enabled=False)+ except BaseException:+ await self._close_unpublished_memory_runtime(runtime)+ raise+ try:+ result = await runtime.reconcile(memory_config)+ async with self._memory_replacement_lock():+ still_owned = getattr(self, "memory_runtime", None) is runtime+ current_enabled = bool(self.config.memory.enabled)+ publishable = (+ still_owned+ and not bool(getattr(runtime, "closing", False))+ )+ if publishable:+ self.memory_module = runtime.module+ if result.get("ok") is True:+ self.config.memory = memory_config+ self._start_memory_capture_adapter(runtime)+ self.memory_adapter = runtime.capture_adapter+ if result.get("ok") is True and not publishable:+ return {+ "ok": False,+ "state": "degraded" if current_enabled else "disabled",+ "error": "memory_operation_in_progress",+ }+ return result+ except BaseException:+ if created:+ detached = await self._detach_memory_runtime(runtime)+ if detached is runtime:+ await runtime.close()+ await self._clear_memory_runtime(runtime)+ raise++ async def capture_memory(self, request: CaptureRequest) -> CaptureReceipt:+ """Snapshot the current module before offering one volatile capture."""++ if not self.config.memory.enabled:+ return DisabledCaptureReceipt()+ implementation_error = getattr(self, "_memory_implementation_error", None)+ if implementation_error is not None:+ raise implementation_error+ _CaptureAccepted, _CaptureRequest, CaptureSkipped = (+ _load_memory_capture_types()+ )+ del _CaptureAccepted, _CaptureRequest+ async with self._memory_replacement_lock():+ implementation_error = getattr(self, "_memory_implementation_error", None)+ if implementation_error is not None:+ raise implementation_error+ runtime = getattr(self, "memory_runtime", None)+ if runtime is None:return CaptureSkipped(reason="memory_operation_in_progress")if not runtime.available:return CaptureSkipped(reason="memory_store_unavailable")- return await runtime.module.capture(request)+ module = runtime.module+ return await module.capture(request)++ def _disabled_memory_source_payload(+ self,+ *,+ reason: str = "memory_disabled",+ ) -> dict[str, Any]:+ return {+ "status": "unavailable",+ "observed_at": None,+ "reason": reason,+ }++ def _disabled_memory_status_payload(+ self,+ *,+ retained_runtime: bool = False,+ cleanup_unproved: bool = False,+ ) -> dict[str, Any]:+ config = self.config.memory+ runtime_busy = retained_runtime or cleanup_unproved+ needs_repair = bool(config.legacy_needs_repair)+ state = "degraded" if runtime_busy else (+ "needs_repair" if needs_repair else "disabled"+ )+ reason = "memory_runtime_busy" if runtime_busy else (+ "memory_legacy_recovery_required" if needs_repair else None+ )+ return {+ "status": "ok",+ "source": self._disabled_memory_source_payload(+ reason="memory_runtime_busy" if runtime_busy else "memory_disabled"+ ),+ "health": None,+ "state": state,+ "reason": reason,+ "attachment_capture": {+ "status": (+ "unavailable"+ if config.effective_multimodal_available()+ else "not_configured"+ )+ },+ }++ def _disabled_memory_status_payload_locked(self) -> dict[str, Any]:+ """Project Controller-owned disabled state while its pointer lock is held."""++ cleanup_task = getattr(self, "_memory_disabled_cleanup_task", None)+ return self._disabled_memory_status_payload(+ retained_runtime=getattr(self, "memory_runtime", None) is not None,+ cleanup_unproved=(+ getattr(self, "_memory_disabled_cleanup_unproved", False)+ or (cleanup_task is not None and not cleanup_task.done())+ ),+ )++ def _disabled_memory_processing_record_payload(self) -> dict[str, Any]:+ def unavailable() -> dict[str, Any]:+ return self._disabled_memory_source_payload()++ return {+ "status": "ok",+ "runtime": {"source": unavailable(), "health": None},+ "sources": {+ "memcells": unavailable(),+ "runs": unavailable(),+ "semantic": unavailable(),+ },+ "anomalies": {"source": unavailable(), "items": []},+ "maintenance": {+ "source": unavailable(),+ # Without store I/O, absence cannot be proved. Keep explicit+ # deletion available for state left by an older enabled run.+ "data_exists": True,+ "can_delete_data": True,+ },+ }++ def _disabled_memory_maintenance_payload(self) -> dict[str, Any]:+ return {+ "status": "ok",+ # See the matching Processing Record projection above.+ "data_exists": True,+ "can_delete_data": True,+ }++ async def memory_status_payload(self) -> dict[str, Any]:+ """Project disabled status without loading or touching Memory state."""++ async with self._memory_replacement_lock():+ if not self.config.memory.enabled:+ return self._disabled_memory_status_payload_locked()+ try:+ runtime = await self._memory_runtime_for_operation()+ return await runtime.status_payload()+ except MemoryStoreUnavailableError:+ async with self._memory_replacement_lock():+ if not self.config.memory.enabled:+ return self._disabled_memory_status_payload_locked()+ raise++ async def wake_memory(self) -> dict[str, Any]:+ """Wake enabled Memory, or return the host-owned disabled outcome."""++ if not self.config.memory.enabled:+ if self.config.memory.legacy_needs_repair:+ return {+ "ok": False,+ "state": "needs_repair",+ "error": "memory_legacy_recovery_required",+ }+ return {"ok": False, "state": "disabled", "error": "memory_disabled"}+ runtime = await self._memory_runtime_for_operation()+ return await runtime.wake()++ async def memory_processing_record_payload(+ self,+ *,+ verified_user_key: str | None,+ ) -> dict[str, Any]:+ if not self.config.memory.enabled:+ return self._disabled_memory_processing_record_payload()+ runtime = await self._memory_runtime_for_operation()+ return await runtime.processing_record_payload(+ verified_user_key=verified_user_key+ )++ async def memory_failure_log_payload(+ self,+ *,+ verified_user_key: str | None,+ ) -> dict[str, Any]:+ runtime = await self._memory_runtime_for_operation()+ return await runtime.failure_log_payload(+ verified_user_key=verified_user_key+ )++ async def memory_maintenance_payload(+ self,+ *,+ verified_user_key: str | None,+ ) -> dict[str, Any]:+ if not self.config.memory.enabled:+ return self._disabled_memory_maintenance_payload()+ runtime = await self._memory_runtime_for_operation()+ return await runtime.maintenance_payload(+ verified_user_key=verified_user_key+ )++ async def _memory_scope_for_runtime(+ self,+ runtime: "MemoryRuntime",+ *,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> tuple[str, str]:+ from avibe_memory.store import is_principal_id, is_project_id++ try:+ if verified_user_key is not None:+ scope = (+ await runtime.resolve_principal_for_user_key(verified_user_key),+ self.default_memory_project_id(),+ )+ else:+ scope = cli_scope+ except MemoryStoreUnavailableError:+ raise+ except Exception as exc:+ raise MemoryStoreUnavailableError(+ "Memory store is unavailable"+ ) from exc+ if (+ not isinstance(scope, tuple)+ or len(scope) != 2+ or not is_principal_id(scope[0])+ or not is_project_id(scope[1])+ ):+ raise PermissionError("Memory access denied")+ return scope++ async def _memory_scope_for_project(+ self,+ runtime: "MemoryRuntime",+ scope: tuple[str, str],+ project_id: str | None,+ ) -> tuple[str, str]:+ principal_id, default_project_id = scope+ if project_id is None or project_id == default_project_id:+ return scope+ try:+ catalog = await runtime.list_memory_projects(principal_id)+ except Exception as exc:+ raise MemoryStoreUnavailableError(+ "Memory store is unavailable"+ ) from exc+ if project_id not in catalog:+ raise ValueError("unknown Memory project")+ return principal_id, project_id++ async def memory_profile_payload(+ self,+ *,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ runtime = await self._memory_runtime_for_operation()+ scope = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ return await runtime.profile_payload(*scope)++ async def memory_processing_record_entries_payload(+ self,+ *,+ cursor: str | None,+ limit: int,+ project_id: str | None,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ runtime = await self._memory_runtime_for_operation()+ scope = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ scope = await self._memory_scope_for_project(runtime, scope, project_id)+ return await runtime.processing_record_entries_payload(+ *scope,+ cursor,+ limit,+ )++ async def memory_processing_record_entry_payload(+ self,+ *,+ memcell_id: str,+ project_id: str | None,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ runtime = await self._memory_runtime_for_operation()+ scope = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ scope = await self._memory_scope_for_project(runtime, scope, project_id)+ return await runtime.processing_record_entry_payload(*scope, memcell_id)++ async def memory_projects_payload(+ self,+ *,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ from vibe.memory_project_ids import (+ DEFAULT_MEMORY_PROJECT_ID,+ MEMORY_SEARCH_ALL_PROJECTS,+ )++ runtime = await self._memory_runtime_for_operation()+ principal_id, _project_id = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ try:+ catalogued = await runtime.list_memory_projects(principal_id)+ except Exception as exc:+ raise MemoryStoreUnavailableError(+ "Memory store is unavailable"+ ) from exc+ named = [item for item in catalogued if item != DEFAULT_MEMORY_PROJECT_ID]+ return {+ "status": "ok",+ "projects": [+ {"id": DEFAULT_MEMORY_PROJECT_ID, "kind": "default"},+ *[{"id": item, "kind": "named"} for item in named],+ {"id": MEMORY_SEARCH_ALL_PROJECTS, "kind": "all"},+ ],+ }++ async def memory_search_payload(+ self,+ *,+ query: str,+ policy: Any,+ project_id: str,+ current_session_id: str | None,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ from vibe.memory_project_ids import DEFAULT_MEMORY_PROJECT_ID++ runtime = await self._memory_runtime_for_operation()+ scope = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ if project_id not in {DEFAULT_MEMORY_PROJECT_ID, "all"}:+ await self._memory_scope_for_project(runtime, scope, project_id)+ return await runtime.search_payload(+ query,+ policy,+ scope[0],+ project_id,+ current_session_id=current_session_id,+ )++ async def memory_list_payload(+ self,+ *,+ project_id: str,+ page: int | None,+ cursor: str | None,+ limit: int,+ origin: str | None,+ verified_user_key: str | None,+ cli_scope: tuple[str, str] | None,+ ) -> dict[str, Any]:+ from vibe.memory_project_ids import (+ DEFAULT_MEMORY_PROJECT_ID,+ MEMORY_SEARCH_ALL_PROJECTS,+ )++ runtime = await self._memory_runtime_for_operation()+ principal_id, default_project_id = await self._memory_scope_for_runtime(+ runtime,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ del default_project_id+ origin_options = {"origin": origin} if origin is not None else {}+ if project_id == MEMORY_SEARCH_ALL_PROJECTS:+ return await runtime.list_all_episodes_payload(+ principal_id,+ cursor=cursor,+ limit=limit,+ **origin_options,+ )+ if project_id != DEFAULT_MEMORY_PROJECT_ID:+ if getattr(runtime, "available", True) is False:+ raise MemoryStoreUnavailableError(+ "Memory store is unavailable"+ )+ await self._memory_scope_for_project(+ runtime,+ (principal_id, DEFAULT_MEMORY_PROJECT_ID),+ project_id,+ )+ return await runtime.list_episodes_payload(+ principal_id,+ project_id,+ page=page,+ page_size=limit,+ **origin_options,+ )async def repair_memory(self, *, confirm_loss: bool) -> dict[str, Any]:"""Reset unusable local data, then prove native EverOS readiness."""@@ -812,14 +1527,6 @@ class Controller:"error": "memory_loss_confirmation_required","result": "unchanged",}- runtime = getattr(self, "memory_runtime", None)- if runtime is None or not getattr(runtime, "needs_repair", False):- return {- "ok": False,- "operation": "repair",- "error": "memory_repair_not_required",- "result": "unchanged",- }return await self._reset_memory_data(operation="repair")async def delete_memory_data(self, *, confirm_loss: bool) -> dict[str, Any]:@@ -933,6 +1640,168 @@ class Controller:exc_info=(type(errors[0]), errors[0], errors[0].__traceback__),)+ @asynccontextmanager+ async def _memory_runtime_for_data_reset(+ self,+ ) -> AsyncIterator[tuple["MemoryRuntime" | None, bool]]:+ async with self._memory_mutation_runtime(+ self.config.memory,+ allow_disabled=True,+ settle_closing=False,+ ) as runtime_context:+ runtime, created = runtime_context+ if runtime is None:+ yield None, False+ return+ try:+ yield runtime, not created+ finally:+ if created and not bool(getattr(runtime, "closing", False)):+ await self._close_unpublished_memory_runtime(runtime)++ async def _cancel_memory_reconcile_task(self) -> None:+ task = getattr(self, "_memory_reconcile_task", None)+ try:+ if task is None:+ return+ if not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ except Exception as error:+ logger.debug("Memory startup reconciliation already failed: %s", error)+ finally:+ self._memory_reconcile_task = None++ async def _cancel_disabled_memory_cleanup_task(self) -> None:+ task = getattr(self, "_memory_disabled_cleanup_task", None)+ try:+ if task is None:+ return+ if not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ except Exception as error:+ logger.debug("Disabled Memory cleanup already failed: %s", error)+ finally:+ self._memory_disabled_cleanup_task = None++ @staticmethod+ def _log_late_memory_shutdown_stage(task: asyncio.Task[Any], label: str) -> None:+ try:+ task.result()+ except asyncio.CancelledError:+ return+ except Exception:+ logger.error("Memory %s failed after the shutdown budget", label, exc_info=True)++ async def _shutdown_memory_stack(self) -> None:+ """Attempt every Memory shutdown stage within one finite shared budget."""++ self._memory_destructive_quiescing = True+ adapter = getattr(self, "memory_adapter", None)+ quiesce = getattr(adapter, "quiesce_memory_capture_tasks", None)+ if callable(quiesce):+ quiesce()++ stages: list[tuple[str, Callable[[], Awaitable[None]]]] = []+ if getattr(self, "_memory_disabled_cleanup_task", None) is not None:+ stages.append(+ ("disabled cleanup", self._cancel_disabled_memory_cleanup_task)+ )+ if getattr(self, "_memory_reconcile_task", None) is not None:+ stages.append(("startup reconciliation", self._cancel_memory_reconcile_task))++ stages.append(+ ("destructive-operation settlement", self._join_memory_destructive_transactions)+ )++ budget = max(+ 0.0,+ float(+ getattr(+ self,+ "_memory_shutdown_budget_seconds",+ _MEMORY_SHUTDOWN_BUDGET_SECONDS,+ )+ ),+ )+ loop = asyncio.get_running_loop()+ deadline = loop.time() + budget+ for index, (label, operation) in enumerate(stages):+ remaining = max(0.0, deadline - loop.time())+ stage_budget = remaining / (len(stages) - index + 1)+ task = asyncio.create_task(operation(), name=f"memory-shutdown-{index}")+ done, _pending = await asyncio.wait({task}, timeout=stage_budget)+ if task not in done:+ self._shutdown_tainted = True+ logger.error(+ "Memory %s exceeded its %.3fs shutdown budget slice",+ label,+ stage_budget,+ )+ task.add_done_callback(+ lambda settled, stage=label: self._log_late_memory_shutdown_stage(+ settled,+ stage,+ )+ )+ task.cancel()+ await asyncio.sleep(0)+ continue+ try:+ task.result()+ except asyncio.CancelledError:+ self._shutdown_tainted = True+ logger.error("Memory %s was cancelled during shutdown", label)+ except Exception:+ self._shutdown_tainted = True+ logger.error("Memory %s failed during shutdown", label, exc_info=True)++ try:+ await self._close_memory_runtime_for_shutdown(+ timeout_seconds=max(0.0, deadline - loop.time())+ )+ except Exception:+ self._shutdown_tainted = True+ logger.error("Memory runtime close failed during shutdown", exc_info=True)++ async def _close_memory_runtime_for_shutdown(self, *, timeout_seconds: float) -> None:+ if any(+ not task.done()+ for task in getattr(self, "_memory_destructive_tasks", ())+ ):+ raise MemoryRuntimeBusyError(+ "Memory destructive operation is still active"+ )+ loop = asyncio.get_running_loop()+ deadline = loop.time() + max(0.0, timeout_seconds)+ async with self._memory_replacement_lock():+ runtime = getattr(self, "memory_runtime", None)+ effective_home = getattr(runtime, "effective_home", None)+ lease = await self._try_memory_operation_lease(effective_home)+ while lease is None and loop.time() < deadline:+ await asyncio.sleep(min(0.01, deadline - loop.time()))+ lease = await self._try_memory_operation_lease(effective_home)+ if lease is None:+ raise MemoryRuntimeBusyError(+ "Memory operation is still active during shutdown"+ )+ try:+ runtime = await self._detach_memory_runtime()+ if runtime is not None:+ await runtime.close(+ timeout_seconds=max(0.0, deadline - loop.time())+ )+ await self._clear_memory_runtime(runtime)+ finally:+ await run_blocking(lease.release)+async def _reset_memory_data_transaction(self,*,@@ -940,16 +1809,19 @@ class Controller:target_config: MemoryConfig | None = None,expected_config: MemoryConfig | None = None,) -> dict[str, Any]:- from core.memory.data_reset import (- unchanged_memory_data_result,- )- async with self._memory_replacement_lock():- runtime = getattr(self, "memory_runtime", None)+ async with self._memory_runtime_for_data_reset() as runtime_context:+ runtime, attached = runtime_context+ from avibe_memory.data_reset import unchanged_memory_data_result++ busy = {+ "ok": False,+ "operation": operation,+ "error": "memory_operation_in_progress",+ "result": "unchanged",+ }if runtime is None:- return unchanged_memory_data_result(- operation=operation,- reason="memory_runtime_unavailable",- )+ return busy+if operation == "repair" and not runtime.needs_repair:return {"ok": False,@@ -958,32 +1830,9 @@ class Controller:"result": "unchanged",}- lease = MemoryOperationLease(runtime.effective_home)- try:- await run_blocking(lease.acquire)- except MemoryOperationBusy:- return {- "ok": False,- "operation": operation,- "error": "memory_operation_in_progress",- "result": "unchanged",- }- except Exception:- logger.exception("Memory data reset could not acquire operation lease")- return unchanged_memory_data_result(- runtime.effective_home,- operation=operation,- reason="operation_lock_failed",- )-- try:- if getattr(runtime, "_artifact_installing", False):- return {- "ok": False,- "operation": operation,- "error": "memory_operation_in_progress",- "result": "unchanged",- }+ if getattr(runtime, "_artifact_installing", False):+ return busy+ if not bool(getattr(runtime, "closing", False)):try:await runtime.prepare_data_reset()except Exception:@@ -996,52 +1845,25 @@ class Controller:reason="sidecar_termination_unproved",)- target = replace(- deepcopy(target_config or self.config.memory),- legacy_needs_repair=False,+ try:+ root_ownership = await self._retire_memory_runtime_for_reset(+ runtime,+ allow_unpublished=not attached,)+ except MemoryRuntimeBusyError:+ await self._settle_retained_memory_runtime(runtime)+ return busy+ if root_ownership is None:+ return busy++ target = replace(+ deepcopy(target_config or self.config.memory),+ legacy_needs_repair=False,+ )- def persist_reset_fence(current: MemoryConfig) -> MemoryConfig:- if operation == "reconfigure":- if expected_config is None or current != expected_config:- raise MemoryConfigStaleWrite("memory candidate changed")- return replace(current, legacy_needs_repair=True)-- try:- fenced_config = (- await run_blocking(- atomic_update_memory,- persist_reset_fence,- )- ).memory- except MemoryConfigStaleWrite:- return {- "ok": False,- "operation": operation,- "error": "memory_operation_in_progress",- "result": "unchanged",- }- except Exception:- logger.exception(- "Memory data reset could not persist its repair fence"- )- return unchanged_memory_data_result(- runtime.effective_home,- operation=operation,- reason="config_persist_failed",- )- self.config.memory = fenced_config-- def persist_confirmed_config(current: MemoryConfig) -> MemoryConfig:- if operation == "reconfigure":- if current != fenced_config:- raise MemoryConfigStaleWrite("memory candidate changed")- return target- return replace(current, legacy_needs_repair=False)-- runtime.retire()+ async def close_reset_runtime() -> dict[str, Any] | None:try:- await runtime.close()+ await runtime.close(root_ownership=root_ownership)except BaseException:logger.exception("Memory data reset could not close the owned runtime")runtime.mark_needs_repair(f"memory_{operation}_failed")@@ -1052,130 +1874,192 @@ class Controller:)failure["state"] = "needs_repair"return failure- if not runtime.closed:- runtime.mark_needs_repair(f"memory_{operation}_failed")- failure = unchanged_memory_data_result(- runtime.effective_home,- operation=operation,- reason="runtime_termination_unproved",+ return None++ async def release_disabled() -> None:+ runtime.release_root_ownership(root_ownership)+ await self._clear_memory_runtime(runtime)++ async def publish(config: MemoryConfig):+ self.config.memory = config+ if config.enabled:+ return await self._activate_memory_replacement(+ runtime,+ config,+ root_ownership,)- failure["state"] = "needs_repair"- return failure+ await release_disabled()+ return None, {"ok": True, "state": "disabled"}+ async def restore_after_fence_failure(+ failure: dict[str, Any],+ ) -> dict[str, Any]:try:- await runtime.settle_after_data_loss()+ live_config = (await run_blocking(V2Config.load)).memoryexcept Exception:logger.exception(- "Memory data reset could not preserve and rotate stable identity"+ "Memory could not reload configuration after reset fencing failed")- runtime.mark_needs_repair(f"memory_{operation}_failed")+ failure.update(state="degraded", result="runtime_restore_failed")+ return failure+ try:+ _fresh, activation = await publish(live_config)+ except MemoryRuntimeBusyError:+ failure.update(+ state="degraded",+ error="memory_operation_in_progress",+ result="runtime_restore_failed",+ )+ return failure+ except Exception:+ logger.exception(+ "Memory could not restore its enabled runtime after fencing failed"+ )+ failure.update(state="degraded", result="runtime_restore_failed")+ return failure+ failure["state"] = str(activation.get("state") or "degraded")+ if activation.get("ok") is not True:+ failure.update(+ error=activation.get("error", failure.get("error")),+ result="runtime_restore_failed",+ )+ return failure++ def persist_reset_fence(current: MemoryConfig) -> MemoryConfig:+ if operation == "reconfigure":+ if expected_config is None or current != expected_config:+ raise MemoryConfigStaleWrite("memory candidate changed")+ return replace(current, legacy_needs_repair=True)++ try:+ fenced_config = (+ await run_blocking(+ atomic_update_memory,+ persist_reset_fence,+ )+ ).memory+ except Exception as exc:+ stale = isinstance(exc, MemoryConfigStaleWrite)+ if not stale:+ logger.exception(+ "Memory data reset could not persist its repair fence"+ )+ if failure := await close_reset_runtime():+ return failure+ if stale:+ failure = busy+ else:failure = unchanged_memory_data_result(runtime.effective_home,operation=operation,- reason="identity_settlement_failed",+ reason="config_persist_failed",)- failure["state"] = "needs_repair"- return failure-- deletion = await run_blocking(- runtime.reset_mutable_data,+ return await restore_after_fence_failure(failure)+ self.config.memory = fenced_config++ def persist_confirmed_config(current: MemoryConfig) -> MemoryConfig:+ if operation == "reconfigure":+ if current != fenced_config:+ raise MemoryConfigStaleWrite("memory candidate changed")+ return target+ return replace(current, legacy_needs_repair=False)++ if failure := await close_reset_runtime():+ return failure+ try:+ await runtime.settle_after_data_loss(root_ownership)+ except Exception:+ logger.exception(+ "Memory data reset could not preserve and rotate stable identity")- deletion_payload = deletion.payload()- if deletion.data_remaining:- failed = runtime.replacement(fenced_config)- self.memory_runtime = failed- self.memory_module = failed.module- return {- "ok": False,- "operation": operation,- "state": "needs_repair",- "error": f"memory_{operation}_failed",- "result": "partial",- **deletion_payload,- }+ runtime.mark_needs_repair(f"memory_{operation}_failed")+ failure = unchanged_memory_data_result(+ runtime.effective_home,+ operation=operation,+ reason="identity_settlement_failed",+ )+ failure["state"] = "needs_repair"+ return failure+ deletion = await run_blocking(+ runtime.reset_mutable_data,+ root_ownership,+ )+ deletion_payload = deletion.payload()+ if deletion.data_remaining:+ await publish(fenced_config)+ return {+ "ok": False,+ "operation": operation,+ "state": "needs_repair",+ "error": f"memory_{operation}_failed",+ "result": "partial",+ **deletion_payload,+ }++ try:+ persisted = await run_blocking(+ atomic_update_memory,+ persist_confirmed_config,+ )+ except Exception as exc:+ stale = isinstance(exc, MemoryConfigStaleWrite)+ if not stale:+ logger.exception(+ "Memory data reset deleted data but could not persist configuration"+ )try:- persisted = await run_blocking(- atomic_update_memory,- persist_confirmed_config,+ live_config = (await run_blocking(V2Config.load)).memory+ except Exception:+ logger.exception(+ "Memory data reset could not reload configuration after deletion")- except Exception as exc:- stale = isinstance(exc, MemoryConfigStaleWrite)- if not stale:- logger.exception(- "Memory data reset deleted data but could not persist configuration"- )- try:- live_config = (await run_blocking(V2Config.load)).memory- except Exception:- logger.exception(- "Memory data reset could not reload configuration after deletion"- )- live_config = deepcopy(expected_config or self.config.memory)- fallback = runtime.replacement(live_config)- self.memory_runtime = fallback- self.memory_module = fallback.module- self.config.memory = live_config- fallback_state = "disabled"- if live_config.enabled:- fallback_activation = await fallback.wake(- operation_lease_held=True- )- fallback_state = str(- fallback_activation.get("state") or "degraded"- )- return {- "ok": False,- "operation": operation,- "state": fallback_state,- "error": (- "memory_operation_in_progress"- if stale- else f"memory_{operation}_failed"- ),- "result": "deleted_config_not_applied",- **deletion_payload,- }-- target = persisted.memory- self.config.memory = target- fresh = runtime.replacement(target)- self.memory_runtime = fresh- self.memory_module = fresh.module- self.config.memory = target+ live_config = deepcopy(expected_config or self.config.memory)+ _fresh, fallback = await publish(live_config)+ return {+ "ok": False,+ "operation": operation,+ "state": str(fallback.get("state") or "degraded"),+ "error": (+ "memory_operation_in_progress"+ if stale+ else f"memory_{operation}_failed"+ ),+ "result": "deleted_config_not_applied",+ **deletion_payload,+ }- if not target.enabled:- return {- "ok": True,- "operation": operation,- "state": "disabled",- "result": "completed",- **deletion_payload,- }- activation = await fresh.wake(operation_lease_held=True)- if activation.get("ok") is not True:- state = activation.get("state")- if state == "needs_repair" and not fresh.needs_repair:- fresh.mark_needs_repair(- str(activation.get("error") or f"memory_{operation}_failed")- )- return {- "ok": False,- "operation": operation,- "state": "needs_repair" if fresh.needs_repair else "degraded",- "error": activation.get("error", f"memory_{operation}_failed"),- "result": "deleted_readiness_failed",- **deletion_payload,- }+ target = persisted.memory+ fresh, activation = await publish(target)+ if fresh is None:return {"ok": True,"operation": operation,- "state": "running",+ "state": "disabled","result": "completed",**deletion_payload,}- finally:- await run_blocking(lease.release)+ if activation.get("ok") is not True:+ state = activation.get("state")+ if state == "needs_repair" and not fresh.needs_repair:+ fresh.mark_needs_repair(+ str(activation.get("error") or f"memory_{operation}_failed")+ )+ return {+ "ok": False,+ "operation": operation,+ "state": "needs_repair" if fresh.needs_repair else "degraded",+ "error": activation.get("error", f"memory_{operation}_failed"),+ "result": "deleted_readiness_failed",+ **deletion_payload,+ }+ return {+ "ok": True,+ "operation": operation,+ "state": "running",+ "result": "completed",+ **deletion_payload,+ }def _memory_replacement_lock(self) -> asyncio.Lock:"""Lazily provide the gate for lightweight Controller test doubles."""@@ -1596,6 +2480,108 @@ class Controller:returnmark_service_instance_started()+ @staticmethod+ def _disabled_memory_ownership_exists(memory_dir: Path) -> bool:+ """Detect only released ownership records without loading Memory code."""++ try:+ (memory_dir / ".rt" / "everos.sidecar.json").lstat()+ return True+ except OSError:+ pass+ try:+ return any(+ path.name.startswith("cascade-sync-")+ and path.name.endswith(".json")+ for path in (memory_dir / ".avibe-memory-locks").iterdir()+ )+ except OSError:+ return False++ async def _recheck_disabled_memory_cleanup(self) -> None:+ if not getattr(self, "_memory_disabled_cleanup_unproved", False):+ return+ memory_dir = paths.get_vibe_remote_dir() / "memory"+ ownership_exists = await asyncio.to_thread(+ self._disabled_memory_ownership_exists,+ memory_dir,+ )+ async with self._memory_replacement_lock():+ self._memory_disabled_cleanup_unproved = ownership_exists++ async def _schedule_disabled_memory_cleanup(self) -> None:+ """Reap older owned Memory children only when a record exists."""++ memory_dir = paths.get_vibe_remote_dir() / "memory"+ ownership_exists = await asyncio.to_thread(+ self._disabled_memory_ownership_exists,+ memory_dir,+ )+ async with self._memory_replacement_lock():+ if not isinstance(+ getattr(self, "memory_adapter", None),+ DisabledMemoryAdapter,+ ):+ return+ task = getattr(self, "_memory_disabled_cleanup_task", None)+ if task is not None and not task.done():+ return+ if not ownership_exists:+ return+ self._memory_disabled_cleanup_unproved = True+ self._memory_disabled_cleanup_task = asyncio.create_task(+ self._cleanup_disabled_memory_process(memory_dir),+ name="memory-disabled-everos-cleanup",+ )++ async def _cleanup_disabled_memory_process(self, memory_dir: Path) -> None:+ async with self._memory_operation() as lease:+ if lease is None:+ async with self._memory_replacement_lock():+ self._memory_disabled_cleanup_unproved = True+ return+ ownership_exists = await asyncio.to_thread(+ self._disabled_memory_ownership_exists,+ memory_dir,+ )+ async with self._memory_replacement_lock():+ if not isinstance(+ getattr(self, "memory_adapter", None),+ DisabledMemoryAdapter,+ ) or getattr(self, "memory_runtime", None) is not None:+ return+ if not ownership_exists:+ self._memory_disabled_cleanup_unproved = False+ return+ self._memory_disabled_cleanup_unproved = True++ try:+ from core.memory_legacy_cleanup import ReleasedEverOSOrphanReconciler++ reconciler = ReleasedEverOSOrphanReconciler(+ provider_root=memory_dir / "everos-root",+ effective_home=paths.get_vibe_remote_dir(),+ )+ await reconciler.reconcile_orphans()+ except asyncio.CancelledError:+ async with self._memory_replacement_lock():+ self._memory_disabled_cleanup_unproved = True+ raise+ except Exception:+ async with self._memory_replacement_lock():+ self._memory_disabled_cleanup_unproved = True+ logger.warning(+ "Disabled Memory could not clean up an older owned EverOS process",+ exc_info=True,+ )+ else:+ ownership_exists = await asyncio.to_thread(+ self._disabled_memory_ownership_exists,+ memory_dir,+ )+ async with self._memory_replacement_lock():+ self._memory_disabled_cleanup_unproved = ownership_exists+def _run_im_runtime(self) -> None:try:self.im_client.run()@@ -1707,6 +2693,10 @@ class Controller:# A no-op in any process that does not hold the service lock, so the# embedded and test paths that run a controller are unaffected.self._publish_readiness_unless_im_runtime_failed()+ try:+ await self._schedule_disabled_memory_cleanup()+ except Exception as e:+ logger.error(f"Failed to schedule disabled Memory cleanup: {e}", exc_info=True)try:await self.update_checker.check_and_send_post_update_notification(ready_platform="avibe")@@ -2087,12 +3077,14 @@ class Controller:# ----- Direct Memory entry admission ---------------------------------#- # The policy lives in ``core.memory.admission``. The controller only+ # The policy lives in ``avibe_memory.admission``. The controller only# collects the facts one turn carries and acts on the verdict.def _memory_admission(self) -> CaptureAdmission:# ``getattr`` keeps a controller assembled without a Memory runtime# failing closed inside the admission module rather than raising here.+ from avibe_memory.admission import CaptureAdmission+return CaptureAdmission(principals=getattr(self, "memory_runtime", None),bindings=_SettingsUserBindings(getattr(self, "platform_settings_managers", None)),@@ -2101,210 +3093,54 @@ class Controller:def _memory_turn_facts(self,context: MessageContext,- *,- text: object = None,- session_id: object = None,- attachment_lease: object = None,- attachment_capture_status: object = None,- attachment_config_generation: object = None,- include_workdir: bool = True,) -> InboundTurnFacts:+ from avibe_memory.admission import InboundTurnFacts+payload = context.platform_specific if isinstance(context.platform_specific, dict) else {}metadata = payload.get("message_metadata")metadata = metadata if isinstance(metadata, dict) else {}- memory_user_id = admitted_user_id(metadata)- if memory_user_id is not None:- user_id = memory_user_id- else:- # IM: the platform sender id is what admission and- # ``principal_for_user_key(f"{platform}:{user_id}")`` expect.- # Workbench without a Memory principal in delivery metadata keeps- # the scope fallback (typically ``"workbench"``), which admission- # rejects.- user_id = getattr(context, "user_id", None)- workdir = None- if include_workdir:- try:- workdir = self.get_cwd(context)- except Exception:- workdir = None+ # Workbench routing identity is broader than Memory admission. Hydration+ # puts only a strictly authenticated current author, or its released-row+ # translation, in this host-owned field.+ platform = context.platform or payload.get("platform")+ user_id = (+ payload.get("author_id")+ if platform == "avibe"+ else getattr(context, "user_id", None)+ )return InboundTurnFacts(- platform=context.platform or payload.get("platform"),+ platform=platform,user_id=user_id,message_id=getattr(context, "message_id", None),- session_id=session_id,- workdir=workdir,- text=text,files=getattr(context, "files", None),is_dm=payload.get("is_dm") is True,- is_ordinary_text=context.is_ordinary_text,- is_ordinary_attachment=context.is_ordinary_attachment,- attachment_lease=attachment_lease,- attachment_capture_status=attachment_capture_status,- attachment_config_generation=attachment_config_generation,- memory_enabled=bool(- getattr(getattr(getattr(self, "config", None), "memory", None), "enabled", False)+ is_ordinary_text=getattr(context, "is_original_human_text", None),+ is_ordinary_attachment=getattr(+ context,+ "is_original_human_attachment",+ None,),)def memory_capture_admitted(self, context: MessageContext) -> bool:+ if not bool(getattr(getattr(self.config, "memory", None), "enabled", False)):+ return Falsereturn self._memory_admission().admits(- self._memory_turn_facts(context, include_workdir=False)- )-- def reserve_memory_attachment_capture(- self,- context: MessageContext,- session_id: str,- ) -> object | None:- """Reserve writer capacity and exact-session order before retaining a lease."""-- admission = self._memory_admission()- facts = self._memory_turn_facts(- context,- text="",- session_id=session_id,- include_workdir=False,- )- if not admission.admits_attachment_turn(facts):- return None- runtime = getattr(self, "memory_runtime", None)- module = getattr(runtime, "module", None)- reserve_capacity = getattr(module, "reserve_capture_capacity", None)- reserve = getattr(module, "reserve_capture_admission", None)- principal_id = admission.principal_for(facts)- project_id = admission.project_for(facts)- if (- not callable(reserve)- or not isinstance(principal_id, str)- or not isinstance(project_id, str)- ):- return None- if not callable(reserve_capacity):- try:- token = reserve(- principal_id=principal_id,- project_id=project_id,- session_id=session_id,- )- except Exception:- return None- read_generation = getattr(- runtime,- "attachment_capture_config_generation",- None,- )- try:- observed_generation = (- read_generation() if callable(read_generation) else None- )- except Exception:- observed_generation = None- return _MemoryAttachmentCaptureReservation(- module=module,- token=token,- config_generation=memory_admission.normalize_attachment_config_generation(- observed_generation- ),- )- try:- capacity_token = reserve_capacity()- except Exception:- return None- if isinstance(capacity_token, str):- if capacity_token not in {"full", "unavailable", "disabled"}:- return None- return _MemoryAttachmentCaptureReservation(- module=module,- token=None,- config_generation=None,- capacity_outcome=capacity_token,- )- try:- token = reserve(- principal_id=principal_id,- project_id=project_id,- session_id=session_id,- )- except Exception:- release_capacity = getattr(module, "release_capture_capacity", None)- if callable(release_capacity):- release_capacity(capacity_token)- return None- if token is None:- release_capacity = getattr(module, "release_capture_capacity", None)- if callable(release_capacity):- release_capacity(capacity_token)- return None- read_generation = getattr(- runtime,- "attachment_capture_config_generation",- None,- )- try:- observed_generation = read_generation() if callable(read_generation) else None- except Exception:- observed_generation = None- generation = memory_admission.normalize_attachment_config_generation(- observed_generation- )- return _MemoryAttachmentCaptureReservation(- module=module,- token=token,- config_generation=generation,- capacity_token=capacity_token,- )-- def reserve_memory_capture_capacity(- self,- context: MessageContext,- text: str,- session_id: str,- ) -> object | None:- """Reserve one writer slot before a text capture task is scheduled."""-- admission = self._memory_admission()- facts = self._memory_turn_facts(- context,- text=text,- session_id=session_id,- include_workdir=False,- )- if not admission.admits(facts):- return None- runtime = getattr(self, "memory_runtime", None)- module = getattr(runtime, "module", None)- reserve_capacity = getattr(module, "reserve_capture_capacity", None)- if not callable(reserve_capacity):- return None- try:- capacity_token = reserve_capacity()- except Exception:- return None- if isinstance(capacity_token, str):- if capacity_token not in {"full", "unavailable", "disabled"}:- return None- return _MemoryAttachmentCaptureReservation(- module=module,- token=None,- config_generation=None,- capacity_outcome=capacity_token,- )- return _MemoryAttachmentCaptureReservation(- module=module,- token=None,- config_generation=None,- capacity_token=capacity_token,+ self._memory_turn_facts(context))def memory_principal_for_context(self, context: MessageContext) -> Optional[str]:+ if not bool(getattr(getattr(self.config, "memory", None), "enabled", False)):+ return Nonereturn self._memory_admission().principal_for(- self._memory_turn_facts(context, include_workdir=False)+ self._memory_turn_facts(context))def configure_memory_cli_session(self, context: MessageContext, *, admitted: bool) -> bool:"""Associate an admitted Agent session with its Memory read/write scope."""+ if not bool(getattr(getattr(self.config, "memory", None), "enabled", False)):+ return Falsefrom core.caller_context import caller_context_from_platform_payloadpayload = context.platform_specific if isinstance(context.platform_specific, dict) else {}@@ -2315,14 +3151,35 @@ class Controller:if not isinstance(facts_by_session, dict):facts_by_session = {}self._memory_cli_facts_by_session = facts_by_session+ implementation_error = getattr(self, "_memory_implementation_error", None)+ implementation_sessions = getattr(self, "_memory_implementation_cli_sessions", None)+ if implementation_error is not None:+ if admitted:+ if not isinstance(implementation_sessions, set):+ implementation_sessions = set()+ self._memory_implementation_cli_sessions = implementation_sessions+ implementation_sessions.add(caller.session_id)+ self._memory_scopes_by_session.pop(caller.session_id, None)+ facts_by_session.pop(caller.session_id, None)+ return True+ if isinstance(implementation_sessions, set):+ implementation_sessions.discard(caller.session_id)+ self._memory_scopes_by_session.pop(caller.session_id, None)+ facts_by_session.pop(caller.session_id, None)+ return Falseadmission = self._memory_admission()facts = self._memory_turn_facts(context)principal_id = admission.principal_for(facts) if admitted else Noneproject_id = admission.project_for(facts) if admitted else Noneif principal_id is None or project_id is None:+ if isinstance(implementation_sessions, set):+ implementation_sessions.discard(caller.session_id)self._memory_scopes_by_session.pop(caller.session_id, None)facts_by_session.pop(caller.session_id, None)return False+ implementation_sessions = getattr(self, "_memory_implementation_cli_sessions", None)+ if isinstance(implementation_sessions, set):+ implementation_sessions.discard(caller.session_id)self._memory_scopes_by_session[caller.session_id] = (principal_id, project_id)facts_by_session[caller.session_id] = factsreturn True@@ -2330,10 +3187,19 @@ class Controller:def memory_scope_for_cli_session(self, session_id: str) -> Optional[tuple[str, str]]:"""Return the principal and project owned by an admitted Agent session."""- from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID- from core.memory.store import is_principal_id, is_project_id-+ if not bool(getattr(getattr(self.config, "memory", None), "enabled", False)):+ return Nonesession_key = str(session_id or "").strip()+ implementation_sessions = getattr(self, "_memory_implementation_cli_sessions", None)+ if (+ getattr(self, "_memory_implementation_error", None) is not None+ and isinstance(implementation_sessions, set)+ and session_key in implementation_sessions+ ):+ return ("__memory_implementation_error__", "default")+ from vibe.memory_project_ids import DEFAULT_MEMORY_PROJECT_ID+ from avibe_memory.store import is_principal_id, is_project_id+scope = self._memory_scopes_by_session.get(session_key)if (isinstance(scope, tuple)@@ -2371,6 +3237,9 @@ class Controller:facts = getattr(self, "_memory_cli_facts_by_session", None)if isinstance(facts, dict):facts.pop(session_id, None)+ implementation_sessions = getattr(self, "_memory_implementation_cli_sessions", None)+ if isinstance(implementation_sessions, set):+ implementation_sessions.discard(session_id)def memory_principal_for_cli_session(self, session_id: str) -> Optional[str]:"""Return the principal associated with an admitted Agent session."""@@ -2387,85 +3256,30 @@ class Controller:def default_memory_project_id(self) -> str:"""Return the Memory project used by Settings and default Agent search."""- from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID+ from vibe.memory_project_ids import DEFAULT_MEMORY_PROJECT_IDreturn DEFAULT_MEMORY_PROJECT_ID- async def run_memory_session_lifecycle(- self,- context: MessageContext,- raw_session_id: str,- operation: Callable[[], Awaitable[_MemorySessionLifecycleResult]],- *,- deadline_seconds: float = 5.0,- ) -> _MemorySessionLifecycleResult:- """Run an IM session reset without waiting for volatile capture delivery."""-- if self._memory_scope_for_im_session(context, raw_session_id) is None:- return await operation()-- runtime = getattr(self, "memory_runtime", None)- offer = getattr(runtime, "offer_barrier", None)- if callable(offer):- try:- offer(raw_session_id)- except Exception:- logger.debug("Memory session barrier offer failed", exc_info=True)- del deadline_seconds- return await operation()-- def _memory_scope_for_im_session(- self,- context: MessageContext,- raw_session_id: object,- ) -> Optional[tuple[str, str]]:- """Resolve the same complete, admitted scope used by IM capture."""-- from core.memory.store import is_principal_id, is_project_id-- if not isinstance(raw_session_id, str) or not raw_session_id:- return None- facts = self._memory_turn_facts(context, session_id=raw_session_id)- if not facts.memory_enabled:- return None- admission = self._memory_admission()- try:- if not admission.admits(facts):- return None- principal_id = admission.principal_for(facts)- project_id = admission.project_for(facts)- except Exception:- logger.debug("Memory session lifecycle admission failed", exc_info=True)- return None- if not is_principal_id(principal_id) or not is_project_id(project_id):- return None- return principal_id, project_id-- def _offer_best_effort_archive_memory_barrier(self, raw_session_id: str) -> None:- """Offer a volatile barrier after archive without delaying the archive."""+ def _offer_best_effort_session_archived(self, raw_session_id: str) -> None:+ """Offer a post-commit archive observation without delaying archive."""try:- runtime = getattr(self, "memory_runtime", None)- offer = getattr(runtime, "offer_barrier", None)+ adapter = getattr(self, "memory_adapter", None)+ offer = getattr(adapter, "offer", None)if callable(offer):- offer(raw_session_id)+ offer(SessionArchived(raw_session_id))except Exception:- logger.debug("archive: Memory barrier offer failed", exc_info=True)+ logger.debug("archive: session observation failed", exc_info=True)finally:self._forget_memory_cli_session(raw_session_id)- async def archive_memory_cli_session(+ async def archive_session(self,raw_session_id: str,*,deadline_seconds: float = 5.0,) -> dict[str, Any]:- """Archive one Workbench session without waiting on Memory.-- The controller still owns the terminal session write. Memory barrier- admission is best-effort after that write commits: a failed, busy, or- fenced runtime must not block or roll back archive.- """+ """Archive one Workbench session and offer its post-commit event."""from core.services import sessions as workbench_sessions_servicefrom storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID@@ -2515,12 +3329,12 @@ class Controller:# Offer before run_blocking can re-raise a pending cancellation.try:loop.call_soon_threadsafe(- self._offer_best_effort_archive_memory_barrier,+ self._offer_best_effort_session_archived,raw_session_id,)except RuntimeError:logger.debug(- "archive: Memory flush dropped; event loop closed for %s",+ "archive: session observation dropped; event loop closed for %s",raw_session_id,)self._forget_memory_cli_session(raw_session_id)@@ -2538,294 +3352,6 @@ class Controller:)return await archive_operation()- def capture_user_memory(- self,- context: MessageContext,- text: str,- session_id: str,- *,- attachment_lease: object = None,- attachment_reservation: object = None,- attachment_config_generation: int | None = None,- attachment_text_only: bool = False,- admission_ready: asyncio.Event | None = None,- ) -> Awaitable[None]:- """Submit one eligible attributed human turn after session resolution.-- This is deliberately best effort. It is scheduled by ``MessageHandler``- and never participates in an agent turn's completion path. Bind the- aggregate before task scheduling can yield to a concurrent reset.- """-- capture_reservation = attachment_reservation- if not isinstance(capture_reservation, _MemoryAttachmentCaptureReservation):- prepared = self.reserve_memory_capture_capacity(- context,- text,- session_id,- )- if prepared is not None:- capture_reservation = prepared-- return self._capture_user_memory_bound(- context,- text,- session_id,- attachment_lease=attachment_lease,- attachment_reservation=capture_reservation,- attachment_config_generation=attachment_config_generation,- attachment_text_only=attachment_text_only,- admission_ready=admission_ready,- observed_runtime=getattr(self, "memory_runtime", None),- )-- async def _capture_user_memory_bound(- self,- context: MessageContext,- text: str,- session_id: str,- *,- attachment_lease: object = None,- attachment_reservation: object = None,- attachment_config_generation: int | None = None,- attachment_text_only: bool = False,- admission_ready: asyncio.Event | None = None,- observed_runtime: object,- ) -> None:- reservation = (- attachment_reservation- if isinstance(- attachment_reservation,- _MemoryAttachmentCaptureReservation,- )- else None- )- if reservation is not None:- attachment_config_generation = reservation.config_generation- if reservation.capacity_blocked:- reservation.release()- return- admission = self._memory_admission()- facts = self._memory_turn_facts(- context,- text=text,- session_id=session_id,- attachment_lease=attachment_lease,- attachment_config_generation=attachment_config_generation,- )- try:- if admission.admits_attachment_turn(facts):- if reservation is None:- await self._capture_user_memory_decided(- admission,- self._memory_attachment_unavailable(facts),- attachment_lease=None,- observed_runtime=observed_runtime,- capacity_reservation=(- reservation.capacity_token- if reservation is not None- else None- ),- )- return- principal_id = admission.principal_for(facts)- project_id = admission.project_for(facts)- module = getattr(observed_runtime, "module", None)- acquire_admission = getattr(module, "capture_admission", None)- if (- isinstance(principal_id, str)- and isinstance(project_id, str)- and callable(acquire_admission)- and (reservation is None or reservation.module is module)- ):- async with acquire_admission(- principal_id=principal_id,- project_id=project_id,- session_id=session_id,- reservation=(- reservation.token if reservation is not None else None- ),- ) as held_admission:- if admission_ready is not None:- admission_ready.set()- await self._capture_user_memory_decided(- admission,- (- self._memory_attachment_unavailable(facts)- if attachment_text_only- else facts- ),- attachment_lease=(- None if attachment_text_only else attachment_lease- ),- observed_runtime=observed_runtime,- held_admission=held_admission,- capacity_reservation=reservation.capacity_token,- )- return- if admission_ready is not None:- admission_ready.set()- await self._capture_user_memory_decided(- admission,- facts,- attachment_lease=attachment_lease,- observed_runtime=observed_runtime,- capacity_reservation=(- reservation.capacity_token if reservation is not None else None- ),- )- finally:- if reservation is not None:- reservation.release()- if admission_ready is not None:- admission_ready.set()-- @staticmethod- def _memory_attachment_unavailable(- facts: InboundTurnFacts,- ) -> InboundTurnFacts:- """Finalize an unavailable attachment set while preserving its caption."""-- return replace(- facts,- attachment_lease=None,- attachment_capture_status="unavailable",- attachment_config_generation=None,- )-- async def _capture_user_memory_decided(- self,- admission: CaptureAdmission,- facts: InboundTurnFacts,- *,- attachment_lease: object,- observed_runtime: object,- held_admission: object = None,- capacity_reservation: object = None,- ) -> None:- platform = CaptureAdmission.platform_of(facts)- if admission.admits_attachment_turn(facts):- status = facts.attachment_capture_status- attachment_selection = None- if status not in {"ready", "not_configured", "unavailable"}:- status = "not_configured"- if (- platform != WORKBENCH_PLATFORM- and memory_admission.normalize_attachment_config_generation(- facts.attachment_config_generation- )- is not None- ):- status = "ready"- elif platform == WORKBENCH_PLATFORM:- status = "unavailable"- read_status = getattr(- observed_runtime,- "attachment_capture_status",- None,- )- if callable(read_status):- try:- observed_status = await read_status()- except Exception:- observed_status = "unavailable"- if observed_status in {- "ready",- "not_configured",- "unavailable",- }:- status = observed_status- if status == "ready" and platform != WORKBENCH_PLATFORM:- try:- attachment_selection = await run_blocking(- memory_admission.select_memory_attachments,- facts.attachment_lease,- )- except Exception as error:- logger.warning(- "memory_attachment_selection_failed "- "platform=%s count=%d error_type=%s",- platform,- len(facts.files or ()),- type(error).__name__,- )- status = "unavailable"- facts = replace(- facts,- attachment_capture_status=status,- attachment_selection=attachment_selection,- )- request = admission.decide(facts)- if not isinstance(request, CaptureRequest):- return-- started_at = time.monotonic()- try:- if observed_runtime is None:- return- if getattr(observed_runtime, "retired", False):- return- async with self._memory_replacement_lock():- runtime = getattr(self, "memory_runtime", None)- if (- runtime is not observed_runtime- or runtime is None- or getattr(runtime, "retired", False)- or not runtime.available- ):- return- if request.attachments and platform != WORKBENCH_PLATFORM:- read_generation = getattr(- runtime,- "attachment_capture_config_generation",- None,- )- current_generation = (- read_generation() if callable(read_generation) else None- )- if (- isinstance(current_generation, bool)- or current_generation != request.attachment_config_generation- ):- request = replace(- request,- attachments=(),- attachment_config_generation=None,- )- if not request.text.strip():- return- capture_options = {}- if held_admission is not None:- capture_options["admission"] = held_admission- if capacity_reservation is not None:- capture_options["capacity_reservation"] = capacity_reservation- if request.attachments and attachment_lease is not None:- capture_options["source_lease"] = attachment_lease- result = await runtime.module.capture(- request,- **capture_options,- )- if platform != WORKBENCH_PLATFORM and isinstance(facts.files, (list, tuple)):- total = len(facts.files)- if total:- captured = (- result.captured_attachment_count- if isinstance(result, CaptureAccepted)- else 0- )- log_attachment_capture(platform, total, captured)- logger.info(- "Memory capture platform=%s latency_ms=%d",- platform,- int((time.monotonic() - started_at) * 1000),- )- except Exception:- logger.warning(- "Memory capture failed platform=%s latency_ms=%d",- platform,- int((time.monotonic() - started_at) * 1000),- )-async def _log_memory_processing_event(self,event: str,@@ -3223,6 +3749,7 @@ class Controller:asyncio.set_event_loop(self._loop)memory_runtime = getattr(self, "memory_runtime", None)if memory_runtime is not None:+ self._start_memory_capture_adapter(memory_runtime)self._memory_reconcile_task = self._loop.create_task(memory_runtime.wake(),name="memory-runtime-wake",@@ -3551,21 +4078,6 @@ class Controller:passself._internal_server_task = None- async def _cancel_memory_reconcile_task() -> None:- task = getattr(self, "_memory_reconcile_task", None)- try:- if task is not None:- if not task.done():- task.cancel()- try:- await task- except asyncio.CancelledError:- pass- except Exception as error:- logger.debug("Memory startup reconciliation already failed: %s", error)- finally:- self._memory_reconcile_task = None-# Without this the task is never settled, so the done callback that# records "stopped" never runs and internal-server.json keeps saying# "ready" after the service exits.@@ -3591,33 +4103,21 @@ class Controller:"Runtime work stack",)_stop_loop_coroutine(self.runtime_command_watcher.stop(), "Runtime command watcher")- # Reconciliation can start the sidecar, so settle it before closing the- # runtime or it could race shutdown and leave a process behind.- _stop_loop_coroutine(_cancel_memory_reconcile_task(), "Memory startup reconciliation")- async def _cancel_memory_capture_tasks() -> None:- handler = getattr(self, "message_handler", None)- quiesce = getattr(handler, "quiesce_memory_capture_tasks", None)- if callable(quiesce):- quiesce()- cancel = getattr(handler, "cancel_memory_capture_tasks", None)- if callable(cancel):- await cancel()-- # Close registration and sweep the resulting closed task set in one- # event-loop turn. This does not depend on platform shutdown ordering.- _stop_loop_coroutine(- _cancel_memory_capture_tasks(),- "Memory capture tasks",- timeout=None,- )+ # Reconciliation, capture cancellation, accepted destructive work, and+ # runtime close share one deadline so no stage can block service exit or+ # starve the stages behind it._stop_loop_coroutine(- self._join_memory_destructive_transactions(),- "Memory destructive transactions",- timeout=None,+ self._shutdown_memory_stack(),+ "Memory stack",+ timeout=(+ getattr(+ self,+ "_memory_shutdown_budget_seconds",+ _MEMORY_SHUTDOWN_BUDGET_SECONDS,+ )+ + 1+ ),)- memory_runtime = getattr(self, "memory_runtime", None)- if memory_runtime is not None:- _stop_loop_coroutine(memory_runtime.close(), "Memory runtime")model_hub_turn_gateway = getattr(self, "model_hub_turn_gateway", None)if model_hub_turn_gateway is not None:_stop_loop_coroutine(model_hub_turn_gateway.close(), "Model Hub turn gateway")diff --git a/core/delivery_target.py b/core/delivery_target.pyindex 5f3cab0a4..f0650be1c 100644--- a/core/delivery_target.py+++ b/core/delivery_target.py@@ -2,7 +2,30 @@from __future__ import annotations-from modules.im import MessageContext+from typing import TYPE_CHECKING, Literal, cast++if TYPE_CHECKING:+ from modules.im import MessageContext+++MessageKind = Literal[+ "original",+ "quick_reply",+ "forwarded",+ "edited",+ "system",+ "unknown",+]+MESSAGE_KINDS = frozenset(+ {"original", "quick_reply", "forwarded", "edited", "system", "unknown"}+)+++def normalize_message_kind(value: object) -> MessageKind:+ """Normalize untrusted or legacy message-kind input fail closed."""++ normalized = str(value or "").strip()+ return cast(MessageKind, normalized if normalized in MESSAGE_KINDS else "unknown")def routed_delivery_context(context: MessageContext) -> MessageContext:@@ -14,6 +37,8 @@ def routed_delivery_context(context: MessageContext) -> MessageContext:return contextpayload["is_dm"] = override.get("is_dm", payload.get("is_dm", False))+ from modules.im import MessageContext+return MessageContext(user_id=str(override.get("user_id") or context.user_id),channel_id=str(override.get("channel_id") or context.channel_id),@@ -22,5 +47,7 @@ def routed_delivery_context(context: MessageContext) -> MessageContext:message_id=context.message_id,platform_specific=payload,files=context.files,- is_ordinary_text=context.is_ordinary_text,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,)diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 690ce35a9..a776cea54 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -12,6 +12,7 @@ from core.message_context import (requires_typed_user_session_key,resolve_context_thread_id,)+from core.memory_adapter import SessionResetfrom modules.agents import get_agent_display_namefrom modules.agents.native_sessions.types import NativeResumeSessionfrom modules.agents.base import AgentRequest@@ -138,38 +139,34 @@ class CommandHandlers(BaseHandler):base_id = context.message_id or context.channel_id or context.user_idreturn f"{platform}_{base_id}", None- async def _run_memory_lifecycle_for_new(+ async def _run_session_lifecycle_for_new(self,- context: MessageContext,session_anchor: Optional[str],operation: Callable[[], Awaitable[_NewSessionResult]],) -> _NewSessionResult:- """Run `/new` without waiting for volatile Memory delivery."""-- async def run_memory_lifecycle() -> _NewSessionResult:- lifecycle = getattr(- self.controller,- "run_memory_session_lifecycle",- None,- )- if session_anchor and callable(lifecycle):- return await lifecycle(- context,- session_anchor,- operation,- deadline_seconds=0.0,- )- return await operation()+ """Run `/new` in the core session generation boundary."""turn_manager = getattr(self.controller, "session_turns", None)turn_lifecycle = getattr(turn_manager, "run_session_lifecycle", None)if session_anchor and callable(turn_lifecycle):return await turn_lifecycle(session_anchor,- run_memory_lifecycle,+ operation,deadline_seconds=0.0,)- return await run_memory_lifecycle()+ return await operation()++ def _offer_session_reset(self, session_anchor: str | None) -> None:+ if not session_anchor:+ return+ adapter = getattr(self.controller, "memory_adapter", None)+ offer = getattr(adapter, "offer", None)+ if not callable(offer):+ return+ try:+ offer(SessionReset(session_anchor))+ except Exception:+ logger.debug("Session reset observation failed", exc_info=True)def _compat_session_keys_for_new(self, context: MessageContext, session_key: str) -> list[str]:keys = [session_key]@@ -606,10 +603,14 @@ class CommandHandlers(BaseHandler):)return False, reclaimed- topic_started, reclaimed = await self._run_memory_lifecycle_for_new(- context,+ async def _reset_and_offer() -> _NewSessionResult:+ result = await _reset_session()+ self._offer_session_reset(memory_session_anchor)+ return result++ topic_started, reclaimed = await self._run_session_lifecycle_for_new(memory_session_anchor,- _reset_session,+ _reset_and_offer,)if topic_started:returndiff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 0545b55c6..6ac7fa883 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -4,7 +4,6 @@ import asyncioimport loggingimport inspectfrom datetime import datetime-from collections.abc import Awaitablefrom typing import Any, List, Optional, Tuplefrom core.audio_asr import (@@ -16,6 +15,7 @@ from core.audio_asr import ()from core.backend_failure import emit_backend_failurefrom core.message_output import HARNESS_PROMPT_ECHO_SPEC_KEY+from core.memory_adapter import TurnAccepted, snapshot_memory_filesfrom core.message_context import (SCHEDULED_DISPATCH_METADATA_APPLIED_KEY,resolve_context_thread_id,@@ -36,6 +36,37 @@ logger = logging.getLogger(__name__)SUBAGENT_REACTION_EMOJI = "🤖"+def memory_turn_event(+ context: MessageContext,+ text: str,+ session_id: str,+ lifecycle_snapshot: object,+ attachment_lease: object = None,+) -> TurnAccepted:+ """Close one live message context into immutable host-owned facts."""++ payload = (+ context.platform_specific+ if isinstance(context.platform_specific, dict)+ else {}+ )+ platform = context.platform or payload.get("platform")+ user_id = payload.get("author_id") if platform == "avibe" else context.user_id+ return TurnAccepted(+ platform=platform,+ user_id=user_id,+ message_id=context.message_id,+ session_id=session_id,+ text=text,+ files=snapshot_memory_files(context.files),+ is_dm=payload.get("is_dm") is True,+ is_ordinary_text=context.is_original_human_text,+ is_ordinary_attachment=context.is_original_human_attachment,+ lifecycle_snapshot=lifecycle_snapshot,+ attachment_lease=attachment_lease,+ )++def _target_agent_variant(value: Any, backend: Optional[str], agent_name: Optional[str] = None) -> Optional[str]:if value is None:return None@@ -50,10 +81,6 @@ def _target_agent_variant(value: Any, backend: Optional[str], agent_name: Optionreturn None if variant in sentinel_values else variant-class _MemoryCaptureRegistrationClosed(Exception):- """Internal signal that shutdown closed attachment capture registration."""--class MessageHandler(BaseHandler):"""Handles message routing and Claude communication"""@@ -66,287 +93,11 @@ class MessageHandler(BaseHandler):self.session_manager = controller.session_managerself.session_handler = None # Will be set after creationself.receiver_tasks = controller.receiver_tasks- self._memory_capture_tasks: set[asyncio.Task[Any]] = set()- self._memory_capture_tasks_by_session: dict[str, set[asyncio.Task[Any]]] = {}- self._memory_capture_registration_open = Truedef set_session_handler(self, session_handler):"""Set reference to session handler"""self.session_handler = session_handler- def _track_memory_capture_task(- self,- task: asyncio.Task[Any],- *,- session_id: str | None = None,- lifecycle_admission: Any = None,- attachment_lease: Any = None,- attachment_reservation: Any = None,- capture: object = None,- ) -> None:- """Retain a best-effort capture until asyncio reports its completion."""-- self._memory_capture_tasks.add(task)- if session_id:- self._memory_capture_tasks_by_session.setdefault(session_id, set()).add(- task- )-- def _on_done(done_task: asyncio.Task[Any]) -> None:- try:- done_task.result()- except asyncio.CancelledError:- pass- except Exception:- logger.warning("Memory capture task failed", exc_info=True)- finally:- self._close_memory_capture(capture)- release_attachment = getattr(attachment_lease, "release", None)- if callable(release_attachment):- release_attachment()- release_reservation = getattr(- attachment_reservation,- "release",- None,- )- if callable(release_reservation):- release_reservation()- release = getattr(lifecycle_admission, "release", None)- if callable(release):- release()- self._memory_capture_tasks.discard(done_task)- if session_id:- bucket = self._memory_capture_tasks_by_session.get(session_id)- if bucket is not None:- bucket.discard(done_task)- if not bucket:- self._memory_capture_tasks_by_session.pop(- session_id,- None,- )-- task.add_done_callback(_on_done)-- def abandon_memory_captures_for_session(self, session_id: str) -> None:- """Cancel captures admitted against a session generation that just ended."""-- tasks = tuple(self._memory_capture_tasks_by_session.get(session_id, ()))- for task in tasks:- task.cancel()-- async def _acquire_memory_capture_admission(- self,- session_id: str,- lifecycle_admission: Any = None,- ) -> Any:- """Take the capture-side lifecycle lease. Never call this on dispatch."""-- if lifecycle_admission is not None:- return lifecycle_admission- manager = getattr(self.controller, "session_turns", None)- acquire = getattr(manager, "acquire_lifecycle_admission", None)- if not callable(acquire):- return None- return await acquire(session_id)-- async def _run_memory_capture(- self,- session_id: str,- expected_snapshot: object,- capture: Awaitable[None],- ) -> None:- """Acquire the lifecycle lock and attribute only in the same generation."""-- pending: Awaitable[None] | None = capture- try:- if not self._memory_capture_registration_open:- return- admission = await self._acquire_memory_capture_admission(session_id)- try:- if not self._memory_capture_registration_open:- return- if not self._memory_session_lifecycle_snapshot_matches(- session_id,- expected_snapshot,- ):- logger.info(- "Memory capture abandoned after session lifecycle "- "transition session=%s epoch=%s",- session_id,- getattr(expected_snapshot, "epoch", None),- )- return- await capture- pending = None- finally:- release = getattr(admission, "release", None)- if callable(release):- release()- finally:- if pending is not None:- close = getattr(pending, "close", None)- if callable(close):- close()-- def _schedule_memory_capture_task(- self,- *,- session_id: str,- expected_snapshot: object,- capture: Awaitable[None],- attachment_lease: Any = None,- attachment_reservation: Any = None,- ) -> asyncio.Task[Any] | None:- """Register a capture without awaiting Memory on the turn path."""-- if not self._memory_capture_registration_open:- self._close_memory_capture(capture)- for resource in (attachment_lease, attachment_reservation):- release = getattr(resource, "release", None)- if callable(release):- release()- return None- capture_task = asyncio.create_task(- self._run_memory_capture(session_id, expected_snapshot, capture),- name="memory-capture",- )- self._track_memory_capture_task(- capture_task,- session_id=session_id,- attachment_lease=attachment_lease,- attachment_reservation=attachment_reservation,- capture=capture,- )- return capture_task-- @staticmethod- def _close_memory_capture(capture: object) -> None:- close = getattr(capture, "close", None)- if not callable(close):- return- try:- close()- except Exception:- logger.debug("Memory capture coroutine close failed", exc_info=True)-- def _schedule_text_only_memory_capture(- self,- context: MessageContext,- text: str,- session_id: str,- *,- expected_snapshot: object,- ) -> None:- capture_memory = getattr(self.controller, "capture_user_memory", None)- if not callable(capture_memory) or not text.strip():- return- if not self._memory_capture_registration_open:- return- capacity_reservation = None- reserve_capacity = getattr(- self.controller,- "reserve_memory_capture_capacity",- None,- )- if callable(reserve_capacity):- try:- capacity_reservation = reserve_capacity(context, text, session_id)- except Exception:- logger.warning(- "Memory text capture capacity reservation failed",- exc_info=True,- )- return- if getattr(- capacity_reservation,- "capacity_blocked",- getattr(capacity_reservation, "capacity_full", False),- ):- release = getattr(capacity_reservation, "release", None)- if callable(release):- release()- return- capture: Awaitable[None] | None = None- try:- capture_options = {}- if capacity_reservation is not None:- capture_options["attachment_reservation"] = capacity_reservation- capture = capture_memory(context, text, session_id, **capture_options)- if (- self._schedule_memory_capture_task(- session_id=session_id,- expected_snapshot=expected_snapshot,- capture=capture,- attachment_reservation=capacity_reservation,- )- is None- ):- self._close_memory_capture(capture)- except Exception:- self._close_memory_capture(capture)- release_reservation = getattr(- capacity_reservation,- "release",- None,- )- if callable(release_reservation):- release_reservation()- logger.warning(- "Memory text capture could not be scheduled",- exc_info=True,- )-- def _memory_session_lifecycle_snapshot(self, session_id: str) -> object:- manager = getattr(self.controller, "session_turns", None)- snapshot = getattr(manager, "snapshot_session_lifecycle", None)- if callable(snapshot):- try:- return snapshot(session_id)- except Exception:- logger.warning(- "Memory lifecycle snapshot failed session=%s",- session_id,- exc_info=True,- )- return None- read_epoch = getattr(manager, "session_lifecycle_epoch", None)- if not callable(read_epoch):- return 0- epoch = read_epoch(session_id)- return epoch if isinstance(epoch, int) and not isinstance(epoch, bool) else 0-- def _memory_session_lifecycle_snapshot_matches(- self,- session_id: str,- expected_snapshot: object,- ) -> bool:- manager = getattr(self.controller, "session_turns", None)- matches = getattr(manager, "session_lifecycle_snapshot_matches", None)- if callable(matches):- return bool(matches(session_id, expected_snapshot))- legacy_matches = getattr(manager, "session_lifecycle_epoch_matches", None)- if callable(legacy_matches):- return bool(legacy_matches(session_id, expected_snapshot))- return (- self._memory_session_lifecycle_snapshot(session_id)- == expected_snapshot- )-- async def cancel_memory_capture_tasks(self) -> None:- """Cancel and join captures before the controller event loop closes."""-- while self._memory_capture_tasks:- tasks = tuple(self._memory_capture_tasks)- for task in tasks:- task.cancel()- await asyncio.gather(*tasks, return_exceptions=True)- self._memory_capture_tasks.difference_update(tasks)-- def quiesce_memory_capture_tasks(self) -> None:- """Close the loop-owned registration gate before shutdown sweeps tasks."""-- self._memory_capture_registration_open = False-async def handle_user_message(self,context: MessageContext,@@ -551,14 +302,19 @@ class MessageHandler(BaseHandler):mirror_harness_inbound(context, message)base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)- memory_session_id = base_session_id- memory_session_snapshot: object | None = None+ capture_session_id = base_session_id+ capture_lifecycle_snapshot: object | None = Noneif is_human:- memory_session_snapshot = (- lifecycle_snapshot- if lifecycle_snapshot is not None- else self._memory_session_lifecycle_snapshot(memory_session_id)- )+ capture_lifecycle_snapshot = lifecycle_snapshot+ if capture_lifecycle_snapshot is None:+ snapshot = getattr(+ getattr(self.controller, "session_turns", None),+ "snapshot_session_lifecycle",+ None,+ )+ capture_lifecycle_snapshot = (+ snapshot(capture_session_id) if callable(snapshot) else 0+ )lifecycle_snapshot = Nonepayload = dict(context.platform_specific or {})payload["turn_source"] = source@@ -572,13 +328,15 @@ class MessageHandler(BaseHandler):# turns defer only until the shared materializer has produced a# descriptor-backed lease.if is_human and not context.files:- self._schedule_text_only_memory_capture(- context,- control_message,- memory_session_id,- expected_snapshot=memory_session_snapshot,+ self.controller.memory_adapter.offer(+ memory_turn_event(+ context,+ control_message,+ capture_session_id,+ capture_lifecycle_snapshot,+ ))- memory_session_snapshot = None+ capture_lifecycle_snapshot = Nonereply_anchor_base_session_id = payload.get("reply_anchor_base_session_id")if reply_anchor_base_session_id and reply_anchor_base_session_id != base_session_id:@@ -967,19 +725,14 @@ class MessageHandler(BaseHandler):)except Exception:if is_human:- try:- self._schedule_text_only_memory_capture(+ self.controller.memory_adapter.offer(+ memory_turn_event(context,control_message,- memory_session_id,- expected_snapshot=memory_session_snapshot,- )- except Exception:- logger.warning(- "Memory caption capture could not be scheduled "- "after attachment materialization failed",- exc_info=True,+ capture_session_id,+ capture_lifecycle_snapshot,)+ )raiseattachment_lease = attachment_batch.leaseprocessed_files = list(attachment_batch.attachments) or None@@ -997,129 +750,17 @@ class MessageHandler(BaseHandler):len(processed_files),)- # Memory capture remains best effort and outside the Agent turn, but- # file turns start only after the one shared download has produced an- # immutable lease. Authorization precedes retaining a Memory consumer.if is_human and context.files:- capture_memory = getattr(self.controller, "capture_user_memory", None)- if callable(capture_memory):- memory_attachment_lease = None- memory_capture_reservation = None- attachment_text_only = False- capture_task = None- try:- if not self._memory_capture_registration_open:- raise _MemoryCaptureRegistrationClosed- stale_attachment_capture = (- not self._memory_session_lifecycle_snapshot_matches(- memory_session_id,- memory_session_snapshot,- )- )- reserve_attachment = getattr(- self.controller,- "reserve_memory_attachment_capture",- None,- )- memory_capture_reservation = (- reserve_attachment(context, memory_session_id)- if callable(reserve_attachment)- and not stale_attachment_capture- else None- )- if getattr(- memory_capture_reservation,- "capacity_blocked",- getattr(memory_capture_reservation, "capacity_full", False),- ):- release = getattr(- memory_capture_reservation,- "release",- None,- )- if callable(release):- release()- memory_capture_reservation = None- raise _MemoryCaptureRegistrationClosed- from core.memory import admission as memory_admission-- attachment_config_generation = (- memory_admission.normalize_attachment_config_generation(- getattr(- memory_capture_reservation,- "config_generation",- None,- )- )- )- if (- attachment_config_generation is not None- and attachment_lease is not None- ):- try:- memory_attachment_lease = attachment_lease.retain()- except Exception as error:- attachment_text_only = True- logger.warning(- "Memory attachment lease could not be retained; "- "capturing text only error_type=%s",- type(error).__name__,- )- capture_options = {- "attachment_reservation": memory_capture_reservation,- "attachment_config_generation": attachment_config_generation,- }- if memory_attachment_lease is not None:- capture_options["attachment_lease"] = memory_attachment_lease- if attachment_text_only:- capture_options["attachment_text_only"] = True- capture = capture_memory(- context,- control_message,- memory_session_id,- **capture_options,- )- capture_task = self._schedule_memory_capture_task(- session_id=memory_session_id,- expected_snapshot=memory_session_snapshot,- capture=capture,- attachment_lease=memory_attachment_lease,- attachment_reservation=memory_capture_reservation,- )- if capture_task is None:- self._close_memory_capture(capture)- raise _MemoryCaptureRegistrationClosed- except _MemoryCaptureRegistrationClosed:- if memory_attachment_lease is not None:- memory_attachment_lease.release()- memory_attachment_lease = None- release_reservation = getattr(- memory_capture_reservation,- "release",- None,- )- if callable(release_reservation):- release_reservation()- except BaseException as error:- if capture_task is not None:- capture_task.cancel()- if memory_attachment_lease is not None:- memory_attachment_lease.release()- memory_attachment_lease = None- release_reservation = getattr(- memory_capture_reservation,- "release",- None,- )- if callable(release_reservation):- release_reservation()- if not isinstance(error, Exception):- raise- logger.warning(- "Memory capture task could not be scheduled",- exc_info=True,- )- memory_session_snapshot = None+ self.controller.memory_adapter.offer(+ memory_turn_event(+ context,+ control_message,+ capture_session_id,+ capture_lifecycle_snapshot,+ attachment_lease,+ )+ )+ capture_lifecycle_snapshot = Noneif durable_ingress_enabled and not durable_delivery_owned:assert durable_dispatch_text is not None@@ -1482,6 +1123,12 @@ class MessageHandler(BaseHandler):parent_native_message_id=(str(context.thread_id or "").strip() or None),+ message_kind=(+ "original"+ if context.is_original_human_text is True+ or context.is_original_human_attachment is True+ else context.message_kind+ ),)reserved = manager.reserve_delivery(conn, request)if str(reserved["id"]) != request.delivery_id:diff --git a/core/internal_server.py b/core/internal_server.pyindex 9c3fd85ba..3d960a57d 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -48,16 +48,30 @@ from sqlalchemy.exc import IntegrityErrorfrom config import pathsfrom config.atomic_io import write_atomic-from core.memory.blocking import run_blocking+from core.delivery_target import normalize_message_kind+from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTESfrom core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULEDfrom modules.im.base import MessageContextfrom storage.db import get_cached_sqlite_engine+from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryStoreUnavailableError,+)from vibe.message_identity import HARNESS_TYPE, is_input_turnif TYPE_CHECKING: # pragma: no cover - typing onlyfrom core.controller import Controllerlogger = logging.getLogger(__name__)+++def _memory_implementation_error_code(error: BaseException) -> str:+ return (+ "memory_implementation_incompatible"+ if isinstance(error, MemoryImplementationIncompatibleError)+ else "memory_implementation_unavailable"+ )_SOCKET_MODE = 0o600_SOCKET_UMASK_MODE = 0o700_CHECK_POSIX_SOCKET_MODE = os.name != "nt"@@ -95,7 +109,7 @@ def _processing_record_list_query(raise ValueError("invalid Processing Record limit")project = values.get("project")if project is not None:- from core.memory.project_ids import parse_agent_search_project+ from vibe.memory_project_ids import parse_agent_search_projectproject = parse_agent_search_project(project)return cursor, limit, project@@ -116,7 +130,7 @@ def _processing_record_entry_query(request: Request) -> tuple[str, str | None]:raise ValueError("invalid Processing Record entry id")project = values.get("project")if project is not None:- from core.memory.project_ids import parse_agent_search_project+ from vibe.memory_project_ids import parse_agent_search_projectproject = parse_agent_search_project(project)return memcell_id, project@@ -169,11 +183,9 @@ def create_app(mark_controller_process()if memory_ui_secret is None:- from core.memory.ui_access import process_ui_read_secret+ from vibe.memory_ui_access import process_ui_read_secretmemory_ui_secret = process_ui_read_secret()- from core.memory.runtime import MemoryStoreUnavailableError-app = FastAPI(title="avibe internal dispatch",docs_url=None,@@ -892,6 +904,7 @@ def create_app("metadata": dict(delivery_payload.get("metadata") or {}),"author_id": delivery_payload.get("author_id"),"author_name": delivery_payload.get("author_name"),+ "message_kind": delivery_payload.get("message_kind"),}try:text, context = await _build_dispatch_payload(dispatch_payload)@@ -1009,28 +1022,33 @@ def create_app(except Exception as exc:logger.exception("internal backend auth test failed")return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})- def _memory_runtime():- return getattr(controller, "memory_runtime", None)-@app.post("/internal/reconcile-memory")async def _reconcile_memory() -> Any:"""Hot-apply persisted Memory configuration on the controller loop."""- from core.memory.artifact import MemoryRuntimeActivationError-try:from config.v2_config import V2Configconfig = await asyncio.to_thread(V2Config.load)result = await controller.reconcile_memory(config.memory)return JSONResponse(status_code=200, content=result)- except MemoryRuntimeActivationError:- logger.exception("internal memory runtime activation failed during reconcile")+ except ImportError:return JSONResponse(status_code=503,- content={"ok": False, "error": "memory_runtime_install_failed"},+ content={"ok": False, "error": "memory_implementation_unavailable"},)- except Exception:+ except Exception as exc:+ if type(exc).__name__ == "MemoryRuntimeActivationError":+ logger.exception("internal memory runtime activation failed during reconcile")+ return JSONResponse(+ status_code=503,+ content={"ok": False, "error": "memory_runtime_install_failed"},+ )+ if isinstance(exc, (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError)):+ return JSONResponse(+ status_code=503,+ content={"ok": False, "error": _memory_implementation_error_code(exc)},+ )logger.exception("internal memory reconcile failed")return JSONResponse(status_code=503,@@ -1041,14 +1059,16 @@ def create_app(async def _memory_wake() -> Any:"""Non-destructively wake the existing admitted Memory root."""- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(- status_code=503,- content={"ok": False, "state": "degraded", "error": "memory_runtime_missing"},- )try:- result = await runtime.wake()+ result = await controller.wake_memory()+ except MemoryStoreUnavailableError:+ result = {+ "ok": False,+ "state": "degraded",+ "error": "memory_store_unavailable",+ }+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ result = {"ok": False, "state": "degraded", "error": _memory_implementation_error_code(exc)}except Exception:logger.exception("internal memory wake failed")result = {"ok": False, "state": "degraded", "error": "memory_wake_failed"}@@ -1090,6 +1110,13 @@ def create_app()try:result = await handler(confirm_loss=True)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ result = {+ "ok": False,+ "operation": operation,+ "error": _memory_implementation_error_code(exc),+ "result": "failed",+ }except Exception:logger.exception("internal Memory %s failed", operation)result = {@@ -1162,6 +1189,12 @@ def create_app(status_code=400,content={"ok": False, "operation": "reconfigure", "error": "memory_invalid_input"},)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ result = {+ "ok": False,+ "operation": "reconfigure",+ "error": _memory_implementation_error_code(exc),+ }except Exception:logger.exception("internal Memory reconfigure failed")result = {@@ -1178,12 +1211,14 @@ def create_app(async def _memory_install_runtime() -> Any:"""Install or repair the managed runtime on the controller lifecycle."""- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"ok": False, "reason": "memory_runtime_missing"})try:- result = await runtime.install_artifact()+ result = await controller.install_memory_runtime()return JSONResponse(status_code=200, content=result)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"ok": False, "reason": _memory_implementation_error_code(exc)},+ )except Exception:logger.exception("internal memory runtime install failed")return JSONResponse(status_code=503, content={"ok": False, "reason": "memory_runtime_install_failed"})@@ -1195,30 +1230,47 @@ def create_app(payload = await _safe_json(request)try:from config.v2_config import memory_config_from_payload- from core.memory.runtime import MemoryRuntime+config = memory_config_from_payload(payload.get("memory", payload) if isinstance(payload, dict) else {})- runtime = _memory_runtime()- if runtime is None:+ preflight = getattr(controller, "preflight_memory", None)+ if not callable(preflight):return JSONResponse(status_code=503, content={"ok": False, "error": "memory_runtime_missing"})- return JSONResponse(status_code=200, content=await runtime.preflight(config))+ return JSONResponse(status_code=200, content=await preflight(config))+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"ok": False, "error": _memory_implementation_error_code(exc)},+ )except Exception:logger.exception("internal memory preflight failed")return JSONResponse(status_code=503, content={"ok": False, "error": "memory_processing_failed"})def _memory_cli_scope(request: Request) -> tuple[str, str] | None:- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERsession_id = str(request.headers.get(CALLER_SESSION_HEADER) or "").strip()if not session_id:return Noneresolve = getattr(controller, "memory_scope_for_cli_session", None)scope = resolve(session_id) if callable(resolve) else None- from core.memory.store import is_principal_id, is_project_id+ if not bool(getattr(getattr(getattr(controller, "config", None), "memory", None), "enabled", False)):+ return None+ implementation_sessions = getattr(controller, "_memory_implementation_cli_sessions", None)+ if (+ getattr(controller, "_memory_implementation_error", None) is not None+ and isinstance(implementation_sessions, set)+ and session_id in implementation_sessions+ and isinstance(scope, tuple)+ and len(scope) == 2+ ):+ return scope+ from vibe.memory_contract import is_memory_principal_id+ from vibe.memory_project_ids import is_project_idif (isinstance(scope, tuple)and len(scope) == 2- and is_principal_id(scope[0])+ and is_memory_principal_id(scope[0])and is_project_id(scope[1])):return scope@@ -1240,7 +1292,7 @@ def create_app(status_code=400,content={"ok": False, "error": "memory_invalid_input"},)- archive_session = getattr(controller, "archive_memory_cli_session", None)+ archive_session = getattr(controller, "archive_session", None)if not callable(archive_session):return JSONResponse(status_code=503,@@ -1284,7 +1336,7 @@ def create_app(return {"ok": True, "session": session}def _verified_memory_ui_user_key(request: Request) -> str | None:- from core.memory.http_headers import (+ from vibe.memory_http_headers import (CALLER_SESSION_HEADER,MEMORY_USER_KEY_HEADER,)@@ -1297,7 +1349,7 @@ def create_app(or (user_key.startswith(remote_prefix) and len(user_key) > len(remote_prefix))):return None- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, verify_ui_read_proof+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, verify_ui_read_proofproof = str(request.headers.get(MEMORY_UI_PROOF_HEADER) or "").strip()if memory_ui_secret is None or not verify_ui_read_proof(@@ -1310,65 +1362,40 @@ def create_app(return Nonereturn user_key- def _memory_read_scope(request: Request) -> tuple[str, str] | None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER+ def _memory_read_owner(+ request: Request,+ ) -> tuple[str | None, tuple[str, str] | None] | None:+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADERif str(request.headers.get(MEMORY_USER_KEY_HEADER) or "").strip():user_key = _verified_memory_ui_user_key(request)if user_key is None:return None- runtime = _memory_runtime()- try:- principal_id = runtime.principal_for_user_key(user_key) if runtime is not None else None- resolve_project = getattr(controller, "default_memory_project_id", None)- project_id = resolve_project() if callable(resolve_project) else None- from core.memory.store import is_principal_id, is_project_id-- if is_principal_id(principal_id) and is_project_id(project_id):- return principal_id, project_id- return None- except MemoryStoreUnavailableError:- raise- except Exception as exc:- raise MemoryStoreUnavailableError("Memory store is unavailable") from exc- return _memory_cli_scope(request)-- async def _memory_read_scope_for_project(- scope: tuple[str, str],- project_id: str | None,- runtime: Any,- ) -> tuple[str, str]:- principal_id, default_project_id = scope- if project_id is None or project_id == default_project_id:- return scope- try:- catalog = await run_blocking(runtime.list_memory_projects, principal_id)- except Exception as exc:- raise MemoryStoreUnavailableError("Memory store is unavailable") from exc- if project_id not in catalog:- raise ValueError("unknown Memory project")- return principal_id, project_id+ return user_key, None+ scope = _memory_cli_scope(request)+ return (None, scope) if scope is not None else None@app.get("/internal/memory/status")async def _memory_status() -> Any:- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"error": "memory_runtime_missing"})try:- return await runtime.status_payload()+ return await controller.memory_status_payload()+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(status_code=503, content={"error": _memory_implementation_error_code(exc)})except Exception:logger.warning("internal memory status failed")return JSONResponse(status_code=503, content={"error": "memory_store_unavailable"})@app.get("/internal/memory/processing-record")async def _memory_processing_record(request: Request) -> Any:- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"error": "memory_runtime_missing"})try:- return await runtime.processing_record_payload(+ return await controller.memory_processing_record_payload(verified_user_key=_verified_memory_ui_user_key(request))+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )except Exception:logger.warning("internal memory Processing Record read failed")return JSONResponse(@@ -1378,26 +1405,27 @@ def create_app(@app.get("/internal/memory/failures")async def _memory_failures(request: Request) -> Any:- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"error": "memory_runtime_missing"})try:- return await runtime.failure_log_payload(+ return await controller.memory_failure_log_payload(verified_user_key=_verified_memory_ui_user_key(request))+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(status_code=503, content={"error": _memory_implementation_error_code(exc)})except Exception:logger.warning("internal memory failure log failed")return JSONResponse(status_code=503, content={"error": "memory_store_unavailable"})@app.get("/internal/memory/maintenance")async def _memory_maintenance(request: Request) -> Any:- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"error": "memory_runtime_missing"})try:- return await runtime.maintenance_payload(+ return await controller.memory_maintenance_payload(verified_user_key=_verified_memory_ui_user_key(request))+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )except Exception:logger.warning("internal memory maintenance read failed")return JSONResponse(@@ -1407,21 +1435,27 @@ def create_app(@app.get("/internal/memory/profile")async def _memory_profile(request: Request) -> Any:+ owner = _memory_read_owner(request)+ if owner is None:+ return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})+ verified_user_key, cli_scope = ownertry:- scope = _memory_read_scope(request)+ return await controller.memory_profile_payload(+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )except MemoryStoreUnavailableError:return JSONResponse(status_code=503,content={"status": "failed", "error": "memory_store_unavailable"},)- if scope is None:+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )+ except PermissionError:return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})- principal_id, project_id = scope- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_runtime_missing"})- try:- return await runtime.profile_payload(principal_id, project_id)except Exception:logger.warning("internal memory profile failed")return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_processing_failed"})@@ -1430,38 +1464,25 @@ def create_app(async def _memory_processing_record_entries(request: Request) -> Any:try:cursor, limit, requested_project = _processing_record_list_query(request)- scope = _memory_read_scope(request)+ owner = _memory_read_owner(request)except ValueError:return JSONResponse(status_code=400,content={"status": "failed", "error": "memory_invalid_input"},)- except MemoryStoreUnavailableError:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if scope is None:+ if owner is None:return JSONResponse(status_code=403,content={"status": "failed", "error": "memory_access_denied"},)- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_runtime_missing"},- )+ verified_user_key, cli_scope = ownertry:- scope = await _memory_read_scope_for_project(- scope, requested_project, runtime- )- principal_id, project_id = scope- return await runtime.processing_record_entries_payload(- principal_id,- project_id,- cursor,- limit,+ return await controller.memory_processing_record_entries_payload(+ cursor=cursor,+ limit=limit,+ project_id=requested_project,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,)except ValueError:return JSONResponse(@@ -1473,6 +1494,16 @@ def create_app(status_code=503,content={"status": "failed", "error": "memory_store_unavailable"},)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )+ except PermissionError:+ return JSONResponse(+ status_code=403,+ content={"status": "failed", "error": "memory_access_denied"},+ )except Exception:logger.warning("internal native Processing Record list failed")return JSONResponse(@@ -1484,37 +1515,24 @@ def create_app(async def _memory_processing_record_entry(request: Request) -> Any:try:memcell_id, requested_project = _processing_record_entry_query(request)- scope = _memory_read_scope(request)+ owner = _memory_read_owner(request)except ValueError:return JSONResponse(status_code=400,content={"status": "failed", "error": "memory_invalid_input"},)- except MemoryStoreUnavailableError:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if scope is None:+ if owner is None:return JSONResponse(status_code=403,content={"status": "failed", "error": "memory_access_denied"},)- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_runtime_missing"},- )+ verified_user_key, cli_scope = ownertry:- scope = await _memory_read_scope_for_project(- scope, requested_project, runtime- )- principal_id, project_id = scope- payload = await runtime.processing_record_entry_payload(- principal_id,- project_id,- memcell_id,+ payload = await controller.memory_processing_record_entry_payload(+ memcell_id=memcell_id,+ project_id=requested_project,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,)except ValueError:return JSONResponse(@@ -1526,6 +1544,16 @@ def create_app(status_code=503,content={"status": "failed", "error": "memory_store_unavailable"},)+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )+ except PermissionError:+ return JSONResponse(+ status_code=403,+ content={"status": "failed", "error": "memory_access_denied"},+ )except Exception:logger.warning("internal native Processing Record detail failed")return JSONResponse(@@ -1544,58 +1572,48 @@ def create_app(@app.get("/internal/memory/projects")async def _memory_projects(request: Request) -> Any:+ owner = _memory_read_owner(request)+ if owner is None:+ return JSONResponse(+ status_code=403,+ content={"status": "failed", "error": "memory_access_denied"},+ )+ verified_user_key, cli_scope = ownertry:- scope = _memory_read_scope(request)+ return await controller.memory_projects_payload(+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ logger.warning("internal memory project list failed")+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )except MemoryStoreUnavailableError:+ logger.warning("internal memory project list failed")return JSONResponse(status_code=503,content={"status": "failed", "error": "memory_store_unavailable"},)- if scope is None:+ except PermissionError:return JSONResponse(status_code=403,content={"status": "failed", "error": "memory_access_denied"},)- principal_id, _project_id = scope- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_runtime_missing"},- )- from core.memory.project_ids import DEFAULT_MEMORY_PROJECT_ID, MEMORY_SEARCH_ALL_PROJECTS-- try:- catalogued = await run_blocking(runtime.list_memory_projects, principal_id)except Exception:logger.warning("internal memory project list failed")return JSONResponse(status_code=503,content={"status": "failed", "error": "memory_store_unavailable"},)- named = [item for item in catalogued if item != DEFAULT_MEMORY_PROJECT_ID]- projects = [- {"id": DEFAULT_MEMORY_PROJECT_ID, "kind": "default"},- *[{"id": item, "kind": "named"} for item in named],- {"id": MEMORY_SEARCH_ALL_PROJECTS, "kind": "all"},- ]- return {"status": "ok", "projects": projects}@app.post("/internal/memory/search")async def _memory_search(request: Request) -> Any:- try:- scope = _memory_read_scope(request)- except MemoryStoreUnavailableError:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if scope is None:+ owner = _memory_read_owner(request)+ if owner is None:return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})- principal_id, project_id = scope- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_runtime_missing"})+ verified_user_key, cli_scope = ownerpayload = await _safe_json(request)if (not isinstance(payload, dict)@@ -1604,16 +1622,15 @@ def create_app(or not isinstance(payload.get("query"), str)):return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})- from core.memory.http_headers import CALLER_SESSION_HEADER, MEMORY_USER_KEY_HEADER- from core.memory.project_ids import (- DEFAULT_MEMORY_PROJECT_ID,+ from vibe.memory_http_headers import CALLER_SESSION_HEADER, MEMORY_USER_KEY_HEADER+ from vibe.memory_project_ids import (omitted_project_to_default,parse_agent_search_project,parse_ui_search_project,)- from core.memory.types import RecallPolicy-try:+ from vibe.memory_contract import RecallPolicy+policy = RecallPolicy.from_payload(payload.get("policy"))raw_project = omitted_project_to_default(payload.get("project"))if str(request.headers.get(MEMORY_USER_KEY_HEADER) or "").strip():@@ -1622,54 +1639,45 @@ def create_app(project_id = parse_agent_search_project(raw_project)except (TypeError, ValueError):return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})+ except ImportError:+ return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_implementation_unavailable"})current_session_id = str(request.headers.get(CALLER_SESSION_HEADER) or "").strip() or None- if project_id not in {DEFAULT_MEMORY_PROJECT_ID, "all"}:- try:- catalog = await run_blocking(runtime.list_memory_projects, principal_id)- except Exception:- logger.warning("internal memory project catalog failed")- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if project_id not in catalog:- return JSONResponse(- status_code=400,- content={"status": "failed", "error": "memory_invalid_input"},- )try:- return await runtime.search_payload(- payload["query"],- policy,- principal_id,- project_id,+ return await controller.memory_search_payload(+ query=payload["query"],+ policy=policy,+ project_id=project_id,current_session_id=current_session_id,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ except ValueError:+ return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})+ except MemoryStoreUnavailableError:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": "memory_store_unavailable"},+ )+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},)+ except PermissionError:+ return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})except Exception:logger.warning("internal memory search failed")return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_processing_failed"})@app.post("/internal/memory/list")async def _memory_list(request: Request) -> Any:- try:- scope = _memory_read_scope(request)- except MemoryStoreUnavailableError:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if scope is None:+ owner = _memory_read_owner(request)+ if owner is None:return JSONResponse(status_code=403,content={"status": "failed", "error": "memory_access_denied"},)- principal_id, _default_project_id = scope- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_runtime_missing"},- )+ verified_user_key, cli_scope = ownerpayload = await _safe_json(request)if not isinstance(payload, dict) or set(payload) - {"project",@@ -1682,21 +1690,18 @@ def create_app(status_code=400,content={"status": "failed", "error": "memory_invalid_input"},)- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.project_ids import (- DEFAULT_MEMORY_PROJECT_ID,+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_project_ids import (MEMORY_SEARCH_ALL_PROJECTS,omitted_project_to_default,parse_agent_search_project,parse_ui_search_project,)- from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES- from core.memory.types import MAX_MEMORY_LIST_PAGE_SIZE-+ from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTES+ from vibe.memory_contract import MAX_MEMORY_LIST_PAGE_SIZEis_ui = bool(str(request.headers.get(MEMORY_USER_KEY_HEADER) or "").strip())limit = payload.get("limit", 20)origin = payload.get("origin", "user")- origin_options = {"origin": origin} if "origin" in payload else {}try:raw_project = omitted_project_to_default(payload.get("project"))project_id = (@@ -1722,6 +1727,7 @@ def create_app()if project_id == MEMORY_SEARCH_ALL_PROJECTS:cursor = payload.get("cursor")+ page = Nonetry:cursor_bytes = (len(cursor.encode("utf-8"))@@ -1746,63 +1752,54 @@ def create_app(status_code=400,content={"status": "failed", "error": "memory_invalid_input"},)- try:- result = await runtime.list_all_episodes_payload(- principal_id,- cursor=cursor,- limit=limit,- **origin_options,- )- if result == {- "status": "failed",- "error": "memory_invalid_input",- }:- return JSONResponse(status_code=400, content=result)- return result- except Exception:- logger.warning("internal aggregate memory list failed")- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_processing_failed"},- )-- page = payload.get("page", 1)- if (- "cursor" in payload- or isinstance(page, bool)- or not isinstance(page, int)- or page < 1- ):- return JSONResponse(- status_code=400,- content={"status": "failed", "error": "memory_invalid_input"},- )- if project_id != DEFAULT_MEMORY_PROJECT_ID:- if getattr(runtime, "available", True) is False:- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- try:- catalog = await run_blocking(runtime.list_memory_projects, principal_id)- except Exception:- logger.warning("internal memory project catalog failed")- return JSONResponse(- status_code=503,- content={"status": "failed", "error": "memory_store_unavailable"},- )- if project_id not in catalog:+ else:+ cursor = None+ page = payload.get("page", 1)+ if (+ "cursor" in payload+ or isinstance(page, bool)+ or not isinstance(page, int)+ or page < 1+ ):return JSONResponse(status_code=400,content={"status": "failed", "error": "memory_invalid_input"},)try:- return await runtime.list_episodes_payload(- principal_id,- project_id,+ result = await controller.memory_list_payload(+ project_id=project_id,page=page,- page_size=limit,- **origin_options,+ cursor=cursor,+ limit=limit,+ origin=origin if "origin" in payload else None,+ verified_user_key=verified_user_key,+ cli_scope=cli_scope,+ )+ if result == {+ "status": "failed",+ "error": "memory_invalid_input",+ }:+ return JSONResponse(status_code=400, content=result)+ return result+ except ValueError:+ return JSONResponse(+ status_code=400,+ content={"status": "failed", "error": "memory_invalid_input"},+ )+ except MemoryStoreUnavailableError:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": "memory_store_unavailable"},+ )+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )+ except PermissionError:+ return JSONResponse(+ status_code=403,+ content={"status": "failed", "error": "memory_access_denied"},)except Exception:logger.warning("internal memory list failed")@@ -1817,9 +1814,6 @@ def create_app(if scope is None:return JSONResponse(status_code=403, content={"status": "failed", "error": "memory_access_denied"})principal_id, project_id = scope- runtime = _memory_runtime()- if runtime is None:- return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_runtime_missing"})payload = await _safe_json(request)if (not isinstance(payload, dict)@@ -1829,7 +1823,7 @@ def create_app(or not payload["text"].strip()):return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})- from core.memory.project_ids import omitted_project_to_default, parse_writable_memory_project+ from vibe.memory_project_ids import omitted_project_to_default, parse_writable_memory_projecttry:project_id = parse_writable_memory_project(@@ -1838,14 +1832,21 @@ def create_app(except ValueError:return JSONResponse(status_code=400, content={"status": "failed", "error": "memory_invalid_input"})- from core.memory import CaptureRequest- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERsession_id = str(request.headers.get(CALLER_SESSION_HEADER) or "").strip()text = payload["text"]source_digest = hashlib.sha256(text.encode("utf-8")).hexdigest()try:+ implementation_error = getattr(controller, "_memory_implementation_error", None)+ if isinstance(+ implementation_error,+ (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError),+ ):+ raise implementation_error+ from avibe_memory import CaptureRequest+capture = getattr(controller, "capture_memory", None)if not callable(capture):return JSONResponse(@@ -1865,7 +1866,43 @@ def create_app(occurred_at_ms=int(time.time() * 1000),))+ except (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError) as exc:+ logger.warning("internal memory remember failed")+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": _memory_implementation_error_code(exc)},+ )+ except ImportError:+ implementation_error = getattr(controller, "_memory_implementation_error", None)+ if isinstance(+ implementation_error,+ (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError),+ ):+ return JSONResponse(+ status_code=503,+ content={+ "status": "failed",+ "error": _memory_implementation_error_code(implementation_error),+ },+ )+ logger.warning("internal memory remember implementation unavailable")+ return JSONResponse(+ status_code=503,+ content={"status": "failed", "error": "memory_implementation_unavailable"},+ )except Exception:+ implementation_error = getattr(controller, "_memory_implementation_error", None)+ if isinstance(+ implementation_error,+ (MemoryImplementationUnavailableError, MemoryImplementationIncompatibleError),+ ):+ return JSONResponse(+ status_code=503,+ content={+ "status": "failed",+ "error": _memory_implementation_error_code(implementation_error),+ },+ )logger.warning("internal memory remember failed")return JSONResponse(status_code=503, content={"status": "failed", "error": "memory_store_unavailable"})response: dict[str, Any] = {"status": receipt.status}@@ -2313,7 +2350,7 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Messagecontext = await asyncio.to_thread(_build_session_context,session_id,- user_id=payload.get("user_id"),+ user_id=payload.get("author_id"),channel_id=payload.get("channel_id"),platform=payload.get("platform"),thread_id=payload.get("thread_id"),@@ -2322,6 +2359,8 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Message)if context.platform_specific is None:context.platform_specific = {}+ context.message_kind = normalize_message_kind(payload.get("message_kind"))+ context.is_original_human_text = context.message_kind == "original"context.platform_specific.update({"delivery_id": payload.get("user_message_id"),@@ -2331,6 +2370,7 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Message"message_metadata": payload.get("metadata") or {},"author_id": payload.get("author_id"),"author_name": payload.get("author_name"),+ "message_kind": context.message_kind,})return text, contextdiff --git a/core/memory/admission_metadata.py b/core/memory/admission_metadata.pydeleted file mode 100644index eead6686d..000000000--- a/core/memory/admission_metadata.py+++ /dev/null@@ -1,60 +0,0 @@-"""Durable Memory admission-metadata keys and their read semantics.--Kept as a leaf module so storage and lightweight Memory-runtime checks can-share the vocabulary without importing CaptureAdmission (attachments, IM-leases, aiohttp).-"""--from __future__ import annotations---MEMORY_USER_ID_METADATA = "_memory_user_id"-MEMORY_ORDINARY_TEXT_METADATA = "_memory_ordinary_text"-MEMORY_CLI_ADMITTED_METADATA = "_memory_cli_admitted"---def _admission_metadata(metadata: object) -> dict:- return metadata if isinstance(metadata, dict) else {}---def admitted_user_id(metadata: object) -> str | None:- """Return the Memory principal, or None when the stored value is unusable.-- Only a non-empty string is usable. Surrounding whitespace is stripped;- a blank or non-string value is treated as missing.- """-- memory_user_id = _admission_metadata(metadata).get(MEMORY_USER_ID_METADATA)- if not isinstance(memory_user_id, str) or not memory_user_id.strip():- return None- if memory_user_id != memory_user_id.strip():- return memory_user_id.strip()- return memory_user_id---def is_ordinary_text(metadata: object) -> bool:- """True only when the surface stored a literal JSON/Python ``True``."""-- return _admission_metadata(metadata).get(MEMORY_ORDINARY_TEXT_METADATA) is True---def is_cli_admitted(metadata: object) -> bool:- """True only when the surface stored a literal JSON/Python ``True``."""-- return _admission_metadata(metadata).get(MEMORY_CLI_ADMITTED_METADATA) is True---def merge_identity(metadata: object) -> tuple[str | None, bool, bool]:- """Return the Memory facts that one dispatch context must keep singular.-- ``author_id`` is the web-push ownership identity, not the Memory principal.- Keep the durable Memory identity alongside the two admission flags so a- merged turn can never cross principals.- """-- metadata = _admission_metadata(metadata)- return (- admitted_user_id(metadata),- is_ordinary_text(metadata),- is_cli_admitted(metadata),- )diff --git a/core/memory_adapter.py b/core/memory_adapter.pynew file mode 100644index 000000000..2621ad3d7--- /dev/null+++ b/core/memory_adapter.py@@ -0,0 +1,103 @@+"""Host-owned value boundary for optional Memory capture."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Protocol, TypeAlias+++@dataclass(frozen=True, slots=True)+class MemoryFile:+ """Immutable copy of one platform-neutral attachment descriptor."""++ name: str+ mimetype: str+ url: str | None = None+ content: bytes | None = None+ local_path: str | None = None+ size: int | None = None+++def snapshot_memory_files(files: object) -> tuple[MemoryFile, ...]:+ """Copy already-normalized descriptors without consulting external state."""++ if not isinstance(files, (list, tuple)):+ return ()+ copied: list[MemoryFile] = []+ for item in files:+ name = getattr(item, "name", None)+ mimetype = getattr(item, "mimetype", None)+ if not isinstance(name, str) or not isinstance(mimetype, str):+ continue+ copied.append(+ MemoryFile(+ name=name,+ mimetype=mimetype,+ url=getattr(item, "url", None),+ content=getattr(item, "content", None),+ local_path=getattr(item, "local_path", None),+ size=getattr(item, "size", None),+ )+ )+ return tuple(copied)+++@dataclass(frozen=True, slots=True)+class TurnAccepted:+ """Closed snapshot of one committed human turn."""++ platform: str | None+ user_id: str | None+ message_id: str | None+ session_id: str+ text: str+ files: tuple[MemoryFile, ...]+ is_dm: bool+ is_ordinary_text: bool | None+ is_ordinary_attachment: bool | None+ lifecycle_snapshot: object+ attachment_lease: object | None = None+++@dataclass(frozen=True, slots=True)+class SessionReset:+ """A core session generation was reset successfully."""++ session_id: str+++@dataclass(frozen=True, slots=True)+class SessionArchived:+ """A core session was archived successfully."""++ session_id: str+++@dataclass(frozen=True, slots=True, eq=False)+class DisabledCaptureReceipt:+ """Host-owned skipped result returned without importing Memory types."""++ reason: str = "memory_disabled"+ status: str = "skipped"++ def __eq__(self, other: object) -> bool:+ return (+ getattr(other, "status", None) == self.status+ and getattr(other, "reason", None) == self.reason+ )+++MemoryEvent: TypeAlias = TurnAccepted | SessionReset | SessionArchived+++class MemoryCaptureAdapter(Protocol):+ """Accept a best-effort host event without waiting or raising."""++ def offer(self, event: MemoryEvent, /) -> None: ...+++class DisabledMemoryAdapter:+ """No-op capture target used while Memory is disabled or unavailable."""++ def offer(self, event: MemoryEvent, /) -> None:+ del eventdiff --git a/core/memory_legacy_cleanup.py b/core/memory_legacy_cleanup.pynew file mode 100644index 000000000..522a0725a--- /dev/null+++ b/core/memory_legacy_cleanup.py@@ -0,0 +1,567 @@+"""Retire process ownership records shipped before Memory became optional.++This module deliberately lives in the host package. Disabled Avibe must be able+to stop a released Memory child even when ``avibe-memory`` is not installed.+It only consumes the two ownership formats that Avibe has already shipped; it+never starts Memory work or writes new workflow state.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import math+import os+import signal+import stat+import sys+from collections.abc import Mapping+from contextlib import contextmanager+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Iterator++import psutil++from config import paths++_SIDECAR_RECORD = Path(".rt/everos.sidecar.json")+_SYNC_PREFIX = "cascade-sync-"+_LOCK_PREFIX = "cascade-rebuild-"+_LOCK_DIRECTORY = ".avibe-memory-locks"+_SIDECAR_MAX_BYTES = 4 * 1024+_SYNC_MAX_BYTES = 16 * 1024+_SYNC_ARGV = ("-I", "-m", "everos.entrypoints.cli.main", "cascade", "sync")+_SIDECAR_ENTRYPOINTS = {"avibe_memory.sidecar", "core.memory.sidecar"}+_REBUILD_ENTRYPOINT = "core.memory.rebuild_child"+++@dataclass(frozen=True, slots=True)+class _Identity:+ pid: int+ stamp: float | None+ wall_create_time: float | None+ uid: int | None+ command: tuple[str, ...] | None+ environment: Mapping[str, str] | None+ process_group: int | None+++def _canonical(path: Path | str) -> Path:+ return Path(os.path.abspath(os.fspath(path))).resolve(strict=False)+++def _same_path(value: object, expected: Path) -> bool:+ if not isinstance(value, str) or not value:+ return False+ try:+ observed = _canonical(value)+ configured = _canonical(expected)+ if observed == configured:+ return True+ left = os.stat(observed)+ right = os.stat(configured)+ return (left.st_dev, left.st_ino) == (right.st_dev, right.st_ino)+ except OSError:+ return False+++def _is_stamp(value: object) -> bool:+ return (+ isinstance(value, (int, float))+ and not isinstance(value, bool)+ and math.isfinite(float(value))+ and float(value) > 0+ )+++def _linux_starttime(pid: int) -> float:+ data = Path(f"/proc/{pid}/stat").read_bytes()+ close = data.rfind(b")")+ if close < 0:+ raise ValueError("process start time is unavailable")+ return float(data[close + 1 :].split()[19])+++def _read_field(reader: Any) -> Any:+ try:+ return reader()+ except (AttributeError, OSError, psutil.AccessDenied, PermissionError):+ return None+++def _inspect(pid: int) -> _Identity | None:+ try:+ process = psutil.Process(pid)+ if process.status() == psutil.STATUS_ZOMBIE:+ return None+ wall_create_time = _read_field(process.create_time)+ stamp = (+ _read_field(lambda: _linux_starttime(pid))+ if sys.platform.startswith("linux")+ else wall_create_time+ )+ command = _read_field(process.cmdline)+ environment = _read_field(process.environ)+ uids = _read_field(process.uids)+ group = _read_field(lambda: os.getpgid(pid)) if os.name == "posix" else None+ except (psutil.NoSuchProcess, psutil.ZombieProcess, ProcessLookupError):+ return None+ except psutil.Error:+ return _Identity(pid, None, None, None, None, None, None)+ return _Identity(+ pid=pid,+ stamp=float(stamp) if _is_stamp(stamp) else None,+ wall_create_time=(+ float(wall_create_time) if _is_stamp(wall_create_time) else None+ ),+ uid=None if uids is None else int(uids.real),+ command=None if command is None else tuple(str(value) for value in command),+ environment=environment,+ process_group=group if isinstance(group, int) and group > 1 else None,+ )+++def _assert_safe_chain(path: Path, *, stop: Path) -> None:+ current = path+ while current != stop.parent:+ try:+ info = current.lstat()+ except FileNotFoundError:+ pass+ except OSError as exc:+ raise RuntimeError("legacy Memory path is unavailable") from exc+ else:+ if stat.S_ISLNK(info.st_mode):+ raise RuntimeError("legacy Memory path contains a symlink")+ if current != path and not stat.S_ISDIR(info.st_mode):+ raise RuntimeError("legacy Memory path has an unsafe parent")+ if current == current.parent:+ raise RuntimeError("legacy Memory path escaped its home")+ current = current.parent+++def _read_record(path: Path, *, max_bytes: int) -> Mapping[str, Any] | None:+ try:+ info = path.lstat()+ except FileNotFoundError:+ return None+ except OSError as exc:+ raise RuntimeError("legacy Memory ownership cannot be inspected") from exc+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):+ raise RuntimeError("legacy Memory ownership is unsafe")+ if info.st_size > max_bytes:+ raise RuntimeError("legacy Memory ownership is oversized")+ getuid = getattr(os, "getuid", None)+ if callable(getuid) and info.st_uid != getuid():+ raise RuntimeError("legacy Memory ownership has another owner")+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, ValueError) as exc:+ raise RuntimeError("legacy Memory ownership is invalid") from exc+ if not isinstance(value, dict):+ raise RuntimeError("legacy Memory ownership is invalid")+ return value+++def _retire(path: Path) -> None:+ try:+ info = path.lstat()+ except FileNotFoundError:+ return+ except OSError as exc:+ raise RuntimeError("legacy Memory ownership cannot be inspected") from exc+ if stat.S_ISLNK(info.st_mode) or not stat.S_ISREG(info.st_mode):+ raise RuntimeError("legacy Memory ownership is unsafe")+ try:+ path.unlink()+ except OSError as exc:+ raise RuntimeError("legacy Memory ownership cannot be retired") from exc+++def _root_artifact(provider_root: Path, prefix: str, suffix: str) -> Path:+ root = _canonical(provider_root)+ parent = root.parent.resolve(strict=False)+ identity_root = root+ if sys.platform == "darwin" and not root.exists():+ identity_root = parent / root.name.casefold()+ digest = hashlib.sha256(f"path:{identity_root}".encode()).hexdigest()+ return parent / _LOCK_DIRECTORY / f"{prefix}{digest}{suffix}"+++@contextmanager+def _provider_lock(provider_root: Path) -> Iterator[None]:+ path = _root_artifact(provider_root, _LOCK_PREFIX, ".lock")+ _assert_safe_chain(path.parent, stop=provider_root.parent)+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ _assert_safe_chain(path.parent, stop=provider_root.parent)+ flags = os.O_RDWR | os.O_CREAT+ if hasattr(os, "O_NOFOLLOW"):+ flags |= os.O_NOFOLLOW+ descriptor = os.open(path, flags, 0o600)+ try:+ if os.name == "posix":+ import fcntl++ fcntl.flock(descriptor, fcntl.LOCK_EX)+ else: # pragma: no cover - Windows+ import msvcrt++ msvcrt.locking(descriptor, msvcrt.LK_LOCK, 1)+ yield+ finally:+ try:+ if os.name == "posix":+ import fcntl++ fcntl.flock(descriptor, fcntl.LOCK_UN)+ else: # pragma: no cover - Windows+ import msvcrt++ msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)+ finally:+ os.close(descriptor)+++def _owned_environment(identity: _Identity, *, root: Path, role: str) -> bool:+ environment = identity.environment+ return (+ environment is not None+ and _same_path(environment.get("EVEROS_ROOT"), root)+ and environment.get("AVIBE_MEMORY_CHILD_ROLE") == role+ )+++def _owned_command(+ identity: _Identity,+ *,+ role: str,+ python: Path,+ socket_path: Path,+) -> bool:+ command = identity.command+ if command is None or not command or command[0] != str(python):+ return False+ if role == "sidecar":+ return (+ len(command) == 5+ and command[1] == "-m"+ and command[2] in _SIDECAR_ENTRYPOINTS+ and command[3] == "--uds"+ and _same_path(command[4], socket_path)+ )+ if role == "cascade_rebuild":+ return command[1:] == (+ "-m",+ _REBUILD_ENTRYPOINT,+ "cascade",+ "rebuild",+ "--yes",+ )+ return role == "cascade_sync" and command[1:] == _SYNC_ARGV+++def _validate_identity(+ identity: _Identity,+ record: Mapping[str, Any],+ *,+ provider_root: Path,+ socket_path: Path,+ role: str,+ require_record_stamp: bool,+ require_command: bool = True,+) -> None:+ getuid = getattr(os, "getuid", None)+ own_uid = getuid() if callable(getuid) else None+ if own_uid is not None and identity.uid != own_uid:+ raise RuntimeError("legacy Memory process identity is unavailable")+ python_value = record.get("python")+ if role == "cascade_sync":+ argv = record.get("argv")+ python_value = argv[0] if isinstance(argv, list) and argv else None+ if not isinstance(python_value, str) or not Path(python_value).is_absolute():+ raise RuntimeError("legacy Memory process identity is unavailable")+ command_matches = _owned_command(+ identity,+ role=role,+ python=Path(python_value),+ socket_path=socket_path,+ )+ legacy_sidecar = role == "sidecar" and record.get("role") is None+ environment_matches = _owned_environment(+ identity,+ root=provider_root,+ role=role,+ )+ if (+ (require_command and not command_matches)+ or (not environment_matches and not (legacy_sidecar and command_matches))+ ):+ raise RuntimeError("legacy Memory process identity is unavailable")+ if require_record_stamp:+ expected = record.get("starttime_ticks", record.get("create_time"))+ observed = (+ identity.stamp+ if "starttime_ticks" in record+ else identity.wall_create_time+ )+ if not _is_stamp(expected) or observed != float(expected):+ raise RuntimeError("legacy Memory process identity is unavailable")+++def _group_members(group: int) -> list[_Identity]:+ members: list[_Identity] = []+ for process in psutil.process_iter(["pid"]):+ pid = process.info.get("pid")+ if not isinstance(pid, int) or pid == os.getpid():+ continue+ try:+ if os.name != "posix" or os.getpgid(pid) != group:+ continue+ except (ProcessLookupError, psutil.NoSuchProcess):+ continue+ except (OSError, psutil.Error) as exc:+ raise RuntimeError(+ "legacy Memory process group cannot be verified"+ ) from exc+ identity = _inspect(pid)+ if identity is not None:+ members.append(identity)+ return members+++def _signal_and_wait(identities: list[_Identity], timeout: float) -> None:+ if not identities:+ return+ for signum, budget in (+ (signal.SIGTERM, timeout),+ (getattr(signal, "SIGKILL", signal.SIGTERM), min(timeout, 3.0)),+ ):+ live: list[psutil.Process] = []+ for identity in identities:+ if not _is_stamp(identity.stamp):+ raise RuntimeError("legacy Memory process identity is unavailable")+ current = _inspect(identity.pid)+ if current is None or current.stamp != identity.stamp:+ continue+ try:+ os.kill(identity.pid, signum)+ live.append(psutil.Process(identity.pid))+ except (ProcessLookupError, psutil.NoSuchProcess):+ continue+ if not live:+ return+ _gone, remaining = psutil.wait_procs(live, timeout=budget)+ if not remaining:+ return+ raise RuntimeError("legacy Memory process group did not exit")+++class ReleasedEverOSOrphanReconciler:+ """Consume released EverOS ownership without importing ``avibe_memory``."""++ def __init__(+ self,+ *,+ provider_root: Path | str,+ effective_home: Path | str,+ stop_timeout_seconds: float = 10.0,+ ) -> None:+ logical_home = Path(os.path.abspath(os.path.expanduser(os.fspath(effective_home))))+ physical_home = paths.physical_home(logical_home)+ root = Path(os.path.abspath(os.path.expanduser(os.fspath(provider_root))))+ for home in (logical_home, physical_home):+ if root.is_relative_to(home):+ root = physical_home.joinpath(*root.relative_to(home).parts)+ break+ else:+ raise RuntimeError("legacy Memory provider root escaped its home")+ self._home = physical_home+ self._memory_dir = physical_home / "memory"+ self._provider_root = root+ self._socket_path = self._memory_dir / ".rt" / "everos.sock"+ self._timeout = max(0.001, float(stop_timeout_seconds))++ async def reconcile_orphans(self) -> None:+ await asyncio.to_thread(self._reconcile_orphans)++ def _reconcile_orphans(self) -> None:+ _assert_safe_chain(self._memory_dir, stop=self._home)+ _assert_safe_chain(self._provider_root, stop=self._home)+ with _provider_lock(self._provider_root):+ self._reconcile_sync()+ self._reconcile_sidecar()++ def _reconcile_sync(self) -> None:+ path = _root_artifact(self._provider_root, _SYNC_PREFIX, ".json")+ record = _read_record(path, max_bytes=_SYNC_MAX_BYTES)+ if record is None:+ return+ self._validate_record_paths(record, role="cascade_sync")+ nonce = record.get("nonce")+ argv = record.get("argv")+ if (+ record.get("state") not in {"pending", "finalized"}+ or not isinstance(nonce, str)+ or len(nonce) != 64+ or any(char not in "0123456789abcdef" for char in nonce)+ or not isinstance(argv, list)+ or len(argv) != len(_SYNC_ARGV) + 1+ or tuple(argv[1:]) != _SYNC_ARGV+ ):+ raise RuntimeError("released sync ownership is invalid")+ parent_pid = record.get("parent_pid")+ if (+ not isinstance(parent_pid, int)+ or parent_pid <= 1+ or not _is_stamp(record.get("parent_create_time"))+ ):+ raise RuntimeError("released sync ownership is invalid")+ parent = _inspect(parent_pid)+ if parent is not None:+ parent_status = self._parent_status(parent, record)+ if parent_status == "owned":+ raise RuntimeError("released sync is still owned by a live parent")+ if parent_status == "unknown":+ raise RuntimeError("released sync parent identity is unavailable")++ identities: list[_Identity] = []+ if record["state"] == "finalized":+ pid = record.get("pid")+ group = record.get("process_group")+ if not isinstance(pid, int) or pid <= 1 or not isinstance(group, int) or group <= 1:+ raise RuntimeError("released sync ownership is invalid")+ if hasattr(os, "getpgrp") and group == os.getpgrp():+ raise RuntimeError("released sync process group is unsafe")+ leader = _inspect(pid)+ if leader is not None:+ _validate_identity(+ leader,+ record,+ provider_root=self._provider_root,+ socket_path=self._socket_path,+ role="cascade_sync",+ require_record_stamp=True,+ )+ identities = _group_members(group)+ else:+ for process in psutil.process_iter(["pid"]):+ pid = process.info.get("pid")+ if not isinstance(pid, int):+ continue+ identity = _inspect(pid)+ if identity is None or identity.environment is None:+ continue+ if identity.environment.get("AVIBE_MEMORY_SYNC_NONCE") == nonce:+ identities.append(identity)++ for identity in identities:+ _validate_identity(+ identity,+ record,+ provider_root=self._provider_root,+ socket_path=self._socket_path,+ role="cascade_sync",+ require_record_stamp=(identity.pid == record.get("pid")),+ require_command=(identity.pid == record.get("pid")),+ )+ self._validate_sync_environment(identity, record)+ _signal_and_wait(identities, self._timeout)+ if record["state"] == "finalized" and _group_members(group):+ raise RuntimeError("released sync process group did not exit")+ _retire(path)++ def _reconcile_sidecar(self) -> None:+ path = self._memory_dir / _SIDECAR_RECORD+ record = _read_record(path, max_bytes=_SIDECAR_MAX_BYTES)+ if record is None:+ return+ role = record.get("role") or "sidecar"+ if role not in {"sidecar", "cascade_rebuild"}:+ raise RuntimeError("released sidecar ownership is invalid")+ self._validate_record_paths(record, role=role)+ pid = record.get("pid")+ if not isinstance(pid, int) or pid <= 1:+ raise RuntimeError("released sidecar ownership is invalid")+ leader = _inspect(pid)+ if leader is not None:+ _validate_identity(+ leader,+ record,+ provider_root=self._provider_root,+ socket_path=self._socket_path,+ role=role,+ require_record_stamp=True,+ )+ group = record.get("process_group")+ identities = [leader] if leader is not None else []+ if isinstance(group, int) and group > 1:+ if hasattr(os, "getpgrp") and group == os.getpgrp():+ raise RuntimeError("released sidecar process group is unsafe")+ identities = _group_members(group)+ for identity in identities:+ _validate_identity(+ identity,+ record,+ provider_root=self._provider_root,+ socket_path=self._socket_path,+ role=role,+ require_record_stamp=(identity.pid == pid),+ require_command=(identity.pid == pid),+ )+ _signal_and_wait(identities, self._timeout)+ if isinstance(group, int) and group > 1 and _group_members(group):+ raise RuntimeError("released sidecar process group did not exit")+ _retire(path)++ def _validate_record_paths(self, record: Mapping[str, Any], *, role: str) -> None:+ record_role = record.get("role") or "sidecar"+ if (+ record_role != role+ or not _same_path(record.get("provider_root"), self._provider_root)+ or not _same_path(record.get("socket_path"), self._socket_path)+ ):+ raise RuntimeError("legacy Memory ownership is for another installation")++ @staticmethod+ def _parent_status(+ parent: _Identity,+ record: Mapping[str, Any],+ ) -> str:+ expected_uid = record.get("parent_uid")+ if expected_uid is not None:+ if parent.uid is None:+ return "unknown"+ if parent.uid != expected_uid:+ return "foreign"+ if "parent_starttime_ticks" in record:+ if parent.stamp is None:+ return "unknown"+ return (+ "owned"+ if parent.stamp == float(record["parent_starttime_ticks"])+ else "foreign"+ )+ value = record.get("parent_create_time")+ if not _is_stamp(value) or parent.wall_create_time is None:+ return "unknown"+ return "owned" if parent.wall_create_time == float(value) else "foreign"++ def _validate_sync_environment(+ self,+ identity: _Identity,+ record: Mapping[str, Any],+ ) -> None:+ environment = identity.environment+ expected_uid = record.get("parent_uid")+ if environment is None or (+ environment.get("AVIBE_MEMORY_SYNC_NONCE") != record["nonce"]+ or environment.get("AVIBE_MEMORY_SYNC_PARENT_PID")+ != str(record["parent_pid"])+ or environment.get("AVIBE_MEMORY_SYNC_PARENT_CREATE_TIME")+ != float(record["parent_create_time"]).hex()+ or environment.get("AVIBE_MEMORY_SYNC_PARENT_UID")+ != ("" if expected_uid is None else str(expected_uid))+ ):+ raise RuntimeError("released sync identity is unavailable")diff --git a/core/memory_loader.py b/core/memory_loader.pynew file mode 100644index 000000000..6b927a714--- /dev/null+++ b/core/memory_loader.py@@ -0,0 +1,93 @@+"""Fixed, fail-closed loader for the optional in-process Memory runtime."""++from __future__ import annotations++import importlib+from collections.abc import Callable+from typing import Any++from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryRuntimeBusyError,+)+++MEMORY_RUNTIME_ENTRYPOINT = "avibe_memory.runtime"+# Host-owned transport bound used by the list route. Keeping this here lets+# disabled/failing package paths validate cursors without importing the optional+# implementation module.+MEMORY_LIST_CURSOR_MAX_BYTES = 8192+++def _resolve_memory_runtime_factory() -> Callable[..., Any]:+ """Import the fixed entrypoint and return its runtime factory."""++ try:+ implementation = importlib.import_module(MEMORY_RUNTIME_ENTRYPOINT)+ except Exception as exc:+ raise MemoryImplementationUnavailableError(+ "Memory implementation is unavailable"+ ) from exc+ try:+ factory = getattr(implementation, "create_memory_runtime", None)+ except Exception as exc:+ raise MemoryImplementationUnavailableError(+ "Memory implementation is unavailable"+ ) from exc+ if not callable(factory):+ raise MemoryImplementationUnavailableError(+ "Memory implementation constructor is unavailable"+ )+ return factory+++def probe_memory_runtime_entrypoint() -> None:+ """Validate the runtime entrypoint contract without constructing it."""++ _resolve_memory_runtime_factory()+++def load_memory_runtime(+ config: Any,+ *,+ allow_disabled: bool = False,+ **runtime_kwargs: Any,+) -> Any:+ """Load and construct the fixed Memory runtime for an enabled snapshot.++ This module intentionally imports no implementation module at import time.+ The entrypoint and constructor are deliberately fixed. Publishable companion+ packages carry exact reciprocal version pins, while this boundary validates the+ factory and constructed runtime surface so a missing or broken implementation+ cannot affect core startup.+ """++ if not bool(getattr(config, "enabled", False)) and not allow_disabled:+ return None+ factory = _resolve_memory_runtime_factory()+ try:+ runtime = factory(config, **runtime_kwargs)+ except MemoryRuntimeBusyError:+ raise+ except Exception as exc:+ raise MemoryImplementationUnavailableError(+ "Memory implementation could not be constructed"+ ) from exc+ if runtime is None:+ raise MemoryImplementationUnavailableError(+ "Memory implementation returned no runtime"+ )+ try:+ module = getattr(runtime, "module", None)+ close = getattr(runtime, "close", None)+ has_available = hasattr(runtime, "available")+ except Exception as exc:+ raise MemoryImplementationIncompatibleError(+ "Memory implementation runtime contract is incompatible"+ ) from exc+ if module is None or not callable(close) or not has_available:+ raise MemoryImplementationIncompatibleError(+ "Memory implementation runtime contract is incompatible"+ )+ return runtimediff --git a/core/session_turns.py b/core/session_turns.pyindex 86663f68b..4f4fb6d9b 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -30,6 +30,7 @@ from sqlalchemy.engine import Connection, Enginefrom sqlalchemy.exc import IntegrityErrorfrom core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USER_KEYS_METADATA+from core.delivery_target import normalize_message_kindfrom core.message_context import (SCHEDULED_DISPATCH_METADATA_APPLIED_KEY,resolve_turn_sink_key,@@ -79,11 +80,6 @@ from storage.models import ()from storage.workbench_sessions_service import derive_session_harness_activitiesfrom core.message_output import terminal_turn_output-from core.memory.admission_metadata import (- is_cli_admitted as memory_cli_admitted,- is_ordinary_text as memory_ordinary_text,- merge_identity as memory_admission_merge_identity,-)from core.runtime_activation import (RuntimeActivationIdentity,RuntimeActivationRegistry,@@ -392,19 +388,12 @@ def _scheduled_merge_key(row: dict[str, Any]) -> Optional[tuple[str, ...]]:)-def _memory_admission_merge_identity(row: dict[str, Any]) -> tuple[str | None, bool, bool]:- """Opaque Memory identity for one delivery row's merge batch."""-- return memory_admission_merge_identity(row.get("metadata"))--def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:"""Return the one compatible leading segment a Turn may claim."""if not rows:return []message_identity = delivery_store.message_merge_identity(rows[0])- memory_admission_identity = _memory_admission_merge_identity(rows[0])scheduled_key = _scheduled_merge_key(rows[0])if _scheduled_provenance(rows[0]) is not None and scheduled_key is None:return [rows[0]]@@ -416,8 +405,6 @@ def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]current = _parse_queue_timestamp(row.get("submitted_at"))if (delivery_store.message_merge_identity(row) != message_identity- or _memory_admission_merge_identity(row)- != memory_admission_identityor _scheduled_merge_key(row) != scheduled_keyor previous is Noneor current is None@@ -436,8 +423,6 @@ def _collect_delivery_segment(rows: list[dict[str, Any]]) -> list[dict[str, Any]breakif delivery_store.message_merge_identity(row) != message_identity:break- if _memory_admission_merge_identity(row) != memory_admission_identity:- breaknative_message_id = str(row.get("native_message_id") or "").strip()if native_message_id:if not segment:@@ -547,6 +532,7 @@ class DeliveryRequest:admission_context: dict[str, Any] | None = Nonenative_message_id: str | None = Noneparent_native_message_id: str | None = None+ message_kind: str = "unknown"# A caller that will immediately promote the durable FIFO head can request# P3 admission without the usual idle-session auto-start. This keeps the# admission and promotion decision on one post-admission queue snapshot.@@ -739,8 +725,8 @@ class SessionTurnManager:raise RuntimeError("session lifecycle ownership changed")state.epoch += 1if abandon_captures:- handler = getattr(self.controller, "message_handler", None)- abandon = getattr(handler, "abandon_memory_captures_for_session", None)+ adapter = getattr(self.controller, "memory_adapter", None)+ abandon = getattr(adapter, "abandon_memory_captures_for_session", None)if callable(abandon):abandon(raw_session_id)@@ -1812,6 +1798,7 @@ class SessionTurnManager:author_name=request.author_name,native_message_id=request.native_message_id,parent_native_message_id=request.parent_native_message_id,+ message_kind=request.message_kind,)def _request_from_delivery(@@ -1842,6 +1829,7 @@ class SessionTurnManager:metadata=dict(payload.get("metadata") or {}),native_message_id=payload.get("native_message_id"),parent_native_message_id=payload.get("parent_native_message_id"),+ message_kind=str(payload.get("message_kind") or "unknown"),)def _committed_delivery_result(@@ -2333,15 +2321,41 @@ class SessionTurnManager:if context.platform != "avibe" and native_message_idelse str(delivery["id"]))- # Routing identity only. Memory's principal already travels in- # delivery ``message_metadata`` via the Memory admission vocabulary.- if payload.get("author_id"):- context.user_id = str(payload["author_id"])if context.platform_specific is None:context.platform_specific = {}metadata = payload.get("metadata") or {}- context.is_ordinary_text = memory_ordinary_text(metadata)- if memory_cli_admitted(metadata):+ raw_snapshot = delivery.get("snapshot_json")+ try:+ snapshot = json.loads(raw_snapshot) if isinstance(raw_snapshot, str) else {}+ except (TypeError, ValueError):+ snapshot = {}+ legacy_workbench = context.platform == "avibe" and (+ not isinstance(snapshot, dict) or "message_kind" not in snapshot+ )+ author_id = payload.get("author_id")+ if legacy_workbench:+ author_id = delivery_store.legacy_admitted_user_id(metadata)+ if author_id:+ context.user_id = str(author_id)+ context.message_kind = normalize_message_kind(payload.get("message_kind"))+ context.is_original_human_text = context.message_kind == "original"+ memory_enabled = bool(+ getattr(+ getattr(getattr(self.controller, "config", None), "memory", None),+ "enabled",+ False,+ )+ )+ memory_cli_admitted = bool(+ context.platform == "avibe"+ and memory_enabled+ and author_id+ and (+ not legacy_workbench+ or delivery_store.legacy_is_cli_admitted(metadata)+ )+ )+ if memory_cli_admitted:context.platform_specific["memory_cli_admitted"] = Trueelse:context.platform_specific.pop("memory_cli_admitted", None)@@ -2352,9 +2366,10 @@ class SessionTurnManager:"display_text": payload.get("text") or "","message_content": dict(payload.get("content") or {}),"message_metadata": dict(metadata),- "author_id": payload.get("author_id"),+ "author_id": author_id,"author_name": payload.get("author_name"),"native_message_id": payload.get("native_message_id"),+ "message_kind": context.message_kind,"delivery_admission_context": (delivery_store.delivery_admission_context(delivery)),@@ -2373,6 +2388,9 @@ class SessionTurnManager:attachments=attachments,)context.files = file_attachments_from_specs(specs)+ context.is_original_human_attachment = bool(+ context.message_kind == "original" and context.files+ )return payload@staticmethod@@ -7172,6 +7190,15 @@ class SessionTurnManager:or "").strip() or None,native_message_id=native_message_id,+ message_kind=str(+ spec.get("message_kind")+ or (+ "original"+ if getattr(context, "is_original_human_text", None) is True+ or getattr(context, "is_original_human_attachment", None) is True+ else getattr(context, "message_kind", "unknown")+ )+ ),)result = await self.deliver(request, context=context)enqueued_states = {diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex 0d681d2b6..e7edb2d39 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -85,6 +85,39 @@ diagnostics. It contains no Memory payload and is not a delivery queue orrecovery state machine. The later sections define the product behavior at theseseams.+## Optional package and upgrades++The implementation is the optional `avibe-memory` distribution. Avibe loads it+in-process only when Memory is required; a missing, incompatible, or failed+package degrades Memory without making Avibe or its Agent unavailable.++Forward upgrades preserve the Memory package when Memory is enabled or the+package is already present. The immutable upgrader in a bundled-Memory release+can only install the new core on its first split-package upgrade. After that+core starts, the existing background dependency reconciler sees the persisted+enabled state after the host is ready, installs the exact same-version companion+under the shared upgrade lock, and schedules one ordinary service+restart. Automatic attempts are persisted per core version and stop after three+failures or non-converging restarts. Disabled, source, editable, and already-ready+installs do not trigger that convergence. A disabled published install may expose+an explicit companion-package bootstrap so the user can install the optional+package before enabling Memory; it never runs automatically.++Package resolution, installation, upgrade, or restart failures leave core+Avibe running and are reported as structured terminal results; a later startup+may retry within that version's budget, while an explicit attempt remains+available after exhaustion. If package installation succeeds but the service+restart cannot be scheduled, the same ledger keeps the dependency repairable and+the next explicit Repair retries only activation. Other startup dependencies+continue reconciling in the surviving UI process. Avibe performs no automatic package rollback+and keeps no rollback plan, lifecycle reservation, quarantine, Gate 5 lifecycle+verifier, or general recovery bootstrap.++Published Memory Runtime artifacts retain their manifest, hash, fetch, verify,+and backup availability safeguards. Those checks protect immutable release+assets and manual recovery inputs; they do not compensate for or reverse an+installed-package transition.+## User and Agent memory ownershipAutomatic capture of a user's messages continues to target that user's Memory@@ -106,10 +139,8 @@ Existing Memory data is not moved. Agent-recorded facts written before thissplit remain under the user owner and are still searchable there. A newerinstallation preserves the released four-field provider-session shape, butdelivery remains process-local; pending Agent-owner work may be lost across restart,-rollback, or runtime replacement and is never replayed from an older queue.-On rollback, already-delivered Agent-owner memories remain stored but are hidden-from an older reader until Avibe is upgraded again. Already submitted provider-outcomes are never replayed by this path.+or runtime replacement and is never replayed from an older queue. Already+submitted provider outcomes are never replayed by this path.## IM attachment capture@@ -269,7 +300,7 @@ capture data.Lifecycle offers and barriers are non-blocking. `/new`, archive, runtimereplacement, and shutdown never wait for capture delivery. Work still preparing-or belonging to a stale authority generation may be missed or invalidated.+after its runtime authority is revoked may be missed or invalidated.Shutdown and replacement intentionally drop volatile work.The writer gives add and flush operations at most three attempts, and retriesdiff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.mdindex a15ff81c1..b1c8e3c4e 100644--- a/docs/MEMORY_ZH.md+++ b/docs/MEMORY_ZH.md@@ -149,7 +149,7 @@ Call Log,记录可以不完整或丢失。包含 `memory.diagnostics.log_provi提供方 I/O 的情况下丢弃。生命周期 offer 和 barrier 都不会阻塞。`/new`、归档、运行时替换和关机不会等待捕获-投递;仍在准备中或属于旧 authority generation 的捕获可能丢失或失效。替换和关机+投递;运行时 authority 被撤销后仍在准备的捕获可能丢失或失效。替换和关机会主动丢弃进程内易失工作。add/flush 最多尝试三次,只有明确证明在提供方执行前失败时才重试。可能已经提交的diff --git a/docs/plans/memory-plugin-isolation-refactor.md b/docs/plans/memory-plugin-isolation-refactor.mdnew file mode 100644index 000000000..789727f97--- /dev/null+++ b/docs/plans/memory-plugin-isolation-refactor.md@@ -0,0 +1,544 @@+# Memory Optional Package Isolation Refactor++> Status: complete (2026-08-29)+>+> Completion baseline: `origin/dev` at `8033662fa` (post-#1774)+>+> `docs/MEMORY.md` is the current product contract. This plan records the+> completed isolation waves and their retained boundaries.++## Decision++Memory runtime implementation now lives in an independently published,+optional Python package loaded in the Avibe process only when Memory is enabled.+EverOS remains the one Memory child process. This refactor does not add another+sidecar, UDS protocol, process supervisor, generic plugin host, or dynamic plugin+registration system.++Avibe keeps a small host integration surface:++- a main-path `MemoryCaptureAdapter` with one `offer` method;+- `DisabledMemoryAdapter` for disabled, missing, or failed optional packages;+- the released typed Memory configuration and destructive-write safety fences;+- the existing named internal Memory routes, CLI command set, Settings UI, and+ prompt behavior; and+- lightweight host-owned request/authentication contracts that do not import+ Memory runtime implementation.++This plan defines the companion-package boundary behaviorally: the optional+implementation package may be deleted or never installed without making Avibe's+main product unavailable. It does not mean removing every Memory label or+explicit user surface from the host.++## Why There Is No Second Memory Process++EverOS already runs as an isolated child under `EverOSSupervisor` and owns the+provider-facing work. Adding++```text+Avibe -> avibe-memory process -> EverOS process+```++would duplicate process lifecycle, health, IPC, restart, release, and shutdown+logic. It would also require a new request protocol for operations that already+use Avibe's internal HTTP routes.++The default target is therefore:++```text+Avibe process+ |+ +-- DisabledMemoryAdapter package absent or disabled+ |+ `-- Enabled adapter from optional package package present and enabled+ |+ `-- existing EverOS child process+```++The optional package is trusted first-party Python code, not hostile code. The+adapter contract and tests protect main-path behavior from expected failure,+latency, queue saturation, and provider faults. They do not claim to sandbox an+arbitrary infinite CPU loop inside Python. A second process is considered only+after a reproducible fault shows that the in-process adapter cannot meet the+bounded contract.++## Completed Scope++The waves closed the following independence gaps without changing Memory product+behavior:++1. Controller no longer imports Memory implementation at module import time.+2. Disabled startup does not construct `MemoryRuntime`.+3. Disabled startup does not open `memory.sqlite` or create attachment, state,+ and lock directories.+4. The optional adapter owns Memory admission, capture tasks, capacity, and+ attachment scheduling.+5. New Workbench and delivery persistence does not write `_memory_*` metadata or+ depend on it for queue segmentation.+6. Memory task and destructive-operation shutdown paths are bounded.+7. Generic helpers and host contracts needed by archive, UI auth, config, and+ internal clients live outside the optional implementation.+8. Install and upgrade paths resolve `avibe-memory` as an optional independent+ distribution.++The refactor targets these gaps. It does not reimplement working Memory product+behavior.++## Behavioral Contract++### Disabled or absent++**Disabled = inert + truthful:** disabled paths never construct a Memory runtime,+status reflects retained fenced ownership, and every internal Memory endpoint+fails closed with its stable error shape for unknown lifecycle failures.++- A fresh home with Memory disabled imports no optional Memory implementation.+- It creates no Memory database, attachment directory, provider root, artifact+ state, or Memory lock.+- It starts no Memory task and no EverOS process.+- An enabled config with a missing or incompatible package degrades only Memory;+ chat, Agent dispatch, `/new`, archive, startup, and shutdown remain available.+- Explicit Memory routes return `memory_implementation_unavailable` with a stable+ user-facing explanation.++An existing disabled installation may need to reap an EverOS process left by an+older release. That cleanup must use existing generic runtime ownership metadata,+run asynchronously after core readiness, create no Memory state, and never block+startup. Fresh disabled installations still have zero Memory side effects.++### Enabled++- Capture remains best effort and outside Agent completion.+- Queue saturation drops capture without backpressure.+- `/new` and archive remain successful when Memory is slow or failed.+- Attachment pin/copy, admission, profile/search/list/remember, prompt routing,+ repair, deletion, and Processing Record behavior remain unchanged.+- Existing Memory config and provider data remain readable without a data move.++### Shutdown and replacement++- Capture registration closes immediately.+- Capture cancellation and destructive-operation settlement each have a finite+ total deadline.+- Expired volatile work is dropped, consistent with `docs/MEMORY.md`.+- The existing EverOS stop-proof and process-group reap behavior remains inside+ the optional implementation.+- Runtime replacement never waits for capture delivery and never runs two+ Memory runtimes against the same provider root.++## Main-Path Interface++The only interface used by message and session flows is:++```python+class MemoryCaptureAdapter(Protocol):+ def offer(self, event: MemoryEvent) -> None: ...+```++`offer` has a closed contract:++- it performs only bounded in-memory validation, lease retention, capacity+ reservation, and `put_nowait` or task registration;+- it performs no filesystem, provider, subprocess, or network I/O on the caller+ stack;+- it never waits and never raises;+- on rejection or queue saturation it releases every retained resource; and+- callers ignore its outcome.++`DisabledMemoryAdapter.offer` is an unconditional no-op.++Lifecycle cleanup is a composition concern owned by Controller startup/shutdown,+not part of this interface. Message handlers cannot close, restart, inspect, or+reconfigure Memory through the capture seam.++Explicit Memory operations do not use a generic `request(operation, payload)`+method. They keep the existing named internal routes and closed CLI command+surface.++## Events++There are three main-path events:++- `TurnAccepted`, offered after a human turn has a stable session/generation and+ admitted local attachments;+- `SessionReset`, offered after `/new` commits; and+- `SessionArchived`, offered after archive commits.++`vibe memory remember` is an explicit named operation and never becomes a fourth+event. Runtime replacement is internal optional-package lifecycle and does not+become a host event.++Events carry trusted host facts, not Memory decisions:++- authenticated author id and surface;+- canonical session id and generation;+- platform, conversation kind, and stable native identifiers;+- original/edit/forward/quote/system/unknown message kind;+- text, attachments, and the existing generic inbound attachment lease; and+- workdir only where the current admission contract already permits it.++Events do not contain Memory principal/project ids, `memory_enabled`, admission+results, provider state, `_memory_*` metadata, or Memory-specific reservation+objects. The enabled adapter derives all Memory facts and owns capture tasks.++## Message Facts and Delivery Merge++The current `is_ordinary_*` classifiers describe native message shape, not+provider behavior. They remain with the IM adapters but are renamed into core+vocabulary, for example `is_original_human_text` and+`is_original_human_attachment`. Unknown shapes remain fail closed.++New Workbench delivery snapshots use core-owned identity:++- `author_id` remains the authenticated local or remote subject and replaces+ `_memory_user_id` as the trusted author input;+- a first-class `message_kind` distinguishes original, quick reply, forwarded,+ edited, system, and unknown input; and+- `message_merge_identity` includes `message_kind` in addition to its existing+ `author_id`, author, source, type, scope, and native-message fields.++Web-push ownership is not automatically a Memory principal: Workbench+`author_id` is Memory-trusted only after strict direct-loopback or authenticated+remote HTTP admission. A third identity/authority P1 on this PR triggers the+circuit breaker and spec review before any further implementation.++This preserves the current safety properties:++- deliveries from different authenticated authors never merge;+- a quick reply never merges with an original human message;+- forwarded/edited/system/unknown input never widens original-human admission;+ and+- one merged Turn has one stable author and message kind.++`memory_cli_admitted` is derived at dispatch from authenticated author and+current Memory configuration; it is not persisted. The Memory adapter derives+its owner from `author_id` for Workbench and the authenticated sender for IM.++Legacy queued rows retain a compatibility reader for `_memory_*`. New writes+stop emitting the fields. The compatibility reader translates old identity into+the core merge key until all released queue rows are naturally retired; there is+no bulk database rewrite and no unsafe mixed merge.++## Attachment Contract++This isolation refactor preserves the current attachment contract:++1. Avibe materializes the file once for Agent delivery and owns the generic+ `InboundAttachmentLease`.+2. The enabled Memory adapter retains that lease inside `offer` before returning.+3. The adapter owns Memory capacity reservation, config-generation validation,+ pin/copy into private Memory storage, and final release.+4. Pin failure keeps the released text-only fallback semantics.+5. The disabled adapter never retains the lease.++`MessageHandler` no longer imports Memory admission or manipulates Memory+reservations, but it does not weaken file lifetime or integrity. Replacing pin+with an expiring path/reference is a separate product decision and is outside+this plan.++## Explicit Host Surfaces That Stay++Keeping these surfaces is deliberate. They are user-selected, do not run on the+main message path, and removing them would create more migration complexity than+isolation value.++### Configuration++Keep `MemoryConfig`, parsing, validation, `atomic_update_memory`, stale-write+protection, and the cross-process operation lease in Avibe. In particular, the+host continues to enforce:++- `enabled` and complete endpoint requirements;+- embedding identity comparison;+- exact `confirm_loss: true` admission;+- `transition_notice_pending`, applied embedding identity, and organization+ transition behavior;+- `legacy_needs_repair` / `repair_required`; and+- compatible loading of released config shapes.++The optional package receives a validated config snapshot. This plan does not+make the Memory mapping opaque and does not change config behavior.++### Internal routes, UI, and CLI++- Keep the current `/internal/memory/*` routes and named internal-client methods.+- Keep the current Settings Memory React page and API result shapes.+- Keep the closed `vibe memory` subcommands, parsing, exit codes, output, and+ i18n.+- Keep current browser auth, CSRF, HMAC proof, and principal derivation.+- When the optional implementation is absent, these routes return one stable+ unavailable result instead of importing it.++There is no iframe, same-origin proxy, dynamic CLI passthrough, or new Memory RPC+protocol.++### Agent prompt++Keep `_MEMORY_CLI_PROMPT`, its eligibility decision, and the current Personal+Memory/user-preferences routing unchanged. Eligibility is derived from validated+host config and the same generic author/message facts; prompt construction never+invokes the optional runtime. Reducing prompt content is a separate product+change.++## Host and Optional-Package Ownership++### Remains in `avibe-os`++- `MemoryConfig` and destructive config transaction safety;+- `MemoryCaptureAdapter` and `DisabledMemoryAdapter`;+- generic message-kind and delivery-merge facts;+- existing Memory UI, CLI, internal routes, auth, i18n, and prompt contract;+- lightweight request/response/error/project-id types required by those host+ surfaces; and+- a fixed optional-package loader at the composition root.++### Moves to `avibe-memory`++- capture admission and owner/project derivation;+- capture task registry, capacity reservation, writer, and pending flush state;+- attachment Memory selection, pin store, modality policy, and extraction;+- Memory SQLite schema/store and processing diagnostics;+- `MemoryRuntime`, `MemoryModule`, provider readers, repair/delete runtime logic;+- EverOS HTTP adapter, process, supervisor, provider-root ownership;+- artifact manager, runtime manifest, runtime build scripts, and release guard;+ and+- Memory implementation tests that exercise only the optional package seam.++### Leaf modules moved before package extraction++Deleting `core.memory` must not delete unrelated host behavior:++| Current leaf | Target owner |+| --- | --- |+| `core.memory.blocking` | generic cancellation-safe blocking helper under `core` |+| `core.memory.operation_lock` | host Memory config/destructive transaction module |+| `core.memory.ui_access` | host Memory UI authentication module under `vibe` |+| `core.memory.http_headers` | host internal Memory request contract under `vibe` |+| `core.memory.admission_metadata` | replaced by `author_id` + core `message_kind`; legacy reader only |+| processing-record/result/error types used by clients | lightweight host Memory contract |+| project-id input parsers used by routes | lightweight host Memory contract |+| `core.memory_telemetry` | optional package or generic attachment logging, depending on caller |++No new `memory_host` framework package is required. Put each leaf under its+existing functional owner.++## Installation and Upgrade Contract++The package split does not silently disable Memory for existing users.++1. Publish `avibe-memory` before the first `avibe-os` release that can load it.+2. Add an `avibe-os[memory]` extra that resolves a host-compatible+ `avibe-memory` release.+3. The post-split upgrade planner chooses the extra when either Memory is enabled+ or the optional package is already installed. Disabled core-only installs+ continue upgrading without it.+4. An immutable bundled-Memory upgrader can only install the first split core.+ After the new core starts, the existing UI background dependency reconciler+ waits for host readiness, reads the persisted enabled state, and reuses the+ exact-version Memory package install action under the shared upgrade lock.+ It persists a three-attempt budget per core version before mutation and+ schedules one ordinary service restart. Controller startup never installs or+ downloads Python packages. Disabled startup remains a zero-install path; a+ published core-only install exposes only a user-invoked companion bootstrap+ so Memory can be enabled later.+5. Later enabled upgrades fail before replacing the current installation if the+ compatible optional package cannot be resolved. The first-hop convergence+ fails closed with Memory unavailable and core Avibe healthy; it never changes+ Memory config or provider data. A later startup retries only within the+ persisted per-version budget; an explicit action remains available after+ exhaustion. A failed activation restart stays repairable and retries restart+ without reinstalling the already-exact companion; the surviving UI process+ continues reconciling its other managed dependencies.+6. A successful upgrade or first-hop convergence schedules the ordinary Avibe+ restart when the runtime is active. Install, upgrade, or restart failures are+ structured terminal results and do not block a later explicit attempt.+7. The existing Dependencies/Memory install action remains available to+ explicitly reinstall the current tool with the Memory extra.+8. EverOS runtime download/install remains an explicit Memory dependency action,+ but its manifest and implementation move with `avibe-memory`.++There is no automatic package rollback, rollback plan, package-lifecycle+reservation, quarantine, Gate 5 lifecycle verifier, or general recovery+bootstrap. The enabled-package startup convergence above is the one dependency+invariant needed to bridge immutable bundled-Memory upgraders. The+retained manifest, hash, fetch, verify, and backup safeguards protect published+Memory Runtime artifact availability; they do not mutate installed Python+packages or recover an upgrade attempt.++Publishable core and optional-package artifacts carry reciprocal exact-version+dependencies. The fixed lazy loader validates the factory and constructed runtime+surface directly. A missing or incompatible implementation selects+`DisabledMemoryAdapter` and reports `memory_implementation_unavailable` or+`memory_implementation_incompatible`; it never fails service startup.++## Completed Migration Waves++Each wave landed as a focused, green PR. The repository did not merge placeholder+scenario IDs or permanent xfails.++### Wave 0: Make disabled Memory truly off (complete)++Delivered:++- choose `DisabledMemoryAdapter` before importing or constructing Memory runtime;+- stop opening Memory store, attachments, artifact state, and operation locks+ when disabled;+- do not schedule Memory wake on fresh disabled installs;+- move `ui_access` and any other startup-required host leaf out of+ `core.memory`;+- bound capture cancellation, destructive settlement, and runtime close during+ shutdown; and+- preserve asynchronous cleanup of pre-existing owned EverOS processes without+ creating new Memory state.++Evidence added:++- `MEMORY-INDEP-013`: disabled fresh startup has zero Memory filesystem/process+ side effects;+- `MEMORY-INDEP-014`: disabled Controller startup succeeds while optional+ implementation imports are blocked; and+- `MEMORY-INDEP-015`: a frozen Memory task cannot make Avibe shutdown unbounded.++Completion evidence: these scenarios and existing `MEMORY-INDEP-001..012` pass. No enabled+Memory product behavior changes.++Compatibility: this wave introduced no persisted format change.++### Wave 1: Return message and session ownership to core (complete)++Delivered:++- rename archive to a core session operation and keep its Memory observation+ after commit;+- remove the Memory-named `/new` wrapper while preserving generation safety and+ best-effort final flush behavior;+- rename platform message-shape classifiers into core vocabulary;+- add `message_kind` to durable snapshot and merge identity;+- stop writing new `_memory_*` metadata and translate legacy rows on read;+- derive Workbench author from existing authenticated `author_id`;+- move admission, task tracking, capacity reservation, and attachment pin+ scheduling behind the enabled adapter; and+- preserve the exact attachment, prompt, config, and explicit-route behavior.++Evidence added:++- `MEMORY-INDEP-016`: new rows use author/message-kind merge identity and contain+ no Memory-private metadata;+- merge characterization for two remote principals, original plus quick reply,+ forwarded/edited input, scheduled delivery, and legacy/new queued rows; and+- attachment tests proving retain/pin/text-only fallback behavior is unchanged.++Completion evidence: removing or forcing the adapter to raise does not change chat,+`/new`, archive, queue grouping, or Agent attachment delivery.++Compatibility: the legacy metadata reader remains; no bulk data migration was+introduced.++### Wave 2: Extract the optional in-process package (complete)++Delivered:++- introduce the fixed lazy loader and enabled adapter implementation;+- move implementation modules listed above to `avibe-memory` without changing+ their internal process/storage design;+- move every host-needed leaf to its real owner before deleting `core.memory`;+- keep named admin routes and host presentation unchanged;+- keep one in-process runtime and one EverOS child; and+- fail closed to `DisabledMemoryAdapter` on absent package, import failure,+ incompatible protocol, or construction failure.++Evidence added:++- `MEMORY-INDEP-017`: core-only installation imports and runs chat, `/new`,+ archive, UI server, internal server, CLI help, and shutdown;+- explicit Memory route/CLI unavailable behavior when the package is absent;+- package import/construction failure containment; and+- core-plus-Memory parity for all existing Memory scenarios.++Completion evidence: the Avibe process imports no optional implementation when disabled;+blocking `avibe_memory` imports leaves all core scenarios green; enabled Memory+passes its existing suite against unchanged data.++Compatibility: the package move kept current data and config formats readable.++### Wave 3: Ship the package split and delete compatibility code (complete)++Delivered:++- publish the matched optional distribution and `avibe-os[memory]` extra;+- update forward upgrades to preserve companion-package presence;+- move runtime manifest/build/release guard ownership;+- add core-only and core-plus-Memory wheel matrices;+- remove `core.memory`, temporary adapters, new-write legacy metadata paths, and+ duplicate tests after the legacy read window; and+- update `docs/MEMORY.md` and user installation documentation.++Evidence added:++- the retired `MEMORY-INDEP-018` package-shape assignment remains historical+ lineage only and is not an implementation target;+- wheel-content assertions proving `avibe-os` contains no Memory runtime+ implementation or EverOS artifact manifest; and+- packaged install smoke for missing, disabled, enabled, incompatible, and+ upgrade cases.++Completion evidence: both package matrices pass CI; local Incus `master` regression passes+Workbench and Slack/Discord/Telegram/Feishu/WeChat capture; service health is+verified; no temporary fallback implementation remains.++The proposed Wave 3c rollback plan, lifecycle reservation, quarantine, Gate 5+verifier, and recovery bootstrap were abandoned and retired. Historical+scenario IDs+`MEMORY-INDEP-018` through `020`, `022`, and `023` remain unassigned and must not+be repurposed. Current executable import and package-shape evidence is owned by+the scenario catalog under `MEMORY-INDEP-021` and `MEMORY-INDEP-024`.++## Verification Summary++| Concern | Required evidence |+| --- | --- |+| Disabled | no implementation import, mkdir, SQLite, lock, task, or EverOS start on a fresh home |+| Missing package | Controller/UI/internal server/CLI import and core flows remain healthy |+| Main path | full queue, capture exception, provider hang, and adapter failure never block Agent completion |+| Session lifecycle | `/new` and archive commit with Memory frozen; stale generations are not attributed |+| Shutdown | capture/destructive/runtime cleanup stays within one finite total budget |+| Delivery | author/message-kind merge preserves current segmentation and legacy-row safety |+| Attachments | current lease, pin, integrity, fallback, and cleanup scenarios remain green |+| Config | stale write, confirm-loss, cloud transition, repair fence, and released-shape fixtures remain green |+| Explicit surfaces | UI, named internal routes, CLI output/exit codes, and prompt routing retain parity |+| Packaging | core-only, core-plus-Memory, enabled upgrade, disabled upgrade, terminal failure, and retry evidence |++## Complexity Guardrails++Do not add the following in this refactor:++- a second Memory process or new UDS protocol;+- `PluginHost`, `PluginManager`, manifest discovery, or directory scanning;+- a generic `request(operation, payload)` interface;+- dynamic UI, CLI, route, prompt, or configuration registration;+- iframe/proxy-based Memory UI extraction;+- opaque Memory configuration;+- a new event bus, durable capture outbox, or dual writer;+- weaker attachment lifetime semantics; or+- prompt or admission product changes hidden inside isolation work.++Shared plugin infrastructure is considered only when a second independently+shipped plugin has concrete, overlapping requirements. Process isolation is+considered only when a reproducible test proves that this in-process Adapter+cannot meet the bounded main-path contract.++## Definition of Done++The refactor is complete when:++- disabled fresh startup has zero Memory runtime side effects;+- deleting or never installing `avibe-memory` leaves Avibe fully operational;+- Memory import, construction, provider, and capture failures cannot affect core+ outcomes or make shutdown unbounded;+- core session and delivery state no longer depends on Memory-private metadata;+- attachment, config safety, prompt, UI, CLI, and enabled Memory behavior remain+ unchanged;+- existing enabled users receive the compatible package during forward upgrade,+ and a terminal failure does not prevent a later attempt;+- `core.memory` and every temporary migration adapter are deleted; and+- no second sidecar or generic plugin framework was introduced.diff --git a/docs/plans/memory-wave3c-release-migration-contract.md b/docs/plans/memory-wave3c-release-migration-contract.mdnew file mode 100644index 000000000..cdf176ec7--- /dev/null+++ b/docs/plans/memory-wave3c-release-migration-contract.md@@ -0,0 +1,141 @@+# Memory Runtime Release Safety Contract++> Status: active release-safety contract+>+> The abandoned Wave 3c Gate 5 transition, package rollback, quarantine,+> recovery-bootstrap, and successor sequencing designs are retired.++## Scope++This document retains the release behavior that current workflows enforce for+the independent `avibe-memory` distribution and Memory Runtime assets. It+covers release identity, immutable runtime bytes, publication ordering, public+availability, exact hash and archive validation, published-manifest+compatibility, and scheduled backup/recovery.++It does not define an upgrade rollback protocol, a package-transition verifier,+or a future release architecture. Historical scenario IDs+`MEMORY-INDEP-020`, `MEMORY-INDEP-022`, and `MEMORY-INDEP-023` remain retired and+must not be marked covered or reused for a different capability.++## Release Identity And Immutable Assets++- An official `v*` annotated tag is the release-state input. The workflow uses+ that tag and its source commit as one release identity.+- Every Memory Runtime manifest has `release_state: published`, names the same+ release tag, and points each archive URL at that tag's GitHub Release.+- Runtime archives and manifests are immutable per tag. A rerun may reuse a+ byte-identical asset, but a same-name mismatch fails and requires a new+ version. It must never overwrite the hosted runtime bytes.+- A GitHub-only `gh-v*` prerelease carries the `avibe-memory` and `avibe-os`+ wheel/sdist pairs, runtime archives, and manifests under the same identity.+ It does not trigger PyPI.++## Publication Order++The existing workflows keep one asset-complete GitHub Draft and one official+finalizer:++1. Derive one package version from the tagged source and use explicit VCS+ pretend-version variables for both `avibe-memory` and `avibe-os`.+2. Build both wheel/sdist pairs plus the Show and Memory Runtime archives and+ manifests from that source.+3. Verify the distributions have the same version, independent contents and+ metadata, and pass the core-only/core-plus-Memory installation matrix.+4. Verify the locally staged Memory Runtime manifest and exact asset set before+ any release publication.+5. Create or reuse the Draft for that tag. Check every existing runtime asset+ for byte identity before mutating any release asset, then upload both+ distribution pairs and the runtime assets.+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.+9. Publish only `avibe-os` through its existing trusted-publishing environment+ after the public `avibe-memory` wheel 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+around a failed integrity check, or invoke automatic package rollback or+lifecycle recovery.++## Guard CLI Contract++Current workflows use exactly three+`scripts/memory_runtime_release_guard.py` subcommands:++- `check-policy` validates that a manifest describes a supported published+ EverOS provenance and has the required platform, same-release URL, size,+ digest, binary path, and optional sync-bootstrap fields.+- `verify --asset-dir <dir>` requires the exact asset-name set, exact manifest+ bytes, declared archive size and SHA-256, the declared runtime binary hash,+ and any declared sync-bootstrap member hashes and marker bytes.+- `fetch --output-dir <dir>` downloads the manifest and archives from the+ manifest's release tag with declared-size bounds, verifies the complete set,+ and replaces the destination only after verification succeeds.++Policy exclusions, byte failures, and internal guard failures retain distinct+exit codes and JSON failure kinds. These paths are stdlib-only and do not depend+on wheel metadata or a static package-transition policy.++## Published Compatibility And Migration++Already-published Memory Runtime manifests remain verifiable through the+explicit `PUBLISHED_RUNTIME_PROVENANCE` ledger. Moving the current EverOS pin+does not remove older supported entries. A manifest with unsupported provenance+is excluded visibly by `check-policy`; it is not treated as a byte-recovery+failure.++For split releases, the `avibe-memory` wheel is the authoritative manifest+owner. A published release may fall back to its legacy `avibe-os` wheel only+when no `avibe-memory` wheel exists. A present but missing or invalid Memory+manifest is excluded visibly and never masked by the legacy fallback. Legacy+core wheels that predate the Memory Runtime manifest are skipped by the+scheduled inventory. Any candidate manifest must self-pin the selected release+tag and pass current policy before it enters guarded backup and recovery+coverage. Changes to a shipped manifest shape require compatible loading or a+deliberate visible exclusion, never startup or workflow failure by accident.++## Availability, Backup, And Recovery++The scheduled `Memory Runtime Release Guard` preserves the managed-runtime+availability contract:++1. Enumerate published releases with either distribution wheel. Prefer+ `avibe-memory`; select `avibe-os` only for a release with no Memory wheel.+2. Extract the manifest from that selected wheel, record its owner, exact wheel+ pattern, and manifest hash, then run `check-policy` and report guarded and+ excluded releases separately.+3. Re-download the exact recorded owner during verification instead of+ rediscovering package ownership.+4. Run `fetch` for every guarded manifest. A successful fetch is the public+ availability and integrity check.+5. Keep a verified backup artifact keyed by the exact manifest SHA-256.+6. On a byte failure, locate the latest non-expired matching backup, run+ `verify` on it, and upload only asset names that are missing from the release.+ Existing names are never clobbered; a same-name integrity failure stops.+7. Run `fetch` again after recovery so restored public bytes must pass the same+ release-tag, manifest, archive, and hash checks.++The backup lookup follows the artifact identity rather than a fixed recent-run+window, and the retained backup remains tied to one exact manifest hash.++## Operator Safety++- 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.+- 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.+- Recovery may restore missing immutable assets only from a verified backup for+ the same manifest hash and release identity.+- Verification and maintenance must not restart local Avibe, mutate Incus, or+ perform release actions outside the release workflows.diff --git a/hatch_build.py b/hatch_build.pyindex c79ffec6f..108492863 100644--- a/hatch_build.py+++ b/hatch_build.py@@ -11,6 +11,7 @@ MANIFEST_WHEEL_PATH = "vibe/show_runtime_manifest.json"_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):@@ -22,14 +23,22 @@ class CustomBuildHook(BuildHookInterface):validate_manifest_file(Path(self.root) / MANIFEST_SOURCE)def finalize(self, version: str, build_data: dict, artifact_path: str) -> None:- if version == "editable" or self.target_name != "wheel":+ if version == "editable":return- with zipfile.ZipFile(artifact_path) as wheel:+ if self.target_name == "wheel":+ with zipfile.ZipFile(artifact_path) as wheel:+ try:+ content = wheel.read(MANIFEST_WHEEL_PATH)+ except KeyError as exc:+ raise RuntimeError(f"Built wheel is missing {MANIFEST_WHEEL_PATH}") from exctry:- content = wheel.read(MANIFEST_WHEEL_PATH)- except KeyError as exc:- raise RuntimeError(f"Built wheel is missing {MANIFEST_WHEEL_PATH}") from exc- try:- validate_manifest_bytes(content)- except ValueError as exc:- raise RuntimeError(f"Built wheel contains an invalid {MANIFEST_WHEEL_PATH}: {exc}") from exc+ 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/hatch_exact_peer.py b/hatch_exact_peer.pynew file mode 100644index 000000000..82c72ec08--- /dev/null+++ b/hatch_exact_peer.py@@ -0,0 +1,382 @@+from __future__ import annotations++import base64+from collections.abc import MutableMapping, MutableSequence+import csv+from email import policy+from email.parser import BytesParser+import hashlib+import io+import os+from pathlib import Path, PurePosixPath+import tarfile+import tempfile+import zipfile++from packaging.requirements import InvalidRequirement, Requirement+from packaging.utils import canonicalize_name+from packaging.version import InvalidVersion, Version+++_METADATA_POLICY = policy.compat32.clone(linesep="\n", max_line_length=0)+++def pin_peer_dependency(+ artifact_path: str,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None = None,+) -> None:+ artifact = Path(artifact_path)+ normalized_version = _normalize_version(package_version)+ try:+ if artifact.suffix == ".whl":+ _pin_wheel(+ artifact,+ project_name=project_name,+ peer_name=peer_name,+ package_version=normalized_version,+ peer_extra=peer_extra,+ )+ elif artifact.name.endswith(".tar.gz"):+ _pin_sdist(+ artifact,+ project_name=project_name,+ peer_name=peer_name,+ package_version=normalized_version,+ peer_extra=peer_extra,+ )+ else:+ raise RuntimeError(f"Unsupported publishable artifact for exact peer metadata: {artifact.name}")+ except Exception:+ artifact.unlink(missing_ok=True)+ raise+++def _normalize_version(value: str) -> str:+ try:+ return str(Version(value))+ except InvalidVersion as exc:+ raise RuntimeError(f"Cannot pin peer metadata to invalid package version {value!r}") from exc+++def _pin_metadata(+ content: bytes,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None,+) -> bytes:+ metadata = BytesParser(policy=policy.compat32).parsebytes(content)+ metadata_name = metadata.get("Name")+ metadata_version = metadata.get("Version")+ if not metadata_name or canonicalize_name(metadata_name) != canonicalize_name(project_name):+ raise RuntimeError(f"Artifact metadata is not for {project_name}")+ if not metadata_version or _normalize_version(metadata_version) != package_version:+ raise RuntimeError(+ f"{project_name} artifact metadata version {metadata_version!r} does not match built version {package_version}"+ )++ requirements = metadata.get_all("Requires-Dist") or []+ parsed: list[Requirement] = []+ for value in requirements:+ try:+ parsed.append(Requirement(value))+ except InvalidRequirement as exc:+ raise RuntimeError(f"{project_name} emitted invalid dependency metadata: {value}") from exc+ peer_indexes = [+ index+ for index, requirement in enumerate(parsed)+ if canonicalize_name(requirement.name) == canonicalize_name(peer_name)+ ]+ if len(peer_indexes) != 1:+ raise RuntimeError(f"{project_name} must declare exactly one {peer_name} dependency")++ peer_index = peer_indexes[0]+ peer_requirement = parsed[peer_index]+ if peer_requirement.url or peer_requirement.extras:+ raise RuntimeError(f"{project_name} cannot exact-pin a URL or extra-qualified {peer_name} dependency")+ if peer_extra is None:+ if peer_requirement.marker is not None:+ raise RuntimeError(f"{project_name} must require {peer_name} without an environment marker")+ elif peer_requirement.marker is None or not _is_exact_extra_marker(peer_requirement, peer_extra):+ raise RuntimeError(f"{project_name} must expose {peer_name} only through the {peer_extra!r} extra")++ marker = f"; {peer_requirement.marker}" if peer_requirement.marker is not None else ""+ requirements[peer_index] = f"{peer_name}=={package_version}{marker}"+ del metadata["Requires-Dist"]+ for requirement in requirements:+ metadata["Requires-Dist"] = requirement++ pinned = metadata.as_bytes(policy=_METADATA_POLICY)+ _verify_exact_pin(+ pinned,+ project_name=project_name,+ peer_name=peer_name,+ package_version=package_version,+ peer_extra=peer_extra,+ )+ return pinned+++def _is_exact_extra_marker(requirement: Requirement, peer_extra: str) -> bool:+ if requirement.marker is None:+ return False+ return requirement.marker.evaluate({"extra": peer_extra}) and not requirement.marker.evaluate(+ {"extra": f"not-{peer_extra}"}+ )+++def _verify_exact_pin(+ content: bytes,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None,+) -> None:+ metadata = BytesParser(policy=policy.compat32).parsebytes(content)+ requirements = metadata.get_all("Requires-Dist") or []+ peers = [+ Requirement(value)+ for value in requirements+ if canonicalize_name(Requirement(value).name) == canonicalize_name(peer_name)+ ]+ if len(peers) != 1 or str(peers[0].specifier) != f"=={package_version}":+ raise RuntimeError(f"{project_name} artifact did not emit the exact {peer_name}=={package_version} contract")+ if peer_extra is None:+ marker_matches = peers[0].marker is None+ else:+ marker_matches = peers[0].marker is not None and _is_exact_extra_marker(peers[0], peer_extra)+ if not marker_matches:+ raise RuntimeError(f"{project_name} artifact emitted the wrong marker for {peer_name}")+++def _pin_wheel(+ artifact: Path,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None,+) -> None:+ with zipfile.ZipFile(artifact) as wheel:+ infos = wheel.infolist()+ entries = {info.filename: wheel.read(info.filename) for info in infos}+ if len(entries) != len(infos):+ raise RuntimeError(f"Wheel contains duplicate paths: {artifact.name}")++ metadata_names = [name for name in entries if name.endswith(".dist-info/METADATA")]+ record_names = [name for name in entries if name.endswith(".dist-info/RECORD")]+ if len(metadata_names) != 1 or len(record_names) != 1:+ raise RuntimeError(f"Wheel must contain one METADATA and one RECORD file: {artifact.name}")+ metadata_name = metadata_names[0]+ record_name = record_names[0]+ if metadata_name.rsplit("/", 1)[0] != record_name.rsplit("/", 1)[0]:+ raise RuntimeError(f"Wheel METADATA and RECORD identities disagree: {artifact.name}")++ entries[metadata_name] = _pin_metadata(+ entries[metadata_name],+ project_name=project_name,+ peer_name=peer_name,+ package_version=package_version,+ peer_extra=peer_extra,+ )+ entries[record_name] = _updated_record(+ entries[record_name], metadata_name=metadata_name, metadata=entries[metadata_name], record_name=record_name+ )++ temporary = _temporary_artifact_path(artifact)+ try:+ with zipfile.ZipFile(temporary, "w") as wheel:+ for info in infos:+ wheel.writestr(info, entries[info.filename])+ os.replace(temporary, artifact)+ finally:+ temporary.unlink(missing_ok=True)+++def _updated_record(content: bytes, *, metadata_name: str, metadata: bytes, record_name: str) -> bytes:+ rows = list(csv.reader(io.StringIO(content.decode("utf-8"))))+ metadata_rows = [row for row in rows if row and row[0] == metadata_name]+ record_rows = [row for row in rows if row and row[0] == record_name]+ if len(metadata_rows) != 1 or len(record_rows) != 1:+ raise RuntimeError("Wheel RECORD must name METADATA and itself exactly once")++ digest = base64.urlsafe_b64encode(hashlib.sha256(metadata).digest()).rstrip(b"=").decode("ascii")+ metadata_rows[0][1:] = [f"sha256={digest}", str(len(metadata))]+ record_rows[0][1:] = ["", ""]+ output = io.StringIO()+ csv.writer(output, lineterminator="\n").writerows(rows)+ return output.getvalue().encode("utf-8")+++def _pin_sdist(+ artifact: Path,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None,+) -> None:+ with tarfile.open(artifact, "r:gz") as sdist:+ pax_headers = dict(sdist.pax_headers)+ members = sdist.getmembers()+ entries: list[tuple[tarfile.TarInfo, bytes | None]] = []+ for member in members:+ source = sdist.extractfile(member) if member.isfile() else None+ entries.append((member, source.read() if source is not None else None))++ pkg_info_indexes = [+ index+ for index, (member, _content) in enumerate(entries)+ if member.isfile() and PurePosixPath(member.name).name == "PKG-INFO"+ ]+ if len(pkg_info_indexes) != 1:+ raise RuntimeError(f"Sdist must contain exactly one PKG-INFO file: {artifact.name}")+ pkg_info_index = pkg_info_indexes[0]+ member, content = entries[pkg_info_index]+ if content is None:+ raise RuntimeError(f"Sdist PKG-INFO is unreadable: {artifact.name}")+ pinned_content = _pin_metadata(+ content,+ project_name=project_name,+ peer_name=peer_name,+ package_version=package_version,+ peer_extra=peer_extra,+ )+ member.size = len(pinned_content)+ entries[pkg_info_index] = (+ member,+ pinned_content,+ )++ pyproject_indexes = [+ index+ for index, (member, _content) in enumerate(entries)+ if member.isfile() and PurePosixPath(member.name).name == "pyproject.toml"+ ]+ if len(pyproject_indexes) != 1:+ raise RuntimeError(f"Sdist must contain exactly one pyproject.toml file: {artifact.name}")+ pyproject_index = pyproject_indexes[0]+ member, content = entries[pyproject_index]+ if content is None:+ raise RuntimeError(f"Sdist pyproject.toml is unreadable: {artifact.name}")+ pinned_content = _pin_sdist_build_input(+ content,+ project_name=project_name,+ peer_name=peer_name,+ package_version=package_version,+ peer_extra=peer_extra,+ )+ member.size = len(pinned_content)+ entries[pyproject_index] = (member, pinned_content)++ temporary = _temporary_artifact_path(artifact)+ try:+ with tarfile.open(temporary, "w:gz", format=tarfile.PAX_FORMAT, pax_headers=pax_headers) as sdist:+ for member, content in entries:+ sdist.addfile(member, io.BytesIO(content) if content is not None else None)+ os.replace(temporary, artifact)+ finally:+ temporary.unlink(missing_ok=True)+++def _pin_sdist_build_input(+ content: bytes,+ *,+ project_name: str,+ peer_name: str,+ package_version: str,+ peer_extra: str | None,+) -> bytes:+ try:+ import tomlkit++ document = tomlkit.parse(content.decode("utf-8"))+ except Exception as exc:+ raise RuntimeError(f"{project_name} sdist has an invalid pyproject.toml") from exc++ project = document.get("project")+ if not isinstance(project, MutableMapping):+ raise RuntimeError(f"{project_name} sdist pyproject.toml has no project table")+ metadata_name = project.get("name")+ if not isinstance(metadata_name, str) or canonicalize_name(metadata_name) != canonicalize_name(project_name):+ raise RuntimeError(f"Sdist build input is not for {project_name}")++ dependencies = _project_peer_dependencies(project, project_name=project_name, peer_extra=peer_extra)+ peer_index, peer_requirement = _find_peer_requirement(+ dependencies,+ project_name=project_name,+ peer_name=peer_name,+ )+ if peer_requirement.url or peer_requirement.extras or peer_requirement.marker is not None:+ raise RuntimeError(f"{project_name} sdist cannot exact-pin a qualified {peer_name} dependency")+ dependencies[peer_index] = f"{peer_name}=={package_version}"++ pinned = tomlkit.dumps(document).encode("utf-8")+ verified = tomlkit.parse(pinned.decode("utf-8"))["project"]+ verified_dependencies = _project_peer_dependencies(+ verified,+ project_name=project_name,+ peer_extra=peer_extra,+ )+ _index, verified_requirement = _find_peer_requirement(+ verified_dependencies,+ project_name=project_name,+ peer_name=peer_name,+ )+ if str(verified_requirement.specifier) != f"=={package_version}" or verified_requirement.marker is not None:+ raise RuntimeError(f"{project_name} sdist build input did not retain the exact {peer_name} pin")+ return pinned+++def _project_peer_dependencies(+ project: MutableMapping,+ *,+ project_name: str,+ peer_extra: str | None,+) -> MutableSequence:+ if peer_extra is None:+ dependencies = project.get("dependencies")+ else:+ optional = project.get("optional-dependencies")+ dependencies = optional.get(peer_extra) if isinstance(optional, MutableMapping) else None+ if not isinstance(dependencies, MutableSequence):+ label = "dependencies" if peer_extra is None else f"optional-dependencies.{peer_extra}"+ raise RuntimeError(f"{project_name} sdist pyproject.toml has no {label} array")+ return dependencies+++def _find_peer_requirement(+ dependencies: MutableSequence,+ *,+ project_name: str,+ peer_name: str,+) -> tuple[int, Requirement]:+ parsed: list[Requirement] = []+ for value in dependencies:+ if not isinstance(value, str):+ raise RuntimeError(f"{project_name} sdist emitted a non-string dependency")+ try:+ parsed.append(Requirement(value))+ except InvalidRequirement as exc:+ raise RuntimeError(f"{project_name} sdist emitted an invalid dependency: {value}") from exc+ peer_indexes = [+ index+ for index, requirement in enumerate(parsed)+ if canonicalize_name(requirement.name) == canonicalize_name(peer_name)+ ]+ if len(peer_indexes) != 1:+ raise RuntimeError(f"{project_name} sdist must declare exactly one {peer_name} dependency")+ peer_index = peer_indexes[0]+ return peer_index, parsed[peer_index]+++def _temporary_artifact_path(artifact: Path) -> Path:+ descriptor, path = tempfile.mkstemp(prefix=f".{artifact.name}.", suffix=".tmp", dir=artifact.parent)+ os.close(descriptor)+ return Path(path)diff --git a/main.py b/main.pyindex c1254bcf9..0b2422acf 100644--- a/main.py+++ b/main.py@@ -146,7 +146,7 @@ def main():macos_session_diagnostics = Nonecontroller = Nonetry:- from core.memory.ui_access import initialize_process_ui_read_secret+ from vibe.memory_ui_access import initialize_process_ui_read_secretinitialize_process_ui_read_secret()acquire_service_instance_lock()diff --git a/modules/im/base.py b/modules/im/base.pyindex 4b5a5b054..b0aa210fc 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -6,6 +6,8 @@ from abc import ABC, abstractmethodfrom typing import Optional, Callable, Dict, Any, List, Tuple, Literal, castfrom dataclasses import dataclass+from core.delivery_target import MessageKind+from .download_target import open_download_targetlogger = logging.getLogger(__name__)@@ -46,10 +48,11 @@ class MessageContext:files: Optional[List[FileAttachment]] = None # List of file attachments# Inbound adapters set this only after classifying their native event.# None is intentionally fail-closed for Memory capture and commands.- is_ordinary_text: Optional[bool] = None+ is_original_human_text: Optional[bool] = None# Attachment turns use a separate native-event classification so adding# files never widens the existing ordinary-text contract.- is_ordinary_attachment: Optional[bool] = None+ is_original_human_attachment: Optional[bool] = None+ message_kind: MessageKind = "unknown"@dataclassdiff --git a/modules/im/discord.py b/modules/im/discord.pyindex fa762e988..683d45dbd 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -18,7 +18,11 @@ from .base import (InlineButton,FileAttachment,)-from .message_facts import is_ordinary_discord_attachment, is_ordinary_discord_text+from .message_facts import (+ discord_message_kind,+ is_original_human_discord_attachment,+ is_original_human_discord_text,+)from .download_target import open_download_targetfrom config.v2_config import DiscordConfigfrom .formatters import DiscordFormatter@@ -227,6 +231,9 @@ class DiscordBot(BaseIMClient):message_id=context.message_id,platform_specific=context.platform_specific,files=context.files,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,)return await self._run_on_client_loop(_impl())@@ -275,6 +282,9 @@ class DiscordBot(BaseIMClient):message_id=context.message_id,platform_specific=next_payload,files=context.files,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,)return await self._run_on_client_loop(_reply_impl())@@ -291,6 +301,9 @@ class DiscordBot(BaseIMClient):message_id=context.message_id,platform_specific=context.platform_specific,files=context.files,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,)return await self._run_on_client_loop(_impl())@@ -1085,7 +1098,8 @@ class DiscordBot(BaseIMClient):message_id=str(message.id),platform_specific={"platform": "discord", "message": message, "is_dm": is_dm},files=files,- is_ordinary_text=is_ordinary_discord_text(message, files),+ is_original_human_text=is_original_human_discord_text(message, files),+ message_kind=discord_message_kind(message, files),)if await self.dispatch_text_command(command_context, content, allow_plain_bind=allow_plain_bind):return@@ -1100,7 +1114,8 @@ class DiscordBot(BaseIMClient):message_id=str(message.id),platform_specific={"platform": "discord", "message": message, "is_dm": is_dm},files=files,- is_ordinary_text=is_ordinary_discord_text(message, files),+ is_original_human_text=is_original_human_discord_text(message, files),+ message_kind=discord_message_kind(message, files),)await self.on_message_callback(context, "")return@@ -1113,8 +1128,9 @@ class DiscordBot(BaseIMClient):message_id=str(message.id),platform_specific={"platform": "discord", "message": message, "is_dm": is_dm},files=files,- is_ordinary_text=is_ordinary_discord_text(message, files),- is_ordinary_attachment=is_ordinary_discord_attachment(message, files),+ is_original_human_text=is_original_human_discord_text(message, files),+ is_original_human_attachment=is_original_human_discord_attachment(message, files),+ message_kind=discord_message_kind(message, files),)if self.on_message_callback:diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex aabe0295b..ea90171f2 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -20,7 +20,11 @@ from .base import (MessageContext,)from .formatters import FeishuFormatter-from .message_facts import is_ordinary_feishu_attachment, is_ordinary_feishu_text+from .message_facts import (+ feishu_message_kind,+ is_original_human_feishu_attachment,+ is_original_human_feishu_text,+)from .download_target import open_download_targetfrom config.v2_config import LarkConfigfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -1759,12 +1763,18 @@ class FeishuBot(BaseIMClient):"is_dm": is_p2p,},files=file_attachments,- is_ordinary_text=is_ordinary_feishu_text(+ is_original_human_text=is_original_human_feishu_text(+ event_data,+ file_attachments,+ shared_text=shared_text,+ ),+ is_original_human_attachment=is_original_human_feishu_attachment(event_data,+ msg_content,file_attachments,shared_text=shared_text,),- is_ordinary_attachment=is_ordinary_feishu_attachment(+ message_kind=feishu_message_kind(event_data,msg_content,file_attachments,diff --git a/modules/im/message_facts.py b/modules/im/message_facts.pyindex b89f26288..6454b22d6 100644--- a/modules/im/message_facts.py+++ b/modules/im/message_facts.py@@ -4,6 +4,8 @@ from __future__ import annotationsfrom typing import Any, Optional+from core.delivery_target import MessageKind+from .base import FileAttachment@@ -78,7 +80,7 @@ def is_plain_slack_composer_blocks(blocks: Any) -> bool:return True-def is_ordinary_slack_text(event: dict[str, Any], files: Optional[list[FileAttachment]]) -> bool:+def is_original_human_slack_text(event: dict[str, Any], files: Optional[list[FileAttachment]]) -> bool:return not any((files,@@ -102,7 +104,7 @@ def is_ordinary_slack_text(event: dict[str, Any], files: Optional[list[FileAttac)-def is_ordinary_slack_attachment(+def is_original_human_slack_attachment(event: dict[str, Any],files: Optional[list[FileAttachment]],) -> bool:@@ -130,7 +132,33 @@ def is_ordinary_slack_attachment()-def is_ordinary_discord_text(message: Any, files: Optional[list[FileAttachment]]) -> bool:+def slack_message_kind(+ event: dict[str, Any],+ files: Optional[list[FileAttachment]],+ *,+ shared: bool = False,+) -> MessageKind:+ if not shared and (+ is_original_human_slack_text(event, files)+ or is_original_human_slack_attachment(event, files)+ ):+ return "original"+ if any(+ (+ event.get("is_system"),+ event.get("system"),+ event.get("type") in {"system", "system_message"},+ )+ ):+ return "system"+ if event.get("edited") or event.get("subtype") == "message_changed":+ return "edited"+ if shared or event.get("forwarded"):+ return "forwarded"+ return "unknown"+++def is_original_human_discord_text(message: Any, files: Optional[list[FileAttachment]]) -> bool:try:is_system = message.is_system() if callable(getattr(message, "is_system", None)) else Falseexcept Exception:@@ -150,7 +178,7 @@ def is_ordinary_discord_text(message: Any, files: Optional[list[FileAttachment]])-def is_ordinary_discord_attachment(+def is_original_human_discord_attachment(message: Any,files: Optional[list[FileAttachment]],) -> bool:@@ -180,7 +208,30 @@ def is_ordinary_discord_attachment()-def is_ordinary_telegram_text(message: dict[str, Any], files: list[FileAttachment]) -> bool:+def discord_message_kind(+ message: Any,+ files: Optional[list[FileAttachment]],+) -> MessageKind:+ if is_original_human_discord_text(+ message, files+ ) or is_original_human_discord_attachment(message, files):+ return "original"+ try:+ if callable(getattr(message, "is_system", None)) and message.is_system():+ return "system"+ except Exception:+ return "unknown"+ if getattr(message, "edited_at", None) is not None:+ return "edited"+ flags = getattr(message, "flags", None)+ if bool(getattr(flags, "forwarded", False)) or getattr(+ message, "message_snapshots", None+ ):+ return "forwarded"+ return "unknown"+++def is_original_human_telegram_text(message: dict[str, Any], files: list[FileAttachment]) -> bool:sender = message.get("from") or {}return not any((@@ -196,7 +247,7 @@ def is_ordinary_telegram_text(message: dict[str, Any], files: list[FileAttachmen)-def is_ordinary_telegram_attachment(+def is_original_human_telegram_attachment(message: dict[str, Any],files: list[FileAttachment],) -> bool:@@ -236,7 +287,30 @@ def is_ordinary_telegram_attachment()-def is_ordinary_feishu_text(+def telegram_message_kind(+ message: dict[str, Any],+ files: list[FileAttachment],+) -> MessageKind:+ if is_original_human_telegram_text(+ message, files+ ) or is_original_human_telegram_attachment(message, files):+ return "original"+ if any(+ (+ message.get("is_system"),+ message.get("system"),+ message.get("type") in {"system", "system_message"},+ )+ ):+ return "system"+ if message.get("edit_date"):+ return "edited"+ if message.get("forward_origin") or message.get("forward_from"):+ return "forwarded"+ return "unknown"+++def is_original_human_feishu_text(event: dict[str, Any],files: Optional[list[FileAttachment]],*,@@ -253,7 +327,7 @@ def is_ordinary_feishu_text()-def is_ordinary_feishu_attachment(+def is_original_human_feishu_attachment(event: dict[str, Any],content: dict[str, Any],files: Optional[list[FileAttachment]],@@ -279,7 +353,58 @@ def is_ordinary_feishu_attachment()-def is_ordinary_workbench_text(payload: object, quick_reply_for: object) -> bool:+def feishu_message_kind(+ event: dict[str, Any],+ content: dict[str, Any],+ files: Optional[list[FileAttachment]],+ *,+ shared_text: Optional[str],+) -> MessageKind:+ if is_original_human_feishu_text(+ event, files, shared_text=shared_text+ ) or is_original_human_feishu_attachment(+ event,+ content,+ files,+ shared_text=shared_text,+ ):+ return "original"+ sender = event.get("sender") or {}+ message = event.get("message") or {}+ if sender.get("sender_type") == "app" or any(+ message.get(key) for key in ("is_system", "system")+ ):+ return "system"+ if message.get("edited"):+ return "edited"+ if shared_text or message.get("forwarded"):+ return "forwarded"+ return "unknown"+++def workbench_message_kind(payload: object, quick_reply_for: object) -> str:+ """Classify a Workbench submit from host-owned request facts."""++ if not isinstance(payload, dict):+ return "unknown"+ if quick_reply_for:+ return "quick_reply"+ metadata = payload.get("metadata")+ if not isinstance(metadata, dict):+ return "original"+ if metadata.get("is_system") or metadata.get("system"):+ return "system"+ if metadata.get("edited"):+ return "edited"+ if any(+ metadata.get(key)+ for key in ("forwarded", "is_forwarded", "forward_origin", "forwarded_from")+ ):+ return "forwarded"+ return "original"+++def is_original_human_workbench_text(payload: object, quick_reply_for: object) -> bool:"""Classify a Workbench submit the same way the IM adapters classify events.Quick replies and forwarded messages are not ordinary human turns. Uploads@@ -287,18 +412,10 @@ def is_ordinary_workbench_text(payload: object, quick_reply_for: object) -> boolcan actually convert."""- if not isinstance(payload, dict) or quick_reply_for:- return False- metadata = payload.get("metadata")- if isinstance(metadata, dict) and any(- metadata.get(key)- for key in ("forwarded", "is_forwarded", "forward_origin", "forwarded_from")- ):- return False- return True+ return workbench_message_kind(payload, quick_reply_for) == "original"-def is_ordinary_wechat_text(msg: dict[str, Any], files: Optional[list[FileAttachment]]) -> bool:+def is_original_human_wechat_text(msg: dict[str, Any], files: Optional[list[FileAttachment]]) -> bool:items = msg.get("item_list") or []return (bool(items)@@ -313,7 +430,7 @@ def is_ordinary_wechat_text(msg: dict[str, Any], files: Optional[list[FileAttach)-def is_ordinary_wechat_attachment(+def is_original_human_wechat_attachment(msg: dict[str, Any],files: Optional[list[FileAttachment]],) -> bool:@@ -347,3 +464,23 @@ def is_ordinary_wechat_attachment(return has_direct_media and not any(msg.get(key) for key in ("is_system", "system", "edited", "forwarded"))+++def wechat_message_kind(+ msg: dict[str, Any],+ files: Optional[list[FileAttachment]],+) -> MessageKind:+ if is_original_human_wechat_text(+ msg, files+ ) or is_original_human_wechat_attachment(msg, files):+ return "original"+ if msg.get("is_system") or msg.get("system"):+ return "system"+ if msg.get("edited"):+ return "edited"+ items = msg.get("item_list") or []+ if msg.get("forwarded") or any(+ isinstance(item, dict) and item.get("ref_msg") for item in items+ ):+ return "forwarded"+ return "unknown"diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 649023493..be2a47cd1 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -21,7 +21,11 @@ from .base import (InlineButton,FileAttachment,)-from .message_facts import is_ordinary_slack_attachment, is_ordinary_slack_text+from .message_facts import (+ is_original_human_slack_attachment,+ is_original_human_slack_text,+ slack_message_kind,+)from .download_target import open_download_targetfrom config.v2_config import SlackConfigfrom core.auth import AuthResult@@ -282,6 +286,9 @@ class SlackBot(BaseIMClient):message_id=context.message_id,platform_specific=context.platform_specific,files=context.files,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,)def _ensure_clients(self):@@ -2097,11 +2104,16 @@ class SlackBot(BaseIMClient):"normalized_user_text": normalized_user_text,},files=file_attachments,- is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not has_shared_content,- is_ordinary_attachment=(- is_ordinary_slack_attachment(event, file_attachments)+ is_original_human_text=is_original_human_slack_text(event, file_attachments) and not has_shared_content,+ is_original_human_attachment=(+ is_original_human_slack_attachment(event, file_attachments)and not has_shared_content),+ message_kind=slack_message_kind(+ event,+ file_attachments,+ shared=has_shared_content,+ ),)if handled_bot_mention_in_message_event and self.settings_manager and thread_id:@@ -2201,11 +2213,16 @@ class SlackBot(BaseIMClient):"normalized_user_text": normalized_user_text,},files=file_attachments,- is_ordinary_text=is_ordinary_slack_text(event, file_attachments) and not bool(shared_text),- is_ordinary_attachment=(- is_ordinary_slack_attachment(event, file_attachments)+ is_original_human_text=is_original_human_slack_text(event, file_attachments) and not bool(shared_text),+ is_original_human_attachment=(+ is_original_human_slack_attachment(event, file_attachments)and not bool(shared_text)),+ message_kind=slack_message_kind(+ event,+ file_attachments,+ shared=bool(shared_text),+ ),)# Mark thread as active only when the mention carries actionable content.@@ -2282,7 +2299,8 @@ class SlackBot(BaseIMClient):"payload": payload,"is_dm": is_dm,},- is_ordinary_text=True,+ is_original_human_text=True,+ message_kind="original",)# Send immediate acknowledgment to Slackdiff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex 774d98424..b62388065 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -28,7 +28,11 @@ from .base import (InlineKeyboard,)from .formatters import TelegramFormatter-from .message_facts import is_ordinary_telegram_attachment, is_ordinary_telegram_text+from .message_facts import (+ is_original_human_telegram_attachment,+ is_original_human_telegram_text,+ telegram_message_kind,+)from . import telegram_apilogger = logging.getLogger(__name__)@@ -630,7 +634,9 @@ class TelegramBot(BaseIMClient):message_id=context.message_id,platform="telegram",files=context.files,- is_ordinary_text=context.is_ordinary_text,+ is_original_human_text=context.is_original_human_text,+ is_original_human_attachment=context.is_original_human_attachment,+ message_kind=context.message_kind,platform_specific={**payload,"is_topic_message": True,@@ -760,8 +766,9 @@ class TelegramBot(BaseIMClient):thread_id=str(thread_id) if thread_id is not None else None,message_id=str(message.get("message_id")),files=files,- is_ordinary_text=is_ordinary_telegram_text(message, files),- is_ordinary_attachment=is_ordinary_telegram_attachment(message, files),+ is_original_human_text=is_original_human_telegram_text(message, files),+ is_original_human_attachment=is_original_human_telegram_attachment(message, files),+ message_kind=telegram_message_kind(message, files),platform="telegram",platform_specific={"is_dm": chat.get("type") == "private",diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex f4cafa6d6..52c8ecce6 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -33,11 +33,12 @@ from vibe.i18n import t as i18n_tfrom vibe.proxy import resolve_proxyfrom modules.im import wechat_api as _wechat_api_modfrom modules.im import wechat_cdn as _wechat_cdn_mod-from modules.im.formatters.wechat_formatter import WeChatFormatterfrom modules.im.message_facts import (- is_ordinary_wechat_attachment,- is_ordinary_wechat_text,+ is_original_human_wechat_attachment,+ is_original_human_wechat_text,+ wechat_message_kind,)+from modules.im.formatters.wechat_formatter import WeChatFormatterlogger = logging.getLogger(__name__)@@ -1352,8 +1353,9 @@ class WeChatBot(BaseIMClient):# Handle media attachmentsawait self._process_media_items(msg, context)- context.is_ordinary_text = is_ordinary_wechat_text(msg, context.files)- context.is_ordinary_attachment = is_ordinary_wechat_attachment(msg, context.files)+ context.is_original_human_text = is_original_human_wechat_text(msg, context.files)+ context.is_original_human_attachment = is_original_human_wechat_attachment(msg, context.files)+ context.message_kind = wechat_message_kind(msg, context.files)# Authorization checkauth_result = self.check_authorization(diff --git a/packaging/avibe-memory/README.md b/packaging/avibe-memory/README.mdnew file mode 100644index 000000000..8c9b3debe--- /dev/null+++ b/packaging/avibe-memory/README.md@@ -0,0 +1,64 @@+# 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:++```console+pip install "avibe-os[memory]"+```++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.++## Distribution contract++Build the independent distribution from the repository root:++```console+python -m build packaging/avibe-memory+```++Both release workflows derive one package version from the release tag and use+that version to build an `avibe-memory` wheel and sdist alongside the matching+`avibe-os` wheel and sdist. They run the independent-content, metadata, and+core-only/core-plus-Memory installation matrix before staging release assets.++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.+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.++The package split changes distribution ownership only. The installed import+path remains `avibe_memory`, the host keeps its fixed loader and protocol+constant, and the EverOS artifact manifest remains available as+`vibe/memory_runtime_manifest.json`. Runtime, storage, configuration, and data+formats are unchanged, so a source-compatible Avibe release can load the same+persisted state. Release failures stop at the failed forward step; this contract+does not add automatic package rollback, a rollback plan, lifecycle reservation,+quarantine, a Gate 5 lifecycle verifier, or recovery bootstrap. Successful+upgrades follow the ordinary Avibe restart path. Package installation, upgrade,+and restart failures are structured terminal results and do not prevent a later+explicit attempt. Manifest/hash/fetch/verify and backup safeguards remain release+asset availability controls, not installed-package rollback machinery.diff --git a/packaging/avibe-memory/hatch_build.py b/packaging/avibe-memory/hatch_build.pynew file mode 100644index 000000000..24ebf55f0--- /dev/null+++ b/packaging/avibe-memory/hatch_build.py@@ -0,0 +1,48 @@+from __future__ import annotations++from pathlib import Path+from runpy import run_path++from hatchling.builders.hooks.plugin.interface import BuildHookInterface+++_ROOT = Path(__file__).resolve().parent+_HELPER = _ROOT / "hatch_exact_peer.py"+if not _HELPER.is_file():+ _HELPER = _ROOT.parents[1] / "hatch_exact_peer.py"+pin_peer_dependency = run_path(str(_HELPER))["pin_peer_dependency"]+++class CustomBuildHook(BuildHookInterface):+ PLUGIN_NAME = "custom"++ def initialize(self, version: str, build_data: dict) -> None:+ root = Path(self.root)+ repository_root = root.parents[1]+ source_root = root if (root / "avibe_memory").is_dir() else repository_root+ sources = {+ source_root / "vibe" / "memory_runtime_manifest.json": (+ "vibe/memory_runtime_manifest.json"+ ),+ }+ if source_root != root:+ sources[source_root / "avibe_memory"] = "avibe_memory"+ if self.target_name == "sdist":+ sources[_HELPER] = "hatch_exact_peer.py"+ missing = [str(path) for path in sources if not path.exists()]+ if missing:+ raise RuntimeError(+ "avibe-memory build sources are missing: " + ", ".join(missing)+ )+ force_include = build_data.setdefault("force_include", {})+ force_include.update({str(path): target for path, target in sources.items()})++ def finalize(self, version: str, build_data: dict, artifact_path: str) -> None:+ if version == "editable":+ return+ pin_peer_dependency(+ artifact_path,+ project_name="avibe-memory",+ peer_name="avibe-os",+ package_version=self.metadata.version,+ )diff --git a/packaging/avibe-memory/pyproject.toml b/packaging/avibe-memory/pyproject.tomlnew file mode 100644index 000000000..ede4f2f11--- /dev/null+++ b/packaging/avibe-memory/pyproject.toml@@ -0,0 +1,41 @@+[build-system]+requires = ["hatchling", "hatch-vcs", "tomlkit>=0.11.1"]+build-backend = "hatchling.build"++[project]+name = "avibe-memory"+dynamic = ["version"]+description = "Optional in-process Memory implementation for Avibe"+readme = "README.md"+license = "MIT"+requires-python = ">=3.10"+authors = [+ { name = "cyhhao", email = "[email protected]" }+]+classifiers = [+ "Development Status :: 4 - Beta",+ "Intended Audience :: Developers",+ "License :: OSI Approved :: MIT License",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.10",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+]+dependencies = [+ "avibe-os>=3.0.14.dev0,<3.1",+]++[project.urls]+Homepage = "https://github.com/avibe-bot/avibe"+Repository = "https://github.com/avibe-bot/avibe"+Documentation = "https://github.com/avibe-bot/avibe#readme"+Issues = "https://github.com/avibe-bot/avibe/issues"++[tool.hatch.version]+source = "vcs"++[tool.hatch.version.raw-options]+search_parent_directories = true++[tool.hatch.build.hooks.custom]diff --git a/pyproject.toml b/pyproject.tomlindex 5f41337a1..c5fa97aa1 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,5 +1,5 @@[build-system]-requires = ["hatchling", "hatch-vcs"]+requires = ["hatchling", "hatch-vcs", "tomlkit>=0.11.1"]build-backend = "hatchling.build"[project]@@ -78,6 +78,11 @@ dependencies = ["prometheus-client>=0.20.0",]+[project.optional-dependencies]+memory = [+ "avibe-memory>=3.0.14.dev0,<3.1",+]+[project.urls]Homepage = "https://github.com/avibe-bot/avibe"Repository = "https://github.com/avibe-bot/avibe"@@ -100,7 +105,6 @@ artifacts = ["vibe/show_runtime_manifest.json","vibe/tmux_runtime_manifest.json","vibe/git_runtime_manifest.json",- "vibe/memory_runtime_manifest.json","vibe/model_hub_runtime/cliproxyapi_manifest.json",]@@ -108,6 +112,7 @@ artifacts = [[tool.hatch.build.targets.wheel]packages = ["vibe", "config", "core", "modules", "storage"]+exclude = ["vibe/memory_runtime_manifest.json"][tool.hatch.build.targets.wheel.force-include]"main.py" = "vibe/service_main.py"@@ -122,6 +127,7 @@ include = ["modules/**","storage/**","hatch_build.py",+ "hatch_exact_peer.py","main.py","scripts/prepare_local_show_runtime_manifest.py","scripts/show_runtime_manifest_asset.py",@@ -129,11 +135,11 @@ include = ["vibe/show_runtime_manifest.json","vibe/tmux_runtime_manifest.json","vibe/git_runtime_manifest.json",- "vibe/memory_runtime_manifest.json","vibe/model_hub_runtime/cliproxyapi_manifest.json","README.md","LICENSE",]+exclude = ["vibe/memory_runtime_manifest.json"][tool.ruff]line-length = 120@@ -157,3 +163,6 @@ dev = ["pytest>=9.0.3","pytest-asyncio>=1.4.0",]++[tool.uv.sources]+avibe-memory = { path = "packaging/avibe-memory" }diff --git a/scripts/build_memory_runtime.py b/scripts/build_memory_runtime.pyindex 7a23ae421..9e8ed48c5 100644--- a/scripts/build_memory_runtime.py+++ b/scripts/build_memory_runtime.py@@ -22,7 +22,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))-from core.memory.artifact_contract import (+from avibe_memory.artifact_contract import (EMBEDDED_PYTHON_VERSION,EVEROS_VERSION,run_cold_artifact_admission,@@ -274,9 +274,9 @@ import asyncioimport sysfrom pathlib import Pathfrom types import SimpleNamespace-from core.memory.everos import EverOSPort-from core.memory.process import EverOSProcess, EverOSProcessSettings-from core.memory.provider_root import ProviderRoot, ProviderRootMetadata+from avibe_memory.everos import EverOSPort+from avibe_memory.process import EverOSProcess, EverOSProcessSettings+from avibe_memory.provider_root import ProviderRoot, ProviderRootMetadataasync def verify() -> None:effective_home = Path(sys.argv[2])diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.pyindex a62246c7b..64893777f 100644--- a/scripts/incus_regression_supervisor.py+++ b/scripts/incus_regression_supervisor.py@@ -11,7 +11,7 @@ from pathlib import Pathfrom config import pathsfrom config.v2_config import V2Config-from core.memory.ui_access import generate_ui_read_secret+from vibe.memory_ui_access import generate_ui_read_secretfrom scripts.incus_regression import SERVICE_HOME, regression_show_runtime_envfrom vibe import runtimediff --git a/scripts/memory_runtime_release_guard.py b/scripts/memory_runtime_release_guard.pyindex ec8153bb9..a91c112f2 100644--- a/scripts/memory_runtime_release_guard.py+++ b/scripts/memory_runtime_release_guard.py@@ -114,7 +114,7 @@ def load_release_spec(manifest_path: Path) -> ReleaseSpec:payload = json.loads(manifest_bytes)except (OSError, json.JSONDecodeError) as exc:raise ManifestPolicyError(f"cannot read Memory Runtime manifest: {exc}") from exc- if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ if not isinstance(payload, dict) or type(payload.get("schema_version")) is not int or payload["schema_version"] != 1:raise ManifestPolicyError("Memory Runtime manifest schema_version must be 1")everos_version = payload.get("everos_version")provenance = (diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 413ca8541..f02c815c6 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -10,17 +10,13 @@ from typing import Any, Iterable, Literalfrom sqlalchemy import Select, and_, func, or_, select, updatefrom sqlalchemy.engine import Connection+from core.delivery_target import normalize_message_kindfrom storage.delivery_states import (CLAIMABLE_QUEUE_STATES,FENCE_STATES,RUN_CANCEL_RETIRE_STATES,policy_for,)-from core.memory.admission_metadata import (- MEMORY_CLI_ADMITTED_METADATA,- MEMORY_ORDINARY_TEXT_METADATA,- MEMORY_USER_ID_METADATA,-)from storage.models import (agent_runs,agent_sessions,@@ -35,6 +31,77 @@ TURN_OWNER_STATES = ("starting", "active")WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA = "_web_push_authorization_contexts"+LEGACY_MEMORY_USER_ID_METADATA = "_memory_user_id"+LEGACY_MEMORY_ORDINARY_TEXT_METADATA = "_memory_ordinary_text"+LEGACY_MEMORY_CLI_ADMITTED_METADATA = "_memory_cli_admitted"+LEGACY_MEMORY_MERGE_IDENTITY_METADATA_KEYS = (+ LEGACY_MEMORY_USER_ID_METADATA,+ LEGACY_MEMORY_ORDINARY_TEXT_METADATA,+ LEGACY_MEMORY_CLI_ADMITTED_METADATA,+)+++def _legacy_memory_metadata(metadata: object) -> dict[str, Any]:+ return metadata if isinstance(metadata, dict) else {}+++def legacy_admitted_user_id(metadata: object) -> str | None:+ """Read the principal from a released pre-author_id Message row."""++ memory_user_id = _legacy_memory_metadata(metadata).get(+ LEGACY_MEMORY_USER_ID_METADATA+ )+ if not isinstance(memory_user_id, str) or not memory_user_id.strip():+ return None+ return memory_user_id.strip()+++def legacy_is_ordinary_text(metadata: object) -> bool:+ """Read the literal ordinary-text flag from a released Message row."""++ return (+ _legacy_memory_metadata(metadata).get(LEGACY_MEMORY_ORDINARY_TEXT_METADATA)+ is True+ )+++def legacy_is_cli_admitted(metadata: object) -> bool:+ """Read the literal CLI-admission flag from a released Message row."""++ return (+ _legacy_memory_metadata(metadata).get(LEGACY_MEMORY_CLI_ADMITTED_METADATA)+ is True+ )+++def legacy_memory_merge_identity(+ metadata: object,+) -> tuple[str | None, bool, bool]:+ """Return the released Memory facts that one dispatch kept singular."""++ return (+ legacy_admitted_user_id(metadata),+ legacy_is_ordinary_text(metadata),+ legacy_is_cli_admitted(metadata),+ )+++def legacy_message_kind(metadata: object) -> str:+ """Translate released `_memory_*` rows into the core message vocabulary."""++ metadata = _legacy_memory_metadata(metadata)+ if metadata.get("quick_reply_for"):+ return "quick_reply"+ if any(+ metadata.get(key)+ for key in ("forwarded", "is_forwarded", "forward_origin", "forwarded_from")+ ):+ return "forwarded"+ if metadata.get("edited"):+ return "edited"+ if metadata.get("is_system") or metadata.get("system"):+ return "system"+ return "original" if legacy_is_ordinary_text(metadata) else "unknown"def utc_now_iso() -> str:@@ -126,6 +193,7 @@ def message_snapshot(author_name: str | None = None,native_message_id: str | None = None,parent_native_message_id: str | None = None,+ message_kind: str | None = None,read_at: str | None = None,) -> dict[str, Any]:"""Build the immutable Message candidate held before native acceptance."""@@ -137,6 +205,11 @@ def message_snapshot(if source == "harness" and author == "user" and resolved_type == "user":author = "harness"resolved_type = "harness"+ filtered_metadata = {+ key: value+ for key, value in (metadata or {}).items()+ if not str(key).startswith("_memory_")+ }return {"scope_id": scope_id,"session_id": session_id,@@ -148,9 +221,10 @@ def message_snapshot("source": source,"native_message_id": native_message_id,"parent_native_message_id": parent_native_message_id,+ "message_kind": normalize_message_kind(message_kind),"content_text": text if text is not None else body.get("text") or None,"content_json": _canonical_json(body),- "metadata_json": _canonical_json(metadata or {}),+ "metadata_json": _canonical_json(filtered_metadata),"read_at": read_at,}@@ -358,6 +432,11 @@ def _delivery_payload_from_snapshot("author_name": snapshot.get("author_name"),"native_message_id": snapshot.get("native_message_id"),"parent_native_message_id": snapshot.get("parent_native_message_id"),+ "message_kind": (+ normalize_message_kind(snapshot.get("message_kind"))+ if "message_kind" in snapshot+ else legacy_message_kind(metadata)+ ),"text": snapshot.get("content_text") or content.get("text") or "","content": content,"metadata": metadata,@@ -417,13 +496,26 @@ _MESSAGE_MERGE_IDENTITY_FIELDS = ("author_id","author_name","parent_native_message_id",+ "message_kind",)def message_merge_identity(value: dict[str, Any]) -> tuple[Any, ...]:"""Return the Message fields that must stay singular after batching."""- return tuple(value.get(field) for field in _MESSAGE_MERGE_IDENTITY_FIELDS)+ metadata = value.get("metadata")+ if not isinstance(metadata, dict):+ metadata = _json_object(value.get("metadata_json"))+ kind = (+ normalize_message_kind(value.get("message_kind"))+ if "message_kind" in value+ else legacy_message_kind(metadata)+ )+ return (+ *(value.get(field) for field in _MESSAGE_MERGE_IDENTITY_FIELDS[:-1]),+ kind,+ legacy_memory_merge_identity(metadata),+ )def has_substantive_input(@@ -596,6 +688,7 @@ def enqueue_queued(author_id: str | None = None,author_name: str | None = None,native_message_id: str | None = None,+ message_kind: str | None = None,metadata: dict[str, Any] | None = None,now: str | None = None,) -> dict[str, Any]:@@ -620,6 +713,7 @@ def enqueue_queued(author_id=author_id,author_name=author_name,native_message_id=native_message_id,+ message_kind=message_kind,),dispatch_text=text if dispatch_text is None else dispatch_text,dedupe_key=native_dedupe_key(@@ -1152,29 +1246,8 @@ def _merged_initial_snapshot(deliveries: list[dict[str, Any]]) -> dict[str, Any]metadata = _json_object(first.get("metadata_json"))web_push_user_keys: list[str] = []authorization_contexts: dict[str, dict[str, Any]] = {}- memory_user_ids: list[str] = []- memory_metadata_present = False- memory_ordinary_text = True- memory_cli_admitted = Truefor snapshot in snapshots:snapshot_metadata = _json_object(snapshot.get("metadata_json"))- memory_metadata_present = memory_metadata_present or any(- key in snapshot_metadata- for key in (- MEMORY_USER_ID_METADATA,- MEMORY_ORDINARY_TEXT_METADATA,- MEMORY_CLI_ADMITTED_METADATA,- )- )- memory_user_id = str(snapshot_metadata.get(MEMORY_USER_ID_METADATA) or "").strip()- if memory_user_id and memory_user_id not in memory_user_ids:- memory_user_ids.append(memory_user_id)- memory_ordinary_text = memory_ordinary_text and (- snapshot_metadata.get(MEMORY_ORDINARY_TEXT_METADATA) is True- )- memory_cli_admitted = memory_cli_admitted and (- snapshot_metadata.get(MEMORY_CLI_ADMITTED_METADATA) is True- )values = [snapshot_metadata.get(WEB_PUSH_USER_KEY_METADATA)]plural = snapshot_metadata.get(WEB_PUSH_USER_KEYS_METADATA)if isinstance(plural, list):@@ -1197,13 +1270,6 @@ def _merged_initial_snapshot(deliveries: list[dict[str, Any]]) -> dict[str, Any]metadata[WEB_PUSH_USER_KEY_METADATA] = web_push_user_keys[0]elif web_push_user_keys:metadata[WEB_PUSH_USER_KEYS_METADATA] = web_push_user_keys- if memory_metadata_present:- metadata[MEMORY_ORDINARY_TEXT_METADATA] = memory_ordinary_text- metadata[MEMORY_CLI_ADMITTED_METADATA] = memory_cli_admitted- if len(memory_user_ids) == 1:- metadata[MEMORY_USER_ID_METADATA] = memory_user_ids[0]- else:- metadata.pop(MEMORY_USER_ID_METADATA, None)filtered_contexts = [contextfor user_key, context in authorization_contexts.items()diff --git a/tests/conftest.py b/tests/conftest.pyindex b9cf4ec37..abf976ab5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -44,6 +44,7 @@ write to ``~/.avibe/`` or legacy ``~/.vibe_remote/``).from __future__ import annotationsimport ast+import osimport shutilimport sqlite3import sys@@ -143,6 +144,25 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):if request.node.get_closest_marker("uses_real_paths"):returnmonkeypatch.delenv("AVIBE_HOME", raising=False)+ # Agent-launched pytest processes inherit the active conversation's caller+ # identity. Tests must opt in to that context explicitly or unrelated+ # Harness/session assertions can bind themselves to the live Agent session.+ for name in (+ "AVIBE_SESSION_ID",+ "AVIBE_RUN_ID",+ "AVIBE_NATIVE_SESSION_ID",+ "AVIBE_CALLER_SOURCE",+ "AVIBE_CALLER_BACKEND",+ "AVIBE_CALLER_PLATFORM",+ "AVIBE_CALLER_USER_ID",+ "AVIBE_CALLER_CHANNEL_ID",+ "AVIBE_CALLER_SESSION_KEY",+ "AVIBE_CALLER_MESSAGE_ID",+ "AVIBE_CALLER_WORKSPACE_ID",+ "AVIBE_CALLER_REMOTE",+ "AVIBE_CALLER_RESOURCE_CONTEXT",+ ):+ monkeypatch.delenv(name, raising=False)isolated_home = tmp_path / "home"monkeypatch.setattr(Path, "home", lambda: isolated_home)monkeypatch.setenv("HOME", str(isolated_home))@@ -306,8 +326,11 @@ def hold_migration_lock_elsewhere():@pytest.fixture(autouse=True)def _reset_memory_artifact_manager():"""Keep the managed Memory runtime bound to the current test home."""+ if os.environ.get("AVIBE_TEST_BLOCK_MEMORY_IMPORTS") == "1":+ yield+ returntry:- from core.memory.artifact import set_memory_artifact_manager_for_tests+ from avibe_memory.artifact import set_memory_artifact_manager_for_testsexcept Exception:yieldreturndiff --git a/tests/e2e/test_upgrade_command.py b/tests/e2e/test_upgrade_command.pyindex 8c3cc2d41..1df61b2fb 100644--- a/tests/e2e/test_upgrade_command.py+++ b/tests/e2e/test_upgrade_command.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport hashlibimport jsonimport os+import shleximport shutilimport subprocessimport sys@@ -35,12 +36,27 @@ def _docker_available() -> bool:return result.returncode == 0-def _build_test_wheel(fixtures_dir: Path, version: str) -> Path:+def _build_test_wheel(+ fixtures_dir: Path,+ version: str,+ *,+ project: Path = REPO_ROOT,+ distribution: str = "avibe_os",+) -> Path:env = os.environ.copy()env["SETUPTOOLS_SCM_PRETEND_VERSION"] = versionresult = subprocess.run(- [sys.executable, "-m", "pip", "wheel", ".", "--no-deps", "--wheel-dir", str(fixtures_dir)],+ [+ sys.executable,+ "-m",+ "pip",+ "wheel",+ str(project),+ "--no-deps",+ "--wheel-dir",+ str(fixtures_dir),+ ],cwd=REPO_ROOT,env=env,capture_output=True,@@ -49,7 +65,7 @@ def _build_test_wheel(fixtures_dir: Path, version: str) -> Path:)assert result.returncode == 0, result.stdout + result.stderr- wheel_path = fixtures_dir / f"avibe_os-{version}-py3-none-any.whl"+ wheel_path = fixtures_dir / f"{distribution}-{version}-py3-none-any.whl"assert wheel_path.exists(), f"Expected built wheel at {wheel_path}"return wheel_path@@ -70,7 +86,9 @@ def _released_initial_wheel(fixtures_dir: Path) -> Path:@pytest.mark.integration-def test_upgrade_command_bridges_released_3_0_13_generation():+def test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generation():+ """The released bundled-Memory upgrader converges onto the split package pair."""+if not _docker_available():pytest.skip("Docker is not available")@@ -78,6 +96,31 @@ def test_upgrade_command_bridges_released_3_0_13_generation():fixtures_dir = Path(tmpdir)initial_wheel_path = _released_initial_wheel(fixtures_dir)wheel_path = _build_test_wheel(fixtures_dir, TEST_RELEASE_VERSION)+ memory_wheel_path = _build_test_wheel(+ fixtures_dir,+ TEST_RELEASE_VERSION,+ project=REPO_ROOT / "packaging" / "avibe-memory",+ distribution="avibe_memory",+ )+ assert memory_wheel_path.exists()++ memory_payload = {+ "enabled": True,+ "mode": "custom",+ "processing": {+ "llm": {+ "base_url": "https://llm.example.test/v1",+ "model": "chat",+ "api_key": "test-key",+ },+ "embedding": {+ "base_url": "https://embedding.example.test/v1",+ "model": "embedding",+ "api_key": "test-key",+ },+ },+ }+ enable_memory = "from vibe import api; api.save_memory_config(" + repr(memory_payload) + ")"metadata_path = fixtures_dir / "metadata.json"metadata_path.write_text(json.dumps({"info": {"version": TEST_RELEASE_VERSION}}), encoding="utf-8")@@ -89,13 +132,18 @@ def test_upgrade_command_bridges_released_3_0_13_generation():"apt-get install -y --no-install-recommends curl ca-certificates bash procps >/dev/null","curl -LsSf https://astral.sh/uv/install.sh | sh",'export PATH="$HOME/.local/bin:$PATH"',+ 'export AVIBE_HOME="$HOME/.avibe-upgrade-test"',"VIBE_INSTALL_SKIP_NODE=1 VIBE_INSTALL_SKIP_SHOW_RUNTIME=1 "f"AVIBE_INSTALL_PACKAGE_SPEC=/fixtures/{initial_wheel_path.name} bash /work/install.sh",'export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"','initial_vibe="$(readlink -f "$HOME/.local/bin/vibe")"',+ 'initial_python="$(dirname "$initial_vibe")/python"','printf "%s\\n" "$initial_vibe" | grep "/uv/tools/"',"vibe version",- 'printf "preserved\\n" > "$HOME/.avibe/upgrade-state-marker"',+ '"$initial_python" -c "from config.v2_config import V2Config; V2Config.default().save()"',+ f'"$initial_python" -c {shlex.quote(enable_memory)}',+ '"$initial_python" -c "from config.v2_config import V2Config; assert V2Config.load().memory.enabled"',+ 'printf "preserved\\n" > "$AVIBE_HOME/upgrade-state-marker"',"AVIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json "f"VIBE_INSTALL_SKIP_SHOW_RUNTIME=1 AVIBE_UPGRADE_PACKAGE_SPEC=/fixtures/{wheel_path.name} vibe check-update","AVIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json "@@ -104,11 +152,28 @@ def test_upgrade_command_bridges_released_3_0_13_generation():'printf "launcher=%s\n" "$(command -v vibe)"',"vibe version",'test -x "$initial_vibe"',- 'test "$(cat "$HOME/.avibe/upgrade-state-marker")" = "preserved"',+ 'test "$(cat "$AVIBE_HOME/upgrade-state-marker")" = "preserved"',"AVIBE_UPDATE_METADATA_URL=file:///fixtures/metadata.json vibe check-update",+ 'upgraded_vibe="$(readlink -f "$(command -v vibe)")"',+ 'upgraded_python="$(dirname "$upgraded_vibe")/python"',+ '"$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","vibe",- "sleep 2",- "vibe status",+ "for attempt in $(seq 1 120); do "+ 'current_vibe="$(readlink -f "$(command -v vibe)")"; '+ 'current_python="$(dirname "$current_vibe")/python"; '+ f'if "$current_python" -c "from importlib.metadata import version; assert version(\'avibe-memory\') == \'{TEST_RELEASE_VERSION}\'" 2>/dev/null; '+ "then break; fi; sleep 1; done",+ '"$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}'\"",+ "for attempt in $(seq 1 120); do "+ 'status_output="$(vibe status 2>/dev/null || true)"; '+ "if printf '%s' \"$status_output\" | grep -q '\"running\": true'; then break; fi; sleep 1; done",+ "printf '%s\\n' \"$status_output\"",+ "printf '%s' \"$status_output\" | grep -q '\"running\": true'",])@@ -125,7 +190,7 @@ def test_upgrade_command_bridges_released_3_0_13_generation():"-v",f"{fixtures_dir}:/fixtures","-w",- "/work",+ "/tmp",BASE_IMAGE,"bash","-lc",diff --git a/tests/memory_import_blocker.py b/tests/memory_import_blocker.pynew file mode 100644index 000000000..82bcbce15--- /dev/null+++ b/tests/memory_import_blocker.py@@ -0,0 +1,62 @@+"""Pytest plugin proving core scenarios do not touch the Memory implementation."""++from __future__ import annotations++import importlib.abc+import os+import sys++import pytest+++class _AvibeMemoryImportBlocker(importlib.abc.MetaPathFinder):+ def __init__(self) -> None:+ self.attempted: list[str] = []++ def find_spec(self, fullname, path, target=None):+ del path, target+ if fullname == "avibe_memory" or fullname.startswith("avibe_memory."):+ self.attempted.append(fullname)+ raise ModuleNotFoundError(+ f"blocked optional Memory implementation: {fullname}"+ )+ return None+++_BLOCKER = _AvibeMemoryImportBlocker()+++def pytest_configure(config: pytest.Config) -> None:+ del config+ os.environ["AVIBE_TEST_BLOCK_MEMORY_IMPORTS"] = "1"+ loaded = [+ name+ for name in sys.modules+ if name == "avibe_memory" or name.startswith("avibe_memory.")+ ]+ if loaded:+ raise pytest.UsageError(+ f"avibe_memory loaded before import tracking started: {loaded}"+ )+ sys.meta_path.insert(0, _BLOCKER)+++def pytest_sessionfinish(+ session: pytest.Session,+ exitstatus: int,+) -> None:+ del exitstatus+ loaded = sorted(+ name+ for name in sys.modules+ if name == "avibe_memory" or name.startswith("avibe_memory.")+ )+ attempted = sorted(set(_BLOCKER.attempted))+ reporter = session.config.pluginmanager.get_plugin("terminalreporter")+ if reporter is not None:+ reporter.write_line(+ "MEMORY-INDEP-017 import tracking: "+ f"attempted={attempted} loaded={loaded}"+ )+ if attempted or loaded:+ session.exitstatus = pytest.ExitCode.TESTS_FAILEDdiff --git a/tests/memory_runtime_factory.py b/tests/memory_runtime_factory.pyindex f4eb56d55..9afda5c43 100644--- a/tests/memory_runtime_factory.py+++ b/tests/memory_runtime_factory.py@@ -9,13 +9,13 @@ from pathlib import Pathfrom typing import AsyncIterator, Callablefrom config.v2_config import MemoryConfig-from core.memory.artifact import MemoryArtifactPort-from core.memory.everos_insight.reader import MemoryInsightReader-from core.memory.process import EverOSProcessFactory-from core.memory.runtime import MemoryRuntime-from core.memory.supervisor import EverOSSupervisor-from core.memory.store import MemoryStore-from core.memory.runtime import ProcessingEvent+from avibe_memory.artifact import MemoryArtifactPort+from avibe_memory.everos_insight.reader import MemoryInsightReader+from avibe_memory.process import EverOSProcessFactory+from avibe_memory.runtime import MemoryRuntime+from avibe_memory.supervisor import EverOSSupervisor+from avibe_memory.store import MemoryStore+from avibe_memory.runtime import ProcessingEvent@dataclassdiff --git a/tests/scenario_harness/memory_im_attachments.py b/tests/scenario_harness/memory_im_attachments.pyindex 8b0e40f07..d2e0c1fbf 100644--- a/tests/scenario_harness/memory_im_attachments.py+++ b/tests/scenario_harness/memory_im_attachments.py@@ -2,20 +2,22 @@from __future__ import annotations+import asyncioimport base64import osfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom types import SimpleNamespace-from core.controller import Controller+from avibe_memory.capture_adapter import EnabledMemoryAdapter+from core.handlers.message_handler import memory_turn_eventfrom core.handlers.inbound_attachments import InboundAttachmentMaterializer-from core.memory.everos import FakeMemoryProvider, ProviderCapture-from core.memory.module import MIN_FREE_DISK_BYTES, MemoryModule-from core.memory.store import MemoryStore-from core.memory.types import MemoryItem+from avibe_memory.everos import FakeMemoryProvider, ProviderCapture+from avibe_memory.module import MIN_FREE_DISK_BYTES, MemoryModule+from avibe_memory.store import MemoryStore+from avibe_memory.types import MemoryItemfrom modules.im.base import FileAttachment, FileDownloadResult, MessageContext-from modules.im.message_facts import is_ordinary_slack_attachment, is_ordinary_slack_text+from modules.im.message_facts import is_original_human_slack_attachment, is_original_human_slack_textPRINCIPAL = "u-11111111111111111111111111111111"@@ -53,24 +55,17 @@ class _SlackDownloader:return FileDownloadResult(True)-class _UserStore:+class _Bindings:def __init__(self, *, bound: bool) -> None:self.bound = bound- def maybe_reload(self) -> None:- return None-- def get_user(self, _user_id: str, *, platform: str):- assert platform == "slack"- return SimpleNamespace(enabled=True) if self.bound else None+ def is_enabled_user(self, platform: str, user_id: str) -> bool:+ return platform == "slack" and user_id == "U1" and self.bound-class _SettingsManager:- def __init__(self, *, bound: bool) -> None:- self._store = _UserStore(bound=bound)-- def get_store(self) -> _UserStore:- return self._store+class _LifecycleAdmission:+ def release(self) -> None:+ return None@dataclass@@ -137,28 +132,27 @@ class MemoryIMAttachmentScenarioHarness:effective_home=self.home,)self.runtime = _Runtime(self.module, attachment_status=attachment_status)- self.controller = Controller.__new__(Controller)- multimodal = (- None- if attachment_status == "not_configured"- else SimpleNamespace(complete=lambda: True)- )- self.controller.config = SimpleNamespace(- memory=SimpleNamespace(- enabled=True,- processing=SimpleNamespace(multimodal=multimodal),- )- )- self.controller.platform_settings_managers = {- "slack": _SettingsManager(bound=bound)- }- self.controller.memory_runtime = self.runtime- self.controller.memory_module = self.module- self.controller.get_cwd = lambda _context: str(root / "project")+ self.bound = bound+ self.adapter = self._new_adapter()self.is_dm = is_dmself.downloader: _SlackDownloader | None = Noneself.last_context: MessageContext | None = None+ def _new_adapter(self) -> EnabledMemoryAdapter:+ return EnabledMemoryAdapter(+ module=self.module,+ principals=self.runtime,+ is_enabled_user=_Bindings(bound=self.bound).is_enabled_user,+ lifecycle_snapshot_matches=lambda _session_id, snapshot: snapshot == 1,+ acquire_lifecycle_admission=lambda _session_id: _completed(+ _LifecycleAdmission()+ ),+ attachment_capture_status=self.runtime.attachment_capture_status,+ attachment_config_generation=(+ self.runtime.attachment_capture_config_generation+ ),+ )+async def capture(self,*,@@ -203,8 +197,8 @@ class MemoryIMAttachmentScenarioHarness:message_id="native-1",platform_specific={"platform": "slack", "is_dm": self.is_dm},files=files,- is_ordinary_text=is_ordinary_slack_text(event, files),- is_ordinary_attachment=is_ordinary_slack_attachment(event, files),+ is_original_human_text=is_original_human_slack_text(event, files),+ is_original_human_attachment=is_original_human_slack_attachment(event, files),)self.last_context = contextself.downloader = _SlackDownloader(@@ -214,33 +208,31 @@ class MemoryIMAttachmentScenarioHarness:effective_home=self.home,attachments_root=self.home / "attachments",).materialize(context, self.downloader)- memory_lease = Nonetry:- reservation = self.controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- config_generation = getattr(reservation, "config_generation", None)- if config_generation is not None:- memory_lease = batch.lease.retain()- await self.controller.capture_user_memory(- context,- text,- "stable-session",- attachment_lease=memory_lease,- attachment_reservation=reservation,- attachment_config_generation=config_generation,+ self.adapter = self._new_adapter()+ assert self.adapter.start(task_factory=asyncio.create_task)+ self.adapter.offer(+ memory_turn_event(+ context,+ text,+ "stable-session",+ 1,+ batch.lease,+ ))batch.lease.adopt()finally:- if memory_lease is not None:- memory_lease.release()batch.lease.release()- # Deterministic synchronization is test-only; product lifecycle offers- # remain non-blocking and never expose a delivery drain.- await self.module.wait_writer_idle_for_tests()+ try:+ await self.adapter.wait_idle_for_tests()+ finally:+ await self.adapter.cancel_memory_capture_tasks()@propertydef memory_bundle_entries(self) -> tuple[Path, ...]:bundles = self.home / "memory" / "attachments" / "bundles"return tuple(bundles.iterdir()) if bundles.exists() else ()+++async def _completed(value: object) -> object:+ return valuediff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 1d95cd485..66ffc435d 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -75,6 +75,10 @@ capabilities:- tests/test_native_session_providers.py- tests/test_core_services_dispatch.py- tests/test_admin_notifications.py+ - tests/test_memory_loader.py+ - tests/test_local_deps.py+ - tests/test_memory_upgrade_packaged.py+ - tests/test_upgrade_flow.py- id: memory_im_attachment_capturename: Bound-DM attachment capture through EverOS multimodal ingeststatus: activediff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.pyindex 40c7c711b..a89c431cd 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py@@ -10,16 +10,16 @@ from types import SimpleNamespaceimport pytestfrom core.caller_context import AVIBE_SESSION_ID_ENV-from core.memory.admission import CaptureAdmission, InboundTurnFacts-from core.memory.attachments import AttachmentCleanupUnprovenError, AttachmentPinError-from core.memory.observations import AddAck, AddRejected-from core.memory.types import RecallItems, RecallPolicy, memory_item_payload+from avibe_memory.admission import CaptureAdmission, InboundTurnFacts+from avibe_memory.attachments import AttachmentCleanupUnprovenError, AttachmentPinError+from avibe_memory.observations import AddAck, AddRejected+from avibe_memory.types import RecallItems, RecallPolicy, memory_item_payloadfrom modules.im.base import FileAttachmentfrom modules.im.message_facts import (- is_ordinary_discord_attachment,- is_ordinary_feishu_attachment,- is_ordinary_telegram_attachment,- is_ordinary_wechat_attachment,+ is_original_human_discord_attachment,+ is_original_human_feishu_attachment,+ is_original_human_telegram_attachment,+ is_original_human_wechat_attachment,)from tests.scenario_harness.memory_im_attachments import (PNG_BYTES,@@ -41,7 +41,7 @@ def test_bound_slack_dm_attachment_reaches_search_with_provider_invocation(harness = MemoryIMAttachmentScenarioHarness(tmp_path)asyncio.run(harness.capture(- text="Remember this screenshot",+ text="记住这张截图",payloads={"screenshot.png": ("image/png", PNG_BYTES)},))@@ -51,6 +51,7 @@ def test_bound_slack_dm_attachment_reaches_search_with_provider_invocation({"name": "screenshot.png", "max_bytes": None}]assert len(harness.provider.captures) == 1+ assert harness.provider.captures[0].text == "记住这张截图"assert harness.provider.flushes == []assert harness.provider.observed_payloads == [PNG_BYTES]assert harness.provider.provider_invocations == ["multimodal_llm"]@@ -405,9 +406,9 @@ def _platform_attachment_fact(platform: str, file: FileAttachment) -> bool:message_snapshots=(),is_system=lambda: False,)- return is_ordinary_discord_attachment(message, [file])+ return is_original_human_discord_attachment(message, [file])if platform == "telegram":- return is_ordinary_telegram_attachment(+ return is_original_human_telegram_attachment({"from": {"id": "U1", "is_bot": False},"document": {"file_id": "native-file", "file_name": file.name},@@ -415,7 +416,7 @@ def _platform_attachment_fact(platform: str, file: FileAttachment) -> bool:[file],)if platform == "lark":- return is_ordinary_feishu_attachment(+ return is_original_human_feishu_attachment({"sender": {"sender_type": "user"},"message": {"message_type": "file"},@@ -424,7 +425,7 @@ def _platform_attachment_fact(platform: str, file: FileAttachment) -> bool:[file],shared_text=None,)- return is_ordinary_wechat_attachment(+ return is_original_human_wechat_attachment({"from_user_id": "U1","item_list": [@@ -480,7 +481,6 @@ def test_enabled_platform_attachment_fact_reaches_memory_admission(files=[file],is_dm=True,is_ordinary_attachment=_platform_attachment_fact(platform, file),- memory_enabled=True,)assert facts.is_ordinary_attachment is Truediff --git a/tests/scenarios/memory_independence/catalog.yaml b/tests/scenarios/memory_independence/catalog.yamlindex 4135e8aae..1f5b201f0 100644--- a/tests/scenarios/memory_independence/catalog.yaml+++ b/tests/scenarios/memory_independence/catalog.yaml@@ -13,6 +13,12 @@ capability:- tests/test_native_session_providers.py- tests/test_core_services_dispatch.py- tests/test_admin_notifications.py+ - tests/test_memory_disabled_isolation.py+ - tests/test_memory_loader.py+ - tests/test_local_deps.py+ - tests/test_memory_upgrade_packaged.py+ - tests/test_upgrade_flow.py+ - tests/scenarios/memory_independence/test_memory_package_shape.pycontract:dispatch: capture_must_not_fence_turn_startdestructive_ops: new_and_archive_fail_open_on_capture_timeout@@ -37,13 +43,13 @@ scenarios:status: coveredkind: correctnesslayer: scenario- test: tests/test_session_delivery_fsm.py::test_capture_admitted_before_new_is_discarded_after_transition+ test: tests/test_memory_adapter.py::test_worker_failure_and_stale_lifecycle_each_release_exactly_once- id: MEMORY-INDEP-003name: Idle-session capture still attributes while shutdown may drop volatile workstatus: coveredkind: regression_keeplayer: scenario- test: tests/test_session_delivery_fsm.py::test_idle_session_capture_attributes_while_shutdown_may_drop+ test: tests/test_memory_adapter.py::test_session_and_shutdown_cancellation_release_active_leases- id: MEMORY-INDEP-004name: Shared delivery imports do not load Memory implementationsstatus: covered@@ -61,13 +67,13 @@ scenarios:status: coveredkind: correctnesslayer: contract- test: tests/test_message_handler_typing.py::MessageHandlerTypingTests::test_text_memory_capture_setup_failure_is_best_effort+ test: tests/test_memory_adapter.py::test_capture_scheduling_failure_releases_retained_lease- id: MEMORY-INDEP-007name: Archive releases process-local Memory authorization after one non-blocking barrier offerstatus: coveredkind: guardraillayer: contract- test: tests/test_memory_slice3.py::test_archive_memory_cli_session_commits_without_waiting_on_memory+ test: tests/test_memory_slice3.py::test_archive_session_commits_then_offers_session_archived- id: MEMORY-INDEP-008name: Shutdown drops queued and tracked Memory work before closing the runtimestatus: covered@@ -85,7 +91,7 @@ scenarios:status: coveredkind: guardraillayer: scenario- test: tests/test_session_delivery_fsm.py::test_session_lifecycle_barrier_is_non_blocking_for_admitted_turn_capture+ test: tests/test_memory_adapter.py::test_reset_and_archive_events_preserve_barriers- id: MEMORY-INDEP-011name: Streaming waiters release lifecycle snapshots after handler admissionstatus: covered@@ -98,3 +104,57 @@ scenarios:kind: regression_keeplayer: contracttest: tests/test_admin_notifications.py::test_memory_indep_012_processing_events_stay_in_service_logs+ - id: MEMORY-INDEP-013+ name: Disabled fresh startup has no Memory runtime filesystem, task, or process side effects+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_memory_disabled_isolation.py::test_memory_indep_013_disabled_fresh_startup_has_no_runtime_side_effects+ - id: MEMORY-INDEP-014+ name: Disabled Controller startup succeeds while optional Memory implementation imports are blocked+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_memory_disabled_isolation.py::test_memory_indep_014_disabled_controller_starts_with_runtime_imports_blocked+ - id: MEMORY-INDEP-015+ name: Shutdown bounds capture cancellation, destructive settlement, and runtime close under one shared budget+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_memory_disabled_isolation.py::test_memory_indep_015_shutdown_bounds_all_memory_stages_under_one_budget+ - id: MEMORY-INDEP-016+ name: New queued rows use authenticated author and message kind without Memory-private metadata+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_session_delivery_fsm.py::test_memory_indep_016_new_queue_uses_core_identity_without_memory_metadata+ - id: MEMORY-INDEP-017+ name: Core workflows run without importing the optional Memory implementation package+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_memory_disabled_isolation.py::test_memory_indep_017_core_workflows_run_without_avibe_memory+ - id: MEMORY-INDEP-021+ name: Not-required and unreadable Memory status imports no optional implementation+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/test_local_deps.py::test_memory_indep_021_status_import_fence+ - id: MEMORY-INDEP-024+ name: Forward upgrades inspect Memory package shape without retired lifecycle imports+ status: covered+ kind: guardrail+ layer: scenario+ test: tests/scenarios/memory_independence/test_memory_package_shape.py::test_memory_indep_024_forward_package_shape_and_import_contract+ - id: MEMORY-INDEP-025+ name: A failed upgrade is terminal, has no compensating package mutation, and permits retry+ status: covered+ kind: correctness+ layer: scenario+ test: tests/test_upgrade_flow.py::test_memory_indep_025_failed_upgrade_is_terminal_and_retryable+ - id: MEMORY-INDEP-026+ name: An enabled bundled-Memory install automatically converges after its first split-package upgrade+ status: covered+ kind: compatibility+ layer: scenario+ test: tests/e2e/test_upgrade_command.py::test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generationdiff --git a/tests/scenarios/memory_independence/test_memory_independence_catalog.py b/tests/scenarios/memory_independence/test_memory_independence_catalog.pyindex db2510274..a1024936d 100644--- a/tests/scenarios/memory_independence/test_memory_independence_catalog.py+++ b/tests/scenarios/memory_independence/test_memory_independence_catalog.py@@ -17,7 +17,7 @@ def test_retained_memory_lifecycle_scenarios_do_not_depend_on_retired_delivery_a)assert "non-blocking" in scenario["name"].lower()assert scenario["test"].endswith(- "test_session_lifecycle_barrier_is_non_blocking_for_admitted_turn_capture"+ "test_reset_and_archive_events_preserve_barriers")test_source = (ROOT / "tests/test_session_delivery_fsm.py").read_text()@@ -28,3 +28,34 @@ def test_retained_memory_lifecycle_scenarios_do_not_depend_on_retired_delivery_a"SessionFlushCoordinator",)assert all(token not in test_source for token in retired_tokens)+++def test_memory_indep_021_catalog_points_to_executable_import_fence() -> None:+ catalog = yaml.safe_load(+ (ROOT / "tests/scenarios/memory_independence/catalog.yaml").read_text()+ )+ scenario = next(+ item for item in catalog["scenarios"] if item["id"] == "MEMORY-INDEP-021"+ )++ assert scenario["status"] == "covered"+ assert scenario["test"].endswith("test_memory_indep_021_status_import_fence")+ test_source = (ROOT / "tests/test_local_deps.py").read_text()+ assert "test_memory_indep_021_status_import_fence" in test_source+++def test_memory_indep_026_catalog_points_to_released_first_hop_upgrade() -> None:+ catalog = yaml.safe_load(+ (ROOT / "tests/scenarios/memory_independence/catalog.yaml").read_text()+ )+ scenario = next(+ item for item in catalog["scenarios"] if item["id"] == "MEMORY-INDEP-026"+ )++ assert scenario["status"] == "covered"+ assert scenario["test"].endswith(+ "test_memory_indep_026_upgrade_command_bridges_released_3_0_13_generation"+ )+ test_source = (ROOT / "tests/e2e/test_upgrade_command.py").read_text()+ assert "INITIAL_RELEASE_VERSION = \"3.0.13\"" in test_source+ assert "version('avibe-memory')" in test_sourcediff --git a/tests/scenarios/memory_independence/test_memory_package_shape.py b/tests/scenarios/memory_independence/test_memory_package_shape.pynew file mode 100644index 000000000..0962464c3--- /dev/null+++ b/tests/scenarios/memory_independence/test_memory_package_shape.py@@ -0,0 +1,167 @@+"""MEMORY-INDEP-024 forward package-shape and retired-import evidence."""++from __future__ import annotations++import ast+from importlib.metadata import PackageNotFoundError+from pathlib import Path++import pytest++from vibe.upgrade import memory_package_installed+++ROOT = Path(__file__).resolve().parents[3]+SHIPPED_SOURCE_ROOTS = ("main.py", "config", "core", "modules", "storage", "vibe")+FORWARD_PACKAGE_SHAPE_IMPORTS = {+ "CORE_PACKAGE_NAME",+ "LEGACY_CORE_PACKAGE_NAME",+ "MEMORY_PACKAGE_NAME",+}+++ ("metadata_result", "expected_present"),+ [+ pytest.param(object(), True, id="installed"),+ pytest.param(PackageNotFoundError(), False, id="absent"),+ pytest.param(OSError("unreadable"), True, id="unreadable"),+ ],+)+def test_memory_indep_024_forward_package_shape_and_import_contract(+ monkeypatch: pytest.MonkeyPatch,+ metadata_result: object,+ expected_present: bool,+) -> None:+ """Forward upgrades preserve installed Memory unless absence is certain."""++ def distribution(_name: str) -> object:+ if isinstance(metadata_result, BaseException):+ raise metadata_result+ return metadata_result++ monkeypatch.setattr("importlib.metadata.distribution", distribution)++ assert memory_package_installed() is expected_present++ package_shape_imports, reservation_imports = _production_imports()++ assert reservation_imports == []+ assert package_shape_imports == {+ "vibe/upgrade.py": FORWARD_PACKAGE_SHAPE_IMPORTS,+ }+++def _imported_modules(node: ast.Import | ast.ImportFrom) -> set[str]:+ if isinstance(node, ast.Import):+ return {alias.name for alias in node.names}++ module = node.module or ""+ imported = {module} if module else set()+ imported.update(+ f"{module}.{alias.name}".strip(".")+ for alias in node.names+ if alias.name != "*"+ )+ return imported+++def _package_shape_imported_names(node: ast.Import | ast.ImportFrom) -> set[str]:+ if isinstance(node, ast.ImportFrom) and (node.module or "").endswith(+ "package_shape"+ ):+ return {alias.name for alias in node.names}+ if any(module.endswith("package_shape") for module in _imported_modules(node)):+ return {"*"}+ return set()+++def _imports_retired_reservation(node: ast.Import | ast.ImportFrom) -> bool:+ return any(+ module.endswith("package_lifecycle_reservation")+ for module in _imported_modules(node)+ )+++ ("source", "expected_package_shape", "expected_reservation"),+ [+ pytest.param(+ "from vibe.package_shape import CORE_PACKAGE_NAME",+ {"CORE_PACKAGE_NAME"},+ False,+ id="package-shape-symbol",+ ),+ pytest.param(+ "from vibe import package_shape",+ {"*"},+ False,+ id="package-shape-parent",+ ),+ pytest.param(+ "from . import package_shape",+ {"*"},+ False,+ id="package-shape-relative-parent",+ ),+ pytest.param(+ "import vibe.package_lifecycle_reservation",+ set(),+ True,+ id="reservation-module",+ ),+ pytest.param(+ "from vibe.package_lifecycle_reservation import PackageLifecycleReservation",+ set(),+ True,+ id="reservation-symbol",+ ),+ pytest.param(+ "from vibe import package_lifecycle_reservation",+ set(),+ True,+ id="reservation-parent",+ ),+ pytest.param(+ "from . import package_lifecycle_reservation",+ set(),+ True,+ id="reservation-relative-parent",+ ),+ ],+)+def test_memory_indep_024_import_syntax_inventory(+ source: str,+ expected_package_shape: set[str],+ expected_reservation: bool,+) -> None:+ node = next(+ node+ for node in ast.walk(ast.parse(source))+ if isinstance(node, (ast.Import, ast.ImportFrom))+ )++ assert _package_shape_imported_names(node) == expected_package_shape+ assert _imports_retired_reservation(node) is expected_reservation+++def _production_imports() -> tuple[dict[str, set[str]], list[str]]:+ package_shape_imports: dict[str, set[str]] = {}+ reservation_imports: list[str] = []+ for root in SHIPPED_SOURCE_ROOTS:+ target = ROOT / root+ sources = [target] if target.is_file() else sorted(target.rglob("*.py"))+ for source in sources:+ relative = source.relative_to(ROOT).as_posix()+ tree = ast.parse(source.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ if not isinstance(node, (ast.Import, ast.ImportFrom)):+ continue+ imported_names = _package_shape_imported_names(node)+ if imported_names:+ package_shape_imports.setdefault(relative, set()).update(+ imported_names+ )+ if _imports_retired_reservation(node):+ reservation_imports.append(relative)+ return package_shape_imports, reservation_importsdiff --git a/tests/scenarios/memory_list/test_memory_list_scenarios.py b/tests/scenarios/memory_list/test_memory_list_scenarios.pyindex 0c860a2c7..2c8c044ad 100644--- a/tests/scenarios/memory_list/test_memory_list_scenarios.py+++ b/tests/scenarios/memory_list/test_memory_list_scenarios.py@@ -8,11 +8,11 @@ from collections import dequefrom datetime import datetime, timezonefrom core.caller_context import AVIBE_SESSION_ID_ENV-from core.memory.everos import AddAck, FakeMemoryProvider-from core.memory.module import MIN_FREE_DISK_BYTES, MemoryModule-from core.memory.runtime import MemoryRuntime-from core.memory.store import MemoryStore-from core.memory.types import CaptureAccepted, CaptureRequest, MemoryListItem, MemoryListPage+from avibe_memory.everos import AddAck, FakeMemoryProvider+from avibe_memory.module import MIN_FREE_DISK_BYTES, MemoryModule+from avibe_memory.runtime import MemoryRuntime+from avibe_memory.store import MemoryStore+from avibe_memory.types import CaptureAccepted, CaptureRequest, MemoryListItem, MemoryListPagefrom vibe import cli, internal_client@@ -103,7 +103,7 @@ def test_captured_processed_episodes_list_through_cli_with_exact_page_boundary(asyncio.run(_capture_and_process())runtime = object.__new__(MemoryRuntime)runtime._module = module- runtime._retired = False+ runtime._closing = Falsemonkeypatch.setenv(AVIBE_SESSION_ID_ENV, "ses-memory-list-scenario")def list_sync(*, project, page, limit, caller_session_id):@@ -193,7 +193,7 @@ def test_settings_can_browse_agent_episodes_without_crossing_owner_scopes(await module.wait_writer_idle_for_tests()runtime = object.__new__(MemoryRuntime)runtime._module = module- runtime._retired = False+ runtime._closing = Falsereturn (await runtime.list_episodes_payload(PRINCIPAL,diff --git a/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py b/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.pyindex d8c3cf4ce..c3b16ff6b 100644--- a/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py+++ b/tests/scenarios/memory_runtime_install/test_memory_runtime_install_scenarios.py@@ -12,9 +12,9 @@ from pathlib import Pathimport yamlfrom core import managed_runtime-from core.memory import artifact as memory_artifact-from core.memory.artifact import MemoryArtifactManager-from core.memory.artifact_contract import ColdArtifactAdmissionResult+from avibe_memory import artifact as memory_artifact+from avibe_memory.artifact import MemoryArtifactManager+from avibe_memory.artifact_contract import ColdArtifactAdmissionResultfrom tests.ui_server_test_helpers import csrf_headers, save_configfrom vibe import apifrom vibe.ui_server import appdiff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.pyindex d351f0a07..81fa1f0e6 100644--- a/tests/test_agent_run_target.py+++ b/tests/test_agent_run_target.py@@ -9,7 +9,7 @@ from sqlalchemy import event, selectfrom sqlalchemy.exc import OperationalErrorfrom core.services import sessions as sessions_service-from core.memory.store import derive_project_id+from avibe_memory.store import derive_project_idfrom core.services.agent_run_target import (resolve_agent_run_target,resolve_default_agent_workdir,diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.pyindex 3ec36e313..6a9d88ab7 100644--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@ -319,24 +319,66 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(len(controller.im_client.sent_messages), 1)- async def test_new_offers_memory_barrier_without_fencing_reset(self):+ async def test_new_uses_core_lifecycle_then_offers_session_reset(self):+ controller = _StubController({"display_name": "Alex"})+ calls = []++ class _Adapter:+ def offer(self, event):+ calls.append((type(event).__name__, event.session_id))++ class _TurnManager:+ async def run_session_lifecycle(+ self,+ raw_session_id,+ operation,+ *,+ deadline_seconds,+ ):+ self_outer.assertEqual(raw_session_id, "wechat_wx-chat")+ self_outer.assertEqual(deadline_seconds, 0.0)+ calls.append(("lifecycle", raw_session_id))+ return await operation()++ async def _clear_sessions(session_key):+ calls.append(("clear", session_key))+ return {}++ self_outer = self+ controller.memory_adapter = _Adapter()+ controller.session_turns = _TurnManager()+ controller.agent_service.clear_sessions = _clear_sessions # type: ignore[attr-defined]+ controller.run_memory_session_lifecycle = lambda *_args, **_kwargs: (_ for _ in ()).throw(+ AssertionError("/new must not use a Memory-named lifecycle wrapper")+ )+ handler = CommandHandlers(controller)+ context = MessageContext(+ user_id="wx-user",+ channel_id="wx-chat",+ platform="wechat",+ )++ await handler.handle_new(context)++ self.assertEqual(+ calls,+ [+ ("lifecycle", "wechat_wx-chat"),+ ("clear", "wechat::wx-chat"),+ ("SessionReset", "wechat_wx-chat"),+ ],+ )++ async def test_new_offers_session_reset_without_fencing_capture(self):controller = _StubController({"display_name": "Alex"})reset_entered = asyncio.Event()release_reset = asyncio.Event()capture_enqueued = asyncio.Event()calls = []- async def _run_lifecycle(- context,- raw_session_id,- operation,- *,- deadline_seconds,- ):- self.assertEqual(raw_session_id, "wechat_wx-chat")- self.assertEqual(deadline_seconds, 0.0)- calls.append(("barrier", context))- return await operation()+ class _Adapter:+ def offer(self, event):+ calls.append((type(event).__name__, event.session_id))async def _clear_sessions(session_key):calls.append(("clear", session_key))@@ -348,7 +390,7 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):calls.append(("capture", "wechat_wx-chat"))capture_enqueued.set()- controller.run_memory_session_lifecycle = _run_lifecycle+ controller.memory_adapter = _Adapter()controller.agent_service.clear_sessions = _clear_sessions # type: ignore[attr-defined]handler = CommandHandlers(controller)context = MessageContext(@@ -369,9 +411,9 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(calls,[- ("barrier", context),("clear", "wechat::wx-chat"),("capture", "wechat_wx-chat"),+ ("SessionReset", "wechat_wx-chat"),],)@@ -430,17 +472,19 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):controller = _StubController({"display_name": "Alex"})controller.config.language = language- async def _busy_lifecycle(- _context,- _raw_session_id,- _operation,- *,- deadline_seconds,- ):- self.assertEqual(deadline_seconds, 0.0)- raise error+ class _TurnManager:+ async def run_session_lifecycle(+ self,+ _raw_session_id,+ _operation,+ *,+ deadline_seconds,+ ):+ self_outer.assertEqual(deadline_seconds, 0.0)+ raise error- controller.run_memory_session_lifecycle = _busy_lifecycle+ self_outer = self+ controller.session_turns = _TurnManager()handler = CommandHandlers(controller)context = MessageContext(user_id="wx-user",@@ -463,9 +507,10 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):[("wx-chat", "❌ 清除会话时出错:provider unavailable")],)- async def test_new_does_not_offer_memory_for_a_fallback_session_anchor(self):+ async def test_new_does_not_offer_session_reset_for_a_fallback_anchor(self):controller = _StubController({"display_name": "Alex"})clear_base_calls = []+ events = []def _raise_for_missing_canonical_anchor(_context):raise RuntimeError("session identity unavailable")@@ -476,12 +521,18 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):(),{"clear_session_base": lambda _self, key, anchor: clear_base_calls.append((key, anchor)) or 1},)()+ controller.memory_adapter = type(+ "Adapter",+ (),+ {"offer": lambda _self, event: events.append(event)},+ )()handler = CommandHandlers(controller)context = MessageContext(user_id="U1", channel_id="C1", message_id="M1", platform="slack")await handler.handle_new(context)self.assertEqual(clear_base_calls, [("slack::C1", "slack_M1")])+ self.assertEqual(events, [])async def test_new_command_reports_paused_bound_definitions(self):"""D2 — `/new` pauses definitions pinned to the session it clears, and says so.@@ -676,21 +727,28 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):controller = _StubController({"display_name": "Alex"})setattr(controller.config, "platform", "telegram")controller.agent_service.clear_sessions = _clear_sessions # type: ignore[attr-defined]- flush_calls = []call_order = []- async def _run_lifecycle(- context,- raw_session_id,- operation,- *,- deadline_seconds,- ):- call_order.append("barrier")- flush_calls.append((context, raw_session_id, deadline_seconds))- return await operation()+ class _Adapter:+ def offer(self, event):+ call_order.append((type(event).__name__, event.session_id))- controller.run_memory_session_lifecycle = _run_lifecycle+ class _TurnManager:+ async def run_session_lifecycle(+ self,+ raw_session_id,+ operation,+ *,+ deadline_seconds,+ ):+ self_outer.assertEqual(raw_session_id, "telegram_-100123_1")+ self_outer.assertEqual(deadline_seconds, 0.0)+ call_order.append("lifecycle")+ return await operation()++ self_outer = self+ controller.memory_adapter = _Adapter()+ controller.session_turns = _TurnManager()controller.session_handler = type("SessionHandler",(),@@ -725,8 +783,10 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):[("-100123", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],)self.assertEqual(controller.im_client.sent_contexts[0].thread_id, "99")- self.assertEqual(flush_calls, [(context, "telegram_-100123_1", 0.0)])- self.assertEqual(call_order, ["barrier", "topic"])+ self.assertEqual(+ call_order,+ ["lifecycle", "topic", ("SessionReset", "telegram_-100123_1")],+ )async def test_slack_dm_start_skips_channel_info_lookup(self):controller = _StubController({"display_name": "Alex"})diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.pyindex e656131f4..efb6aa5bf 100644--- a/tests/test_controller_dispatch_loop.py+++ b/tests/test_controller_dispatch_loop.py@@ -372,14 +372,20 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:def __init__(self) -> None:self.closed = False- async def close(self) -> None:+ def begin_close(self) -> None:+ memory_adapter.quiesce_memory_capture_tasks()++ async def close(self, **_kwargs: object) -> None:+ await memory_adapter.cancel_memory_capture_tasks()assert stopped["capture"] is Trueself.closed = Truestopped["runtime"] = Truestop_order.append("memory-runtime")- class _MessageHandler:+ class _MemoryAdapter:def quiesce_memory_capture_tasks(self) -> None:+ if stopped["capture-registration"]:+ returnstopped["capture-registration"] = Truestop_order.append("capture-registration")@@ -392,7 +398,8 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:controller.runtime_work_supervisor = _Supervisor("supervisor")controller.watch_service = _WatchStopper("watch")controller.runtime_command_watcher = _Stopper("runtime")- controller.message_handler = _MessageHandler()+ memory_adapter = _MemoryAdapter()+ controller.memory_adapter = memory_adaptermemory_runtime = _MemoryRuntime()controller.memory_runtime = memory_runtime@@ -868,7 +875,10 @@ def test_cleanup_sync_cancels_memory_reconcile_before_closing_runtime() -> None:controller._join_memory_destructive_transactions = join_destructive_transactionsclass _MemoryRuntime:- async def close(self) -> None:+ def begin_close(self) -> None:+ assert reconcile_task.cancelled()++ async def close(self, **_kwargs: object) -> None:assert reconcile_task.cancelled()assert cleanup_order == ["destructive-transactions"]cleanup_order.append("runtime")diff --git a/tests/test_controller_memory_data_reset.py b/tests/test_controller_memory_data_reset.pyindex d5d353271..30899f49d 100644--- a/tests/test_controller_memory_data_reset.py+++ b/tests/test_controller_memory_data_reset.py@@ -1,6 +1,8 @@from __future__ import annotationsimport asyncio+import builtins+from contextlib import asynccontextmanagerfrom copy import deepcopyimport osimport stat@@ -16,8 +18,11 @@ from config.v2_config import (MemoryEndpointConfig,MemoryProcessingConfig,)+from config.memory_operation_lock import MemoryOperationLeasefrom core.controller import Controller-from core.memory.data_reset import reset_memory_data_roots+from avibe_memory.data_reset import reset_memory_data_roots+from core.memory_adapter import DisabledMemoryAdapter+from vibe.memory_contract import MemoryImplementationUnavailableError, MemoryRuntimeBusyErrorclass _Runtime:@@ -26,26 +31,39 @@ class _Runtime:home: Path,*,needs_repair: bool = False,- close_proved: bool = True,+ fail_stage: str | None = None,wake_result: dict[str, object] | None = None,) -> None:self.effective_home = homeself.needs_repair = needs_repair- self.closed = False- self.retired = False+ self.close_completed = False+ self.closing = Falseself.module = object()+ self.capture_adapter = DisabledMemoryAdapter()self._artifact_installing = False- self._close_proved = close_proved+ self._fail_stage = fail_stageself._wake_result = wake_result or {"ok": True, "state": "running"}self.events: list[str] = []self.marked_reason: str | None = Noneself.replacement_runtime: _Runtime | None = Noneself.replacement_configs: list[MemoryConfig] = []+ self.root_ownership = object()+ self.root_handoffs: list[object] = []+ self.root_released = Falseasync def prepare_data_reset(self) -> None:self.events.append("reap")- def replacement(self, config: MemoryConfig) -> _Runtime:+ def _fail_once(self, stage: str) -> None:+ if self._fail_stage == stage:+ self._fail_stage = None+ raise RuntimeError(f"{stage} failed")++ def start_capture_adapter(self, **_options: object) -> bool:+ return True++ def replacement(self, config: MemoryConfig, root_ownership: object) -> _Runtime:+ assert root_ownership is self.root_ownershipself.replacement_configs.append(config)if self.replacement_runtime is not None:return self.replacement_runtime@@ -54,37 +72,70 @@ class _Runtime:needs_repair=config.legacy_needs_repair,)- def retire(self) -> None:- self.events.append("retire")- self.retired = True+ def begin_close(self) -> None:+ if self.closing:+ return+ self.closing = True+ self.events.append("begin_close")++ def begin_root_ownership_handoff(self) -> object:+ self.begin_close()+ if self._fail_stage == "handoff":+ self._fail_stage = None+ raise MemoryRuntimeBusyError("Memory provider root ownership changed")+ self.root_handoffs.append(self.root_ownership)+ return self.root_ownership++ def accept_root_ownership(self) -> None:+ return None- async def close(self) -> None:+ async def close(+ self,+ *,+ root_ownership: object | None = None,+ timeout_seconds: float | None = None,+ ) -> None:+ del timeout_seconds+ if root_ownership is not None:+ assert root_ownership is self.root_ownershipself.events.append("close")- self.closed = self._close_proved+ self._fail_once("close")+ self.close_completed = Trueasync def wake(self, *, operation_lease_held: bool) -> dict[str, object]:assert operation_lease_held is Trueself.events.append("wake")return self._wake_result- async def settle_after_data_loss(self) -> None:- assert self.closed is True+ async def settle_after_data_loss(self, root_ownership: object) -> None:+ assert root_ownership is self.root_ownership+ assert self.close_completed is True+ self._fail_once("settle")self.events.append("settle")- def reset_mutable_data(self):- assert self.closed is True+ def reset_mutable_data(self, root_ownership: object):+ assert root_ownership is self.root_ownership+ assert self.close_completed is True+ self._fail_once("delete")self.events.append("delete")return reset_memory_data_roots(self.effective_home)+ def release_root_ownership(self, root_ownership: object) -> None:+ assert root_ownership is self.root_ownership+ self.root_released = True++ def release_retained_root_ownership(self) -> None:+ self.root_released = True+def mark_needs_repair(self, reason: str) -> None:self.marked_reason = reasonself.needs_repair = True-def _controller(runtime: _Runtime, *, enabled: bool = True) -> Controller:+def _controller(runtime: _Runtime | None, *, enabled: bool = True) -> Controller:controller = Controller.__new__(Controller)controller.memory_runtime = runtime- controller.memory_module = runtime.module+ controller.memory_module = runtime.module if runtime is not None else Nonecontroller.config = SimpleNamespace(memory=MemoryConfig(enabled=enabled))return controller@@ -104,6 +155,31 @@ def _persist(monkeypatch: pytest.MonkeyPatch, controller: Controller) -> None:monkeypatch.setattr("core.controller.atomic_update_memory", update)+async def test_reset_reaches_implementation_boundary_before_importing_reset_helpers(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ controller = Controller.__new__(Controller)++ @asynccontextmanager+ async def unavailable_runtime():+ raise MemoryImplementationUnavailableError("implementation missing")+ yield++ controller._memory_runtime_for_data_reset = unavailable_runtime+ real_import = builtins.__import__++ def block_reset_helper(name, *args, **kwargs):+ if name == "avibe_memory.data_reset":+ raise ModuleNotFoundError(name)+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", block_reset_helper)++ with pytest.raises(MemoryImplementationUnavailableError, match="implementation missing"):+ await controller._reset_memory_data_transaction(operation="delete_data")++def test_reset_memory_data_roots_deletes_only_exact_confined_roots(tmp_path: Path) -> None:_roots(tmp_path)memory_state = tmp_path / "state" / "memory" / "memory.sqlite"@@ -154,83 +230,83 @@ def test_reset_memory_data_roots_fails_closed_on_special_entry(tmp_path: Path) -assert stat.S_ISFIFO(os.lstat(unsafe).st_mode)+ ("needs_repair", "confirm_loss", "error"),+ (+ (True, False, "memory_loss_confirmation_required"),+ (False, True, "memory_repair_not_required"),+ ),+)@pytest.mark.asyncio-async def test_repair_requires_exact_loss_confirmation(tmp_path: Path) -> None:- """MEMORY-REPAIR-201: Repair requires exact accepted-loss authority."""-- runtime = _Runtime(tmp_path, needs_repair=True)- controller = _controller(runtime)-- result = await controller.repair_memory(confirm_loss=False)-- assert result == {- "ok": False,- "operation": "repair",- "error": "memory_loss_confirmation_required",- "result": "unchanged",- }- assert runtime.events == []---async def test_repair_is_not_offered_for_degraded_runtime(tmp_path: Path) -> None:- """MEMORY-REPAIR-201: degraded state grants no Repair authority."""+async def test_repair_requires_exact_loss_and_repair_authority(+ needs_repair: bool,+ confirm_loss: bool,+ error: str,+ tmp_path: Path,+) -> None:+ """MEMORY-REPAIR-201: Repair requires loss and needs-repair authority."""- runtime = _Runtime(tmp_path, needs_repair=False)+ runtime = _Runtime(tmp_path, needs_repair=needs_repair)controller = _controller(runtime)- result = await controller.repair_memory(confirm_loss=True)+ result = await controller.repair_memory(confirm_loss=confirm_loss)- assert result["error"] == "memory_repair_not_required"+ assert result["error"] == errorassert runtime.events == [][email protected]("failure_stage", (None, "handoff", "close", "settle", "delete"))@pytest.mark.asyncio-async def test_repair_stops_owned_runtime_before_delete_and_proves_native_readiness(+async def test_repair_reuses_retained_owner_until_reset_proves(+ failure_stage: str | None,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """MEMORY-REPAIR-202: Repair proves stop, reset, and native readiness."""+ """MEMORY-REPAIR-202/203: failed reset phases retain or recover one owner."""_roots(tmp_path)- runtime = _Runtime(tmp_path, needs_repair=True)+ runtime = _Runtime(+ tmp_path,+ needs_repair=True,+ fail_stage=failure_stage,+ )+ if failure_stage == "handoff":+ runtime.closing = Truefresh = _Runtime(tmp_path)runtime.replacement_runtime = freshcontroller = _controller(runtime)_persist(monkeypatch, controller)- events = runtime.events-- result = await controller.repair_memory(confirm_loss=True)+ if failure_stage == "delete":+ with pytest.raises(RuntimeError, match="delete failed"):+ await controller.repair_memory(confirm_loss=True)+ else:+ first = await controller.repair_memory(confirm_loss=True)+ if failure_stage is None:+ result = first+ elif failure_stage == "handoff":+ assert first["error"] == "memory_operation_in_progress"+ else:+ assert first["ok"] is False+ assert first["state"] == "needs_repair"+ if failure_stage is not None:+ if failure_stage == "handoff":+ assert controller.memory_runtime is None+ assert runtime.root_released is True+ controller._create_memory_runtime = lambda *_args, **_kwargs: runtime+ else:+ assert controller.memory_runtime is runtime+ assert runtime.root_released is False+ assert fresh.events == []+ result = await controller.repair_memory(confirm_loss=True)assert result["ok"] is Trueassert result["state"] == "running"- assert events == ["reap", "retire", "close", "settle", "delete"]+ assert all(token is runtime.root_ownership for token in runtime.root_handoffs)+ assert len(runtime.root_handoffs) == (1 if failure_stage in {None, "handoff"} else 2)assert fresh.events == ["wake"]assert controller.memory_runtime is fresh-async def test_repair_deletes_nothing_when_termination_is_unproved(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """MEMORY-REPAIR-203: failed termination proof grants no deletion."""-- _roots(tmp_path)- runtime = _Runtime(tmp_path, needs_repair=True, close_proved=False)- controller = _controller(runtime)- _persist(monkeypatch, controller)- result = await controller.repair_memory(confirm_loss=True)-- assert result["ok"] is False- assert result["reason"] == "runtime_termination_unproved"- assert result["state"] == "needs_repair"- assert result["data_deleted"] is False- assert "delete" not in runtime.events- assert runtime.marked_reason == "memory_repair_failed"- assert (tmp_path / "memory").is_dir()--@pytest.mark.asyncioasync def test_external_post_reset_wake_failure_remains_degraded(tmp_path: Path,@@ -296,25 +372,42 @@ async def test_local_post_reset_wake_failure_remains_needs_repair(@pytest.mark.asyncio-async def test_delete_data_has_distinct_intent_but_reuses_reset(+async def test_delete_data_lazily_constructs_runtime_after_disabled_restart(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:- """MEMORY-DELETE-DATA-001: explicit deletion uses the shared reset."""-_roots(tmp_path)runtime = _Runtime(tmp_path)- fresh = _Runtime(tmp_path)- runtime.replacement_runtime = freshcontroller = _controller(runtime, enabled=False)+ controller.memory_runtime = None+ controller.memory_module = None+ controller.memory_adapter = DisabledMemoryAdapter()+ created: list[MemoryConfig] = []+ loader_flags: list[bool] = []++ def create_memory_runtime(+ config: MemoryConfig,+ **kwargs: object,+ ) -> _Runtime:+ created.append(config)+ loader_flags.append(bool(kwargs["allow_disabled"]))+ return runtime++ monkeypatch.setattr(controller, "_create_memory_runtime", create_memory_runtime)_persist(monkeypatch, controller)+result = await controller.delete_memory_data(confirm_loss=True)assert result["ok"] is Trueassert result["operation"] == "delete_data"assert result["state"] == "disabled"assert result["data_deleted"] is True- assert fresh.events == []+ assert created == [controller.config.memory]+ assert loader_flags == [True]+ assert controller.memory_runtime is None+ assert controller.memory_module is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+ assert runtime.replacement_configs == []@pytest.mark.asyncio@@ -332,7 +425,9 @@ async def test_partial_deletion_persists_repair_fence(assert result["result"] == "partial"assert result["state"] == "needs_repair"assert controller.config.memory.legacy_needs_repair is True- assert runtime.replacement_configs[0].legacy_needs_repair is True+ assert runtime.replacement_configs == []+ assert controller.memory_runtime is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)@pytest.mark.asyncio@@ -439,12 +534,16 @@ async def test_reconfigure_accepts_scope_release_acknowledgement(][email protected]("write_failure", ("stale", "error"))@pytest.mark.asyncio-async def test_reconfigure_rejects_a_stale_memory_snapshot(+async def test_reconfigure_fence_failure_restores_exact_enabled_runtime(+ write_failure: str,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:runtime = _Runtime(tmp_path)+ fresh = _Runtime(tmp_path)+ runtime.replacement_runtime = freshcontroller = _controller(runtime)expected = controller.config.memorytarget = MemoryConfig(enabled=True)@@ -455,10 +554,16 @@ async def test_reconfigure_rejects_a_stale_memory_snapshot()def update(transform):+ if write_failure == "error":+ raise OSError("write failed")concurrent = MemoryConfig(enabled=False)return SimpleNamespace(memory=transform(concurrent))monkeypatch.setattr("core.controller.atomic_update_memory", update)+ monkeypatch.setattr(+ "core.controller.V2Config.load",+ classmethod(lambda cls: SimpleNamespace(memory=expected)),+ )result = await controller.reconfigure_memory(target,@@ -466,13 +571,100 @@ async def test_reconfigure_rejects_a_stale_memory_snapshot(confirm_loss=True,)+ assert result["ok"] is False+ assert result["error"] == (+ "memory_operation_in_progress"+ if write_failure == "stale"+ else "memory_reconfigure_failed"+ )+ assert result["state"] == "running"+ assert runtime.events == ["reap", "begin_close", "close"]+ assert runtime.replacement_configs == [expected]+ assert fresh.events == ["wake"]+ assert controller.memory_runtime is fresh+++async def test_unpublished_reset_blocks_concurrent_enable_before_construction(+ tmp_path: Path,+) -> None:+ controller = _controller(None, enabled=False)+ controller.memory_adapter = DisabledMemoryAdapter()+ controller._memory_implementation_error = None+ runtime = _Runtime(tmp_path)+ reset_started = asyncio.Event()+ reset_release = asyncio.Event()+ lease = threading.Lock()+ construction_calls: list[object] = []++ async def try_lease(_effective_home=None):+ if not lease.acquire(blocking=False):+ return None+ return SimpleNamespace(release=lease.release)++ async def prepare_data_reset() -> None:+ reset_started.set()+ await reset_release.wait()++ runtime.prepare_data_reset = prepare_data_reset+ controller._try_memory_operation_lease = try_lease+ controller._create_memory_runtime = lambda config, **_kwargs: (+ construction_calls.append(config) or runtime+ )+ reset = asyncio.create_task(+ controller._reset_memory_data_transaction(operation="delete_data")+ )+ await reset_started.wait()++ assert await controller.reconcile_memory(MemoryConfig(enabled=True)) == {+ "ok": False,+ "error": "memory_operation_in_progress",+ }+ assert construction_calls == [controller.config.memory]+ assert controller.memory_runtime is None++ reset.cancel()+ reset_release.set()+ with pytest.raises(asyncio.CancelledError):+ await reset+ assert runtime.close_completed is True+++async def test_reset_lost_runtime_writes_no_fence_and_leaves_replacement(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runtime = _Runtime(tmp_path)+ replacement = _Runtime(tmp_path)+ controller = _controller(runtime)+ replacement_adapter = object()++ async def lose_expected_runtime() -> None:+ runtime.events.append("reap")+ controller.memory_runtime = replacement+ controller.memory_module = replacement.module+ controller.memory_adapter = replacement_adapter++ runtime.prepare_data_reset = lose_expected_runtime+ monkeypatch.setattr(+ "core.controller.atomic_update_memory",+ lambda _transform: pytest.fail("lost ownership must not persist a fence"),+ )++ result = await controller.delete_memory_data(confirm_loss=True)+assert result == {"ok": False,- "operation": "reconfigure",+ "operation": "delete_data","error": "memory_operation_in_progress","result": "unchanged",}assert runtime.events == ["reap"]+ assert replacement.events == []+ assert controller.memory_runtime is replacement+ assert controller.memory_module is replacement.module+ assert controller.memory_adapter is replacement_adapter@pytest.mark.asyncio@@ -523,7 +715,7 @@ async def test_reconfigure_does_not_overwrite_a_change_racing_with_deletion(@pytest.mark.asyncio-async def test_cancelled_reset_joins_deletion_before_releasing_exclusion(+async def test_reset_disable_and_cancellation_retain_owner_until_settlement(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,) -> None:@@ -531,46 +723,48 @@ async def test_cancelled_reset_joins_deletion_before_releasing_exclusion(runtime = _Runtime(tmp_path)fresh = _Runtime(tmp_path)runtime.replacement_runtime = fresh- controller = _controller(runtime, enabled=False)+ controller = _controller(runtime)+ enabled = controller.config.memory_persist(monkeypatch, controller)deletion_started = threading.Event()allow_deletion_to_finish = threading.Event()- lease_events: list[str] = []- class Lease:- def __init__(self, _home: Path) -> None:- pass-- def acquire(self) -> None:- lease_events.append("acquire")-- def release(self) -> None:- lease_events.append("release")-- def blocking_reset():+ def blocking_reset(_root_ownership: object):runtime.events.append("delete")deletion_started.set()allow_deletion_to_finish.wait(timeout=5)return reset_memory_data_roots(tmp_path)runtime.reset_mutable_data = blocking_reset- monkeypatch.setattr("core.controller.MemoryOperationLease", Lease)task = asyncio.create_task(controller.delete_memory_data(confirm_loss=True))assert await asyncio.to_thread(deletion_started.wait, 2)+ disabled = MemoryConfig(enabled=False)+ assert await controller.reconcile_memory(disabled) == {+ "ok": False,+ "state": "disabled",+ "error": "memory_operation_in_progress",+ }+ assert controller.config.memory == enabledtask.cancel()await asyncio.sleep(0.05)assert task.done() is False- assert lease_events == ["acquire"]assert len(controller._memory_destructive_tasks) == 1allow_deletion_to_finish.set()with pytest.raises(asyncio.CancelledError):await task- assert lease_events == ["acquire", "release"]+ lease = MemoryOperationLease(tmp_path)+ lease.acquire()+ lease.release()assert controller._memory_destructive_tasks == set()- assert runtime.events == ["reap", "retire", "close", "settle", "delete"]+ assert runtime.events == ["reap", "begin_close", "close", "settle", "delete"]assert controller.memory_runtime is fresh+ assert controller.memory_module is fresh.module+ assert controller.config.memory == enabled+ assert controller.memory_adapter is fresh.capture_adapter+ assert runtime.replacement_configs == [enabled]+ assert runtime.root_released is False@pytest.mark.asynciodiff --git a/tests/test_discord_reply_anchor.py b/tests/test_discord_reply_anchor.pyindex 04d8bcf12..b29d5da30 100644--- a/tests/test_discord_reply_anchor.py+++ b/tests/test_discord_reply_anchor.py@@ -179,7 +179,7 @@ class DiscordReplyAnchorTests(unittest.IsolatedAsyncioTestCase):discord_module.discord.Thread = original_threadbot.on_message_callback.assert_awaited_once()- self.assertTrue(bot.on_message_callback.await_args.args[0].is_ordinary_text)+ self.assertTrue(bot.on_message_callback.await_args.args[0].is_original_human_text)self.assertEqual(bot.on_message_callback.await_args.args[1], "scheduled follow-up context")async def test_native_file_message_publishes_ordinary_attachment_fact(self):@@ -221,7 +221,7 @@ class DiscordReplyAnchorTests(unittest.IsolatedAsyncioTestCase):bot.on_message_callback.assert_awaited_once()context = bot.on_message_callback.await_args.args[0]- self.assertIs(context.is_ordinary_attachment, True)+ self.assertIs(context.is_original_human_attachment, True)async def test_send_auth_denial_acknowledges_silent_interaction_denial(self):bot = object.__new__(DiscordBot)diff --git a/tests/test_fake_memory_provider.py b/tests/test_fake_memory_provider.pyindex 64fe36b73..374ed1aa0 100644--- a/tests/test_fake_memory_provider.py+++ b/tests/test_fake_memory_provider.py@@ -5,14 +5,14 @@ from collections import dequeimport pytest-from core.memory.everos import (+from avibe_memory.everos import (AddAck,FakeMemoryProvider,FlushSucceeded,MemoryProviderPort,ProviderCapture,)-from core.memory.types import MemoryListItem, MemoryListPage, ProviderSessionRef+from avibe_memory.types import MemoryListItem, MemoryListPage, ProviderSessionRefSESSION_REF = ProviderSessionRef(diff --git a/tests/test_feishu_post_messages.py b/tests/test_feishu_post_messages.pyindex 8d162ae94..fdd7bb6d0 100644--- a/tests/test_feishu_post_messages.py+++ b/tests/test_feishu_post_messages.py@@ -127,12 +127,12 @@ class FeishuPostMessageTests(unittest.IsolatedAsyncioTestCase):args = bot.on_message_callback.await_args.argscontext, text = argsself.assertEqual(text, "日报\nhello\n[image]")- self.assertFalse(context.is_ordinary_text)+ self.assertFalse(context.is_original_human_text)self.assertIsNotNone(context.files)assert context.files is not Noneself.assertEqual(len(context.files), 1)self.assertEqual(context.files[0].name, "img_123.image")- self.assertIs(context.is_ordinary_attachment, False)+ self.assertIs(context.is_original_human_attachment, False)async def test_native_file_message_publishes_lark_attachment_fact(self):bot = self._make_bot()@@ -160,7 +160,7 @@ class FeishuPostMessageTests(unittest.IsolatedAsyncioTestCase):bot.on_message_callback.assert_awaited_once()context = bot.on_message_callback.await_args.args[0]self.assertEqual(context.platform, "lark")- self.assertIs(context.is_ordinary_attachment, True)+ self.assertIs(context.is_original_human_attachment, True)async def test_active_thread_requires_fresh_mention_when_require_mention_enabled(self):bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret", require_mention=True))diff --git a/tests/test_github_release.py b/tests/test_github_release.pyindex 2657f170d..02b673b79 100644--- a/tests/test_github_release.py+++ b/tests/test_github_release.py@@ -443,7 +443,7 @@ def test_release_workflows_stage_then_finalize_once() -> None:assert "python release-automation/scripts/github_release.py ensure-draft" in publishassert "path: release-automation" in publishassert "ref: ${{ needs.resolve-tag.outputs.workflow_sha }}" in publish- assert publish.index("- name: Build package") < publish.index(+ assert publish.index("- name: Build Python distributions") < publish.index("- name: Checkout release automation")assert "finalize-github-release:" in publish@@ -451,12 +451,22 @@ def test_release_workflows_stage_then_finalize_once() -> None:assert "--run-sha \"${{ needs.resolve-tag.outputs.workflow_sha }}\"" in publishassert "--source-sha \"${{ needs.resolve-tag.outputs.source_sha }}\"" in publishassert "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(+ " publish-avibe-os:", 1+ )[0]avibe_publish = publish.split(" publish-avibe-os:", 1)[1].split(" publish-vibe-remote:", 1)[0]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_publishassert "- finalize-github-release" in avibe_publishassert "- finalize-github-release" in legacy_publishdiff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.pyindex 4c391de3d..3c5bb929f 100644--- a/tests/test_i18n_backend_keys.py+++ b/tests/test_i18n_backend_keys.py@@ -23,7 +23,7 @@ from core.failure_notices import (NOTICE_REASON_UNKNOWN_I18N_KEY,PER_FIRE_INTERRUPT_REASONS,)-from core.memory.types import CLOSED_MEMORY_ERROR_CODES+from vibe.memory_contract import CLOSED_MEMORY_ERROR_CODESfrom core.run_settlement import (RUN_INTERRUPTION_REASONS,SETTLEMENT_I18N_KEYS,diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pyindex 96c46f134..3ef450257 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -449,7 +449,7 @@ def test_memory_archive_session_round_trip_uses_only_session_identity(socket_patdef test_memory_recovery_reads_round_trip_signed_operator(monkeypatch, socket_path):- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accesscaptured: list[httpx.Request] = []monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")@@ -588,7 +588,7 @@ def test_memory_list_sync_forwards_page_project_and_caller_session(socket_path):def test_memory_list_async_signs_ui_aggregate_cursor(monkeypatch, socket_path):- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accessmonkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")captured: dict[str, object] = {}@@ -636,7 +636,7 @@ def test_memory_list_async_signs_ui_aggregate_cursor(monkeypatch, socket_path):def test_memory_ui_read_helper_signs_the_fixed_local_owner(monkeypatch, socket_path):- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accesscaptured: dict[str, str] = {}monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")@@ -680,7 +680,7 @@ def test_memory_destructive_clients_sign_owner_and_post_exact_loss_confirmation(operation,path,):- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accesscaptured: dict[str, object] = {}monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")@@ -761,7 +761,7 @@ def test_memory_reconfigure_forwards_candidate_and_expected_snapshot(monkeypatch: pytest.MonkeyPatch,socket_path,) -> None:- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accesscaptured: dict[str, object] = {}monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")@@ -825,7 +825,7 @@ def test_memory_wake_maps_read_transport_errors_to_unavailable(def test_memory_processing_record_helpers_forward_query_and_sign_owner(monkeypatch, socket_path):- from core.memory import ui_access+ from vibe import memory_ui_access as ui_accesscaptured: list[httpx.Request] = []monkeypatch.setattr(ui_access, "_process_secret", "test-ui-controller-secret")diff --git a/tests/test_internal_client_timeouts.py b/tests/test_internal_client_timeouts.pyindex 7da557915..aecc41bfd 100644--- a/tests/test_internal_client_timeouts.py+++ b/tests/test_internal_client_timeouts.py@@ -13,20 +13,22 @@ import inspectimport refrom pathlib import Path-from core.memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS-from core.memory.module import PROVIDER_READ_TIMEOUT_SECONDS-from core.memory.everos import PROCESSING_PROBE_MAX_DEADLINE_SECONDS-from core.memory.types import MAX_AGENTIC_TIMEOUT_SECONDS-from core.memory.processing_record import (+from avibe_memory.confined_filesystem import PRIVATE_SQLITE_BUSY_TIMEOUT_SECONDS+from avibe_memory.module import PROVIDER_READ_TIMEOUT_SECONDS+from avibe_memory.everos import PROCESSING_PROBE_MAX_DEADLINE_SECONDS+from avibe_memory.processing_record import (PROCESSING_RECORD_TRANSPORT_MARGIN_SECONDS,- PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS,PROCESSING_RECORD_WORK_TIMEOUT_SECONDS,)-from core.memory.process import (+from avibe_memory.process import (_PROCESSING_PROBE_TIMEOUT_SECONDS,_STARTUP_TIMEOUT_SECONDS,_STOP_TIMEOUT_SECONDS,)+from vibe.memory_contract import (+ MAX_AGENTIC_TIMEOUT_SECONDS,+ PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS,+)ADD_TIMEOUT_SECONDS = 30.0from vibe.internal_client import (MEMORY_FAILURES_TIMEOUT_SECONDS,diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex b77e15c53..fae85b2f3 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -16,7 +16,10 @@ We exercise three layers:from __future__ import annotationsimport asyncio+import ast+import builtinsimport contextlib+import inspectimport socketimport sysimport tempfile@@ -34,9 +37,14 @@ from sqlalchemy import selectsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core import internal_server, session_turns+from core.controller import Controllerfrom core.message_context import build_context_turn_sink_keyfrom core.vibe_agents import VibeAgentStore-from core.memory.runtime import MemoryStoreUnavailableError+from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryStoreUnavailableError,+)from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULTfrom core.services.agent_steering import SteerOutcome, result as steer_resultfrom core.services.dispatch import (@@ -48,6 +56,7 @@ from core.services.dispatch import (from modules.im import MessageContextfrom storage import message_deliveries, resource_access_servicefrom vibe.authorization import AuthorizationContext+from config.v2_config import MemoryConfig# ---------------------------------------------------------------------@@ -129,6 +138,7 @@ def _reserve_submission(content: dict | None = None,metadata: dict | None = None,native_message_id: str | None = None,+ message_kind: str | None = None,):delivery_id = message_deliveries.new_delivery_id()row = message_deliveries.insert_delivery(@@ -149,6 +159,7 @@ def _reserve_submission(metadata=metadata,author_name=author_name,native_message_id=native_message_id,+ message_kind=message_kind,),dispatch_text=text,dedupe_key=(@@ -353,9 +364,349 @@ def _build_controller_double(handler=None):# ``_t`` returns the key verbatim so refusal chunks stay JSON-serializable# (a bare MagicMock would blow up ``json.dumps`` in ``_sse_event``).controller._t = lambda key, **kwargs: key+ controller.config = SimpleNamespace(memory=MemoryConfig(enabled=True))+ controller.memory_adapter = None+ controller.memory_runtime = None+ controller.memory_module = None+ controller._memory_reconcile_task = None+ controller._memory_disabled_cleanup_task = None+ controller._memory_disabled_cleanup_unproved = False+ controller._memory_replacement_gate = None+ controller.default_memory_project_id.return_value = "default"+ for method_name in (+ "_memory_replacement_lock",+ "_await_disabled_memory_cleanup",+ "_attach_memory_runtime",+ "_detach_memory_runtime",+ "_memory_runtime_for_operation",+ "_disabled_memory_source_payload",+ "_disabled_memory_status_payload",+ "_disabled_memory_status_payload_locked",+ "_disabled_memory_processing_record_payload",+ "_disabled_memory_maintenance_payload",+ "_memory_scope_for_runtime",+ "_memory_scope_for_project",+ "wake_memory",+ "install_memory_runtime",+ "memory_status_payload",+ "memory_processing_record_payload",+ "memory_failure_log_payload",+ "memory_maintenance_payload",+ "memory_profile_payload",+ "memory_processing_record_entries_payload",+ "memory_processing_record_entry_payload",+ "memory_projects_payload",+ "memory_search_payload",+ "memory_list_payload",+ ):+ method = getattr(Controller, method_name)+ setattr(controller, method_name, method.__get__(controller, Controller))return controller+def test_memory_internal_routes_cannot_bypass_controller_lifecycle() -> None:+ """Wave 0: internal Memory routes must not inspect runtime ownership."""++ tree = ast.parse(inspect.getsource(internal_server.create_app))+ bypasses = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Attribute)+ and node.attr == "memory_runtime"+ and isinstance(node.value, ast.Name)+ and node.value.id == "controller"+ ]+ private_runtime_helpers = [+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == "_memory_runtime"+ ]+ reflective_bypasses = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "getattr"+ and len(node.args) >= 2+ and isinstance(node.args[0], ast.Name)+ and node.args[0].id == "controller"+ and isinstance(node.args[1], ast.Constant)+ and node.args[1].value == "memory_runtime"+ ]++ assert bypasses == []+ assert private_runtime_helpers == []+ assert reflective_bypasses == []+++def test_memory_internal_server_keeps_implementation_imports_out_of_host_boundary() -> None:+ tree = ast.parse(Path(internal_server.__file__).read_text(encoding="utf-8"))+ implementation_imports: list[str] = []+ for node in ast.walk(tree):+ if isinstance(node, ast.ImportFrom) and node.module:+ if node.module == "avibe_memory" and [alias.name for alias in node.names] != [+ "CaptureRequest"+ ]:+ implementation_imports.append(node.module)+ elif node.module.startswith("avibe_memory.") and node.module != "core.memory_loader":+ implementation_imports.append(node.module)+ elif isinstance(node, ast.Import):+ implementation_imports.extend(+ alias.name+ for alias in node.names+ if alias.name == "avibe_memory" or alias.name.startswith("avibe_memory.")+ )++ assert implementation_imports == []+++def test_disabled_memory_status_route_uses_host_projection_without_runtime() -> None:+ from core.memory_adapter import DisabledMemoryAdapter++ controller = _build_controller_double()+ controller.config.memory = MemoryConfig(enabled=False)+ controller.memory_adapter = DisabledMemoryAdapter()+ controller._create_memory_runtime = Mock(+ side_effect=AssertionError("status must not construct Memory")+ )+ app = internal_server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://test",+ ) as client:+ return await client.get("/internal/memory/status")++ response = asyncio.run(_exercise())++ assert response.status_code == 200+ assert response.json()["state"] == "disabled"+ assert response.json()["source"]["reason"] == "memory_disabled"+ controller._create_memory_runtime.assert_not_called()+++def test_memory_status_unknown_failure_uses_stable_envelope() -> None:+ controller = _build_controller_double()+ controller.memory_status_payload = AsyncMock(+ side_effect=RuntimeError("injected lifecycle failure")+ )+ app = internal_server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://test",+ ) as client:+ return await client.get("/internal/memory/status")++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {"error": "memory_store_unavailable"}+++def test_memory_projects_unknown_lifecycle_failure_uses_stable_envelope() -> None:+ from vibe.memory_http_headers import CALLER_SESSION_HEADER++ controller = _build_controller_double()+ controller.memory_scope_for_cli_session.return_value = (+ "u-11111111111111111111111111111111",+ "default",+ )+ controller.memory_projects_payload = AsyncMock(+ side_effect=RuntimeError("injected lifecycle failure")+ )+ app = internal_server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://test",+ ) as client:+ return await client.get(+ "/internal/memory/projects",+ headers={CALLER_SESSION_HEADER: "session-1"},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {+ "status": "failed",+ "error": "memory_store_unavailable",+ }+++ ("error_type", "expected_code"),+ [+ ("MemoryImplementationUnavailableError", "memory_implementation_unavailable"),+ ("MemoryImplementationIncompatibleError", "memory_implementation_incompatible"),+ ],+)+def test_memory_projects_implementation_failure_uses_stable_error_envelope(+ error_type: str,+ expected_code: str,+) -> None:+ from core import internal_server as server+ from vibe.memory_http_headers import CALLER_SESSION_HEADER+ from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ )++ error_class = {+ "MemoryImplementationUnavailableError": MemoryImplementationUnavailableError,+ "MemoryImplementationIncompatibleError": MemoryImplementationIncompatibleError,+ }[error_type]+ controller = _build_controller_double()+ controller.memory_scope_for_cli_session.return_value = (+ "u-11111111111111111111111111111111",+ "default",+ )+ controller.memory_projects_payload = AsyncMock(side_effect=error_class("injected"))+ app = server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.get(+ "/internal/memory/projects",+ headers={CALLER_SESSION_HEADER: "session-1"},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {"status": "failed", "error": expected_code}+++def test_memory_projects_implementation_failure_preserves_admitted_cli_session_boundary() -> None:+ from core import internal_server as server+ from vibe.memory_http_headers import CALLER_SESSION_HEADER+ from vibe.memory_contract import MemoryImplementationUnavailableError++ controller = Controller.__new__(Controller)+ controller.config = SimpleNamespace(memory=SimpleNamespace(enabled=True))+ controller._memory_implementation_error = MemoryImplementationUnavailableError("injected")+ controller._memory_scopes_by_session = {}+ controller._memory_cli_facts_by_session = {}+ controller._memory_implementation_cli_sessions = set()+ controller._memory_admission = lambda: pytest.fail(+ "implementation failure must be projected before admission imports"+ )+ controller._memory_turn_facts = lambda _context: pytest.fail(+ "implementation failure must be projected before facts imports"+ )+ controller.memory_projects_payload = AsyncMock(+ side_effect=MemoryImplementationUnavailableError("injected")+ )++ context = SimpleNamespace(+ platform_specific={+ "agent_session_target": {"id": "session-1"},+ },+ platform="avibe",+ )+ assert Controller.configure_memory_cli_session(+ controller,+ context,+ admitted=True,+ )+ assert controller._memory_implementation_cli_sessions == {"session-1"}+ app = server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.get(+ "/internal/memory/projects",+ headers={CALLER_SESSION_HEADER: "session-1"},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {"status": "failed", "error": "memory_implementation_unavailable"}+++ ("implementation_error", "expected_error"),+ [+ (MemoryImplementationUnavailableError("injected"), "memory_implementation_unavailable"),+ (MemoryImplementationIncompatibleError("injected"), "memory_implementation_incompatible"),+ ],+)+def test_memory_remember_implementation_failure_uses_stable_error_envelope(+ monkeypatch: pytest.MonkeyPatch,+ implementation_error: BaseException,+ expected_error: str,+) -> None:+ from vibe.memory_http_headers import CALLER_SESSION_HEADER++ controller = Controller.__new__(Controller)+ controller.config = SimpleNamespace(memory=SimpleNamespace(enabled=True))+ controller._memory_implementation_error = implementation_error+ controller.memory_scope_for_cli_session = lambda _session_id: (+ "u-11111111111111111111111111111111",+ "default",+ )+ controller.capture_memory = Mock(+ side_effect=AssertionError(+ "implementation failure must short-circuit before capture"+ )+ )+ real_import = builtins.__import__++ def fail_memory_type_import(name, *args, **kwargs):+ if name == "avibe_memory" or name.startswith("avibe_memory."):+ raise RuntimeError("optional implementation import failed")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", fail_memory_type_import)+ app = internal_server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.post(+ "/internal/memory/remember",+ headers={CALLER_SESSION_HEADER: "session-1"},+ json={"text": "remember this"},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {"status": "failed", "error": expected_error}+++def test_memory_install_route_delegates_to_controller_lifecycle() -> None:+ controller = _build_controller_double()+ controller.memory_runtime = None+ controller.install_memory_runtime = AsyncMock(return_value={"ok": True})+ app = internal_server.create_app(controller)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://test",+ ) as client:+ return await client.post("/internal/memory/install-runtime")++ response = asyncio.run(_exercise())++ assert response.status_code == 200+ assert response.json() == {"ok": True}+ controller.install_memory_runtime.assert_awaited_once_with()++def test_controller_double_omits_retired_turn_lifecycle_admission() -> None:async def _exercise() -> None:context = MessageContext(@@ -413,7 +764,7 @@ def test_memory_archive_session_delegates_raw_identity_with_bounded_lifecycle()controller.memory_scope_for_cli_session = Mock(side_effect=AssertionError("the endpoint must not resolve identity"))- controller.archive_memory_cli_session = AsyncMock(+ controller.archive_session = AsyncMock(return_value={"id": "ses-memory", "status": "archived"})app = internal_server.create_app(controller)@@ -438,7 +789,7 @@ def test_memory_archive_session_delegates_raw_identity_with_bounded_lifecycle()}# The UI transport waits without a reporting deadline so the controller can# finish the terminal archive write. Memory flush is scheduled afterwards.- controller.archive_memory_cli_session.assert_awaited_once_with(+ controller.archive_session.assert_awaited_once_with("ses-memory",deadline_seconds=5.0,)@@ -459,7 +810,7 @@ def test_memory_archive_session_rejects_widened_or_invalid_payloads(payload: dict[str, object],) -> None:controller = _build_controller_double()- controller.archive_memory_cli_session = AsyncMock(return_value={})+ controller.archive_session = AsyncMock(return_value={})app = internal_server.create_app(controller)async def _exercise() -> httpx.Response:@@ -477,7 +828,7 @@ def test_memory_archive_session_rejects_widened_or_invalid_payloads(assert response.status_code == 400assert response.json() == {"ok": False, "error": "memory_invalid_input"}- controller.archive_memory_cli_session.assert_not_awaited()+ controller.archive_session.assert_not_awaited()@pytest.mark.parametrize(@@ -493,7 +844,7 @@ def test_memory_archive_session_returns_closed_failure_codes(error_code: str,) -> None:controller = _build_controller_double()- controller.archive_memory_cli_session = AsyncMock(side_effect=error)+ controller.archive_session = AsyncMock(side_effect=error)app = internal_server.create_app(controller)async def _exercise() -> httpx.Response:@@ -514,8 +865,8 @@ def test_memory_archive_session_returns_closed_failure_codes(def test_memory_recovery_reads_resolve_only_signed_ui_operators() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"calls: list[tuple[str, str | None]] = []@@ -615,7 +966,7 @@ def test_memory_recovery_reads_resolve_only_signed_ui_operators() -> None:def test_memory_search_accepts_bounded_agentic_policy_from_cli_session() -> None:- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERcaptured: list[tuple] = []@@ -676,13 +1027,51 @@ def test_memory_search_accepts_bounded_agentic_policy_from_cli_session() -> Noneassert current_session_id == "ses-memory"+def test_memory_search_route_does_not_import_memory_types_on_request(monkeypatch) -> None:+ import builtins++ from vibe.memory_http_headers import CALLER_SESSION_HEADER++ controller = _build_controller_double()+ controller.memory_scope_for_cli_session.return_value = (+ "u-11111111111111111111111111111111",+ "default",+ )+ controller.memory_search_payload = AsyncMock(+ return_value={"status": "ok", "items": []}+ )+ app = internal_server.create_app(controller)+ real_import = builtins.__import__++ def guarded_import(name, *args, **kwargs):+ if name == "avibe_memory.types":+ raise RuntimeError("optional implementation initializer")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", guarded_import)++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.post(+ "/internal/memory/search",+ headers={CALLER_SESSION_HEADER: "ses-memory"},+ json={"query": "connect the clues", "policy": {"mode": "keyword"}},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 200+ assert response.json() == {"status": "ok", "items": []}++def test_memory_list_accepts_everos_maximum_at_controller_boundary() -> None:"""MEMORY-LIST-009: the internal socket accepts the EverOS maximum."""- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERruntime = SimpleNamespace(- list_memory_projects=Mock(return_value=("default", "notes")),+ list_memory_projects=AsyncMock(return_value=("default", "notes")),list_episodes_payload=AsyncMock(return_value={"status": "ok", "items": [], "page": 2}),@@ -709,7 +1098,7 @@ def test_memory_list_accepts_everos_maximum_at_controller_boundary() -> None:assert response.status_code == 200assert response.json() == {"status": "ok", "items": [], "page": 2}controller.memory_scope_for_cli_session.assert_called_once_with("ses-memory-list")- runtime.list_memory_projects.assert_called_once_with(+ runtime.list_memory_projects.assert_awaited_once_with("u-11111111111111111111111111111111")runtime.list_episodes_payload.assert_awaited_once_with(@@ -721,11 +1110,11 @@ def test_memory_list_accepts_everos_maximum_at_controller_boundary() -> None:def test_memory_list_reports_unavailable_store_before_named_project_validation() -> None:- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERruntime = SimpleNamespace(available=False,- list_memory_projects=Mock(return_value=("default",)),+ list_memory_projects=AsyncMock(return_value=("default",)),list_episodes_payload=AsyncMock(),)controller = _build_controller_double()@@ -752,12 +1141,12 @@ def test_memory_list_reports_unavailable_store_before_named_project_validation()"status": "failed","error": "memory_store_unavailable",}- runtime.list_memory_projects.assert_not_called()+ runtime.list_memory_projects.assert_not_awaited()runtime.list_episodes_payload.assert_not_awaited()def test_memory_list_rejects_all_for_cli_at_controller_boundary() -> None:- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERruntime = SimpleNamespace(list_all_episodes_payload=AsyncMock(),@@ -793,12 +1182,12 @@ def test_memory_list_rejects_all_for_cli_at_controller_boundary() -> None:def test_memory_list_all_is_available_only_to_signed_ui_principal() -> None:"""MEMORY-LIST-003, MEMORY-LIST-008."""- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"runtime = SimpleNamespace(- principal_for_user_key=Mock(+ resolve_principal_for_user_key=AsyncMock(return_value="u-22222222222222222222222222222222"),list_all_episodes_payload=AsyncMock(@@ -842,7 +1231,7 @@ def test_memory_list_all_is_available_only_to_signed_ui_principal() -> None:assert response.status_code == 200assert response.json()["next_cursor"] == "next-token"- runtime.principal_for_user_key.assert_called_once_with(user_key)+ runtime.resolve_principal_for_user_key.assert_awaited_once_with(user_key)runtime.list_all_episodes_payload.assert_awaited_once_with("u-22222222222222222222222222222222",cursor="cursor-token",@@ -852,7 +1241,7 @@ def test_memory_list_all_is_available_only_to_signed_ui_principal() -> None:def test_memory_list_rejects_agent_origin_for_cli_callers() -> None:- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERruntime = SimpleNamespace(list_episodes_payload=AsyncMock())controller = _build_controller_double()@@ -888,12 +1277,12 @@ def test_memory_list_rejects_agent_origin_for_cli_callers() -> None:def test_memory_list_rejects_invalid_aggregate_cursor_at_controller_boundary() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"runtime = SimpleNamespace(- principal_for_user_key=Mock(+ resolve_principal_for_user_key=AsyncMock(return_value="u-22222222222222222222222222222222"),list_all_episodes_payload=AsyncMock(@@ -934,12 +1323,12 @@ def test_memory_list_rejects_invalid_aggregate_cursor_at_controller_boundary() -def test_memory_list_rejects_surrogate_aggregate_cursor_at_controller_boundary() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"runtime = SimpleNamespace(- principal_for_user_key=Mock(+ resolve_principal_for_user_key=AsyncMock(return_value="u-22222222222222222222222222222222"),list_all_episodes_payload=AsyncMock(),@@ -979,15 +1368,17 @@ def test_memory_list_rejects_surrogate_aggregate_cursor_at_controller_boundary()runtime.list_all_episodes_payload.assert_not_awaited()-def test_memory_list_accepts_maximum_aggregate_cursor_transport_bound() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+def test_memory_list_accepts_maximum_aggregate_cursor_transport_bound(monkeypatch) -> None:+ import builtins++ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTES+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"cursor = "a" * MEMORY_LIST_CURSOR_MAX_BYTESruntime = SimpleNamespace(- principal_for_user_key=Mock(+ resolve_principal_for_user_key=AsyncMock(return_value="u-22222222222222222222222222222222"),list_all_episodes_payload=AsyncMock(@@ -1000,6 +1391,14 @@ def test_memory_list_accepts_maximum_aggregate_cursor_transport_bound() -> None:app = internal_server.create_app(controller, memory_ui_secret=secret)path = "/internal/memory/list"user_key = "avibe:local"+ real_import = builtins.__import__++ def guarded_import(name, *args, **kwargs):+ if name == "avibe_memory.runtime":+ raise RuntimeError("optional implementation initializer")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", guarded_import)async def _exercise() -> httpx.Response:transport = httpx.ASGITransport(app=app)@@ -1050,6 +1449,34 @@ def test_memory_wake_uses_non_destructive_runtime_operation() -> None:runtime.wake.assert_awaited_once_with()+def test_memory_wake_preserves_store_unavailable_outcome() -> None:+ controller = _build_controller_double()+ controller.wake_memory = AsyncMock(+ side_effect=MemoryStoreUnavailableError(+ "Disabled Memory cleanup is still in progress"+ )+ )+ app = internal_server.create_app(controller, memory_ui_secret="test-secret")++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://test",+ ) as client:+ return await client.post("/internal/memory/wake", json={})++ response = asyncio.run(_exercise())++ assert response.status_code == 503+ assert response.json() == {+ "ok": False,+ "state": "degraded",+ "error": "memory_store_unavailable",+ }+ controller.wake_memory.assert_awaited_once_with()++def test_reconcile_memory_hot_applies_the_persisted_config(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1083,9 +1510,8 @@ def test_reconcile_memory_hot_applies_the_persisted_config(def test_memory_preflight_requires_signed_ui_operator() -> None:- runtime = SimpleNamespace(preflight=AsyncMock())controller = _build_controller_double()- controller.memory_runtime = runtime+ controller.preflight_memory = AsyncMock()app = internal_server.create_app(controller, memory_ui_secret="test-secret")async def _exercise() -> httpx.Response:@@ -1096,7 +1522,64 @@ def test_memory_preflight_requires_signed_ui_operator() -> None:response = asyncio.run(_exercise())assert response.status_code == 403assert response.json() == {"ok": False, "error": "memory_access_denied"}- runtime.preflight.assert_not_awaited()+ controller.preflight_memory.assert_not_awaited()+++def test_memory_preflight_uses_controller_lifecycle_when_runtime_is_disabled() -> None:+ from config.v2_config import (+ MemoryConfig,+ MemoryEndpointConfig,+ MemoryProcessingConfig,+ memory_config_to_payload,+ )+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof++ secret = "test-memory-ui-secret"+ path = "/internal/memory/preflight"+ candidate = MemoryConfig(+ enabled=True,+ processing=MemoryProcessingConfig(+ llm=MemoryEndpointConfig(+ base_url="https://llm.example/v1",+ model="chat-model",+ api_key="llm-secret",+ ),+ embedding=MemoryEndpointConfig(+ base_url="https://embedding.example/v1",+ model="embedding-model",+ api_key="embedding-secret",+ ),+ ),+ )+ controller = _build_controller_double()+ controller.memory_runtime = None+ controller.preflight_memory = AsyncMock(return_value={"ok": True})+ app = internal_server.create_app(controller, memory_ui_secret=secret)+ headers = {+ MEMORY_USER_KEY_HEADER: "avibe:local",+ MEMORY_UI_PROOF_HEADER: build_ui_read_proof(+ secret,+ method="POST",+ path=path,+ user_key="avibe:local",+ ),+ }++ async def _exercise() -> httpx.Response:+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.post(+ path,+ headers=headers,+ json={"memory": memory_config_to_payload(candidate, include_secrets=True)},+ )++ response = asyncio.run(_exercise())++ assert response.status_code == 200+ assert response.json() == {"ok": True}+ controller.preflight_memory.assert_awaited_once_with(candidate)@pytest.mark.parametrize(@@ -1111,8 +1594,8 @@ def test_memory_data_operations_require_signed_ui_operator(method_name: str,operation: str,) -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADERsecret = "test-memory-ui-secret"controller = _build_controller_double()@@ -1159,8 +1642,8 @@ def test_memory_data_operations_require_exact_loss_confirmation(method_name: str,operation: str,) -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"controller = _build_controller_double()@@ -1214,8 +1697,8 @@ def test_memory_data_operations_return_distinct_final_result(method_name: str,operation: str,) -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"result = {@@ -1252,8 +1735,8 @@ def test_memory_data_operations_return_distinct_final_result(def test_memory_reconfigure_forwards_the_cas_snapshot() -> None:from config.v2_config import MemoryConfig, memory_config_to_payload- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"path = "/internal/memory/reconfigure"@@ -1323,8 +1806,8 @@ def test_memory_reconfigure_forwards_the_cas_snapshot() -> None:],)def test_memory_repair_maps_controller_status(result: dict, expected_status: int) -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"path = "/internal/memory/repair"@@ -1356,8 +1839,8 @@ def test_memory_repair_maps_controller_status(result: dict, expected_status: intdef test_processing_record_degrades_signed_operator_lookup_failure() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"verified_user_keys: list[str | None] = []@@ -1417,8 +1900,8 @@ def test_processing_record_degrades_signed_operator_lookup_failure() -> None:def test_processing_record_route_leaves_operator_lookup_to_runtime() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofsecret = "test-memory-ui-secret"verified_user_keys: list[str | None] = []@@ -1473,13 +1956,13 @@ def test_processing_record_route_leaves_operator_lookup_to_runtime() -> None:def test_native_processing_record_routes_authorize_the_selected_project() -> None:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proof+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import MEMORY_UI_PROOF_HEADER, build_ui_read_proofprincipal_id = "u-11111111111111111111111111111111"runtime = SimpleNamespace(- principal_for_user_key=Mock(return_value=principal_id),- list_memory_projects=Mock(return_value=("default", "notes")),+ resolve_principal_for_user_key=AsyncMock(return_value=principal_id),+ list_memory_projects=AsyncMock(return_value=("default", "notes")),processing_record_entries_payload=AsyncMock(return_value={"status": "ok", "entries": [], "next_cursor": None}),@@ -1537,30 +2020,36 @@ def test_native_processing_record_routes_authorize_the_selected_project() -> Nonruntime.processing_record_entry_payload.assert_awaited_once_with(principal_id, "notes", "mc_1")- assert runtime.list_memory_projects.call_count == 3+ assert runtime.list_memory_projects.await_count == 3-def test_memory_remember_route_rejects_capture_queued_across_runtime_replacement() -> None:- """The production CLI route cannot repopulate the fresh reset aggregate."""+def test_memory_remember_route_does_not_hold_pointer_lock_during_capture() -> None:+ """Long capture work runs after the Controller pointer snapshot."""from core.controller import Controller- from core.memory import CaptureAccepted- from core.memory.http_headers import CALLER_SESSION_HEADER+ from avibe_memory import CaptureAccepted+ from vibe.memory_http_headers import CALLER_SESSION_HEADERclass Module:def __init__(self) -> None:self.calls = 0+ self.started = asyncio.Event()+ self.release = asyncio.Event()async def capture(self, _request): # noqa: ANN001, ANN202+ assert controller._memory_replacement_lock().locked() is Falseself.calls += 1+ self.started.set()+ await self.release.wait()return CaptureAccepted()- old_module = Module()- fresh_module = Module()- old_runtime = SimpleNamespace(retired=False, available=True, module=old_module)- fresh_runtime = SimpleNamespace(retired=False, available=True, module=fresh_module)+ module = Module()+ runtime = SimpleNamespace(available=True, module=module)controller = Controller.__new__(Controller)- controller.memory_runtime = old_runtime+ controller.config = SimpleNamespace(+ memory=SimpleNamespace(enabled=True),+ )+ controller.memory_runtime = runtimecontroller.memory_scope_for_cli_session = lambda _session_id: ("u-" + "1" * 32,"p-" + "2" * 32,@@ -1568,8 +2057,6 @@ def test_memory_remember_route_rejects_capture_queued_across_runtime_replacementapp = internal_server.create_app(controller)async def _exercise() -> httpx.Response:- gate = controller._memory_replacement_lock()- await gate.acquire()transport = httpx.ASGITransport(app=app)async with httpx.AsyncClient(transport=transport,@@ -1582,31 +2069,25 @@ def test_memory_remember_route_rejects_capture_queued_across_runtime_replacementheaders={CALLER_SESSION_HEADER: "session-1"},))- for _ in range(20):- await asyncio.sleep(0)- if getattr(gate, "_waiters", None):- break- assert getattr(gate, "_waiters", None)- controller.memory_runtime = fresh_runtime- gate.release()+ await module.started.wait()+ async with asyncio.timeout(0.1):+ async with controller._memory_replacement_lock():+ assert controller.memory_runtime is runtime+ module.release.set()return await requestresponse = asyncio.run(_exercise())assert response.status_code == 200- assert response.json() == {- "status": "skipped",- "reason": "memory_operation_in_progress",- }- assert old_module.calls == 0- assert fresh_module.calls == 0+ assert response.json() == {"status": "accepted"}+ assert module.calls == 1def test_memory_remember_accepts_text_over_legacy_controller_limit() -> None:"""MEMORY-SEARCH-018: the internal socket delegates large remember text."""- from core.memory import CaptureAccepted- from core.memory.http_headers import CALLER_SESSION_HEADER+ from avibe_memory import CaptureAccepted+ from vibe.memory_http_headers import CALLER_SESSION_HEADERtext = "remember this detail " * 300controller = _build_controller_double()@@ -2104,13 +2585,18 @@ def test_dispatch_context_does_not_restore_memory_admission_from_transient_paylo{"session_id": session["id"],"text": "remember this",+ "author_id": "remote:authenticated",+ "user_id": "remote:forged-memory-principal",+ "message_kind": "original","memory_cli_admitted": True,"is_ordinary_text": True,}))- assert context.is_ordinary_text is None+ assert context.user_id == "remote:authenticated"+ assert context.message_kind == "original"+ assert context.is_original_human_text is Trueassert "memory_cli_admitted" not in (context.platform_specific or {})@@ -2605,6 +3091,73 @@ def test_dispatch_async_starts_authorized_remote_reservation(stored = message_deliveries.get_delivery(conn, remote["id"])assert stored is not Noneassert stored["state"] == "accepted"+++def test_dispatch_async_restores_message_kind_from_reserved_delivery(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session = _create_test_session(+ tmp_path,+ native_id="proj_durable_message_kind",+ )+ with engine.begin() as conn:+ reserved = _reserve_submission(+ conn,+ scope_id=session["scope_id"],+ session_id=session["id"],+ text="durable quick reply",+ message_kind="quick_reply",+ )++ observed: list[MessageContext] = []+ dispatch_kinds: list[object] = []+ build_dispatch_payload = internal_server._build_dispatch_payload++ async def observe_dispatch_payload(payload):+ dispatch_kinds.append(payload.get("message_kind"))+ return await build_dispatch_payload(payload)++ monkeypatch.setattr(+ internal_server,+ "_build_dispatch_payload",+ observe_dispatch_payload,+ )+ controller = None++ async def handler(context, _text):+ observed.append(context)+ controller.mark_turn_complete(context)++ controller = _build_controller_double(handler)+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://testserver",+ ) as client:+ return await client.post(+ "/internal/dispatch_async",+ json={+ "session_id": session["id"],+ "text": "stale request text",+ "user_message_id": reserved["id"],+ "message_kind": "original",+ },+ )++ response = asyncio.run(_go())++ assert response.status_code == 202+ assert dispatch_kinds == ["quick_reply"]+ assert len(observed) == 1+ assert observed[0].message_kind == "quick_reply"+ assert observed[0].is_original_human_text is False++def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(monkeypatch,tmp_path,@@ -7511,16 +8064,16 @@ def test_flush_runs_authorized_remote_fifo_head(session_id=session["id"],text="remote queued input",metadata=_authorized_remote_message_metadata(),+ author_id="remote-user",+ message_kind="original",)local = message_deliveries.enqueue_queued(conn,scope_id=session["scope_id"],session_id=session["id"],text="local queued input",- metadata={- message_deliveries.MEMORY_USER_ID_METADATA: "local",- message_deliveries.MEMORY_ORDINARY_TEXT_METADATA: True,- },+ author_id="local",+ message_kind="original",)manager, runs = _manager_accepting_runs()diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex 0f035059a..33f86497b 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -13,8 +13,11 @@ import ioimport jsonimport osimport subprocess+import sysimport tarfileimport urllib.error+from contextlib import nullcontext+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import Mock@@ -1219,7 +1222,7 @@ def test_dependencies_status_shape(monkeypatch):monkeypatch.setattr(api.V2Config,"load",- classmethod(lambda _cls: SimpleNamespace(memory=SimpleNamespace(enabled=True))),+ classmethod(lambda _cls: SimpleNamespace(memory_required=True)),)monkeypatch.setattr(api,@@ -1251,25 +1254,53 @@ def test_dependencies_status_shape(monkeypatch):}monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())- import core.memory.artifact as memory_artifact-- class _MemoryMgr:- def status(self):- return {+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda **_: (+ {+ "id": "memory-package",+ "kind": "runtime",+ "required": True,+ "installed": True,+ "provider_count": 1,+ "version": "1.2.3",+ "latest_version": "1.2.3",+ "has_update": False,+ "status": "ready",+ "readiness": "ready",+ "reason": None,+ "action_class": "none",+ "warnings": [],+ },+ {+ "id": "memory-runtime",+ "kind": "runtime",+ "required": True,"installed": False,"version": None,- "selected_version": "1.2.3",- "matches_manifest": None,+ "latest_version": "1.2.3",+ "has_update": False,"status": "missing",- "manifest": {"everos_version": "1.2.3", "release_state": "unavailable"},"reason": "memory_runtime_unpublished",- }-- monkeypatch.setattr(memory_artifact, "get_memory_artifact_manager", lambda: _MemoryMgr())+ "action_class": "repairable",+ "release_state": "unavailable",+ "download_error": None,+ },+ ),+ )out = api.dependencies_status()assert out["ok"]by = {d["id"]: d for d in out["deps"]}- assert list(by) == ["askill", "avault", "show-runtime", "memory-runtime", "tmux", "node"]+ assert list(by) == [+ "askill",+ "avault",+ "show-runtime",+ "memory-package",+ "memory-runtime",+ "tmux",+ "node",+ ]assert "tmux" in by and by["tmux"]["required"] is False # tmux is the optional terminal backendassert by["askill"]["status"] == "ready" and by["askill"]["version"] == "0.1.13" and by["askill"]["required"]assert by["askill"]["latest_version"] is None and by["askill"]["has_update"] is False@@ -1278,6 +1309,7 @@ def test_dependencies_status_shape(monkeypatch):assert by["show-runtime"]["installed"] and by["show-runtime"]["version"] == "1.4.0"assert by["show-runtime"]["latest_version"] == "1.4.0"assert by["show-runtime"]["has_update"] is False+ assert by["memory-package"]["readiness"] == "ready"assert by["memory-runtime"] == {"id": "memory-runtime","kind": "runtime",@@ -1288,6 +1320,7 @@ def test_dependencies_status_shape(monkeypatch):"has_update": False,"status": "missing","reason": "memory_runtime_unpublished",+ "action_class": "repairable","release_state": "unavailable","download_error": None,}@@ -1340,16 +1373,20 @@ def test_dependencies_status_projects_show_runtime_identity_without_pairing(monkclassmethod(lambda _cls: SimpleNamespace(memory=SimpleNamespace(enabled=False))),)- import core.memory.artifact as memory_artifactimport core.show_runtime as show_runtimeimport core.tmux_runtime as tmux_runtimemanager = Mock()manager.status.return_value = runtime_status- memory_manager = Mock()- memory_manager.status.return_value = {"installed": False, "status": "missing", "manifest": None}monkeypatch.setattr(show_runtime, "get_show_runtime_manager", lambda: manager)- monkeypatch.setattr(memory_artifact, "get_memory_artifact_manager", lambda: memory_manager)+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda **_: (+ {"id": "memory-package", "status": "not_required"},+ {"id": "memory-runtime", "status": "not_required"},+ ),+ )monkeypatch.setattr(tmux_runtime, "tmux_status", lambda: {"installed": False, "version": None, "status": "missing"})entry = next(item for item in api.dependencies_status()["deps"] if item["id"] == "show-runtime")@@ -1372,6 +1409,529 @@ def test_memory_runtime_dependency_status_maps_closed_failures(runtime, expectedassert api._memory_runtime_dependency_status(runtime) == expected+ ("metadata", "status", "reason", "action_class"),+ (+ (api._MemoryPackageMetadata(0, None), "missing", "memory_package_missing", "repairable"),+ (+ api._MemoryPackageMetadata(2, None),+ "error",+ "memory_package_metadata_ambiguous",+ "operator_only",+ ),+ (+ api._MemoryPackageMetadata(None, None),+ "error",+ "memory_package_metadata_unreadable",+ "operator_only",+ ),+ (+ api._MemoryPackageMetadata(1, None),+ "error",+ "memory_package_metadata_unreadable",+ "operator_only",+ ),+ (+ api._MemoryPackageMetadata(1, "3.0.15"),+ "error",+ "memory_package_version_mismatch",+ "repairable",+ ),+ ),+)+def test_required_memory_package_metadata_precedes_optional_imports(+ monkeypatch,+ metadata,+ status,+ reason,+ action_class,+) -> None:+ monkeypatch.setattr(+ api,+ "_load_memory_requirement",+ lambda: api._MemoryRequirementProjection(True, "required"),+ )+ monkeypatch.setattr(api, "_inspect_memory_package_metadata", lambda: metadata)+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind="package"))+ monkeypatch.setattr(api, "_memory_package_restart_retry_required", lambda _version: False)+ probe = Mock(side_effect=AssertionError("metadata failure imported Memory runtime"))+ artifact = Mock(side_effect=AssertionError("metadata failure imported Memory artifact"))+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", probe)+ monkeypatch.setattr(api, "_memory_artifact_status", artifact)++ package, runtime = api._memory_dependencies_status(offline=True)++ assert package["status"] == status+ assert package["reason"] == reason+ assert package["action_class"] == action_class+ assert runtime["reason"] == reason+ probe.assert_not_called()+ artifact.assert_not_called()+++ (+ "requirement",+ "metadata",+ "build_kind",+ "current_version",+ "probe_failure",+ "artifact_imported",+ "expected",+ ),+ (+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(1, "3.0.13"),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_required", "memory_package_version_mismatch", "repairable"),+ id="not-required-exposes-version-bootstrap",+ ),+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(0, None),+ "package",+ "3.0.14",+ False,+ True,+ ("missing", "not_required", "memory_package_missing", "repairable"),+ id="not-required-exposes-missing-bootstrap",+ ),+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(1, "3.0.14"),+ "package",+ "3.0.14",+ True,+ True,+ ("not_required", "not_required", None, "repairable"),+ id="not-required-exact-package-keeps-explicit-repair",+ ),+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(None, None),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_required", "memory_package_metadata_unreadable", "operator_only"),+ id="not-required-unreadable-metadata-stays-operator-only",+ ),+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(2, None),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_required", "memory_package_metadata_ambiguous", "operator_only"),+ id="not-required-ambiguous-metadata-stays-operator-only",+ ),+ pytest.param(+ api._MemoryRequirementProjection(False, "not_required"),+ api._MemoryPackageMetadata(0, None),+ "source",+ "3.0.14",+ False,+ True,+ ("not_required", "not_required", None, "none"),+ id="not-required-source-stays-operator-owned",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(1, "3.0.14"),+ "package",+ "3.0.14",+ False,+ True,+ ("ready", "ready", None, "none"),+ id="required-ready",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(0, None),+ "package",+ "3.0.14",+ False,+ True,+ ("missing", "not_ready", "memory_package_missing", "repairable"),+ id="required-missing",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(1, "3.0.13"),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_ready", "memory_package_version_mismatch", "repairable"),+ id="required-version-mismatch",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(1, "3.0.14"),+ "package",+ "3.0.14",+ True,+ True,+ ("error", "not_ready", "memory_package_runtime_unavailable", "repairable"),+ id="required-runtime-probe-broken",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(1, "3.0.14"),+ "package",+ "3.0.14",+ False,+ False,+ ("error", "not_ready", "memory_package_artifact_unavailable", "repairable"),+ id="required-artifact-import-broken",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(None, None),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_ready", "memory_package_metadata_unreadable", "operator_only"),+ id="operator-only-unreadable-metadata",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(2, None),+ "package",+ "3.0.14",+ False,+ True,+ ("error", "not_ready", "memory_package_metadata_ambiguous", "operator_only"),+ id="operator-only-duplicate-provider",+ ),+ pytest.param(+ api._MemoryRequirementProjection(True, "required"),+ api._MemoryPackageMetadata(1, "3.0.14"),+ "source",+ "3.0.14",+ False,+ True,+ ("error", "not_ready", "memory_package_source_build", "operator_only"),+ id="operator-only-source-deployment",+ ),+ ),+)+def test_memory_package_state_action_matrix(+ monkeypatch,+ requirement,+ metadata,+ build_kind,+ current_version,+ probe_failure,+ artifact_imported,+ expected,+) -> None:+ monkeypatch.setattr(api, "_load_memory_requirement", lambda: requirement)+ monkeypatch.setattr(api, "_inspect_memory_package_metadata", lambda: metadata)+ monkeypatch.setattr(api, "_published_running_version", lambda: current_version)+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind=build_kind))+ monkeypatch.setattr(api, "_memory_package_restart_retry_required", lambda _version: False)+ monkeypatch.setattr(+ api,+ "probe_memory_runtime_entrypoint",+ Mock(side_effect=ImportError("broken entrypoint") if probe_failure else None),+ )+ monkeypatch.setattr(+ api,+ "_memory_artifact_status",+ lambda **_: (+ artifact_imported,+ {"installed": True, "status": "ready", "matches_manifest": True},+ ),+ )++ package, _runtime = api._memory_dependencies_status(offline=True)++ assert (+ package["status"],+ package["readiness"],+ package["reason"],+ package["action_class"],+ ) == expected+++def test_required_memory_package_probe_and_artifact_order_keeps_package_ready(+ monkeypatch,+) -> None:+ events: list[str] = []+ monkeypatch.setattr(+ api,+ "_load_memory_requirement",+ lambda: api._MemoryRequirementProjection(True, "required"),+ )+ monkeypatch.setattr(+ api,+ "_inspect_memory_package_metadata",+ lambda: api._MemoryPackageMetadata(1, "3.0.14"),+ )+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind="package"))+ monkeypatch.setattr(+ api,+ "probe_memory_runtime_entrypoint",+ lambda: events.append("runtime-probe"),+ )++ def artifact_status(*, offline: bool) -> tuple[bool, dict]:+ assert offline is True+ events.append("artifact-import-and-status")+ return True, {+ "installed": False,+ "status": "error",+ "reason": "memory_runtime_install_failed",+ }++ monkeypatch.setattr(api, "_memory_artifact_status", artifact_status)++ package, runtime = api._memory_dependencies_status(offline=True)++ assert events == ["runtime-probe", "artifact-import-and-status"]+ assert package["readiness"] == "ready"+ assert package["reason"] is None+ assert runtime["status"] == "error"+ assert runtime["reason"] == "memory_runtime_install_failed"+++def test_memory_package_restart_failure_remains_explicitly_repairable(+ monkeypatch,+) -> None:+ monkeypatch.setattr(+ api,+ "_load_memory_requirement",+ lambda: api._MemoryRequirementProjection(True, "required"),+ )+ monkeypatch.setattr(+ api,+ "_inspect_memory_package_metadata",+ lambda: api._MemoryPackageMetadata(1, "3.0.14"),+ )+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind="package"))+ monkeypatch.setattr(api, "_memory_package_restart_retry_required", lambda _version: True)+ probe = Mock(side_effect=AssertionError("restart retry must not re-import the companion"))+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", probe)++ package, runtime = api._memory_dependencies_status(offline=True)++ assert (package["status"], package["reason"], package["action_class"]) == (+ "error",+ "memory_package_restart_failed",+ "repairable",+ )+ assert runtime["reason"] == "memory_package_restart_failed"+ probe.assert_not_called()+++ ("build_kind", "current_version"),+ (("source", "3.0.14"), ("package", "3.0.14")),+)+def test_mismatched_memory_runtime_keeps_repair_action_across_build_paths(+ monkeypatch,+ build_kind,+ current_version,+) -> None:+ monkeypatch.setattr(+ api,+ "_load_memory_requirement",+ lambda: api._MemoryRequirementProjection(True, "required"),+ )+ monkeypatch.setattr(+ api,+ "_inspect_memory_package_metadata",+ lambda: api._MemoryPackageMetadata(1, "3.0.14"),+ )+ monkeypatch.setattr(api, "_published_running_version", lambda: current_version)+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind=build_kind))+ monkeypatch.setattr(api, "_memory_package_restart_retry_required", lambda _version: False)+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", lambda: None)+ monkeypatch.setattr(+ api,+ "_memory_artifact_status",+ lambda **_: (+ True,+ {+ "installed": True,+ "status": "ready",+ "matches_manifest": False,+ },+ ),+ )++ _package, runtime = api._memory_dependencies_status(offline=True)++ assert runtime["has_update"] is True+ assert runtime["action_class"] == "repairable"+++def test_required_memory_package_accepts_pep440_equivalent_versions(+ monkeypatch,+) -> None:+ monkeypatch.setattr(+ api,+ "_load_memory_requirement",+ lambda: api._MemoryRequirementProjection(True, "required"),+ )+ monkeypatch.setattr(+ api,+ "_inspect_memory_package_metadata",+ lambda: api._MemoryPackageMetadata(1, "3.0.14.0"),+ )+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind="package"))+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", lambda: None)+ monkeypatch.setattr(+ api,+ "_memory_artifact_status",+ lambda **_: (True, {"installed": True, "status": "ready"}),+ )++ package, _runtime = api._memory_dependencies_status(offline=True)++ assert package["readiness"] == "ready"+ assert package["has_update"] is False+++def test_memory_package_metadata_enumerates_canonical_provider_set(+ monkeypatch,+) -> None:+ import importlib.metadata++ calls: list[str] = []+ providers = (SimpleNamespace(version="3.0.14"), SimpleNamespace(version="3.0.14"))++ def distributions(*, name: str):+ calls.append(name)+ return providers++ monkeypatch.setattr(importlib.metadata, "distributions", distributions)++ assert api._inspect_memory_package_metadata() == api._MemoryPackageMetadata(2, None)+ assert calls == ["avibe-memory"]+++def test_missing_first_run_config_is_readable_not_required(monkeypatch) -> None:+ monkeypatch.setattr(+ api.V2Config,+ "load",+ classmethod(lambda _cls: (_ for _ in ()).throw(FileNotFoundError())),+ )++ requirement = api._load_memory_requirement()++ assert requirement == api._MemoryRequirementProjection(False, "not_required")+++ "case",+ ("disabled", "safe-degraded-memory", "whole-config-failure"),+)+def test_memory_indep_021_status_import_fence(tmp_path, case) -> None:+ script = r'''+import importlib.abc+import json+import sys+from types import SimpleNamespace++from config import paths+from config.v2_config import V2Config++case = sys.argv[1]+config_path = paths.get_config_path()+config_path.parent.mkdir(parents=True, exist_ok=True)+config = V2Config.default()+config.save(config_path)+if case == "safe-degraded-memory":+ payload = json.loads(config_path.read_text(encoding="utf-8"))+ payload["memory"]["recovery_intent"] = "invalid"+ config_path.write_text(json.dumps(payload), encoding="utf-8")+elif case == "whole-config-failure":+ config_path.write_text("{", encoding="utf-8")++assert not any(+ name == "avibe_memory" or name.startswith("avibe_memory.")+ for name in sys.modules+)++class BlockMemoryImplementation(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path=None, target=None):+ if fullname == "avibe_memory" or fullname.startswith("avibe_memory."):+ raise AssertionError(f"optional implementation import: {fullname}")+ return None++sys.meta_path.insert(0, BlockMemoryImplementation())+from vibe import api++metadata_calls = []++def inspect_metadata():+ metadata_calls.append(True)+ return api._MemoryPackageMetadata(0, None)++api._inspect_memory_package_metadata = inspect_metadata+api._published_running_version = lambda: "3.0.14"+api.get_build_identity = lambda: SimpleNamespace(kind="package")+package, runtime = api._memory_dependencies_status(offline=True)+if case == "whole-config-failure":+ assert package["readiness"] == "memory_requirement_unreadable"+ assert package["reason"] == "memory_requirement_unreadable"+ assert package["action_class"] == "operator_only"+ assert metadata_calls == []+else:+ assert package["readiness"] == "not_required"+ assert package["status"] == "missing"+ assert package["reason"] == "memory_package_missing"+ assert package["action_class"] == "repairable"+ assert runtime["status"] == "not_required"+ assert metadata_calls == [True]+ if case == "safe-degraded-memory":+ assert package["warnings"]++from vibe.upgrade import MemoryRequirementUnreadableError, configured_memory_enabled++if case == "whole-config-failure":+ try:+ configured_memory_enabled()+ except MemoryRequirementUnreadableError:+ pass+ else:+ raise AssertionError("whole-config failure admitted package mutation")+else:+ assert configured_memory_enabled() is False++assert not any(+ name == "avibe_memory" or name.startswith("avibe_memory.")+ for name in sys.modules+)+'''+ env = {+ **os.environ,+ "AVIBE_HOME": str(tmp_path / case),+ "PYTHONPATH": str(Path(__file__).resolve().parents[1]),+ }+ result = subprocess.run(+ [sys.executable, "-c", script, case],+ cwd=tmp_path,+ env=env,+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr++def test_memory_runtime_dependency_job_uses_controller_lifecycle(monkeypatch):from vibe import internal_client@@ -1440,6 +2000,13 @@ def test_dependencies_status_node_unsupported_not_ready(monkeypatch):def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeypatch):askill_calls = []avault_calls = []+ memory_calls = []++ def reconcile_memory_package():+ memory_calls.append("reconcile")+ return {"ok": True, "skipped": True, "reason": "memory_not_required"}++ monkeypatch.setattr(api, "reconcile_memory_package_on_startup", reconcile_memory_package)def fake_ensure(force=False):askill_calls.append(force)@@ -1486,6 +2053,8 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeypout = api.reconcile_startup_dependencies()assert out["ok"] is True+ assert memory_calls == ["reconcile"]+ assert out["memory_package"]["reason"] == "memory_not_required"assert askill_calls == [False]assert avault_calls == [False]assert manager.prepared == [(False, True)]@@ -1497,6 +2066,174 @@ def test_reconcile_startup_dependencies_uses_automatic_runtime_admission(monkeypassert out["show_runtime"]["runtime"]["state"] == "unchecked"+def test_memory_indep_026_startup_repairs_required_missing_companion_once(monkeypatch):+ """MEMORY-INDEP-026: a split-first startup converges through exact repair."""++ calls: list[bool] = []+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda *, offline: (+ {+ "required": True,+ "readiness": "not_ready",+ "reason": "memory_package_missing",+ "action_class": "repairable",+ },+ {},+ ),+ )++ def repair(*, automatic: bool = False) -> dict:+ assert automatic is True+ calls.append(True)+ return {+ "ok": True,+ "message": "memory_package_ready",+ "reason": None,+ "restarting": True,+ "restart": {"job_id": "restart"},+ }++ monkeypatch.setattr(api, "_prepare_memory_package_job", repair)++ result = api.reconcile_memory_package_on_startup()++ assert calls == [True]+ assert result == {+ "ok": True,+ "message": "memory_package_ready",+ "reason": None,+ "restarting": True,+ "restart": {"job_id": "restart"},+ }+++def test_startup_memory_repair_continues_other_dependencies_before_service_restart(+ monkeypatch,+):+ events: list[str] = []+ monkeypatch.setattr(+ api,+ "reconcile_memory_package_on_startup",+ lambda: {+ "ok": True,+ "message": "memory_package_ready",+ "reason": None,+ "restarting": True,+ },+ )+ monkeypatch.setattr(+ api,+ "ensure_askill_installed",+ lambda **_kwargs: events.append("askill") or {"ok": True},+ )+ monkeypatch.setattr(+ api,+ "ensure_avault_installed",+ lambda **_kwargs: events.append("avault") or {"ok": True},+ )+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")++ import core.show_runtime as srt_mod++ class _Mgr:+ def status(self, *, offline=False):+ return {+ "node_available": False,+ "node_supported": None,+ "node_version": None,+ }++ monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())++ result = api.reconcile_startup_dependencies()++ assert events == ["askill", "avault"]+ assert result["memory_package"]["restarting"] is True+ assert result["show_runtime"]["status"] == "failed"+++ "package",+ (+ {+ "required": False,+ "readiness": "not_required",+ "reason": None,+ "action_class": "none",+ },+ {+ "required": True,+ "readiness": "ready",+ "reason": None,+ "action_class": "none",+ },+ {+ "required": True,+ "readiness": "not_ready",+ "reason": "memory_package_source_build",+ "action_class": "operator_only",+ },+ ),+ ids=("disabled", "ready", "source"),+)+def test_startup_memory_package_reconcile_skips_nonrepairable_states(monkeypatch, package):+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda *, offline: (package, {}),+ )+ monkeypatch.setattr(+ api,+ "_prepare_memory_package_job",+ lambda: pytest.fail("a non-repairable package state must not install"),+ )++ result = api.reconcile_memory_package_on_startup()++ assert result["ok"] is True+ assert result["skipped"] is True+++def test_startup_memory_repair_failure_keeps_other_dependency_reconcile_running(monkeypatch):+ events: list[str] = []+ monkeypatch.setattr(+ api,+ "reconcile_memory_package_on_startup",+ lambda: {+ "ok": False,+ "message": "memory_package_install_failed",+ "reason": "memory_package_install_failed",+ },+ )+ monkeypatch.setattr(+ api,+ "ensure_askill_installed",+ lambda *, force: events.append("askill") or {"ok": True},+ )+ monkeypatch.setattr(+ api,+ "ensure_avault_installed",+ lambda *, force: events.append("avault") or {"ok": True},+ )++ import core.show_runtime as srt_mod++ class _Mgr:+ def status(self, *, offline=False):+ return {"node_available": False, "node_supported": None, "node_version": None}++ monkeypatch.setattr(srt_mod, "get_show_runtime_manager", lambda: _Mgr())+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "0")++ result = api.reconcile_startup_dependencies()++ assert events == ["askill", "avault"]+ assert result["ok"] is False+ assert result["memory_package"]["reason"] == "memory_package_install_failed"++def test_reconcile_startup_dependencies_reports_runtime_install_failure_without_node(monkeypatch):monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: {"ok": True, "installed": True})monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: {"ok": True, "installed": True})@@ -1591,6 +2328,392 @@ def test_startup_show_page_prewarm_limit_env(monkeypatch):assert api.startup_show_page_prewarm_limit() == 10+ ("package", "expected_reason"),+ (+ pytest.param(+ {+ "required": False,+ "provider_count": 0,+ "version": None,+ "reason": None,+ "action_class": "none",+ },+ "memory_not_required",+ id="not-required",+ ),+ pytest.param(+ {+ "required": True,+ "provider_count": None,+ "version": None,+ "reason": "memory_package_metadata_unreadable",+ "action_class": "operator_only",+ },+ "memory_package_metadata_unreadable",+ id="operator-only-metadata",+ ),+ pytest.param(+ {+ "required": True,+ "provider_count": 1,+ "version": "3.0.14",+ "reason": "memory_package_source_build",+ "action_class": "operator_only",+ },+ "memory_package_source_build",+ id="source-deployment",+ ),+ pytest.param(+ {+ "required": True,+ "provider_count": 1,+ "version": "3.0.14",+ "reason": None,+ "action_class": "none",+ },+ "memory_package_not_repairable",+ id="already-ready",+ ),+ ),+)+def test_memory_package_server_admission_rejects_nonrepairable_rows(+ monkeypatch,+ package,+ expected_reason,+) -> None:+ monkeypatch.setattr(+ api,+ "_memory_dependencies_status",+ lambda **_: (package, {"id": "memory-runtime"}),+ )++ result = api.start_dependency_install_job("memory-package")++ assert result == {+ "ok": False,+ "status": "rejected",+ "message": expected_reason,+ "output": None,+ "reason": expected_reason,+ "action_class": "operator_only",+ }+++def test_memory_package_dependency_job_uses_existing_pinned_plan(monkeypatch) -> None:+ plan = SimpleNamespace(+ command=["repair"],+ activation=None,+ method="pip",+ preflight_error=None,+ )+ calls: dict[str, object] = {}+ lock_events: list[str] = []+ monkeypatch.setattr(api, "_memory_package_repair_rejection", lambda **_kwargs: None)+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ 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)+ monkeypatch.setattr(api, "_memory_package_restart_retry_required", lambda _version: False)+ record_result = Mock()+ monkeypatch.setattr(api, "_record_memory_package_repair_result", record_result)+ monkeypatch.setattr(+ api,+ "verify_python_environment",+ lambda _python: SimpleNamespace(ok=True, detail="ok"),+ )++ class _Lock:+ def __enter__(self):+ lock_events.append("entered")++ def __exit__(self, *_args):+ lock_events.append("exited")++ monkeypatch.setattr(api, "atomic_upgrade_lock", _Lock)++ def build_plan(**kwargs):+ lock_events.append("build")+ calls["plan"] = kwargs+ return plan++ def execute_plan(actual, **kwargs):+ lock_events.append("execute")+ calls["execute"] = (actual, kwargs)+ return subprocess.CompletedProcess(["repair"], 0, stdout="installed", stderr="")++ monkeypatch.setattr(api, "build_upgrade_plan", build_plan)+ monkeypatch.setattr(api, "execute_upgrade_plan", execute_plan)+ def schedule_restart(**kwargs):+ lock_events.append("restart")+ calls["restart"] = kwargs+ return {"job_id": "restart"}++ monkeypatch.setattr(api, "schedule_restart", schedule_restart)++ result = api._prepare_memory_package_job()++ assert result["ok"] is True+ assert result["message"] == "memory_package_ready"+ assert calls["plan"] == {+ "version": "3.0.14",+ "package_name": api.PACKAGE_NAME,+ "memory_package": True,+ "memory_version": "3.0.14",+ "vibe_path": "/bin/vibe",+ }+ assert calls["execute"] == (+ plan,+ {+ "run": subprocess.run,+ "capture_output": True,+ "text": True,+ "timeout": api.UPGRADE_INSTALL_TIMEOUT_SECONDS,+ "cwd": "/safe",+ },+ )+ assert calls["restart"] == {+ "delay_seconds": 2.0,+ "vibe_path": "/bin/vibe",+ "trigger": "memory-package-repair",+ "scope": "service",+ }+ assert result["restarting"] is True+ assert result["restart"] == {"job_id": "restart"}+ assert lock_events == ["entered", "build", "execute", "restart", "exited"]+ record_result.assert_called_once_with(+ "3.0.14",+ result="restart_scheduled",+ reason=None,+ )+++def test_memory_package_dependency_job_fails_closed_when_restart_cannot_be_scheduled(+ monkeypatch,+ tmp_path,+) -> None:+ state_path = tmp_path / "memory-package-auto-repair.json"+ monkeypatch.setattr(api, "_memory_package_auto_repair_state_path", lambda: state_path)+ monkeypatch.setattr(api, "_memory_package_repair_rejection", lambda **_kwargs: None)+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/bin/vibe")+ monkeypatch.setattr(api, "get_safe_cwd", lambda: "/safe")+ monkeypatch.setattr(api, "atomic_upgrade_lock", nullcontext)+ monkeypatch.setattr(api, "restart_is_pending", lambda: False)+ monkeypatch.setattr(+ api,+ "verify_python_environment",+ lambda _python: SimpleNamespace(ok=True, detail="ok"),+ )+ build_plan = Mock(+ return_value=SimpleNamespace(+ activation=None,+ method="pip",+ preflight_error=None,+ )+ )+ monkeypatch.setattr(+ api,+ "build_upgrade_plan",+ build_plan,+ )+ execute_plan = Mock(+ return_value=subprocess.CompletedProcess(+ ["repair"], 0, stdout="installed", stderr=""+ )+ )+ monkeypatch.setattr(+ api,+ "execute_upgrade_plan",+ execute_plan,+ )+ schedule = Mock(side_effect=RuntimeError("restart unavailable"))+ monkeypatch.setattr(api, "schedule_restart", schedule)++ result = api._prepare_memory_package_job()++ assert result == {+ "ok": False,+ "message": "memory_package_restart_failed",+ "output": "installed",+ "reason": "memory_package_restart_failed",+ "restarting": False,+ }+ assert api._memory_package_restart_retry_required("3.0.14") is True++ schedule.side_effect = None+ schedule.return_value = {"job_id": "restart"}+ retry = api._prepare_memory_package_job()++ assert retry["ok"] is True+ assert retry["restarting"] is True+ assert build_plan.call_count == 1+ assert execute_plan.call_count == 1+ assert schedule.call_count == 2+ assert api._memory_package_restart_retry_required("3.0.14") is False+++def test_memory_indep_026_auto_repair_persists_a_per_version_attempt_budget(+ monkeypatch,+ tmp_path,+) -> None:+ """MEMORY-INDEP-026: restart loops stop after the persisted attempt budget."""++ state_path = tmp_path / "memory-package-auto-repair.json"+ installs: list[int] = []+ restarts: list[int] = []+ monkeypatch.setattr(api, "_memory_package_auto_repair_state_path", lambda: state_path)+ monkeypatch.setattr(api, "atomic_upgrade_lock", nullcontext)+ monkeypatch.setattr(api, "_memory_package_repair_rejection", lambda **_kwargs: None)+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ 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)+ monkeypatch.setattr(+ api,+ "build_upgrade_plan",+ lambda **_kwargs: SimpleNamespace(+ activation=None,+ method="pip",+ preflight_error=None,+ ),+ )+ monkeypatch.setattr(+ api,+ "execute_upgrade_plan",+ lambda *_args, **_kwargs: installs.append(1)+ or subprocess.CompletedProcess(["repair"], 0, stdout="installed", stderr=""),+ )+ monkeypatch.setattr(+ api,+ "verify_python_environment",+ lambda _python: SimpleNamespace(ok=True, detail="ok"),+ )+ monkeypatch.setattr(+ api,+ "schedule_restart",+ lambda **_kwargs: restarts.append(1) or {"job_id": f"restart-{len(restarts)}"},+ )++ results = [api._prepare_memory_package_job(automatic=True) for _ in range(4)]++ assert len(installs) == len(restarts) == api._MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS+ assert all(result.get("restarting") for result in results[:3])+ assert results[3]["skipped"] is True+ assert results[3]["reason"] == "memory_package_auto_repair_exhausted"+ state = json.loads(state_path.read_text(encoding="utf-8"))+ assert state["core_version"] == "3.0.14"+ assert state["attempts"] == 3+ assert state["result"] == "restart_scheduled"+++def test_memory_auto_repair_budget_resets_only_for_a_new_core_version(monkeypatch, tmp_path) -> None:+ state_path = tmp_path / "memory-package-auto-repair.json"+ monkeypatch.setattr(api, "_memory_package_auto_repair_state_path", lambda: state_path)++ first = api._reserve_memory_package_auto_repair_attempt("3.0.14")+ api._finish_memory_package_auto_repair_attempt(+ "3.0.14",+ first["token"],+ result="failed",+ reason="memory_package_install_failed",+ )+ second = api._reserve_memory_package_auto_repair_attempt("3.0.15")++ assert first["attempts"] == 1+ assert second["attempts"] == 1+ state = json.loads(state_path.read_text(encoding="utf-8"))+ assert state["core_version"] == "3.0.15"+ assert state["result"] == "running"+++def test_memory_package_reachability_disabled_enable_bootstrap_ready(+ monkeypatch,+ tmp_path,+) -> None:+ import time as _t++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ api.V2Config.default().save()+ metadata = {"value": api._MemoryPackageMetadata(0, None)}+ monkeypatch.setattr(api, "_inspect_memory_package_metadata", lambda: metadata["value"])+ monkeypatch.setattr(api, "_published_running_version", lambda: "3.0.14")+ monkeypatch.setattr(api, "get_build_identity", lambda: SimpleNamespace(kind="package"))+ monkeypatch.setattr(api, "probe_memory_runtime_entrypoint", lambda: None)+ monkeypatch.setattr(+ api,+ "_memory_artifact_status",+ lambda **_: (True, {"installed": True, "status": "ready", "matches_manifest": True}),+ )++ disabled, _runtime = api._memory_dependencies_status(offline=True)+ assert (disabled["required"], disabled["status"], disabled["action_class"]) == (+ False,+ "missing",+ "repairable",+ )+ monkeypatch.setattr(+ api,+ "_prepare_memory_package_job",+ lambda **_kwargs: pytest.fail("disabled startup must not auto-install"),+ )+ assert api.reconcile_memory_package_on_startup()["skipped"] is True++ def bootstrap() -> dict:+ metadata["value"] = api._MemoryPackageMetadata(1, "3.0.14")+ return {"ok": True, "message": "memory_package_ready", "output": None}++ monkeypatch.setattr(api, "_prepare_memory_package_job", bootstrap)+ with api._AGENT_INSTALL_JOB_LOCK:+ api._AGENT_INSTALL_JOBS.clear()+ api._AGENT_INSTALL_LATEST_BY_BACKEND.clear()+ started = api.start_dependency_install_job("memory-package")+ result = started+ for _ in range(100):+ result = api.get_agent_install_job(started["job_id"], backend="memory-package")+ if result.get("status") != "running":+ break+ _t.sleep(0.01)+ assert result["status"] == "succeeded"++ optional_ready, _runtime = api._memory_dependencies_status(offline=True)+ assert (optional_ready["readiness"], optional_ready["action_class"]) == (+ "not_required",+ "repairable",+ )+ assert api._memory_package_repair_rejection(allow_optional=True) is None+ monkeypatch.setattr(+ api,+ "_prepare_memory_package_job",+ lambda **_kwargs: pytest.fail("disabled startup must remain a no-op"),+ )+ assert api.reconcile_memory_package_on_startup()["skipped"] is True++ api.save_memory_config(+ {+ "enabled": True,+ "mode": "custom",+ "processing": {+ "llm": {+ "base_url": "https://llm.example.test/v1",+ "model": "chat",+ "api_key": "test-key",+ },+ "embedding": {+ "base_url": "https://embedding.example.test/v1",+ "model": "embedding",+ "api_key": "test-key",+ },+ },+ }+ )+ ready, _runtime = api._memory_dependencies_status(offline=True)+ assert (ready["readiness"], ready["action_class"]) == (+ "ready",+ "none",+ )++def test_start_dependency_install_job_rejects_unknown():assert api.start_dependency_install_job("bogus")["ok"] is Falsediff --git a/tests/test_managed_runtime.py b/tests/test_managed_runtime.pyindex 87e99937b..eb85d1b69 100644--- a/tests/test_managed_runtime.py+++ b/tests/test_managed_runtime.py@@ -24,10 +24,10 @@ from core.managed_runtime import (ManagedRuntimeManifest,ManagedRuntimeSpec,)-from core.memory import artifact as memory_artifact-from core.memory.artifact import MemoryArtifactManager, MemoryRuntimeActivationError-from core.memory.artifact_contract import COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON-from core.memory.provider_root import ProviderRootError+from avibe_memory import artifact as memory_artifact+from avibe_memory.artifact import MemoryArtifactManager, MemoryRuntimeActivationError+from avibe_memory.artifact_contract import COLD_ARTIFACT_ADMISSION_TIMEOUT_REASON+from avibe_memory.provider_root import ProviderRootErrorfrom vibe.model_hub_runtime.installer import EngineRuntimeManagerdiff --git a/tests/test_memory_adapter.py b/tests/test_memory_adapter.pynew file mode 100644index 000000000..96c91ee7f--- /dev/null+++ b/tests/test_memory_adapter.py@@ -0,0 +1,751 @@+from __future__ import annotations++import asyncio+import builtins+import os+import socket+import sqlite3+import subprocess+from contextlib import asynccontextmanager+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++import avibe_memory.capture_adapter as capture_adapter_module+from avibe_memory.capture_adapter import EnabledMemoryAdapter+from avibe_memory.types import CaptureAccepted, CaptureAttachment+from core.memory_adapter import (+ DisabledMemoryAdapter,+ MemoryFile,+ SessionArchived,+ SessionReset,+ TurnAccepted,+)+from core.handlers.message_handler import memory_turn_event+from modules.im.base import FileAttachment, MessageContext+++PRINCIPAL = "u-" + ("1" * 32)+++class _Lease:+ def __init__(self) -> None:+ self.retained = 0+ self.released = 0++ def retain(self) -> _LeaseReference:+ self.retained += 1+ return _LeaseReference(self)+++class _LeaseReference:+ def __init__(self, owner: _Lease) -> None:+ self.owner = owner+ self.active = True++ def release(self) -> None:+ if self.active:+ self.active = False+ self.owner.released += 1+++class _Capacity:+ def __init__(self) -> None:+ self.active = True+++class _Module:+ def __init__(self) -> None:+ self.capacity_outcome: object = None+ self.capacities: list[_Capacity] = []+ self.reservations: list[object] = []+ self.captures: list[object] = []+ self.barriers: list[str] = []+ self.capture_error: BaseException | None = None+ self.capture_started = asyncio.Event()+ self.capture_continue = asyncio.Event()+ self.capture_continue.set()++ def reserve_capture_capacity(self) -> object:+ if isinstance(self.capacity_outcome, str):+ return self.capacity_outcome+ capacity = _Capacity()+ self.capacities.append(capacity)+ return capacity++ def release_capture_capacity(self, reservation: object) -> None:+ if isinstance(reservation, _Capacity):+ reservation.active = False++ def reserve_capture_admission(self, **_scope: object) -> object:+ reservation = SimpleNamespace(active=True)+ self.reservations.append(reservation)+ return reservation++ def cancel_capture_reservation(self, reservation: object) -> None:+ reservation.active = False++ @asynccontextmanager+ async def capture_admission(self, **_options: object):+ admission = SimpleNamespace(release=Mock())+ yield admission++ async def capture(self, request, **_options: object) -> object:+ self.capture_started.set()+ await self.capture_continue.wait()+ if self.capture_error is not None:+ raise self.capture_error+ self.captures.append(request)+ return SimpleNamespace(status="accepted")++ def offer_barrier(self, session_id: str) -> object:+ self.barriers.append(session_id)+ return "queued"++ async def wait_writer_idle_for_tests(self, **_options: object) -> None:+ return None+++class _Principals:+ def __init__(self, forbidden: bool = False) -> None:+ self.forbidden = forbidden+ self.calls = 0++ def principal_for_user_key(self, _user_key: str) -> str:+ self.calls += 1+ if self.forbidden:+ raise AssertionError("offer reached SQLite/store principal derivation")+ return PRINCIPAL++class _Bindings:+ def __init__(self, forbidden: bool = False, enabled: bool = True) -> None:+ self.forbidden = forbidden+ self.enabled = enabled+ self.calls = 0++ def is_enabled_user(self, _platform: str, _user_id: str) -> bool:+ self.calls += 1+ if self.forbidden:+ raise AssertionError("offer reached settings/binding lookup")+ return self.enabled+++class _Lifecycle:+ def __init__(self) -> None:+ self.matches = True+ self.match_calls = 0+ self.acquired = 0+ self.released = 0++ def snapshot_matches(self, _session_id: str, _snapshot: object) -> bool:+ self.match_calls += 1+ return self.matches++ async def acquire(self, _session_id: str) -> object:+ self.acquired += 1+ lifecycle = self++ class Admission:+ def release(self) -> None:+ lifecycle.released += 1++ return Admission()+++def _event(+ *,+ text: str = "remember this",+ lease: object = None,+ files: tuple[MemoryFile, ...] = (),+ snapshot: object = 1,+) -> TurnAccepted:+ return TurnAccepted(+ platform="slack",+ user_id="user-1",+ message_id="native-1",+ session_id="session-1",+ text=text,+ files=files,+ is_dm=True,+ is_ordinary_text=not files,+ is_ordinary_attachment=bool(files),+ lifecycle_snapshot=snapshot,+ attachment_lease=lease,+ )+++def _adapter(+ module: _Module,+ *,+ lifecycle: _Lifecycle | None = None,+ principals: _Principals | None = None,+ bindings: _Bindings | None = None,+ selector=None,+ status_reader=None,+ generation_reader=None,+ task_factory=asyncio.create_task,+ max_pending_events: int = 256,+) -> tuple[EnabledMemoryAdapter, _Lifecycle]:+ lifecycle = lifecycle or _Lifecycle()+ options = {}+ if selector is not None:+ options["attachment_selector"] = selector+ adapter = EnabledMemoryAdapter(+ module=module,+ principals=principals or _Principals(),+ is_enabled_user=(bindings or _Bindings()).is_enabled_user,+ lifecycle_snapshot_matches=lifecycle.snapshot_matches,+ acquire_lifecycle_admission=lifecycle.acquire,+ attachment_capture_status=(+ status_reader or (lambda: asyncio.sleep(0, result="ready"))+ ),+ attachment_config_generation=generation_reader or (lambda: 7),+ max_pending_events=max_pending_events,+ **options,+ )+ assert adapter.start(task_factory=task_factory)+ return adapter, lifecycle+++async def _settle(adapter: EnabledMemoryAdapter) -> None:+ await adapter.wait_idle_for_tests()+ await asyncio.sleep(0)+++def test_non_running_controller_loop_can_schedule_dispatcher() -> None:+ from core.controller import Controller++ loop = asyncio.new_event_loop()+ asyncio.set_event_loop(loop)+ try:+ assert loop.is_running() is False+ module = _Module()+ lifecycle = _Lifecycle()+ adapter = EnabledMemoryAdapter(+ module=module,+ principals=_Principals(),+ is_enabled_user=_Bindings().is_enabled_user,+ lifecycle_snapshot_matches=lifecycle.snapshot_matches,+ acquire_lifecycle_admission=lifecycle.acquire,+ attachment_capture_status=lambda: asyncio.sleep(0, result="ready"),+ attachment_config_generation=lambda: 7,+ )++ class Runtime:+ def start_capture_adapter(self, *, task_factory) -> bool:+ return adapter.start(task_factory=task_factory)++ controller = Controller.__new__(Controller)+ controller._loop = loop+ assert controller._start_memory_capture_adapter(Runtime())+ assert adapter._worker_task is not None+ assert adapter._worker_task.get_loop() is loop+ loop.run_until_complete(adapter.cancel_memory_capture_tasks())+ finally:+ asyncio.set_event_loop(None)+ loop.close()+++def test_disabled_adapter_has_zero_side_effects() -> None:+ """Scenarios: MEMORY-INDEP-001, MEMORY-INDEP-003, MEMORY-INDEP-004."""++ lease = Mock()+ DisabledMemoryAdapter().offer(_event(lease=lease))+ lease.retain.assert_not_called()+++def test_host_event_is_closed_and_uses_authenticated_workbench_author() -> None:+ """Scenario: MEMORY-INDEP-016."""++ file = FileAttachment(+ name="原始.pdf",+ mimetype="application/pdf",+ local_path="/private/original.pdf",+ )+ context = MessageContext(+ user_id="routing-user",+ channel_id="session-1",+ platform="avibe",+ message_id="native-1",+ platform_specific={"author_id": "authenticated-author", "is_dm": False},+ files=[file],+ is_original_human_text=True,+ is_original_human_attachment=True,+ )++ event = memory_turn_event(context, "记住原件", "session-1", (3, 4))+ file.name = "mutated.pdf"+ context.user_id = "mutated-user"+ context.files.clear()++ assert event.user_id == "authenticated-author"+ assert event.text == "记住原件"+ assert event.files == (+ MemoryFile(+ name="原始.pdf",+ mimetype="application/pdf",+ local_path="/private/original.pdf",+ ),+ )+++async def test_offer_hot_path_only_retains_reserves_and_puts_nowait(monkeypatch) -> None:+ """Scenario: MEMORY-INDEP-001; synchronous offer is a strict sentinel."""++ module = _Module()+ principals = _Principals(forbidden=True)+ bindings = _Bindings(forbidden=True)++ def forbidden(*_args, **_kwargs):+ raise AssertionError("offer reached filesystem/SQLite/provider/subprocess work")++ created_tasks: list[str] = []+ create_task = asyncio.create_task++ def task_factory(coroutine, *, name: str):+ created_tasks.append(name)+ return create_task(coroutine, name=name)++ adapter, lifecycle = _adapter(+ module,+ principals=principals,+ bindings=bindings,+ selector=forbidden,+ status_reader=forbidden,+ generation_reader=forbidden,+ task_factory=task_factory,+ )+ lease = _Lease()+ files = (MemoryFile("账单.pdf", "application/pdf"),)++ monkeypatch.setattr(builtins, "open", forbidden)+ monkeypatch.setattr(os, "open", forbidden)+ monkeypatch.setattr(os, "stat", forbidden)+ monkeypatch.setattr(os, "scandir", forbidden)+ monkeypatch.setattr(Path, "open", forbidden)+ monkeypatch.setattr(Path, "stat", forbidden)+ monkeypatch.setattr(sqlite3, "connect", forbidden)+ monkeypatch.setattr(subprocess, "run", forbidden)+ monkeypatch.setattr(subprocess, "Popen", forbidden)+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)+ monkeypatch.setattr(socket, "create_connection", forbidden)+ monkeypatch.setattr(asyncio, "create_task", forbidden)+ monkeypatch.setattr(module, "reserve_capture_admission", forbidden)+ monkeypatch.setattr(module, "capture_admission", forbidden)+ monkeypatch.setattr(module, "capture", forbidden)+ monkeypatch.setattr(module, "offer_barrier", forbidden)++ adapter.offer(_event(text="记住账单", files=files, lease=lease))++ assert lease.retained == 1+ assert lease.released == 0+ assert principals.calls == 0+ assert bindings.calls == 0+ assert lifecycle.match_calls == lifecycle.acquired == 0+ assert module.captures == []+ assert created_tasks == ["memory-capture-dispatcher"]+ monkeypatch.undo()+ await adapter.cancel_memory_capture_tasks()+ assert lease.released == 1+++async def test_success_releases_one_retained_lease_and_forwards_capture() -> None:+ """Scenarios: MEMORY-INDEP-001, MEMORY-IM-ATTACH-001."""++ module = _Module()+ attachment = CaptureAttachment(+ kind="pdf",+ name="账单.pdf",+ uri="file:///private/账单.pdf",+ ext="pdf",+ )+ selector = lambda _lease: SimpleNamespace(attachments=(attachment,), skipped=())+ adapter, lifecycle = _adapter(module, selector=selector)+ lease = _Lease()++ adapter.offer(+ _event(+ text="请记住这张账单",+ files=(MemoryFile("账单.pdf", "application/pdf"),),+ lease=lease,+ )+ )+ await _settle(adapter)++ assert [request.text for request in module.captures] == ["请记住这张账单"]+ assert module.captures[0].attachments == (attachment,)+ assert lease.retained == lease.released == 1+ assert lifecycle.acquired == lifecycle.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_attachment_capture_telemetry_accounts_each_terminal_path_once(+ monkeypatch,+) -> None:+ records: list[tuple[str, int, int]] = []+ monkeypatch.setattr(+ capture_adapter_module,+ "log_attachment_capture",+ lambda platform, total, captured: records.append(+ (platform, total, captured)+ ),+ )+ files = (MemoryFile("receipt.pdf", "application/pdf"),)++ capacity_module = _Module()+ capacity_module.capacity_outcome = "full"+ capacity_adapter, _ = _adapter(capacity_module)+ capacity_adapter.offer(_event(files=files))+ await capacity_adapter.cancel_memory_capture_tasks()++ denied_module = _Module()+ denied_adapter, _ = _adapter(+ denied_module,+ bindings=_Bindings(enabled=False),+ )+ denied_adapter.offer(_event(files=files))+ await _settle(denied_adapter)+ await denied_adapter.cancel_memory_capture_tasks()++ stale_module = _Module()+ stale_lifecycle = _Lifecycle()+ stale_lifecycle.matches = False+ stale_adapter, _ = _adapter(stale_module, lifecycle=stale_lifecycle)+ stale_adapter.offer(_event(files=files))+ await _settle(stale_adapter)+ await stale_adapter.cancel_memory_capture_tasks()++ accepted_module = _Module()++ async def accept_capture(*_args, **_kwargs):+ return CaptureAccepted(captured_attachment_count=1)++ accepted_module.capture = accept_capture+ accepted_adapter, _ = _adapter(+ accepted_module,+ selector=lambda _lease: SimpleNamespace(+ attachments=(+ CaptureAttachment(+ kind="pdf",+ name="receipt.pdf",+ uri="file:///private/receipt.pdf",+ ext="pdf",+ ),+ ),+ skipped=(),+ ),+ )+ accepted_adapter.offer(_event(files=files, lease=_Lease()))+ await _settle(accepted_adapter)+ await accepted_adapter.cancel_memory_capture_tasks()++ assert records == [+ ("slack", 1, 0),+ ("slack", 1, 0),+ ("slack", 1, 0),+ ("slack", 1, 1),+ ]+++async def test_denied_attachment_is_rejected_before_any_preparation() -> None:+ module = _Module()+ bindings = _Bindings(enabled=False)+ generation = Mock(side_effect=AssertionError("generation read before authorization"))+ status = Mock(side_effect=AssertionError("status read before authorization"))+ selector = Mock(side_effect=AssertionError("selection ran before authorization"))+ adapter, _ = _adapter(+ module,+ bindings=bindings,+ generation_reader=generation,+ status_reader=status,+ selector=selector,+ )+ lease = _Lease()++ adapter.offer(+ _event(+ text="private caption",+ files=(MemoryFile("private.pdf", "application/pdf"),),+ lease=lease,+ )+ )+ await _settle(adapter)++ assert bindings.calls == 1+ generation.assert_not_called()+ status.assert_not_called()+ selector.assert_not_called()+ assert module.captures == []+ assert lease.retained == lease.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_missing_generation_skips_provider_probe_and_degrades_caption() -> None:+ module = _Module()+ status = Mock(side_effect=AssertionError("provider probed without opt-in"))+ selector = Mock(side_effect=AssertionError("selection ran without opt-in"))+ adapter, _ = _adapter(+ module,+ generation_reader=lambda: None,+ status_reader=status,+ selector=selector,+ )+ lease = _Lease()++ adapter.offer(+ _event(+ text="caption survives",+ files=(MemoryFile("receipt.pdf", "application/pdf"),),+ lease=lease,+ )+ )+ await _settle(adapter)++ status.assert_not_called()+ selector.assert_not_called()+ assert len(module.captures) == 1+ assert module.captures[0].attachments == ()+ assert lease.retained == lease.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_queue_full_releases_rejected_and_shutdown_releases_queued_lease() -> None:+ module = _Module()+ adapter, _ = _adapter(module, max_pending_events=1)+ first = _Lease()+ rejected = _Lease()++ adapter.offer(_event(lease=first))+ adapter.offer(_event(lease=rejected))++ assert rejected.retained == rejected.released == 1+ await adapter.cancel_memory_capture_tasks()+ assert first.retained == first.released == 1+++async def test_capture_scheduling_failure_releases_retained_lease() -> None:+ """Scenario: MEMORY-INDEP-006."""+ module = _Module()++ def task_factory(coroutine, *, name: str):+ if name == "memory-capture":+ raise RuntimeError("registration failed")+ return asyncio.create_task(coroutine, name=name)++ adapter, _ = _adapter(module, task_factory=task_factory)+ lease = _Lease()+ adapter.offer(_event(lease=lease))+ await _settle(adapter)++ assert lease.retained == lease.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_capture_registration_failure_joins_task_before_releasing_lease() -> None:+ """Scenario: MEMORY-INDEP-006."""++ module = _Module()+ adapter, _ = _adapter(module)+ adapter._track_capture_task = Mock(side_effect=RuntimeError("registration failed"))+ lease = _Lease()+ adapter.offer(_event(lease=lease))+ await _settle(adapter)++ assert lease.retained == lease.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_pre_first_step_cancellation_releases_all_ownership() -> None:+ module = _Module()+ adapter, _ = _adapter(module)+ original_track = adapter._track_capture_task++ def track_then_cancel(task, session_id, ownership):+ original_track(task, session_id, ownership)+ task.cancel()++ adapter._track_capture_task = track_then_cancel+ lease = _Lease()+ adapter.offer(_event(lease=lease))+ await _settle(adapter)++ assert module.captures == []+ assert lease.retained == lease.released == 1+ assert module.capacities and all(not item.active for item in module.capacities)+ assert module.reservations and all(+ not item.active for item in module.reservations+ )+ assert adapter.capture_tasks == set()+ await adapter.cancel_memory_capture_tasks()+++def test_controller_passes_only_fresh_binding_callable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import core.controller as controller_module+ from config.v2_config import MemoryConfig+ from core.controller import Controller++ calls: list[str] = []+ passed: dict[str, object] = {}++ class Store:+ def maybe_reload(self) -> None:+ calls.append("reload")++ def get_user(self, user_id: str, *, platform: str):+ calls.append(f"lookup:{platform}:{user_id}")+ return SimpleNamespace(enabled=False)++ def load_runtime(_config, **kwargs):+ passed.update(kwargs)+ return object()++ monkeypatch.setattr(controller_module, "load_memory_runtime", load_runtime)+ controller = Controller.__new__(Controller)+ controller.platform_settings_managers = {+ "slack": SimpleNamespace(get_store=lambda: Store())+ }+ controller.session_turns = SimpleNamespace(+ session_lifecycle_snapshot_matches=lambda *_args: True,+ acquire_lifecycle_admission=lambda *_args: None,+ )+ controller._log_memory_processing_event = lambda *_args: None+ controller._adopt_settled_memory_config = lambda _config: None++ assert controller._create_memory_runtime(MemoryConfig(enabled=True)) is not None+ assert "platform_settings_managers" not in passed+ is_enabled_user = passed["is_enabled_user"]+ assert callable(is_enabled_user)+ assert is_enabled_user("slack", "user-1") is False+ assert calls == ["reload", "lookup:slack:user-1"]+++async def test_worker_failure_and_stale_lifecycle_each_release_exactly_once() -> None:+ """Scenario: MEMORY-INDEP-002."""+ module = _Module()+ module.capture_error = RuntimeError("worker failed")+ adapter, lifecycle = _adapter(module)+ failed = _Lease()+ adapter.offer(_event(lease=failed))+ await _settle(adapter)+ assert failed.retained == failed.released == 1++ lifecycle.matches = False+ stale = _Lease()+ adapter.offer(_event(lease=stale, snapshot=2))+ await _settle(adapter)+ assert stale.retained == stale.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_session_and_shutdown_cancellation_release_active_leases() -> None:+ """Scenarios: MEMORY-INDEP-001, MEMORY-INDEP-003, MEMORY-INDEP-008."""+ module = _Module()+ module.capture_continue.clear()+ adapter, _ = _adapter(module)+ abandoned = _Lease()+ adapter.offer(_event(lease=abandoned))+ await module.capture_started.wait()+ adapter.abandon_memory_captures_for_session("session-1")+ await _settle(adapter)+ assert abandoned.retained == abandoned.released == 1++ module.capture_started.clear()+ shutdown = _Lease()+ adapter.offer(_event(lease=shutdown))+ await module.capture_started.wait()+ await adapter.cancel_memory_capture_tasks()+ assert shutdown.retained == shutdown.released == 1+++ "text,expected_captures",+ [("caption survives", 1), ("", 0)],+)+async def test_unavailable_attachment_preparation_degrades_or_fails_closed(+ text: str,+ expected_captures: int,+) -> None:+ """Scenarios: MEMORY-IM-ATTACH-003, MEMORY-IM-ATTACH-004."""++ module = _Module()+ adapter, _ = _adapter(module, selector=lambda _lease: None)+ lease = _Lease()+ adapter.offer(+ _event(+ text=text,+ files=(MemoryFile("receipt.pdf", "application/pdf"),),+ lease=lease,+ )+ )+ await _settle(adapter)++ assert len(module.captures) == expected_captures+ if module.captures:+ assert module.captures[0].attachments == ()+ assert lease.retained == lease.released == 1+ await adapter.cancel_memory_capture_tasks()+++async def test_reset_and_archive_events_preserve_barriers() -> None:+ """Scenarios: MEMORY-INDEP-005, MEMORY-INDEP-010."""++ module = _Module()+ first_started = asyncio.Event()+ first_continue = asyncio.Event()+ second_started = asyncio.Event()++ async def capture(request, **_options: object) -> object:+ if request.text == "first capture":+ first_started.set()+ await first_continue.wait()+ else:+ second_started.set()+ module.captures.append(request)+ return SimpleNamespace(status="accepted")++ module.capture = capture+ adapter, _ = _adapter(module)++ first_lease = _Lease()+ second_lease = _Lease()+ adapter.offer(_event(text="first capture", lease=first_lease))+ await asyncio.wait_for(first_started.wait(), timeout=1.0)++ adapter.offer(_event(text="second capture", lease=second_lease))+ adapter.offer(SessionReset("session-reset"))+ adapter.offer(SessionArchived("session-archived"))+ await asyncio.wait_for(second_started.wait(), timeout=1.0)++ async def wait_for_barriers() -> None:+ while len(module.barriers) < 2:+ await asyncio.sleep(0)++ await asyncio.wait_for(wait_for_barriers(), timeout=1.0)++ assert module.barriers == ["session-reset", "session-archived"]+ assert [request.text for request in module.captures] == ["second capture"]+ assert first_lease.retained == 1+ assert first_lease.released == 0+ assert second_lease.retained == second_lease.released == 1++ first_continue.set()+ await _settle(adapter)+ assert first_lease.retained == first_lease.released == 1+ await adapter.cancel_memory_capture_tasks()diff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.pyindex 2cc95fcd7..60aef705f 100644--- a/tests/test_memory_admission.py+++ b/tests/test_memory_admission.py@@ -11,21 +11,24 @@ from types import SimpleNamespaceimport pytest-from core.memory.admission import (- MEMORY_CLI_ADMITTED_METADATA,- MEMORY_ORDINARY_TEXT_METADATA,- MEMORY_USER_ID_METADATA,+from avibe_memory.admission import (CaptureAdmission,InboundTurnFacts,- is_cli_admitted,- is_ordinary_text,- merge_identity,)-from core.memory.attachments import workbench_capture_attachments-from core.memory.types import CaptureAttachment, CaptureRequest, CaptureSkipped+from avibe_memory.attachments import workbench_capture_attachments+from avibe_memory.im_attachments import select_memory_attachments+from avibe_memory.types import CaptureAttachment, CaptureRequest, CaptureSkippedfrom core.handlers.inbound_attachments import InboundAttachmentMaterializerfrom modules.im.base import FileAttachment, FileDownloadResult, MessageContext-from modules.im.message_facts import is_ordinary_workbench_text+from modules.im.message_facts import is_original_human_workbench_text+from storage.message_deliveries import (+ LEGACY_MEMORY_CLI_ADMITTED_METADATA as MEMORY_CLI_ADMITTED_METADATA,+ LEGACY_MEMORY_ORDINARY_TEXT_METADATA as MEMORY_ORDINARY_TEXT_METADATA,+ LEGACY_MEMORY_USER_ID_METADATA as MEMORY_USER_ID_METADATA,+ legacy_is_cli_admitted as is_cli_admitted,+ legacy_is_ordinary_text as is_ordinary_text,+ legacy_memory_merge_identity as merge_identity,+)PRINCIPAL = "u-" + ("1" * 32)@@ -45,12 +48,6 @@ class _Principals:self.keys.append(user_key)return PRINCIPAL- def project_for_workdir(self, workdir: str) -> str:- if self.raises:- raise RuntimeError("memory store unavailable")- return PROJECT--class _Bindings:def __init__(self, *, enabled: bool = True, raises: bool = False) -> None:self.enabled = enabled@@ -79,7 +76,6 @@ def _facts(**overrides) -> InboundTurnFacts:"text": "ordinary text","is_dm": True,"is_ordinary_text": True,- "memory_enabled": True,}return InboundTurnFacts(**{**defaults, **overrides})@@ -212,7 +208,6 @@ def test_user_turns_capture_into_default_without_a_workdir() -> None:@pytest.mark.parametrize("facts,reason",[- (_facts(memory_enabled=False), "memory_disabled"),(_facts(is_dm=False), "memory_access_denied"),(_facts(message_id=None), "memory_invalid_input"),(_facts(message_id=""), "memory_invalid_input"),@@ -241,15 +236,6 @@ def test_a_non_bool_is_dm_never_admits_a_public_channel_turn(malformed: object)assert admission.decide(facts) == CaptureSkipped(reason="memory_access_denied")[email protected]("malformed", ["false", "true", "0", "1", 0, 1, None, "", []])-def test_a_non_bool_memory_enabled_never_enables_capture(malformed: object) -> None:- """A mis-typed enablement flag must read as disabled, not as consent."""-- assert _admission().decide(_facts(memory_enabled=malformed)) == CaptureSkipped(- reason="memory_disabled"- )--@pytest.mark.parametrize("malformed", ["true", "1", 1, "ordinary"])def test_a_non_bool_is_ordinary_text_is_not_a_classification(malformed: object) -> None:"""Only the surface's literal `True` counts as "this is ordinary human text"."""@@ -262,7 +248,7 @@ def test_a_non_bool_is_ordinary_text_is_not_a_classification(malformed: object)def test_a_literal_true_still_admits_after_strict_normalization() -> None:"""The strict reading must not reject the well-behaved surfaces."""- assert isinstance(_admission().decide(_facts(is_dm=True, memory_enabled=True)), CaptureRequest)+ assert isinstance(_admission().decide(_facts(is_dm=True)), CaptureRequest)def test_bound_slack_attachment_turn_selects_only_the_materialized_lease(@@ -281,6 +267,7 @@ def test_bound_slack_attachment_turn_selects_only_the_materialized_lease(attachment_lease=batch.lease,attachment_capture_status="ready",attachment_config_generation=1,+ attachment_selection=select_memory_attachments(batch.lease),))finally:@@ -354,21 +341,22 @@ def test_im_attachment_only_turn_with_every_upload_filtered_is_not_captured() ->],)def test_denied_attachment_turn_never_reads_the_lease(- monkeypatch: pytest.MonkeyPatch,overrides: dict[str, object],) -> None:"""Scenario: MEMORY-IM-ATTACH-002."""- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: pytest.fail("denied turn reached Memory attachment selection"),- )+ class ForbiddenSelection:+ @property+ def attachments(self):+ pytest.fail("denied turn reached Memory attachment selection")+facts = _facts(**{"files": [object()],"is_ordinary_text": False,"is_ordinary_attachment": True,"attachment_capture_status": "ready",+ "attachment_selection": ForbiddenSelection(),**overrides,})@@ -396,17 +384,7 @@ def test_not_configured_attachment_turn_keeps_safe_caption() -> None:assert request.attachments == ()-def test_mixed_attachment_rejections_keep_caption(- monkeypatch: pytest.MonkeyPatch,-) -> None:- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: SimpleNamespace(- attachments=(),- skipped=("file_too_large", "unsupported_type"),- ),- )-+def test_mixed_attachment_rejections_keep_caption() -> None:request = _admission().decide(_facts(text="safe caption",@@ -416,6 +394,10 @@ def test_mixed_attachment_rejections_keep_caption(attachment_lease=object(),attachment_capture_status="ready",attachment_config_generation=1,+ attachment_selection=SimpleNamespace(+ attachments=(),+ skipped=("file_too_large", "unsupported_type"),+ ),))@@ -423,62 +405,12 @@ def test_mixed_attachment_rejections_keep_caption(assert request.attachments == ()-def test_unexpected_attachment_selection_failure_keeps_text(- monkeypatch: pytest.MonkeyPatch,- caplog: pytest.LogCaptureFixture,-) -> None:- """Scenario: MEMORY-IM-ATTACH-004."""-- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: (_ for _ in ()).throw(- RuntimeError("secret attachment name must not be logged")- ),- )- caplog.set_level("INFO", logger="core.memory.admission")-- request = _admission().decide(- _facts(- text="keep this caption",- files=[object()],- is_ordinary_text=False,- is_ordinary_attachment=True,- attachment_lease=object(),- attachment_capture_status="ready",- attachment_config_generation=9,- )- )-- assert isinstance(request, CaptureRequest)- assert request.text == "keep this caption"- assert request.attachments == ()- warnings = [- record- for record in caplog.records- if record.message.startswith("memory_attachment_selection_failed")- ]- assert len(warnings) == 1- assert "error_type=RuntimeError" in warnings[0].getMessage()- assert "secret attachment name" not in caplog.text---def test_disabled_memory_is_answered_before_any_directory_lookup() -> None:- principals = _Principals(raises=True)- bindings = _Bindings(raises=True)-- decision = _admission(principals=principals, bindings=bindings).decide(- _facts(memory_enabled=False)- )-- assert decision == CaptureSkipped(reason="memory_disabled")--def test_workbench_attachment_only_turn_is_captured(monkeypatch, tmp_path: Path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))attachment = tmp_path / "attachments" / "avibe" / "receipt.pdf"attachment.parent.mkdir(parents=True)attachment.write_bytes(b"pdf")- ordinary = is_ordinary_workbench_text(+ ordinary = is_original_human_workbench_text({"content": {"attachments": [{"token": "receipt"}]}},None,)@@ -546,7 +478,7 @@ def test_only_extensions_the_provider_can_parse_become_attachments(monkeypatch,assert [attachment.kind for attachment in converted] == ["doc", "pdf", "image"]def test_workbench_turn_of_only_unparseable_uploads_is_not_captured(monkeypatch, tmp_path: Path) -> None:uploads = _uploads_dir(monkeypatch, tmp_path)- ordinary = is_ordinary_workbench_text(+ ordinary = is_original_human_workbench_text({"content": {"attachments": [{"token": "export"}]}},None,)@@ -635,19 +567,19 @@ def test_merge_identity_normalizes_unusable_metadata(assert is_cli_admitted(metadata) is expected[2]-def test_delivery_store_shares_metadata_keys_without_capture_admission() -> None:- """Storage can name the keys without loading CaptureAdmission or aiohttp."""+def test_delivery_store_uses_only_legacy_translation_without_capture_admission() -> None:+ """Storage can translate released rows without loading Memory runtime code."""script = """import sysfrom storage import message_deliveries-from core.memory.admission_metadata import MEMORY_USER_ID_METADATA-assert message_deliveries.MEMORY_USER_ID_METADATA is MEMORY_USER_ID_METADATA-assert "core.memory.admission" not in sys.modules-assert "core.memory.im_attachments" not in sys.modules-assert "core.memory.module" not in sys.modules-assert "core.memory.store" not in sys.modules-assert "core.memory.types" not in sys.modules+assert message_deliveries.legacy_message_kind({"_memory_ordinary_text": True}) == "original"+assert not any(name == "avibe_memory" or name.startswith("avibe_memory.") for name in sys.modules)+assert "avibe_memory.admission" not in sys.modules+assert "avibe_memory.im_attachments" not in sys.modules+assert "avibe_memory.module" not in sys.modules+assert "avibe_memory.store" not in sys.modules+assert "avibe_memory.types" not in sys.modulesassert "core.handlers" not in sys.modulesassert "httpx" not in sys.modules"""@@ -670,12 +602,12 @@ def test_session_turns_import_keeps_memory_and_handlers_behind_their_boundaries(script = """import sysimport core.session_turns-assert "core.memory.admission" not in sys.modules-assert "core.memory.attachments" not in sys.modules-assert "core.memory.im_attachments" not in sys.modules-assert "core.memory.module" not in sys.modules-assert "core.memory.runtime" not in sys.modules-assert "core.memory.types" not in sys.modules+assert "avibe_memory.admission" not in sys.modules+assert "avibe_memory.attachments" not in sys.modules+assert "avibe_memory.im_attachments" not in sys.modules+assert "avibe_memory.module" not in sys.modules+assert "avibe_memory.runtime" not in sys.modules+assert "avibe_memory.types" not in sys.modulesassert "core.handlers" not in sys.modulesassert "core.handlers.message_handler" not in sys.modulesassert "aiohttp" not in sys.modules@@ -691,16 +623,16 @@ assert "aiohttp" not in sys.modulesdef test_workbench_submits_are_classified_beside_their_im_siblings() -> None:- assert is_ordinary_workbench_text({"text": "hello"}, None) is True- assert is_ordinary_workbench_text({"text": "hello"}, "msg-7") is False+ assert is_original_human_workbench_text({"text": "hello"}, None) is True+ assert is_original_human_workbench_text({"text": "hello"}, "msg-7") is Falseassert (- is_ordinary_workbench_text(+ is_original_human_workbench_text({"content": {"attachments": [{"token": "upload-1"}]}},None,)is True)- assert is_ordinary_workbench_text({"files": [{"name": "a.png"}]}, None) is True- assert is_ordinary_workbench_text({"metadata": {"forwarded": True}}, None) is False- assert is_ordinary_workbench_text({"metadata": {"forward_origin": "chat"}}, None) is False- assert is_ordinary_workbench_text("not a payload", None) is False+ assert is_original_human_workbench_text({"files": [{"name": "a.png"}]}, None) is True+ assert is_original_human_workbench_text({"metadata": {"forwarded": True}}, None) is False+ assert is_original_human_workbench_text({"metadata": {"forward_origin": "chat"}}, None) is False+ assert is_original_human_workbench_text("not a payload", None) is Falsediff --git a/tests/test_memory_artifact_contract.py b/tests/test_memory_artifact_contract.pyindex 60fcbf60d..91493d1e5 100644--- a/tests/test_memory_artifact_contract.py+++ b/tests/test_memory_artifact_contract.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport subprocessfrom pathlib import Path-from core.memory import artifact_contract+from avibe_memory import artifact_contractdef test_cold_artifact_admission_is_bounded_and_warms_the_runtime(diff --git a/tests/test_memory_attachment_drop_accounting.py b/tests/test_memory_attachment_drop_accounting.pydeleted file mode 100644index 1688b6c48..000000000--- a/tests/test_memory_attachment_drop_accounting.py+++ /dev/null@@ -1,143 +0,0 @@-"""Result-driven telemetry for IM attachment capture attempts."""--from __future__ import annotations--from pathlib import Path-from types import SimpleNamespace-from unittest.mock import Mock--import pytest--from core.memory.attachments import AttachmentPinError-from core.memory.types import CaptureAttachment-from modules.im.base import FileAttachment---def _attachment_context(message_id: str, count: int):- from tests.test_memory_slice3 import _context-- context = _context("slack", ordinary=False)- context.message_id = message_id- context.files = [- FileAttachment(- name=f"attachment-{index}.pdf",- mimetype="application/pdf",- url=f"https://files.slack.test/private/{index}",- )- for index in range(count)- ]- context.is_ordinary_attachment = True- return context---def _assert_single_conservation_record(- caplog: pytest.LogCaptureFixture,- *,- total: int,- captured: int,-) -> None:- records = [- record.getMessage()- for record in caplog.records- if record.message.startswith("memory_attachment_capture ")- ]- assert len(records) == 1- fields = dict(part.split("=", 1) for part in records[0].split()[1:])- assert set(fields) == {"platform", "total", "captured", "dropped"}- assert fields["platform"] == "slack"- assert int(fields["total"]) == total- assert int(fields["captured"]) == captured- assert int(fields["dropped"]) == total - captured---async def test_attachment_capture_telemetry_uses_terminal_result(- monkeypatch: pytest.MonkeyPatch,- caplog: pytest.LogCaptureFixture,- tmp_path: Path,-) -> None:- """Scenario: MEMORY-IM-ATTACH-004."""-- from tests.test_memory_module import _module- from tests.test_memory_slice3 import _Runtime, _controller-- caplog.set_level("INFO", logger="core.memory.admission")-- # A partial download followed by reservation failure reaches the terminal- # text-only result with no captured attachments.- controller = _controller()- controller.memory_module.reserve_capture_admission = Mock(- side_effect=RuntimeError("reservation unavailable")- )- context = _attachment_context("reservation-failure", 2)- assert (- controller.reserve_memory_attachment_capture(context, "stable-session")- is None- )- await controller.capture_user_memory(- context,- "keep this caption",- "stable-session",- )- _assert_single_conservation_record(caplog, total=2, captured=0)-- # The stale state produced when /new wins during materialization follows the- # same no-reservation path and still emits exactly one terminal record.- caplog.clear()- controller = _controller()- context = _attachment_context("stale-after-reset", 1)- await controller.capture_user_memory(- context,- "keep this caption",- "stable-session",- )- _assert_single_conservation_record(caplog, total=1, captured=0)-- # One materialized survivor reaches pinning, but the terminal text fallback- # reports zero because no attachment bundle was actually enqueued.- caplog.clear()- module, _store, provider = _module(tmp_path)- attachment_store = module._attachment_store- controller = _controller()- controller.memory_module = module- controller.memory_runtime = _Runtime(module)- source = tmp_path / "attachments" / "avibe" / "survivor.pdf"- source.parent.mkdir(parents=True, exist_ok=True)- source.write_bytes(b"survivor")- survivor = CaptureAttachment(- kind="pdf",- name="survivor.pdf",- uri=source.as_uri(),- ext="pdf",- )- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: SimpleNamespace(attachments=(survivor,), skipped=()),- )-- def fail_pin(*_args, **_kwargs):- raise AttachmentPinError(- "memory_store_unavailable",- "leased source changed before pinning",- )-- monkeypatch.setattr(attachment_store, "pin", fail_pin)- context = _attachment_context("pin-failure", 2)- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None- await controller.capture_user_memory(- context,- "keep this caption",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- )- await module.wait_writer_idle_for_tests()- assert len(provider.captures) == 1- assert provider.captures[0].text == "keep this caption"- assert provider.captures[0].attachments == ()- await module.close_writer()- _assert_single_conservation_record(caplog, total=2, captured=0)diff --git a/tests/test_memory_attachments.py b/tests/test_memory_attachments.pyindex e7c339a95..96715bab6 100644--- a/tests/test_memory_attachments.py+++ b/tests/test_memory_attachments.py@@ -12,9 +12,9 @@ from urllib.parse import quoteimport pytest-import core.memory.attachments as attachment_module-import core.memory.confined_filesystem as confined_filesystem_module-from core.memory.attachments import (+import avibe_memory.attachments as attachment_module+import avibe_memory.confined_filesystem as confined_filesystem_module+from avibe_memory.attachments import (AttachmentBundleInvalidError,AttachmentCleanupUnprovenError,AttachmentPinError,@@ -23,7 +23,7 @@ from core.memory.attachments import (PinnedBundle,workbench_capture_attachments,)-from core.memory.types import CaptureAttachment+from avibe_memory.types import CaptureAttachment@pytest.fixturediff --git a/tests/test_memory_blocking.py b/tests/test_memory_blocking.pyindex 6c6d6a034..572aa51fe 100644--- a/tests/test_memory_blocking.py+++ b/tests/test_memory_blocking.py@@ -6,7 +6,7 @@ from concurrent.futures import ThreadPoolExecutorimport pytest-from core.memory.blocking import run_blocking+from core.blocking import run_blockingdef test_run_blocking_returns_operation_result() -> None:diff --git a/tests/test_memory_cli.py b/tests/test_memory_cli.pyindex 7d45eff1f..fa25721cf 100644--- a/tests/test_memory_cli.py+++ b/tests/test_memory_cli.py@@ -2,6 +2,7 @@from __future__ import annotations+import builtinsimport jsonimport shlexfrom pathlib import Path@@ -9,7 +10,7 @@ from pathlib import Pathimport pytestfrom core.caller_context import AVIBE_SESSION_ID_ENV-from core.memory.types import MAX_AGENTIC_TIMEOUT_SECONDS, RecallPolicy+from avibe_memory.types import MAX_AGENTIC_TIMEOUT_SECONDS, RecallPolicyfrom core.system_prompt_injection import _MEMORY_CLI_PROMPTfrom vibe import cli, internal_client@@ -403,6 +404,34 @@ def test_memory_status_json_returns_a_closed_service_down_code(monkeypatch, caps}+def test_memory_status_does_not_import_optional_implementation(monkeypatch, capsys) -> None:+ args = cli.build_parser().parse_args(["memory", "status", "--json"])+ original_import = builtins.__import__++ def core_only_import(name, *args, **kwargs):+ if name == "avibe_memory" or name.startswith("avibe_memory."):+ raise ModuleNotFoundError(name)+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", core_only_import)+ monkeypatch.setattr(+ internal_client,+ "memory_status_sync",+ lambda **_kwargs: {+ "status_code": 503,+ "body": {+ "status": "failed",+ "error": "memory_implementation_unavailable",+ },+ },+ )++ assert cli.cmd_memory(args) == 1+ assert json.loads(capsys.readouterr().out)["code"] == (+ "memory_implementation_unavailable"+ )++def test_memory_cli_passes_agent_session_to_the_internal_boundary(monkeypatch, capsys) -> None:args = cli.build_parser().parse_args(["memory", "status", "--json"])calls: list[dict[str, str | None]] = []@@ -564,7 +593,37 @@ def test_memory_cli_locale_read_failure_keeps_closed_service_down_error(monkeypamonkeypatch.setattr(internal_client, "memory_status_sync", unavailable)assert cli.cmd_memory(args) == 1- assert capsys.readouterr().err.strip() == "Memory status failed: memory_sidecar_unavailable"+ assert capsys.readouterr().err.strip() == "Memory status failed: Memory sidecar unavailable"+++ ("code", "label"),+ [+ ("memory_implementation_unavailable", "Memory implementation unavailable"),+ ("memory_implementation_incompatible", "Memory implementation is incompatible"),+ ],+)+def test_memory_cli_implementation_failure_localizes_human_error_without_changing_json_code(+ monkeypatch,+ capsys,+ code,+ label,+) -> None:+ args = cli.build_parser().parse_args(["memory", "status"])+ monkeypatch.setattr(cli, "_memory_cli_language", lambda: "en")+ monkeypatch.setattr(+ internal_client,+ "memory_status_sync",+ lambda **_kwargs: {+ "status_code": 503,+ "body": {"status": "failed", "error": code},+ },+ )++ assert cli.cmd_memory(args) == 1+ error = capsys.readouterr().err.strip()+ assert label in error+ assert code not in error@pytest.mark.parametrize("outcome", ["accepted", "duplicate"])diff --git a/tests/test_memory_confined_filesystem.py b/tests/test_memory_confined_filesystem.pyindex 622211a6e..4653afbc3 100644--- a/tests/test_memory_confined_filesystem.py+++ b/tests/test_memory_confined_filesystem.py@@ -11,7 +11,7 @@ from pathlib import Pathimport pytest-from core.memory.confined_filesystem import (+from avibe_memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,PrivateSqliteDatabase,@@ -62,12 +62,12 @@ delattr(os, "O_NOFOLLOW")# Importing ordinary application wiring must remain usable when only Memory# persistence is unsupported on the host.import core.controller # noqa: F401-from core.memory.attachments import AttachmentPinError, AttachmentPinStore-from core.memory.confined_filesystem import ConfinedFilesystemError, PrivateSqliteDatabase+from avibe_memory.attachments import AttachmentPinError, AttachmentPinStore+from avibe_memory.confined_filesystem import ConfinedFilesystemError, PrivateSqliteDatabasefrom config.v2_config import MemoryConfig-from core.memory.artifact import MemoryArtifactManager-from core.memory.runtime import create_memory_runtime-from core.memory.provider_root import ProviderRoot, ProviderRootError, ProviderRootMetadata+from avibe_memory.artifact import MemoryArtifactManager+from avibe_memory.runtime import create_memory_runtime+from avibe_memory.provider_root import ProviderRoot, ProviderRootError, ProviderRootMetadatahome = Path(sys.argv[1])try:AttachmentPinStore(effective_home=home, source_root=home / "source")@@ -134,7 +134,7 @@ assert not home.exists()def test_supported_host_exposes_strict_no_follow_capability() -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemassert confined_filesystem.required_no_follow_flag() == os.O_NOFOLLOW@@ -142,7 +142,7 @@ def test_supported_host_exposes_strict_no_follow_capability() -> None:def test_spilled_directory_order_preserves_raw_filename_order_across_batches(monkeypatch: pytest.MonkeyPatch,) -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemnames = ["z", "a", "\udcff", "\udc80", "middle"]@@ -170,7 +170,7 @@ def test_spilled_directory_order_preserves_raw_filename_order_across_batches(def test_spilled_directory_order_translates_connect_failure(monkeypatch: pytest.MonkeyPatch,) -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemfailure = sqlite3.OperationalError("temporary database unavailable")@@ -188,7 +188,7 @@ def test_spilled_directory_order_translates_connect_failure(def test_spilled_directory_order_closes_and_translates_schema_failure(monkeypatch: pytest.MonkeyPatch,) -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_connection = sqlite3.connect("")failure = sqlite3.OperationalError("temporary schema unavailable")@@ -226,7 +226,7 @@ def test_spilled_directory_order_closes_after_operation_database_failure(monkeypatch: pytest.MonkeyPatch,failure_stage: str,) -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemclass Entry:name = "entry"@@ -279,7 +279,7 @@ def test_spilled_directory_order_closes_after_operation_database_failure(def test_spilled_directory_order_closes_temporary_database_on_base_exception() -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemclass InjectedCancellation(BaseException):pass@@ -303,7 +303,7 @@ def test_spilled_directory_order_closes_on_scan_failure_and_cancellation(monkeypatch: pytest.MonkeyPatch,failure: BaseException,) -> None:- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemclass FailingScandir:def __enter__(self):@@ -351,7 +351,7 @@ def test_remove_confined_path_refuses_to_follow_a_swapped_directory(victim.write_text("outside must survive", encoding="utf-8")moved = home / "held-managed"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_scandir = confined_filesystem.os.scandirswapped = False@@ -383,7 +383,7 @@ def test_remove_confined_path_rejects_root_swap_before_directory_open(target.mkdir(mode=0o700)held = home / "held-managed"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_connect = confined_filesystem.sqlite3.connectswapped = False@@ -417,7 +417,7 @@ def test_remove_confined_regular_file_does_not_initialize_directory_ordering(target.chmod(0o600)connect_calls = 0- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemdef fail_connect(*_args, **_kwargs):nonlocal connect_calls@@ -476,7 +476,7 @@ def test_confined_atomic_replace_stays_on_pinned_parent_during_directory_swap(sentinel.write_text("outside survives", encoding="utf-8")held = home / "held-managed"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_replace = confined_filesystem.os.replaceswapped = False@@ -513,7 +513,7 @@ def test_confined_atomic_replace_cleans_a_source_replaced_during_rename(outside = tmp_path / "outside.txt"outside.write_text("outside survives", encoding="utf-8")- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_replace = confined_filesystem.os.replace@@ -552,7 +552,7 @@ def test_confined_atomic_replace_removes_a_source_made_public_during_rename(outside = tmp_path / "outside.txt"outside.write_text("outside survives", encoding="utf-8")- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_replace = confined_filesystem.os.replace@@ -581,7 +581,7 @@ def test_confined_atomic_replace_removes_a_source_hardlinked_during_rename(target = home / "target"outside_link = tmp_path / "outside-link.txt"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_replace = confined_filesystem.os.replace@@ -665,7 +665,7 @@ def test_remove_confined_path_never_chmods_a_swapped_entry_without_an_anchor(locked.chmod(0o000)held = target / "held-locked"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_open = confined_filesystem.os.openreal_chmod = confined_filesystem.os.chmod@@ -713,7 +713,7 @@ def test_remove_confined_path_does_not_require_procfs_for_openable_directories(nested.mkdir(mode=0o700)nested.chmod(mode)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemfake_o_path = 1 << 30real_open = confined_filesystem.os.open@@ -751,7 +751,7 @@ def test_remove_confined_path_rejects_a_mount_boundary_before_scanning(victim = mounted / "victim.txt"victim.write_text("must survive", encoding="utf-8")- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_open = confined_filesystem.os.openreal_scandir = confined_filesystem.os.scandir@@ -803,7 +803,7 @@ def test_remove_confined_path_rejects_directory_swap_during_permission_hardeninglocked.chmod(0o000)held = target / "held-locked"- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmodswapped = False@@ -854,7 +854,7 @@ def test_remove_confined_path_does_not_follow_symlink_swapped_in_during_hardeninvictim = outside / "victim.txt"victim.write_text("outside survives", encoding="utf-8")- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmodswapped = False@@ -896,7 +896,7 @@ def test_remove_confined_path_rechecks_device_after_permission_hardening(target.mkdir(mode=0o700)target.chmod(0o000)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmodreal_stat = confined_filesystem.os.stat@@ -941,7 +941,7 @@ def test_remove_confined_path_fails_closed_without_anchored_hardening(target.mkdir(mode=0o700)target.chmod(0o000)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmod@@ -973,7 +973,7 @@ def test_remove_anchored_entry_rejects_foreign_owned_directory(descriptor = os.open(home, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))real_uid = os.getuid()- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemmonkeypatch.setattr(confined_filesystem.os, "getuid", lambda: real_uid + 1)try:@@ -997,7 +997,7 @@ def test_remove_anchored_entry_rejects_cross_device_directory(target.chmod(0o777)descriptor = os.open(home, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_stat = confined_filesystem.os.stat@@ -1070,7 +1070,7 @@ def test_private_sqlite_transaction_commits_before_hardening(def connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=TrackingConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmod@@ -1125,7 +1125,7 @@ def test_private_sqlite_transaction_body_failure_remains_primary_during_cleanup(def connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=FailingCleanupConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmod@@ -1186,7 +1186,7 @@ def test_private_sqlite_transaction_commit_failure_remains_primary_during_cleanudef connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=FailingCommitConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmod@@ -1245,7 +1245,7 @@ def test_private_sqlite_transaction_rolls_back_cancellation(def connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=TrackingConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmod@@ -1301,7 +1301,7 @@ def test_private_sqlite_transaction_translates_hardening_failure_after_commit(def connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=TrackingConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemreal_chmod = confined_filesystem.os.chmodharden_error = ConfinedFilesystemError("unsafe SQLite sidecar")@@ -1354,7 +1354,7 @@ def test_private_sqlite_transaction_closes_setup_failure_without_translation(def connect(*args, **kwargs):return real_connect(*args, **kwargs, factory=FailingSetupConnection)- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemmonkeypatch.setattr(confined_filesystem.sqlite3, "connect", connect)@@ -1410,7 +1410,7 @@ def test_private_sqlite_database_rejects_unowned_database(database.prepare()real_uid = os.getuid()- from core.memory import confined_filesystem+ from avibe_memory import confined_filesystemmonkeypatch.setattr(confined_filesystem.os, "getuid", lambda: real_uid + 1)with pytest.raises(ConfinedFilesystemError):diff --git a/tests/test_memory_disabled_isolation.py b/tests/test_memory_disabled_isolation.pynew file mode 100644index 000000000..fbe095b30--- /dev/null+++ b/tests/test_memory_disabled_isolation.py@@ -0,0 +1,1438 @@+from __future__ import annotations++import asyncio+import os+import subprocess+import sys+import time+import tomllib+import types+from collections.abc import Awaitable, Callable+from dataclasses import replace+from pathlib import Path++import pytest++from config import paths+from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core import memory_legacy_cleanup+from core.controller import Controller+from avibe_memory import CaptureRequest, CaptureSkipped+from core.memory_adapter import DisabledMemoryAdapter+from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryStoreUnavailableError,+)+++ROOT = Path(__file__).resolve().parents[1]+++class _NoRetainedRootOwnership:+ def release_retained_root_ownership(self) -> None:+ return None+++def _disabled_app_config():+ return to_app_config(+ V2Config.from_payload(+ {+ "platform": "avibe",+ "platforms": {"enabled": [], "primary": "avibe"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "memory": {"enabled": False},+ "setup_completed": True,+ }+ )+ )+++def _controller_with_memory(memory=None) -> Controller:+ controller = Controller.__new__(Controller)+ controller.config = types.SimpleNamespace(+ memory=memory or _disabled_app_config().memory+ )+ controller.memory_adapter = DisabledMemoryAdapter()+ controller.memory_runtime = None+ controller.memory_module = None+ controller._memory_reconcile_task = None+ controller._memory_disabled_cleanup_task = None+ controller._memory_disabled_cleanup_unproved = False+ controller._memory_implementation_error = None+ return controller+++def _capture_request() -> CaptureRequest:+ return CaptureRequest(+ source_message_id="message-1",+ session_id="session-1",+ principal_id="u-11111111111111111111111111111111",+ project_id="default",+ provenance="agent",+ text="remember this",+ occurred_at_ms=1,+ )+++def _memory_state_entries(home: Path) -> list[Path]:+ if not home.exists():+ return []+ return [+ path.relative_to(home)+ for path in home.rglob("*")+ if any(+ "memory" in part.casefold() or "everos" in part.casefold()+ for part in path.relative_to(home).parts+ )+ ]+++def test_memory_cli_session_keeps_authenticated_boundary_when_implementation_is_unavailable() -> None:+ controller = Controller.__new__(Controller)+ controller.config = types.SimpleNamespace(+ memory=types.SimpleNamespace(enabled=True),+ )+ controller._memory_implementation_error = MemoryImplementationUnavailableError("injected")+ controller._memory_scopes_by_session = {}+ controller._memory_cli_facts_by_session = {}+ controller._memory_implementation_cli_sessions = set()+ controller._memory_admission = lambda: pytest.fail(+ "implementation failure must be projected before admission imports"+ )+ controller._memory_turn_facts = lambda _context: pytest.fail(+ "implementation failure must be projected before facts imports"+ )+ context = types.SimpleNamespace(+ platform_specific={+ "agent_session_target": {"id": "session-implementation"},+ },+ platform="avibe",+ )++ assert Controller.configure_memory_cli_session(+ controller,+ context,+ admitted=True,+ )+ assert Controller.memory_scope_for_cli_session(controller, "session-implementation") == (+ "__memory_implementation_error__",+ "default",+ )+++async def _start_disabled_cleanup(+ monkeypatch: pytest.MonkeyPatch,+ reconcile_orphans: Callable[[], Awaitable[None]],+) -> tuple[Controller, asyncio.Task[None], Path]:+ memory_dir = paths.get_vibe_remote_dir() / "memory"+ record_path = memory_dir / ".rt" / "everos.sidecar.json"+ record_path.parent.mkdir(parents=True)+ record_path.write_text("{}", encoding="utf-8")++ class _Reconciler:+ def __init__(self, **_kwargs) -> None:+ pass++ async def reconcile_orphans(self) -> None:+ await reconcile_orphans()++ monkeypatch.setattr(+ memory_legacy_cleanup,+ "ReleasedEverOSOrphanReconciler",+ _Reconciler,+ )++ controller = _controller_with_memory()+ await controller._schedule_disabled_memory_cleanup()+ cleanup_task = controller._memory_disabled_cleanup_task+ assert cleanup_task is not None+ return controller, cleanup_task, record_path+++def test_memory_indep_013_disabled_fresh_startup_has_no_runtime_side_effects(+ tmp_path: Path,+) -> None:+ script = r'''+import asyncio+import sys+from pathlib import Path++from config import paths+from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core.controller import Controller+from core.memory_adapter import DisabledMemoryAdapter, TurnAccepted+from modules.im import MessageContext++config = to_app_config(V2Config.from_payload({+ "platform": "avibe",+ "platforms": {"enabled": [], "primary": "avibe"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "memory": {"enabled": False},+ "setup_completed": True,+}))+controller = Controller(config)+home = paths.get_vibe_remote_dir()++assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+assert controller.memory_runtime is None+assert controller.memory_module is None+assert "avibe_memory.runtime" not in sys.modules+assert "avibe_memory.process" not in sys.modules+assert not [+ path for path in home.rglob("*")+ if any("memory" in part.casefold() or "everos" in part.casefold()+ for part in path.relative_to(home).parts)+]+asyncio.run(controller._schedule_disabled_memory_cleanup())+assert controller._memory_disabled_cleanup_task is None+assert "avibe_memory.process" not in sys.modules+++async def offer_capture() -> None:+ offered = []++ class RecordingDisabledAdapter(DisabledMemoryAdapter):+ def offer(self, event, /) -> None:+ offered.append(event)++ controller.memory_adapter = RecordingDisabledAdapter()+ context = MessageContext(+ user_id="user-1",+ channel_id="session-1",+ platform="avibe",+ message_id="message-1",+ is_original_human_text=True,+ )+ before = set(asyncio.all_tasks())+ event = TurnAccepted(+ platform="avibe",+ user_id="user-1",+ message_id="message-1",+ session_id="session-1",+ text="remember nothing",+ files=(),+ is_dm=False,+ is_ordinary_text=True,+ is_ordinary_attachment=False,+ lifecycle_snapshot=None,+ )+ controller.memory_adapter.offer(event)+ created = set(asyncio.all_tasks()).difference(before)+ assert offered == [event]+ assert not any(task.get_name().startswith("memory-") for task in created)+++asyncio.run(offer_capture())+'''+ home = tmp_path / "home"+ environment = os.environ.copy()+ environment["AVIBE_HOME"] = str(home)+ environment["HOME"] = str(tmp_path)+ environment["PYTHONPATH"] = str(ROOT)++ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+ assert _memory_state_entries(home) == []+++def test_memory_indep_014_disabled_controller_starts_with_runtime_imports_blocked(+ tmp_path: Path,+) -> None:+ script = r'''+import asyncio+import importlib.abc+import sys++BLOCKED = {+ "avibe_memory.blocking",+ "avibe_memory.operation_lock",+ "avibe_memory.process",+ "avibe_memory.runtime",+ "avibe_memory.ui_access",+}+++class BlockMemoryImplementation(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path, target=None):+ del path, target+ if fullname in BLOCKED:+ raise ImportError(f"blocked optional Memory implementation: {fullname}")+ return None+++sys.meta_path.insert(0, BlockMemoryImplementation())++from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core import internal_server+from core.controller import Controller+from core.memory_adapter import DisabledMemoryAdapter++config = to_app_config(V2Config.from_payload({+ "platform": "avibe",+ "platforms": {"enabled": [], "primary": "avibe"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "memory": {"enabled": False},+ "setup_completed": True,+}))+controller = Controller(config)+internal_server.create_app(controller, memory_ui_secret="test-secret")+status = asyncio.run(controller.memory_status_payload())+assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+assert controller.memory_runtime is None+assert status == {+ "status": "ok",+ "source": {"status": "unavailable", "observed_at": None, "reason": "memory_disabled"},+ "health": None,+ "state": "disabled",+ "reason": None,+ "attachment_capture": {"status": "not_configured"},+}+assert not BLOCKED.intersection(sys.modules)+'''+ environment = os.environ.copy()+ environment["AVIBE_HOME"] = str(tmp_path / "home")+ environment["HOME"] = str(tmp_path)+ environment["PYTHONPATH"] = str(ROOT)++ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+ assert _memory_state_entries(tmp_path / "home") == []+++def test_disabled_cleanup_consumes_released_record_without_optional_package(+ tmp_path: Path,+) -> None:+ script = r'''+import asyncio+import importlib.abc+import json+import sys+++class BlockMemoryImplementation(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path, target=None):+ del path, target+ if fullname == "avibe_memory" or fullname.startswith("avibe_memory."):+ raise ImportError(f"blocked optional Memory implementation: {fullname}")+ return None+++sys.meta_path.insert(0, BlockMemoryImplementation())++from config import paths+from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core.controller import Controller++config = to_app_config(V2Config.from_payload({+ "platform": "avibe",+ "platforms": {"enabled": [], "primary": "avibe"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "memory": {"enabled": False},+ "setup_completed": True,+}))+controller = Controller(config)+home = paths.get_vibe_remote_dir()+memory_dir = home / "memory"+record_path = memory_dir / ".rt" / "everos.sidecar.json"+record_path.parent.mkdir(mode=0o700, parents=True)+record_path.write_text(json.dumps({+ "pid": 99999999,+ "create_time": 1.0,+ "provider_root": str(memory_dir / "everos-root"),+ "socket_path": str(memory_dir / ".rt" / "everos.sock"),+ "role": "sidecar",+ "python": "/runtime/bin/python",+}), encoding="utf-8")+record_path.chmod(0o600)+++async def cleanup() -> None:+ await controller._schedule_disabled_memory_cleanup()+ task = controller._memory_disabled_cleanup_task+ assert task is not None+ await task+++asyncio.run(cleanup())+assert not record_path.exists()+assert not any(+ name == "avibe_memory" or name.startswith("avibe_memory.")+ for name in sys.modules+)+'''+ environment = os.environ.copy()+ environment["AVIBE_HOME"] = str(tmp_path / "home")+ environment["HOME"] = str(tmp_path)+ environment["PYTHONPATH"] = str(ROOT)++ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+++def test_enabled_controller_degrades_when_runtime_attribute_probe_fails(+ tmp_path: Path,+) -> None:+ script = r'''+import sys+import types++from config.v2_compat import to_app_config+from config.v2_config import V2Config+from core.controller import Controller+from core.memory_adapter import DisabledMemoryAdapter+from vibe.memory_contract import MemoryImplementationUnavailableError+++class BrokenRuntime(types.ModuleType):+ def __getattr__(self, name):+ if name == "create_memory_runtime":+ raise RuntimeError("broken optional runtime attribute")+ raise AttributeError(name)+++sys.modules["avibe_memory.runtime"] = BrokenRuntime("avibe_memory.runtime")+config = to_app_config(V2Config.from_payload({+ "platform": "avibe",+ "platforms": {"enabled": [], "primary": "avibe"},+ "mode": "self_host",+ "version": "v2",+ "runtime": {"default_cwd": "_tmp", "log_level": "INFO"},+ "agents": {+ "default_backend": "opencode",+ "opencode": {"enabled": True, "cli_path": "opencode"},+ },+ "memory": {+ "enabled": True,+ "processing": {+ "llm": {+ "base_url": "https://llm.example.test/v1",+ "model": "chat",+ "api_key": "llm-key",+ },+ "embedding": {+ "base_url": "https://embed.example.test/v1",+ "model": "embed",+ "api_key": "embed-key",+ },+ },+ },+ "setup_completed": True,+}))+controller = Controller(config)+assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+assert controller.memory_runtime is None+assert isinstance(controller._memory_implementation_error, MemoryImplementationUnavailableError)+'''+ environment = os.environ.copy()+ environment["AVIBE_HOME"] = str(tmp_path / "home")+ environment["HOME"] = str(tmp_path)+ environment["PYTHONPATH"] = str(ROOT)++ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+++def test_host_surfaces_import_with_avibe_memory_blocked(+ tmp_path: Path,+) -> None:+ script = r'''+import importlib.abc+import sys++class BlockMemoryImplementation(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path, target=None):+ del path, target+ if fullname == "avibe_memory" or fullname.startswith("avibe_memory."):+ raise ImportError(f"blocked optional Memory implementation: {fullname}")+ return None+++sys.meta_path.insert(0, BlockMemoryImplementation())++from config.v2_config import V2Config+from core import internal_server, system_prompt_injection+from vibe import cli, internal_client, ui_memory_routes++assert V2Config is not None+assert internal_server is not None+assert system_prompt_injection is not None+assert cli is not None+assert internal_client is not None+assert ui_memory_routes is not None+loaded_memory_children = {+ name+ for name in sys.modules+ if name == "avibe_memory" or name.startswith("avibe_memory.")+}+assert loaded_memory_children == set()+'''+ environment = os.environ.copy()+ environment["AVIBE_HOME"] = str(tmp_path / "home")+ environment["HOME"] = str(tmp_path)+ environment["PYTHONPATH"] = str(ROOT)++ completed = subprocess.run(+ [sys.executable, "-c", script],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+++def test_memory_indep_017_core_workflows_run_without_avibe_memory(+ tmp_path: Path,+) -> None:+ """Run representative core workflows with the implementation unavailable."""++ scenarios = (+ "tests/test_message_handler_typing.py::MessageHandlerTypingTests::test_im_human_input_enters_delivery_owner_before_backend",+ "tests/test_command_handler_user_names.py::CommandHandlerUserNameTests::test_new_command_sends_fresh_session_confirmation",+ "tests/test_session_archive.py::test_archive_reclaims_bound_resources",+ "tests/test_ui_server_fastapi.py::test_websocket_echo_smoke_when_enabled",+ "tests/test_internal_server.py::test_disabled_memory_status_route_uses_host_projection_without_runtime",+ "tests/test_vibe_cli.py::test_retention_help_reads_raw_config_without_loading_or_migrating",+ "tests/test_controller_dispatch_loop.py::test_cleanup_sync_stops_watch_service_on_stopped_loop",+ )+ environment = os.environ.copy()+ isolated_home = tmp_path / "core-only-home"+ environment.update(+ {+ "AVIBE_HOME": str(isolated_home / ".avibe"),+ "CLAUDE_CONFIG_DIR": str(isolated_home / ".claude"),+ "CODEX_HOME": str(isolated_home / ".codex"),+ "HOME": str(isolated_home),+ "PYTHONDONTWRITEBYTECODE": "1",+ "PYTHONPATH": str(ROOT),+ "XDG_CACHE_HOME": str(isolated_home / ".cache"),+ "XDG_CONFIG_HOME": str(isolated_home / ".config"),+ "XDG_DATA_HOME": str(isolated_home / ".local" / "share"),+ "XDG_STATE_HOME": str(isolated_home / ".local" / "state"),+ }+ )++ completed = subprocess.run(+ [+ sys.executable,+ "-m",+ "pytest",+ "-q",+ "-p",+ "tests.memory_import_blocker",+ *scenarios,+ ],+ cwd=ROOT,+ env=environment,+ capture_output=True,+ text=True,+ timeout=120,+ check=False,+ )++ assert completed.returncode == 0, completed.stdout + completed.stderr+ assert "7 passed" in completed.stdout+ assert (+ "MEMORY-INDEP-017 import tracking: attempted=[] loaded=[]"+ in completed.stdout+ )+++def test_wave_3a_package_metadata_separates_avibe_memory_distribution() -> None:+ """Wave 3a keeps the implementation out of the core distribution."""++ metadata = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))+ targets = metadata["tool"]["hatch"]["build"]["targets"]+ memory_metadata = tomllib.loads(+ (ROOT / "packaging/avibe-memory/pyproject.toml").read_text(encoding="utf-8")+ )++ assert "avibe_memory" not in targets["wheel"]["packages"]+ assert "avibe_memory/**" not in targets["sdist"]["include"]+ assert "vibe/memory_runtime_manifest.json" in targets["wheel"]["exclude"]+ assert memory_metadata["project"]["name"] == "avibe-memory"+++ "record_relative_path",+ [+ Path(".rt/everos.sidecar.json"),+ Path(".avibe-memory-locks/cascade-sync-owned.json"),+ ],+)+async def test_disabled_cleanup_reaps_only_preexisting_everos_ownership(+ monkeypatch: pytest.MonkeyPatch,+ record_relative_path: Path,+) -> None:+ memory_dir = paths.get_vibe_remote_dir() / "memory"+ record_path = memory_dir / record_relative_path+ record_path.parent.mkdir(parents=True)+ record_path.write_text("{}", encoding="utf-8")+ calls: list[tuple[Path, Path]] = []++ class _Reconciler:+ def __init__(self, *, provider_root, effective_home) -> None:+ self._paths = (provider_root, effective_home)++ async def reconcile_orphans(self) -> None:+ calls.append(self._paths)++ monkeypatch.setattr(+ memory_legacy_cleanup,+ "ReleasedEverOSOrphanReconciler",+ _Reconciler,+ )++ controller = _controller_with_memory()++ await controller._schedule_disabled_memory_cleanup()++ assert controller._memory_disabled_cleanup_task is not None+ await controller._memory_disabled_cleanup_task+ assert calls == [+ (+ memory_dir / "everos-root",+ paths.get_vibe_remote_dir(),+ )+ ]+++async def test_disabled_cleanup_pending_projects_degraded_status(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ cleanup_started = asyncio.Event()+ cleanup_release = asyncio.Event()++ async def reconcile_orphans() -> None:+ cleanup_started.set()+ await cleanup_release.wait()+ record_path.unlink()++ controller, cleanup_task, record_path = await _start_disabled_cleanup(+ monkeypatch,+ reconcile_orphans,+ )+ await cleanup_started.wait()++ try:+ status = await asyncio.wait_for(+ controller.memory_status_payload(),+ timeout=0.1,+ )+ assert status["state"] == "degraded"+ assert status["reason"] == "memory_runtime_busy"+ assert status["source"]["reason"] == "memory_runtime_busy"+ finally:+ cleanup_release.set()+ await cleanup_task+++async def test_enabled_operation_bounds_disabled_cleanup_wait_and_remains_retryable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ cleanup_started = asyncio.Event()+ cleanup_release = asyncio.Event()++ async def reconcile_orphans() -> None:+ cleanup_started.set()+ await cleanup_release.wait()+ record_path.unlink()++ controller, cleanup_task, record_path = await _start_disabled_cleanup(+ monkeypatch,+ reconcile_orphans,+ )+ await cleanup_started.wait()+ controller.config.memory = replace(controller.config.memory, enabled=True)+ controller._memory_disabled_cleanup_wait_seconds = 0.01++ class _Runtime:+ async def wake(self) -> dict[str, object]:+ return {"ok": True, "state": "running"}++ controller.memory_runtime = _Runtime()++ try:+ with pytest.raises(+ MemoryStoreUnavailableError,+ match="Disabled Memory cleanup is still in progress",+ ):+ await asyncio.wait_for(controller.wake_memory(), timeout=0.1)++ class _Python310AsyncioTimeoutError(Exception):+ pass++ async def raise_python310_timeout(+ _future: object,+ *,+ timeout: float,+ ) -> None:+ assert timeout == 0.01+ raise _Python310AsyncioTimeoutError++ with monkeypatch.context() as python310:+ python310.setattr(+ asyncio,+ "TimeoutError",+ _Python310AsyncioTimeoutError,+ )+ python310.setattr(asyncio, "wait_for", raise_python310_timeout)+ with pytest.raises(+ MemoryStoreUnavailableError,+ match="Disabled Memory cleanup is still in progress",+ ):+ await controller.wake_memory()+ assert cleanup_task.done() is False+ assert cleanup_task.cancelled() is False++ cleanup_release.set()+ await cleanup_task+ assert await controller.wake_memory() == {"ok": True, "state": "running"}+ finally:+ cleanup_release.set()+ await cleanup_task+++ ("outcome", "expected_state"),+ [("failure", "degraded"), ("retained", "degraded"), ("released", "disabled")],+)+async def test_disabled_cleanup_terminal_status_tracks_ownership(+ monkeypatch: pytest.MonkeyPatch,+ outcome: str,+ expected_state: str,+) -> None:+ async def reconcile_orphans() -> None:+ if outcome == "failure":+ raise RuntimeError("cleanup failed")+ if outcome == "released":+ record_path.unlink()++ controller, cleanup_task, record_path = await _start_disabled_cleanup(+ monkeypatch,+ reconcile_orphans,+ )+ await cleanup_task++ status = await controller.memory_status_payload()++ assert status["state"] == expected_state+ assert status["reason"] == (+ "memory_runtime_busy" if expected_state == "degraded" else None+ )++[email protected]("active_operation", ("preflight", "install"))+async def test_memory_reconcile_lazily_enters_and_leaves_enabled_runtime(+ active_operation: str,+) -> None:+ controller = _controller_with_memory()+ enabled = replace(controller.config.memory, enabled=True)+ offers: list[object] = []+ operation_started = asyncio.Event()+ operation_release = asyncio.Event()++ class _CaptureAdapter:+ def offer(self, event: object) -> None:+ offers.append(event)++ class _Runtime(_NoRetainedRootOwnership):+ def __init__(self) -> None:+ self.module = object()+ self.available = True+ self.closed = False+ self.capture_adapter = _CaptureAdapter()+ self.begin_close_calls = 0++ def start_capture_adapter(self, **_options: object) -> bool:+ return True++ async def reconcile(self, _config) -> dict[str, object]:+ return {"ok": True, "state": "running"}++ async def preflight(self, _config) -> dict[str, object]:+ operation_started.set()+ await operation_release.wait()+ return {"ok": True}++ async def install_artifact(self, **_options: object) -> dict[str, object]:+ return await self.preflight(enabled)++ async def close(self) -> None:+ self.closed = True++ def begin_close(self) -> None:+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+ self.begin_close_calls += 1++ runtime = _Runtime()+ controller._create_memory_runtime = lambda _config: runtime+ assert await controller.reconcile_memory(enabled) == {+ "ok": True,+ "state": "running",+ }+ assert controller.memory_runtime is runtime+ assert controller.memory_module is runtime.module+ assert controller.memory_adapter is runtime.capture_adapter+ assert controller.config.memory.enabled is True++ event = object()+ controller.memory_adapter.offer(event)+ assert offers == [event]++ operation = asyncio.create_task(+ controller.preflight_memory(enabled)+ if active_operation == "preflight"+ else controller.install_memory_runtime()+ )+ await operation_started.wait()++ disabled = replace(enabled, enabled=False)+ assert await controller.reconcile_memory(disabled) == {+ "ok": False,+ "state": "disabled",+ "error": "memory_operation_in_progress",+ }+ assert controller.config.memory is enabled+ assert controller.memory_runtime is runtime+ assert controller.memory_adapter is runtime.capture_adapter+ assert runtime.begin_close_calls == 0++ operation_release.set()+ assert await operation == {"ok": True}+ assert await controller.reconcile_memory(disabled) == {+ "ok": True,+ "state": "disabled",+ }+ assert runtime.closed is True+ assert controller.memory_runtime is None+ assert controller.memory_module is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)+ assert controller.config.memory.enabled is False++[email protected]("overlap", ("preflight", "install"))+async def test_overlapping_unpublished_operations_return_busy(+ overlap: str,+) -> None:+ controller = _controller_with_memory()+ candidate = replace(controller.config.memory, enabled=True)+ preflight_started = asyncio.Event()+ preflight_release = asyncio.Event()+ construction_attempts: list[object] = []++ class _Runtime:+ module = object()++ def __init__(self) -> None:+ self.closed = False++ async def preflight(self, config) -> dict[str, object]:+ assert config is candidate+ preflight_started.set()+ await preflight_release.wait()+ return {"ok": True}++ def begin_close(self) -> None:+ return None++ async def close(self) -> None:+ self.closed = True++ runtime = _Runtime()++ def create_runtime(config, **_kwargs):+ construction_attempts.append(config)+ return runtime++ controller._create_memory_runtime = create_runtime+ first = asyncio.create_task(controller.preflight_memory(candidate))+ await preflight_started.wait()++ if overlap == "preflight":+ busy = await controller.preflight_memory(candidate)+ assert busy == {"ok": False, "error": "memory_operation_in_progress"}+ else:+ busy = await controller.install_memory_runtime()+ assert busy == {+ "ok": False,+ "reason": "memory_operation_in_progress",+ "download_error": None,+ }++ assert construction_attempts == [candidate]+ assert controller.memory_runtime is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)++ preflight_release.set()+ assert await first == {"ok": True}+ assert runtime.closed is True++[email protected]("recovery", ("preflight", "install"))+async def test_cached_implementation_failure_only_retries_for_explicit_recovery(+ recovery: str,+) -> None:+ controller = _controller_with_memory(+ replace(_disabled_app_config().memory, enabled=True)+ )+ failure = MemoryImplementationUnavailableError("startup failed")+ controller._memory_implementation_error = failure+ controller._create_memory_runtime = lambda *_args, **_kwargs: pytest.fail(+ "ordinary reads must not retry a cached implementation failure"+ )++ with pytest.raises(MemoryImplementationUnavailableError) as raised:+ await controller.memory_projects_payload(+ verified_user_key=None,+ cli_scope=("u-11111111111111111111111111111111", "default"),+ )++ assert raised.value is failure+ events: list[str] = []++ class _Runtime(_NoRetainedRootOwnership):+ def __init__(self, label: str, *, fail_close: bool = False) -> None:+ self.label = label+ self.module = object()+ self.closing = False+ self.fail_close = fail_close++ async def install_artifact(self, **_options: object) -> dict[str, object]:+ assert controller.memory_runtime is None+ events.append(f"{self.label}:install")+ return {"ok": True}++ async def preflight(self, _config: object) -> dict[str, object]:+ events.append(f"{self.label}:preflight")+ return {"ok": True}++ def begin_close(self) -> None:+ self.closing = True+ events.append(f"{self.label}:begin-close")++ async def close(self) -> None:+ events.append(f"{self.label}:close")+ if self.fail_close:+ self.fail_close = False+ raise RuntimeError("close failed")++ retained = _Runtime("retained", fail_close=True)+ fresh = _Runtime("fresh")+ runtimes = iter((retained, fresh))+ controller._create_memory_runtime = lambda *_args, **_kwargs: next(runtimes)++ with pytest.raises(RuntimeError, match="close failed"):+ await controller.install_memory_runtime()+ assert controller.memory_runtime is retained+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)++ if recovery == "preflight":+ result = await controller.preflight_memory(controller.config.memory)+ else:+ result = await controller.install_memory_runtime()+ assert result == {"ok": True}+ assert events == [+ "retained:install",+ "retained:begin-close",+ "retained:close",+ "retained:close",+ f"fresh:{recovery}",+ "fresh:begin-close",+ "fresh:close",+ ]+ assert controller.memory_runtime is None+ assert controller.memory_module is None+ assert controller._memory_implementation_error is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)++ retry_failure = MemoryImplementationIncompatibleError("still incompatible")++ def fail_retry(_config, **_kwargs):+ raise retry_failure++ controller._create_memory_runtime = fail_retry+ with pytest.raises(MemoryImplementationIncompatibleError) as raised:+ await controller.preflight_memory(controller.config.memory)+ assert raised.value is retry_failure+ assert controller._memory_implementation_error is retry_failure++[email protected]("ordering", ("reaper-first", "enable-first"))+async def test_disabled_reaper_enable_and_shutdown_share_root_mutation_gate(+ ordering: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ controller = _controller_with_memory()+ controller._memory_disabled_cleanup_unproved = True+ enabled = replace(controller.config.memory, enabled=True)+ lease_held = False+ reaper_started = asyncio.Event()+ reaper_release = asyncio.Event()+ attach_started = asyncio.Event()+ attach_release = asyncio.Event()+ reaper_calls = 0+ construction_calls = 0++ class _Lease:+ def release(self) -> None:+ nonlocal lease_held+ lease_held = False++ async def try_lease(_effective_home=None):+ nonlocal lease_held+ if lease_held:+ return None+ lease_held = True+ return _Lease()++ class _Reconciler:+ def __init__(self, **_kwargs) -> None:+ pass++ async def reconcile_orphans(self) -> None:+ nonlocal reaper_calls+ reaper_calls += 1+ reaper_started.set()+ await reaper_release.wait()++ monkeypatch.setattr(+ memory_legacy_cleanup,+ "ReleasedEverOSOrphanReconciler",+ _Reconciler,+ )+ controller._try_memory_operation_lease = try_lease+ controller._disabled_memory_ownership_exists = lambda _path: True++ class _Runtime:+ module = object()+ capture_adapter = object()+ closing = False++ async def reconcile(self, _config) -> dict[str, object]:+ return {"ok": True, "state": "running"}++ def start_capture_adapter(self, **_kwargs) -> bool:+ return True++ def begin_close(self) -> None:+ self.closing = True++ async def close(self, **_options: object) -> None:+ return None++ runtime = _Runtime()++ def create_runtime(_config, **_kwargs):+ nonlocal construction_calls+ construction_calls += 1+ return runtime++ controller._create_memory_runtime = create_runtime+ memory_dir = Path("unused-memory-root")++ if ordering == "reaper-first":+ cleanup = asyncio.create_task(+ controller._cleanup_disabled_memory_process(memory_dir)+ )+ await reaper_started.wait()+ assert await controller.reconcile_memory(enabled) == {+ "ok": False,+ "error": "memory_operation_in_progress",+ }+ assert construction_calls == 0+ reaper_release.set()+ await cleanup+ else:+ attach = controller._attach_memory_runtime++ async def blocked_attach(*args, **kwargs) -> None:+ attach_started.set()+ await attach_release.wait()+ await attach(*args, **kwargs)++ controller._attach_memory_runtime = blocked_attach+ reconcile = asyncio.create_task(controller.reconcile_memory(enabled))+ await attach_started.wait()+ await controller._cleanup_disabled_memory_process(memory_dir)+ assert reaper_calls == 0+ shutdown = asyncio.create_task(+ controller._close_memory_runtime_for_shutdown(timeout_seconds=0.5)+ )+ await asyncio.sleep(0.02)+ assert shutdown.done() is False+ assert controller.memory_runtime is None+ attach_release.set()+ assert await reconcile == {"ok": True, "state": "running"}+ await shutdown+ assert controller.memory_runtime is None++ assert controller._memory_replacement_lock().locked() is False+++async def test_disable_publishes_disabled_before_failed_close() -> None:+ enabled = replace(_disabled_app_config().memory, enabled=True)+ disabled = replace(enabled, enabled=False)+ controller = _controller_with_memory(enabled)+ original_adapter = object()+ controller.memory_adapter = original_adapter++ class _Runtime:+ def __init__(self) -> None:+ self.module = object()+ self.fail_close = True+ self.close_calls = 0+ self.root_released = False++ def begin_close(self) -> None:+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)++ async def close(self, **_options: object) -> None:+ self.close_calls += 1+ if self.fail_close:+ raise RuntimeError("close failed")++ def release_retained_root_ownership(self) -> None:+ self.root_released = True++ runtime = _Runtime()+ controller.memory_runtime = runtime+ controller.memory_module = runtime.module++ assert await controller.reconcile_memory(disabled) == {+ "ok": False,+ "state": "disabled",+ "error": "memory_operation_in_progress",+ }++ assert controller.config.memory == disabled+ assert controller.memory_runtime is runtime+ assert controller.memory_module is None+ assert isinstance(controller.memory_adapter, DisabledMemoryAdapter)++ runtime.fail_close = False+ assert await controller.reconcile_memory(disabled) == {+ "ok": True,+ "state": "disabled",+ }+ assert runtime.close_calls == 2+ assert runtime.root_released is True+ assert controller.memory_runtime is None+++ ("cleanup_unproved", "expected_state", "expected_reason", "source_reason"),+ [+ (False, "needs_repair", "memory_legacy_recovery_required", "memory_disabled"),+ (True, "degraded", "memory_runtime_busy", "memory_runtime_busy"),+ ],+)+async def test_disabled_status_projects_repair_and_cleanup_fences(+ cleanup_unproved: bool,+ expected_state: str,+ expected_reason: str,+ source_reason: str,+) -> None:+ controller = _controller_with_memory(+ replace(+ _disabled_app_config().memory,+ legacy_needs_repair=True,+ )+ )+ controller._memory_disabled_cleanup_unproved = cleanup_unproved++ status = await controller.memory_status_payload()++ assert status["state"] == expected_state+ assert status["reason"] == expected_reason+ assert status["source"]["reason"] == source_reason+++async def test_disabled_operations_do_not_construct_runtime() -> None:+ controller = _controller_with_memory()+ factory_calls: list[object] = []++ def create_runtime(config, **_kwargs):+ factory_calls.append(config)+ raise AssertionError("disabled operations must not construct Memory")++ controller._create_memory_runtime = create_runtime++ processing, maintenance = await asyncio.gather(+ controller.memory_processing_record_payload(verified_user_key="user-1"),+ controller.memory_maintenance_payload(verified_user_key="user-1"),+ )++ unavailable = {+ "status": "unavailable",+ "observed_at": None,+ "reason": "memory_disabled",+ }+ assert processing == {+ "status": "ok",+ "runtime": {"source": unavailable, "health": None},+ "sources": {+ "memcells": unavailable,+ "runs": unavailable,+ "semantic": unavailable,+ },+ "anomalies": {"source": unavailable, "items": []},+ "maintenance": {+ "source": unavailable,+ "data_exists": True,+ "can_delete_data": True,+ },+ }+ assert maintenance == {+ "status": "ok",+ "data_exists": True,+ "can_delete_data": True,+ }+ assert await controller.wake_memory() == {+ "ok": False,+ "state": "disabled",+ "error": "memory_disabled",+ }+ assert await controller.capture_memory(+ _capture_request()+ ) == CaptureSkipped(reason="memory_disabled")+ with pytest.raises(MemoryStoreUnavailableError, match="Memory is disabled"):+ await controller.memory_projects_payload(+ verified_user_key=None,+ cli_scope=("u-11111111111111111111111111111111", "default"),+ )+ assert factory_calls == []+++async def test_implementation_failure_rechecked_after_blocked_capture_lock() -> None:+ controller = _controller_with_memory(+ replace(_disabled_app_config().memory, enabled=True)+ )+ request = _capture_request()++ gate = controller._memory_replacement_lock()+ await gate.acquire()+ capture = asyncio.create_task(controller.capture_memory(request))+ await asyncio.sleep(0)+ assert not capture.done()+ controller._memory_implementation_error = MemoryImplementationUnavailableError("injected")+ gate.release()++ with pytest.raises(MemoryImplementationUnavailableError):+ await capture+++async def test_enabled_status_does_not_wait_for_startup_wake() -> None:+ controller = _controller_with_memory(+ replace(_disabled_app_config().memory, enabled=True)+ )+ controller.memory_adapter = None+ wake_release = asyncio.Event()++ async def startup_wake() -> None:+ await wake_release.wait()++ controller._memory_reconcile_task = asyncio.create_task(startup_wake())++ class _Runtime:+ module = object()+ closed = False++ async def status_payload(self) -> dict[str, object]:+ return {"status": "ok", "state": "starting"}++ runtime = _Runtime()+ controller.memory_runtime = runtime+ controller.memory_module = runtime.module++ try:+ assert await asyncio.wait_for(+ controller.memory_status_payload(),+ timeout=0.1,+ ) == {"status": "ok", "state": "starting"}+ finally:+ wake_release.set()+ await controller._memory_reconcile_task+++async def test_reconcile_provider_work_does_not_hold_pointer_lock() -> None:+ enabled = replace(_disabled_app_config().memory, enabled=True)+ candidate = replace(enabled)+ controller = _controller_with_memory(enabled)+ controller.memory_adapter = None+ reconcile_started = asyncio.Event()+ reconcile_release = asyncio.Event()++ class _Runtime:+ module = object()+ capture_adapter = object()+ capture_starts = 0++ def start_capture_adapter(self, **_options: object) -> bool:+ self.capture_starts += 1+ return True++ async def reconcile(self, config) -> dict[str, object]:+ assert config is candidate+ assert controller._memory_replacement_lock().locked() is False+ reconcile_started.set()+ await reconcile_release.wait()+ return {"ok": True, "state": "running"}++ async def preflight(self, _config) -> dict[str, object]:+ pytest.fail("preflight overlapped enabled reconciliation")++ runtime = _Runtime()+ controller.memory_runtime = runtime+ controller.memory_module = runtime.module+ reconcile = asyncio.create_task(controller.reconcile_memory(candidate))+ await reconcile_started.wait()++ async with asyncio.timeout(0.1):+ async with controller._memory_replacement_lock():+ assert controller.memory_runtime is runtime+ assert await controller.preflight_memory(candidate) == {+ "ok": False,+ "error": "memory_operation_in_progress",+ }++ reconcile_release.set()+ assert await reconcile == {"ok": True, "state": "running"}+ assert controller.config.memory is candidate+ assert runtime.capture_starts == 1+++async def test_memory_indep_015_shutdown_uses_one_budget_after_stage_timeout() -> None:+ controller = Controller.__new__(Controller)+ controller._memory_reconcile_task = None+ controller._memory_shutdown_budget_seconds = 0.04+ controller._shutdown_tainted = False+ controller._memory_destructive_quiescing = False+ controller.message_handler = types.SimpleNamespace(+ quiesce_memory_capture_tasks=lambda: None,+ )+ release = asyncio.Event()+ close_deadlines: list[float] = []++ async def transaction() -> dict[str, object]:+ await release.wait()+ assert controller.memory_runtime is runtime+ assert runtime.closed is False+ return {"ok": True}++ destructive = asyncio.create_task(transaction())+ controller._memory_destructive_tasks = {destructive}++ class _MemoryRuntime:+ def __init__(self) -> None:+ self.closed = False++ def begin_close(self) -> None:+ return None++ async def close(self, **options: object) -> None:+ self.closed = True+ close_deadlines.append(float(options["timeout_seconds"]))++ runtime = _MemoryRuntime()+ controller.memory_runtime = runtime++ started_at = time.monotonic()+ await controller._shutdown_memory_stack()++ assert time.monotonic() - started_at < 0.2+ assert destructive.done() is False+ assert runtime.closed is False+ assert controller.memory_runtime is runtime+ assert controller._shutdown_tainted is True+ assert close_deadlines == []++ release.set()+ await destructive+ await controller._shutdown_memory_stack()+ assert runtime.closed is True+ assert controller.memory_runtime is None+ assert 0.0 <= close_deadlines[0] <= controller._memory_shutdown_budget_secondsdiff --git a/tests/test_memory_distribution.py b/tests/test_memory_distribution.pynew file mode 100644index 000000000..f4a07e017--- /dev/null+++ b/tests/test_memory_distribution.py@@ -0,0 +1,661 @@+from __future__ import annotations++import base64+import csv+from email.parser import Parser+import hashlib+import io+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tarfile+from typing import Any+import zipfile++from packaging.requirements import Requirement+from packaging.specifiers import SpecifierSet+from packaging.utils import canonicalize_name, parse_wheel_filename+from packaging.version import Version+import pytest+import yaml++from hatch_exact_peer import pin_peer_dependency++try:+ import tomllib+except ModuleNotFoundError: # pragma: no cover - Python 3.10 compatibility+ import tomli as tomllib+++ROOT = Path(__file__).resolve().parents[1]+MEMORY_PROJECT = ROOT / "packaging" / "avibe-memory"+COMPATIBILITY = SpecifierSet(">=3.0.14.dev0,<3.1")+PACKAGE_CONTRACT_VERSION = Version("3.0.99rc1")+WORKFLOW_DIR = ROOT / ".github" / "workflows"+++def _project(path: Path) -> dict[str, Any]:+ return tomllib.loads(path.read_text(encoding="utf-8"))["project"]+++def _build_system(path: Path) -> dict[str, Any]:+ return tomllib.loads(path.read_text(encoding="utf-8"))["build-system"]+++def _workflow(name: str) -> dict[str, Any]:+ return yaml.safe_load((WORKFLOW_DIR / name).read_text(encoding="utf-8"))+++def _step(job: dict[str, Any], name: str) -> dict[str, Any]:+ matches = [step for step in job["steps"] if step.get("name") == name]+ assert len(matches) == 1+ return matches[0]+++def _needs(job: dict[str, Any]) -> set[str]:+ needs = job.get("needs", [])+ return {needs} if isinstance(needs, str) else set(needs)+++def _requirement(requirements: list[str], name: str) -> Requirement:+ canonical_name = canonicalize_name(name)+ matches = [+ Requirement(value)+ for value in requirements+ if canonicalize_name(Requirement(value).name) == canonical_name+ ]+ assert len(matches) == 1+ return matches[0]+++def _wheel_path(variable: str) -> Path:+ value = os.environ.get(variable)+ if value is None:+ pytest.skip(f"{variable} is set by the package-matrix build job")+ path = Path(value).resolve()+ assert path.is_file()+ return path+++def _wheel_metadata(wheel: Path) -> tuple[set[str], Any]:+ with zipfile.ZipFile(wheel) as archive:+ names = set(archive.namelist())+ metadata_paths = [name for name in names if name.endswith(".dist-info/METADATA")]+ assert len(metadata_paths) == 1+ metadata_content = archive.read(metadata_paths[0])+ metadata = Parser().parsestr(metadata_content.decode("utf-8"))+ record_paths = [name for name in names if name.endswith(".dist-info/RECORD")]+ assert len(record_paths) == 1+ record = list(csv.reader(io.StringIO(archive.read(record_paths[0]).decode("utf-8"))))+ metadata_record = [row for row in record if row and row[0] == metadata_paths[0]]+ assert len(metadata_record) == 1+ digest = base64.urlsafe_b64encode(hashlib.sha256(metadata_content).digest()).rstrip(b"=").decode("ascii")+ assert metadata_record[0][1:] == [f"sha256={digest}", str(len(metadata_content))]+ return names, metadata+++def _sdist_metadata(wheel: Path, distribution: str) -> Any:+ sdist = _sdist_path(wheel, distribution)+ with tarfile.open(sdist, "r:gz") as archive:+ metadata = _sdist_member(archive, "PKG-INFO")+ return Parser().parsestr(metadata.decode("utf-8"))+++def _sdist_pyproject(wheel: Path, distribution: str) -> dict[str, Any]:+ sdist = _sdist_path(wheel, distribution)+ with tarfile.open(sdist, "r:gz") as archive:+ return tomllib.loads(_sdist_member(archive, "pyproject.toml").decode("utf-8"))+++def _sdist_path(wheel: Path, distribution: str) -> Path:+ matches = list(wheel.parent.glob(f"{distribution}-*.tar.gz"))+ assert len(matches) == 1+ return matches[0]+++def _sdist_member(archive: tarfile.TarFile, name: str) -> bytes:+ matches = [+ member+ for member in archive.getmembers()+ if member.isfile() and Path(member.name).name == name+ ]+ assert len(matches) == 1+ member_file = archive.extractfile(matches[0])+ assert member_file is not None+ return member_file.read()+++def _write_minimal_wheel(directory: Path, distribution: str, version: str) -> Path:+ normalized = distribution.replace("-", "_")+ dist_info = f"{normalized}-{version}.dist-info"+ wheel = directory / f"{normalized}-{version}-py3-none-any.whl"+ entries = {+ f"{dist_info}/METADATA": f"Metadata-Version: 2.4\nName: {distribution}\nVersion: {version}\n\n",+ f"{dist_info}/WHEEL": (+ "Wheel-Version: 1.0\n"+ "Generator: avibe-package-contract-test\n"+ "Root-Is-Purelib: true\n"+ "Tag: py3-none-any\n\n"+ ),+ }+ entries[f"{dist_info}/RECORD"] = "".join(f"{name},,\n" for name in entries) + f"{dist_info}/RECORD,,\n"+ with zipfile.ZipFile(wheel, "w") as archive:+ for name, content in entries.items():+ archive.writestr(name, content)+ return wheel+++def _parent_site_packages() -> list[Path]:+ paths = [+ path+ for value in sys.path+ if value and (path := Path(value).resolve()).name in {"site-packages", "dist-packages"}+ ]+ assert paths+ return paths+++def _provision_build_requirement_wheelhouse(pyprojects: tuple[dict[str, Any], ...], directory: Path) -> None:+ requirements = sorted(+ {+ value+ for pyproject in pyprojects+ for value in pyproject["build-system"]["requires"]+ }+ )+ parsed = [Requirement(value) for value in requirements]+ directory.mkdir()+ _run(+ Path(sys.executable),+ "-m",+ "pip",+ "download",+ "--disable-pip-version-check",+ "--only-binary=:all:",+ "--dest",+ str(directory),+ *requirements,+ cwd=directory.parent,+ )++ wheels = list(directory.glob("*.whl"))+ assert wheels+ downloaded_names = {canonicalize_name(parse_wheel_filename(wheel.name)[0]) for wheel in wheels}+ assert {canonicalize_name(requirement.name) for requirement in parsed} <= downloaded_names+++def _run(python: Path, *args: str, cwd: Path) -> None:+ environment = {**os.environ, "PYTHONPATH": ""}+ result = subprocess.run(+ [str(python), *args],+ cwd=cwd,+ env=environment,+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+++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_requirement.specifier == COMPATIBILITY+++def test_sdist_rewriter_is_an_explicit_isolated_build_requirement() -> None:+ for pyproject in (ROOT / "pyproject.toml", MEMORY_PROJECT / "pyproject.toml"):+ requirement = _requirement(_build_system(pyproject)["requires"], "tomlkit")+ assert str(requirement.specifier) == ">=0.11.1"+++def test_pr_artifact_build_uses_an_explicit_prerelease_contract_version() -> None:+ step = _step(_workflow("lint.yml")["jobs"]["build-linux-artifacts"], "Build package artifact")+ environment = step["env"]++ assert Version(environment["AVIBE_PACKAGE_CONTRACT_VERSION"]) == PACKAGE_CONTRACT_VERSION+ assert PACKAGE_CONTRACT_VERSION.is_prerelease+ assert environment["SETUPTOOLS_SCM_PRETEND_VERSION"] == str(PACKAGE_CONTRACT_VERSION)+ assert environment["SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS"] == str(PACKAGE_CONTRACT_VERSION)+ assert environment["SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY"] == str(PACKAGE_CONTRACT_VERSION)+ assert "python -m build\n" in step["run"]+++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"+ 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",+ )+ 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"):+ pin_peer_dependency(+ str(wheel),+ project_name="avibe-os",+ peer_name="avibe-memory",+ package_version="3.0.99rc1",+ peer_extra="memory",+ )++ assert not wheel.exists()+++def test_distribution_release_contract_is_forward_only_and_memory_first() -> None:+ contract = " ".join(+ (MEMORY_PROJECT / "README.md").read_text(encoding="utf-8").split()+ )++ assert "asset-complete GitHub Release" in contract+ assert "Publish `avibe-memory`" 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+ assert "not release-ready by itself" not in contract+ assert "Wave 3b" not in contract+ assert "Wave 3c" not in contract+++def test_release_workflows_have_no_unconditional_memory_wave_blocker() -> None:+ for name in ("publish.yml", "release_ai.yml"):+ workflow = (WORKFLOW_DIR / name).read_text(encoding="utf-8")+ assert "Block Memory Wave" not in workflow+ assert "Memory Wave 3a release blocked" not in workflow+++ ("workflow_name", "job_name", "manifest_step"),+ [+ ("publish.yml", "build", "Verify package runtime manifests"),+ ("release_ai.yml", "build-assets", "Verify bundled runtime manifests"),+ ],+)+def test_release_paths_build_and_verify_both_distributions(+ workflow_name: str,+ job_name: str,+ manifest_step: str,+) -> None:+ job = _workflow(workflow_name)["jobs"][job_name]+ names = [step.get("name") for step in job["steps"]]+ pin = _step(job, "Pin package version to release tag")["run"]+ build = _step(job, "Build Python distributions")["run"]+ assets = _step(job, "Verify Python distribution asset matrix")["run"]+ manifests = _step(job, manifest_step)["run"]+ package_matrix = _step(job, "Verify distribution package matrix")["run"]++ assert "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=$PACKAGE_VERSION" in pin+ assert "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY=$PACKAGE_VERSION" in pin+ assert "python -m build --outdir dist packaging/avibe-memory" in build+ assert "python -m build" in build+ for pattern in (+ "avibe_memory-*.whl",+ "avibe_memory-*.tar.gz",+ "avibe_os-*.whl",+ "avibe_os-*.tar.gz",+ ):+ assert pattern in assets+ assert 'AVIBE_CORE_WHEEL="$(ls dist/avibe_os-*.whl)"' in package_matrix+ assert 'AVIBE_MEMORY_WHEEL="$(ls dist/avibe_memory-*.whl)"' in package_matrix+ assert "pytest tests/test_memory_distribution.py" in package_matrix+ assert 'Path("dist").glob("avibe_os-*.whl")' in manifests or "avibe_os-" in manifests+ assert "avibe_memory-" in manifests+ assert "avibe-os wheel unexpectedly owns the Memory Runtime manifest" in manifests+ assert "avibe-memory wheel is missing vibe/memory_runtime_manifest.json" in manifests+ assert names.index("Build Python distributions") < names.index(manifest_step)+ assert names.index(manifest_step) < names.index("Verify distribution package matrix")+++def test_github_only_release_uploads_both_distribution_pairs() -> None:+ workflow = _workflow("release_ai.yml")+ build_job = workflow["jobs"]["build-assets"]+ release_job = workflow["jobs"]["release"]+ artifact_upload = _step(build_job, "Upload release artifacts")+ 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 'gh release upload "$TAG"' in release_upload+ assert '"${package_assets[@]}" --clobber' in release_upload+++def test_official_draft_uploads_both_verified_distribution_pairs() -> None:+ build_job = _workflow("publish.yml")["jobs"]["build"]+ names = [step.get("name") for step in build_job["steps"]]+ release_upload = _step(build_job, "Upload GitHub release assets")["run"]++ 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+++def test_official_release_publishes_and_verifies_memory_before_core() -> None:+ jobs = _workflow("publish.yml")["jobs"]++ assert {"build", "finalize-github-release"} <= _needs(+ jobs["publish-avibe-memory"]+ )+ 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 "finalize-github-release" in _needs(jobs["publish-avibe-os"])++ verify = _step(+ jobs["verify-avibe-memory-pypi"],+ "Verify PyPI serves the exact avibe-memory wheel",+ )["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",+ ):+ assert fragment in verify+++ ("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",+ "avibe_os-*",+ "avibe_memory-*",+ ),+ (+ "publish-vibe-remote",+ "Keep vibe-remote distributions only",+ "vibe_remote-*",+ "avibe_",+ ),+ ],+)+def test_each_trusted_publisher_receives_only_its_distribution(+ job_name: str,+ keep_step: str,+ allowed: str,+ excluded: str,+) -> None:+ job = _workflow("publish.yml")["jobs"][job_name]+ names = [step.get("name") for step in job["steps"]]+ keep = _step(job, keep_step)["run"]+ publish_steps = [+ step+ for step in job["steps"]+ if str(step.get("uses", "")).startswith("pypa/gh-action-pypi-publish@")+ ]++ assert len(publish_steps) == 1+ assert names.index(keep_step) < job["steps"].index(publish_steps[0])+ assert allowed in keep+ assert excluded not in keep+ assert publish_steps[0]["with"]["skip-existing"] is True+++def test_built_distributions_have_independent_contents_and_exact_peer_metadata() -> None:+ core_wheel = _wheel_path("AVIBE_CORE_WHEEL")+ memory_wheel = _wheel_path("AVIBE_MEMORY_WHEEL")+ core_names, core_metadata = _wheel_metadata(core_wheel)+ memory_names, memory_metadata = _wheel_metadata(memory_wheel)+ core_sdist_metadata = _sdist_metadata(core_wheel, "avibe_os")+ memory_sdist_metadata = _sdist_metadata(memory_wheel, "avibe_memory")+ core_sdist_pyproject = _sdist_pyproject(core_wheel, "avibe_os")+ memory_sdist_pyproject = _sdist_pyproject(memory_wheel, "avibe_memory")+ core_sdist_project = core_sdist_pyproject["project"]+ memory_sdist_project = memory_sdist_pyproject["project"]++ assert core_metadata["Name"] == "avibe-os"+ assert memory_metadata["Name"] == "avibe-memory"+ assert not any(name.startswith("avibe_memory/") for name in core_names)+ assert "vibe/memory_runtime_manifest.json" not in core_names+ assert "core/memory_loader.py" in core_names++ source_files = {+ path.relative_to(ROOT).as_posix()+ for path in (ROOT / "avibe_memory").rglob("*")+ if path.is_file() and "__pycache__" not in path.parts+ }+ packaged_files = {+ name for name in memory_names if name.startswith("avibe_memory/")+ }+ assert packaged_files == source_files+ assert "vibe/memory_runtime_manifest.json" in memory_names+ with zipfile.ZipFile(memory_wheel) as archive:+ assert archive.read("vibe/memory_runtime_manifest.json") == (+ ROOT / "vibe/memory_runtime_manifest.json"+ ).read_bytes()++ core_version = Version(core_metadata["Version"])+ memory_version = Version(memory_metadata["Version"])+ assert memory_version == core_version+ explicit_version = os.environ.get("AVIBE_PACKAGE_CONTRACT_VERSION")+ if explicit_version is not None:+ assert core_version == Version(explicit_version) == PACKAGE_CONTRACT_VERSION++ 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"})+ 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 str(memory_build_requirement.specifier) == f"=={memory_version}"+ assert memory_build_requirement.marker is None+ for pyproject in (core_sdist_pyproject, memory_sdist_pyproject):+ build_requirement = _requirement(pyproject["build-system"]["requires"], "tomlkit")+ assert str(build_requirement.specifier) == ">=0.11.1"+++def test_memory_extra_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"])+ environment = tmp_path / "same-version-resolver"+ subprocess.run(+ [sys.executable, "-m", "venv", str(environment)],+ check=True,+ capture_output=True,+ text=True,+ )+ python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ child_site_packages = subprocess.run(+ [str(python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ Path(child_site_packages, "avibe-test-environment.pth").write_text(+ "".join(f"{path}\n" for path in _parent_site_packages()),+ encoding="utf-8",+ )+ _run(+ python,+ "-m",+ "pip",+ "install",+ "--disable-pip-version-check",+ "--no-deps",+ "--force-reinstall",+ str(core_wheel),+ cwd=tmp_path,+ )+ _run(+ python,+ "-m",+ "pip",+ "install",+ "--disable-pip-version-check",+ "--no-index",+ "--find-links",+ str(core_wheel.parent),+ "--find-links",+ str(memory_wheel.parent),+ f"avibe-os[memory]=={core_version}",+ cwd=tmp_path,+ )+ _run(+ python,+ "-c",+ (+ "from importlib.metadata import version; "+ f"assert version('avibe-os') == version('avibe-memory') == {str(core_version)!r}"+ ),+ cwd=tmp_path,+ )+++def test_memory_extra_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")+ memory_sdist = _sdist_path(memory_wheel, "avibe_memory")+ core_pyproject = _sdist_pyproject(core_wheel, "avibe_os")+ memory_pyproject = _sdist_pyproject(memory_wheel, "avibe_memory")+ core_version = Version(_sdist_metadata(core_wheel, "avibe_os")["Version"])+ decoy_version = Version("3.0.99rc2")+ assert decoy_version > core_version++ 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)++ environment = tmp_path / "sdist-resolver"+ subprocess.run(+ [sys.executable, "-m", "venv", str(environment)],+ check=True,+ capture_output=True,+ text=True,+ )+ python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ child_site_packages = subprocess.run(+ [str(python), "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ Path(child_site_packages, "avibe-test-runtime-dependencies.pth").write_text(+ "".join(f"{path}\n" for path in _parent_site_packages()),+ encoding="utf-8",+ )++ install_command = [+ "-m",+ "pip",+ "install",+ "--disable-pip-version-check",+ "--no-index",+ "--find-links",+ str(package_links),+ "--find-links",+ str(build_links),+ f"avibe-os[memory] @ {core_sdist.as_uri()}",+ ]+ assert "--no-build-isolation" not in install_command+ assert install_command.count("--find-links") == 2+ _run(+ python,+ *install_command,+ cwd=tmp_path,+ )+ _run(+ python,+ "-c",+ (+ "from importlib.metadata import version; "+ f"assert version('avibe-os') == version('avibe-memory') == {str(core_version)!r}"+ ),+ cwd=tmp_path,+ )++[email protected]("installation", ["core-only", "core+memory"])+def test_wheel_installation_matrix(+ installation: str,+ tmp_path: Path,+) -> None:+ core_wheel = _wheel_path("AVIBE_CORE_WHEEL")+ memory_wheel = _wheel_path("AVIBE_MEMORY_WHEEL")+ environment = tmp_path / installation+ subprocess.run(+ [sys.executable, "-m", "venv", str(environment)],+ check=True,+ capture_output=True,+ text=True,+ )+ python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+ wheels = [core_wheel]+ if installation == "core+memory":+ wheels.append(memory_wheel)+ _run(+ python,+ "-m",+ "pip",+ "install",+ "--disable-pip-version-check",+ "--no-deps",+ *(str(wheel) for wheel in wheels),+ cwd=tmp_path,+ )++ expected = installation == "core+memory"+ _run(+ python,+ "-c",+ (+ "import importlib.util; "+ "import core.memory_loader as loader; "+ f"assert (importlib.util.find_spec('avibe_memory') is not None) is {expected!r}; "+ "assert loader.MEMORY_RUNTIME_ENTRYPOINT == 'avibe_memory.runtime'; "+ "assert not hasattr(loader, 'MEMORY_RUNTIME_PROTOCOL_VERSION'); "+ "assert not hasattr(loader, 'MEMORY_RUNTIME_LIFECYCLE_CONTRACT')"+ ),+ cwd=tmp_path,+ )+ if expected:+ _run(+ python,+ "-c",+ (+ "from importlib.metadata import distribution; "+ "import avibe_memory; "+ "assert distribution('avibe-memory').metadata['Name'] == 'avibe-memory'; "+ "assert avibe_memory.__name__ == 'avibe_memory'"+ ),+ cwd=tmp_path,+ )diff --git a/tests/test_memory_everos.py b/tests/test_memory_everos.pyindex e85961594..ddba99608 100644--- a/tests/test_memory_everos.py+++ b/tests/test_memory_everos.py@@ -11,8 +11,8 @@ from unittest.mock import patchimport httpximport pytest-from core.memory import artifact as memory_artifact-from core.memory.everos import (+from avibe_memory import artifact as memory_artifact+from avibe_memory.everos import (PROCESSING_PROBE_REQUEST_TIMEOUT_SECONDS,_AGENTIC_ROUND_HEADER,_AGENTIC_TIMEOUT_HEADER,@@ -33,12 +33,12 @@ from core.memory.everos import (ProviderCapture,attachment_add_rejection_proves_no_write,)-from core.memory.store import (+from avibe_memory.store import (MemoryStore,_provider_session_ref,derive_assistant_memory_owner_id,)-from core.memory.types import (+from avibe_memory.types import (MemoryListItem,MemoryListPage,MemoryProfile,@@ -70,7 +70,7 @@ def test_attachment_rejection_no_write_proof_matches_pinned_everos_version() ->def _sidecar_transport(handler):- return patch("core.memory.everos.httpx.AsyncHTTPTransport", return_value=httpx.MockTransport(handler))+ return patch("avibe_memory.everos.httpx.AsyncHTTPTransport", return_value=httpx.MockTransport(handler))class _FailingResponseStream(httpx.AsyncByteStream):@@ -1611,7 +1611,7 @@ def test_processing_health_probes_both_authenticated_endpoints() -> None:).processing_healthy()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:# The production adapter uses two client constructions: sidecar is not# used for processing probes, so return a normal mock transport client# through a small real-client factory instead of inspecting secrets.@@ -1700,7 +1700,7 @@ def test_processing_preflight_projects_sanitized_provider_error() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)result = asyncio.run(run())assert result.ok is False@@ -1751,7 +1751,7 @@ def test_processing_preflight_accepts_truncated_chat_completion_from_resolved_sl).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -1851,7 +1851,7 @@ def test_processing_preflight_accepts_thinking_model_chat_completions() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -1886,7 +1886,7 @@ def test_processing_health_accepts_thinking_model_chat_completions() -> None:).processing_healthy()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -1911,7 +1911,7 @@ def test_processing_preflight_reports_the_rejected_2xx_shape() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -1952,7 +1952,7 @@ def test_processing_preflight_requires_completion_metadata_for_empty_chat_conten).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -1991,7 +1991,7 @@ def test_processing_preflight_rejects_unhashable_finish_reason() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2029,7 +2029,7 @@ def test_processing_preflight_probes_configured_rerank_endpoint() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2075,7 +2075,7 @@ def test_processing_preflight_probes_vllm_rerank_endpoint() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2120,7 +2120,7 @@ def test_processing_preflight_probes_dashscope_rerank_endpoint() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2166,7 +2166,7 @@ def test_processing_preflight_infers_dashscope_from_maas_url_without_provider()).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2208,7 +2208,7 @@ def test_processing_preflight_probes_configured_multimodal_endpoint() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2271,7 +2271,7 @@ def test_processing_preflight_returns_typed_multimodal_failure() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2308,7 +2308,7 @@ def test_processing_preflight_returns_typed_rerank_failure() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2341,7 +2341,7 @@ def test_processing_preflight_scrubs_provider_error_code() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2367,7 +2367,7 @@ def test_processing_preflight_preserves_http_status_for_non_json_errors() -> Non).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2399,7 +2399,7 @@ def test_processing_preflight_accepts_large_bounded_embedding_vectors() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2430,7 +2430,7 @@ def test_processing_preflight_rejects_response_above_two_mibibytes() -> None:).preflight()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2465,7 +2465,7 @@ def test_processing_health_rejects_response_above_two_mibibytes() -> None:).processing_healthy()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)@@ -2490,7 +2490,7 @@ def test_processing_health_rejects_llm_probe_without_completion_content() -> Non).processing_healthy()real_async_client = httpx.AsyncClient- with patch("core.memory.everos.httpx.AsyncClient", autospec=True) as client_type:+ with patch("avibe_memory.everos.httpx.AsyncClient", autospec=True) as client_type:client_type.side_effect = lambda **kwargs: real_async_client(transport=httpx.MockTransport(handler), **kwargs)assert asyncio.run(run()) is Falsediff --git a/tests/test_memory_im_attachments.py b/tests/test_memory_im_attachments.pyindex b500cfdb6..a78b9486f 100644--- a/tests/test_memory_im_attachments.py+++ b/tests/test_memory_im_attachments.py@@ -5,11 +5,11 @@ from pathlib import Pathimport pytest-import core.memory.im_attachments as im_attachment_module+import avibe_memory.im_attachments as im_attachment_modulefrom core.handlers.inbound_attachments import InboundAttachmentMaterializer-from core.memory.attachments import AttachmentPinStore-from core.memory.im_attachments import select_memory_attachments-from core.memory.types import CaptureAttachment+from avibe_memory.attachments import AttachmentPinStore+from avibe_memory.im_attachments import select_memory_attachments+from avibe_memory.types import CaptureAttachmentfrom modules.im.base import FileAttachment, FileDownloadResult, MessageContextdiff --git a/tests/test_memory_insight.py b/tests/test_memory_insight.pyindex 32d0f591a..b1d19c947 100644--- a/tests/test_memory_insight.py+++ b/tests/test_memory_insight.py@@ -4,7 +4,7 @@ from pathlib import Pathimport pytest-from core.memory.everos_insight.reader import MemoryInsightPaths, MemoryInsightReader+from avibe_memory.everos_insight.reader import MemoryInsightPaths, MemoryInsightReaderdef test_insight_reader_exposes_only_native_processing_record_operations(diff --git a/tests/test_memory_legacy_cleanup.py b/tests/test_memory_legacy_cleanup.pynew file mode 100644index 000000000..d391fa967--- /dev/null+++ b/tests/test_memory_legacy_cleanup.py@@ -0,0 +1,181 @@+from __future__ import annotations++import json+import os+from pathlib import Path++import pytest++from core import memory_legacy_cleanup as cleanup+++def _sidecar_record(home: Path) -> tuple[Path, dict[str, object]]:+ provider_root = home / "memory" / "everos-root"+ socket_path = home / "memory" / ".rt" / "everos.sock"+ record: dict[str, object] = {+ "pid": 451,+ "create_time": 10.5,+ "starttime_ticks": 10.5,+ "process_group": None,+ "provider_root": str(provider_root),+ "socket_path": str(socket_path),+ "role": "sidecar",+ "python": "/runtime/bin/python",+ }+ path = home / "memory" / ".rt" / "everos.sidecar.json"+ path.parent.mkdir(mode=0o700, parents=True)+ path.write_text(json.dumps(record), encoding="utf-8")+ path.chmod(0o600)+ return path, record+++def _identity(+ home: Path,+ *,+ command: tuple[str, ...] | None = None,+) -> cleanup._Identity:+ return cleanup._Identity(+ pid=451,+ stamp=10.5,+ wall_create_time=10.5,+ uid=os.getuid() if hasattr(os, "getuid") else None,+ command=command+ or (+ "/runtime/bin/python",+ "-m",+ "core.memory.sidecar",+ "--uds",+ str(home / "memory" / ".rt" / "everos.sock"),+ ),+ environment={+ "EVEROS_ROOT": str(home / "memory" / "everos-root"),+ "AVIBE_MEMORY_CHILD_ROLE": "sidecar",+ },+ process_group=None,+ )+++def _sync_record(home: Path) -> Path:+ provider_root = home / "memory" / "everos-root"+ path = cleanup._root_artifact(provider_root, cleanup._SYNC_PREFIX, ".json")+ record = {+ "state": "finalized",+ "nonce": "a" * 64,+ "pid": 451,+ "create_time": 10.5,+ "process_group": 451,+ "parent_pid": 99999999,+ "parent_create_time": 8.25,+ "parent_uid": os.getuid() if hasattr(os, "getuid") else None,+ "provider_root": str(provider_root),+ "socket_path": str(home / "memory" / ".rt" / "everos.sock"),+ "role": "cascade_sync",+ "argv": [+ "/runtime/bin/python",+ "-I",+ "-m",+ "everos.entrypoints.cli.main",+ "cascade",+ "sync",+ ],+ }+ path.parent.mkdir(mode=0o700, parents=True)+ path.write_text(json.dumps(record), encoding="utf-8")+ path.chmod(0o600)+ return path+++async def test_core_reaper_retires_gone_released_sidecar(tmp_path: Path) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ path, _record = _sidecar_record(home)+ reaper = cleanup.ReleasedEverOSOrphanReconciler(+ provider_root=home / "memory" / "everos-root",+ effective_home=home,+ )++ await reaper.reconcile_orphans()++ assert not path.exists()+++async def test_core_reaper_retires_gone_released_sync(tmp_path: Path) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ path = _sync_record(home)+ reaper = cleanup.ReleasedEverOSOrphanReconciler(+ provider_root=home / "memory" / "everos-root",+ effective_home=home,+ )++ await reaper.reconcile_orphans()++ assert not path.exists()+++async def test_core_reaper_signals_only_an_exact_released_identity(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ path, _record = _sidecar_record(home)+ observed: list[list[cleanup._Identity]] = []+ monkeypatch.setattr(cleanup, "_inspect", lambda _pid: _identity(home))+ monkeypatch.setattr(+ cleanup,+ "_signal_and_wait",+ lambda identities, _timeout: observed.append(identities),+ )+ reaper = cleanup.ReleasedEverOSOrphanReconciler(+ provider_root=home / "memory" / "everos-root",+ effective_home=home,+ )++ await reaper.reconcile_orphans()++ assert [[identity.pid for identity in batch] for batch in observed] == [[451]]+ assert not path.exists()+++async def test_core_reaper_preserves_record_when_identity_does_not_match(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)+ path, _record = _sidecar_record(home)+ monkeypatch.setattr(+ cleanup,+ "_inspect",+ lambda _pid: _identity(home, command=("/usr/bin/python", "foreign.py")),+ )+ monkeypatch.setattr(+ cleanup,+ "_signal_and_wait",+ lambda *_args, **_kwargs: pytest.fail("foreign process must not be signalled"),+ )+ reaper = cleanup.ReleasedEverOSOrphanReconciler(+ provider_root=home / "memory" / "everos-root",+ effective_home=home,+ )++ with pytest.raises(RuntimeError, match="identity is unavailable"):+ await reaper.reconcile_orphans()++ assert path.exists()+++def test_core_reaper_confines_released_provider_root(tmp_path: Path) -> None:+ home = tmp_path / "home"+ home.mkdir(mode=0o700)++ with pytest.raises(RuntimeError, match="escaped its home"):+ cleanup.ReleasedEverOSOrphanReconciler(+ provider_root=tmp_path / "foreign",+ effective_home=home,+ )diff --git a/tests/test_memory_loader.py b/tests/test_memory_loader.pynew file mode 100644index 000000000..c38b5c020--- /dev/null+++ b/tests/test_memory_loader.py@@ -0,0 +1,219 @@+from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from core.memory_loader import load_memory_runtime, probe_memory_runtime_entrypoint+from vibe.memory_contract import (+ MemoryImplementationIncompatibleError,+ MemoryImplementationUnavailableError,+ MemoryRuntimeBusyError,+)+++def _config(enabled: bool = True) -> SimpleNamespace:+ return SimpleNamespace(enabled=enabled)+++def _implementation(factory: object) -> SimpleNamespace:+ return SimpleNamespace(create_memory_runtime=factory)+++def test_disabled_loader_never_imports_optional_implementation(monkeypatch: pytest.MonkeyPatch) -> None:+ import core.memory_loader++ importer = Mock(side_effect=AssertionError("disabled loader imported Memory"))+ monkeypatch.setattr(core.memory_loader.importlib, "import_module", importer)++ assert load_memory_runtime(_config(False)) is None+ importer.assert_not_called()++[email protected]("probe_only", (False, True))+def test_loader_and_probe_map_missing_implementation_to_unavailable(+ monkeypatch: pytest.MonkeyPatch,+ probe_only: bool,+) -> None:+ import core.memory_loader++ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(side_effect=ModuleNotFoundError("optional package missing")),+ )++ with pytest.raises(MemoryImplementationUnavailableError):+ if probe_only:+ probe_memory_runtime_entrypoint()+ else:+ load_memory_runtime(_config())+++def test_entrypoint_contract_has_no_parallel_integer_version_markers() -> None:+ import core.memory_loader+ import avibe_memory.runtime++ retired_markers = (+ "MEMORY_RUNTIME_PROTOCOL_VERSION",+ "MEMORY_RUNTIME_LIFECYCLE_CONTRACT",+ )+ assert all(not hasattr(core.memory_loader, name) for name in retired_markers)+ assert all(not hasattr(avibe_memory.runtime, name) for name in retired_markers)++[email protected]("factory", (None, object()))+def test_entrypoint_probe_rejects_missing_or_noncallable_factory(+ monkeypatch: pytest.MonkeyPatch,+ factory: object,+) -> None:+ import core.memory_loader++ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(factory)),+ )++ with pytest.raises(MemoryImplementationUnavailableError):+ probe_memory_runtime_entrypoint()+++def test_entrypoint_probe_validates_contract_without_constructing_runtime(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import core.memory_loader++ factory = Mock(side_effect=AssertionError("the contract probe constructed Memory"))+ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(factory)),+ )++ assert probe_memory_runtime_entrypoint() is None+ factory.assert_not_called()+++ "attribute",+ (+ "create_memory_runtime",+ ),+)+def test_loader_translates_implementation_attribute_probe_failure(+ monkeypatch: pytest.MonkeyPatch,+ attribute: str,+) -> None:+ import core.memory_loader++ class _BrokenImplementation:+ def __getattr__(self, name: str) -> object:+ if name == attribute:+ raise RuntimeError("broken implementation attribute")+ return None++ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_BrokenImplementation()),+ )++ with pytest.raises(MemoryImplementationUnavailableError):+ load_memory_runtime(_config())+++def test_loader_maps_constructor_failure_to_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ import core.memory_loader++ factory = Mock(side_effect=RuntimeError("constructor failed"))+ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(factory)),+ )++ with pytest.raises(MemoryImplementationUnavailableError):+ load_memory_runtime(_config())+++def test_loader_preserves_runtime_root_busy(monkeypatch: pytest.MonkeyPatch) -> None:+ import core.memory_loader++ busy = MemoryRuntimeBusyError("provider root busy")+ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(Mock(side_effect=busy))),+ )++ with pytest.raises(MemoryRuntimeBusyError) as raised:+ load_memory_runtime(_config())++ assert raised.value is busy+++ ("config", "loader_kwargs", "factory_kwargs"),+ (+ (_config(), {"marker": "tested"}, {"marker": "tested"}),+ (_config(False), {"allow_disabled": True}, {}),+ ),+)+def test_loader_constructs_declared_runtime(+ monkeypatch: pytest.MonkeyPatch,+ config: SimpleNamespace,+ loader_kwargs: dict[str, object],+ factory_kwargs: dict[str, object],+) -> None:+ import core.memory_loader++ async def close() -> None:+ return None++ runtime = SimpleNamespace(module=object(), available=True, close=close)+ factory = Mock(return_value=runtime)+ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(factory)),+ )++ assert load_memory_runtime(config, **loader_kwargs) is runtime+ factory.assert_called_once_with(config, **factory_kwargs)+++def test_loader_rejects_incomplete_runtime_contract(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import core.memory_loader++ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(Mock(return_value=SimpleNamespace()))),+ )++ with pytest.raises(MemoryImplementationIncompatibleError):+ load_memory_runtime(_config())+++def test_loader_maps_runtime_contract_probe_failure_to_incompatible(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ import core.memory_loader++ class _BrokenRuntime:+ @property+ def module(self):+ raise RuntimeError("module probe failed")++ monkeypatch.setattr(+ core.memory_loader.importlib,+ "import_module",+ Mock(return_value=_implementation(Mock(return_value=_BrokenRuntime()))),+ )++ with pytest.raises(MemoryImplementationIncompatibleError):+ load_memory_runtime(_config())diff --git a/tests/test_memory_modality.py b/tests/test_memory_modality.pyindex e1c187366..33b60dfdc 100644--- a/tests/test_memory_modality.py+++ b/tests/test_memory_modality.py@@ -4,7 +4,7 @@ from types import ModuleTypeimport pytest-from core.memory.modality import (+from avibe_memory.modality import (PINNED_UPSTREAM_EXCLUDED_EXTENSIONS,SUPPORTED_ATTACHMENT_EXTENSIONS,classify_pinned_attachment,diff --git a/tests/test_memory_module.py b/tests/test_memory_module.pyindex 788191025..2c061eaef 100644--- a/tests/test_memory_module.py+++ b/tests/test_memory_module.py@@ -8,15 +8,15 @@ from types import SimpleNamespaceimport pytest-from core.memory.attachments import (+from avibe_memory.attachments import (AttachmentCleanupUnprovenError,AttachmentPinError,AttachmentPinStore,)-from core.memory.everos import FakeMemoryProvider-from core.memory.module import MIN_FREE_DISK_BYTES, MemoryModule-from core.memory.store import MemoryStore, VolatileAdmission-from core.memory.types import (+from avibe_memory.everos import FakeMemoryProvider+from avibe_memory.module import MIN_FREE_DISK_BYTES, MemoryModule+from avibe_memory.store import MemoryStore, VolatileAdmission+from avibe_memory.types import (CaptureAccepted,CaptureAttachment,CaptureDuplicate,@@ -32,7 +32,7 @@ from core.memory.types import (OperationFailed,ProviderSearchItem,)-from core.memory.writer import MAX_WRITER_PERMITS+from avibe_memory.writer import MAX_WRITER_PERMITSPRINCIPAL = "u-" + "1" * 32diff --git a/tests/test_memory_native_processing_record.py b/tests/test_memory_native_processing_record.pyindex 588a0fb54..893d2f657 100644--- a/tests/test_memory_native_processing_record.py+++ b/tests/test_memory_native_processing_record.py@@ -6,8 +6,8 @@ import jsonfrom pathlib import Pathimport sqlite3-from core.memory.native_processing_record import NativeProcessingRecordReader-from core.memory.store import derive_assistant_memory_owner_id+from avibe_memory.native_processing_record import NativeProcessingRecordReader+from avibe_memory.store import derive_assistant_memory_owner_idPRINCIPAL = "u-" + "a" * 32diff --git a/tests/test_memory_operation_lock.py b/tests/test_memory_operation_lock.pyindex e08e09eb2..7de3add2a 100644--- a/tests/test_memory_operation_lock.py+++ b/tests/test_memory_operation_lock.py@@ -6,7 +6,7 @@ from pathlib import Pathimport pytest-from core.memory.operation_lock import (+from config.memory_operation_lock import (MemoryOperationBusy,MemoryOperationLease,memory_operation_lock_path,diff --git a/tests/test_memory_process.py b/tests/test_memory_process.pyindex 5dd7c39ad..ea08b57f9 100644--- a/tests/test_memory_process.py+++ b/tests/test_memory_process.py@@ -4,12 +4,15 @@ from collections import dequeimport jsonimport osfrom pathlib import Path+import sysimport pytest-from core.memory.confined_filesystem import ConfinedFilesystemError-from core.memory.process import (+from avibe_memory.confined_filesystem import ConfinedFilesystemError+from avibe_memory.process import (_ProcessIdentity,+ _cmdline_is_sidecar,+ _memory_child_environment,EverOSProcessSettings,FakeEverOSProcess,FakeEverOSProcessFactory,@@ -149,13 +152,18 @@ def _sidecar_record(home: Path) -> tuple[Path, dict[str, object]]:return path, record-def _sidecar_identity(home: Path, record: dict[str, object]) -> _ProcessIdentity:+def _sidecar_identity(+ home: Path,+ record: dict[str, object],+ *,+ entrypoint: str = "avibe_memory.sidecar",+) -> _ProcessIdentity:return _ProcessIdentity(stamp=10.5,cmdline=(str(record["python"]),"-m",- "core.memory.sidecar",+ entrypoint,"--uds",str(record["socket_path"]),),@@ -301,6 +309,23 @@ def test_process_factory_keeps_secrets_out_of_repr(tmp_path: Path) -> None:assert factory.supervised == [process]+def test_memory_child_environment_exposes_top_level_package_root(+ tmp_path: Path,+) -> None:+ environment = _memory_child_environment(+ python=Path(sys.executable),+ memory_dir=tmp_path / "memory",+ provider_root=tmp_path / "memory" / "everos-root",+ attachments_root=tmp_path / "memory" / "attachments",+ settings=EverOSProcessSettings(),+ role=None,+ )++ package_root = Path(__file__).resolve().parents[1]+ assert environment["PYTHONPATH"] == str(package_root)+ assert (package_root / "avibe_memory").is_dir()++def test_recorded_sidecar_reaper_confines_provider_root(tmp_path: Path) -> None:home = tmp_path / "home"home.mkdir(mode=0o700)@@ -331,14 +356,29 @@ async def test_recorded_sidecar_reaper_accepts_empty_owned_root(tmp_path: Path)@pytest.mark.asyncio-async def test_sidecar_reaper_verifies_identity_before_signalling(tmp_path: Path) -> None:+ ("entrypoint", "legacy_record"),+ [+ ("avibe_memory.sidecar", False),+ ("core.memory.sidecar", False),+ ("core.memory.sidecar", True),+ ],+)+async def test_sidecar_reaper_verifies_identity_before_signalling(+ tmp_path: Path,+ entrypoint: str,+ legacy_record: bool,+) -> None:home = tmp_path / "home"provider_root = home / "memory" / "everos-root"provider_root.mkdir(mode=0o700, parents=True)home.chmod(0o700)(home / "memory").chmod(0o700)path, record = _sidecar_record(home)- identity = _sidecar_identity(home, record)+ if legacy_record:+ record.pop("role")+ path.write_text(json.dumps(record), encoding="utf-8")+ identity = _sidecar_identity(home, record, entrypoint=entrypoint)host = _SidecarHost({451: identity})reaper = ReleasedEverOSOrphanReconciler(provider_root=provider_root,@@ -352,6 +392,18 @@ async def test_sidecar_reaper_verifies_identity_before_signalling(tmp_path: Pathassert not path.exists()+ "entrypoint",+ ["avibe_memory.sidecar", "core.memory.sidecar"],+)+def test_sidecar_discovery_accepts_current_and_released_entrypoints(+ entrypoint: str,+) -> None:+ assert _cmdline_is_sidecar(+ ("/runtime/bin/python", "-m", entrypoint, "--uds", "/memory.sock")+ )++@pytest.mark.asyncioasync def test_reaper_consumes_released_rebuild_ownership(tmp_path: Path) -> None:home = tmp_path / "home"diff --git a/tests/test_memory_processing_record.py b/tests/test_memory_processing_record.pyindex c5f0e721d..f207a462a 100644--- a/tests/test_memory_processing_record.py+++ b/tests/test_memory_processing_record.py@@ -1,6 +1,6 @@from __future__ import annotations-from core.memory.processing_record import (+from avibe_memory.processing_record import (AnomalyProjection,MaintenanceProjection,ProcessingRecordSummary,diff --git a/tests/test_memory_project_ids.py b/tests/test_memory_project_ids.pyindex 513612d4a..1aa659a30 100644--- a/tests/test_memory_project_ids.py+++ b/tests/test_memory_project_ids.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from core.memory.project_ids import (+from vibe.memory_project_ids import (DEFAULT_MEMORY_PROJECT_ID,MEMORY_SEARCH_ALL_PROJECTS,is_legacy_memory_project_id,diff --git a/tests/test_memory_provider_root.py b/tests/test_memory_provider_root.pyindex 28fbec3a1..e768b20c1 100644--- a/tests/test_memory_provider_root.py+++ b/tests/test_memory_provider_root.py@@ -9,8 +9,8 @@ from types import SimpleNamespaceimport pytest-import core.memory.confined_filesystem as confined_filesystem_module-from core.memory.provider_root import (+import avibe_memory.confined_filesystem as confined_filesystem_module+from avibe_memory.provider_root import (PROVIDER_ROOT_CONTROL_FILES,ROOT_SENTINEL_FILENAME,ProviderRoot,diff --git a/tests/test_memory_python_compat.py b/tests/test_memory_python_compat.pyindex 088eeec8c..e249f4eb9 100644--- a/tests/test_memory_python_compat.py+++ b/tests/test_memory_python_compat.py@@ -4,7 +4,7 @@ import astfrom pathlib import Path-MEMORY_ROOT = Path(__file__).resolve().parents[1] / "core" / "memory"+MEMORY_ROOT = Path(__file__).resolve().parents[1] / "avibe_memory"def test_memory_modules_do_not_import_python_311_datetime_utc() -> None:diff --git a/tests/test_memory_recall_policy.py b/tests/test_memory_recall_policy.pyindex c85980dbb..75d40b85a 100644--- a/tests/test_memory_recall_policy.py+++ b/tests/test_memory_recall_policy.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from core.memory.types import RecallPolicy+from avibe_memory.types import RecallPolicydef test_non_agentic_policy_defaults_only_an_omitted_limit() -> None:diff --git a/tests/test_memory_runtime.py b/tests/test_memory_runtime.pyindex c9f74805e..ead408b0b 100644--- a/tests/test_memory_runtime.py+++ b/tests/test_memory_runtime.py@@ -2,18 +2,25 @@import asyncioimport sqlite3+import threadingfrom datetime import datetime, timedelta, timezonefrom pathlib import Pathimport pytest-import core.memory.runtime as runtime_module+import avibe_memory.runtime as runtime_module+from avibe_memory.capture_adapter import EnabledMemoryAdapterfrom config.v2_config import MemoryEndpointConfig, MemoryProcessingConfig-from core.memory.everos import ProviderHealthSnapshot-from core.memory.processing_record import RuntimeHealthProjection, SourceObservation-from core.memory.runtime import MemoryConfig, MemoryRuntime-from core.memory.store import MemoryStore-from core.memory.types import MemoryItems, MemoryListItem, MemoryListPage+from avibe_memory.everos import ProviderHealthSnapshot+from avibe_memory.processing_record import (+ MaintenanceObservation,+ RuntimeHealthProjection,+ SourceObservation,+)+from avibe_memory.runtime import MemoryConfig, MemoryRuntime+from avibe_memory.store import MemoryStore+from avibe_memory.types import MemoryItems, MemoryListItem, MemoryListPage+from vibe.memory_contract import MemoryRuntimeBusyErrordef _runtime(tmp_path: Path) -> MemoryRuntime:@@ -81,7 +88,10 @@ async def test_all_project_list_accepts_everos_maximum_page_size(for index in range(100))- runtime.list_memory_projects = lambda _principal_id: ("default",)+ async def list_memory_projects(_principal_id: str) -> tuple[str, ...]:+ return ("default",)++ runtime.list_memory_projects = list_memory_projectsasync def list_episodes(**kwargs: object) -> MemoryListPage:page = int(kwargs["page"])@@ -152,10 +162,265 @@ async def test_session_lifecycle_offers_without_waiting_for_capture(tmp_path: Pa@pytest.mark.asyncio-async def test_runtime_close_drops_volatile_work(tmp_path: Path) -> None:+ "read_kind",+ ("sources", "maintenance", "principal", "projects"),+)+async def test_local_reads_hold_reset_and_fail_closed_after_detach(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ read_kind: str,+) -> None:+ def fail_supervisor(**_kwargs):+ raise RuntimeError("supervisor construction failed")++ with pytest.raises(RuntimeError) as retained:+ MemoryRuntime(+ MemoryConfig(enabled=True),+ effective_home=tmp_path,+ supervisor_factory=fail_supervisor,+ )+ assert retained.traceback is not Noneruntime = _runtime(tmp_path)++ observation = MaintenanceObservation(block_reason=None, can_delete_data=True)+ principal_id = "u-11111111111111111111111111111111"+ read_call = {+ "sources": lambda: runtime._processing_record_sources(None),+ "maintenance": lambda: runtime._processing_record_maintenance(+ None, observation+ ),+ "principal": lambda: runtime.resolve_principal_for_user_key("avibe:local"),+ "projects": lambda: runtime.list_memory_projects(principal_id),+ }[read_kind]+ wake = None+ if read_kind == "sources":+ failure = await runtime._processing_record_failure_log(None)+ assert failure.items == ()+ assert failure.unavailable_reason == "memory_failure_history_unavailable"+ wake_entered = asyncio.Event()++ async def pending_wake() -> None:+ wake_entered.set()+ await asyncio.Event().wait()++ monkeypatch.setattr(runtime, "_wake_after_writer_close", pending_wake)+ runtime._defer_wake_until_writer_closed()+ wake = runtime._wake_task+ assert wake is not None+ await wake_entered.wait()+ run_local = runtime._run_local_observation+ started = threading.Event()+ release = threading.Event()++ async def blocked(operation):+ def run():+ started.set()+ assert release.wait(timeout=5.0)+ return operation()++ return await run_local(run)++ monkeypatch.setattr(runtime, "_run_local_observation", blocked)+ read = asyncio.create_task(read_call())++ try:+ assert await asyncio.to_thread(started.wait, 1.0)+ ownership = runtime.begin_root_ownership_handoff()++ async def close_and_reset():+ await runtime.close(root_ownership=ownership)+ return runtime.reset_mutable_data(ownership)++ resetting = asyncio.create_task(close_and_reset())+ while "local cleanup" not in runtime._close_phase_tasks:+ await asyncio.sleep(0)+ assert resetting.done() is False+ assert (tmp_path / "memory").exists()+ finally:+ release.set()+ await read+ assert (await resetting).data_deleted is True+ if wake is not None:+ assert wake.cancelled() and runtime._wake_task is None+ monkeypatch.setattr(runtime, "_run_local_observation", run_local)++ if read_kind in {"sources", "maintenance"}:+ detached = await read_call()+ else:+ with pytest.raises(MemoryRuntimeBusyError):+ await read_call()+ if read_kind == "sources":+ assert {+ detached.memcells.reason,+ detached.runs.reason,+ detached.semantic.reason,+ } == {"busy"}+ assert not hasattr(runtime, "log_entries_payload")+ assert not hasattr(runtime, "_call_log_db_path")+ failure = await runtime._processing_record_failure_log(None)+ assert failure.unavailable_reason == "busy"+ elif read_kind == "maintenance":+ assert detached.data_exists is True+ assert detached.can_delete_data is False+ assert detached.error == "busy"+ with pytest.raises(MemoryRuntimeBusyError):+ _runtime(tmp_path)++ if read_kind == "sources":+ replacement = runtime.replacement(MemoryConfig(enabled=True), ownership)+ with pytest.raises(MemoryRuntimeBusyError):+ _runtime(tmp_path)+ replacement.accept_root_ownership()+ await replacement.close()+ else:+ runtime.release_retained_root_ownership()+ await _runtime(tmp_path).close()+++async def test_runtime_close_timeouts_still_attempt_everos_stop(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runtime = _runtime(tmp_path)+ release = asyncio.Event()+ phases: list[str] = []++ def stalled(label: str):+ async def wait() -> None:+ phases.append(label)+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ await release.wait()++ return wait++ async def stop_provider() -> None:+ phases.append("provider")++ monkeypatch.setattr(runtime, "_cancel_capture_tasks", stalled("capture"))+ monkeypatch.setattr(runtime, "_close_local_runtime", stalled("local"))+ monkeypatch.setattr(runtime._supervisor, "close", stop_provider)++ with pytest.raises(RuntimeError, match="local cleanup"):+ await runtime.close(timeout_seconds=0.03)++ assert phases == ["capture", "local", "provider"]+ with pytest.raises(MemoryRuntimeBusyError):+ _runtime(tmp_path)+ release.set()+ await asyncio.sleep(0)+ await runtime.close(timeout_seconds=1.0)++ replacement = _runtime(tmp_path)+ await replacement.close()+++async def test_blocked_artifact_install_keeps_root_across_cached_close_deadline(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runtime = _runtime(tmp_path)+ install_started = threading.Event()+ install_release = threading.Event()++ def blocked_ensure(*, force: bool) -> dict[str, object]:+ assert force is True+ install_started.set()+ assert install_release.wait(timeout=2.0)+ return {"ok": True}++ monkeypatch.setattr(runtime._artifact_manager, "ensure", blocked_ensure)+ install = asyncio.create_task(runtime.install_artifact())+ assert await asyncio.to_thread(install_started.wait, 1.0)++ close = asyncio.create_task(runtime.close(timeout_seconds=1.0))+ while "local cleanup" not in runtime._close_phase_tasks:+ await asyncio.sleep(0)+ with pytest.raises(TimeoutError):+ await runtime.close(timeout_seconds=0.03)+ assert close.done() is False+ with pytest.raises(MemoryRuntimeBusyError):+ _runtime(tmp_path)++ install_release.set()+ assert await install == {+ "ok": False,+ "reason": "memory_operation_in_progress",+ "download_error": None,+ }+ await close+ replacement = _runtime(tmp_path)+ await replacement.close()++[email protected]("operation", ("reconcile", "wake"))+async def test_revoked_lifecycle_stops_before_provider_root_side_effects(+ operation: str,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ runtime = _runtime(tmp_path)+ stop_started = asyncio.Event()+ stop_release = asyncio.Event()++ async def truthy(*_args) -> bool:+ return True++ async def delayed_stop() -> None:+ stop_started.set()+ await stop_release.wait()++ async def unexpected_async(name: str, *_args, **_kwargs):+ pytest.fail(f"revoked reconciliation reached {name}")++ def unexpected_sync(name: str, *_args, **_kwargs):+ pytest.fail(f"revoked reconciliation reached {name}")++ async def no_op() -> None:+ return None++ monkeypatch.setattr(runtime, "_reconcile_released_ownership", truthy)+ monkeypatch.setattr(runtime, "_probe_processing", truthy)+ monkeypatch.setattr(runtime, "artifact_admitted", lambda: True)+ monkeypatch.setattr(runtime._artifact_manager, "resolve_python", lambda: Path("python"))+ monkeypatch.setattr(runtime._supervisor, "stop", delayed_stop)+ monkeypatch.setattr(+ runtime._supervisor,+ "wake",+ lambda *_args, **_kwargs: unexpected_async("provider wake"),+ )+ monkeypatch.setattr(+ runtime._store,+ "ensure_meta",+ lambda: unexpected_sync("store metadata"),+ )+ monkeypatch.setattr(+ runtime._provider_root_owner,+ "ensure",+ lambda *_args: unexpected_sync("provider root ensure"),+ )+ monkeypatch.setattr(runtime, "_close_local_runtime", no_op)+ monkeypatch.setattr(runtime._supervisor, "close", no_op)++ lifecycle = asyncio.create_task(+ runtime.reconcile(MemoryConfig(enabled=True))+ if operation == "reconcile"+ else runtime.wake(operation_lease_held=True)+ )+ await stop_started.wait()+ runtime.begin_close()+ stop_release.set()++ expected = {"ok": False, "error": "memory_operation_in_progress"}+ if operation == "wake":+ expected["state"] = "starting"+ assert await lifecycle == expectedawait runtime.close()- assert runtime.closed@pytest.mark.asyncio@@ -190,6 +455,46 @@ async def test_environmental_store_failure_defers_durable_repair_fence(await runtime.close()+async def test_store_recovery_keeps_facade_identity_and_starts_bound_scheduler(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store_type = runtime_module.MemoryStore++ def unavailable_store(*_args, **_kwargs):+ raise PermissionError("denied")++ async def acquire(_session_id: str) -> object:+ return type("Admission", (), {"release": lambda self: None})()++ monkeypatch.setattr(runtime_module, "MemoryStore", unavailable_store)+ runtime = MemoryRuntime(+ MemoryConfig(enabled=True),+ effective_home=tmp_path,+ is_enabled_user=lambda _platform, _user_id: True,+ lifecycle_snapshot_matches=lambda _session_id, _snapshot: True,+ acquire_lifecycle_admission=acquire,+ )+ facade = runtime.capture_adapter+ assert isinstance(facade, EnabledMemoryAdapter)+ assert runtime.available is False+ assert runtime.start_capture_adapter(+ task_factory=asyncio.get_running_loop().create_task+ ) is False++ monkeypatch.setattr(runtime_module, "MemoryStore", store_type)+ assert runtime._open_store() is True++ assert runtime.capture_adapter is facade+ assert runtime.available is True+ assert facade._worker_task is not None+ assert not facade._worker_task.done()+ with pytest.raises(RuntimeError, match="scheduler is already bound"):+ runtime.start_capture_adapter(task_factory=lambda _pending, **_kwargs: None)+ await runtime.close()++@pytest.mark.asyncioasync def test_disabled_legacy_recovery_remains_visible_as_needs_repair(tmp_path: Path,@@ -321,63 +626,6 @@ async def test_malformed_released_clear_journal_remains_repair_fenced(await runtime.close()-async def test_runtime_close_cancels_pending_automatic_wake(- tmp_path: Path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- """MEMORY-INDEP-003: shutdown cancels volatile recovery work."""-- runtime = _runtime(tmp_path)- wake_entered = asyncio.Event()-- async def pending_wake() -> None:- wake_entered.set()- await asyncio.Event().wait()-- monkeypatch.setattr(runtime, "_wake_after_writer_close", pending_wake)- runtime._defer_wake_until_writer_closed()- wake = runtime._wake_task- assert wake is not None- await wake_entered.wait()-- await asyncio.wait_for(runtime.close(), timeout=1.0)-- assert wake.cancelled()- assert runtime._wake_task is None- assert runtime.closed---async def test_processing_record_uses_native_sources_without_call_log(tmp_path: Path) -> None:- runtime = _runtime(tmp_path)-- projection = await runtime._processing_record_sources(None)-- assert projection.memcells.status == "unavailable"- assert projection.runs.status == "unavailable"- assert projection.semantic.status == "unavailable"- assert not hasattr(runtime, "log_entries_payload")- assert not hasattr(runtime, "log_unlinked_calls_payload")- assert not hasattr(runtime, "_call_log_db_path")- await runtime.close()---async def test_capture_diagnostics_are_unavailable_without_delivery_history(- tmp_path: Path,-) -> None:- """MEMORY-SEARCH-014: absent durable history is unavailable, not empty."""-- runtime = _runtime(tmp_path)-- observation = await runtime._processing_record_failure_log(None)-- assert observation.items == ()- assert observation.unavailable_reason == "memory_failure_history_unavailable"- await runtime.close()--@pytest.mark.asyncioasync def test_status_uses_unified_state_and_omits_cascade_protocol(tmp_path: Path) -> None:runtime = _runtime(tmp_path)@@ -429,6 +677,13 @@ async def test_disabled_attachment_intake_is_unavailable_in_status(),effective_home=tmp_path,)+ first_epoch = runtime.attachment_capture_config_generation()+ assert isinstance(first_epoch, int)+ runtime._replace_provider(runtime._provider)+ second_epoch = runtime.attachment_capture_config_generation()+ assert isinstance(second_epoch, int)+ assert second_epoch > first_epoch+runtime.module._writer.disable_attachment_intake()assert (await runtime.status_payload())["attachment_capture"] == {diff --git a/tests/test_memory_runtime_factory.py b/tests/test_memory_runtime_factory.pyindex 3ba987d83..5250ef392 100644--- a/tests/test_memory_runtime_factory.py+++ b/tests/test_memory_runtime_factory.py@@ -8,8 +8,8 @@ from typing import AsyncIteratorimport pytestfrom config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfig-from core.memory.artifact import FakeMemoryArtifactManager-from core.memory.process import FakeEverOSProcessFactory+from avibe_memory.artifact import FakeMemoryArtifactManager+from avibe_memory.process import FakeEverOSProcessFactoryfrom tests.memory_runtime_factory import (MemoryRuntimeFactory,finalizing_memory_runtimes,@@ -302,7 +302,6 @@ async def test_factory_settles_runtime_tasks_and_sidecar_before_scope_exit(assert scheduler_task not in asyncio.all_tasks()assert runtime.module._writer._worker_task is Noneassert runtime.module._writer._scheduler_task is None- assert runtime.closed is Trueasync def test_factory_continues_teardown_after_a_close_failure(tmp_path: Path) -> None:@@ -353,7 +352,7 @@ sys.path.insert(0, {str(project_root)!r})import pytestfrom config.v2_config import MemoryConfig-from core.memory.artifact import FakeMemoryArtifactManager+from avibe_memory.artifact import FakeMemoryArtifactManager@pytest.mark.asynciodiff --git a/tests/test_memory_runtime_release.py b/tests/test_memory_runtime_release.pyindex 115c9aedf..fb5000d34 100644--- a/tests/test_memory_runtime_release.py+++ b/tests/test_memory_runtime_release.py@@ -13,7 +13,7 @@ from pathlib import Pathimport pytest-from core.memory.artifact_contract import ColdArtifactAdmissionResult+from avibe_memory.artifact_contract import ColdArtifactAdmissionResultfrom scripts import build_memory_runtime as runtime_builderfrom scripts import generate_memory_runtime_manifest as manifest_generatorfrom scripts.build_memory_runtime import (diff --git a/tests/test_memory_runtime_release_guard.py b/tests/test_memory_runtime_release_guard.pyindex 7aeec4968..947635b2c 100644--- a/tests/test_memory_runtime_release_guard.py+++ b/tests/test_memory_runtime_release_guard.py@@ -4,6 +4,8 @@ import gzipimport hashlibimport ioimport json+import subprocess+import sysimport tarfilefrom pathlib import Path@@ -12,6 +14,8 @@ import pytestfrom scripts import memory_runtime_release_guard as guardfrom scripts.build_memory_runtime import LOCK_SHA256 as RUNTIME_LOCK_SHA256+ROOT = Path(__file__).resolve().parents[1]+def test_guard_platform_contract_keeps_no_follow_capable_shipped_targets_enabled() -> None:assert guard.EXPECTED_PLATFORMS == frozenset({"darwin-arm64", "linux-arm64", "linux-x64"})@@ -77,6 +81,68 @@ def _manifest(return manifest, remote[email protected]("schema_version", [True, 1.0])+def test_guard_policy_requires_integer_schema_version(+ tmp_path: Path,+ schema_version: object,+) -> None:+ manifest, _ = _manifest(tmp_path)+ payload = json.loads(manifest.read_bytes())+ payload["schema_version"] = schema_version+ manifest.write_text(json.dumps(payload), encoding="utf-8")++ with pytest.raises(guard.ManifestPolicyError, match="schema_version"):+ guard.load_release_spec(manifest)+++def test_existing_guard_commands_remain_stdlib_only(tmp_path: Path) -> None:+ manifest, _ = _manifest(tmp_path)+ script = ROOT / "scripts/memory_runtime_release_guard.py"++ result = subprocess.run(+ [+ sys._base_executable,+ "-S",+ str(script),+ "--manifest",+ str(manifest),+ "check-policy",+ ],+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0, result.stderr+++def test_retired_gate5_verifier_symbols_have_no_production_or_workflow_callers() -> None:+ retired_symbols = (+ "Package" + "Metadata",+ "PackageRelease" + "Policy",+ "Requirement" + "Classification",+ "load_package_release_" + "policy",+ "classify_" + "requirement",+ "inspect_" + "wheel",+ "verify_static_" + "transition",+ "verify_wheel_" + "transition",+ )+ sources = [+ *sorted((ROOT / "scripts").rglob("*.py")),+ *sorted((ROOT / ".github/workflows").glob("*.yml")),+ *sorted((ROOT / ".github/workflows").glob("*.yaml")),+ ]++ references = {+ symbol: path.relative_to(ROOT).as_posix()+ for path in sources+ for symbol in retired_symbols+ if symbol in path.read_text(encoding="utf-8")+ }++ assert references == {}++@pytest.mark.parametrize("everos_version", sorted(guard.PUBLISHED_RUNTIME_PROVENANCE))def test_guard_accepts_every_published_runtime_provenance(tmp_path: Path,@@ -150,6 +216,36 @@ def _fake_download(remote: dict[str, bytes]):return download+def test_current_workflow_guard_command_shapes_execute(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ manifest, remote = _manifest(tmp_path)+ asset_dir = tmp_path / "assets"+ asset_dir.mkdir()+ for url, payload in remote.items():+ (asset_dir / url.rsplit("/", 1)[-1]).write_bytes(payload)+ monkeypatch.setattr(guard, "_download", _fake_download(remote))++ command_lines = (+ ["--manifest", str(manifest), "check-policy"],+ ["--manifest", str(manifest), "verify", "--asset-dir", str(asset_dir)],+ [+ "--manifest",+ str(manifest),+ "fetch",+ "--output-dir",+ str(tmp_path / "fetched"),+ ],+ )++ for argv in command_lines:+ assert guard.main(argv) == 0+ result = json.loads(capsys.readouterr().out)+ assert result == {"ok": True, "release_tag": "v3.1.0", "asset_count": 4}++def test_fetch_and_verify_exact_memory_runtime_release(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,@@ -273,3 +369,49 @@ def test_guard_workflow_reports_and_verifies_supported_published_manifests() ->assert "Excluded Memory Runtime manifests" in resolutionassert "fromJSON(needs.resolve_manifests.outputs.manifests)" in workflowassert "matrix.manifest.release_tag" in workflow+++def _guard_workflow() -> str:+ return (ROOT / ".github/workflows/memory-runtime-release-guard.yml").read_text(encoding="utf-8")+++def test_guard_workflow_prefers_memory_distribution_for_split_releases() -> None:+ workflow = _guard_workflow()+ memory_selection = '[.tag_name, "avibe-memory", "avibe_memory-*.whl"] | @tsv'+ legacy_selection = '[.tag_name, "avibe-os", "avibe_os-*.whl"] | @tsv'++ assert memory_selection in workflow+ assert legacy_selection in workflow+ assert workflow.index(memory_selection) < workflow.index(legacy_selection)+++def test_guard_workflow_keeps_legacy_core_only_releases_guarded() -> None:+ workflow = _guard_workflow()++ assert 'elif any(.assets[]?; (.name | startswith("avibe_os-"))' in workflow+ assert '[.tag_name, "avibe-os", "avibe_os-*.whl"] | @tsv' in workflow+ assert 'if [ "$manifest_owner" = "avibe-os" ]; then' in workflow+++def test_guard_workflow_never_falls_back_from_an_invalid_memory_owner() -> None:+ workflow = _guard_workflow()+ resolution = workflow.split("- name: Resolve every published Memory Runtime manifest", 1)[1]+ resolution = resolution.split(" guard:", 1)[0]++ assert resolution.count("gh release download") == 1+ assert '--pattern "$wheel_pattern"' in resolution+ assert "Memory wheel exists, it is authoritative and must not fall back." in resolution+ assert '$manifest_owner wheel does not contain a valid self-pinned published manifest' in resolution+++def test_guard_workflow_verification_consumes_recorded_manifest_owner() -> None:+ workflow = (ROOT / ".github/workflows/memory-runtime-release-guard.yml").read_text(encoding="utf-8")+ verification = workflow.split("- name: Resolve selected published Memory Runtime manifest", 1)[1]+ verification = verification.split("- name: Fetch and verify published assets", 1)[0]++ assert "manifest_owner: $manifest_owner" in workflow+ assert "wheel_pattern: $wheel_pattern" in workflow+ assert "MANIFEST_OWNER: ${{ matrix.manifest.manifest_owner }}" in verification+ assert "WHEEL_PATTERN: ${{ matrix.manifest.wheel_pattern }}" in verification+ assert '--pattern "$WHEEL_PATTERN"' in verification+ assert 'glob(os.environ["WHEEL_PATTERN"])' in verificationdiff --git a/tests/test_memory_sidecar.py b/tests/test_memory_sidecar.pyindex 6b080de23..a5184fddc 100644--- a/tests/test_memory_sidecar.py+++ b/tests/test_memory_sidecar.py@@ -9,10 +9,10 @@ from types import SimpleNamespaceimport pytest-from core.memory import everos-from core.memory.everos import MULTIMODAL_EXPLICIT_ENV-from core.memory import sidecar-from core.memory.sidecar import (+from avibe_memory import everos+from avibe_memory.everos import MULTIMODAL_EXPLICIT_ENV+from avibe_memory import sidecar+from avibe_memory.sidecar import (_processing_healthy_from_child_environment,_request_rejection,)diff --git a/tests/test_memory_slice3.py b/tests/test_memory_slice3.pyindex de1100d22..ac45eb134 100644--- a/tests/test_memory_slice3.py+++ b/tests/test_memory_slice3.py@@ -17,8 +17,7 @@ import pytestfrom config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfigfrom core.controller import Controller-from core.handlers.message_handler import MessageHandler-from core.memory import (+from avibe_memory import (CaptureAccepted,CaptureAttachment,CaptureDuplicate,@@ -26,21 +25,27 @@ from core.memory import (CaptureSkipped,MemoryModule,)-from core.memory.admission import InboundTurnFacts-from core.memory.everos import FakeMemoryProvider-from core.memory.store import MemoryStore+from avibe_memory.admission import InboundTurnFacts+from avibe_memory.everos import FakeMemoryProvider+from avibe_memory.store import MemoryStore+from core.memory_adapter import SessionArchivedfrom modules.im.base import FileAttachment, MessageContextfrom modules.im.message_facts import (- is_ordinary_discord_attachment,- is_ordinary_discord_text,- is_ordinary_feishu_attachment,- is_ordinary_feishu_text,- is_ordinary_slack_attachment,- is_ordinary_slack_text,- is_ordinary_telegram_attachment,- is_ordinary_telegram_text,- is_ordinary_wechat_attachment,- is_ordinary_wechat_text,+ discord_message_kind,+ feishu_message_kind,+ is_original_human_discord_attachment,+ is_original_human_discord_text,+ is_original_human_feishu_attachment,+ is_original_human_feishu_text,+ is_original_human_slack_attachment,+ is_original_human_slack_text,+ is_original_human_telegram_attachment,+ is_original_human_telegram_text,+ is_original_human_wechat_attachment,+ is_original_human_wechat_text,+ slack_message_kind,+ telegram_message_kind,+ wechat_message_kind,)@@ -73,7 +78,6 @@ class _Runtime:def __init__(self, module) -> None:self.module = moduleself.available = True- self.retired = Falseself.attachment_status = "ready"self.attachment_generation: int | None = 1self.barrier_offers = 0@@ -84,10 +88,6 @@ class _Runtime:suffix = "1" if user_key.endswith("user-1") else "2"return f"u-{suffix * 32}"- def project_for_workdir(self, workdir: str) -> str:- assert workdir == "/tmp/project"- return PROJECT-async def attachment_capture_status(self) -> str:return self.attachment_status@@ -130,6 +130,15 @@ class _CaptureModule:)+class _ArchiveAdapter:+ def __init__(self, runtime: _Runtime) -> None:+ self.runtime = runtime++ def offer(self, event: object) -> None:+ if isinstance(event, SessionArchived):+ self.runtime.offer_barrier(event.session_id)++def _controller(*, user=None):user = user or SimpleNamespace(enabled=True, is_admin=False)controller = Controller.__new__(Controller)@@ -151,6 +160,7 @@ def _controller(*, user=None):}controller.memory_module = _CaptureModule()controller.memory_runtime = _Runtime(controller.memory_module)+ controller.memory_adapter = _ArchiveAdapter(controller.memory_runtime)controller.get_cwd = lambda _context: "/tmp/project"return controller@@ -163,762 +173,11 @@ def _context(platform: str, *, user_id: str = "user-1", ordinary=True, **payloadmessage_id="native-1",platform_specific={"platform": platform, "is_dm": True, **payload},files=[],- is_ordinary_text=ordinary,- )---def test_message_handler_retains_memory_capture_task_until_completion() -> None:- handler = MessageHandler.__new__(MessageHandler)- handler._memory_capture_tasks = set()-- async def run() -> None:- release = asyncio.Event()- task = asyncio.create_task(release.wait())- reference = weakref.ref(task)- handler._track_memory_capture_task(task)- del task- gc.collect()-- assert reference() is not None- assert len(handler._memory_capture_tasks) == 1-- release.set()- await reference()- await asyncio.sleep(0)- assert handler._memory_capture_tasks == set()-- asyncio.run(run())---def test_message_handler_cancels_and_joins_memory_capture_tasks() -> None:- handler = MessageHandler.__new__(MessageHandler)- handler._memory_capture_tasks = set()- released = Mock()-- async def run() -> None:- started = asyncio.Event()-- async def capture() -> None:- started.set()- await asyncio.Event().wait()-- task = asyncio.create_task(capture())- handler._track_memory_capture_task(task, attachment_lease=released)- await started.wait()-- await handler.cancel_memory_capture_tasks()-- assert task.cancelled()- assert handler._memory_capture_tasks == set()- released.release.assert_called_once_with()-- asyncio.run(run())--[email protected]("platform", ["slack", "discord", "telegram", "feishu", "wechat"])-def test_capture_admits_every_enabled_bound_dm_user(platform: str) -> None:- controller = _controller(user=SimpleNamespace(enabled=True, is_admin=False))-- assert controller.memory_capture_admitted(_context(platform)) is True- assert controller.memory_capture_admitted(_context(platform, is_dm=False)) is False--[email protected]("status", ["ready", "unavailable"])-def test_slack_memory_lease_retention_is_local_and_ignores_runtime_health(- status: str,-) -> None:- """Scenarios: MEMORY-IM-ATTACH-001, MEMORY-IM-ATTACH-003."""-- controller = _controller()- controller.memory_runtime.attachment_status = status- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True-- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )-- assert reservation is not None- assert reservation.config_generation == 1--[email protected]("generation", [None, True, -1, "1"])-def test_slack_memory_reservation_normalizes_invalid_multimodal_generation(- generation: object,-) -> None:- """Scenario: MEMORY-IM-ATTACH-003."""-- controller = _controller()- controller.memory_runtime.attachment_generation = generation- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True-- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )-- assert reservation is not None- assert reservation.config_generation is None---def test_attachment_capacity_is_reserved_before_session_or_lease_work() -> None:- controller = _controller()- reserve_admission = Mock()- controller.memory_module.reserve_capture_capacity = lambda: "full"- controller.memory_module.reserve_capture_admission = reserve_admission- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True-- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )-- assert reservation is not None- assert reservation.capacity_full is True- reserve_admission.assert_not_called()- reservation.release()--[email protected]("outcome", ["unavailable", "disabled"])-def test_capture_capacity_terminal_outcomes_are_propagated(outcome: str) -> None:- controller = _controller()- controller.memory_module.reserve_capture_capacity = lambda: outcome-- reservation = controller.reserve_memory_capture_capacity(- _context("slack"),- "remember this",- "stable-session",- )-- assert reservation is not None- assert reservation.capacity_outcome == outcome- assert reservation.capacity_blocked is True- reservation.release()---def test_attachment_reservation_failure_preserves_caption_as_text_only() -> None:- """Scenario: MEMORY-IM-ATTACH-004."""-- controller = _controller()- controller.memory_module.reserve_capture_admission = Mock(- side_effect=RuntimeError("reservation unavailable")- )- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True-- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is None-- asyncio.run(- controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_reservation=reservation,- )- )-- assert len(controller.memory_module.accepted) == 1- request = controller.memory_module.accepted[0]- assert request.text == "keep the caption"- assert request.attachments == ()---def test_retained_lease_failure_preserves_reserved_caption_as_text_only() -> None:- """Scenario: MEMORY-IM-ATTACH-004."""-- controller = _controller()- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None-- asyncio.run(- controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_reservation=reservation,- attachment_text_only=True,- )+ is_original_human_text=ordinary,)- assert len(controller.memory_module.accepted) == 1- request = controller.memory_module.accepted[0]- assert request.text == "keep the caption"- assert request.attachments == ()---def test_slack_without_multimodal_opt_in_skips_live_health_read() -> None:- """Scenario: MEMORY-IM-ATTACH-003."""-- async def run() -> None:- controller = _controller()- store = MemoryStore()- provider = FakeMemoryProvider()- module = MemoryModule(store, provider, enabled=True)- controller.memory_module = module- controller.memory_runtime = _Runtime(module)- controller.memory_runtime.attachment_generation = None- health_reads = 0-- async def attachment_capture_status() -> str:- nonlocal health_reads- health_reads += 1- await asyncio.Event().wait()- return "ready"-- controller.memory_runtime.attachment_capture_status = attachment_capture_status- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None- assert reservation.config_generation is None-- await asyncio.wait_for(- controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_reservation=reservation,- ),- timeout=1.0,- )-- assert health_reads == 0- await module.wait_writer_idle_for_tests()- assert len(provider.captures) == 1- assert provider.captures[0].text == "keep the caption"- assert provider.captures[0].attachments == ()-- reset_ran = False-- async def reset() -> None:- nonlocal reset_ran- reset_ran = True-- module.offer_barrier("stable-session")- await asyncio.wait_for(reset(), timeout=1.5)- assert reset_ran is True- await module.close_writer()-- asyncio.run(run())--def test_configured_attachment_capture_skips_live_health_read(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Scenario: MEMORY-IM-ATTACH-001."""-- async def run() -> None:- controller = _controller()- health_reads = 0-- async def attachment_capture_status() -> str:- nonlocal health_reads- health_reads += 1- await asyncio.Event().wait()- return "ready"-- controller.memory_runtime.attachment_capture_status = attachment_capture_status- attachment = CaptureAttachment(- kind="pdf",- name="receipt.pdf",- uri="file:///leased/receipt.pdf",- ext="pdf",- )- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: SimpleNamespace(attachments=(attachment,), skipped=()),- )- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None- assert reservation.config_generation == 1-- await asyncio.wait_for(- controller.capture_user_memory(- context,- "remember this",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- ),- timeout=1.0,- )-- assert health_reads == 0- assert len(controller.memory_module.accepted) == 1- assert controller.memory_module.accepted[0].attachments == (attachment,)-- asyncio.run(run())---def test_configured_attachment_capture_does_not_block_session_reset(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Scenario: MEMORY-IM-ATTACH-003."""-- async def run() -> None:- controller = _controller()- store = MemoryStore()- module = MemoryModule(store, FakeMemoryProvider(), enabled=True)- controller.memory_module = module- controller.memory_runtime = _Runtime(module)- health_reads = 0-- async def attachment_capture_status() -> str:- nonlocal health_reads- health_reads += 1- await asyncio.Event().wait()- return "ready"-- controller.memory_runtime.attachment_capture_status = attachment_capture_status- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: SimpleNamespace(attachments=(), skipped=()),- )- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None- capture = asyncio.create_task(- controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- )- )- reset_ran = False-- async def reset() -> None:- nonlocal reset_ran- reset_ran = True-- module.offer_barrier("stable-session")- await asyncio.wait_for(reset(), timeout=0.75)- await asyncio.wait_for(capture, timeout=1.0)-- assert reset_ran is True- assert health_reads == 0-- asyncio.run(run())---def test_attachment_selection_runs_off_event_loop(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Scenario: MEMORY-IM-ATTACH-001."""-- async def run() -> None:- controller = _controller()- event_loop_thread = threading.get_ident()- binding_threads: list[int] = []- settings_store = controller.platform_settings_managers["slack"].get_store()- original_maybe_reload = settings_store.maybe_reload-- def observe_settings_access() -> None:- binding_threads.append(threading.get_ident())- original_maybe_reload()-- monkeypatch.setattr(settings_store, "maybe_reload", observe_settings_access)- attachment = CaptureAttachment(- kind="pdf",- name="receipt.pdf",- uri="file:///leased/receipt.pdf",- ext="pdf",- )- selector_threads: list[int] = []- release_selection = threading.Event()- released_by_event_loop: list[bool] = []-- def select_attachments(_lease):- selector_threads.append(threading.get_ident())- released_by_event_loop.append(release_selection.wait(timeout=1.0))- return SimpleNamespace(attachments=(attachment,), skipped=())-- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- select_attachments,- )- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None-- asyncio.get_running_loop().call_later(0.05, release_selection.set)- await asyncio.wait_for(- controller.capture_user_memory(- context,- "remember this",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- ),- timeout=2.0,- )-- assert binding_threads and set(binding_threads) == {event_loop_thread}- assert selector_threads and selector_threads[0] != event_loop_thread- assert released_by_event_loop == [True]-- asyncio.run(run())---def test_attachment_capture_fails_closed_when_config_generation_changes(- monkeypatch: pytest.MonkeyPatch,- caplog: pytest.LogCaptureFixture,-) -> None:- """Scenario: MEMORY-IM-ATTACH-003."""-- caplog.set_level("INFO", logger="core.memory.admission")-- async def run() -> None:- controller = _controller()- attachment = CaptureAttachment(- kind="pdf",- name="receipt.pdf",- uri="file:///leased/receipt.pdf",- ext="pdf",- )- def select_attachments(_lease):- controller.memory_runtime.attachment_generation = 2- return SimpleNamespace(attachments=(attachment,), skipped=())-- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- select_attachments,- )- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None-- await controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- )-- assert len(controller.memory_module.accepted) == 1- request = controller.memory_module.accepted[0]- assert request.text == "keep the caption"- assert request.attachments == ()- assert request.attachment_config_generation is None-- asyncio.run(run())- records = [- record- for record in caplog.records- if record.message.startswith("memory_attachment_capture ")- ]- assert len(records) == 1- assert "platform=slack total=1 captured=0 dropped=1" in records[0].getMessage()---def test_downstream_capture_unavailability_does_not_change_ingress_eligibility(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Scenario: MEMORY-IM-ATTACH-003."""-- async def run() -> None:- controller = _controller()- attachment = CaptureAttachment(- kind="pdf",- name="receipt.pdf",- uri="file:///leased/receipt.pdf",- ext="pdf",- )- monkeypatch.setattr(- "core.memory.admission.select_memory_attachments",- lambda _lease: SimpleNamespace(attachments=(attachment,), skipped=()),- )- captured_requests: list[CaptureRequest] = []-- async def unavailable_capture(request, **_options):- captured_requests.append(request)- return CaptureSkipped(reason="memory_operation_in_progress")-- controller.memory_module.capture = unavailable_capture- controller.memory_runtime.attachment_status = "unavailable"- context = _context("slack", ordinary=False)- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- url="https://files.slack.test/private",- )- ]- context.is_ordinary_attachment = True- reservation = controller.reserve_memory_attachment_capture(- context,- "stable-session",- )- assert reservation is not None-- await controller.capture_user_memory(- context,- "keep the caption",- "stable-session",- attachment_lease=object(),- attachment_reservation=reservation,- )-- assert len(captured_requests) == 1- assert captured_requests[0].attachments == (attachment,)-- asyncio.run(run())--- "context,text,enabled",- [- (_context("slack", is_dm=False), "normal", True),- (_context("slack", ordinary=False), "normal", True),- (_context("slack", user_id=""), "normal", True),- (_context("avibe", user_id="workbench"), "normal", True),- (_context("slack"), "normal", False),- ],-)-def test_capture_skips_ineligible_human_turns(context, text, enabled) -> None:- controller = _controller()- controller.config.memory.enabled = enabled-- asyncio.run(controller.capture_user_memory(context, text, "stable-session"))-- assert controller.memory_module.accepted == []---def test_capture_stamps_user_principal_provenance_and_native_dedup_key() -> None:- """MEMORY-SEARCH-015: capture identity stays caller-scoped and deduplicated."""-- controller = _controller()- context = _context("telegram")- other_user = _context("telegram", user_id="user-2")-- asyncio.run(controller.capture_user_memory(context, "/memory status", "stable-session"))- asyncio.run(controller.capture_user_memory(context, "/memory status", "stable-session"))- asyncio.run(controller.capture_user_memory(other_user, "/memory status", "stable-session"))-- assert len(controller.memory_module.accepted) == 2- request = controller.memory_module.accepted[0]- assert request.source_message_id == f"im:telegram:u-{'1' * 32}:native-1"- assert request.session_id == "stable-session"- assert request.principal_id == "u-" + ("1" * 32)- assert request.project_id == PROJECT- assert request.provenance == "user_input"- assert request.text == "/memory status"- assert controller.memory_module.accepted[1].source_message_id == f"im:telegram:u-{'2' * 32}:native-1"---def test_capture_user_memory_rejects_fresh_runtime_after_reset_gate() -> None:- controller = _controller()- gate = controller._memory_replacement_lock()-- async def run() -> None:- await gate.acquire()- capture = controller.capture_user_memory(- _context("telegram"),- "remember this",- "stable-session",- )-- fresh_module = _CaptureModule()- controller.memory_runtime = _Runtime(fresh_module)- queued = asyncio.create_task(capture)- await asyncio.sleep(0)- gate.release()-- await queued- assert fresh_module.accepted == []-- asyncio.run(run())---def test_memory_session_lifecycle_reuses_capture_scope_and_raw_anchor() -> None:- controller = _controller()- operation_calls = []-- async def reset_session() -> str:- operation_calls.append("reset")- return "reset-complete"-- result = asyncio.run(- controller.run_memory_session_lifecycle(- _context("wechat"),- "wechat_dm-1",- reset_session,- deadline_seconds=4.0,- )- )-- assert result == "reset-complete"- assert operation_calls == ["reset"]- assert controller.memory_runtime.barrier_sessions == ["wechat_dm-1"]---def test_memory_session_lifecycle_does_not_reset_without_a_fence() -> None:- controller = _controller()- controller.memory_runtime.barrier_error = RuntimeError("fence unavailable")- operation_calls = []-- async def reset_session() -> str:- operation_calls.append("reset")- return "reset-complete"-- result = asyncio.run(- controller.run_memory_session_lifecycle(- _context("slack"),- "slack_dm-1",- reset_session,- )- )-- assert result == "reset-complete"- assert operation_calls == ["reset"]---def test_memory_session_lifecycle_resets_without_guessing_an_ineligible_scope() -> None:- controller = _controller(user=SimpleNamespace(enabled=False, is_admin=False))- operation_calls = []-- async def reset_session() -> str:- operation_calls.append("reset")- return "reset-complete"-- result = asyncio.run(- controller.run_memory_session_lifecycle(- _context("slack"),- "slack_dm-1",- reset_session,- )- )-- assert result == "reset-complete"- assert operation_calls == ["reset"]- assert controller.memory_runtime.barrier_sessions == []---def test_memory_session_lifecycle_does_not_repeat_failed_reset() -> None:- controller = _controller()- operation_calls = []-- async def reset_session() -> None:- operation_calls.append("reset")- raise RuntimeError("reset failed")-- with pytest.raises(RuntimeError, match="reset failed"):- asyncio.run(- controller.run_memory_session_lifecycle(- _context("telegram"),- "telegram_dm-1",- reset_session,- )- )-- assert operation_calls == ["reset"]---def test_archive_memory_cli_session_commits_without_waiting_on_memory(+def test_archive_session_commits_then_offers_session_archived(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:@@ -946,17 +205,18 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(principal_id = "u-" + ("2" * 32)barrier_started_after_archive: list[bool] = []- class LifecycleRuntime(_Runtime):- def offer_barrier(self, raw_session_id: str) -> str:+ class RecordingAdapter:+ def offer(self, event: object) -> None:with engine.connect() as conn:barrier_started_after_archive.append(workbench_sessions_service.get_session(conn, session_id)["status"]== "archived")- return super().offer_barrier(raw_session_id)+ assert type(event).__name__ == "SessionArchived"+ assert getattr(event, "session_id") == session_idcontroller = _controller()- controller.memory_runtime = LifecycleRuntime(controller.memory_module)+ controller.memory_adapter = RecordingAdapter()from core.session_turns import SessionTurnManagercontroller.session_turns = SessionTurnManager()@@ -969,11 +229,10 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(user_id="workbench-user",message_id="message-1",session_id=session_id,- memory_enabled=True,)}async def run() -> None:- result = await controller.archive_memory_cli_session(+ result = await controller.archive_session(session_id,deadline_seconds=2.0,)@@ -982,10 +241,6 @@ def test_archive_memory_cli_session_commits_without_waiting_on_memory(assert workbench_sessions_service.get_session(conn, session_id)["status"] == "archived"await asyncio.sleep(0)assert barrier_started_after_archive == [True]- assert controller.memory_runtime.barrier_offers == 1- assert controller.memory_runtime.barrier_sessions == [session_id]- assert session_id not in controller._memory_scopes_by_session- assert session_id not in controller._memory_cli_facts_by_sessiontry:asyncio.run(run())@@ -1004,14 +259,14 @@ def test_archive_memory_barrier_failure_still_releases_authorization() -> None:}controller._memory_cli_facts_by_session = {session_id: object()}- controller._offer_best_effort_archive_memory_barrier(session_id)+ controller._offer_best_effort_session_archived(session_id)assert controller.memory_runtime.barrier_offers == 1assert session_id not in controller._memory_scopes_by_sessionassert session_id not in controller._memory_cli_facts_by_session-def test_archive_memory_cli_session_offers_barrier_when_commit_is_cancelled(+def test_archive_session_offers_barrier_when_commit_is_cancelled(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:@@ -1056,13 +311,14 @@ def test_archive_memory_cli_session_offers_barrier_when_commit_is_cancelled(controller = _controller()controller.memory_runtime = LifecycleRuntime(controller.memory_module)+ controller.memory_adapter = _ArchiveAdapter(controller.memory_runtime)controller._memory_scopes_by_session = {session_id: ("u-" + ("2" * 32), PROJECT),}controller._memory_cli_facts_by_session = {}async def run() -> None:- archive = asyncio.create_task(controller.archive_memory_cli_session(session_id))+ archive = asyncio.create_task(controller.archive_session(session_id))deadline = asyncio.get_running_loop().time() + 2.0while not commit_entered.is_set():if asyncio.get_running_loop().time() >= deadline:@@ -1086,7 +342,7 @@ def test_archive_memory_cli_session_offers_barrier_when_commit_is_cancelled(@pytest.mark.parametrize("state", ["missing", "reserved", "archived"])-def test_archive_memory_cli_session_preflight_skips_memory_lifecycle(+def test_archive_session_preflight_skips_lifecycle_event(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,state: str,@@ -1122,7 +378,7 @@ def test_archive_memory_cli_session_preflight_skips_memory_lifecycle(controller._memory_cli_facts_by_session = {}async def archive() -> dict[str, object]:- return await controller.archive_memory_cli_session(session_id)+ return await controller.archive_session(session_id)try:if state == "missing":@@ -1140,7 +396,7 @@ def test_archive_memory_cli_session_preflight_skips_memory_lifecycle(assert controller.memory_runtime.barrier_offers == 0-def test_archive_memory_cli_session_commits_when_barrier_offer_fails(+def test_archive_session_commits_when_barrier_offer_fails(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:@@ -1169,7 +425,7 @@ def test_archive_memory_cli_session_commits_when_barrier_offer_fails(controller._memory_cli_facts_by_session = {}async def run() -> dict[str, object]:- result = await controller.archive_memory_cli_session(session_id)+ result = await controller.archive_session(session_id)await asyncio.sleep(0)return result@@ -1213,52 +469,6 @@ def test_retired_memory_delivery_symbols_have_no_product_callers() -> None:assert offenders == []-def test_workbench_capture_requires_resolved_identity_and_uses_row_id() -> None:- controller = _controller()- context = _context("avibe", user_id="local")-- asyncio.run(controller.capture_user_memory(context, "ordinary text", "stable-session"))-- request = controller.memory_module.accepted[0]- assert request.source_message_id == f"workbench:u-{'2' * 32}:native-1"- assert request.principal_id == "u-" + ("2" * 32)- assert request.project_id == PROJECT---def test_workbench_capture_converts_owned_attachment_without_text(monkeypatch, tmp_path: Path) -> None:- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- attachment_path = tmp_path / "attachments" / "avibe" / "receipt.pdf"- attachment_path.parent.mkdir(parents=True)- attachment_path.write_bytes(b"pdf")- controller = _controller()- context = _context("avibe", user_id="local")- context.files = [- FileAttachment(- name="receipt.pdf",- mimetype="application/pdf",- local_path=str(attachment_path),- )- ]-- asyncio.run(controller.capture_user_memory(context, "", "stable-session"))-- request = controller.memory_module.accepted[0]- assert request.text == ""- assert request.attachments[0].kind == "pdf"- assert request.attachments[0].name == "receipt.pdf"- assert request.attachments[0].uri == attachment_path.as_uri()---def test_im_attachments_remain_out_of_scope() -> None:- controller = _controller()- context = _context("slack")- context.files = [object()]-- asyncio.run(controller.capture_user_memory(context, "ordinary text", "stable-session"))-- assert controller.memory_module.accepted == []--def test_im_adapters_normalize_native_ordinary_text_facts() -> None:discord_message = SimpleNamespace(author=SimpleNamespace(bot=False),@@ -1269,24 +479,58 @@ def test_im_adapters_normalize_native_ordinary_text_facts() -> None:message_snapshots=(),is_system=lambda: False,)- assert is_ordinary_discord_text(discord_message, None) is True+ assert is_original_human_discord_text(discord_message, None) is Truediscord_message.flags.forwarded = True- assert is_ordinary_discord_text(discord_message, None) is False+ assert is_original_human_discord_text(discord_message, None) is False- assert is_ordinary_slack_text({"text": "hello"}, None) is True- assert is_ordinary_slack_text({"text": "hello", "subtype": "message_changed"}, None) is False+ assert is_original_human_slack_text({"text": "hello"}, None) is True+ assert is_original_human_slack_text({"text": "hello", "subtype": "message_changed"}, None) is False- assert is_ordinary_telegram_text({"from": {"is_bot": False}, "text": "hello"}, []) is True- assert is_ordinary_telegram_text({"from": {"is_bot": False}, "forward_origin": {"type": "user"}}, []) is False+ assert is_original_human_telegram_text({"from": {"is_bot": False}, "text": "hello"}, []) is True+ assert is_original_human_telegram_text({"from": {"is_bot": False}, "forward_origin": {"type": "user"}}, []) is Falsefeishu_event = {"sender": {"sender_type": "user"}, "message": {"message_type": "text"}}- assert is_ordinary_feishu_text(feishu_event, None, shared_text=None) is True+ assert is_original_human_feishu_text(feishu_event, None, shared_text=None) is Truefeishu_event["message"]["message_type"] = "post"- assert is_ordinary_feishu_text(feishu_event, None, shared_text=None) is False+ assert is_original_human_feishu_text(feishu_event, None, shared_text=None) is False- assert is_ordinary_wechat_text({"item_list": [{"type": "TEXT"}]}, None) is True- assert is_ordinary_wechat_text({"item_list": [{"type": 1}, {"type": 2}]}, None) is False- assert is_ordinary_wechat_text({"item_list": [{"type": 1, "ref_msg": {"title": "quoted"}}]}, None) is False+ assert is_original_human_wechat_text({"item_list": [{"type": "TEXT"}]}, None) is True+ assert is_original_human_wechat_text({"item_list": [{"type": 1}, {"type": 2}]}, None) is False+ assert is_original_human_wechat_text({"item_list": [{"type": 1, "ref_msg": {"title": "quoted"}}]}, None) is False+++def test_im_adapters_publish_concrete_native_message_kinds() -> None:+ discord_message = SimpleNamespace(+ author=SimpleNamespace(bot=False),+ edited_at=None,+ attachments=[],+ embeds=[],+ flags=SimpleNamespace(forwarded=True),+ message_snapshots=(),+ is_system=lambda: False,+ )+ assert discord_message_kind(discord_message, None) == "forwarded"+ assert slack_message_kind(+ {"text": "edited", "subtype": "message_changed"},+ None,+ ) == "edited"+ assert telegram_message_kind(+ {"from": {"is_bot": False}, "is_system": True},+ [],+ ) == "system"+ assert feishu_message_kind(+ {+ "sender": {"sender_type": "user"},+ "message": {"message_type": "text", "forwarded": True},+ },+ {},+ None,+ shared_text="forwarded body",+ ) == "forwarded"+ assert wechat_message_kind(+ {"item_list": [{"type": 1, "ref_msg": {"title": "quoted"}}]},+ None,+ ) == "forwarded"def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:@@ -1310,7 +554,7 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:message_snapshots=(),is_system=lambda: False,)- assert is_ordinary_discord_attachment(discord_message, [discord_file]) is True+ assert is_original_human_discord_attachment(discord_message, [discord_file]) is Truefor field, value in (("embeds", [object()]),("components", [object()]),@@ -1319,10 +563,10 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:("message_snapshots", [object()]),):setattr(discord_message, field, value)- assert is_ordinary_discord_attachment(discord_message, [discord_file]) is False+ assert is_original_human_discord_attachment(discord_message, [discord_file]) is Falsesetattr(discord_message, field, None)discord_message.author.bot = True- assert is_ordinary_discord_attachment(discord_message, [discord_file]) is False+ assert is_original_human_discord_attachment(discord_message, [discord_file]) is Falsetelegram_file = FileAttachment(name="telegram-file.bin",@@ -1340,20 +584,20 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:"media_group_id": "album-1",native_field: native_value,}- assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is True+ assert is_original_human_telegram_attachment(telegram_message, [telegram_file]) is Truefor rejected_field in ("video", "animation", "sticker"):telegram_message = {"from": {"id": 42, "is_bot": False},"document": {"file_id": "document"},rejected_field: {"file_id": "decorated"},}- assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is False+ assert is_original_human_telegram_attachment(telegram_message, [telegram_file]) is Falsetelegram_message = {"from": {"id": 42, "is_bot": False},"document": {"file_id": "document"},"forward_origin": {"type": "user"},}- assert is_ordinary_telegram_attachment(telegram_message, [telegram_file]) is False+ assert is_original_human_telegram_attachment(telegram_message, [telegram_file]) is Falsefeishu_file = FileAttachment(name="report.pdf",@@ -1365,7 +609,7 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:"message": {"message_type": "file"},}assert (- is_ordinary_feishu_attachment(+ is_original_human_feishu_attachment(feishu_event,{"file_key": "file-key", "file_name": "report.pdf"},[feishu_file],@@ -1374,7 +618,7 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:is True)assert (- is_ordinary_feishu_attachment(+ is_original_human_feishu_attachment(feishu_event,{"file_key": ""},[feishu_file],@@ -1384,7 +628,7 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:)feishu_event["message"]["message_type"] = "image"assert (- is_ordinary_feishu_attachment(+ is_original_human_feishu_attachment(feishu_event,{"image_key": "image-key"},[feishu_file],@@ -1394,7 +638,7 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:)feishu_event["message"]["message_type"] = "media"assert (- is_ordinary_feishu_attachment(+ is_original_human_feishu_attachment(feishu_event,{"file_key": "media-key"},[feishu_file],@@ -1421,9 +665,9 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:},],}- assert is_ordinary_wechat_attachment(wechat_message, wechat_files) is True+ assert is_original_human_wechat_attachment(wechat_message, wechat_files) is Truewechat_message["item_list"][0]["ref_msg"] = {"title": "forwarded"}- assert is_ordinary_wechat_attachment(wechat_message, wechat_files) is False+ assert is_original_human_wechat_attachment(wechat_message, wechat_files) is Falsefor item_type, media_field in ((2, "image_item"),(3, "voice_item"),@@ -1440,11 +684,11 @@ def test_im_adapters_normalize_native_ordinary_attachment_facts() -> None:}]}- assert is_ordinary_wechat_attachment(direct_message, wechat_files) is True+ assert is_original_human_wechat_attachment(direct_message, wechat_files) is Truedirect_message["item_list"][0][media_field]["media"]["encrypt_query_param"] = ""- assert is_ordinary_wechat_attachment(direct_message, wechat_files) is False+ assert is_original_human_wechat_attachment(direct_message, wechat_files) is Falsedef _slack_dm_event(**overrides) -> dict:@@ -1482,7 +726,7 @@ def _slack_dm_event(**overrides) -> dict:def test_slack_composer_rich_text_dm_is_ordinary_human_text() -> None:- assert is_ordinary_slack_text(_slack_dm_event(), None) is True+ assert is_original_human_slack_text(_slack_dm_event(), None) is True# Mentions, links, emoji, styled runs, lists, quotes, and code blocks are all# plain composer output for a human-typed DM.@@ -1526,7 +770,7 @@ def test_slack_composer_rich_text_dm_is_ordinary_human_text() -> None:}],)- assert is_ordinary_slack_text(decorated, None) is True+ assert is_original_human_slack_text(decorated, None) is Truedef test_slack_non_text_block_payloads_are_not_ordinary() -> None:@@ -1546,7 +790,7 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:}],)- assert is_ordinary_slack_text(upload, None) is False+ assert is_original_human_slack_text(upload, None) is Falseextracted_upload = [FileAttachment(name="screenshot.png",@@ -1554,7 +798,7 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:url="https://files.slack.com/files-pri/T04-F04/screenshot.png",)]- assert is_ordinary_slack_attachment(upload, extracted_upload) is True+ assert is_original_human_slack_attachment(upload, extracted_upload) is True# Forwarded / shared message: composer rich text PLUS a share attachment.forwarded = _slack_dm_event(@@ -1570,8 +814,8 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:}],)- assert is_ordinary_slack_text(forwarded, None) is False- assert is_ordinary_slack_attachment(forwarded, extracted_upload) is False+ assert is_original_human_slack_text(forwarded, None) is False+ assert is_original_human_slack_attachment(forwarded, extracted_upload) is False# App-authored layout blocks are not composer output, even without ``bot_id``.app_blocks = _slack_dm_event(@@ -1581,8 +825,8 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:{"type": "image", "image_url": "https://example.com/chart.png", "alt_text": "chart"},],)- assert is_ordinary_slack_text(app_blocks, None) is False- assert is_ordinary_slack_attachment(app_blocks, extracted_upload) is False+ assert is_original_human_slack_text(app_blocks, None) is False+ assert is_original_human_slack_attachment(app_blocks, extracted_upload) is False# An unrecognized node inside rich text fails closed.unknown_element = _slack_dm_event(@@ -1602,27 +846,27 @@ def test_slack_non_text_block_payloads_are_not_ordinary() -> None:}],)- assert is_ordinary_slack_text(unknown_element, None) is False+ assert is_original_human_slack_text(unknown_element, None) is False# Only an absent blocks value or a real empty list is the legacy plain-text# shape. Falsy values of any other type are malformed and fail closed.- assert is_ordinary_slack_text(_slack_dm_event(blocks=[]), None) is True+ assert is_original_human_slack_text(_slack_dm_event(blocks=[]), None) is Truefor malformed_blocks in ({}, "", 0, False):- assert is_ordinary_slack_text(_slack_dm_event(blocks=malformed_blocks), None) is False+ assert is_original_human_slack_text(_slack_dm_event(blocks=malformed_blocks), None) is False# Edits and bot/self events stay excluded regardless of block content.- assert is_ordinary_slack_text(_slack_dm_event(subtype="message_changed"), None) is False- assert is_ordinary_slack_text(_slack_dm_event(subtype="future_system_event"), None) is False+ assert is_original_human_slack_text(_slack_dm_event(subtype="message_changed"), None) is False+ assert is_original_human_slack_text(_slack_dm_event(subtype="future_system_event"), None) is Falseassert (- is_ordinary_slack_text(+ is_original_human_slack_text(_slack_dm_event(edited={"user": "U04ABCDEF", "ts": "1753420900.000000"}),None,)is False)- assert is_ordinary_slack_text(_slack_dm_event(bot_id="B04BOTID"), None) is False+ assert is_original_human_slack_text(_slack_dm_event(bot_id="B04BOTID"), None) is Falseassert (- is_ordinary_slack_text(+ is_original_human_slack_text(_slack_dm_event(),[FileAttachment(@@ -1690,11 +934,13 @@ def _reconcile_controller(current: MemoryConfig) -> Controller:def test_a_failed_memory_reconciliation_does_not_adopt_the_candidate_config() -> None:controller = _reconcile_controller(_memory_config())- result = asyncio.run(controller.reconcile_memory(_memory_config(enabled=False)))+ result = asyncio.run(+ controller.reconcile_memory(_memory_config(llm_model="replacement"))+ )assert result["ok"] is Falseassert controller.memory_runtime.calls == 1- assert controller.config.memory.enabled is True+ assert controller.config.memory.processing.llm.model == "chat"def test_controller_adopts_an_independent_settled_memory_snapshot() -> None:diff --git a/tests/test_memory_store.py b/tests/test_memory_store.pyindex 740dcd802..3eb6a0537 100644--- a/tests/test_memory_store.py+++ b/tests/test_memory_store.py@@ -7,8 +7,8 @@ import sqlite3import pytest-from core.memory.project_ids import MAX_NAMED_MEMORY_PROJECTS-from core.memory.store import (+from vibe.memory_project_ids import MAX_NAMED_MEMORY_PROJECTS+from avibe_memory.store import (MEMORY_STORE_SCHEMA_VERSION,MemoryStore,_provider_session_ref,@@ -47,7 +47,7 @@ def test_incomplete_v4_store_is_rejected_during_initialization(path = _store_path(tmp_path)path.parent.mkdir(parents=True)with sqlite3.connect(path) as conn:- conn.executescript(Path("core/memory/schema.sql").read_text(encoding="utf-8"))+ conn.executescript(Path("avibe_memory/schema.sql").read_text(encoding="utf-8"))conn.execute(f'ALTER TABLE "{table}" DROP COLUMN "{column}"')conn.execute(f"PRAGMA user_version = {MEMORY_STORE_SCHEMA_VERSION}")@@ -64,7 +64,7 @@ def test_v4_store_without_required_primary_key_is_rejected_during_initializationpath.parent.mkdir(parents=True)replacement = f"{table}_without_key"with sqlite3.connect(path) as conn:- conn.executescript(Path("core/memory/schema.sql").read_text(encoding="utf-8"))+ conn.executescript(Path("avibe_memory/schema.sql").read_text(encoding="utf-8"))conn.execute(f'CREATE TABLE "{replacement}" AS SELECT * FROM "{table}"')conn.execute(f'DROP TABLE "{table}"')conn.execute(f'ALTER TABLE "{replacement}" RENAME TO "{table}"')@@ -175,7 +175,7 @@ def test_released_v2_migration_discards_delivery_tables_and_derives_projects(tmppath = _store_path(tmp_path)path.parent.mkdir(parents=True)- schema = Path("core/memory/schema_v2.sql").read_text(encoding="utf-8")+ schema = Path("avibe_memory/schema_v2.sql").read_text(encoding="utf-8")with sqlite3.connect(path) as conn:conn.executescript(schema)conn.execute("PRAGMA user_version = 2")@@ -298,7 +298,7 @@ def test_unknown_released_store_shape_is_left_untouched((0, "tests/fixtures/memory_initial_foundation_v0.sql"),(0, "tests/fixtures/memory_foundation_v0.sql"),(1, "tests/fixtures/memory_foundation_v1.sql"),- (3, "core/memory/schema_v2.sql"),+ (3, "avibe_memory/schema_v2.sql"),],)def test_released_identity_shapes_migrate_without_provider_io(diff --git a/tests/test_memory_supervisor.py b/tests/test_memory_supervisor.pyindex 510ba5e54..9b4f2980c 100644--- a/tests/test_memory_supervisor.py+++ b/tests/test_memory_supervisor.py@@ -5,12 +5,12 @@ from collections import dequefrom pathlib import Pathimport sys-from core.memory.process import (+from avibe_memory.process import (EverOSProcessSettings,FakeEverOSProcess,FakeEverOSProcessFactory,)-from core.memory.supervisor import EverOSSupervisor+from avibe_memory.supervisor import EverOSSupervisordef _settings() -> EverOSProcessSettings:diff --git a/tests/test_memory_ui_access.py b/tests/test_memory_ui_access.pyindex 2a48203fb..3f704a9fe 100644--- a/tests/test_memory_ui_access.py+++ b/tests/test_memory_ui_access.py@@ -1,7 +1,7 @@import io-from core.memory import ui_access-from core.memory.ui_access import build_ui_read_proof, verify_ui_read_proof+from vibe import memory_ui_access as ui_access+from vibe.memory_ui_access import build_ui_read_proof, verify_ui_read_prooffrom vibe import runtimediff --git a/tests/test_memory_upgrade_packaged.py b/tests/test_memory_upgrade_packaged.pynew file mode 100644index 000000000..53ffb2e68--- /dev/null+++ b/tests/test_memory_upgrade_packaged.py@@ -0,0 +1,276 @@+from __future__ import annotations++import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest++from vibe.upgrade import build_upgrade_plan, execute_upgrade_plan+++ROOT = Path(__file__).resolve().parents[1]+++def _wheel(project: Path, version: str, wheelhouse: Path) -> None:+ env = {**os.environ, "SETUPTOOLS_SCM_PRETEND_VERSION": version}+ result = subprocess.run(+ [sys.executable, "-m", "pip", "wheel", str(project), "--no-deps", "--wheel-dir", str(wheelhouse)],+ cwd=ROOT,+ env=env,+ capture_output=True,+ text=True,+ check=False,+ timeout=600,+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def _build_release_wheels(version: str, wheelhouse: Path) -> None:+ _wheel(ROOT, version, wheelhouse)+ _wheel(ROOT / "packaging" / "avibe-memory", version, wheelhouse)+++def _python(environment: Path) -> Path:+ return environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")+++def _installed_versions(python: Path) -> dict[str, str]:+ result = subprocess.run(+ [+ str(python),+ "-c",+ "from importlib.metadata import distributions; print('\\n'.join(f'{d.metadata[\"Name\"]}=={d.version}' for d in distributions()))",+ ],+ capture_output=True,+ text=True,+ check=True,+ )+ values: dict[str, str] = {}+ for line in result.stdout.splitlines():+ if "==" in line:+ name, version = line.split("==", 1)+ values[name.lower()] = version+ return values+++def _venv(path: Path) -> Path:+ result = subprocess.run([sys.executable, "-m", "venv", str(path)], capture_output=True, text=True)+ assert result.returncode == 0, result.stdout + result.stderr+ return _python(path)++[email protected](scope="module")+def packaged_dependency_seed(tmp_path_factory: pytest.TempPathFactory) -> Path:+ seed_root = tmp_path_factory.mktemp("packaged-dependency-seed")+ source_wheelhouse = seed_root / "source"+ source_wheelhouse.mkdir()+ _build_release_wheels("3.0.14", source_wheelhouse)+ dependency_seed = seed_root / "dependencies"+ dependency_seed.mkdir()+ seed = subprocess.run(+ [+ sys.executable,+ "-m",+ "pip",+ "download",+ "--dest",+ str(dependency_seed),+ "setuptools",+ "wheel",+ str(next(source_wheelhouse.glob("avibe_os-3.0.14-*.whl"))),+ str(next(source_wheelhouse.glob("avibe_memory-3.0.14-*.whl"))),+ ],+ env={**os.environ, "PIP_FIND_LINKS": str(source_wheelhouse)},+ capture_output=True,+ text=True,+ check=False,+ timeout=600,+ )+ assert seed.returncode == 0, seed.stdout + seed.stderr+ return dependency_seed+++def _install_initial(python: Path, wheelhouse: Path, *, memory: bool, dependency_seed: Path) -> None:+ for artifact in dependency_seed.iterdir():+ if artifact.name.lower().startswith(("avibe_os-", "avibe_memory-")):+ continue+ shutil.copy2(artifact, wheelhouse / artifact.name)+ wheels = [next(wheelhouse.glob("avibe_os-3.0.14-*.whl"))]+ if memory:+ wheels.append(next(wheelhouse.glob("avibe_memory-3.0.14-*.whl")))+ env = {**os.environ, "PIP_NO_INDEX": "1", "PIP_FIND_LINKS": str(wheelhouse)}+ result = subprocess.run(+ [str(python), "-m", "pip", "install", *(str(wheel) for wheel in wheels)],+ env=env,+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def _plan_env(wheelhouse: Path) -> dict[str, str]:+ return {+ **os.environ,+ "PIP_NO_INDEX": "1",+ "PIP_FIND_LINKS": str(wheelhouse),+ }+++def test_memory_indep_021_packaged_core_only_status_blocks_optional_imports(+ tmp_path: Path,+ packaged_dependency_seed: Path,+) -> None:+ wheelhouse = tmp_path / "wheelhouse"+ wheelhouse.mkdir()+ _build_release_wheels("3.0.14", wheelhouse)+ python = _venv(tmp_path / "core-only-status-venv")+ _install_initial(+ python,+ wheelhouse,+ memory=False,+ dependency_seed=packaged_dependency_seed,+ )+ script = r'''+import importlib.abc+import json+import os+import sys++from config import paths+from config.v2_config import V2Config++config_path = paths.get_config_path()+config_path.parent.mkdir(parents=True, exist_ok=True)+V2Config.default().save(config_path)+if os.environ["MEMORY_CONFIG_CASE"] == "malformed":+ payload = json.loads(config_path.read_text(encoding="utf-8"))+ payload["memory"]["recovery_intent"] = "invalid"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++class BlockMemoryImplementation(importlib.abc.MetaPathFinder):+ def find_spec(self, fullname, path=None, target=None):+ if fullname == "avibe_memory" or fullname.startswith("avibe_memory."):+ raise AssertionError(f"optional implementation import: {fullname}")+ return None++sys.meta_path.insert(0, BlockMemoryImplementation())+from vibe import api++package, runtime = api._memory_dependencies_status(offline=True)+assert package["readiness"] == "not_required"+assert package["provider_count"] == 0+assert runtime["status"] == "not_required"+assert not any(+ name == "avibe_memory" or name.startswith("avibe_memory.")+ for name in sys.modules+)+'''+ for case in ("disabled", "malformed"):+ home = tmp_path / f"avibe-home-{case}"+ result = subprocess.run(+ [str(python), "-c", script],+ cwd=tmp_path,+ env={+ **os.environ,+ "AVIBE_HOME": str(home),+ "MEMORY_CONFIG_CASE": case,+ "PYTHONPATH": "",+ },+ capture_output=True,+ text=True,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+++def test_packaged_memory_shape_survives_synchronous_upgrade(+ tmp_path: Path,+ packaged_dependency_seed: Path,+) -> None:+ """Run the public planner and executor across a paired package upgrade."""++ if not (ROOT / "vibe" / "show_runtime_manifest.json").is_file():+ pytest.fail("packaged wheel smoke requires the prepared local Show Runtime manifest")++ wheelhouse = tmp_path / "wheelhouse"+ wheelhouse.mkdir()+ for version in ("3.0.14", "3.0.15"):+ _build_release_wheels(version, wheelhouse)++ environment = tmp_path / "memory-venv"+ python = _venv(environment)+ _install_initial(python, wheelhouse, memory=True, dependency_seed=packaged_dependency_seed)+ env = _plan_env(wheelhouse)+ assert _installed_versions(python)["avibe-os"] == "3.0.14"+ assert _installed_versions(python)["avibe-memory"] == "3.0.14"++ forward = build_upgrade_plan(+ python_executable=str(python),+ base_env=env,+ memory_enabled=True,+ memory_package=True,+ target_version="3.0.15",+ package_spec="avibe-os",+ )+ assert "avibe-os[memory]" in forward.command+ assert "avibe-memory==3.0.15" in forward.command+ 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"+++def test_packaged_core_only_upgrade_preserves_core_only_shape(+ tmp_path: Path, packaged_dependency_seed: Path+) -> None:+ wheelhouse = tmp_path / "wheelhouse"+ wheelhouse.mkdir()+ for version in ("3.0.14", "3.0.15"):+ _build_release_wheels(version, wheelhouse)+ python = _venv(tmp_path / "core-only-venv")+ _install_initial(python, wheelhouse, memory=False, dependency_seed=packaged_dependency_seed)+ plan = build_upgrade_plan(+ python_executable=str(python),+ base_env=_plan_env(wheelhouse),+ memory_enabled=False,+ memory_package=False,+ package_spec="avibe-os",+ )+ result = execute_upgrade_plan(plan, cwd=tmp_path, capture_output=True, text=True, check=False, timeout=600)+ assert result.returncode == 0, result.stdout + result.stderr+ versions = _installed_versions(python)+ assert versions["avibe-os"] == "3.0.15"+ assert "avibe-memory" not in versions+++def test_packaged_missing_memory_fails_before_install(tmp_path: Path, packaged_dependency_seed: Path) -> None:+ wheelhouse = tmp_path / "wheelhouse"+ wheelhouse.mkdir()+ _build_release_wheels("3.0.14", wheelhouse)+ _build_release_wheels("3.0.15", wheelhouse)+ 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()+ plan = build_upgrade_plan(+ python_executable=str(python),+ base_env=_plan_env(wheelhouse),+ memory_enabled=True,+ memory_package=True,+ target_version="3.0.15",+ package_spec="avibe-os",+ )+ result = execute_upgrade_plan(plan, cwd=tmp_path, capture_output=True, text=True, check=False, timeout=600)+ assert result.returncode != 0+ versions = _installed_versions(python)+ assert versions["avibe-os"] == "3.0.14"+ assert versions["avibe-memory"] == "3.0.14"diff --git a/tests/test_memory_wake.py b/tests/test_memory_wake.pyindex fc83e80b3..598d8eb1b 100644--- a/tests/test_memory_wake.py+++ b/tests/test_memory_wake.py@@ -11,19 +11,19 @@ from pathlib import Pathimport pytest-import core.memory.runtime as runtime_module+import avibe_memory.runtime as runtime_modulefrom config.v2_config import MemoryConfig, MemoryEndpointConfig, MemoryProcessingConfig-from core.memory.artifact import (+from avibe_memory.artifact import (EVEROS_VERSION,FakeMemoryArtifactManager,MemoryArtifactCandidate,MemoryArtifactManager,MemoryProviderRootState,)-from core.memory.confined_filesystem import ConfinedFilesystemError-from core.memory.everos import FakeMemoryProvider, ProviderHealthSnapshot-from core.memory.operation_lock import MemoryOperationBusy-from core.memory.process import FakeEverOSProcessFactory+from avibe_memory.confined_filesystem import ConfinedFilesystemError+from avibe_memory.everos import FakeMemoryProvider, ProviderHealthSnapshot+from config.memory_operation_lock import MemoryOperationBusy+from avibe_memory.process import FakeEverOSProcessFactorydef _config(*, legacy_needs_repair: bool = False) -> MemoryConfig:@@ -255,6 +255,8 @@ async def test_wake_retries_short_operation_lease_contention()attempts = 0releases = 0+ acquired = threading.Event()+ finish_acquire = threading.Event()class Lease:def __init__(self, _home: Path) -> None:@@ -265,6 +267,8 @@ async def test_wake_retries_short_operation_lease_contention(attempts += 1if attempts < 3:raise MemoryOperationBusy("busy")+ acquired.set()+ finish_acquire.wait(timeout=5)def release(self) -> None:nonlocal releases@@ -280,15 +284,28 @@ async def test_wake_retries_short_operation_lease_contention(effective_home=tmp_path,)- result = await runtime.wake()+ wake = asyncio.create_task(runtime.wake())+ assert await asyncio.to_thread(acquired.wait, 2)+ runtime.begin_close()+ finish_acquire.set()+ result = await wake- assert result == {"ok": True, "state": "running"}- assert attempts == 3- assert releases == 1+ assert result == {+ "ok": False,+ "state": "starting",+ "error": "memory_operation_in_progress",+ }+ assert (attempts, releases) == (3, 1)+ later = Lease(tmp_path)+ later.acquire()+ later.release()+ assert (attempts, releases) == (4, 2)[email protected]("consumer", ("wake", "install", "controller"))@pytest.mark.asyncio-async def test_cancelled_wake_releases_a_completed_lease_acquisition(+async def test_cancelled_operation_releases_a_completed_lease_acquisition(+ consumer: str,tmp_path: Path,monkeypatch: pytest.MonkeyPatch,memory_runtime_factory,@@ -310,8 +327,17 @@ async def test_cancelled_wake_releases_a_completed_lease_acquisition(lease_events.append("release")monkeypatch.setattr(runtime_module, "MemoryOperationLease", Lease)- runtime = memory_runtime_factory(_config(), effective_home=tmp_path)- task = asyncio.create_task(runtime.wake())+ if consumer == "controller":+ import core.controller as controller_module+ from core.controller import Controller++ monkeypatch.setattr(controller_module, "MemoryOperationLease", Lease)+ controller = Controller.__new__(Controller)+ task = asyncio.create_task(controller._try_memory_operation_lease(tmp_path))+ else:+ runtime = memory_runtime_factory(_config(), effective_home=tmp_path)+ operation = runtime.wake if consumer == "wake" else runtime.install_artifact+ task = asyncio.create_task(operation())assert await asyncio.to_thread(acquire_started.wait, 2)task.cancel()diff --git a/tests/test_memory_writer.py b/tests/test_memory_writer.pyindex a0b19d4f9..d23bdfd3d 100644--- a/tests/test_memory_writer.py+++ b/tests/test_memory_writer.py@@ -9,17 +9,17 @@ from types import SimpleNamespaceimport pytest-from core.memory.everos import (+from avibe_memory.everos import (AddAck,FakeMemoryProvider,FlushRetryable,FlushSucceeded,MemoryProviderFailure,)-from core.memory.attachments import AttachmentBundleInvalidError-from core.memory.store import MemoryStore, VolatileAdmission-from core.memory.types import ProviderSessionRef-from core.memory.writer import (+from avibe_memory.attachments import AttachmentBundleInvalidError+from avibe_memory.store import MemoryStore, VolatileAdmission+from avibe_memory.types import ProviderSessionRef+from avibe_memory.writer import (IDLE_FLUSH_SECONDS,MAX_ATTEMPTS,MAX_DUPLICATE_ENTRIES,@@ -39,10 +39,11 @@ PRINCIPAL = "u-" + "1" * 32def _writer(tmp_path: Path, provider: FakeMemoryProvider, **kwargs: object) -> BestEffortMemoryWriter:store = MemoryStore(tmp_path / "state" / "memory" / "memory.sqlite", effective_home=tmp_path)+ enabled = kwargs.pop("enabled", lambda: True)return BestEffortMemoryWriter(store=store,provider=provider,- enabled=lambda: True,+ enabled=enabled,**kwargs,)@@ -157,7 +158,7 @@ async def test_full_queue_discards_increment_process_local_count(if sleeps > 1:raise asyncio.CancelledError- monkeypatch.setattr("core.memory.writer.asyncio.sleep", one_scheduler_tick)+ monkeypatch.setattr("avibe_memory.writer.asyncio.sleep", one_scheduler_tick)await writer._schedule_due_flushes()assert writer.dropped_count() == 3@@ -178,6 +179,36 @@ async def test_worker_delivers_captures_in_offer_order(tmp_path: Path) -> None:]+async def test_revoked_runtime_drops_detached_provider_completion(+ tmp_path: Path,+) -> None:+ active = True+ provider = FakeMemoryProvider()+ provider_entered = asyncio.Event()+ provider_release = asyncio.Event()+ successes: list[str] = []++ async def delayed_add(capture): # noqa: ANN001, ANN202+ provider_entered.set()+ await provider_release.wait()+ return AddAck(request_id="old-runtime", status="accumulated")++ provider.add = delayed_add+ writer = _writer(tmp_path, provider, enabled=lambda: active)+ writer._store.mark_capture_success = lambda: successes.append("published")+ _reserve_and_offer(writer, 0)+ await provider_entered.wait()++ active = False+ provider_release.set()+ await writer.wait_idle_for_tests()++ assert successes == []+ assert writer._pending == {}+ assert writer._permits == MAX_WRITER_PERMITS++@pytest.mark.asyncioasync def test_extracted_add_clears_existing_volatile_session_state(tmp_path: Path) -> None:provider = FakeMemoryProvider(@@ -618,7 +649,7 @@ async def test_close_during_attachment_projection_releases_reservation(await asyncio.Event().wait()return operation(*args)- monkeypatch.setattr("core.memory.writer.run_blocking", controlled_run_blocking)+ monkeypatch.setattr("avibe_memory.writer.run_blocking", controlled_run_blocking)writer = _writer(tmp_path,FakeMemoryProvider(),@@ -907,7 +938,7 @@ async def test_each_exact_flush_threshold_queues_a_visible_barrier(if sleeps > 1:raise asyncio.CancelledError- monkeypatch.setattr("core.memory.writer.asyncio.sleep", one_scheduler_tick)+ monkeypatch.setattr("avibe_memory.writer.asyncio.sleep", one_scheduler_tick)await writer._schedule_due_flushes()assert writer._pending[key].scheduledassert writer._queued_items == 1@@ -944,7 +975,7 @@ async def test_flush_threshold_near_misses_do_not_schedule(if sleeps > 1:raise asyncio.CancelledError- monkeypatch.setattr("core.memory.writer.asyncio.sleep", one_scheduler_tick)+ monkeypatch.setattr("avibe_memory.writer.asyncio.sleep", one_scheduler_tick)await writer._schedule_due_flushes()assert not writer._pending[key].scheduledassert writer._queued_items == 0@@ -983,7 +1014,7 @@ async def test_wall_clock_rollback_does_not_delay_due_flush(if sleeps > 1:raise asyncio.CancelledError- monkeypatch.setattr("core.memory.writer.asyncio.sleep", one_scheduler_tick)+ monkeypatch.setattr("avibe_memory.writer.asyncio.sleep", one_scheduler_tick)await writer._schedule_due_flushes()assert writer._pending[key].scheduled@@ -1083,7 +1114,7 @@ async def test_failed_automatic_barrier_offer_defers_for_five_minutes(if sleeps > 2:raise asyncio.CancelledError- monkeypatch.setattr("core.memory.writer.asyncio.sleep", two_scheduler_ticks)+ monkeypatch.setattr("avibe_memory.writer.asyncio.sleep", two_scheduler_ticks)await writer._schedule_due_flushes()assert writer._pending[key].retry_after == current + IDLE_FLUSH_SECONDSdiff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex 7395c275e..915e0213a 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -13,10 +13,11 @@ ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))async def _wait_capture_tasks(handler) -> None:- while handler._memory_capture_tasks:- tasks = tuple(handler._memory_capture_tasks)+ adapter = handler.controller.memory_adapter+ while adapter.capture_tasks:+ tasks = tuple(adapter.capture_tasks)await asyncio.gather(*tasks, return_exceptions=True)- handler._memory_capture_tasks.difference_update(tasks)+ await asyncio.sleep(0)from modules.im import MessageContextfrom modules.sessions_facade import SessionsFacade@@ -175,6 +176,24 @@ class _StubAgentService:return self.stop_result+class _RecordingMemoryAdapter:+ def __init__(self) -> None:+ self.events = []++ @property+ def capture_tasks(self) -> set:+ return set()++ def offer(self, event) -> None:+ self.events.append(event)++ def quiesce_memory_capture_tasks(self) -> None:+ return None++ async def cancel_memory_capture_tasks(self) -> None:+ return None++class _StubController:def __init__(self, *, platform: str, ack_mode: str, typing_result: bool):self.config = type(@@ -198,6 +217,7 @@ class _StubController:self.command_handler = type("Cmd", (), {"handle_start": staticmethod(lambda context, args: None)})()self.agent_auth_service = type("Auth", (), {})()self.processing_indicator = ProcessingIndicatorService(self)+ self.memory_adapter = _RecordingMemoryAdapter()def update_thread_message_id(self, context):return None@@ -473,9 +493,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):lease.adopt.assert_called_once_with()lease.release.assert_called_once_with()- async def test_memory_attachment_capture_starts_after_one_shared_materialization(self):- """Scenario: MEMORY-IM-ATTACH-001."""-+ async def test_failed_durable_admission_releases_unowned_attachment_lease(self):from modules.im.base import FileAttachmentcontroller = _StubController(@@ -484,122 +502,12 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):typing_result=True,)controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- reservation = _capture_reservation()- controller.reserve_memory_attachment_capture = Mock(- return_value=reservation- )- events = []- retained_lease = Mock()- lease = Mock()- lease.retain.return_value = retained_lease- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )-- async def capture_user_memory(- _context,- _text,- _session_id,- *,- attachment_lease,- attachment_reservation,- attachment_config_generation,- ):- self.assertIs(attachment_reservation, reservation)- self.assertEqual(attachment_config_generation, 1)- events.append(("capture", attachment_lease))-- controller.capture_user_memory = capture_user_memoryhandler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())handler._is_duplicate_human_delivery = Mock(return_value=False)handler._prepend_message_metadata = AsyncMock(return_value="review this")-- async def materialize(_context, _working_path):- events.append(("materialize", None))- return types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- errors=("download_failed",),- lease=lease,- )-- handler._materialize_file_attachments = AsyncMock(side_effect=materialize)-- async def admit(**kwargs):- events.append(("agent-admission", kwargs["attachment_lease"]))- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-memory-attachment",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)-- handler._materialize_file_attachments.assert_awaited_once()- controller.reserve_memory_attachment_capture.assert_called_once_with(- context,- "base-session",- )- lease.retain.assert_called_once_with()- retained_lease.release.assert_called_once_with()- self.assertLess(- [kind for kind, _value in events].index("materialize"),- [kind for kind, _value in events].index("capture"),- )- self.assertIn(("capture", retained_lease), events)-- async def test_memory_lease_retain_failure_still_schedules_caption_capture(self):- """Scenario: MEMORY-IM-ATTACH-004."""-- from modules.im.base import FileAttachment-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- reservation = _capture_reservation()- controller.reserve_memory_attachment_capture = Mock(- return_value=reservation- )- captured = []-- async def capture_user_memory(- _context,- text,- _session_id,- *,- attachment_reservation,- attachment_config_generation,- attachment_text_only,- ):- self.assertIs(attachment_reservation, reservation)- self.assertEqual(attachment_config_generation, 1)- self.assertIs(attachment_text_only, True)- captured.append(text)-- controller.capture_user_memory = capture_user_memory- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="remember this")+ handler._emit_agent_dispatch_failure = AsyncMock()lease = Mock()- lease.retain.side_effect = RuntimeError("retain failed")attachment = FileAttachment(name="report.pdf",mimetype="application/pdf",@@ -613,511 +521,145 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):lease=lease,))-- async def admit(**_kwargs):- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)+ handler._admit_human_delivery = AsyncMock(+ side_effect=RuntimeError("admission rejected")+ )context = MessageContext(user_id="U1",- channel_id="D1",- message_id="m-retain-failure",+ channel_id="C1",+ message_id="m-rejected-attachment",platform="slack",- platform_specific={"is_dm": True},files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,)- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)+ await handler.handle_user_message(context, "review this")- self.assertEqual(captured, ["remember this"])- lease.retain.assert_called_once_with()- lease.adopt.assert_called_once_with()+ lease.adopt.assert_not_called()lease.release.assert_called_once_with()- async def test_materializer_global_failures_capture_caption_once(self):- """Scenario: MEMORY-IM-ATTACH-004."""-- from modules.im.base import FileAttachment-- cases = (- ("slack", OSError("attachment root initialization failed")),- ("discord", RuntimeError("attachment lease initialization failed")),- ("telegram", RuntimeError("attachment gather failed")),- )- for platform, materialization_error in cases:- with self.subTest(platform=platform):- controller = _StubController(- platform=platform,- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- controller.capture_user_memory = AsyncMock()- controller.reserve_memory_attachment_capture = Mock()- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(- return_value="remember this caption"- )- handler._materialize_file_attachments = AsyncMock(- side_effect=materialization_error- )- handler._emit_agent_dispatch_failure = AsyncMock()- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id=f"m-materializer-{platform}",- platform=platform,- platform_specific={"is_dm": True},- files=[- FileAttachment(- "report.pdf",- "application/pdf",- url="private",- )- ],- is_ordinary_attachment=True,- )-- result = await handler._handle_turn(- context,- "remember this caption",- source=handler.TURN_SOURCE_HUMAN,- )- await _wait_capture_tasks(handler)-- self.assertEqual(result, str(materialization_error))- controller.capture_user_memory.assert_awaited_once_with(- context,- "remember this caption",- "base-session",- )- controller.reserve_memory_attachment_capture.assert_not_called()- handler._emit_agent_dispatch_failure.assert_awaited_once()- self.assertIs(- handler._emit_agent_dispatch_failure.await_args.args[2],- materialization_error,- )- self.assertEqual(controller.agent_service.requests, [])-- async def test_materializer_failure_with_empty_caption_does_not_capture(self):- """Scenario: MEMORY-IM-ATTACH-004."""-- from modules.im.base import FileAttachment-+ async def test_inline_stop_uses_durable_empty_p0_owner(self):controller = _StubController(- platform="discord",+ platform="slack",ack_mode="reaction",typing_result=True,)- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- controller.capture_user_memory = AsyncMock()+ cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})+ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ cancel=cancel,+ )handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="")- handler._materialize_file_attachments = AsyncMock(- side_effect=RuntimeError("materialization failed")- )- handler._emit_agent_dispatch_failure = AsyncMock()context = MessageContext(user_id="U1",- channel_id="D1",- message_id="m-empty-caption-materializer",- platform="discord",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler._handle_turn(- context,- " ",- source=handler.TURN_SOURCE_HUMAN,+ channel_id="C1",+ thread_id="T1",+ message_id="m-stop",+ platform="slack",+ platform_specific={+ "agent_session_id": "ses-durable",+ "control_text": "stop",+ },)- controller.capture_user_memory.assert_not_called()-- async def test_materializer_cancellation_does_not_capture_caption(self):- """Scenario: MEMORY-IM-ATTACH-004."""+ await handler.handle_user_message(context, "stop")- from modules.im.base import FileAttachment+ cancel.assert_awaited_once_with("ses-durable")+ self.assertEqual(controller.agent_service.stop_requests, [])+ self.assertEqual(controller.agent_service.requests, [])+ async def test_retried_inline_stop_cannot_cancel_a_newer_turn(self):controller = _StubController(- platform="telegram",+ platform="slack",ack_mode="reaction",typing_result=True,)- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- controller.capture_user_memory = AsyncMock()+ cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})+ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ cancel=cancel,+ )+ controller.settings_manager.sessions.try_record_processed_message = Mock(+ side_effect=[True, False]+ )handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="remember this")- handler._materialize_file_attachments = AsyncMock(- side_effect=asyncio.CancelledError- )- handler._emit_agent_dispatch_failure = AsyncMock()context = MessageContext(user_id="U1",- channel_id="D1",- message_id="m-cancelled-materializer",- platform="telegram",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,+ channel_id="C1",+ thread_id="T1",+ message_id="m-stop-retry",+ platform="slack",+ platform_specific={+ "agent_session_id": "ses-durable",+ "control_text": "stop",+ },)- with self.assertRaises(asyncio.CancelledError):- await handler._handle_turn(- context,- "remember this",- source=handler.TURN_SOURCE_HUMAN,- )-- controller.capture_user_memory.assert_not_called()- handler._emit_agent_dispatch_failure.assert_not_awaited()-- async def test_caption_fallback_scheduling_failure_preserves_materializer_error(self):- """Scenario: MEMORY-IM-ATTACH-004."""+ await handler.handle_user_message(context, "stop")+ await handler.handle_user_message(context, "stop")- from modules.im.base import FileAttachment+ cancel.assert_awaited_once_with("ses-durable")+ self.assertEqual(controller.agent_service.stop_requests, [])+ self.assertEqual(controller.agent_service.requests, [])- materialization_error = RuntimeError("materialization failed")+ async def test_pre_request_failure_uses_plain_terminal_output(self):controller = _StubController(platform="slack",ack_mode="reaction",typing_result=True,)- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=AsyncMock(- side_effect=RuntimeError("capture scheduling failed")- ),- )- controller.capture_user_memory = AsyncMock()+ controller.emit_agent_message = AsyncMock(return_value=None)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="remember this")- handler._materialize_file_attachments = AsyncMock(- side_effect=materialization_error+ handler._prepare_turn_context = AsyncMock(+ side_effect=RuntimeError("context preparation failed"))- handler._emit_agent_dispatch_failure = AsyncMock()context = MessageContext(user_id="U1",- channel_id="D1",- message_id="m-failed-caption-fallback",+ channel_id="C1",platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,)- result = await handler._handle_turn(+ error = await handler._handle_turn(context,- "remember this",+ "hello",source=handler.TURN_SOURCE_HUMAN,)- self.assertEqual(result, "materialization failed")- controller.capture_user_memory.assert_not_awaited()- self.assertIs(- handler._emit_agent_dispatch_failure.await_args.args[2],- materialization_error,+ self.assertEqual(error, "context preparation failed")+ self.assertEqual(controller.emit_agent_message.await_count, 2)+ notify_call, call = controller.emit_agent_message.await_args_list+ self.assertEqual(+ notify_call.args[:3],+ (context, "notify", "Error: context preparation failed"),)+ self.assertEqual(call.args[:3], (context, "result", ""))+ output = call.kwargs["output"]+ self.assertTrue(output.completes_turn)+ self.assertTrue(output.settles_run)+ self.assertIsNone(output.activity_id)- async def test_invalid_attachment_generation_is_normalized_before_capture(self):- """Scenario: MEMORY-IM-ATTACH-003."""-- from modules.im.base import FileAttachment-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- reservation = _capture_reservation(generation=True)- controller.reserve_memory_attachment_capture = Mock(- return_value=reservation- )- controller.capture_user_memory = AsyncMock()- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )+ async def test_wechat_forces_typing_even_when_ack_mode_is_message(self):+ controller = _StubController(platform="wechat", ack_mode="message", typing_result=True)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="remember this")- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )-- async def admit(**_kwargs):- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-invalid-generation",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)+ context = MessageContext(user_id="U1", channel_id="C1", message_id="m1")- capture_call = controller.capture_user_memory.await_args- self.assertIsNone(- capture_call.kwargs["attachment_config_generation"]- )- self.assertNotIn("attachment_lease", capture_call.kwargs)- lease.retain.assert_not_called()+ await handler.handle_user_message(context, "hello")- async def test_denied_attachment_turn_does_not_retain_a_memory_lease(self):- """Scenario: MEMORY-IM-ATTACH-002."""+ _, request = controller.agent_service.requests[0]+ self.assertIsNone(request.ack_message_id)+ self.assertTrue(request.typing_indicator_active)+ self.assertEqual(controller.im_client.sent_messages, [])+ self.assertEqual(controller.im_client.reactions, [])+ self.assertGreaterEqual(len(controller.im_client.typing_calls), 1)- from modules.im.base import FileAttachment+ await handler._remove_ack_reaction(context, request)+ self.assertEqual(controller.im_client.clear_calls, [("C1", "U1")])- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- controller.reserve_memory_attachment_capture = Mock(return_value=None)- controller.capture_user_memory = AsyncMock()- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )-- async def admit(**_kwargs):- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="C-public",- message_id="m-denied-memory-attachment",- platform="slack",- platform_specific={"is_dm": False},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler.handle_user_message(context, "review this")- await _wait_capture_tasks(handler)-- lease.retain.assert_not_called()- controller.capture_user_memory.assert_called_once()- args, kwargs = controller.capture_user_memory.call_args- self.assertEqual(args, (context, "review this", "base-session"))- self.assertIsNone(kwargs["attachment_reservation"])- self.assertNotIn("attachment_lease", kwargs)-- async def test_failed_durable_admission_releases_unowned_attachment_lease(self):- from modules.im.base import FileAttachment-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._emit_agent_dispatch_failure = AsyncMock()- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )- handler._admit_human_delivery = AsyncMock(- side_effect=RuntimeError("admission rejected")- )- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-rejected-attachment",- platform="slack",- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- )-- await handler.handle_user_message(context, "review this")-- lease.adopt.assert_not_called()- lease.release.assert_called_once_with()-- async def test_inline_stop_uses_durable_empty_p0_owner(self):- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- cancel=cancel,- )- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- context = MessageContext(- user_id="U1",- channel_id="C1",- thread_id="T1",- message_id="m-stop",- platform="slack",- platform_specific={- "agent_session_id": "ses-durable",- "control_text": "stop",- },- )-- await handler.handle_user_message(context, "stop")-- cancel.assert_awaited_once_with("ses-durable")- self.assertEqual(controller.agent_service.stop_requests, [])- self.assertEqual(controller.agent_service.requests, [])-- async def test_retried_inline_stop_cannot_cancel_a_newer_turn(self):- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- cancel=cancel,- )- controller.settings_manager.sessions.try_record_processed_message = Mock(- side_effect=[True, False]- )- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- context = MessageContext(- user_id="U1",- channel_id="C1",- thread_id="T1",- message_id="m-stop-retry",- platform="slack",- platform_specific={- "agent_session_id": "ses-durable",- "control_text": "stop",- },- )-- await handler.handle_user_message(context, "stop")- await handler.handle_user_message(context, "stop")-- cancel.assert_awaited_once_with("ses-durable")- self.assertEqual(controller.agent_service.stop_requests, [])- self.assertEqual(controller.agent_service.requests, [])-- async def test_pre_request_failure_uses_plain_terminal_output(self):- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.emit_agent_message = AsyncMock(return_value=None)- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._prepare_turn_context = AsyncMock(- side_effect=RuntimeError("context preparation failed")- )- context = MessageContext(- user_id="U1",- channel_id="C1",- platform="slack",- )-- error = await handler._handle_turn(- context,- "hello",- source=handler.TURN_SOURCE_HUMAN,- )-- self.assertEqual(error, "context preparation failed")- self.assertEqual(controller.emit_agent_message.await_count, 2)- notify_call, call = controller.emit_agent_message.await_args_list- self.assertEqual(- notify_call.args[:3],- (context, "notify", "Error: context preparation failed"),- )- self.assertEqual(call.args[:3], (context, "result", ""))- output = call.kwargs["output"]- self.assertTrue(output.completes_turn)- self.assertTrue(output.settles_run)- self.assertIsNone(output.activity_id)-- async def test_wechat_forces_typing_even_when_ack_mode_is_message(self):- controller = _StubController(platform="wechat", ack_mode="message", typing_result=True)- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- context = MessageContext(user_id="U1", channel_id="C1", message_id="m1")-- await handler.handle_user_message(context, "hello")-- _, request = controller.agent_service.requests[0]- self.assertIsNone(request.ack_message_id)- self.assertTrue(request.typing_indicator_active)- self.assertEqual(controller.im_client.sent_messages, [])- self.assertEqual(controller.im_client.reactions, [])- self.assertGreaterEqual(len(controller.im_client.typing_calls), 1)-- await handler._remove_ack_reaction(context, request)- self.assertEqual(controller.im_client.clear_calls, [("C1", "U1")])-- async def test_typing_mode_falls_back_to_reaction_when_platform_lacks_typing(self):- controller = _StubController(platform="slack", ack_mode="typing", typing_result=False)+ async def test_typing_mode_falls_back_to_reaction_when_platform_lacks_typing(self):+ controller = _StubController(platform="slack", ack_mode="typing", typing_result=False)handler = MessageHandler(controller)handler.set_session_handler(_StubSessionHandler())context = MessageContext(user_id="U1", channel_id="C1", message_id="m1")@@ -1157,928 +699,6 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):{"id": "agent-default", "name": "default", "backend": "codex"},)- async def test_first_pass_memory_capture_holds_session_lifecycle_admission(self):- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- lifecycle_lock = asyncio.Lock()- capture_started = asyncio.Event()- release_capture = asyncio.Event()-- async def acquire_lifecycle_admission(session_id):- assert session_id == "base-session"- await lifecycle_lock.acquire()-- class Admission:- def release(self):- lifecycle_lock.release()-- return Admission()-- async def capture_user_memory(_context, _text, _session_id):- capture_started.set()- await release_capture.wait()-- controller.session_turns = types.SimpleNamespace(- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- controller.capture_user_memory = capture_user_memory- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-capture-admission",- platform="slack",- )-- await handler.handle_user_message(context, "remember this")- await asyncio.wait_for(capture_started.wait(), timeout=1.0)-- blocked_lifecycle = asyncio.create_task(- controller.session_turns.acquire_lifecycle_admission("base-session")- )- await asyncio.sleep(0)- assert not blocked_lifecycle.done()-- release_capture.set()- await _wait_capture_tasks(handler)- admission = await asyncio.wait_for(blocked_lifecycle, timeout=1.0)- admission.release()-- async def test_text_memory_capture_setup_failure_is_best_effort(self):- """Scenario: MEMORY-INDEP-006."""-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.capture_user_memory = Mock(- side_effect=RuntimeError("Memory runtime binding failed")- )- handler = MessageHandler(controller)- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-memory-setup-failure",- platform="slack",- )-- handler._schedule_text_only_memory_capture(- context,- "remember this",- "base-session",- expected_snapshot=0,- )-- assert handler._memory_capture_tasks == set()-- async def test_text_memory_capacity_is_released_when_setup_raises(self):- class Reservation:- capacity_full = False-- def __init__(self):- self.released = 0-- def release(self):- self.released += 1-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- reservation = Reservation()- controller.reserve_memory_capture_capacity = Mock(- return_value=reservation- )- controller.capture_user_memory = Mock(- side_effect=RuntimeError("Memory runtime binding failed")- )- handler = MessageHandler(controller)- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-memory-capacity-release",- platform="slack",- )-- handler._schedule_text_only_memory_capture(- context,- "remember this",- "base-session",- expected_snapshot=0,- )-- assert reservation.released == 1- assert handler._memory_capture_tasks == set()-- async def test_text_memory_terminal_capacity_drops_before_scheduling(self):- class Reservation:- capacity_blocked = True-- def __init__(self):- self.released = 0-- def release(self):- self.released += 1-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- reservation = Reservation()- controller.reserve_memory_capture_capacity = Mock(return_value=reservation)- controller.capture_user_memory = Mock()- handler = MessageHandler(controller)- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-memory-terminal-capacity",- platform="slack",- )-- handler._schedule_text_only_memory_capture(- context,- "remember this",- "base-session",- expected_snapshot=0,- )-- controller.capture_user_memory.assert_not_called()- assert reservation.released == 1- assert handler._memory_capture_tasks == set()-- async def test_attachment_memory_terminal_capacity_drops_before_lease_retain(self):- from modules.im.base import FileAttachment-- class Reservation:- capacity_blocked = True-- def __init__(self):- self.released = 0-- def release(self):- self.released += 1-- controller = _StubController(- platform="slack",- ack_mode="reaction",- typing_result=True,- )- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- reservation = Reservation()- controller.reserve_memory_attachment_capture = Mock(return_value=reservation)- controller.capture_user_memory = AsyncMock()- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="remember this")- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- errors=(),- lease=lease,- )- )-- async def admit(**_kwargs):- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-memory-terminal-attachment-capacity",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)-- lease.retain.assert_not_called()- controller.capture_user_memory.assert_not_awaited()- assert reservation.released == 1- assert handler._memory_capture_tasks == set()-- async def test_text_memory_capture_starts_before_agent_route_resolution(self):- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- captured = asyncio.Event()-- async def capture_user_memory(_context, _text, session_id):- self.assertEqual(session_id, "base-session")- captured.set()-- controller.capture_user_memory = capture_user_memory- controller.resolve_vibe_agent_for_context = Mock(- side_effect=RuntimeError("route unavailable")- )- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-early-memory",- platform="slack",- )-- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)-- assert captured.is_set()-- async def test_shutdown_quiesce_prevents_late_text_capture_registration(self):- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- lifecycle_admission = Mock()- controller.session_turns = types.SimpleNamespace(- acquire_lifecycle_admission=AsyncMock(- return_value=lifecycle_admission- ),- )- controller.capture_user_memory = AsyncMock()- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler.quiesce_memory_capture_tasks()- context = MessageContext(- user_id="U1",- channel_id="C1",- message_id="m-quiesced-text-memory",- platform="slack",- )-- await handler.handle_user_message(context, "remember this")-- controller.capture_user_memory.assert_not_called()- lifecycle_admission.release.assert_not_called()- controller.session_turns.acquire_lifecycle_admission.assert_not_awaited()- assert handler._memory_capture_tasks == set()-- async def test_attachment_capture_uses_anchor_before_agent_variant_namespace(self):- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())- reservation = _capture_reservation()- controller.reserve_memory_attachment_capture = Mock(- return_value=reservation- )- captured_session_ids = []- lease = Mock()- retained_lease = Mock()- lease.retain.return_value = retained_lease- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )-- async def capture_user_memory(- _context,- _text,- session_id,- *,- attachment_lease,- attachment_reservation,- attachment_config_generation,- ):- self.assertIs(attachment_lease, retained_lease)- self.assertIs(attachment_reservation, reservation)- self.assertEqual(attachment_config_generation, 1)- captured_session_ids.append(session_id)-- controller.capture_user_memory = capture_user_memory- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )-- async def admit(**kwargs):- self.assertEqual(kwargs["session_anchor"], "base-session:researcher")- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-canonical-memory",- platform="slack",- platform_specific={- "is_dm": True,- "agent_run_target": {"agent_variant": "researcher"},- },- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await handler.handle_user_message(context, "remember this")- await _wait_capture_tasks(handler)-- self.assertEqual(captured_session_ids, ["base-session"])-- async def test_attachment_capture_releases_turn_fence_before_background_work(self):- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- lifecycle_released = asyncio.Event()- capture_can_finish = asyncio.Event()- capture_finished = asyncio.Event()-- async def acquire_lifecycle_admission(session_id):- self.assertEqual(session_id, "base-session")-- class Admission:- def release(self):- lifecycle_released.set()-- return Admission()-- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- reservation = _capture_reservation()- controller.reserve_memory_attachment_capture = Mock(- return_value=reservation- )- lease = Mock()- retained_lease = Mock()- lease.retain.return_value = retained_lease- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )-- async def capture_user_memory(- _context,- _text,- _session_id,- *,- attachment_lease,- attachment_reservation,- attachment_config_generation,- ):- self.assertIs(attachment_lease, retained_lease)- self.assertIs(attachment_reservation, reservation)- self.assertEqual(attachment_config_generation, 1)- await capture_can_finish.wait()- capture_finished.set()-- controller.capture_user_memory = capture_user_memory- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )-- async def admit(**_kwargs):- assert not capture_finished.is_set()- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-background-memory",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- await asyncio.wait_for(- handler.handle_user_message(context, "remember this"),- timeout=1.0,- )-- assert not capture_finished.is_set()- handler._admit_human_delivery.assert_awaited_once()- capture_can_finish.set()- await _wait_capture_tasks(handler)- assert lifecycle_released.is_set()- retained_lease.release.assert_called_once_with()-- async def test_session_reset_during_download_drops_stale_attachment_without_waiting(- self,- ):- """Scenario: MEMORY-IM-ATTACH-004."""-- from core.session_turns import SessionTurnManager- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- controller.session_turns = SessionTurnManager(controller)- controller.reserve_memory_attachment_capture = Mock(- return_value=_capture_reservation()- )- controller.capture_user_memory = AsyncMock()- download_started = asyncio.Event()- release_download = asyncio.Event()- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )-- async def materialize(_context, _working_path):- download_started.set()- await release_download.wait()- return types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- errors=(),- lease=lease,- )-- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = materialize-- async def admit(**kwargs):- admitted_lease = kwargs["attachment_lease"]- admitted_lease.adopt()- admitted_lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-reset-during-download",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- turn = asyncio.create_task(- handler.handle_user_message(context, "keep this caption")- )- await asyncio.wait_for(download_started.wait(), timeout=1.0)- reset_completed = asyncio.Event()-- async def reset_operation():- reset_completed.set()- return "reset"-- reset = await asyncio.wait_for(- controller.session_turns.run_session_lifecycle(- "base-session",- reset_operation,- deadline_seconds=0.05,- ),- timeout=0.1,- )- self.assertEqual(reset, "reset")- assert reset_completed.is_set()- assert not turn.done()-- release_download.set()- await asyncio.wait_for(turn, timeout=1.0)- await _wait_capture_tasks(handler)-- controller.reserve_memory_attachment_capture.assert_not_called()- lease.retain.assert_not_called()- controller.capture_user_memory.assert_not_awaited()-- async def test_second_same_session_attachment_turn_does_not_wait_for_first_capture(- self,- ):- """Scenario: MEMORY-IM-ATTACH-001."""-- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- released_admissions = []-- async def acquire_lifecycle_admission(session_id):- self.assertEqual(session_id, "base-session")-- class Admission:- def release(self):- released_admissions.append(session_id)-- return Admission()-- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- reservations = [_capture_reservation(), _capture_reservation()]- controller.reserve_memory_attachment_capture = Mock(- side_effect=reservations- )- first_capture_started = asyncio.Event()- release_first_capture = asyncio.Event()- second_capture_started = asyncio.Event()- capture_index = 0-- async def capture_user_memory(- _context,- _text,- _session_id,- **_options,- ):- nonlocal capture_index- index = capture_index- capture_index += 1- if index == 0:- first_capture_started.set()- await release_first_capture.wait()- return- await release_first_capture.wait()- second_capture_started.set()-- controller.capture_user_memory = capture_user_memory- leases = [Mock(), Mock()]- retained = [Mock(), Mock()]- for lease, retained_lease in zip(leases, retained, strict=True):- lease.retain.return_value = retained_lease- attachments = [- FileAttachment(- name=f"report-{index}.pdf",- mimetype="application/pdf",- local_path=f"/tmp/leased-report-{index}.pdf",- size=10,- )- for index in range(2)- ]- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(- side_effect=[- types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- for attachment, lease in zip(attachments, leases, strict=True)- ]- )-- async def admit(**kwargs):- lease = kwargs["attachment_lease"]- lease.adopt()- lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)-- async def send(index: int) -> None:- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id=f"m-overlap-{index}",- platform="slack",- platform_specific={"is_dm": True},- files=[- FileAttachment(- f"report-{index}.pdf",- "application/pdf",- url="private",- )- ],- is_ordinary_attachment=True,- )- await handler.handle_user_message(context, "remember this")-- await asyncio.wait_for(send(0), timeout=1.0)- await asyncio.wait_for(first_capture_started.wait(), timeout=1.0)- await asyncio.wait_for(send(1), timeout=1.0)-- self.assertEqual(handler._admit_human_delivery.await_count, 2)- self.assertEqual(released_admissions, [])- assert not second_capture_started.is_set()- release_first_capture.set()- await _wait_capture_tasks(handler)- assert second_capture_started.is_set()- self.assertEqual(released_admissions, ["base-session", "base-session"])-- async def test_attachment_capture_cancelled_during_admission_does_not_retain_lease(- self,- ):- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- acquisition_started = asyncio.Event()- never_acquired = asyncio.Event()-- async def acquire_lifecycle_admission(session_id):- self.assertEqual(session_id, "base-session")- acquisition_started.set()- await never_acquired.wait()- raise AssertionError("unreachable")-- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- controller.reserve_memory_attachment_capture = Mock(- return_value=_capture_reservation()- )- controller.capture_user_memory = AsyncMock()- lease = Mock()- retained_lease = Mock()- lease.retain.return_value = retained_lease- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-cancelled-memory-admission",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- task = asyncio.create_task(- handler.handle_user_message(context, "remember this")- )- await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)- await asyncio.wait_for(task, timeout=1.0)- await handler.cancel_memory_capture_tasks()-- lease.retain.assert_called_once_with()- retained_lease.release.assert_called()- controller.capture_user_memory.assert_not_awaited()-- async def test_shutdown_quiesce_closes_capture_registration_before_sweep(- self,- ):- """Scenario: MEMORY-IM-ATTACH-004."""-- from modules.im.base import FileAttachment-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- acquisition_started = asyncio.Event()- release_acquisition = asyncio.Event()- lifecycle_admission = Mock()-- async def acquire_lifecycle_admission(session_id):- self.assertEqual(session_id, "base-session")- acquisition_started.set()- await release_acquisition.wait()- return lifecycle_admission-- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- controller.reserve_memory_attachment_capture = Mock(- return_value=_capture_reservation()- )- controller.capture_user_memory = AsyncMock()- lease = Mock()- attachment = FileAttachment(- name="report.pdf",- mimetype="application/pdf",- local_path="/tmp/leased-report.pdf",- size=10,- )- handler = MessageHandler(controller)- handler.set_session_handler(_StubSessionHandler())- handler._is_duplicate_human_delivery = Mock(return_value=False)- handler._prepend_message_metadata = AsyncMock(return_value="review this")- handler._materialize_file_attachments = AsyncMock(- return_value=types.SimpleNamespace(- attachments=(attachment,),- display_errors=(),- lease=lease,- )- )-- async def admit(**kwargs):- admitted_lease = kwargs["attachment_lease"]- admitted_lease.adopt()- admitted_lease.release()- return True-- handler._admit_human_delivery = AsyncMock(side_effect=admit)- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-shutdown-registration",- platform="slack",- platform_specific={"is_dm": True},- files=[FileAttachment("report.pdf", "application/pdf", url="private")],- is_ordinary_attachment=True,- )-- turn = asyncio.create_task(- handler.handle_user_message(context, "remember this")- )- await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)- handler.quiesce_memory_capture_tasks()- await handler.cancel_memory_capture_tasks()- release_acquisition.set()- await asyncio.wait_for(turn, timeout=1.0)-- controller.capture_user_memory.assert_not_awaited()- assert handler._memory_capture_tasks == set()-- async def test_cancelled_attachment_registration_removes_real_lease_directory(- self,- ):- """Scenario: MEMORY-IM-ATTACH-004."""-- from core.handlers.inbound_attachments import InboundAttachmentMaterializer- from modules.im.base import FileAttachment, FileDownloadResult-- class Downloader:- async def download_file_to_path(- self,- _file_info,- _target_path,- *,- target_fd=None,- **_kwargs,- ):- assert target_fd is not None- os.write(target_fd, b"%PDF-1.7\n")- return FileDownloadResult(True)-- root = Path(self.enterContext(tempfile.TemporaryDirectory())).resolve()- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-real-cancelled-registration",- platform="slack",- platform_specific={"is_dm": True},- files=[- FileAttachment(- "report.pdf",- "application/pdf",- url="private",- size=9,- )- ],- is_ordinary_attachment=True,- )- batch = await InboundAttachmentMaterializer(- effective_home=root,- attachments_root=root / "attachments",- ).materialize(context, Downloader())- leased_path = Path(batch.attachments[0].local_path)- retained_lease = batch.lease.retain()- batch.lease.release()- assert leased_path.exists()-- controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)- acquisition_started = asyncio.Event()- never_acquired = asyncio.Event()-- async def acquire_lifecycle_admission(_session_id):- acquisition_started.set()- await never_acquired.wait()- raise AssertionError("unreachable")-- controller.session_turns = types.SimpleNamespace(- deliver=AsyncMock(),- acquire_lifecycle_admission=acquire_lifecycle_admission,- )- controller.capture_user_memory = AsyncMock()- handler = MessageHandler(controller)-- async def capture_write() -> None:- await controller.capture_user_memory(context, "remember this", "base-session")-- handler._schedule_memory_capture_task(- session_id="base-session",- expected_snapshot=0,- capture=capture_write(),- attachment_lease=retained_lease,- )- await asyncio.wait_for(acquisition_started.wait(), timeout=1.0)- await handler.cancel_memory_capture_tasks()-- assert not leased_path.exists()- assert list((root / "attachments" / "im").iterdir()) == []- controller.capture_user_memory.assert_not_called()-- async def test_shutdown_cancels_inflight_capture_and_removes_real_lease_directory(- self,- ):- """Scenario: MEMORY-IM-ATTACH-004."""-- from core.handlers.inbound_attachments import InboundAttachmentMaterializer- from modules.im.base import FileAttachment, FileDownloadResult-- class Downloader:- async def download_file_to_path(- self,- _file_info,- _target_path,- *,- target_fd=None,- **_kwargs,- ):- assert target_fd is not None- os.write(target_fd, b"%PDF-1.7\n")- return FileDownloadResult(True)-- root = Path(self.enterContext(tempfile.TemporaryDirectory())).resolve()- context = MessageContext(- user_id="U1",- channel_id="D1",- message_id="m-shutdown-capture",- platform="slack",- platform_specific={"is_dm": True},- files=[- FileAttachment(- "report.pdf",- "application/pdf",- url="private",- size=9,- )- ],- is_ordinary_attachment=True,- )- batch = await InboundAttachmentMaterializer(- effective_home=root,- attachments_root=root / "attachments",- ).materialize(context, Downloader())- leased_path = Path(batch.attachments[0].local_path)- retained_lease = batch.lease.retain()- batch.lease.release()- assert leased_path.exists()-- handler = MessageHandler(- _StubController(platform="slack", ack_mode="reaction", typing_result=True)- )- capture_started = asyncio.Event()-- async def capture() -> None:- capture_started.set()- await asyncio.Event().wait()-- capture_task = asyncio.create_task(capture())- handler._track_memory_capture_task(- capture_task,- attachment_lease=retained_lease,- )- await capture_started.wait()-- await handler.cancel_memory_capture_tasks()-- assert capture_task.cancelled()- assert handler._memory_capture_tasks == set()- assert not leased_path.exists()- assert list((root / "attachments" / "im").iterdir()) == []-async def test_scope_model_and_reasoning_override_vibe_agent_defaults(self):controller = _StubController(platform="slack", ack_mode="reaction", typing_result=True)controller.settings_manager.routing = type(diff --git a/tests/test_release_package_version.py b/tests/test_release_package_version.pyindex e4fcf8ad6..44eeda8f9 100644--- a/tests/test_release_package_version.py+++ b/tests/test_release_package_version.py@@ -34,3 +34,4 @@ def test_package_release_workflows_pin_scm_version_to_release_tag() -> None:assert "python scripts/release_package_version.py" in workflowassert "SETUPTOOLS_SCM_PRETEND_VERSION=$PACKAGE_VERSION" in workflowassert "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=$PACKAGE_VERSION" in workflow+ assert "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_MEMORY=$PACKAGE_VERSION" in workflowdiff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex f4db332ff..448c8dd57 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -949,6 +949,7 @@ def test_pair_rejects_custom_proxy_only_dns_backend(monkeypatch) -> None:def test_validated_backend_request_connects_to_pinned_ip_without_hostname_dns(monkeypatch) -> None:captured: dict[str, object] = {}+ monkeypatch.setattr(remote_access, "_validated_backend_proxy_url", lambda _url: None)class FakeResponse:status = 200@@ -1002,6 +1003,7 @@ def test_validated_backend_request_connects_to_pinned_ip_without_hostname_dns(modef test_validated_backend_request_retries_next_pinned_address(monkeypatch) -> None:attempts: list[str] = []+ monkeypatch.setattr(remote_access, "_validated_backend_proxy_url", lambda _url: None)class FakeResponse:status = 200diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 54646b241..7d243538a 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -1,47 +1,24 @@from __future__ import annotations-import ast-import inspectimport ioimport os-import sqlite3import sys-import textwrapimport threading-from contextlib import contextmanager-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Pathfrom types import SimpleNamespaceimport pytestfrom config import paths-from storage.backups import create_sqlite_migration_backupfrom vibe import restart_supervisorfrom vibe import runtime-from vibe.upgrade import RollbackTarget-#: The install the machine was on before the upgrade replaced it. Deliberately-#: not this process's own interpreter: the case the launcher exists for is the-#: `vibe-remote` -> `avibe-os` rename, where the two generations live in-#: different directories, and a fixture reusing `sys.executable` would pass-#: whether or not the target's install is carried anywhere at all.-_REPLACED_INSTALL = runtime.ServiceLauncher(- python="/uv/tools/vibe-remote/bin/python",- main="/uv/tools/vibe-remote/lib/python3.13/site-packages/vibe/service_main.py",-)---def _rollback_target(version: str = "3.0.10") -> RollbackTarget:- """The install to go back to, as the upgrade captured it before installing."""-- return RollbackTarget(version=version, package="vibe-remote", launcher=_REPLACED_INSTALL)-def _fake_start_runtime(calls, service_pid: int = 222, ui_pid: int = 333):calls.append("start_runtime")runtime.write_status("running", f"pid={service_pid}", service_pid, ui_pid)- return restart_supervisor.StartedRuntime(service_pid, ui_pid, ("127.0.0.1", 5123))+ return restart_supervisor.StartedRuntime(service_pid, ui_pid)def _fake_stop_runtime(calls, *, ui_stopped=True, ui_pid=None, service_stopped=True):@@ -56,60 +33,6 @@ def _fake_stop_runtime(calls, *, ui_stopped=True, ui_pid=None, service_stopped=T)-def _fake_pinned_install(calls, installs, *, pin: str = "vibe-remote==3.0.10"):- """Record only the rollback's pinned install, never host process-table probes.-- Patching ``restart_supervisor.subprocess.run`` replaces the stdlib function- for every importer. Rollback then inspects leftover pids through- ``get_process_command``, which shells out to ``ps -p <pid>``. Capturing that- probe as ``installs[0]`` makes the pin assertion fail on whatever pid the- host happens to have live.- """-- def run(command, **_kwargs):- argv = list(command)- if any(pin in str(part) for part in argv):- calls.append("install")- installs.append(argv)- return SimpleNamespace(returncode=0, stdout="", stderr="")-- return run---@contextmanager-def _serve_version_endpoints(responses):- requests = []-- class Handler(BaseHTTPRequestHandler):- def do_GET(self):- requests.append(self.path)- status, content_type, body = responses[self.path]- self.send_response(status)- self.send_header("Content-Type", content_type)- self.end_headers()- self.wfile.write(body)-- def log_message(self, _format, *_args):- return-- server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- thread = threading.Thread(target=server.serve_forever, daemon=True)- thread.start()- try:- yield server.server_port, requests- finally:- server.shutdown()- thread.join()- server.server_close()---def _point_running_ui_probe_at(monkeypatch, port):- from core.services import settings as settings_service-- config = SimpleNamespace(ui=SimpleNamespace(setup_port=port))- monkeypatch.setattr(settings_service, "load_config", lambda **_kwargs: config)- monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda _config: "127.0.0.1")-def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -222,223 +145,6 @@ def test_candidate_supervisor_drops_source_pythonpath(monkeypatch, tmp_path):assert "PYTHONHOME" not in calls["kwargs"]["env"]-def test_legacy_upgrade_target_reads_the_running_release_and_launcher(monkeypatch, tmp_path):- """A pre-rollback release can still hand the new supervisor its target."""-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- paths.ensure_data_dirs()- tool_root = tmp_path / "uv" / "tools" / "avibe-os"- python_path = tool_root / "bin" / "python"- vibe_path = tool_root / "bin" / "vibe"- service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"- python_path.parent.mkdir(parents=True)- service_main.parent.mkdir(parents=True)- python_path.write_text("#!/bin/sh\n", encoding="utf-8")- vibe_path.write_text(f"#!{python_path}\n", encoding="utf-8")- service_main.write_text("# old release\n", encoding="utf-8")- metadata_dir = service_main.parent.parent / "avibe_os-3.0.12.dist-info"- metadata_dir.mkdir()- (metadata_dir / "METADATA").write_text("Name: avibe-os\nVersion: 3.0.12\n", encoding="utf-8")-- monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 123)- monkeypatch.setattr(restart_supervisor, "_running_ui_version", lambda: None)- monkeypatch.setattr(- runtime,- "get_process_command",- lambda pid: f"{python_path} {service_main}",- )-- target = restart_supervisor._discover_legacy_upgrade_target(- trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")- )-- assert target == RollbackTarget(- version="3.0.12",- package="avibe-os",- launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),- )---def test_legacy_upgrade_target_prefers_running_version_over_stale_metadata(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- paths.ensure_data_dirs()- tool_root = tmp_path / "venv"- python_path = tool_root / "bin" / "python"- service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"- python_path.parent.mkdir(parents=True)- service_main.parent.mkdir(parents=True)- python_path.write_text("#!/bin/sh\n", encoding="utf-8")- service_main.write_text("# replaced release\n", encoding="utf-8")- metadata_root = service_main.parent.parent- for name, version in (("avibe_os", "3.0.13"), ("vibe_remote", "2.9.4")):- metadata_dir = metadata_root / f"{name}-{version}.dist-info"- metadata_dir.mkdir()- package_name = "avibe-os" if name == "avibe_os" else "vibe-remote"- (metadata_dir / "METADATA").write_text(- f"Name: {package_name}\nVersion: {version}\n", encoding="utf-8"- )-- monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 123)- monkeypatch.setattr(- runtime,- "get_process_command",- lambda pid: f"{python_path} {service_main}",- )- responses = {- "/api/version/local": (200, "text/html", b"<!doctype html><title>Avibe</title>"),- "/api/version": (200, "application/json", b'{"current":"3.0.12"}'),- }- with _serve_version_endpoints(responses) as (port, requests):- _point_running_ui_probe_at(monkeypatch, port)- target = restart_supervisor._discover_legacy_upgrade_target(- trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")- )-- assert target == RollbackTarget(- version="3.0.12",- package="avibe-os",- launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),- )- assert requests == ["/api/version/local", "/api/version"]---def test_running_ui_version_falls_back_from_missing_new_endpoint(monkeypatch):- responses = {- "/api/version/local": (404, "application/json", b'{"detail":"Not Found"}'),- "/api/version": (200, "application/json", b'{"current":"3.0.12"}'),- }- with _serve_version_endpoints(responses) as (port, requests):- _point_running_ui_probe_at(monkeypatch, port)-- version = restart_supervisor._running_ui_version()-- assert version == "3.0.12"- assert requests == ["/api/version/local", "/api/version"]---def test_legacy_upgrade_target_stays_unavailable_when_all_identity_sources_are_invalid(- monkeypatch, tmp_path-):- tool_root = tmp_path / "uv" / "tools" / "avibe-os"- python_path = tool_root / "bin" / "python"- service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"- python_path.parent.mkdir(parents=True)- service_main.parent.mkdir(parents=True)- python_path.write_text("#!/bin/sh\n", encoding="utf-8")- service_main.write_text("# replaced release without trusted metadata\n", encoding="utf-8")- monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 123)- monkeypatch.setattr(restart_supervisor, "_read_recorded_ui_pid", lambda: None)- monkeypatch.setattr(runtime, "get_process_command", lambda _pid: f"{python_path} {service_main}")- responses = {- "/api/version/local": (200, "text/html", b"<!doctype html><title>Avibe</title>"),- "/api/version": (200, "application/json", b'{"current":"not-a-release"}'),- }- with _serve_version_endpoints(responses) as (port, requests):- _point_running_ui_probe_at(monkeypatch, port)- target = restart_supervisor._discover_legacy_upgrade_target(- trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")- )-- assert target is None- assert requests == ["/api/version/local", "/api/version"]---def test_legacy_upgrade_target_recovers_from_ui_only_process(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))- paths.ensure_data_dirs()- tool_root = tmp_path / "uv" / "tools" / "vibe-remote"- python_path = tool_root / "bin" / "python"- service_main = tool_root / "lib" / "python3.12" / "site-packages" / "vibe" / "service_main.py"- python_path.parent.mkdir(parents=True)- service_main.parent.mkdir(parents=True)- python_path.write_text("#!/bin/sh\n", encoding="utf-8")- service_main.write_text("# old release\n", encoding="utf-8")- metadata_dir = service_main.parent.parent / "vibe_remote-2.9.4.dist-info"- metadata_dir.mkdir()- (metadata_dir / "METADATA").write_text("Name: vibe-remote\nVersion: 2.9.4\n", encoding="utf-8")-- monkeypatch.setattr(restart_supervisor, "_read_recorded_pid", lambda: 999)- monkeypatch.setattr(restart_supervisor, "_read_recorded_ui_pid", lambda: 456)- monkeypatch.setattr(- runtime,- "get_process_command",- lambda pid: None if pid == 999 else f'{python_path} -c "from vibe.ui_server import run_ui_server; run_ui_server()"',- )- monkeypatch.setattr(restart_supervisor, "_running_ui_version", lambda: "2.9.4")-- target = restart_supervisor._discover_legacy_upgrade_target(- trigger="upgrade", vibe_path=str(tmp_path / "retargeted-vibe")- )-- assert target == RollbackTarget(- version="2.9.4",- package="vibe-remote",- launcher=runtime.ServiceLauncher(python=str(python_path), main=str(service_main)),- )---def test_service_launcher_from_process_strips_windows_quotes(monkeypatch, tmp_path):- python_path = tmp_path / "Program Files" / "uv" / "tools" / "avibe-os" / "Scripts" / "python.exe"- service_main = tmp_path / "Program Files" / "uv" / "tools" / "avibe-os" / "Lib" / "site-packages" / "vibe" / "service_main.py"- service_main.parent.mkdir(parents=True)- service_main.write_text("# old release\n", encoding="utf-8")- command = f'"{python_path}" "{service_main}"'- monkeypatch.setattr(runtime, "get_process_command", lambda pid: command)-- target = restart_supervisor._service_launcher_from_process(123)-- assert target == runtime.ServiceLauncher(python=str(python_path), main=str(service_main))---def test_legacy_upgrade_without_target_leaves_packaged_runtime_running(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- paths.ensure_data_dirs()- monkeypatch.setattr(restart_supervisor, "get_build_identity", lambda: SimpleNamespace(kind="package"))- monkeypatch.setattr(restart_supervisor, "_discover_legacy_upgrade_target", lambda **kwargs: None)- monkeypatch.setattr(- restart_supervisor,- "_stop_runtime_for_restart",- lambda **kwargs: pytest.fail("a legacy upgrade without a target must not stop the runtime"),- )-- rc = restart_supervisor._run_restart_job(- job_id="job-legacy-no-target",- delay_seconds=0,- vibe_path="/bin/vibe",- trigger="upgrade",- )-- assert rc == 2- status = runtime.read_json(runtime.get_restart_status_path())- assert status["state"] == "failed"- assert "existing runtime was left running" in status["error"]---def test_failed_legacy_upgrade_uses_discovered_target_for_rollback(monkeypatch, tmp_path):- """The v3.0.12 path is recoverable even though it passed no rollback argv."""-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)- monkeypatch.setattr(- restart_supervisor,- "_discover_legacy_upgrade_target",- lambda **kwargs: _rollback_target(),- )-- rc = restart_supervisor._run_restart_job(- job_id="joblegacy",- delay_seconds=0,- vibe_path="/bin/vibe",- trigger="upgrade",- rollback_to=None,- )-- assert rc == 1- status = runtime.read_json(runtime.get_restart_status_path())- assert status["rollback_to"] == "3.0.10"- assert status["rollback_target_source"] == "running_service"- assert status["rollback"]["state"] == "succeeded"- assert armed.observed_by_the_rolled_back_version == [["before the upgrade"]]-def test_schedule_restart_can_prepare_show_runtime_after_restart(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))@@ -466,7 +172,7 @@ def test_schedule_restart_can_prepare_show_runtime_after_restart(monkeypatch, tmdef test_schedule_restart_passes_memory_ui_secret_only_through_stdin(monkeypatch, tmp_path):- from core.memory.ui_access import MEMORY_UI_SECRET_STDIN_ENV+ from vibe.memory_ui_access import MEMORY_UI_SECRET_STDIN_ENVmonkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()@@ -509,21 +215,7 @@ def test_schedule_restart_passes_memory_ui_secret_only_through_stdin(monkeypatchdef test_the_argv_the_job_builds_is_the_argv_the_entry_point_accepts(monkeypatch, tmp_path):- """One command, one parser, proved by running the built argv through the CLI.-- `schedule_restart` builds a command line and a detached `vibe` process parses- it back. For a while both ends were owned by different parsers -- this module- built the `--rollback-*` flags, `vibe/cli.py` declared the ones it knew about,- and the top-level parser ran first. So the flags were not merely unsupported,- they were rejected: the child exited on `unrecognized arguments`, the seeded- "scheduled" record was never overwritten by anyone, and the machine stayed on- the release that could not start. Every test in this file called- `restart_supervisor.main([...])` directly, so nothing crossed that seam.-- Asserted as a round trip rather than as a list of flags: the spawned argv is- taken exactly as `Popen` received it and handed to the real entry point, so a- flag added to the builder later is covered without touching this test.- """+ """The detached restart command round-trips through the real CLI parser."""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()@@ -533,45 +225,84 @@ def test_the_argv_the_job_builds_is_the_argv_the_entry_point_accepts(monkeypatchmonkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)+ monkeypatch.setattr(+ restart_supervisor.subprocess,+ "Popen",+ lambda command, **kwargs: spawned.setdefault("command", command) and SimpleNamespace(pid=45678),+ )- def fake_popen(command, **kwargs):- spawned["command"] = command- return SimpleNamespace(pid=45678)-- monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)-- rollback_to = _rollback_target("3.0.10")restart_supervisor.schedule_restart(delay_seconds=0,vibe_path="/bin/vibe",trigger="upgrade",scope="service",prepare_show_runtime=True,- rollback_to=rollback_to,)+ assert not any(argument.startswith("--rollback") for argument in spawned["command"])from vibe import cliran = {}+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)+ monkeypatch.setattr(restart_supervisor, "_run_restart_job", lambda **kwargs: ran.update(kwargs) or 0)+ monkeypatch.setattr(sys, "argv", list(spawned["command"]))++ with pytest.raises(SystemExit) as exit_info:+ cli.main()- def fake_run_restart_job(**kwargs):- ran.update(kwargs)- return 0+ assert exit_info.value.code == 0+ assert ran == {+ "job_id": ran["job_id"],+ "delay_seconds": 0.0,+ "vibe_path": "/bin/vibe",+ "trigger": "upgrade",+ "scope": "service",+ "prepare_show_runtime": True,+ }++def test_entry_point_accepts_and_ignores_retired_rollback_argv(monkeypatch):+ from vibe import cli++ ran = {}monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: None)- monkeypatch.setattr(restart_supervisor, "_run_restart_job", fake_run_restart_job)- monkeypatch.setattr(sys, "argv", list(spawned["command"]))+ monkeypatch.setattr(restart_supervisor, "_run_restart_job", lambda **kwargs: ran.update(kwargs) or 0)+ monkeypatch.setattr(+ sys,+ "argv",+ [+ "vibe",+ "__restart-supervisor",+ "--job-id",+ "legacy-upgrade",+ "--trigger",+ "upgrade",+ "--rollback-to",+ "3.0.14",+ "--rollback-package",+ "avibe-os",+ "--rollback-memory-package",+ "--rollback-memory-version",+ "3.0.14",+ "--rollback-python",+ "/opt/avibe/bin/python",+ "--rollback-main",+ "/opt/avibe/vibe/service_main.py",+ ],+ )with pytest.raises(SystemExit) as exit_info:cli.main()assert exit_info.value.code == 0- # Not just "it parsed": the rollback target has to arrive whole, because a- # partially-carried one is the failure this whole path exists to prevent.- assert ran["rollback_to"] == rollback_to- assert ran["trigger"] == "upgrade"- assert ran["scope"] == "service"- assert ran["prepare_show_runtime"] is True+ assert ran == {+ "job_id": "legacy-upgrade",+ "delay_seconds": 0.0,+ "vibe_path": None,+ "trigger": "upgrade",+ "scope": "all",+ "prepare_show_runtime": False,+ }def test_schedule_restart_marks_status_failed_when_spawn_fails(monkeypatch, tmp_path):@@ -711,8 +442,6 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "get_restart_command", lambda vibe_path=None: ["/bin/vibe"])monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)- monkeypatch.setattr(restart_supervisor, "_discover_legacy_upgrade_target", lambda **kwargs: None)- monkeypatch.setattr(restart_supervisor, "get_build_identity", lambda: SimpleNamespace(kind="source"))def fake_run(command, **kwargs):calls.append(("run", command))@@ -887,7 +616,7 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):paths.get_runtime_pid_path().unlink()except FileNotFoundError:pass- return restart_supervisor.StartedRuntime(222, 333, ("127.0.0.1", 5123))+ return restart_supervisor.StartedRuntime(222, 333)monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", slow_start_runtime)# Both halves of the generation this start launched are alive: the status@@ -1025,30 +754,13 @@ def test_start_runtime_processes_starts_service_and_ui(monkeypatch, tmp_path):assert started.service_pid == 222assert started.ui_pid == 333- # The health target is resolved here or nowhere: this is the only place that- # loads the config to decide the bind host and port, so it is the only answer- # to "where is the UI" that cannot disagree with where the UI was started.- assert started.ui_health_target == ("0.0.0.0", 5123)assert calls[:2] == ["ensure_data_dirs", "load_config"]assert calls[2][:3] == ("start_service", False, 0)assert calls[3] == ("bind_host", config)assert calls[4][:4] == ("start_ui", "0.0.0.0", 5123, False)assert calls[2][3]["memory_ui_secret"] == calls[4][4]["memory_ui_secret"]-- # Every process this helper starts comes from the one install it was given,- # asserted over whatever it started rather than over two named spawns: the- # service and the UI are two halves of one generation, and a rollback that- # started one from the restored install and the other from the replaced one- # is a state neither release was ever run in. `None` is "this process",- # which is the right answer for every restart except a rollback.- def started_from() -> list:- return [call[-1].get("launcher") for call in calls if call[0] in ("start_service", "start_ui")]-- assert started_from() == [None, None]-- calls.clear()- restart_supervisor._start_runtime_processes(launcher=_REPLACED_INSTALL)- assert started_from() == [_REPLACED_INSTALL, _REPLACED_INSTALL]+ assert "launcher" not in calls[2][3]+ assert "launcher" not in calls[4][4]status = runtime.read_status()# "starting", not "running", and the stubbed lock says the pid is recorded.@@ -1160,459 +872,75 @@ def test_restart_job_service_scope_keeps_ui(monkeypatch, tmp_path):assert status["scope"] == "service"-def _seed_state_database(db_path):- """The database as the machine had it before the upgrade touched anything."""-- db_path.parent.mkdir(parents=True, exist_ok=True)- with sqlite3.connect(db_path) as conn:- conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")- conn.execute("delete from alembic_version")- conn.execute("insert into alembic_version (version_num) values ('20260806_0047')")- conn.execute("create table payload (value text)")- conn.execute("insert into payload (value) values ('before the upgrade')")---def _payload_rows(db_path) -> list[str]:- with sqlite3.connect(db_path) as conn:- return [row[0] for row in conn.execute("select value from payload order by rowid")]---def _upgrade_restart_that_dies_after_migrating(- monkeypatch,- tmp_path,- *,- service_running: bool,- ui_serving: bool = True,-):- """Arm the incident this whole path exists for, and hand back what it did.-- The new version stops the old one, starts, takes its pre-migration backup,- commits a row, and then dies without ever holding the service lock. Only the- two processes and the package index are stubbed: the database, the backup- window, and the watermark the job reads out of it are the real ones, because- they are the things the rollback has to get right.- """-+def test_failed_upgrade_restart_reports_terminal_failure_without_package_rollback(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()paths.get_runtime_pid_path().write_text("111", encoding="utf-8")- db_path = paths.get_sqlite_state_path()- _seed_state_database(db_path)-- calls: list[str] = []- installs: list[list[str]] = []- launchers: list = []- observed_by_the_rolled_back_version: list[list[str]] = []-- def start(start_ui=True, launcher=None):- calls.append("start_runtime")- launchers.append(launcher)- if calls.count("start_runtime") == 1:- # The new version gets far enough to take its rollback point and- # commit, then dies without ever holding the lock.- create_sqlite_migration_backup(db_path, backups_dir=paths.get_state_backups_dir())- with sqlite3.connect(db_path) as conn:- conn.execute("insert into payload (value) values ('committed by the new version')")- raise RuntimeError("service refused to start")- observed_by_the_rolled_back_version.append(_payload_rows(db_path))- return _fake_start_runtime([], service_pid=222, ui_pid=333)+ package_commands = []+ calls = []monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))- monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor.subprocess, "run", _fake_pinned_install(calls, installs))- monkeypatch.setattr(runtime, "verified_service_running", lambda: service_running)- monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout=None: pid)- # The machine as this failure actually leaves it: the version that died in- # its migration is gone, and so nothing of it is still holding the database- # open. Stated here rather than left to the host's real process table, which- # a test may not read and must never depend on.- monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", list)- monkeypatch.setattr(runtime, "ui_pid_file_points_to_running_ui", lambda *args, **kwargs: False)- # The UI the rollback restarts, and whether it answers. Both are stubbed- # rather than left to the host: `_ui_is_serving` opens a real socket, and a- # test that let it would wait out the timeout against whatever happens to be- # listening on the developer's machine.- ui_probes: list[tuple[str, int]] = []- monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 333)+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda start_ui=True: _fake_start_runtime(calls))+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)+ monkeypatch.setattr(runtime, "wait_for_service_ready", lambda pid, timeout: None)monkeypatch.setattr(- runtime,- "wait_for_ui_server",- lambda host, port, timeout=None: ui_probes.append((host, port)) or ui_serving,- )-- return SimpleNamespace(- db_path=db_path,- calls=calls,- installs=installs,- launchers=launchers,- ui_probes=ui_probes,- observed_by_the_rolled_back_version=observed_by_the_rolled_back_version,- )---def test_a_rollback_whose_ui_never_serves_is_not_reported_as_recovered(monkeypatch, tmp_path):- """A live pid is not a serving UI, and this job is the one that cannot guess.-- The service came back and holds the lock; the UI process was started and is- alive, and never answers. Everything a pid-based check can see says the- machine is up, which is exactly the evidence this record must not accept:- nobody is watching an unattended rollback, so the half that is dark has to be- the half that is reported. The service pid is still recorded either way --- the run failed, it did not vanish.- """-- armed = _upgrade_restart_that_dies_after_migrating(- monkeypatch, tmp_path, service_running=False, ui_serving=False- )-- restart_supervisor._run_restart_job(- job_id="jobdark", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()+ restart_supervisor.subprocess,+ "run",+ lambda command, **kwargs: package_commands.append(command),)- rollback = runtime.read_json(runtime.get_restart_status_path())["rollback"]- assert rollback["state"] == "failed"- assert rollback["ui"] == {"pid": 333, "serving": False}- assert rollback["service_pid"] == 222- assert "Web UI" in rollback["error"]- # It reached the UI at all, rather than failing for want of a probe.- assert armed.ui_probes---def test_a_restart_that_leaves_nothing_running_puts_the_old_version_back(monkeypatch, tmp_path):- """The property the change exists for: an upgrade cannot end with a dark instance.-- Install, then restore, then start -- and the started version has to find the- database the version it is reads. That last part is why the order is asserted- through what the started process sees rather than through a call log: a- restore that lands after the start is a restore that lands after the service- has already opened a schema it cannot read.- """-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)-rc = restart_supervisor._run_restart_job(- job_id="jobroll", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()- )-- # The restart still failed, and still says so: a rollback recovers the- # machine, it does not turn a failed upgrade into a successful one.- assert rc == 1- status = runtime.read_json(runtime.get_restart_status_path())- assert status["ok"] is False- assert "start runtime failed: service refused to start" in status["error"]-- # Nothing of the failed generation is left alive across the install and the- # restore: the second stop is the rollback's own, and without it a process- # that never reached the lock is still holding the database file open when- # the restore rewrites it -- and is what the final start would adopt.- assert armed.calls == ["stop_runtime", "start_runtime", "stop_runtime", "install", "start_runtime"]- # The distribution the OLD release was published as, not the one this build- # is: a machine that predates the `vibe-remote` -> `avibe-os` rename has no- # `avibe-os==3.0.10` to go back to, and pinning one is an index round-trip- # that fails and leaves the instance dark.- assert "vibe-remote==3.0.10" in armed.installs[0]- assert armed.observed_by_the_rolled_back_version == [["before the upgrade"]]- assert _payload_rows(armed.db_path) == ["before the upgrade"]-- # The rollback starts the install it just reinstalled, not the one this job- # is running out of. An upgrade spawns the job through the `vibe` on PATH,- # which the install has already replaced, so by now `sys.executable` names- # the failed generation -- and across the `vibe-remote` -> `avibe-os` rename- # the two are different directories, both present, both startable. `None`- # for the first start is the upgrade's own: it is what should run next.- assert armed.launchers == [None, _REPLACED_INSTALL]-- rollback = status["rollback"]- assert rollback["target_version"] == "3.0.10"- assert rollback["state"] == "succeeded"- assert rollback["install"]["ok"] is True- assert rollback["database"]["restored"] is True- assert runtime.read_status()["service_pid"] == 222---def test_a_service_still_holding_the_lock_is_never_rolled_back_underneath(monkeypatch, tmp_path):- """The same failure, the opposite answer, decided by one fact: the lock.-- A restart that failed while a service is still serving has not produced the- state this recovery exists for, and reinstalling and restoring underneath- that live process is the damage rather than the repair. Nothing about the- failure itself distinguishes the two cases -- only what is holding the lock- when it is over does.- """-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=True)-- rc = restart_supervisor._run_restart_job(- job_id="jobheld", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()- )-- assert rc == 1- assert armed.calls == ["stop_runtime", "start_runtime"]- assert armed.installs == []- assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]- status = runtime.read_json(runtime.get_restart_status_path())- assert status["rollback"] == {"target_version": "3.0.10", "state": "skipped", "reason": "service_running"}---def test_a_service_that_took_the_lock_and_then_died_is_rolled_back(monkeypatch, tmp_path):- """The incident this path exists for, in the shape it actually has.-- The lock is taken BEFORE the database is migrated -- it has to be, since the- migration is what it excludes. So a release that fails on its migration does- hold the lock, for the seconds it takes to get there and die, and a job that- stopped at "the pid is recorded" spends those seconds writing- `state: succeeded` about an instance that ends them with nothing running.-- Which makes the recorded pid unusable as the finish line, in the one case- that matters. What ends the wait is the service saying it is up, which it- says after the migration.- """-- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- paths.ensure_data_dirs()- paths.get_runtime_pid_path().write_text("111", encoding="utf-8")- db_path = paths.get_sqlite_state_path()- _seed_state_database(db_path)- calls: list[str] = []- installs: list[list[str]] = []- launchers: list = []- observed_by_the_rolled_back_version: list[list[str]] = []- alive = {222: True, 333: True, 444: True}-- def start(start_ui=True, launcher=None):- calls.append("start_runtime")- launchers.append(launcher)- if calls.count("start_runtime") == 1:- # The new version takes its rollback point, commits, and is now in- # the migration that will kill it -- all of it under the lock.- create_sqlite_migration_backup(db_path, backups_dir=paths.get_state_backups_dir())- with sqlite3.connect(db_path) as conn:- conn.execute("insert into payload (value) values ('committed by the new version')")- runtime.write_status("running", "pid=222", 222, 333)- return restart_supervisor.StartedRuntime(222, 333, ("127.0.0.1", 5123))- observed_by_the_rolled_back_version.append(_payload_rows(db_path))- return _fake_start_runtime([], service_pid=444, ui_pid=333)-- def started(pid: int) -> bool:- # Asking is what finds out: the migration failed, so by the time anyone- # looks a second time the holder is gone and the lock with it.- alive[pid] = False- return pid == 444-- monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda stop_ui=True: _fake_stop_runtime(calls))- monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", start)- monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)- monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))- monkeypatch.setattr(restart_supervisor.subprocess, "run", _fake_pinned_install(calls, installs))- # The failed generation is gone: nothing of it is still holding the database- # open. Stated here rather than left to the host's real process table, which- # a test may not read and must never depend on -- the sibling helper already- # isolates this, and without it ``ps -p 444`` (a pid this test invented)- # lands in the shared ``subprocess.run`` mock as a fake install.- monkeypatch.setattr(restart_supervisor, "_remaining_service_pids_after_stop", list)- monkeypatch.setattr(runtime, "ui_pid_file_points_to_running_ui", lambda *args, **kwargs: False)- monkeypatch.setattr(runtime, "pid_alive", lambda pid: alive.get(pid, False))- monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: True)- monkeypatch.setattr(runtime, "service_instance_started", started)- monkeypatch.setattr(runtime, "verified_service_running", lambda: False)- monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port, timeout=None: True)-- rc = restart_supervisor._run_restart_job(- job_id="jobdark", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()+ job_id="job-upgrade-failed",+ delay_seconds=0,+ vibe_path="/bin/vibe",+ trigger="upgrade",)assert rc == 3+ assert calls == ["stop_runtime", "start_runtime"]+ assert package_commands == []status = runtime.read_json(runtime.get_restart_status_path())assert status["ok"] is False- assert "did not finish starting" in status["error"]- assert status["rollback"]["state"] == "succeeded"- assert "vibe-remote==3.0.10" in installs[0]- assert observed_by_the_rolled_back_version == [["before the upgrade"]]- assert _payload_rows(db_path) == ["before the upgrade"]---def test_a_generation_that_was_already_gone_is_quiesced(monkeypatch, tmp_path):- """The ordinary case, and the one a stop report gets exactly backwards.-- A version that died in its migration has nothing left to kill, so- `stop_service` reports that it stopped nothing -- the same answer it gives- for a process that refused to die, because the two states are- indistinguishable from the report and distinguishable only from the machine.- A rollback gated on the report therefore refuses to run on the failure it was- built for, which is the one where the instance is already dark.- """-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)- monkeypatch.setattr(- restart_supervisor,- "_stop_runtime_for_restart",- lambda stop_ui=True: _fake_stop_runtime(armed.calls, service_stopped=False, ui_stopped=False),- )-- rc = restart_supervisor._run_restart_job(- job_id="jobgone", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()- )-- assert rc == 1- status = runtime.read_json(runtime.get_restart_status_path())- assert status["rollback"]["quiesced"] is True- assert status["rollback"]["state"] == "succeeded"- assert _payload_rows(armed.db_path) == ["before the upgrade"]--- "survivor",- [- {"service_pids": [999]},- {"ui_alive": True},- ],- ids=["a-service-process-of-the-failed-generation", "a-ui-process-that-would-not-die"],-)-def test_a_failed_generation_that_will_not_stop_stops_the_rollback_instead(monkeypatch, tmp_path, survivor):- """Quiescing is a step with an outcome, not a step with a side effect.-- A process that resists termination is the entire reason the stop is there, so- a rollback that ran it and then carried on regardless would be at its most- confident in the only case it is about. What follows makes that concrete: the- restore rewrites a database file that process holds open, and the final start- adopts its live recorded pid instead of launching what was just reinstalled --- so the rollback would report success for the version it was rolling back from,- over a database it had corrupted underneath it.-- So the database is what this asserts on. Untouched is the whole claim; the- status record only has to be readable enough to send someone to look.- """-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)- # Whichever process survived, and whatever the stop said about it: what- # decides is the machine afterwards, so the stop is left reporting success.- monkeypatch.setattr(- restart_supervisor, "_remaining_service_pids_after_stop", lambda: list(survivor.get("service_pids", []))- )- monkeypatch.setattr(- runtime, "ui_pid_file_points_to_running_ui", lambda *args, **kwargs: bool(survivor.get("ui_alive"))- )-- rc = restart_supervisor._run_restart_job(- job_id="jobstuck", delay_seconds=0, vibe_path="/bin/vibe", trigger="upgrade", rollback_to=_rollback_target()- )-- assert rc == 1- status = runtime.read_json(runtime.get_restart_status_path())- assert status["rollback"]["state"] == "failed"- assert status["rollback"]["quiesced"] is False- assert "still running" in status["rollback"]["error"]- # Nothing was installed and nothing was restored: the machine is left exactly- # as the failed upgrade left it, which is recoverable by hand.- assert [command for command in armed.installs if any("3.0.10" in argument for argument in command)] == []- assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]---def test_a_restart_with_no_version_to_go_back_to_changes_nothing(monkeypatch, tmp_path):- """A plain restart is already running what it would reinstall.-- It has no rollback target, so the failure is left exactly as it happened for- whoever looks at it -- including the database, which nothing here is entitled- to move backwards. The absent record is the readable part: a failed restart- with a `rollback_to` and no `rollback` was armed and killed before it could- recover, which is a different incident from one that was never recoverable.- """-- armed = _upgrade_restart_that_dies_after_migrating(monkeypatch, tmp_path, service_running=False)-- rc = restart_supervisor._run_restart_job(job_id="jobplain", delay_seconds=0, vibe_path="/bin/vibe", trigger="cli")-- assert rc == 1- assert armed.calls == ["stop_runtime", "start_runtime"]- assert armed.installs == []- assert _payload_rows(armed.db_path) == ["before the upgrade", "committed by the new version"]- status = runtime.read_json(runtime.get_restart_status_path())- assert status["rollback_to"] is None- assert "rollback" not in status---def test_no_failure_branch_can_end_the_job_without_the_rollback_decision():- """Whether to roll back is asked once, not per failure branch.-- A list of the branches that deserve a rollback is complete only until the- next branch is added, and the one nobody remembered is exactly the one that- leaves an instance dark. So the job has a single failure exit, and this- asserts that structurally: any new branch reaching the raw `_fail` directly- fails here, at the moment it is written, rather than in the incident.- """-- tree = ast.parse(textwrap.dedent(inspect.getsource(restart_supervisor._run_restart_job)))- wrapper = next(- node for node in ast.walk(tree) if isinstance(node, ast.FunctionDef) and node.name == "fail"- )- inside_the_wrapper = {id(node) for node in ast.walk(wrapper)}- calls = [- node- for node in ast.walk(tree)- if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "_fail"- ]-- assert [node for node in calls if id(node) in inside_the_wrapper], "the wrapper is what ends a failed job"- assert [node for node in calls if id(node) not in inside_the_wrapper] == []---def test_a_recoverable_restart_carries_its_rollback_target_into_the_job(monkeypatch, tmp_path):- """The target survives the process boundary the restart is built on.-- `schedule_restart` spawns a detached job, so the install to go back to has to- travel as argv and be read back by the job's own parser. Asserted as a round- trip rather than as two independent expectations: the two sides are what can- drift, and a flag renamed on one of them would leave every rollback silently- disarmed while both halves still look right.+ assert status["state"] == "failed"+ assert status["error"] == "service pid 222 did not finish starting"+ assert not any("rollback" in key for key in status)- Asserted as equality against the whole target rather than field by field.- Argv is the one place the fields are apart, so it is the one place they can- be separated by accident -- a version arriving without its distribution pins- a name the old release never had, and one arriving without its install- reinstalls the right release and then starts the wrong one -- and a field- added later is carried by this test without it being edited, or fails it.- """+def test_terminal_restart_failure_does_not_block_a_subsequent_attempt(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()- commands: list[list[str]] = []+ restart_supervisor._write_status(+ {+ "ok": False,+ "job_id": "failed-attempt",+ "state": "failed",+ "trigger": "upgrade",+ "error": "new release failed readiness",+ }+ )+ spawned = []monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: {"PATH": "/bin"})monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)+ monkeypatch.setattr(+ restart_supervisor.subprocess,+ "Popen",+ lambda command, **kwargs: spawned.append(command) or SimpleNamespace(pid=45678),+ )- def fake_popen(command, **kwargs):- commands.append(command)- return SimpleNamespace(pid=4242)-- monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)-- target = _rollback_target()- restart_supervisor.schedule_restart(+ admitted = restart_supervisor.schedule_restart(delay_seconds=0,vibe_path="/bin/vibe",trigger="upgrade",- rollback_to=target,)- upgrade_argv = commands[-1]- restart_supervisor.schedule_restart(delay_seconds=0, vibe_path="/bin/vibe", trigger="cli")- plain_argv = commands[-1]- assert [argument for argument in plain_argv if argument.startswith("--rollback")] == []-- parsed: dict = {}- monkeypatch.setattr(restart_supervisor, "_run_restart_job", lambda **kwargs: parsed.update(kwargs) or 0)- assert restart_supervisor.main(upgrade_argv[2:]) == 0- assert parsed["rollback_to"] == target-- parsed.clear()- assert restart_supervisor.main(plain_argv[2:]) == 0- assert parsed["rollback_to"] is None-- # A partial set is refused rather than completed from this process. The job- # runs the release the rollback is undoing, so "fill in the missing install- # from here" is the exact wrong answer, and a silent one.- with pytest.raises(SystemExit):- restart_supervisor.main(["--job-id", "jobpartial", "--rollback-to", "3.0.10"])++ assert admitted["job_id"] != "failed-attempt"+ assert spawned+ status = runtime.read_json(runtime.get_restart_status_path())+ assert status["job_id"] == admitted["job_id"]+ assert status["state"] == "scheduled"+ assert status["error"] is Nonediff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 94a978991..d1bf56843 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -13044,6 +13044,7 @@ class _DispatchController:"""def __init__(self, db_path: Path, working_path: Path) -> None:+ from core.memory_adapter import DisabledMemoryAdapterfrom core.processing_indicator import ProcessingIndicatorServicefrom storage.sessions_service import SQLiteSessionsService@@ -13069,6 +13070,7 @@ class _DispatchController:# Reached only on HUMAN turns (the Workbench dispatch path); a bare# namespace makes the handler's ``getattr`` probes miss and move on.self.agent_auth_service = SimpleNamespace()+ self.memory_adapter = DisabledMemoryAdapter()self.primary_platform = "slack"from core.vibe_agents import VibeAgentStorediff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex d91406d62..623505c19 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -5,6 +5,7 @@ import gcimport jsonimport threadingfrom concurrent.futures import ThreadPoolExecutor+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patch@@ -12,6 +13,9 @@ from unittest.mock import AsyncMock, patchimport pytestfrom sqlalchemy import select, update+from avibe_memory.capture_adapter import EnabledMemoryAdapter+from core.handlers.message_handler import memory_turn_event+from core.memory_adapter import SessionArchived, SessionResetfrom core.services.agent_steering import SteerOutcome, result as steer_resultfrom core.services.dispatch import TurnDispatchOutcomefrom core.native_dispatch_phase import (@@ -39,6 +43,7 @@ from core.session_turns import (DeliveryResult,SessionTurnManager,Turn,+ _collect_delivery_segment,_scheduled_merge_key,)from core.message_context import SCHEDULED_DISPATCH_METADATA_APPLIED_KEY@@ -61,15 +66,6 @@ from storage.models import ()-async def _wait_capture_tasks(handler) -> None:- """Test-only synchronization for handler-owned volatile capture tasks."""-- while handler._memory_capture_tasks:- tasks = tuple(handler._memory_capture_tasks)- await asyncio.gather(*tasks, return_exceptions=True)- handler._memory_capture_tasks.difference_update(tasks)--@pytest.fixturedef anyio_backend() -> str:return "asyncio"@@ -213,17 +209,6 @@ def managers(tmp_path: Path):engine_b.dispose()-def _capture_handler(manager: SessionTurnManager) -> MessageHandler:- handler = MessageHandler.__new__(MessageHandler)- handler.controller = manager.controller- handler._memory_capture_tasks = set()- handler._memory_capture_tasks_by_session = {}- handler._memory_capture_registration_open = True- manager.controller.session_turns = manager- manager.controller.message_handler = handler- return handler--@pytest.mark.anyioasync def test_completed_memory_lifecycle_state_does_not_accumulate(managers) -> None:"""Scenario: MEMORY-INDEP-005.@@ -255,77 +240,6 @@ async def test_completed_memory_lifecycle_state_does_not_accumulate(managers) ->assert len(manager._session_lifecycle_states) == 0-async def test_session_lifecycle_barrier_is_non_blocking_for_admitted_turn_capture(- managers,-) -> None:- """Scenario: MEMORY-INDEP-010."""-- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- release_capture = asyncio.Event()- capture_entered = asyncio.Event()- captured: list[str] = []- snapshot = manager.snapshot_session_lifecycle("ses_fsm")-- async def capture() -> None:- capture_entered.set()- await release_capture.wait()- captured.append("provider-write")-- task = handler._schedule_memory_capture_task(- session_id="ses_fsm",- expected_snapshot=snapshot,- capture=capture(),- )- assert task is not None- await asyncio.wait_for(capture_entered.wait(), timeout=1.0)-- async def lifecycle_operation() -> str:- release_capture.set()- await asyncio.sleep(0)- assert captured == []- return "reset"-- assert await asyncio.wait_for(- manager.run_session_lifecycle(- "ses_fsm",- lifecycle_operation,- deadline_seconds=1.0,- ),- timeout=1.0,- ) == "reset"- await _wait_capture_tasks(handler)- assert captured == []- assert task.cancelled()---async def test_session_lifecycle_does_not_join_queued_capture_admission(managers) -> None:- manager, _other, _engine, _engine_b, _starts = managers- state = manager._session_lifecycle_state("ses_fsm")- holder = await manager.acquire_lifecycle_admission("ses_fsm")- queued = asyncio.create_task(manager.acquire_lifecycle_admission("ses_fsm"))- while state.admission_waiters != 1:- await asyncio.sleep(0)-- holder.release()- assert state.admission_lock.locked() is False-- assert await asyncio.wait_for(- manager.run_session_lifecycle("ses_fsm", lambda: _completed("reset")),- timeout=1.0,- ) == "reset"-- queued.cancel()- with pytest.raises(asyncio.CancelledError):- await queued---async def _completed(value: str) -> str:- return value--@pytest.mark.anyioasync def test_session_lifecycle_invalidates_snapshot_after_operation(managers) -> None:manager, _other, _engine, _engine_b, _starts = managers@@ -371,29 +285,77 @@ async def test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops() -> None:"""Scenario: MEMORY-INDEP-001."""- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- capture_holding = asyncio.Event()- never_resolves = asyncio.Event()- lifecycle_busy = False- dispatched: list[str] = []+ manager, _other, _engine, _engine_b, starts = managers+ capture_started = asyncio.Event()- async def hung_capture() -> None:- capture_holding.set()- await never_resolves.wait()+ class Module:+ def __init__(self) -> None:+ self.capacities: list[SimpleNamespace] = []+ self.reservations: list[SimpleNamespace] = []+ self.barriers: list[str] = []- handler._schedule_memory_capture_task(- session_id="ses_fsm",- expected_snapshot=manager.snapshot_session_lifecycle("ses_fsm"),- capture=hung_capture(),- )- await asyncio.wait_for(capture_holding.wait(), timeout=1.0)+ def reserve_capture_capacity(self) -> object:+ capacity = SimpleNamespace(active=True)+ self.capacities.append(capacity)+ return capacity++ def release_capture_capacity(self, capacity: object) -> None:+ capacity.active = False++ def reserve_capture_admission(self, **_scope: object) -> object:+ reservation = SimpleNamespace(active=True)+ self.reservations.append(reservation)+ return reservation++ def cancel_capture_reservation(self, reservation: object) -> None:+ reservation.active = False++ @asynccontextmanager+ async def capture_admission(self, **_options: object):+ yield object()++ async def capture(self, _request: object, **_options: object) -> object:+ capture_started.set()+ await asyncio.Event().wait()- async def run_turn(_session_id, _context, text, **_kwargs):- dispatched.append(text)+ def offer_barrier(self, session_id: str) -> object:+ self.barriers.append(session_id)+ return "queued"- manager._run = run_turn- started = await asyncio.wait_for(+ async def wait_writer_idle_for_tests(self, **_options: object) -> None:+ return None++ class Principals:+ def principal_for_user_key(self, _user_key: str) -> str:+ return "u-11111111111111111111111111111111"++ module = Module()+ adapter = EnabledMemoryAdapter(+ module=module,+ principals=Principals(),+ is_enabled_user=lambda _platform, _user_id: True,+ lifecycle_snapshot_matches=manager.session_lifecycle_snapshot_matches,+ acquire_lifecycle_admission=manager.acquire_lifecycle_admission,+ attachment_capture_status=lambda: asyncio.sleep(0, result="unavailable"),+ attachment_config_generation=lambda: None,+ )+ manager.controller.memory_adapter = adapter+ assert adapter.start(task_factory=asyncio.create_task)+ context = _context()+ context.message_id = "native-memory-turn"+ context.is_original_human_text = True+ context.platform_specific["author_id"] = "authenticated-author"+ adapter.offer(+ memory_turn_event(+ context,+ "记住这一轮",+ "ses_fsm",+ manager.snapshot_session_lifecycle("ses_fsm"),+ )+ )+ await asyncio.wait_for(capture_started.wait(), timeout=1.0)++ delivered = await asyncio.wait_for(manager.deliver(DeliveryRequest(session_id="ses_fsm",@@ -404,8 +366,8 @@ async def test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops(),timeout=1.0,)- assert started.turn_id- assert dispatched == ["next turn"]+ assert delivered.turn_id+ assert starts[-1] == (delivered.turn_id, "next turn")async def reset_session() -> str:return "reset"@@ -413,187 +375,36 @@ async def test_hung_memory_capture_does_not_fence_next_turn_or_destructive_ops(async def archive_session() -> str:return "archived"- try:- assert await asyncio.wait_for(- manager.run_session_lifecycle(- "ses_fsm",- reset_session,- deadline_seconds=0.05,- ),- timeout=1.0,- ) == "reset"- assert await asyncio.wait_for(- manager.run_session_lifecycle(- "ses_fsm",- archive_session,- deadline_seconds=0.05,- ),- timeout=1.0,- ) == "archived"- except Exception as error:- lifecycle_busy = getattr(error, "code", None) == "memory_session_lifecycle_busy"- raise- assert lifecycle_busy is False- never_resolves.set()- await _wait_capture_tasks(handler)---async def test_capture_admitted_before_new_is_discarded_after_transition(- managers,-) -> None:- """Scenario: MEMORY-INDEP-002."""-- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- attributed: list[str] = []- admitted = asyncio.Event()- finish_capture = asyncio.Event()- sampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")-- async def capture_write() -> None:- attributed.append("wrote")-- async def delayed_capture() -> None:- admitted.set()- await finish_capture.wait()- await handler._run_memory_capture(+ assert await asyncio.wait_for(+ manager.run_session_lifecycle("ses_fsm",- sampled_snapshot,- capture_write(),- )-- capture_task = asyncio.create_task(delayed_capture())- handler._track_memory_capture_task(capture_task, session_id="ses_fsm")- await asyncio.wait_for(admitted.wait(), timeout=1.0)-- async def reset_session() -> str:- return "reset"-- assert await manager.run_session_lifecycle(- "ses_fsm",- reset_session,- deadline_seconds=0.05,- ) == "reset"- assert not manager.session_lifecycle_snapshot_matches(- "ses_fsm",- sampled_snapshot,- )-- finish_capture.set()- await _wait_capture_tasks(handler)- assert attributed == []---async def test_idle_session_capture_attributes_while_shutdown_may_drop(- managers,-) -> None:- """Scenario: MEMORY-INDEP-003."""-- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- attributed: list[str] = []-- async def capture_write() -> None:- attributed.append("wrote")-- await handler._run_memory_capture(- "ses_fsm",- manager.snapshot_session_lifecycle("ses_fsm"),- capture_write(),- )- assert attributed == ["wrote"]-- never_resolves = asyncio.Event()-- async def accepted_capture() -> None:- await never_resolves.wait()-- pending = asyncio.create_task(accepted_capture(), name="memory-capture")- handler._track_memory_capture_task(pending, session_id="ses_fsm")- wait_tasks = asyncio.create_task(_wait_capture_tasks(handler))- await asyncio.sleep(0)- assert not wait_tasks.done()- never_resolves.set()- await asyncio.wait_for(wait_tasks, timeout=1.0)- assert handler._memory_capture_tasks == set()---async def test_successful_lifecycle_does_not_cancel_a_new_generation_capture(- managers,-) -> None:- """A capture registered during reset must not be cancelled on the success bump."""-- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- scheduled: list[asyncio.Task[object]] = []-- async def reset_session() -> str:- task = handler._schedule_memory_capture_task(- session_id="ses_fsm",- expected_snapshot=manager.snapshot_session_lifecycle("ses_fsm"),- capture=asyncio.sleep(0),- )- assert task is not None- scheduled.append(task)- await asyncio.sleep(0)- return "reset"-- assert await manager.run_session_lifecycle(- "ses_fsm",- reset_session,- deadline_seconds=1.0,+ reset_session,+ deadline_seconds=0.05,+ ),+ timeout=1.0,) == "reset"- assert scheduled[0].cancelled() is False- await _wait_capture_tasks(handler)- assert scheduled[0].cancelled() is False---async def test_failed_busy_lifecycle_invalidates_in_flight_capture(- managers,-) -> None:- """A busy old-generation capture is fenced before a failing /new runs."""-- manager, _other, _engine, _engine_b, _starts = managers- handler = _capture_handler(manager)- never_resolves = asyncio.Event()- holding = asyncio.Event()-- async def hung_capture() -> None:- holding.set()- await never_resolves.wait()-- sampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")- task = handler._schedule_memory_capture_task(- session_id="ses_fsm",- expected_snapshot=sampled_snapshot,- capture=hung_capture(),- )- assert task is not None- await asyncio.wait_for(holding.wait(), timeout=1.0)-- async def reset_session() -> str:- raise RuntimeError("reset failed")-- with pytest.raises(RuntimeError, match="reset failed"):- await manager.run_session_lifecycle(+ adapter.offer(SessionReset("ses_fsm"))+ assert await asyncio.wait_for(+ manager.run_session_lifecycle("ses_fsm",- reset_session,+ archive_session,deadline_seconds=0.05,- )+ ),+ timeout=1.0,+ ) == "archived"+ adapter.offer(SessionArchived("ses_fsm"))- await _wait_capture_tasks(handler)- assert not manager.session_lifecycle_snapshot_matches(- "ses_fsm",- sampled_snapshot,+ await adapter.wait_idle_for_tests(timeout_seconds=1.0)+ assert module.barriers == ["ses_fsm", "ses_fsm"]+ assert module.capacities and all(not item.active for item in module.capacities)+ assert module.reservations and all(+ not item.active for item in module.reservations)- assert task.cancelled()- assert not handler._memory_capture_tasks+ assert adapter.capture_tasks == set()+ await adapter.cancel_memory_capture_tasks()async def _activate(manager: SessionTurnManager,*,@@ -957,7 +768,7 @@ def test_fifo_segment_starts_one_turn_and_materializes_one_merged_message(manageassert stored["delivered_at"] == accepted[0]["materialized_at"]-def test_memory_fifo_segment_merges_only_one_user(managers) -> None:+def test_fifo_segment_merges_only_one_authenticated_author(managers) -> None:manager, _other, engine, _engine_b, starts = managersactive_turn_id, _ = asyncio.run(_activate(manager, text="active"))queued = [@@ -967,10 +778,8 @@ def test_memory_fifo_segment_merges_only_one_user(managers) -> None:session_id="ses_fsm",priority="p3",content=text,- metadata={- "_memory_user_id": user_id,- "_memory_ordinary_text": True,- },+ author_id=user_id,+ message_kind="original",),context=_context(),)@@ -1031,6 +840,140 @@ def test_fifo_segment_does_not_merge_different_message_authors(managers) -> Noneassert bob["state"] == "queued"+def test_memory_indep_016_new_queue_uses_core_identity_without_memory_metadata(+ managers,+) -> None:+ """Scenario: MEMORY-INDEP-016."""++ manager, _other, engine, _engine_b, _starts = managers+ result = asyncio.run(+ manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="Continue",+ author_id="remote:alice",+ message_kind="quick_reply",+ metadata={+ "quick_reply_for": "msg-agent",+ "_memory_user_id": "forged-principal",+ "_memory_ordinary_text": True,+ "_memory_cli_admitted": True,+ },+ ),+ context=_context(),+ )+ )++ row = _row(engine, str(result.delivery_id))+ snapshot = json.loads(row["snapshot_json"])+ metadata = json.loads(snapshot["metadata_json"])+ assert snapshot["author_id"] == "remote:alice"+ assert snapshot["message_kind"] == "quick_reply"+ assert not any(key.startswith("_memory_") for key in metadata)+++def test_core_message_kind_separates_original_and_quick_reply_segments() -> None:+ common = {+ "scope_id": "scope",+ "platform": "avibe",+ "author": "user",+ "type": "user",+ "source": "user",+ "author_id": "remote:alice",+ "author_name": "Alice",+ "parent_native_message_id": None,+ "metadata": {},+ }+ original = {**common, "message_kind": "original"}+ quick_reply = {**common, "message_kind": "quick_reply"}++ assert _collect_delivery_segment([original, quick_reply]) == [original]+++def test_legacy_and_new_original_rows_do_not_merge_admission_schemas() -> None:+ legacy = {+ "scope_id": "scope",+ "platform": "avibe",+ "author": "user",+ "type": "user",+ "source": "user",+ "author_id": "remote:alice",+ "author_name": "Alice",+ "parent_native_message_id": None,+ "metadata": {"_memory_ordinary_text": True},+ }+ current = {+ **legacy,+ "message_kind": "original",+ "metadata": {},+ }++ assert delivery_store.message_merge_identity(legacy) != (+ delivery_store.message_merge_identity(current)+ )+++def test_raw_legacy_and_new_original_snapshots_do_not_merge_admission_schemas() -> None:+ common = {+ "scope_id": "scope",+ "platform": "avibe",+ "author": "user",+ "type": "user",+ "source": "user",+ "author_id": "remote:alice",+ "author_name": "Alice",+ "parent_native_message_id": None,+ }+ legacy = {+ **common,+ "metadata_json": json.dumps({"_memory_ordinary_text": True}),+ }+ current = {+ **common,+ "message_kind": "original",+ "metadata_json": "{}",+ }++ assert delivery_store.message_merge_identity(legacy) != (+ delivery_store.message_merge_identity(current)+ )++[email protected]("metadata_field", delivery_store.LEGACY_MEMORY_MERGE_IDENTITY_METADATA_KEYS)+def test_every_released_memory_admission_fact_fences_delivery_segments(+ metadata_field: str,+) -> None:+ metadata = {+ delivery_store.LEGACY_MEMORY_USER_ID_METADATA: "principal-a",+ delivery_store.LEGACY_MEMORY_ORDINARY_TEXT_METADATA: True,+ delivery_store.LEGACY_MEMORY_CLI_ADMITTED_METADATA: True,+ }+ common = {+ "scope_id": "scope",+ "platform": "avibe",+ "author": "user",+ "type": "user",+ "source": "user",+ "author_id": "same-core-author",+ "author_name": "Alice",+ "parent_native_message_id": None,+ }+ first = {**common, "metadata": metadata}+ changed_metadata = dict(metadata)+ value = changed_metadata[metadata_field]+ changed_metadata[metadata_field] = not value if isinstance(value, bool) else f"{value}-other"+ second = {**common, "metadata": changed_metadata}++ first_identity = delivery_store.message_merge_identity(first)+ second_identity = delivery_store.message_merge_identity(second)++ assert first_identity[-1] == delivery_store.legacy_memory_merge_identity(metadata)+ assert second_identity[-1] == delivery_store.legacy_memory_merge_identity(changed_metadata)+ assert first_identity != second_identity+ assert _collect_delivery_segment([first, second]) == [first]++def test_scheduled_segment_key_keeps_source_sessions_separate() -> None:def row(source_session_id: str) -> dict:return {@@ -2101,7 +2044,7 @@ def test_hydrate_delivery_context_preserves_im_author_as_routing_identity(manager._hydrate_delivery_context(context, delivery)assert context.user_id == author_id- assert context.platform_specific["message_metadata"]["_memory_user_id"] == "local"+ assert context.platform_specific["message_metadata"] == {}def test_wechat_outbound_send_uses_hydrated_author_id(managers) -> None:@@ -2154,8 +2097,8 @@ def test_wechat_outbound_send_uses_hydrated_author_id(managers) -> None:assert message_id-def test_workbench_memory_principal_stays_in_turn_facts(managers) -> None:- """Workbench Memory identity is metadata-only; missing metadata skips capture."""+def test_workbench_memory_principal_uses_authenticated_author_id(managers) -> None:+ """Workbench Memory never trusts released `_memory_user_id` metadata."""manager, _other, engine, _engine_b, starts = managerscontroller = _memory_facts_controller()@@ -2175,12 +2118,10 @@ def test_workbench_memory_principal_stays_in_turn_facts(managers) -> None:skipped_context = _context()skipped_context.user_id = "workbench"manager._hydrate_delivery_context(skipped_context, skipped_delivery)- skipped_facts = controller._memory_turn_facts(- skipped_context, include_workdir=False- )+ skipped_facts = controller._memory_turn_facts(skipped_context)assert skipped_context.user_id == "workbench"- assert skipped_facts.user_id == "workbench"+ assert skipped_facts.user_id is Noneassert controller.memory_capture_admitted(skipped_context) is Falseassert controller.memory_principal_for_context(skipped_context) is Noneassert starts@@ -2201,6 +2142,7 @@ def test_workbench_memory_principal_stays_in_turn_facts(managers) -> None:source="user",text="remember this",author_id="push-user",+ message_kind="original",metadata={"_memory_user_id": "local","_memory_ordinary_text": True,@@ -2211,10 +2153,102 @@ def test_workbench_memory_principal_stays_in_turn_facts(managers) -> None:context = _context()context.user_id = "workbench"manager._hydrate_delivery_context(context, _row(engine, remembered_id))- facts = controller._memory_turn_facts(context, include_workdir=False)+ facts = controller._memory_turn_facts(context)assert context.user_id == "push-user"- assert facts.user_id == "local"+ assert facts.user_id == "push-user"+ assert controller.memory_principal_for_context(context) == "principal:avibe:push-user"+++def test_legacy_workbench_lan_author_does_not_gain_memory_admission(managers) -> None:+ manager, _other, engine, _engine_b, _starts = managers+ manager.controller.config.memory = SimpleNamespace(enabled=True)+ snapshot = delivery_store.message_snapshot(+ scope_id=None,+ session_id="ses_fsm",+ platform="avibe",+ author="user",+ source="user",+ text="legacy LAN input",+ author_id="local",+ metadata={+ "_memory_cli_admitted": False,+ "_memory_ordinary_text": True,+ },+ )+ snapshot.pop("message_kind")+ snapshot["metadata_json"] = json.dumps(+ {+ "_memory_cli_admitted": False,+ "_memory_ordinary_text": True,+ }+ )+ delivery_id = delivery_store.new_delivery_id()+ with engine.begin() as conn:+ delivery_store.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id="ses_fsm",+ priority="p3",+ state="queued",+ snapshot=snapshot,+ dispatch_text="legacy LAN input",+ )++ context = _context()+ manager._hydrate_delivery_context(context, _row(engine, delivery_id))+ controller = _memory_facts_controller()++ assert context.user_id == "user"+ assert (context.platform_specific or {}).get("memory_cli_admitted") is None+ assert controller.memory_capture_admitted(context) is False+ assert controller.memory_principal_for_context(context) is None+++def test_legacy_workbench_strict_author_keeps_memory_admission(managers) -> None:+ manager, _other, engine, _engine_b, _starts = managers+ manager.controller.config.memory = SimpleNamespace(enabled=True)+ snapshot = delivery_store.message_snapshot(+ scope_id=None,+ session_id="ses_fsm",+ platform="avibe",+ author="user",+ source="user",+ text="legacy loopback input",+ author_id="local",+ metadata={+ "_memory_user_id": "local",+ "_memory_cli_admitted": True,+ "_memory_ordinary_text": True,+ },+ )+ snapshot.pop("message_kind")+ snapshot["metadata_json"] = json.dumps(+ {+ "_memory_user_id": "local",+ "_memory_cli_admitted": True,+ "_memory_ordinary_text": True,+ }+ )+ delivery_id = delivery_store.new_delivery_id()+ with engine.begin() as conn:+ delivery_store.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id="ses_fsm",+ priority="p3",+ state="queued",+ snapshot=snapshot,+ dispatch_text="legacy loopback input",+ )++ context = _context()+ manager._hydrate_delivery_context(context, _row(engine, delivery_id))+ controller = _memory_facts_controller()++ assert context.user_id == "local"+ assert (context.platform_specific or {}).get("memory_cli_admitted") is True+ assert controller.memory_capture_admitted(context) is Trueassert controller.memory_principal_for_context(context) == "principal:avibe:local"@@ -2227,6 +2261,7 @@ def test_durable_workbench_turn_restores_memory_admission_facts(from core.system_prompt_injection import memory_cli_prompt_admittedmanager, _other, engine, _engine_b, _starts = managers+ manager.controller.config.memory = SimpleNamespace(enabled=True)classifications: list[bool | None] = []routing_users: list[str | None] = []memory_users: list[str | None] = []@@ -2254,10 +2289,10 @@ def test_durable_workbench_turn_restores_memory_admission_facts()async def capture_start(_session_id, context, _text, **_kwargs):- classifications.append(context.is_ordinary_text)+ classifications.append(context.is_original_human_text)routing_users.append(context.user_id)memory_users.append(- facts_controller._memory_turn_facts(context, include_workdir=False).user_id+ facts_controller._memory_turn_facts(context).user_id)prompt_admitted = memory_cli_prompt_admitted(prompt_controller, context)payload = context.platform_specific or {}@@ -2278,8 +2313,10 @@ def test_durable_workbench_turn_restores_memory_admission_facts(session_id="ses_fsm",priority="p3",content="remember this",+ author_id="local",+ message_kind="original",metadata={- "_memory_user_id": "local",+ "_memory_user_id": "forged","_memory_cli_admitted": True,"_memory_ordinary_text": True,},@@ -2301,10 +2338,12 @@ def test_durable_workbench_turn_restores_memory_admission_facts(session_id="ses_fsm",platform="avibe",author="user",- source="user",- text="remember this",- metadata={- "_memory_user_id": "local",+ source="user",+ text="remember this",+ author_id="local",+ message_kind="original",+ metadata={+ "_memory_user_id": "forged","_memory_cli_admitted": True,"_memory_ordinary_text": True,},@@ -2317,7 +2356,7 @@ def test_durable_workbench_turn_restores_memory_admission_facts(asyncio.run(manager.recover_durable_delivery_state(service_restart=True))assert classifications == [True]- assert routing_users == ["user"]+ assert routing_users == ["local"]assert memory_users == ["local"]assert memory_cli_observations == [(True, True, (principal_id, project_id)),@@ -2366,148 +2405,57 @@ def test_durable_memory_cli_admission_fails_closed(assert admissions == [None][email protected]("launch_path", ["immediate", "fifo", "recovery"])[email protected]("reverse_order", [False, True], ids=["listed-order", "reverse-order"])@pytest.mark.parametrize(- ("other_label", "ordinary_marker", "cli_marker", "extra_metadata"),+ "message_kind",[- pytest.param(- "quick-reply",- False,- True,- {"quick_reply_for": "agent-message-1"},- id="ordinary-vs-quick-reply",- ),- pytest.param(- "forwarded",- False,- True,- {"forwarded": True},- id="ordinary-vs-forwarded",- ),- pytest.param(- "cli-not-admitted",- True,- False,- {},- id="cli-admission-difference",- ),- pytest.param(- "cli-malformed",- True,- 1,- {},- id="cli-admission-strict-bool",- ),- pytest.param(- "ordinary-malformed",- 1,- True,- {},- id="ordinary-classification-strict-bool",- ),+ "quick_reply",+ "forwarded",+ "edited",+ "system",+ "unknown",],)-def test_durable_batch_preserves_each_delivery_memory_admission_facts(+def test_non_original_message_kinds_do_not_merge_or_expand_admission(managers,- launch_path: str,- reverse_order: bool,- other_label: str,- ordinary_marker: object,- cli_marker: object,- extra_metadata: dict[str, object],+ message_kind: str,) -> None:- manager, _other, _engine, _engine_b, _starts = managers- ordinary_facts = (- "ordinary",- {- "_memory_ordinary_text": True,- "_memory_cli_admitted": True,- },- )- other_facts = (- other_label,- {- **extra_metadata,- "_memory_ordinary_text": ordinary_marker,- "_memory_cli_admitted": cli_marker,- },- )- fact_pair = [ordinary_facts, other_facts]- ordered_facts = list(reversed(fact_pair)) if reverse_order else fact_pair- starts: list[tuple[str, str, bool | None, bool, tuple[str, ...]]] = []- started_contexts: list[MessageContext] = []-- async def capture_start(_session_id, context, text, **kwargs):- payload = context.platform_specific or {}- started_contexts.append(context)- starts.append(- (- str(kwargs.get("logical_turn_id") or ""),- text,- context.is_ordinary_text,- payload.get("memory_cli_admitted") is True,- tuple(payload.get("delivery_ids") or ()),- )- )- _complete_capture_admission(context)-- manager._run = capture_start-- async def run() -> list[str]:- delivery_ids: list[str] = []- for index, (label, metadata) in enumerate(ordered_facts):- result = await manager.deliver(- DeliveryRequest(- session_id="ses_fsm",- priority="p3",- content=f"text-{label}",- metadata=metadata,- admission_only=(launch_path != "immediate" or index == 0),- ),- context=_context(),- )- assert result.delivery_id is not None- delivery_ids.append(result.delivery_id)-- if launch_path == "fifo":- assert await manager.drain_delivery_queue("ses_fsm")- elif launch_path == "recovery":- await manager.recover_durable_delivery_state(service_restart=True)-- assert len(starts) == 1- first_context = started_contexts[0]- turn_id = starts[0][0]- first_context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"- manager._active_identity = lambda _backend, _session_id, logical_id: (- logical_id,- f"native-{logical_id}",- )- manager.on_native_start(- first_context,- backend="codex",- runtime_key=f"runtime-key-{turn_id}",- runtime_turn_id=f"runtime-{turn_id}",- )- assert await manager.terminalize_turn(turn_id)- return delivery_ids-- delivery_ids = asyncio.run(run())+ manager, _other, engine, _engine_b, _starts = managers+ common = {+ "platform": "avibe",+ "source": "user",+ "author": "user",+ "author_id": "remote:alice",+ }+ rows = [+ {**common, "message_kind": "original"},+ {**common, "message_kind": message_kind},+ ]+ assert _collect_delivery_segment(rows) == [rows[0]]- assert [start[1:] for start in starts] == [- (- f"text-{label}",- metadata.get("_memory_ordinary_text") is True,- metadata.get("_memory_cli_admitted") is True,- (delivery_id,),+ delivery_id = delivery_store.new_delivery_id()+ with engine.begin() as conn:+ delivery_store.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id="ses_fsm",+ priority="p3",+ state="queued",+ snapshot=delivery_store.message_snapshot(+ scope_id=None,+ session_id="ses_fsm",+ platform="avibe",+ author="user",+ source="user",+ text="not original",+ author_id="remote:alice",+ message_kind=message_kind,+ ),+ dispatch_text="not original",)- for (label, metadata), delivery_id in zip(ordered_facts, delivery_ids)- ]- assert [start[1] for start in starts if start[2] is True] == [- f"text-{label}"- for label, metadata in ordered_facts- if metadata.get("_memory_ordinary_text") is True- ]+ context = _context()+ manager._hydrate_delivery_context(context, _row(engine, delivery_id))+ assert context.message_kind == message_kind+ assert context.is_original_human_text is Falsedef test_dispatch_uses_current_session_route_without_mutating_delivery_provenance(@@ -5873,16 +5821,20 @@ def test_reserved_attachment_only_submission_recovers_exact_dispatch_inputs(source="user",text="",content={"attachments": [{"token": token}]},+ message_kind="original",),dispatch_text="",)- dispatched: list[tuple[str, list[str]]] = []+ dispatched: list[tuple[str, list[str], str, bool, bool]] = []async def capture(_session_id, context, text, **_kwargs):dispatched.append((text,[str(item.local_path) for item in (context.files or [])],+ context.message_kind,+ context.is_original_human_text is True,+ context.is_original_human_attachment is True,))_complete_capture_admission(context)@@ -5890,7 +5842,7 @@ def test_reserved_attachment_only_submission_recovers_exact_dispatch_inputs(manager._run = captureasyncio.run(manager.recover_durable_delivery_state())- assert dispatched == [("", [str(attachment)])]+ assert dispatched == [("", [str(attachment)], "original", True, True)]assert _row(engine, delivery_id)["state"] == "claimed"diff --git a/tests/test_slack_app_mention_empty.py b/tests/test_slack_app_mention_empty.pyindex 6e216fb9e..a34acfaab 100644--- a/tests/test_slack_app_mention_empty.py+++ b/tests/test_slack_app_mention_empty.py@@ -135,7 +135,7 @@ class SlackAppMentionEmptyTests(unittest.IsolatedAsyncioTestCase):received["thread_id"] = context.thread_idreceived["text"] = textreceived["control_text"] = (context.platform_specific or {}).get("control_text")- received["is_ordinary_text"] = context.is_ordinary_text+ received["is_ordinary_text"] = context.is_original_human_textslack.register_callbacks(on_message=_on_message)slack.settings_manager = object()diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.pyindex 62b71b2e0..ae95986a5 100644--- a/tests/test_slack_dm_mentions.py+++ b/tests/test_slack_dm_mentions.py@@ -770,8 +770,8 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):async def _on_message(context, text):received.update(text=text,- ordinary_text=context.is_ordinary_text,- ordinary_attachment=context.is_ordinary_attachment,+ ordinary_text=context.is_original_human_text,+ ordinary_attachment=context.is_original_human_attachment,files=[file.name for file in context.files or ()],)diff --git a/tests/test_sse_broker.py b/tests/test_sse_broker.pyindex 996a58581..6a2361443 100644--- a/tests/test_sse_broker.py+++ b/tests/test_sse_broker.py@@ -135,6 +135,11 @@ def test_publish_survives_concurrent_subscribe_churn():try:while not stop.is_set():broker.publish("ping", {"n": 1})+ # Preserve sustained cross-thread contention without queuing an+ # unbounded number of callbacks ahead of the churn coroutine.+ # The lock race needs overlap, not event-loop starvation.+ if stop.wait(0.0005):+ breakexcept BaseException as exc: # noqa: BLE001errors.append(exc)diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex b916d97d7..9c735daa7 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -112,7 +112,7 @@ def test_group_message_uses_channel_require_mention_override() -> None:)bot.on_message_callback.assert_awaited_once()- assert bot.on_message_callback.await_args.args[0].is_ordinary_text is True+ assert bot.on_message_callback.await_args.args[0].is_original_human_text is Trueassert bot.on_message_callback.await_args.args[1] == "hello team"@@ -227,7 +227,7 @@ def test_photo_context_publishes_ordinary_attachment_fact_from_largest_photo() -)assert context is not None- assert context.is_ordinary_attachment is True+ assert context.is_original_human_attachment is Trueassert context.files is not Noneassert [file.url for file in context.files] == ["large"]diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.pyindex d9dfc481e..f36b0efdb 100644--- a/tests/test_ui_memory_routes.py+++ b/tests/test_ui_memory_routes.py@@ -1,5 +1,8 @@from __future__ import annotations+import ast+import builtins+from pathlib import Pathfrom typing import Anyimport pytest@@ -589,3 +592,108 @@ def test_memory_list_route_forwards_agent_origin()assert over_limit.status_code == 400assert len(calls) == 1+++def test_memory_list_ui_route_stays_host_owned_when_runtime_import_fails(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ """UI Memory routes stay host-owned when implementation imports are blocked."""++ tree = ast.parse(Path(ui_memory_routes.__file__).read_text(encoding="utf-8"))+ implementation_imports = [+ node.module+ for node in ast.walk(tree)+ if isinstance(node, ast.ImportFrom)+ and node.module+ and node.module.startswith("avibe_memory.")+ and node.module != "core.memory_loader"+ ]+ assert implementation_imports == []++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config()+ calls: list[dict[str, object]] = []++ async def memory_list(**kwargs):+ calls.append(kwargs)+ return {+ "status_code": 200,+ "body": {"status": "ok", "items": [], "next_cursor": None},+ }++ monkeypatch.setattr(internal_client, "memory_list", memory_list)+ real_import = builtins.__import__++ def guarded_import(name, *args, **kwargs):+ if name.startswith("avibe_memory.") and name != "core.memory_loader":+ raise RuntimeError(f"optional implementation initializer: {name}")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", guarded_import)+ from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTES++ client = app.test_client()+ settings = client.get(+ "/api/memory/settings",+ headers=_local_headers(),+ **_request_options(),+ )++ assert settings.status_code == 200+ assert settings.get_json()["status"] == "ok"++ async def memory_search(query, policy, **kwargs):+ assert query == "hello"+ assert policy["mode"] == "keyword"+ assert kwargs == {"user_key": "avibe:local", "project": None}+ return {"status_code": 200, "body": {"status": "ok", "items": []}}++ monkeypatch.setattr(internal_client, "memory_search", memory_search)+ search = client.post(+ "/api/memory/search",+ json={"query": "hello", "policy": {"mode": "keyword"}},+ headers=csrf_headers(client, BASE_URL),+ **_request_options(),+ )++ assert search.status_code == 200+ assert search.get_json() == {"status": "ok", "items": []}++ response = client.post(+ "/api/memory/list",+ json={"project": "all", "cursor": "a" * MEMORY_LIST_CURSOR_MAX_BYTES},+ headers=csrf_headers(client, BASE_URL),+ **_request_options(),+ )++ assert response.status_code == 200+ assert response.get_json() == {+ "status": "ok",+ "items": [],+ "next_cursor": None,+ }+ assert calls == [+ {+ "user_key": "avibe:local",+ "project": "all",+ "page": None,+ "cursor": "a" * MEMORY_LIST_CURSOR_MAX_BYTES,+ "limit": 20,+ "origin": None,+ }+ ]++ invalid = client.post(+ "/api/memory/list",+ json={"project": "all", "cursor": "a" * (MEMORY_LIST_CURSOR_MAX_BYTES + 1)},+ headers=csrf_headers(client, BASE_URL),+ **_request_options(),+ )++ assert invalid.status_code == 400+ assert invalid.get_json() == {+ "status": "failed",+ "error": "memory_invalid_input",+ }+ assert len(calls) == 1diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 47e2cbf4e..d77da0927 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -2440,6 +2440,37 @@ def test_config_restart_fallback_schedules_when_in_flight_finishes_after_marker(assert runtime.read_json(restart_supervisor._pending_restart_path()) is None+def test_terminal_restart_failure_does_not_block_config_restart_retry(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ from vibe import restart_supervisor+ from vibe import runtime++ runtime.get_restart_status_path().parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(+ runtime.get_restart_status_path(),+ {+ "ok": False,+ "state": "failed",+ "job_id": "failed-upgrade",+ "supervisor_pid": 4242,+ "error": "new release failed readiness",+ },+ )+ scheduled: list[dict] = []+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4242)+ monkeypatch.setattr(runtime, "read_status", lambda: {"service_pid": None, "ui_pid": 22})+ monkeypatch.setattr(+ restart_supervisor,+ "schedule_restart",+ lambda **kwargs: scheduled.append(kwargs) or {"job_id": "retry"},+ )++ result = ui_server._schedule_service_restart_for_config_fallback()++ assert result == {"ok": True, "restart": {"job_id": "retry"}}+ assert scheduled == [{"delay_seconds": 0.0, "trigger": "web-ui-config", "scope": "service"}]++def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))ui_dist = tmp_path / "dist"diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.pyindex 8e8ba6665..a94b7dfec 100644--- a/tests/test_ui_server_install.py+++ b/tests/test_ui_server_install.py@@ -153,6 +153,56 @@ def test_dependency_install_route_allows_memory_runtime(monkeypatch, tmp_path):assert response.get_json()["backend"] == "memory-runtime"+def test_dependency_install_route_allows_memory_package(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.setattr(+ api,+ "start_dependency_install_job",+ lambda dep: {+ "ok": True,+ "job_id": "job-memory-package",+ "backend": dep,+ "status": "running",+ },+ )++ client = app.test_client()+ response = client.post(+ "/api/dependencies/memory-package/install",+ headers=csrf_headers(client, "http://127.0.0.1:15131"),+ base_url="http://127.0.0.1:15131",+ )++ assert response.status_code == 200+ assert response.get_json()["backend"] == "memory-package"+++def test_dependency_install_route_preserves_structured_memory_package_rejection(+ monkeypatch,+ tmp_path,+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ rejection = {+ "ok": False,+ "status": "rejected",+ "message": "memory_package_source_build",+ "output": None,+ "reason": "memory_package_source_build",+ "action_class": "operator_only",+ }+ monkeypatch.setattr(api, "start_dependency_install_job", lambda _dep: rejection)++ client = app.test_client()+ response = client.post(+ "/api/dependencies/memory-package/install",+ headers=csrf_headers(client, "http://127.0.0.1:15131"),+ base_url="http://127.0.0.1:15131",+ )++ assert response.status_code == 200+ assert response.get_json() == rejection++def test_install_job_fails_when_runtime_refresh_fails(monkeypatch):monkeypatch.setattr(api, "is_agent_backend", lambda name: name == "codex")monkeypatch.setattr(api, "supports_runtime_refresh", lambda name: name == "codex")diff --git a/tests/test_ui_server_reload.py b/tests/test_ui_server_reload.pyindex 8272c1cdb..12b1532c6 100644--- a/tests/test_ui_server_reload.py+++ b/tests/test_ui_server_reload.py@@ -142,7 +142,7 @@ def test_ui_reload_routes_replacement_output_through_runtime_log_sinks(monkeypat"core.services.settings.load_config",lambda *a, **k: _config_with_tunnel(enabled=False),)- monkeypatch.setattr("core.memory.ui_access._process_secret", memory_ui_secret)+ monkeypatch.setattr("vibe.memory_ui_access._process_secret", memory_ui_secret)monkeypatch.setattr(threading, "Thread", _ImmediateThread)monkeypatch.setattr(runtime, "read_status", lambda: {"state": "running", "service_pid": 111})monkeypatch.setattr(runtime, "write_status", lambda *args: captured.setdefault("status", args))diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.pyindex 7081c2757..e72c37361 100644--- a/tests/test_ui_session_stream.py+++ b/tests/test_ui_session_stream.py@@ -248,6 +248,10 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):with (patch("vibe.internal_client.dispatch_async", dispatch_mock),patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),+ patch(+ "vibe.ui_server._workbench_author_id",+ return_value="remote:user-a",+ ),patch("vibe.ui_server.is_direct_loopback_memory_request", return_value=False),):client = app.test_client()@@ -267,7 +271,7 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):assert payload["author"] == "user"assert payload["author_id"] == "remote:user-a"assert "_web_push_user_key" not in payload["metadata"]- assert payload["metadata"]["_memory_cli_admitted"] is False+ assert not any(key.startswith("_memory_") for key in payload["metadata"])assert payload["text"] == "no stream"assert payload["draft_advanced"] is Trueassert payload["draft"]["text"] == ""@@ -277,8 +281,36 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):sent = dispatch_mock.await_args.args[0]assert sent["session_id"] == session_idassert sent["text"] == "no stream"- assert sent["memory_cli_admitted"] is False- assert sent["is_ordinary_text"] is True+ assert sent["author_id"] == "remote:user-a"+ assert sent["message_kind"] == "original"+ assert "user_id" not in sent+ assert "memory_cli_admitted" not in sent+ assert "is_ordinary_text" not in sent+++def test_lan_workbench_message_has_no_memory_author(isolated_state, tmp_path):+ from vibe.ui_server import app++ _, session_id = _make_session(tmp_path)+ dispatch = _accepted_dispatch(session_id)+ with (+ patch("vibe.internal_client.dispatch_async", dispatch),+ patch("vibe.ui_server._web_push_user_key", return_value="local"),+ patch("vibe.ui_server.is_direct_loopback_memory_request", return_value=False),+ patch("vibe.ui_server._load_remote_access_config", return_value=None),+ ):+ client = app.test_client()+ response = client.post(+ f"/api/sessions/{session_id}/messages",+ json={"text": "LAN input"},+ headers=csrf_headers(client),+ )++ assert response.status_code == 201+ assert response.get_json()["author_id"] is None+ sent = dispatch.await_args.args[0]+ assert sent["author_id"] is None+ assert "memory_cli_admitted" not in sent@pytest.mark.parametrize(@@ -288,7 +320,7 @@ def test_route_fire_and_forgets_dispatch(isolated_state, tmp_path):{"text": "forwarded text", "metadata": {"forwarded": True}},],)-def test_workbench_side_actions_are_not_marked_as_ordinary_memory_input(+def test_workbench_side_actions_have_fail_closed_core_message_kinds(isolated_state,tmp_path,payload,@@ -306,14 +338,19 @@ def test_workbench_side_actions_are_not_marked_as_ordinary_memory_input()assert response.status_code == 201- assert dispatch.await_args.args[0]["is_ordinary_text"] is False+ expected_kind = (+ "quick_reply"+ if "quick_reply_for" in payload.get("metadata", {})+ else "forwarded"+ )+ assert dispatch.await_args.args[0]["message_kind"] == expected_kindassert response.get_json()["draft_advanced"] is ("quick_reply_for" not in payload.get("metadata", {}))-def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(+def test_workbench_text_uses_authenticated_author_and_core_message_kind(isolated_state,tmp_path,):@@ -338,29 +375,11 @@ def test_workbench_memory_text_is_persisted_and_dispatched_as_ordinary_input(assert response_payload["text"] == "/memory status"payload = dispatch.await_args.args[0]assert payload["text"] == "/memory status"- assert payload["user_id"] == "local"+ assert payload["author_id"] == "local"assert payload["message_id"] == response_payload["id"]- assert payload["memory_cli_admitted"] is True--- "session_payload,expected",- [- ({"sub": "user-a"}, "remote:user-a"),- ({}, None),- (None, None),- ],-)-def test_remote_workbench_memory_identity_requires_a_stable_subject(session_payload, expected):- from vibe.ui_server import app, _workbench_memory_user_id-- with (- app.test_request_context("/chat/session", headers={"Cookie": "avibe_remote_session=session"}),- patch("vibe.ui_server.is_direct_loopback_memory_request", return_value=False),- patch("vibe.ui_server._load_remote_access_config", return_value=object()),- patch("vibe.ui_server._resolved_remote_session_payload", return_value=session_payload),- ):- assert _workbench_memory_user_id() == expected+ assert payload["message_kind"] == "original"+ assert "memory_cli_admitted" not in payload+ assert "user_id" not in payloaddef test_workbench_dispatch_propagates_attachment_and_resolved_identity(@@ -398,7 +417,8 @@ def test_workbench_dispatch_propagates_attachment_and_resolved_identity(assert response.status_code == 201payload = dispatch.await_args.args[0]- assert payload["user_id"] == "local"+ assert payload["author_id"] == "local"+ assert payload["message_kind"] == "original"assert payload["message_id"] == response.get_json()["id"]assert len(payload["files"]) == 1assert payload["files"][0]["name"] == "diagram.png"@@ -433,6 +453,7 @@ def test_route_reads_the_materialized_message_id_for_a_merged_batch(text="older queued input",metadata={"_web_push_user_key": "remote:user-a"},author_id="remote:user-a",+ message_kind="original",),dispatch_text="older queued input",now="2026-01-01T00:00:00Z",@@ -479,6 +500,10 @@ def test_route_reads_the_materialized_message_id_for_a_merged_batch(with (patch("vibe.internal_client.dispatch_async", AsyncMock(side_effect=dispatch)),patch("vibe.ui_server._web_push_user_key", return_value="remote:user-a"),+ patch(+ "vibe.ui_server._workbench_author_id",+ return_value="remote:user-a",+ ),):client = app.test_client()response = client.post(diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.pyindex 7c29c1b62..fbd1e71b9 100644--- a/tests/test_ui_show_pages.py+++ b/tests/test_ui_show_pages.py@@ -11642,6 +11642,7 @@ def test_startup_dependency_reconcile_prewarms_runtime_after_prepare(monkeypatchreturn SimpleNamespace(available=True, reason=None)monkeypatch.setattr("vibe.api.reconcile_startup_dependencies", fake_reconcile)+ monkeypatch.setattr("vibe.ui_server._server", SimpleNamespace(started=True))monkeypatch.setattr("vibe.api.startup_show_page_prewarm_targets",lambda: {@@ -11691,10 +11692,41 @@ def test_startup_dependency_reconcile_does_not_prewarm_policy_skip(monkeypatch):"core.show_runtime.prewarm_show_runtime",lambda: pytest.fail("a policy skip must not enter prewarm"),)+ monkeypatch.setattr("vibe.ui_server._server", SimpleNamespace(started=True))asyncio.run(_reconcile_startup_dependencies_task())+def test_startup_dependency_reconcile_waits_until_the_ui_host_is_ready(monkeypatch):+ from vibe.ui_server import _reconcile_startup_dependencies_task++ server = SimpleNamespace(started=False)+ calls: list[str] = []+ monkeypatch.setattr("vibe.ui_server._server", server)+ monkeypatch.setattr(+ "vibe.api.reconcile_startup_dependencies",+ lambda: calls.append("reconcile")+ or {+ "ok": True,+ "show_runtime": {+ "ok": True,+ "policy": {"state": "skipped"},+ "install": {"state": "absent"},+ },+ },+ )++ async def run() -> None:+ task = asyncio.create_task(_reconcile_startup_dependencies_task())+ await asyncio.sleep(0.01)+ assert calls == []+ server.started = True+ await asyncio.wait_for(task, timeout=1.0)++ asyncio.run(run())+ assert calls == ["reconcile"]++def test_show_runtime_proxy_logs_entry_timing(monkeypatch, tmp_path, caplog):caplog.set_level("INFO")monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex cbf271ab5..3c8a67ca5 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -9,6 +9,7 @@ import sysfrom types import SimpleNamespacefrom pathlib import Pathfrom typing import Any+from unittest.mock import Mockimport pytest@@ -18,10 +19,13 @@ from vibe import api, cli, runtimefrom vibe.runtime import ServiceLauncherfrom vibe.upgrade import (AtomicActivation,+ MemoryRequirementUnreadableError,UpgradePlan,build_upgrade_plan,+ configured_memory_enabled,has_newer_version,get_current_vibe_bin_dir,+ get_current_uv_tool_dir,get_latest_version_info,get_restart_command,get_restart_environment,@@ -30,10 +34,8 @@ from vibe.upgrade import (defer_upgrade_activation,get_running_vibe_path,get_safe_cwd,- installed_package_name,pinned_package_spec,- RollbackTarget,- rollback_target,+ execute_upgrade_plan,restart_is_pending,)@@ -42,22 +44,14 @@ from vibe.upgrade import (def _tree_is_not_an_installed_distribution(monkeypatch):"""Every test here describes a machine, not the machine running the tests.- `installed_package_name()` asks this process's own metadata which- distribution provides `vibe`, and the answer differs by checkout: a developer- running from a source tree gets nothing, while CI installs the package first- and gets `avibe-os`. Tests written against the first answer pass locally and- then fail on a runner for a reason that has nothing to do with the change --- `test_a_spec_that_cannot_carry_a_pin_is_refused` did exactly that, because an- installed name outranks the configured spec whose refusal it was asserting.-- Answering `[]` here is the honest state for a checkout, and it is the state- every test in this module was already written against. Only the ambient- metadata is removed; the interpreter-path heuristic stays live, so a test can- still hand in a uv tool path and be answered from it, and a test that wants a- measured name sets one explicitly.+ Installed provider metadata differs between a source checkout and CI. Empty+ provider metadata keeps forward-plan tests deterministic; tests for a mixed+ provider state replace it explicitly."""monkeypatch.setattr("vibe.upgrade._distributions_providing_this_package", lambda: [])+ monkeypatch.setattr("vibe.upgrade.memory_package_installed", lambda: False)+def test_build_upgrade_plan_stages_custom_legacy_uv_launcher(monkeypatch):@@ -644,7 +638,6 @@ def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_pathcandidate.write_text("candidate\n", encoding="utf-8")candidate_python.write_text("python\n", encoding="utf-8")activation = AtomicActivation(launcher, candidate, tmp_path / "generation")- rollback = RollbackTarget("3.0.10", "vibe-remote", ServiceLauncher("old-python", "old-main"))calls = {}monkeypatch.setattr(upgrade, "_candidate_python", lambda _candidate: candidate_python)@@ -666,7 +659,6 @@ def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_pathprocess = defer_upgrade_activation(activation,parent_pid=123,- rollback_to=rollback,restart_required=True,prepare_show_runtime=True,)@@ -904,24 +896,15 @@ def test_build_upgrade_plan_uses_env_package_spec(monkeypatch):#: How each installer spells "do it even though you believe it is already done".#: Written as a mapping rather than as two assertions so that an installer added#: to `build_upgrade_plan` later fails this test until someone decides what its-#: word is, instead of silently shipping a rollback path that can no-op.+#: word is, instead of silently shipping an exact install that can no-op.FORCES_THE_INSTALL = {"uv": "--force", "pip": "--force-reinstall"}-def test_a_pinned_plan_never_asks_for_an_upgrade_and_always_forces_the_install(monkeypatch):- # Two ways for a rollback command to install nothing and still exit 0, one- # per word, and both silent on every installer path.- #- # Asking for an upgrade resolves forward to the exact release being rolled- # back FROM: uv resolves past the pin, pip declines to move backwards at all.- #- # Not forcing leaves the installer free to decide the pin is already- # satisfied -- and on the case this change exists for, it is. Installing- # `avibe-os` over a `vibe-remote` machine never uninstalls `vibe-remote`, so- # that distribution's metadata still stands and still claims the old version,- # while the files under `vibe/` are the new release's, written over the top.- # `pip install vibe-remote==<old>` reads as satisfied, pip does nothing, and- # the supervisor starts the failed generation again and calls it a recovery.+def test_an_exact_plan_never_asks_for_an_upgrade_and_always_forces_the_install(monkeypatch):+ # The explicit Memory install targets the running core release. Asking for an+ # upgrade would widen that request, while omitting force lets the installer+ # declare the already-present core requirement satisfied without applying the+ # matching optional package.monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)@@ -931,6 +914,7 @@ def test_a_pinned_plan_never_asks_for_an_upgrade_and_always_forces_the_install(mvibe_path="/custom/bin/vibe",base_env={"PATH": "/usr/bin"},version="3.0.10",+ package_name="avibe-os",)assert uv_plan.method == "uv"assert uv_plan.command == [@@ -943,12 +927,14 @@ def test_a_pinned_plan_never_asks_for_an_upgrade_and_always_forces_the_install(m"--force",]assert "--upgrade" not in uv_plan.command+ assert uv_plan.env["UV_TOOL_DIR"] == "/tmp/.local/share/uv/tools"pip_plan = build_upgrade_plan(python_executable="/usr/bin/python3",uv_path=None,base_env={"PATH": "/usr/bin"},version="3.0.10",+ package_name="avibe-os",)assert pip_plan.method == "pip"assert pip_plan.command == [@@ -973,23 +959,7 @@ def _metadata_records(monkeypatch, distribution: str, version: str) -> None:def test_a_forward_upgrade_forces_the_install_once_metadata_stops_describing_the_code(monkeypatch):- """The rollback's own no-op, one release later and with a person watching.-- A rollback installs `vibe-remote==3.0.10` over a machine whose forward upgrade- installed `avibe-os==3.0.11`, and pip never uninstalls the distribution it- replaced. So the tree ends up holding both: the files under `vibe/` are 3.0.10,- and `avibe-os` still records 3.0.11 with nothing on disk behind it.-- Then `vibe upgrade` runs. It compares this process's 3.0.10 against the- published 3.0.11 and decides to install; pip reads `avibe-os==3.0.11` as- already satisfied and does nothing; the command reports success and the- machine keeps running 3.0.10 -- silently, indefinitely, and now on the path a- user invokes by hand.-- So `--force-reinstall` is not a property of pinned plans, it is a property of- asking for a version that is not the version on disk. Measured from our own- two answers, never read off the metadata that is the thing in doubt.- """+ """A forward install cannot trust stale metadata over the running files."""monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)@@ -1010,18 +980,8 @@ def test_a_forward_upgrade_forces_the_install_once_metadata_stops_describing_theassert "--force-reinstall" in plan.command-def test_the_rename_pair_left_by_a_rollback_forces_the_next_install(monkeypatch):- """The state this check exists for is the one where two distributions are present.-- A rollback across the rename installs `vibe-remote==3.0.10` over a tree whose- forward upgrade installed `avibe-os==3.0.11`, and pip does not uninstall the- distribution it replaced. So both are recorded and only one of them can be- describing the files under `vibe/`. Asking a single distribution -- or- treating "more than one" as unreadable -- would make this exact machine the- one machine that answers "metadata agrees", which is how the no-op ships:- the next upgrade asks pip for a version `avibe-os` already claims, pip does- nothing, and the instance keeps running the rolled-back code forever.- """+def test_a_stale_rename_pair_forces_the_next_install(monkeypatch):+ """Two disagreeing distribution records cannot make an upgrade a no-op."""monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)@@ -1106,196 +1066,9 @@ def test_an_unknown_install_shape_is_never_forced_on_a_guess(monkeypatch, case,assert "--force-reinstall" not in plan.command, case-def test_a_rollback_pins_the_distribution_the_install_actually_came_from(monkeypatch):- # Which distribution published the running version and which one the next- # upgrade should ask for are different questions, and on a machine that- # predates the rename they have different answers. Going forward wants the- # configured spec -- that is what the rename is for. Going back wants this,- # because `avibe-os==2.x` names a release that was never published under that- # name, so the rollback resolves to nothing and the instance stays dark.- monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")-- legacy = "/home/ai/.local/share/uv/tools/vibe-remote/bin/python"- assert pinned_package_spec("2.9.4", python_executable=legacy) == "vibe-remote==2.9.4"- plan = build_upgrade_plan(- python_executable=legacy,- uv_path="/usr/local/bin/uv",- base_env={"PATH": "/usr/bin"},- version="2.9.4",- )- assert "vibe-remote==2.9.4" in plan.command- assert not any(argument.startswith("avibe-os") for argument in plan.command)-- # An install whose path says nothing about a distribution -- pip into a shared- # environment -- has only the configured spec to go on, and gets it.- assert pinned_package_spec("3.0.10", python_executable="/usr/bin/python3") == "avibe-os==3.0.10"---def test_the_rename_pair_still_names_the_distribution_that_describes_the_code(monkeypatch):- """Two providers is not an unreadable machine, it is the aftermath of a rollback.-- Installing `avibe-os` over a `vibe-remote` machine never uninstalls the older- distribution, so once a rollback has crossed the rename the tree holds both- for good. Every upgrade after that measures its rollback target in this state,- which is why reading two providers as unanswerable does not cost one recovery- -- it costs every recovery the machine will ever attempt.-- The metadata is what tells them apart: `avibe-os` records the release that- failed, `vibe-remote` records the files that are running. Naming neither left- `package=None`, `pinned_package_spec` fell back to the configured forward- name, and `avibe-os==2.9.0` was never published under that name -- so the one- recovery attempt could only fail, on an instance that is already down.- """-- monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")- monkeypatch.setattr(- "vibe.upgrade._distributions_providing_this_package",- lambda: ["avibe-os", "vibe-remote"],- )- recorded = {"avibe-os": "3.0.11", "vibe-remote": "2.9.0"}- monkeypatch.setattr("importlib.metadata.version", lambda name: recorded[name])- monkeypatch.setattr("vibe.__version__", "2.9.0", raising=False)-- assert installed_package_name() == "vibe-remote"-- # And the consequence the name is measured for: the pin this machine's next- # failed upgrade rolls back to names a release that exists.- launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")- monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)- target = rollback_target()- assert target is not None and target.package == "vibe-remote"- assert pinned_package_spec(target.version, package_name=target.package) == "vibe-remote==2.9.0"---def test_providers_that_cannot_be_told_apart_are_left_to_the_path(monkeypatch):- """Metadata answers this only while it distinguishes them.-- Two distributions recording the same release is a vendored or mid-rename- environment, not a rollback, and there is nothing in the metadata to prefer- one name over the other. Guessing would put the pin on a distribution that may- never have published the version -- the same failure, arrived at from the- opposite direction -- so the interpreter path answers instead, and `None` when- it cannot either.- """-- monkeypatch.setattr(- "vibe.upgrade._distributions_providing_this_package",- lambda: ["avibe-os", "vibe-remote"],- )- monkeypatch.setattr("importlib.metadata.version", lambda name: "3.0.11")- monkeypatch.setattr("vibe.__version__", "3.0.11", raising=False)-- monkeypatch.setattr("vibe.upgrade.sys.executable", "/usr/bin/python3")- assert installed_package_name() is None-- monkeypatch.setattr("vibe.upgrade.sys.executable", "/home/ai/.local/share/uv/tools/vibe-remote/bin/python")- assert installed_package_name() == "vibe-remote"---def test_a_spec_that_cannot_carry_a_pin_is_refused(monkeypatch):- # The alternative to refusing is falling back to the unpinned spec, which is- # the reinstall-the-failure command above. Whoever configured a wheel path or- # an index URL as the upgrade source gets a rollback that fails loudly instead- # of one that lies. The message must not quote the spec: it can be an index- # URL carrying credentials, and it is written to a restart log.- monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "https://user:[email protected]/simple/avibe-os")-- with pytest.raises(ValueError) as refusal:- pinned_package_spec("3.0.10")- assert "secret" not in str(refusal.value)-- monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)- monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)- with pytest.raises(ValueError):- build_upgrade_plan(- python_executable="/usr/bin/python3",- uv_path=None,- base_env={"PATH": "/usr/bin"},- version="3.0.10",- )---def test_a_tree_with_no_published_release_has_no_rollback_target(monkeypatch):- # A source checkout, an editable install, and a regression build all report- # the same placeholder version, which names no release. Handing it on as a- # target buys an index round-trip that fails, and then tells whoever is- # looking at a dark instance that the rollback mechanism is broken, when the- # truth is that this install never had a release to go back to.- from vibe import UNKNOWN_VERSION-- monkeypatch.setattr("vibe.__version__", UNKNOWN_VERSION, raising=False)- assert rollback_target() is None-- # And a tree that does name a release answers with the distribution and the- # install too, in one value: all three are read here, in the process that- # still predates the install, and there is no way to obtain one without the- # others. The install matters as much as the version -- a rollback across the- # `vibe-remote` -> `avibe-os` rename reinstalls into a directory this process- # is not running out of, so a target that named only the version would be- # restored correctly and then started from the wrong generation.- launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")- monkeypatch.setattr("vibe.__version__", "3.0.10", raising=False)- monkeypatch.setattr("vibe.upgrade.installed_package_name", lambda *args, **kwargs: "vibe-remote")- monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)- assert rollback_target() == RollbackTarget(version="3.0.10", package="vibe-remote", launcher=launcher)---REPO_ROOT = Path(__file__).resolve().parents[1]-#: Everything shipped to a user's machine.-SHIPPED_SOURCE_ROOTS = ("main.py", "config", "core", "modules", "storage", "vibe")---def test_only_the_plan_builder_can_ask_what_this_install_is():- """One caller, found by looking rather than by remembering.-- The measurement has always been documented as something to take before the- install and never after, and both upgrade paths took it after anyway --- inside `if result.returncode == 0:`, describing an install that by then had- already been overwritten. A rule that lives in a docstring is enforced by- whoever happens to have read it.-- Moving it into `UpgradePlan` removes the ordering from every caller: a plan- is what produces the command, so the measurement cannot happen later than the- install unless someone reaches past the plan. This counts over the whole- shipped tree so that reaching past it fails here, when it is written, rather- than on a machine that predates the rename months later.- """-- callers = {}- for root in SHIPPED_SOURCE_ROOTS:- target = REPO_ROOT / root- for source in [target] if target.is_file() else sorted(target.rglob("*.py")):- tree = ast.parse(source.read_text(encoding="utf-8"))- calls = sum(- 1- for node in ast.walk(tree)- if isinstance(node, ast.Call)- and (getattr(node.func, "id", None) or getattr(node.func, "attr", None)) == "rollback_target"- )- if calls:- callers[source.relative_to(REPO_ROOT).as_posix()] = calls-- assert callers == {"vibe/upgrade.py": 1}---def test_the_plan_that_installs_carries_what_it_is_replacing(monkeypatch):- # A forward plan describes an install that is about to stop existing, so it- # takes the measurement while there is still something to measure. A pinned- # plan IS the rollback -- the process building one is the release that failed- # -- so measuring there would hand the failure forward as its own recovery- # target, which is the shape of every way this has gone wrong so far.- launcher = ServiceLauncher(python="/uv/tools/vibe-remote/bin/python", main="/uv/tools/vibe-remote/service_main.py")- monkeypatch.setattr("vibe.__version__", "3.0.10", raising=False)- monkeypatch.setattr("vibe.upgrade.installed_package_name", lambda *args, **kwargs: "vibe-remote")- monkeypatch.setattr("vibe.runtime.current_service_launcher", lambda: launcher)+def test_exact_package_spec_uses_the_explicit_distribution() -> None:+ assert pinned_package_spec("3.0.10", package_name="avibe-os") == "avibe-os==3.0.10"- forward = build_upgrade_plan(python_executable="/usr/bin/python3", uv_path=None, base_env={"PATH": "/usr/bin"})- assert forward.rollback_to == RollbackTarget(version="3.0.10", package="vibe-remote", launcher=launcher)-- pinned = build_upgrade_plan(- python_executable="/usr/bin/python3", uv_path=None, base_env={"PATH": "/usr/bin"}, version="3.0.9"- )- assert pinned.rollback_to is Nonedef test_build_upgrade_plan_finds_uv_outside_current_path(monkeypatch):@@ -1342,6 +1115,17 @@ def test_get_current_vibe_bin_dir_resolves_launcher_target(monkeypatch):assert bin_dir == "/home/test/.local/bin"+ "executable",+ (+ "/home/test/.local/share/uv/tools/avibe-os/bin/python",+ "/home/test/.avibe/runtime/install-generations/abc/uv/tools/avibe-os/bin/python",+ ),+)+def test_get_current_uv_tool_dir_preserves_the_logical_running_generation(executable):+ assert get_current_uv_tool_dir(executable) == str(Path(executable).parents[2])++def test_get_latest_version_info_uses_override_metadata_url(monkeypatch, tmp_path):metadata_path = tmp_path / "metadata.json"metadata_path.write_text('{"info": {"version": "9999.0.0"}}', encoding="utf-8")@@ -1614,28 +1398,22 @@ def test_get_restart_environment_normalizes_relative_pythonpath_entries(monkeypaassert env["PYTHONPATH"] == f"{source_root}{os.pathsep}{tmp_path}{os.pathsep}{tmp_path / 'src'}"-#: A machine that predates the rename, as its own plan describes it. The upgrade-#: paths below cannot be handed this any other way, which is the point: the-#: measurement is a field of the plan precisely so that no caller is left with an-#: ordering to remember, and a test that could still inject it late would be-#: describing a seam that no longer exists.-LEGACY_INSTALL = RollbackTarget(- version="3.0.10",- package="vibe-remote",- launcher=ServiceLauncher("/uv/tools/vibe-remote/bin/python", "/uv/tools/vibe-remote/service_main.py"),-)-def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):plan = UpgradePlan(command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],env={"UV_TOOL_BIN_DIR": "/custom/bin"},method="uv",- rollback_to=LEGACY_INSTALL,)calls: dict[str, Any] = {}- monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "3.0.15"})+ monkeypatch.setattr(+ api,+ "build_upgrade_plan",+ lambda **kwargs: calls.setdefault("plan_kwargs", kwargs) and plan,+ )monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)monkeypatch.setattr(api, "schedule_restart", lambda **kwargs: calls.setdefault("restart_kwargs", kwargs))@@ -1658,6 +1436,7 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):assert calls["run_kwargs"]["text"] is Trueassert calls["run_kwargs"]["timeout"] == 1800assert calls["run_kwargs"]["env"] == plan.env+ assert calls["plan_kwargs"]["target_version"] == "3.0.15"safe_cwd = calls["run_kwargs"].get("cwd")assert safe_cwd and os.path.isabs(safe_cwd), f"subprocess.run cwd must be an absolute path, got {safe_cwd!r}"assert calls["restart_kwargs"] == {@@ -1665,15 +1444,88 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):"vibe_path": "/custom/bin/vibe","trigger": "upgrade","prepare_show_runtime": True,- # The install this process was running, taken BEFORE it was replaced and- # carried here by the plan that replaced it: what the restart reinstalls- # if it cannot bring the new one up. Version, distribution and launcher- # together, because a pin needs the first two and a machine that predates- # the rename does not answer "avibe-os" for either.- "rollback_to": LEGACY_INSTALL,}+def test_memory_indep_025_failed_upgrade_is_terminal_and_retryable(monkeypatch):+ plan = UpgradePlan(+ command=["/usr/bin/python3", "-m", "pip", "install", "--upgrade", "avibe-os"],+ env=None,+ method="pip",+ )+ restart = Mock(return_value={"job_id": "retry-restart"})+ install = Mock(+ side_effect=[+ subprocess.CompletedProcess(+ plan.command,+ 1,+ stdout="",+ stderr="resolver rejected the release",+ ),+ subprocess.CompletedProcess(+ plan.command,+ 0,+ stdout="installed on retry",+ stderr="",+ ),+ ]+ )++ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)+ monkeypatch.setattr(api, "get_version_info", lambda: {"latest": "3.0.15"})+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)+ monkeypatch.setattr(api, "restart_is_pending", lambda: False)+ monkeypatch.setattr(+ api,+ "verify_python_environment",+ lambda _python: SimpleNamespace(ok=True, detail=""),+ )+ monkeypatch.setattr(api, "schedule_restart", restart)+ monkeypatch.setattr(api.subprocess, "run", install)++ failed = api.do_upgrade(auto_restart=True)+ succeeded = api.do_upgrade(auto_restart=True)++ assert failed == {+ "ok": False,+ "message": "Upgrade failed",+ "output": "resolver rejected the release",+ "restarting": False,+ }+ assert succeeded == {+ "ok": True,+ "message": "Upgrade successful. Restarting...",+ "output": "installed on retry",+ "restarting": True,+ }+ assert [call.args[0] for call in install.call_args_list] == [+ plan.command,+ plan.command,+ ]+ restart.assert_called_once()++def test_do_upgrade_blocks_mutation_when_memory_requirement_is_unreadable(+ monkeypatch,+) -> None:+ monkeypatch.setattr(+ api,+ "configured_memory_enabled",+ Mock(side_effect=MemoryRequirementUnreadableError()),+ )+ plan = Mock(side_effect=AssertionError("unreadable requirement built a plan"))+ monkeypatch.setattr(api, "build_upgrade_plan", plan)+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")++ result = api.do_upgrade()++ assert result["ok"] is False+ assert result["reason"] == "memory_requirement_unreadable"+ assert result["restarting"] is False+ plan.assert_not_called()++def test_do_upgrade_auto_restart_does_not_block_on_runtime_prepare(monkeypatch):plan = UpgradePlan(command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],@@ -1682,6 +1534,7 @@ def test_do_upgrade_auto_restart_does_not_block_on_runtime_prepare(monkeypatch):)events: list[str] = []+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)@@ -1710,6 +1563,7 @@ def test_do_upgrade_running_runtime_honors_show_runtime_skip_for_restart(monkeyp)calls: dict[str, Any] = {}+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)monkeypatch.setenv("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "1")monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")@@ -1735,6 +1589,7 @@ def test_do_upgrade_reports_restart_scheduling_failure_as_partial_success(monkeymethod="uv",)+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)@@ -1766,6 +1621,7 @@ def test_do_upgrade_without_auto_restart_prepares_runtime(monkeypatch):)calls: dict[str, Any] = {}+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(api, "_runtime_process_was_running", lambda: True)@@ -1808,6 +1664,7 @@ def test_do_upgrade_keeps_runtime_stopped_when_it_was_not_running(monkeypatch):)calls: dict[str, Any] = {}+ monkeypatch.setattr(api, "configured_memory_enabled", lambda: False)monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)monkeypatch.setattr(api, "get_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)@@ -1882,13 +1739,17 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],env={"UV_TOOL_BIN_DIR": "/custom/bin"},method="uv",- rollback_to=LEGACY_INSTALL,)calls: dict[str, Any] = {}+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: False)monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")- monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(+ cli,+ "build_upgrade_plan",+ lambda **kwargs: calls.setdefault("plan_kwargs", kwargs) and plan,+ )monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: True)def fake_schedule_restart(**kwargs):@@ -1914,6 +1775,7 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):assert calls["kwargs"]["capture_output"] is Trueassert calls["kwargs"]["text"] is Trueassert calls["kwargs"]["env"] == plan.env+ assert calls["plan_kwargs"]["target_version"] == "2.2.0"assert "cwd" in calls["kwargs"], "subprocess.run must specify cwd to avoid stale venv cwd"assert os.path.isabs(calls["kwargs"]["cwd"]), f"cwd must be absolute, got {calls['kwargs']['cwd']!r}"assert calls["restart_kwargs"] == {@@ -1921,8 +1783,6 @@ def test_cmd_upgrade_uses_upgrade_plan_env(monkeypatch):"vibe_path": "/custom/bin/vibe","trigger": "upgrade","prepare_show_runtime": True,- # See the do_upgrade case: the restart is handed the install to fall back to.- "rollback_to": LEGACY_INSTALL,}@@ -1934,6 +1794,7 @@ def test_cmd_upgrade_running_runtime_honors_show_runtime_skip_for_restart(monkey)calls: dict[str, Any] = {}+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: False)monkeypatch.setenv("VIBE_INSTALL_SKIP_SHOW_RUNTIME", "true")monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")@@ -1962,6 +1823,7 @@ def test_cmd_upgrade_reports_restart_scheduling_failure_as_partial_success(monkemethod="uv",)+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: False)monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)@@ -1993,6 +1855,7 @@ def test_cmd_upgrade_keeps_runtime_stopped_when_it_was_not_running(monkeypatch):)calls: dict[str, Any] = {}+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: False)monkeypatch.setattr(cli, "get_latest_version", lambda: {"error": None, "has_update": True, "latest": "2.2.0"})monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")monkeypatch.setattr(cli, "build_upgrade_plan", lambda **kwargs: plan)@@ -2032,6 +1895,531 @@ def test_cmd_upgrade_skips_install_when_already_latest(monkeypatch):assert cli.cmd_upgrade() == 0+def test_cmd_upgrade_blocks_mutation_when_memory_requirement_is_unreadable(+ monkeypatch,+ capsys,+) -> None:+ monkeypatch.setattr(+ cli,+ "get_latest_version",+ lambda: {"error": "metadata unavailable", "has_update": False, "latest": None},+ )+ monkeypatch.setattr(+ cli,+ "configured_memory_enabled",+ Mock(side_effect=MemoryRequirementUnreadableError()),+ )+ plan = Mock(side_effect=AssertionError("unreadable requirement built a plan"))+ monkeypatch.setattr(cli, "build_upgrade_plan", plan)+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")++ assert cli.cmd_upgrade() == 1+ assert "persisted Memory requirement" in capsys.readouterr().out+ plan.assert_not_called()++[email protected]("source", ["local", "direct"])+def test_cmd_upgrade_metadata_failure_uses_exact_memory_artifact(monkeypatch, tmp_path, capsys, source):+ artifact = tmp_path / "avibe_os-3.1.0-py3-none-any.whl"+ package_spec = (+ str(artifact)+ if source == "local"+ else "avibe-os @ https://example.test/releases/avibe_os-3.1.0-py3-none-any.whl"+ )+ calls: dict[str, Any] = {}++ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", package_spec)+ monkeypatch.setattr(+ cli,+ "get_latest_version",+ lambda: {"error": "metadata unavailable", "has_update": False, "latest": None},+ )+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: True)+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: True)+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: {"job_id": "restart"})+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ def execute(plan, **kwargs):+ calls["plan"] = plan+ return subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr="")++ monkeypatch.setattr(cli, "execute_upgrade_plan", execute)++ assert cli.cmd_upgrade() == 0+ assert "Attempting upgrade anyway..." in capsys.readouterr().out+ assert "avibe-memory==3.1.0" in calls["plan"].command+++def test_cmd_upgrade_metadata_failure_refuses_unversioned_memory_source(monkeypatch, capsys):+ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")+ monkeypatch.setattr(+ cli,+ "get_latest_version",+ lambda: {"error": "metadata unavailable", "has_update": False, "latest": None},+ )+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: True)+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")+ monkeypatch.setattr(+ cli,+ "execute_upgrade_plan",+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("upgrade must not execute")),+ )++ assert cli.cmd_upgrade() == 1+ output = capsys.readouterr().out+ assert "Attempting upgrade anyway..." not in output+ assert "Upgrade failed" in output+++def test_cmd_upgrade_metadata_failure_keeps_core_only_fallback(monkeypatch, capsys):+ calls: dict[str, Any] = {}++ monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "avibe-os")+ monkeypatch.setattr(+ cli,+ "get_latest_version",+ lambda: {"error": "metadata unavailable", "has_update": False, "latest": None},+ )+ monkeypatch.setattr(cli, "configured_memory_enabled", lambda: False)+ monkeypatch.setattr(cli, "cache_running_vibe_path", lambda: "/custom/bin/vibe")+ monkeypatch.setattr(cli, "_runtime_process_was_running", lambda: True)+ monkeypatch.setattr(cli, "schedule_restart", lambda **kwargs: {"job_id": "restart"})+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ def execute(plan, **kwargs):+ calls["plan"] = plan+ return subprocess.CompletedProcess(plan.command, 0, stdout="done", stderr="")++ monkeypatch.setattr(cli, "execute_upgrade_plan", execute)++ assert cli.cmd_upgrade() == 0+ assert "Attempting upgrade anyway..." in capsys.readouterr().out+ assert calls["plan"].command[-1] == "avibe-os"+++def test_memory_enabled_forward_plan_locks_memory_to_target_release(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)+ monkeypatch.setattr("vibe.upgrade.installed_metadata_describes_running_code", lambda: True)++ plan = build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ memory_package=True,+ memory_version="3.0.14",+ target_version="3.1.0",+ package_spec="avibe-os>=3.1,<3.2",+ )++ target = "avibe-os[memory]<3.2,>=3.1"+ memory = "avibe-memory==3.1.0"+ assert plan.command == ["/usr/bin/python3", "-m", "pip", "install", "--upgrade", target, memory]+ assert plan.preflight_command == [+ "/usr/bin/python3",+ "-m",+ "pip",+ "install",+ "--dry-run",+ "--upgrade",+ target,+ memory,+ ]+ assert plan.preflight_fallback_command == [+ "/usr/bin/python3",+ "-m",+ "pip",+ "download",+ "--dest",+ "{avibe-pip-download-destination}",+ target,+ memory,+ ]+ assert "<3.1" not in " ".join(plan.command + plan.preflight_command)+++def test_memory_enabled_forward_plan_requires_target_release(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ with pytest.raises(ValueError, match="target release version"):+ build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ memory_package=True,+ package_spec="avibe-os",+ )+++ ("package_spec", "target_version"),+ [+ ("avibe-os==3.1.0", "3.1.0"),+ (+ "avibe-os @ https://example.test/releases/avibe_os-3.1.1-py3-none-any.whl",+ "3.1.1",+ ),+ ("/fixtures/avibe_os-3.1.2.tar.gz", "3.1.2"),+ ],+)+def test_memory_enabled_forward_plan_derives_target_from_versioned_spec(+ monkeypatch, package_spec, target_version+):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ plan = build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ package_spec=package_spec,+ )++ memory_pin = f"avibe-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+++ "package_spec",+ [+ "/fixtures/avibe_os-3.2.0-py3-none-any.whl",+ "avibe-os @ https://example.test/releases/avibe_os-3.2.0-py3-none-any.whl",+ "avibe-os==3.2.0",+ ],+)+def test_exact_package_spec_overrides_conflicting_memory_target(monkeypatch, package_spec):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ plan = build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ target_version="3.1.0",+ package_spec=package_spec,+ )++ 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+++def test_uv_exact_artifact_overrides_conflicting_memory_target(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.is_uv_tool_install", lambda executable: True)+ monkeypatch.setattr("vibe.upgrade.is_legacy_uv_tool_install", lambda executable: False)+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: "/usr/bin/uv")+ monkeypatch.setattr("vibe.upgrade.get_current_vibe_bin_dir", lambda vibe_path: None)++ plan = build_upgrade_plan(+ python_executable="/tools/avibe/bin/python",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ target_version="3.1.0",+ 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 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+++ "package_spec",+ [+ "avibe-os",+ "avibe-os>=3.1,<3.2",+ "avibe-os==3.1.*",+ ],+)+def test_named_package_spec_accepts_compatible_memory_target(monkeypatch, package_spec):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ plan = build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ target_version="3.1.4",+ package_spec=package_spec,+ )++ assert "avibe-memory==3.1.4" in plan.command+++def test_named_package_spec_rejects_incompatible_memory_target(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ with pytest.raises(ValueError, match="target release version"):+ build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ target_version="3.2.0",+ package_spec="avibe-os>=3.1,<3.2",+ )+++ "package_spec",+ [+ "avibe-os",+ "avibe-os>=3.1,<3.2",+ "avibe-os==3.1.*",+ "git+https://example.test/[email protected]",+ "avibe-os @ git+https://example.test/[email protected]",+ "/fixtures/avibe.whl",+ ],+)+def test_memory_enabled_forward_plan_rejects_unversioned_fallback_specs(monkeypatch, package_spec):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ with pytest.raises(ValueError, match="target release version"):+ build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ package_spec=package_spec,+ )+++ "package_spec",+ [+ "git+https://example.test/[email protected]",+ "avibe-os @ git+https://example.test/[email protected]",+ "https://user:[email protected]/download",+ "avibe-os @ https://user:[email protected]/download",+ "/fixtures/avibe.whl",+ ],+)+def test_opaque_memory_source_rejects_metadata_without_exposing_spec(monkeypatch, package_spec):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ with pytest.raises(ValueError) as refusal:+ build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ target_version="3.1.0",+ package_spec=package_spec,+ )++ assert str(refusal.value) == "A Memory-preserving upgrade requires a target release version"+++def test_memory_preflight_failure_does_not_mutate_package(monkeypatch):+ plan = UpgradePlan(+ command=["python", "-m", "pip", "install", "avibe-os[memory]"],+ env={},+ method="pip",+ preflight_command=["python", "-m", "pip", "install", "--dry-run", "avibe-os[memory]"],+ preflight_fallback_command=[+ "python",+ "-m",+ "pip",+ "download",+ "--dest",+ "{avibe-pip-download-destination}",+ "avibe-os[memory]",+ ],+ )+ calls: list[list[str]] = []++ def run(command, **kwargs):+ calls.append(command)+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="missing memory")++ result = execute_upgrade_plan(plan, run=run)++ assert result.returncode == 1+ assert calls == [plan.preflight_command]+++def test_legacy_pip_fallback_resolves_target_extra_before_install(tmp_path):+ plan = UpgradePlan(+ command=["python", "-m", "pip", "install", "avibe-os[memory]"],+ env={},+ method="pip",+ preflight_command=["python", "-m", "pip", "install", "--dry-run", "avibe-os[memory]"],+ preflight_fallback_command=[+ "python",+ "-m",+ "pip",+ "download",+ "--dest",+ "{avibe-pip-download-destination}",+ "avibe-os[memory]",+ ],+ )+ calls: list[list[str]] = []+ scratch: Path | None = None++ def run(command, **kwargs):+ nonlocal scratch+ calls.append(command)+ if "--dry-run" in command:+ return subprocess.CompletedProcess(command, 2, stdout="", stderr="no such option: --dry-run")+ if "download" in command:+ scratch = Path(command[command.index("--dest") + 1])+ assert scratch.is_dir()+ assert "--no-deps" not in command+ return subprocess.CompletedProcess(command, 0, stdout="resolved", stderr="")+ return subprocess.CompletedProcess(command, 0, stdout="installed", stderr="")++ result = execute_upgrade_plan(plan, run=run)++ assert result.returncode == 0+ assert [command[3] for command in calls] == ["install", "download", "install"]+ assert scratch is not None and not scratch.exists()+++def test_legacy_pip_fallback_failure_stops_before_install():+ plan = UpgradePlan(+ command=["python", "-m", "pip", "install", "avibe-os[memory]"],+ env={},+ method="pip",+ preflight_command=["python", "-m", "pip", "install", "--dry-run", "avibe-os[memory]"],+ preflight_fallback_command=[+ "python",+ "-m",+ "pip",+ "download",+ "--dest",+ "{avibe-pip-download-destination}",+ "avibe-os[memory]",+ ],+ )+ calls: list[list[str]] = []++ def run(command, **kwargs):+ calls.append(command)+ if "--dry-run" in command:+ return subprocess.CompletedProcess(command, 2, stdout="", stderr="no such option: --dry-run")+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="missing target Memory wheel")++ result = execute_upgrade_plan(plan, run=run)++ assert result.returncode == 1+ assert len(calls) == 2+ assert calls[1][3] == "download"+ assert "--no-deps" not in calls[1]+ assert plan.command not in calls+++def test_pip_preflight_does_not_fallback_on_resolver_failure():+ plan = UpgradePlan(+ command=["python", "-m", "pip", "install", "avibe-os[memory]"],+ env={},+ method="pip",+ preflight_command=["python", "-m", "pip", "install", "--dry-run", "avibe-os[memory]"],+ preflight_fallback_command=["python", "-m", "pip", "download", "avibe-os[memory]"],+ )+ calls: list[list[str]] = []++ def run(command, **kwargs):+ calls.append(command)+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="No matching distribution found")++ result = execute_upgrade_plan(plan, run=run)++ assert result.returncode == 1+ assert calls == [plan.preflight_command]+++def test_unreadable_memory_config_blocks_package_plan(monkeypatch):+ monkeypatch.setattr("config.v2_config.V2Config.load", lambda: (_ for _ in ()).throw(ValueError("bad config")))++ with pytest.raises(MemoryRequirementUnreadableError):+ configured_memory_enabled()+++def test_missing_first_run_config_does_not_block_package_plan(monkeypatch):+ monkeypatch.setattr(+ "config.v2_config.V2Config.load",+ lambda: (_ for _ in ()).throw(FileNotFoundError()),+ )++ assert configured_memory_enabled() is False+++def test_uv_forward_plan_locks_memory_to_target_release(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.is_uv_tool_install", lambda executable: True)+ monkeypatch.setattr("vibe.upgrade.is_legacy_uv_tool_install", lambda executable: False)+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: "/usr/bin/uv")+ monkeypatch.setattr("vibe.upgrade.get_current_vibe_bin_dir", lambda vibe_path: None)++ plan = build_upgrade_plan(+ python_executable="/tools/avibe/bin/python",+ base_env={"PATH": "/usr/bin"},+ memory_enabled=True,+ memory_package=True,+ target_version="3.1.0",+ package_spec="avibe-os>=3.1,<3.2",+ )++ target = "avibe-os[memory]<3.2,>=3.1"+ memory = "avibe-memory==3.1.0"+ assert plan.command == [+ "/usr/bin/uv",+ "tool",+ "install",+ target,+ "--with",+ memory,+ "--upgrade",+ "--force",+ ]+ assert plan.preflight_command == [+ "/usr/bin/uv",+ "pip",+ "install",+ "--dry-run",+ "--python",+ "/tools/avibe/bin/python",+ "--upgrade",+ target,+ memory,+ ]+++def test_explicit_memory_install_keeps_exact_package_version(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.find_uv_binary", lambda **kwargs: None)++ plan = build_upgrade_plan(+ python_executable="/usr/bin/python3",+ base_env={"PATH": "/usr/bin"},+ version="3.0.14",+ package_name="avibe-os",+ memory_package=True,+ memory_version="3.0.14",+ )++ 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 plan.preflight_command is not None+ assert "avibe-memory==3.0.14" in plan.preflight_command+++def test_with_memory_extra_preserves_vcs_url_and_local_specs(tmp_path, monkeypatch):+ from vibe.upgrade import _with_memory_extra++ 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"+ )+ 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()}"+ )++def test_get_safe_cwd_returns_absolute_existing_dir():cwd = get_safe_cwd()assert os.path.isabs(cwd)diff --git a/tests/test_version_identity.py b/tests/test_version_identity.pyindex a43d294dd..519672f73 100644--- a/tests/test_version_identity.py+++ b/tests/test_version_identity.py@@ -70,13 +70,6 @@ def test_packaged_install_keeps_semantic_update_behavior(monkeypatch) -> None:assert api.get_version_info() == {**expected, "build": {"kind": "package"}}-def test_local_version_info_never_queries_package_index(monkeypatch) -> None:- monkeypatch.setattr("vibe.__version__", "3.0.12", raising=False)- monkeypatch.setattr(api, "get_build_identity", lambda: type("Build", (), {"as_dict": lambda self: {"kind": "package"}})())-- assert api.get_local_version_info() == {"current": "3.0.12", "build": {"kind": "package"}}--def test_configured_missing_metadata_stays_a_source_build(monkeypatch, tmp_path) -> None:monkeypatch.setenv("VIBE_BUILD_METADATA_PATH", str(tmp_path / "not-written-yet.json"))monkeypatch.setattr("vibe.__version__", "3.0.6rc5", raising=False)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 4eca75710..cf58142a1 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -1,4 +1,5 @@import asyncio+import builtinsimport hashlibimport jsonimport os@@ -2936,7 +2937,7 @@ def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(consumer,):if consumer == "memory":- from core.memory.artifact import MemoryArtifactManager+ from avibe_memory.artifact import MemoryArtifactManagermanager = MemoryArtifactManager(runtime_dir=tmp_path / "memory-runtime",@@ -3051,7 +3052,7 @@ def test_runtime_clean_reclaims_each_shared_consumer_in_preview_and_real_run(def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatch):from core import tmux_runtime- from core.memory import artifact as memory_artifact+ from avibe_memory import artifact as memory_artifactfrom vibe.model_hub_runtime import installer as model_hub_installercalls = []@@ -3101,6 +3102,77 @@ def test_runtime_clean_registry_invokes_every_current_shared_consumer(monkeypatc]+def test_runtime_clean_isolates_missing_memory_implementation(monkeypatch):+ from core import tmux_runtime+ from vibe.model_hub_runtime import installer as model_hub_installer++ calls = []+ original_import = builtins.__import__++ def core_only_import(name, *args, **kwargs):+ if name == "avibe_memory.artifact":+ raise ModuleNotFoundError(name, name="avibe_memory")+ return original_import(name, *args, **kwargs)++ class FakeManager:+ def __init__(self, runtime_id):+ self.runtime_id = runtime_id++ def clean(self, *, keep_previous, dry_run):+ calls.append((self.runtime_id, keep_previous, dry_run))+ return {"ok": True, "removed": []}++ monkeypatch.setattr(builtins, "__import__", core_only_import)+ monkeypatch.setattr(+ cli,+ "_clean_git_runtime",+ lambda **kwargs: calls.append(("git", kwargs["keep_previous"], kwargs["dry_run"]))+ or {"ok": True, "removed": []},+ )+ monkeypatch.setattr(+ model_hub_installer,+ "EngineRuntimeManager",+ lambda: FakeManager("model_hub_engine"),+ )+ monkeypatch.setattr(+ tmux_runtime,+ "get_tmux_runtime_manager",+ lambda: FakeManager("tmux"),+ )++ results = cli._clean_managed_runtime_consumers(keep_previous=2, dry_run=True)++ assert results["memory-runtime"] == {+ "ok": True,+ "removed": [],+ "skipped": True,+ "reason": "memory_implementation_unavailable",+ }+ assert results["git"]["ok"] is True+ assert results["model_hub_engine"]["ok"] is True+ assert results["tmux"]["ok"] is True+ assert calls == [+ ("git", 2, True),+ ("model_hub_engine", 2, True),+ ("tmux", 2, True),+ ]+++def test_runtime_clean_reports_broken_memory_implementation_import(monkeypatch):+ original_import = builtins.__import__++ def broken_memory_import(name, *args, **kwargs):+ if name == "avibe_memory.artifact":+ raise ModuleNotFoundError("missing companion dependency", name="memory_dependency")+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", broken_memory_import)+ cleaners = dict(cli._managed_runtime_cleaners())++ with pytest.raises(ModuleNotFoundError, match="missing companion dependency"):+ cleaners["memory-runtime"](keep_previous=2, dry_run=True)++def test_runtime_clean_returns_nonzero_and_reports_git_exception_reason(monkeypatch, capsys):from core import git_runtimediff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex f95890c52..6612f5670 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -443,7 +443,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):bot.on_message_callback.assert_awaited_once()args = bot.on_message_callback.await_args.args # type: ignore[union-attr]self.assertEqual(args[0].user_id, "user-1")- self.assertTrue(args[0].is_ordinary_text)+ self.assertTrue(args[0].is_original_human_text)self.assertEqual(args[1], "hi")async def test_process_inbound_message_marks_quoted_text_nonordinary(self):@@ -469,7 +469,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):await asyncio.gather(*tuple(bot._message_callback_tasks))context = bot.on_message_callback.await_args.args[0] # type: ignore[union-attr]- self.assertFalse(context.is_ordinary_text)+ self.assertFalse(context.is_original_human_text)async def test_direct_voice_and_video_publish_ordinary_attachment_fact(self):bot = self._make_bot()@@ -499,7 +499,7 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):await asyncio.gather(*tuple(bot._message_callback_tasks))context = bot.on_message_callback.await_args.args[0] # type: ignore[union-attr]- self.assertIs(context.is_ordinary_attachment, True)+ self.assertIs(context.is_original_human_attachment, True)self.assertEqual([file.mimetype for file in context.files or []], ["audio/silk", "video/mp4"])async def test_process_inbound_message_sends_pending_bind_menu_hint_once(self):diff --git a/ui/src/components/settings/SettingsDependenciesPage.logic.ts b/ui/src/components/settings/SettingsDependenciesPage.logic.tsindex 12a39025d..47e8371ca 100644--- a/ui/src/components/settings/SettingsDependenciesPage.logic.ts+++ b/ui/src/components/settings/SettingsDependenciesPage.logic.ts@@ -1,10 +1,30 @@import type { DependencyItem, MemoryStatusResult } from '@/context/ApiContext';-const INSTALLABLE_DEPENDENCIES = new Set(['askill', 'avault', 'show-runtime', 'memory-runtime', 'tmux']);+const INSTALLABLE_DEPENDENCIES = new Set([+ 'askill',+ 'avault',+ 'show-runtime',+ 'memory-package',+ 'memory-runtime',+ 'tmux',+]);export const dependencyHasInstallAction = (- dependency: Pick<DependencyItem, 'id' | 'status'>,-): boolean => dependency.status !== 'unsupported' && INSTALLABLE_DEPENDENCIES.has(dependency.id);+ dependency: Pick<DependencyItem, 'id' | 'status' | 'action_class'>,+): boolean => {+ const optionalMemoryPackageRepair = (+ dependency.id === 'memory-package'+ && dependency.status === 'not_required'+ && dependency.action_class === 'repairable'+ );+ return (+ dependency.status !== 'unsupported'+ && (dependency.status !== 'not_required' || optionalMemoryPackageRepair)+ && dependency.action_class !== 'none'+ && dependency.action_class !== 'operator_only'+ && INSTALLABLE_DEPENDENCIES.has(dependency.id)+ );+};/** Treat any active or uncertain runtime as unsafe for dependency replacement. */export const memoryRuntimeSidecarRunning = (diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.ts b/ui/src/components/settings/SettingsDependenciesPage.test.tsindex e759fe4c7..f3b7df88c 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.ts+++ b/ui/src/components/settings/SettingsDependenciesPage.test.ts@@ -5,10 +5,19 @@ import { dependencyHasInstallAction, memoryRuntimeSidecarRunning } from './Settidescribe('dependencyHasInstallAction', () => {it('hides install and repair actions for unsupported dependencies', () => {expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'unsupported' })).toBe(false);+ expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'not_required' })).toBe(false);+ expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'error', action_class: 'operator_only' })).toBe(false);+ expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'missing', action_class: 'none' })).toBe(false);});it('keeps supported dependency actions unchanged', () => {+ expect(dependencyHasInstallAction({ id: 'memory-package', status: 'missing', action_class: 'repairable' })).toBe(true);+ expect(dependencyHasInstallAction({ id: 'memory-package', status: 'error', action_class: 'repairable' })).toBe(true);+ expect(dependencyHasInstallAction({ id: 'memory-package', status: 'not_required', action_class: 'repairable' })).toBe(true);+ expect(dependencyHasInstallAction({ id: 'memory-package', status: 'not_required', action_class: 'none' })).toBe(false);+ expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'not_required', action_class: 'repairable' })).toBe(false);expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'missing' })).toBe(true);+ expect(dependencyHasInstallAction({ id: 'memory-runtime', status: 'ready', action_class: 'repairable' })).toBe(true);expect(dependencyHasInstallAction({ id: 'show-runtime', status: 'ready' })).toBe(true);expect(dependencyHasInstallAction({ id: 'node', status: 'missing' })).toBe(false);});diff --git a/ui/src/components/settings/SettingsDependenciesPage.test.tsx b/ui/src/components/settings/SettingsDependenciesPage.test.tsxindex fa448f2f2..88086e22b 100644--- a/ui/src/components/settings/SettingsDependenciesPage.test.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.test.tsx@@ -67,6 +67,59 @@ afterEach(() => {});describe('SettingsDependenciesPage Memory runtime', () => {+ it('routes repairable Python package bootstrap through its own dependency action', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ id: 'memory-package',+ installed: false,+ status: 'missing',+ action_class: 'repairable',+ version: null,+ })],+ });+ renderPage();++ await userEvent.click(await screen.findByRole('button', { name: 'settings.dependencies.install' }));++ await waitFor(() => expect(api.installDependency).toHaveBeenCalledWith('memory-package'));+ expect(api.installDependency).not.toHaveBeenCalledWith('memory-runtime');+ });++ it('hides package bootstrap while Memory is not required', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ id: 'memory-package',+ installed: false,+ status: 'not_required',+ action_class: 'none',+ version: null,+ })],+ });+ renderPage();++ expect(await screen.findByText('settings.dependencies.statusNotRequired')).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'settings.dependencies.install' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'settings.dependencies.repair' })).toBeNull();+ });++ it('keeps explicit package repair available while disabled', async () => {+ api.listDependencies.mockResolvedValue({+ ok: true,+ deps: [dependency({+ id: 'memory-package',+ status: 'not_required',+ action_class: 'repairable',+ })],+ });+ renderPage();++ await userEvent.click(await screen.findByRole('button', { name: 'settings.dependencies.reinstall' }));++ await waitFor(() => expect(api.installDependency).toHaveBeenCalledWith('memory-package'));+ });+it('shows only dependency repair and the Memory settings link', async () => {renderPage();expect(await screen.findByRole('button', { name: 'settings.dependencies.repair' })).toBeTruthy();diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex 8a26ef7e0..d99e46fbd 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -40,6 +40,7 @@ const DEP_META: Record<string, DepMeta> = {askill: { icon: WandSparkles, tileCls: 'bg-mint-soft', iconCls: 'text-mint-ink' },avault: { icon: KeyRound, tileCls: 'bg-gold-soft', iconCls: 'text-gold-ink' },'show-runtime': { icon: LayoutDashboard, tileCls: 'bg-cyan-soft', iconCls: 'text-cyan-ink' },+ 'memory-package': { icon: Brain, tileCls: 'bg-gold-soft', iconCls: 'text-gold-ink' },'memory-runtime': { icon: Brain, tileCls: 'bg-violet-soft', iconCls: 'text-violet-ink' },tmux: { icon: SquareTerminal, tileCls: 'bg-surface-3', iconCls: 'text-foreground' },node: { icon: Hexagon, tileCls: 'bg-violet-soft', iconCls: 'text-violet-ink' },@@ -124,13 +125,15 @@ export const SettingsDependenciesPage: React.FC = () => {// of the generic "not installed" fallback.if (d.status === 'unsupported') return t('settings.dependencies.statusUnsupported');if (d.status === 'error') return t('settings.dependencies.statusError');+ if (d.status === 'not_required') return t('settings.dependencies.statusNotRequired');if (!d.installed) return t('settings.dependencies.statusMissing');if (d.status === 'upgrade_required') return t('settings.dependencies.statusUpgradeRequired');const word = d.kind === 'node' ? t('settings.dependencies.statusDetected') : t('settings.dependencies.statusReady');return d.version ? `${word} · v${String(d.version).replace(/^v/i, '')}` : word;};- const statusVariant = (d: DependencyItem): 'success' | 'warning' | 'destructive' => {+ const statusVariant = (d: DependencyItem): 'secondary' | 'success' | 'warning' | 'destructive' => {+ if (d.status === 'not_required') return 'secondary';if (d.status === 'error') return 'destructive';if (d.status === 'unsupported' || d.status === 'upgrade_required') return 'warning';return d.installed ? 'success' : 'destructive';diff --git a/ui/src/components/settings/SettingsMemoryPage.test.tsx b/ui/src/components/settings/SettingsMemoryPage.test.tsxindex 19e4eba18..1385140b0 100644--- a/ui/src/components/settings/SettingsMemoryPage.test.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.test.tsx@@ -159,6 +159,22 @@ afterEach(() => {});describe('SettingsMemoryPage', () => {+ it('directs disabled Memory to the explicit package bootstrap when missing', async () => {+ api.getMemorySettings.mockResolvedValue({ ...settings, enabled: false });+ api.listDependencies.mockResolvedValue({+ deps: [+ { id: 'memory-package', installed: false, status: 'missing', action_class: 'repairable' },+ { id: 'memory-runtime', installed: null, status: 'not_required', action_class: 'none' },+ ],+ });++ renderPage();++ await screen.findByText('repair-supported');+ expect(screen.getByText('memory.setup.runtimeRequired')).toBeTruthy();+ expect(screen.getByRole('link', { name: /memory.settings.goToDependencies/ })).toBeTruthy();+ });+it('offers Retry startup for degraded Memory', async () => {api.getMemoryStatus.mockResolvedValue(status('degraded'));renderPage();diff --git a/ui/src/components/settings/SettingsMemoryPage.tsx b/ui/src/components/settings/SettingsMemoryPage.tsxindex f29a7f9fc..15daf5496 100644--- a/ui/src/components/settings/SettingsMemoryPage.tsx+++ b/ui/src/components/settings/SettingsMemoryPage.tsx@@ -50,7 +50,6 @@ export const SettingsMemoryPage: React.FC = () => {const [waking, setWaking] = useState(false);const [repairing, setRepairing] = useState(false);const [settingsSaving, setSettingsSaving] = useState(false);- const [dependencyReady, setDependencyReady] = useState(true);const [runtimeInstalled, setRuntimeInstalled] = useState<boolean | null>(null);const [repairError, setRepairError] = useState<string | null>(null);const [deleteResult, setDeleteResult] = useState<MemoryDataOperationResult | null>(null);@@ -93,16 +92,21 @@ export const SettingsMemoryPage: React.FC = () => {const loadDependency = useCallback(async () => {try {const res = await api.listDependencies();- const dep = res.deps?.find((item) => item.id === 'memory-runtime');- if (dep) {- setRuntimeInstalled(dep.installed);- setDependencyReady(dep.installed && dep.status === 'ready');+ const memoryPackage = res.deps?.find((item) => item.id === 'memory-package');+ const memoryRuntime = res.deps?.find((item) => item.id === 'memory-runtime');+ if (memoryPackage?.action_class === 'repairable' && memoryPackage.installed !== true) {+ setRuntimeInstalled(false);+ } else if (memoryRuntime) {+ setRuntimeInstalled(+ memoryRuntime.status === 'not_required'+ ? null+ : memoryRuntime.installed === true,+ );} else {setRuntimeInstalled(true);}} catch {setRuntimeInstalled(true);- setDependencyReady(true);}}, [api]);@@ -244,7 +248,6 @@ export const SettingsMemoryPage: React.FC = () => {settings={settings}maintenance={maintenanceRead.data}maintenanceError={maintenanceRead.error}- dependencyReady={dependencyReady}mutationBusy={waking || repairing || deleting}onSavingChange={setSettingsSaving}onSaved={(next) => {diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsxindex 1413b80c6..d8d50c8dc 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.test.tsx@@ -56,7 +56,6 @@ const renderPanel = (overrides: Partial<React.ComponentProps<typeof MemorySettinsettings,maintenance: { status: 'ok', data_exists: true, can_delete_data: true },maintenanceError: null,- dependencyReady: true,onSaved: vi.fn(),onReloadSettings: vi.fn(),onReloadMaintenance: vi.fn(),@@ -78,6 +77,18 @@ afterEach(() => {});describe('MemorySettingsPanel', () => {+ it('keeps configuration enablement reachable while Memory is disabled', async () => {+ const user = userEvent.setup();+ renderPanel({ settings: { ...settings, enabled: false } });+ const enable = screen.getByRole('switch', { name: 'memory.settings.enableLabel' });++ expect((enable as HTMLButtonElement).disabled).toBe(false);+ await user.click(enable);+ await user.click(screen.getByRole('button', { name: 'memory.settings.save' }));++ await waitFor(() => expect(api.saveMemorySettings).toHaveBeenCalledWith({ enabled: true }));+ });+it('exposes one explicit Delete data action', async () => {const props = renderPanel();await userEvent.click(screen.getByRole('button', { name: 'memory.deleteData.button' }));diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.tsxindex bc9f25875..cfc1ad39e 100644--- a/ui/src/components/settings/memory/MemorySettingsPanel.tsx+++ b/ui/src/components/settings/memory/MemorySettingsPanel.tsx@@ -1,12 +1,9 @@import { useEffect, useState } from 'react';-import { Link } from 'react-router-dom';import { useTranslation } from 'react-i18next';import {- ArrowUpRight,Building2,Cloud,Loader2,- ShieldAlert,SlidersHorizontal,Trash2,} from 'lucide-react';@@ -205,7 +202,6 @@ export const MemorySettingsPanel: React.FC<{settings: MemorySettings;maintenance: MemoryMaintenance | null;maintenanceError: string | null;- dependencyReady: boolean;mutationBusy?: boolean;onSavingChange?: (saving: boolean) => void;onSaved: (next: MemorySettingsOk) => void;@@ -217,7 +213,6 @@ export const MemorySettingsPanel: React.FC<{settings,maintenance,maintenanceError,- dependencyReady,mutationBusy = false,onSavingChange,onSaved,@@ -442,25 +437,12 @@ export const MemorySettingsPanel: React.FC<{<div className="flex min-w-0 flex-col gap-1"><span className="text-[13px] font-semibold text-foreground">{t('memory.settings.enableLabel')}</span><span className="text-[11.5px] leading-snug text-muted">{t('memory.settings.enableHint')}</span>- {!dependencyReady && !enabledDraft ? (- <div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11.5px] text-gold-ink">- <ShieldAlert className="size-3.5 shrink-0" />- {t('memory.settings.dependencyNotReady')}- <Button asChild variant="secondary" size="xs">- <Link to="/settings/dependencies">- {t('memory.settings.goToDependencies')}- <ArrowUpRight className="size-3.5" />- </Link>- </Button>- </div>- ) : null}</div><Switchchecked={enabledDraft}onCheckedChange={setMemoryEnabled}disabled={busy- || (!enabledDraft && !dependencyReady)|| (!enabledDraft && !customMode && !settings.cloud_available)}label={t('memory.settings.enableLabel')}diff --git a/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx b/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsxindex ae049f482..7336d272d 100644--- a/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx+++ b/ui/src/components/settings/memory/MemoryStatusPanel.i18n.test.tsx@@ -46,6 +46,24 @@ const renderStatus = (language: 'en' | 'zh', state: MemoryStatus['state'], reasoafterEach(cleanup);describe('MemoryStatusPanel localized recovery contract', () => {+ it.each([+ [+ 'en',+ 'Memory is still handling work and could not stop safely.',+ 'Reason: Memory is still handling work and could not stop safely.',+ ],+ [+ 'zh',+ '记忆仍在处理工作,无法安全停止。',+ '原因:记忆仍在处理工作,无法安全停止。',+ ],+ ] as const)('localizes runtime-busy status and source reasons in %s', (language, reason, sourceReason) => {+ renderStatus(language, 'degraded', 'memory_runtime_busy');+ expect(screen.getByText(reason)).toBeTruthy();+ expect(screen.getByText(sourceReason)).toBeTruthy();+ expect(screen.queryByText(/memory_runtime_busy/)).toBeNull();+ });+it.each([['en', 'Needs repair', 'The confined local Memory data root is unusable or incompatible and needs Repair.'],['zh', '需要修复', '受限的本地记忆数据根不可用或不兼容,需要修复。'],diff --git a/ui/src/components/settings/memory/memoryCopyContract.test.ts b/ui/src/components/settings/memory/memoryCopyContract.test.tsindex 689f1ab30..fc2686f73 100644--- a/ui/src/components/settings/memory/memoryCopyContract.test.ts+++ b/ui/src/components/settings/memory/memoryCopyContract.test.ts@@ -92,6 +92,8 @@ describe('Memory UI copy contracts', () => {'memory_local_data_unusable','memory_repair_not_required','memory_delete_data_failed',+ 'memory_implementation_unavailable',+ 'memory_implementation_incompatible',] as const) {expect(bundles[language].errors[key]).toBeTruthy();}diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.ts b/ui/src/components/settings/memory/memoryStatusPresentation.tsindex d56cb0ab9..f401df8af 100644--- a/ui/src/components/settings/memory/memoryStatusPresentation.ts+++ b/ui/src/components/settings/memory/memoryStatusPresentation.ts@@ -43,6 +43,7 @@ const HEALTH_STATUS_LABEL_KEYS = {const MEMORY_SOURCE_ERROR_REASONS = new Set(['memory_disabled',+ 'memory_runtime_busy','memory_runtime_missing','memory_runtime_unsupported','memory_runtime_install_failed',diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex b3a07934e..ebffc1bcf 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1860,8 +1860,9 @@ export type InstallResult = {output: string | null;path?: string | null;job_id?: string;- status?: 'running' | 'succeeded' | 'failed';+ status?: 'running' | 'succeeded' | 'failed' | 'rejected';reason?: string | null;+ action_class?: 'operator_only';download_error?: DependencyDownloadError | null;};@@ -1878,10 +1879,12 @@ export type DependencyDownloadError = {export type DependencyItem = {id: string;kind: 'tool' | 'runtime' | 'node';- required: boolean;- installed: boolean;+ required: boolean | null;+ installed: boolean | null;version: string | null;- status: 'ready' | 'missing' | 'upgrade_required' | 'unsupported' | 'error';+ status: 'ready' | 'not_required' | 'missing' | 'upgrade_required' | 'unsupported' | 'error';+ readiness?: 'ready' | 'not_required' | 'not_ready' | 'memory_requirement_unreadable';+ action_class?: 'none' | 'repairable' | 'operator_only';reason?: string | null;release_state?: 'published' | 'unavailable' | null;download_error?: DependencyDownloadError | null;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 65a9812ea..99b2590b2 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -386,6 +386,7 @@"statusReady": "Ready","statusDetected": "Detected","statusMissing": "Not installed",+ "statusNotRequired": "Not required","statusUpgradeRequired": "Upgrade required","install": "Install","reinstall": "Reinstall",@@ -418,6 +419,10 @@"label": "Node.js","detail": "Shared prerequisite for the runtimes above."},+ "memory-package": {+ "label": "Memory Python package",+ "detail": "Optional Memory implementation matched to this Avibe release."+ },"memory-runtime": {"label": "Memory runtime","detail": "Runs local memory distillation and search on your machine."@@ -1887,6 +1892,18 @@"remote_access_diagnostics_failed": "Connectivity diagnostics could not finish.","bind_code_limit_reached": "Too many active bind codes. Revoke an unused code before creating another.","memory_disabled": "Memory is disabled, or this connection can't reach it.",+ "memory_requirement_unreadable": "Memory settings could not be read safely. Repair the configuration before changing packages.",+ "memory_not_required": "Enable Memory in Settings before installing its Python package.",+ "memory_package_not_repairable": "The Memory Python package does not currently need repair.",+ "memory_package_admission_unavailable": "Avibe could not verify whether the Memory package can be repaired safely.",+ "memory_package_source_build": "Memory package repair is unavailable from a source checkout.",+ "memory_package_unpublished_build": "Memory package repair requires a published Avibe release.",+ "memory_package_metadata_unreadable": "The installed Memory package metadata could not be read. Repair it manually.",+ "memory_package_metadata_ambiguous": "Multiple Memory package providers were found. Remove the duplicate installation before retrying.",+ "memory_package_install_failed": "The Memory Python package could not be installed.",+ "memory_package_restart_failed": "The Memory package was installed, but Avibe could not schedule the service restart.",+ "memory_implementation_unavailable": "The Memory implementation is unavailable.",+ "memory_implementation_incompatible": "The Memory implementation is incompatible with this Avibe version.","memory_invalid_input": "That Memory request wasn't valid.","memory_processing_record_entry_not_found": "That Memory processing entry is no longer available.","memory_failure_history_unavailable": "Detailed Memory failure history is unavailable.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1f19a9f1e..22657b297 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -386,6 +386,7 @@"statusReady": "就绪","statusDetected": "已检测","statusMissing": "未安装",+ "statusNotRequired": "无需安装","statusUpgradeRequired": "需要升级","install": "安装","reinstall": "重新安装",@@ -418,6 +419,10 @@"label": "Node.js","detail": "上述运行时的共同前置依赖。"},+ "memory-package": {+ "label": "记忆 Python 包",+ "detail": "与当前 Avibe 版本匹配的可选记忆实现。"+ },"memory-runtime": {"label": "记忆运行时","detail": "在本机运行记忆提炼与搜索。"@@ -1887,6 +1892,18 @@"remote_access_diagnostics_failed": "连接诊断未能完成。","bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。","memory_disabled": "记忆功能已禁用,或当前连接无法访问它。",+ "memory_requirement_unreadable": "无法安全读取记忆设置。请先修复配置,再更改软件包。",+ "memory_not_required": "请先在记忆设置中启用记忆功能,再安装其 Python 软件包。",+ "memory_package_not_repairable": "记忆 Python 软件包当前无需修复。",+ "memory_package_admission_unavailable": "Avibe 无法确认是否能安全修复记忆软件包。",+ "memory_package_source_build": "源码检出环境不支持修复记忆软件包。",+ "memory_package_unpublished_build": "修复记忆软件包需要已发布的 Avibe 版本。",+ "memory_package_metadata_unreadable": "无法读取已安装记忆软件包的元数据,请手动修复。",+ "memory_package_metadata_ambiguous": "检测到多个记忆软件包提供者。请移除重复安装后重试。",+ "memory_package_install_failed": "无法安装记忆 Python 软件包。",+ "memory_package_restart_failed": "记忆软件包已安装,但 Avibe 无法安排服务重启。",+ "memory_implementation_unavailable": "记忆实现当前不可用。",+ "memory_implementation_incompatible": "记忆实现与此 Avibe 版本不兼容。","memory_invalid_input": "该记忆请求无效。","memory_processing_record_entry_not_found": "该记忆处理条目已不可用。","memory_failure_history_unavailable": "详细的记忆失败历史记录不可用。",diff --git a/uv.lock b/uv.lockindex 1ad82d9d4..d222c5f58 100644--- a/uv.lock+++ b/uv.lock@@ -294,6 +294,16 @@ 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" },+]++[package.metadata]+requires-dist = [{ name = "avibe-os", specifier = ">=3.0.14.dev0,<3.1" }]+[[package]]name = "avibe-os"source = { editable = "." }@@ -331,6 +341,11 @@ dependencies = [{ name = "uvicorn", extra = ["standard"] },]+[package.optional-dependencies]+memory = [+ { name = "avibe-memory" },+]+[package.dev-dependencies]dev = [{ name = "jsonschema" },@@ -345,6 +360,7 @@ 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" },@@ -372,6 +388,7 @@ requires-dist = [{ name = "typing-extensions", specifier = ">=4.12.2" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.27" },]+provides-extras = ["memory"][package.metadata.requires-dev]dev = [diff --git a/vibe/__init__.py b/vibe/__init__.pyindex 50fdf7f60..0f4eacc56 100644--- a/vibe/__init__.py+++ b/vibe/__init__.py@@ -2,9 +2,8 @@#: The version a build-less tree reports: a source checkout, an editable#: install, or a regression environment built with a pretend version. It names no-#: published release, so anything that has to INSTALL a specific version has to-#: treat it as "unknown" instead of as a target -- see-#: `vibe.upgrade.rollback_target`.+#: published release, so update comparisons must treat it as "unknown" rather+#: than as an index-served release.UNKNOWN_VERSION = "0.0.0.dev0"try:diff --git a/vibe/api.py b/vibe/api.pyindex 7f3475ead..f8d3317bb 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -18,7 +18,7 @@ import timeimport urllib.parseimport urllib.requestimport uuid-from dataclasses import replace+from dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezonefrom http.client import HTTPSConnectionfrom pathlib import Path@@ -29,6 +29,7 @@ from sqlalchemy import selectfrom sqlalchemy.dialects.sqlite import insert as sqlite_insertfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import (CONFIG_LOCK,MemoryConfig,@@ -53,8 +54,9 @@ from config.v2_settings import (from config.v2_sessions import SessionsStorefrom config.platform_registry import get_platform_descriptorfrom core import latest_version_cache+from core.memory_loader import probe_memory_runtime_entrypoint+from config.memory_operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom core.install_integrity import verify_python_environment-from core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom vibe.opencode_config import (get_opencode_config_paths,load_first_opencode_user_config,@@ -63,13 +65,18 @@ from vibe.opencode_config import (from vibe.build_identity import get_build_identityfrom vibe.upgrade import (AtomicActivation,+ MEMORY_PACKAGE_NAME,+ PACKAGE_NAME,+ MemoryRequirementUnreadableError,_candidate_python,activation_block_reason,activate_upgrade_candidate,atomic_upgrade_lock,build_upgrade_plan,+ configured_memory_enabled,defer_upgrade_activation,discard_atomic_uv_install_generation,+ execute_upgrade_plan,get_latest_version_info,get_running_vibe_path,get_safe_cwd,@@ -106,6 +113,7 @@ from core.vibe_agents import ()from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNALfrom core.dependency_network import DependencyNetworkError, dependency_error_message, fetch_bytes+from storage.lock import MigrationFileLock, MigrationLockTimeoutlogger = logging.getLogger(__name__)@@ -6239,20 +6247,6 @@ def get_version_info() -> dict:return result-def get_local_version_info() -> dict:- """Return only the version already loaded by this process.-- Upgrade recovery must be able to identify the release that is still- running even when the package index is unavailable. Keep this endpoint- separate from :func:`get_version_info`, whose update check is intentionally- allowed to perform network I/O for the user-facing version screen.- """-- from vibe import __version__-- return {"current": __version__, "build": get_build_identity().as_dict()}--def do_upgrade(auto_restart: bool = True) -> dict:"""Perform upgrade to latest version.@@ -6263,7 +6257,22 @@ def do_upgrade(auto_restart: bool = True) -> dict:{"ok": bool, "message": str, "output": str | None, "restarting": bool}"""current_vibe_path = get_running_vibe_path()- plan = build_upgrade_plan(vibe_path=current_vibe_path)+ try:+ plan = build_upgrade_plan(+ vibe_path=current_vibe_path,+ memory_enabled=configured_memory_enabled(),+ target_version=get_version_info().get("latest"),+ )+ except MemoryRequirementUnreadableError:+ return {+ "ok": False,+ "message": backend_t("update.memoryRequirementUnreadable"),+ "output": None,+ "reason": "memory_requirement_unreadable",+ "restarting": False,+ }+ except ValueError as exc:+ return {"ok": False, "message": "Upgrade failed.", "output": str(exc), "restarting": False}if plan.preflight_error:return {"ok": False,@@ -6299,8 +6308,9 @@ def do_upgrade(auto_restart: bool = True) -> dict:"output": "The active Avibe generation changed while waiting for the upgrade lock; retry the upgrade.","restarting": False,}- result = subprocess.run(- plan.command,+ result = execute_upgrade_plan(+ plan,+ run=subprocess.run,capture_output=True,text=True,# A wheel install copies the complete candidate environment before@@ -6309,7 +6319,6 @@ def do_upgrade(auto_restart: bool = True) -> dict:# existed. The candidate is isolated now; this is only a bound for# a genuinely hung resolver/download.timeout=UPGRADE_INSTALL_TIMEOUT_SECONDS,- env=plan.env,cwd=safe_cwd,)if result.returncode == 0 and plan.activation is not None:@@ -6321,7 +6330,6 @@ def do_upgrade(auto_restart: bool = True) -> dict:defer_upgrade_activation(plan.activation,parent_pid=os.getpid(),- rollback_to=plan.rollback_to,restart_required=auto_restart and runtime_was_running,prepare_show_runtime=not should_skip_show_runtime_prepare(),)@@ -6355,7 +6363,6 @@ def do_upgrade(auto_restart: bool = True) -> dict:vibe_path=current_vibe_path,trigger="upgrade",prepare_show_runtime=not should_skip_show_runtime_prepare(),- rollback_to=plan.rollback_to,**({"python_executable": str(restart_python)} if restart_python else {}),)restarting = True@@ -8635,13 +8642,425 @@ def reconcile_askill_auto_update() -> dict:# =============================================================================-# Dependencies aggregate + manual install jobs (askill / show runtime)+# Dependencies aggregate + explicit manual install jobs# =============================================================================-_ALLOWED_DEP_INSTALLS = {"askill", "avault", "show-runtime", "memory-runtime", "tmux"}+_ALLOWED_DEP_INSTALLS = {+ "askill",+ "avault",+ "show-runtime",+ "memory-package",+ "memory-runtime",+ "tmux",+}_STARTUP_DEPENDENCY_RECONCILE_LOCK = threading.Lock()_DEFAULT_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 3_MAX_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 10+_MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS = 3+_MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION = 1+++@dataclass(frozen=True)+class _MemoryRequirementProjection:+ required: bool | None+ state: str+ warnings: tuple[str, ...] = ()+++@dataclass(frozen=True)+class _MemoryPackageMetadata:+ provider_count: int | None+ version: str | None++ @property+ def installed(self) -> bool | None:+ if self.provider_count is None:+ return None+ return self.provider_count > 0+++def _load_memory_requirement() -> _MemoryRequirementProjection:+ """Read the persisted requirement before any optional implementation import."""++ try:+ config = V2Config.load()+ except FileNotFoundError:+ return _MemoryRequirementProjection(False, "not_required")+ except Exception: # noqa: BLE001+ logger.warning("Could not read the persisted Memory requirement", exc_info=True)+ return _MemoryRequirementProjection(None, "memory_requirement_unreadable")++ required = config.memory_required+ if required is None:+ return _MemoryRequirementProjection(+ None,+ "memory_requirement_unreadable",+ tuple(config.load_warnings),+ )+ memory_recovered = any(+ section == "memory" or section.startswith("memory.")+ for section in config.recovered_sections+ )+ return _MemoryRequirementProjection(+ required,+ "required" if required else "not_required",+ tuple(config.load_warnings) if memory_recovered else (),+ )+++def _inspect_memory_package_metadata() -> _MemoryPackageMetadata:+ """Inspect canonical distribution providers without importing implementation code."""++ from importlib.metadata import distributions+ from packaging.version import Version++ try:+ providers = tuple(distributions(name=MEMORY_PACKAGE_NAME))+ except Exception: # noqa: BLE001+ return _MemoryPackageMetadata(None, None)+ if len(providers) != 1:+ return _MemoryPackageMetadata(len(providers), None)+ try:+ raw_version = str(providers[0].version).strip()+ version = str(Version(raw_version))+ except Exception: # noqa: BLE001+ version = None+ return _MemoryPackageMetadata(1, version)+++def _published_running_version() -> str | None:+ from packaging.version import InvalidVersion, Version+ from vibe import __version__++ try:+ version = Version(__version__)+ except InvalidVersion:+ return None+ if version.is_devrelease or version.local is not None:+ return None+ return str(version)+++def _memory_versions_match(left: str, right: str) -> bool:+ from packaging.version import Version++ return Version(left) == Version(right)+++def _memory_artifact_status(*, offline: bool) -> tuple[bool, dict]:+ """Import the artifact contract, then inspect EverOS without changing package readiness."""++ failed = {+ "installed": False,+ "status": "missing",+ "manifest": None,+ "reason": "memory_runtime_install_failed",+ }+ try:+ from avibe_memory.artifact import (+ MemoryArtifactManager,+ get_memory_artifact_manager,+ )+ except Exception: # noqa: BLE001+ return False, failed+ try:+ manager = (+ MemoryArtifactManager(offline=True)+ if offline+ else get_memory_artifact_manager()+ )+ status = manager.status()+ if not isinstance(status, dict):+ raise TypeError("Memory artifact status must be a mapping")+ return True, status+ except Exception: # noqa: BLE001+ return True, failed+++def _memory_package_row(+ requirement: _MemoryRequirementProjection,+ metadata: _MemoryPackageMetadata,+ *,+ status: str,+ readiness: str,+ reason: str | None,+ action_class: str,+ current_version: str | None = None,+) -> dict:+ return {+ "id": "memory-package",+ "kind": "runtime",+ "required": requirement.required,+ "installed": metadata.installed,+ "provider_count": metadata.provider_count,+ "version": metadata.version,+ "latest_version": current_version,+ "has_update": bool(+ metadata.version+ and current_version+ and not _memory_versions_match(metadata.version, current_version)+ ),+ "status": status,+ "readiness": readiness,+ "reason": reason,+ "action_class": action_class,+ "warnings": list(requirement.warnings),+ }+++def _memory_runtime_row(+ requirement: _MemoryRequirementProjection,+ runtime: dict | None,+ *,+ reason: str | None = None,+ action_class: str = "none",+) -> dict:+ runtime = runtime or {}+ manifest = runtime.get("manifest") if isinstance(runtime.get("manifest"), dict) else {}+ release_state = manifest.get("release_state")+ if requirement.state == "not_required":+ status = "not_required"+ elif reason is not None:+ status = "error"+ else:+ status = _memory_runtime_dependency_status(runtime)+ return {+ "id": "memory-runtime",+ "kind": "runtime",+ "required": requirement.required,+ "installed": (+ None if requirement.state != "required" and not runtime else bool(runtime.get("installed"))+ ),+ "version": runtime.get("version"),+ "latest_version": runtime.get("selected_version"),+ "has_update": bool(+ runtime.get("installed") and runtime.get("matches_manifest") is False+ ),+ "status": status,+ "reason": reason if reason is not None else runtime.get("reason"),+ "action_class": action_class,+ "release_state": release_state if release_state in {"published", "unavailable"} else None,+ "download_error": runtime.get("download_error"),+ }+++def _memory_runtime_action_class(runtime: dict) -> str:+ if not runtime.get("installed") or runtime.get("matches_manifest") is False:+ return "repairable"+ return "none"+++def _memory_dependencies_status(*, offline: bool) -> tuple[dict, dict]:+ requirement = _load_memory_requirement()+ unknown_metadata = _MemoryPackageMetadata(None, None)+ if requirement.state == "memory_requirement_unreadable":+ reason = "memory_requirement_unreadable"+ return (+ _memory_package_row(+ requirement,+ unknown_metadata,+ status="error",+ readiness=reason,+ reason=reason,+ action_class="operator_only",+ ),+ _memory_runtime_row(requirement, None, reason=reason),+ )++ metadata = _inspect_memory_package_metadata()+ if requirement.state == "not_required":+ current_version = _published_running_version()+ published_install = (+ get_build_identity().kind != "source" and current_version is not None+ )+ if published_install:+ if metadata.provider_count == 0:+ status = "missing"+ reason = "memory_package_missing"+ action_class = "repairable"+ elif metadata.provider_count is None:+ status = "error"+ reason = "memory_package_metadata_unreadable"+ action_class = "operator_only"+ elif metadata.provider_count > 1:+ status = "error"+ reason = "memory_package_metadata_ambiguous"+ action_class = "operator_only"+ elif metadata.version is None:+ status = "error"+ reason = "memory_package_metadata_unreadable"+ action_class = "operator_only"+ elif not _memory_versions_match(metadata.version, current_version):+ status = "error"+ reason = "memory_package_version_mismatch"+ action_class = "repairable"+ else:+ status = "not_required"+ reason = None+ # Disabled means no automatic install, not no recovery path. An+ # exact package can still have a broken import/entry point.+ action_class = "repairable"+ return (+ _memory_package_row(+ requirement,+ metadata,+ status=status,+ readiness="not_required",+ reason=reason,+ action_class=action_class,+ current_version=current_version,+ ),+ _memory_runtime_row(requirement, None),+ )+ return (+ _memory_package_row(+ requirement,+ metadata,+ status="not_required",+ readiness="not_required",+ reason=None,+ action_class="none",+ ),+ _memory_runtime_row(requirement, None),+ )++ current_version = _published_running_version()+ build_is_source = get_build_identity().kind == "source"+ if build_is_source or current_version is None:+ reason = (+ "memory_package_source_build"+ if build_is_source+ else "memory_package_unpublished_build"+ )+ package = _memory_package_row(+ requirement,+ metadata,+ status="error",+ readiness="not_ready",+ reason=reason,+ action_class="operator_only",+ )+ try:+ probe_memory_runtime_entrypoint()+ except Exception: # noqa: BLE001+ return package, _memory_runtime_row(+ requirement,+ None,+ reason="memory_package_runtime_unavailable",+ )+ artifact_imported, runtime = _memory_artifact_status(offline=offline)+ if not artifact_imported:+ return package, _memory_runtime_row(+ requirement,+ None,+ reason="memory_package_artifact_unavailable",+ )+ return package, _memory_runtime_row(+ requirement,+ runtime,+ action_class=_memory_runtime_action_class(runtime),+ )++ if metadata.provider_count == 0:+ reason = "memory_package_missing"+ action_class = "repairable"+ status = "missing"+ elif metadata.provider_count is None:+ reason = "memory_package_metadata_unreadable"+ action_class = "operator_only"+ status = "error"+ elif metadata.provider_count > 1:+ reason = "memory_package_metadata_ambiguous"+ action_class = "operator_only"+ status = "error"+ elif metadata.version is None:+ reason = "memory_package_metadata_unreadable"+ action_class = "operator_only"+ status = "error"+ elif not _memory_versions_match(metadata.version, current_version):+ reason = "memory_package_version_mismatch"+ action_class = "repairable"+ status = "error"+ else:+ reason = None+ action_class = "none"+ status = "ready"+ if reason is not None:+ return (+ _memory_package_row(+ requirement,+ metadata,+ status=status,+ readiness="not_ready",+ reason=reason,+ action_class=action_class,+ current_version=current_version,+ ),+ _memory_runtime_row(requirement, None, reason=reason),+ )++ if _memory_package_restart_retry_required(current_version):+ reason = "memory_package_restart_failed"+ return (+ _memory_package_row(+ requirement,+ metadata,+ status="error",+ readiness="not_ready",+ reason=reason,+ action_class="repairable",+ current_version=current_version,+ ),+ _memory_runtime_row(requirement, None, reason=reason),+ )++ try:+ probe_memory_runtime_entrypoint()+ except Exception: # noqa: BLE001+ reason = "memory_package_runtime_unavailable"+ return (+ _memory_package_row(+ requirement,+ metadata,+ status="error",+ readiness="not_ready",+ reason=reason,+ action_class="repairable",+ current_version=current_version,+ ),+ _memory_runtime_row(requirement, None, reason=reason),+ )+ artifact_imported, runtime = _memory_artifact_status(offline=offline)+ if not artifact_imported:+ reason = "memory_package_artifact_unavailable"+ return (+ _memory_package_row(+ requirement,+ metadata,+ status="error",+ readiness="not_ready",+ reason=reason,+ action_class="repairable",+ current_version=current_version,+ ),+ _memory_runtime_row(requirement, None, reason=reason),+ )+ return (+ _memory_package_row(+ requirement,+ metadata,+ status="ready",+ readiness="ready",+ reason=None,+ action_class="none",+ current_version=current_version,+ ),+ _memory_runtime_row(+ requirement,+ runtime,+ action_class=_memory_runtime_action_class(runtime),+ ),+ )def dependencies_status(*, offline: bool = False) -> dict:@@ -8713,42 +9132,8 @@ def dependencies_status(*, offline: bool = False) -> dict:})- try:- from core.memory.artifact import MemoryArtifactManager, get_memory_artifact_manager-- memory_manager = MemoryArtifactManager(offline=True) if offline else get_memory_artifact_manager()- memory_runtime = memory_manager.status()- except Exception: # noqa: BLE001- memory_runtime = {- "installed": False,- "status": "missing",- "manifest": None,- "reason": "memory_runtime_install_failed",- }- memory_manifest = memory_runtime.get("manifest") if isinstance(memory_runtime.get("manifest"), dict) else {}- release_state = memory_manifest.get("release_state")- try:- memory_required = bool(V2Config.load().memory.enabled)- except Exception: # noqa: BLE001- memory_required = False- deps.append(- {- "id": "memory-runtime",- "kind": "runtime",- "required": memory_required,- "installed": bool(memory_runtime.get("installed")),- "version": memory_runtime.get("version"),- "latest_version": memory_runtime.get("selected_version"),- "has_update": bool(- memory_runtime.get("installed")- and memory_runtime.get("matches_manifest") is False- ),- "status": _memory_runtime_dependency_status(memory_runtime),- "reason": memory_runtime.get("reason"),- "release_state": release_state if release_state in {"published", "unavailable"} else None,- "download_error": memory_runtime.get("download_error"),- }- )+ memory_package, memory_runtime = _memory_dependencies_status(offline=offline)+ deps.extend((memory_package, memory_runtime))try:from core.tmux_runtime import TmuxRuntimeManager, tmux_status@@ -8876,6 +9261,385 @@ def _prepare_memory_runtime_job() -> dict:}+def _memory_package_repair_rejection(*, allow_optional: bool = False) -> dict | None:+ """Recheck the status-owned package repair contract before mutation."""++ try:+ package, _runtime = _memory_dependencies_status(offline=True)+ except Exception: # noqa: BLE001+ logger.warning("Memory package repair admission could not project readiness", exc_info=True)+ reason = "memory_package_admission_unavailable"+ return {+ "ok": False,+ "status": "rejected",+ "message": reason,+ "output": None,+ "reason": reason,+ "action_class": "operator_only",+ }++ provider_count = package.get("provider_count")+ version = package.get("version")+ metadata_readable = provider_count == 0 or (+ provider_count == 1 and isinstance(version, str) and bool(version)+ )+ if (+ (+ package.get("required") is True+ or (allow_optional and package.get("required") is False)+ )+ and package.get("action_class") == "repairable"+ and metadata_readable+ ):+ return None++ reason = package.get("reason")+ if not isinstance(reason, str) or not reason:+ if package.get("required") is False:+ reason = "memory_not_required"+ elif package.get("required") is not True:+ reason = "memory_requirement_unreadable"+ elif package.get("action_class") == "none":+ reason = "memory_package_not_repairable"+ else:+ reason = "memory_package_admission_unavailable"+ return {+ "ok": False,+ "status": "rejected",+ "message": reason,+ "output": None,+ "reason": reason,+ "action_class": "operator_only",+ }+++def _memory_package_auto_repair_state_path() -> Path:+ return paths.get_state_dir() / "memory-package-auto-repair.json"+++def _memory_package_restart_retry_required(version: str) -> bool:+ """Whether package install succeeded but activation restart did not."""++ try:+ payload = json.loads(+ _memory_package_auto_repair_state_path().read_text(encoding="utf-8")+ )+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):+ return False+ return bool(+ isinstance(payload, dict)+ and payload.get("state_version") == _MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION+ and payload.get("core_version") == version+ and payload.get("result") == "failed"+ and payload.get("reason") == "memory_package_restart_failed"+ )+++def _reserve_memory_package_auto_repair_attempt(version: str) -> dict:+ """Persist one automatic attempt before any package mutation begins."""++ state_path = _memory_package_auto_repair_state_path()+ lock_path = state_path.with_name(f".{state_path.name}.lock")+ state_path.parent.mkdir(parents=True, exist_ok=True)+ with MigrationFileLock(lock_path, timeout_seconds=5.0):+ try:+ payload = json.loads(state_path.read_text(encoding="utf-8"))+ except FileNotFoundError:+ payload = {}+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:+ logger.warning("Memory package auto-repair state is unreadable: %s", exc)+ return {+ "allowed": False,+ "attempts": _MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS,+ "reason": "memory_package_auto_repair_state_unreadable",+ }++ if not isinstance(payload, dict) or (+ payload and payload.get("state_version") != _MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION+ ):+ return {+ "allowed": False,+ "attempts": _MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS,+ "reason": "memory_package_auto_repair_state_unreadable",+ }+ attempts = payload.get("attempts", 0) if payload.get("core_version") == version else 0+ if not isinstance(attempts, int) or isinstance(attempts, bool) or attempts < 0:+ return {+ "allowed": False,+ "attempts": _MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS,+ "reason": "memory_package_auto_repair_state_unreadable",+ }+ if attempts >= _MEMORY_PACKAGE_AUTO_REPAIR_MAX_ATTEMPTS:+ return {+ "allowed": False,+ "attempts": attempts,+ "reason": "memory_package_auto_repair_exhausted",+ }++ token = uuid.uuid4().hex+ attempt = {+ "state_version": _MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION,+ "core_version": version,+ "attempts": attempts + 1,+ "result": "running",+ "attempt_token": token,+ "updated_at": datetime.now(timezone.utc).isoformat(),+ }+ write_atomic(state_path, json.dumps(attempt, sort_keys=True) + "\n")+ return {+ "allowed": True,+ "attempts": attempts + 1,+ "token": token,+ }+++def _finish_memory_package_auto_repair_attempt(+ version: str,+ token: str,+ *,+ result: str,+ reason: str | None,+) -> None:+ """Settle only the exact attempt this process reserved."""++ state_path = _memory_package_auto_repair_state_path()+ lock_path = state_path.with_name(f".{state_path.name}.lock")+ try:+ with MigrationFileLock(lock_path, timeout_seconds=5.0):+ payload = json.loads(state_path.read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ return+ if payload.get("core_version") != version or payload.get("attempt_token") != token:+ return+ payload["result"] = result+ payload["reason"] = reason+ payload["updated_at"] = datetime.now(timezone.utc).isoformat()+ write_atomic(state_path, json.dumps(payload, sort_keys=True) + "\n")+ except (OSError, UnicodeError, json.JSONDecodeError, MigrationLockTimeout):+ logger.warning("Memory package auto-repair result could not be persisted", exc_info=True)+++def _record_memory_package_repair_result(+ version: str,+ *,+ result: str,+ reason: str | None,+) -> None:+ """Persist manual activation state without consuming the automatic budget."""++ state_path = _memory_package_auto_repair_state_path()+ lock_path = state_path.with_name(f".{state_path.name}.lock")+ state_path.parent.mkdir(parents=True, exist_ok=True)+ try:+ with MigrationFileLock(lock_path, timeout_seconds=5.0):+ try:+ payload = json.loads(state_path.read_text(encoding="utf-8"))+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):+ payload = {}+ attempts = (+ payload.get("attempts", 0)+ if isinstance(payload, dict) and payload.get("core_version") == version+ else 0+ )+ if not isinstance(attempts, int) or isinstance(attempts, bool) or attempts < 0:+ attempts = 0+ write_atomic(+ state_path,+ json.dumps(+ {+ "state_version": _MEMORY_PACKAGE_AUTO_REPAIR_STATE_VERSION,+ "core_version": version,+ "attempts": attempts,+ "result": result,+ "reason": reason,+ "updated_at": datetime.now(timezone.utc).isoformat(),+ },+ sort_keys=True,+ )+ + "\n",+ )+ except (OSError, MigrationLockTimeout):+ logger.warning("Memory package repair result could not be persisted", exc_info=True)+++def _prepare_memory_package_job(*, automatic: bool = False) -> dict:+ """Install the matching optional package through the existing dependency job."""++ reservation: dict | None = None+ current_version: str | None = None+ try:+ with atomic_upgrade_lock():+ rejection = _memory_package_repair_rejection(+ allow_optional=not automatic,+ )+ if rejection is not None:+ return rejection++ current_version = _published_running_version()+ if current_version is None:+ reason = "memory_package_unpublished_build"+ return {+ "ok": False,+ "message": reason,+ "output": None,+ "reason": reason,+ "action_class": "operator_only",+ }+ current_vibe_path = get_running_vibe_path()+ restart_only = _memory_package_restart_retry_required(current_version)+ if restart_is_pending():+ return {+ "ok": False,+ "message": "memory_package_upgrade_busy",+ "output": None,+ "reason": "memory_package_upgrade_busy",+ }+ if automatic:+ reservation = _reserve_memory_package_auto_repair_attempt(current_version)+ if not reservation.get("allowed"):+ return {+ "ok": False,+ "skipped": True,+ "message": reservation.get("reason"),+ "output": None,+ "reason": reservation.get("reason"),+ "action_class": "repairable",+ "attempts": reservation.get("attempts"),+ }++ output = ""+ if restart_only:+ result = {"ok": True}+ else:+ plan = build_upgrade_plan(+ version=current_version,+ package_name=PACKAGE_NAME,+ memory_package=True,+ memory_version=current_version,+ vibe_path=current_vibe_path,+ )+ if plan.preflight_error:+ return {+ "ok": False,+ "message": "memory_package_install_unsafe",+ "output": plan.preflight_error,+ "reason": "memory_package_install_unsafe",+ }+ install = execute_upgrade_plan(+ plan,+ run=subprocess.run,+ capture_output=True,+ text=True,+ timeout=UPGRADE_INSTALL_TIMEOUT_SECONDS,+ cwd=get_safe_cwd(),+ )+ output = _truncate_install_output(+ ((install.stdout or "") + (f"\n{install.stderr}" if install.stderr else "")).strip()+ )+ if install.returncode != 0:+ result = {+ "ok": False,+ "message": "memory_package_install_failed",+ "output": output or None,+ "reason": "memory_package_install_failed",+ }+ else:+ # Keep the current UI process on its live tool environment+ # so a service-only restart can immediately observe the+ # companion. The shared upgrade lock serializes this exact+ # repair with staged forward upgrades.+ integrity = verify_python_environment(sys.executable)+ result = (+ {"ok": True}+ if integrity.ok+ else {+ "ok": False,+ "message": "memory_package_install_failed",+ "output": integrity.detail,+ "reason": "memory_package_install_failed",+ }+ )+ if result.get("ok"):+ try:+ restart = schedule_restart(+ delay_seconds=2.0,+ vibe_path=current_vibe_path,+ trigger="memory-package-repair",+ scope="service",+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("Memory package repair could not schedule activation restart", exc_info=True)+ result = {+ "ok": False,+ "message": "memory_package_restart_failed",+ "output": output or str(exc),+ "reason": "memory_package_restart_failed",+ "restarting": False,+ }+ else:+ result = {+ "ok": True,+ "message": "memory_package_ready",+ "output": output or None,+ "reason": None,+ "restarting": True,+ "restart": restart,+ }+ except (OSError, subprocess.TimeoutExpired, ValueError, MigrationLockTimeout) as exc:+ logger.warning("Memory package repair failed before completion: %s", exc)+ result = {+ "ok": False,+ "message": "memory_package_install_failed",+ "output": str(exc),+ "reason": "memory_package_install_failed",+ }+ if reservation is not None and current_version is not None:+ _finish_memory_package_auto_repair_attempt(+ current_version,+ str(reservation["token"]),+ result="restart_scheduled" if result.get("restarting") else "failed",+ reason=result.get("reason") if isinstance(result.get("reason"), str) else None,+ )+ elif current_version is not None and (+ result.get("restarting") or result.get("reason") == "memory_package_restart_failed"+ ):+ _record_memory_package_repair_result(+ current_version,+ result="restart_scheduled" if result.get("restarting") else "failed",+ reason=result.get("reason") if isinstance(result.get("reason"), str) else None,+ )+ return result+++def reconcile_memory_package_on_startup() -> dict:+ """Converge an enabled published install onto its exact Memory companion.++ The first upgrade from a bundled-Memory release is executed by the old+ upgrader, which can only request ``avibe-os``. Once the new core starts,+ the persisted enabled state is the durable fact that requires the optional+ companion. Reuse the explicit repair path so package identity, mutation,+ and restart behavior have one implementation.+ """++ package, _runtime = _memory_dependencies_status(offline=True)+ if package.get("required") is True and package.get("action_class") == "repairable":+ return _prepare_memory_package_job(automatic=True)++ reason = package.get("reason")+ if not isinstance(reason, str) or not reason:+ if package.get("required") is False:+ reason = "memory_not_required"+ elif package.get("action_class") == "none":+ reason = "memory_package_ready"+ else:+ reason = "memory_package_not_repairable"+ return {+ "ok": True,+ "skipped": True,+ "reason": reason,+ }++def _prepare_tmux_job() -> dict:try:from core.tmux_runtime import ensure_tmux_installed@@ -8974,6 +9738,7 @@ def reconcile_startup_dependencies() -> dict:started_at = time.monotonic()result: dict[str, Any] = {"ok": True,+ "memory_package": {"ok": False, "status": "unknown"},"node": {"ok": False, "status": "unknown"},"askill": {"ok": False, "status": "unknown"},"avault": {"ok": False, "status": "unknown"},@@ -8981,6 +9746,17 @@ def reconcile_startup_dependencies() -> dict:"tmux": {"ok": False, "status": "unknown"},}try:+ try:+ memory_package = reconcile_memory_package_on_startup()+ except Exception as exc: # noqa: BLE001+ logger.warning("Startup dependency reconcile failed to repair Memory package: %s", exc, exc_info=True)+ memory_package = {+ "ok": False,+ "message": "memory_package_install_failed",+ "reason": "memory_package_install_failed",+ }+ result["memory_package"] = memory_package+try:askill = ensure_askill_installed(force=False)except Exception as exc: # noqa: BLE001@@ -9051,7 +9827,8 @@ def reconcile_startup_dependencies() -> dict:result["duration_ms"] = int((time.monotonic() - started_at) * 1000)result["ok"] = (- bool(result["askill"].get("ok"))+ bool(result["memory_package"].get("ok"))+ and bool(result["askill"].get("ok"))and bool(result["avault"].get("ok"))and bool(result["show_runtime"].get("ok")))@@ -9070,6 +9847,10 @@ def start_dependency_install_job(dep: str) -> dict:"""if dep not in _ALLOWED_DEP_INSTALLS:return {"ok": False, "message": f"Unknown dependency: {dep}"}+ if dep == "memory-package":+ rejection = _memory_package_repair_rejection(allow_optional=True)+ if rejection is not None:+ return rejectionjob_id = uuid.uuid4().hexnow = time.time()@@ -9101,6 +9882,8 @@ def start_dependency_install_job(dep: str) -> dict:result = ensure_avault_installed(force=True)elif dep == "show-runtime":result = _prepare_show_runtime_job()+ elif dep == "memory-package":+ result = _prepare_memory_package_job()elif dep == "memory-runtime":result = _prepare_memory_runtime_job()elif dep == "tmux":diff --git a/vibe/cli.py b/vibe/cli.pyindex 83112faff..3a8fab238 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -63,15 +63,16 @@ from core.watches import ()from vibe import __version__, api, runtimefrom vibe.i18n import normalize_language, t as i18n_t-from vibe.restart_supervisor import RestartState, schedule_restart+from vibe.restart_supervisor import schedule_restartfrom vibe.screenshot import ScreenshotError, capture_screenshotfrom vibe.upgrade import (CURRENT_VIBE_EXECUTABLE_ENV,LEGACY_PACKAGE_NAME,+ MemoryRequirementUnreadableError,PACKAGE_NAME,AtomicActivation,DEFERRED_ACTIVATION_TIMEOUT_SECONDS,- RollbackTarget,+ RestartState,activate_installer_candidate,activate_upgrade_candidate,activation_block_reason,@@ -79,6 +80,8 @@ from vibe.upgrade import (atomic_upgrade_lock,build_upgrade_plan,cache_running_vibe_path,+ configured_memory_enabled,+ execute_upgrade_plan,defer_upgrade_activation,get_latest_version_info,get_safe_cwd,@@ -550,6 +553,8 @@ _MEMORY_CLI_REASON_I18N_KEYS = {"memory_delete_data_failed": "memory.cli.reason.deleteDataFailed","memory_reconfigure_failed": "memory.cli.reason.reconfigureFailed","memory_operation_in_progress": "memory.cli.reason.operationInProgress",+ "memory_implementation_unavailable": "memory.cli.reason.implementationUnavailable",+ "memory_implementation_incompatible": "memory.cli.reason.implementationIncompatible",}_DOCTOR_MEMORY_REASON_I18N_KEYS = {"memory_runtime_install_requires_stopped_memory": "memory.cli.reason.runtimeInstallRequiresStoppedMemory",@@ -584,14 +589,23 @@ def _print_memory_cli_error(operation: str, code: str, *, as_json: bool, languagif as_json:print(json.dumps(payload, indent=2))else:- print(i18n_t("memory.cli.error", language, operation=operation, code=code), file=sys.stderr)+ display_code = _memory_cli_label(+ code,+ keys=_MEMORY_CLI_REASON_I18N_KEYS,+ fallback_key="memory.cli.reason.unknown",+ language=language,+ )+ print(+ i18n_t("memory.cli.error", language, operation=operation, code=display_code),+ file=sys.stderr,+ )return 1def _memory_cli_body(response: object, *, fallback: str) -> tuple[dict | None, str | None]:"""Validate the closed controller response shape used by ``vibe memory``."""- from core.memory.types import is_memory_error_code+ from vibe.memory_contract import is_memory_error_codeif not isinstance(response, dict):return None, "memory_provider_response_invalid"@@ -730,7 +744,7 @@ def cmd_memory(args) -> int:from vibe import internal_clientfrom core.caller_context import caller_context_from_env- from core.memory.types import (+ from vibe.memory_contract import (MAX_MEMORY_LIST_PAGE_SIZE,MAX_MEMORY_SEARCH_RESULTS,)@@ -12555,7 +12569,7 @@ def _start_service_after_repair(*,stopped_pids: list[int],) -> dict:- from core.memory.ui_access import generate_ui_read_secret+ from vibe.memory_ui_access import generate_ui_read_secret# This repair stopped the old service and starts a replacement, so it is the# same shape ``cmd_start`` handles when it starts a service beside a@@ -13230,7 +13244,7 @@ def cmd_start():else:_write_status("starting")- from core.memory.ui_access import generate_ui_read_secret+ from vibe.memory_ui_access import generate_ui_read_secret# The Memory UI read proof is a per-launch secret: it reaches a child only# over stdin and is deliberately never persisted, so this launcher can only@@ -14979,17 +14993,28 @@ def cmd_upgrade():if info["error"]:print(f"\033[33mFailed to check for updates: {info['error']}\033[0m")- print("Attempting upgrade anyway...")elif not info["has_update"]:print("\033[32mYou are already using the latest version.\033[0m")return 0else:print(f"New version available: {info['latest']}")- print("\nUpgrading...")-current_vibe_path = cache_running_vibe_path()- plan = build_upgrade_plan(vibe_path=current_vibe_path)+ try:+ plan = build_upgrade_plan(+ vibe_path=current_vibe_path,+ memory_enabled=configured_memory_enabled(),+ target_version=info.get("latest"),+ )+ except MemoryRequirementUnreadableError:+ print(f"\033[31m{i18n_t('update.memoryRequirementUnreadable')}\033[0m")+ return 1+ except ValueError as exc:+ print(f"\033[31mUpgrade failed: {exc}\033[0m")+ return 1+ if info["error"]:+ print("Attempting upgrade anyway...")+ print("\nUpgrading...")if plan.preflight_error:print(f"\033[31mUpgrade cannot be activated safely: {plan.preflight_error}\033[0m")return 1@@ -15012,11 +15037,11 @@ def cmd_upgrade():if plan.activation is not None and activation_block_reason(plan.activation) == "superseded":print("\033[31mUpgrade was superseded by another activation; retry the upgrade.\033[0m")return 1- result = subprocess.run(- plan.command,+ result = execute_upgrade_plan(+ plan,+ run=subprocess.run,capture_output=True,text=True,- env=plan.env,cwd=safe_cwd,timeout=UPGRADE_INSTALL_TIMEOUT_SECONDS,)@@ -15029,7 +15054,6 @@ def cmd_upgrade():defer_upgrade_activation(plan.activation,parent_pid=os.getpid(),- rollback_to=plan.rollback_to,restart_required=runtime_was_running,prepare_show_runtime=not should_skip_show_runtime_prepare(),)@@ -15055,7 +15079,6 @@ def cmd_upgrade():vibe_path=current_vibe_path,trigger="upgrade",prepare_show_runtime=not should_skip_show_runtime_prepare(),- rollback_to=plan.rollback_to,**({"python_executable": str(restart_python)} if restart_python else {}),)except Exception as exc:@@ -15485,11 +15508,22 @@ def _format_byte_size(size: int) -> str:def _managed_runtime_cleaners() -> tuple[tuple[str, Callable[..., dict[str, Any]]], ...]:"""Return the shared-runtime cleanup passes in stable output order."""- from core.memory.artifact import get_memory_artifact_managerfrom core.tmux_runtime import get_tmux_runtime_managerfrom vibe.model_hub_runtime.installer import EngineRuntimeManagerdef clean_memory(*, keep_previous: int, dry_run: bool) -> dict[str, Any]:+ try:+ from avibe_memory.artifact import get_memory_artifact_manager+ except ModuleNotFoundError as exc:+ if exc.name not in {"avibe_memory", "avibe_memory.artifact"}:+ raise+ return {+ "ok": True,+ "removed": [],+ "skipped": True,+ "reason": "memory_implementation_unavailable",+ }+return get_memory_artifact_manager().clean(keep_previous=keep_previous,dry_run=dry_run,@@ -17530,10 +17564,6 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:parser.add_argument("--source-generation")parser.add_argument("--restart", action="store_true")parser.add_argument("--prepare-show-runtime", action="store_true")- parser.add_argument("--rollback-to")- parser.add_argument("--rollback-package")- parser.add_argument("--rollback-python")- parser.add_argument("--rollback-main")args = parser.parse_args(argv)deadline = time.monotonic() + DEFERRED_ACTIVATION_TIMEOUT_SECONDS@@ -17553,18 +17583,6 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:candidate_launcher=Path(args.candidate),source_generation=source_generation,)- if args.restart and args.rollback_to and (not args.rollback_python or not args.rollback_main):- print("deferred upgrade restart is missing its rollback launcher", file=sys.stderr)- return 1- rollback_to = (- RollbackTarget(- version=args.rollback_to,- package=args.rollback_package,- launcher=runtime.ServiceLauncher(python=args.rollback_python, main=args.rollback_main),- )- if args.rollback_to- else None- )activated = Falsetry:with atomic_upgrade_lock():@@ -17585,7 +17603,6 @@ def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:vibe_path=args.launcher,trigger="upgrade",prepare_show_runtime=args.prepare_show_runtime,- rollback_to=rollback_to,python_executable=sys.executable,)except Exception as exc:diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex afd39672f..26f1d0451 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -450,6 +450,7 @@"infoUnavailable": "Update information unavailable. Please try again later.","upgradeFailed": "Upgrade failed. Please check logs.","upgradeFailedShort": "Upgrade failed",+ "memoryRequirementUnreadable": "Upgrade blocked because the persisted Memory requirement could not be read safely.","upgradeFailedSlack": "❌ *Upgrade Failed*\n\nPlease check the logs for details.","updating": "Updating Avibe...","updatingSlack": "⏳ *Updating Avibe...*\n\nPlease wait, the service will restart shortly.",@@ -828,6 +829,8 @@"deleteDataFailed": "Memory data deletion failed","reconfigureFailed": "Memory reconfiguration failed","operationInProgress": "another Memory operation is in progress",+ "implementationUnavailable": "Memory implementation unavailable",+ "implementationIncompatible": "Memory implementation is incompatible","unknown": "unknown reason"},"fault": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex eb85bf4b9..bcc5aac1b 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -450,6 +450,7 @@"infoUnavailable": "更新信息不可用,请稍后重试。","upgradeFailed": "升级失败,请检查日志。","upgradeFailedShort": "升级失败",+ "memoryRequirementUnreadable": "无法安全读取持久化的记忆需求,升级已被阻止。","upgradeFailedSlack": "❌ *升级失败*\n\n请检查日志获取详情。","updating": "正在更新 Avibe...","updatingSlack": "⏳ *正在更新 Avibe...*\n\n请稍等,服务稍后会重启。",@@ -828,6 +829,8 @@"deleteDataFailed": "记忆数据删除失败","reconfigureFailed": "记忆重新配置失败","operationInProgress": "另一项记忆操作正在进行",+ "implementationUnavailable": "记忆实现不可用",+ "implementationIncompatible": "记忆实现不兼容","unknown": "未知原因"},"fault": {diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 280f932f7..959e0d465 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -27,10 +27,10 @@ from typing import Any, AsyncIterator, Literal, Optionalimport httpxfrom config import paths-from core.memory.processing_record import (+from vibe.memory_contract import (+ MAX_AGENTIC_TIMEOUT_SECONDS,PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS,)-from core.memory.types import MAX_AGENTIC_TIMEOUT_SECONDSlogger = logging.getLogger(__name__)@@ -47,14 +47,14 @@ _CHECK_POSIX_SOCKET_MODE = os.name != "nt"# the sources below rather than trusting these numbers to stay in step.## Most Memory reads wait on one provider operation bounded by-# ``core.memory.module.PROVIDER_READ_TIMEOUT_SECONDS`` (20s). Search can first+# ``avibe_memory.module.PROVIDER_READ_TIMEOUT_SECONDS`` (20s). Search can first# probe capabilities and then issue an agentic provider read bounded at 30s,# so it needs a separate transport bound outside both sequential steps.MEMORY_READ_TIMEOUT_SECONDS = 25.0MEMORY_SEARCH_TIMEOUT_SECONDS = 55.0MEMORY_STATUS_TIMEOUT_SECONDS = MEMORY_READ_TIMEOUT_SECONDS-# Processing Record owns its complete identity/journal/provider/store work-# budget; the transport imports that bound so the two processes cannot drift.+# The host contract owns the transport deadline; its relationship test keeps it+# outside the implementation's complete identity/journal/provider/store budget.MEMORY_PROCESSING_RECORD_TIMEOUT_SECONDS = (PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS)@@ -939,14 +939,14 @@ def _memory_cli_session_headers(session_id: str | None) -> dict[str, str] | Nonesession_id = str(session_id or "").strip()if not session_id:return None- from core.memory.http_headers import CALLER_SESSION_HEADER+ from vibe.memory_http_headers import CALLER_SESSION_HEADERreturn {CALLER_SESSION_HEADER: session_id}def _memory_user_key_headers(method: str, path: str, user_key: str) -> dict[str, str]:- from core.memory.http_headers import MEMORY_USER_KEY_HEADER- from core.memory.ui_access import (+ from vibe.memory_http_headers import MEMORY_USER_KEY_HEADER+ from vibe.memory_ui_access import (MEMORY_UI_PROOF_HEADER,build_ui_read_proof,process_ui_read_secret,diff --git a/vibe/memory_contract.py b/vibe/memory_contract.pynew file mode 100644index 000000000..049017b2c--- /dev/null+++ b/vibe/memory_contract.py@@ -0,0 +1,236 @@+"""Lightweight contracts shared by Memory's host-facing HTTP boundary."""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Literal+++MAX_AGENTIC_TIMEOUT_SECONDS = 30.0+# Pinned EverOS 1.2.3 request bounds. Keep every host entry point aligned+# with the provider contract instead of layering a smaller product limit on top.+MAX_MEMORY_SEARCH_RESULTS = 100+MAX_MEMORY_LIST_PAGE_SIZE = 100+# The implementation currently proves a 40-second composite read bound. Keep+# the host transport outside it without importing the optional implementation.+PROCESSING_RECORD_TRANSPORT_TIMEOUT_SECONDS = 45.0++RecallMode = Literal["auto", "keyword", "vector", "hybrid", "agentic"]++# Host-owned capability projection shared by settings and Memory admission.+# Keep the released platform set in one place so host surfaces do not import+# optional implementation modules just to render availability.+IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset(+ {"slack", "discord", "telegram", "lark", "wechat"}+)+++@dataclass(frozen=True)+class RecallPolicy:+ """Host-owned bounded recall policy accepted by Memory HTTP routes."""++ mode: RecallMode = "hybrid"+ max_results: int = 8+ include_profile: bool = True+ include_current_session: bool = False+ timeout_seconds: float | None = None+ max_model_calls: int | None = None+ cost_budget_tokens: int | None = None++ def __post_init__(self) -> None:+ if self.mode not in {"auto", "keyword", "vector", "hybrid", "agentic"}:+ raise ValueError("invalid recall mode")+ if (+ isinstance(self.max_results, bool)+ or not isinstance(self.max_results, int)+ or not 1 <= self.max_results <= MAX_MEMORY_SEARCH_RESULTS+ ):+ raise ValueError("invalid recall result limit")+ if type(self.include_profile) is not bool or type(self.include_current_session) is not bool:+ raise ValueError("invalid recall include policy")+ if self.mode == "agentic":+ if (+ self.timeout_seconds is None+ or isinstance(self.timeout_seconds, bool)+ or not isinstance(self.timeout_seconds, (int, float))+ or not math.isfinite(float(self.timeout_seconds))+ or not 0 < float(self.timeout_seconds) <= MAX_AGENTIC_TIMEOUT_SECONDS+ or isinstance(self.max_model_calls, bool)+ or not isinstance(self.max_model_calls, int)+ or not 1 <= self.max_model_calls <= 4+ or isinstance(self.cost_budget_tokens, bool)+ or not isinstance(self.cost_budget_tokens, int)+ or not 1 <= self.cost_budget_tokens <= 32_000+ ):+ raise ValueError("agentic recall requires bounded budgets")+ elif any(+ value is not None+ for value in (+ self.timeout_seconds,+ self.max_model_calls,+ self.cost_budget_tokens,+ )+ ):+ raise ValueError("non-agentic recall cannot carry agentic budgets")++ @classmethod+ def from_payload(cls, value: object) -> "RecallPolicy":+ if not isinstance(value, dict):+ raise ValueError("invalid recall policy")+ allowed = {+ "mode",+ "max_results",+ "include_profile",+ "include_current_session",+ "timeout_seconds",+ "max_model_calls",+ "cost_budget_tokens",+ }+ if not set(value).issubset(allowed):+ raise ValueError("invalid recall policy")+ mode = value.get("mode", "hybrid")+ budget_fields = {+ "timeout_seconds",+ "max_model_calls",+ "cost_budget_tokens",+ }+ if mode == "agentic":+ if not {"max_results", *budget_fields}.issubset(value):+ raise ValueError("agentic recall requires explicit budgets")+ elif set(value).intersection(budget_fields):+ raise ValueError("non-agentic recall cannot carry agentic budgets")+ return cls(+ mode=mode,+ max_results=value.get("max_results", 8),+ include_profile=value.get("include_profile", True),+ include_current_session=value.get("include_current_session", False),+ timeout_seconds=value.get("timeout_seconds"),+ max_model_calls=value.get("max_model_calls"),+ cost_budget_tokens=value.get("cost_budget_tokens"),+ )++ def payload(self) -> dict[str, object]:+ payload: dict[str, object] = {+ "mode": self.mode,+ "max_results": self.max_results,+ "include_profile": self.include_profile,+ "include_current_session": self.include_current_session,+ }+ if self.mode == "agentic":+ payload.update(+ timeout_seconds=self.timeout_seconds,+ max_model_calls=self.max_model_calls,+ cost_budget_tokens=self.cost_budget_tokens,+ )+ return payload+++def is_memory_principal_id(value: object) -> bool:+ """Validate the opaque principal shape without importing Memory storage."""++ return (+ isinstance(value, str)+ and len(value) == 34+ and value.startswith("u-")+ and all(char in "0123456789abcdef" for char in value[2:])+ )++MemoryErrorCode = Literal[+ "memory_disabled",+ "memory_invalid_input",+ "memory_access_denied",+ "memory_input_too_large",+ "memory_queue_full",+ "memory_low_disk_space",+ "memory_store_unavailable",+ "memory_runtime_missing",+ "memory_runtime_unsupported",+ "memory_runtime_install_failed",+ "memory_reconcile_failed",+ "memory_wake_failed",+ "memory_runtime_busy",+ "memory_permission_denied",+ "memory_disk_unavailable",+ "memory_sidecar_unavailable",+ "memory_provider_timeout",+ "memory_provider_response_invalid",+ "memory_capability_unavailable",+ "memory_processing_failed",+ "memory_loss_confirmation_required",+ "memory_local_data_unusable",+ "memory_legacy_recovery_required",+ "memory_embedding_unavailable",+ "memory_llm_unavailable",+ "memory_rerank_unavailable",+ "memory_multimodal_unavailable",+ "memory_repair_failed",+ "memory_repair_not_required",+ "memory_delete_data_failed",+ "memory_reconfigure_failed",+ "memory_operation_in_progress",+ "memory_implementation_unavailable",+ "memory_implementation_incompatible",+]++# This transport vocabulary is wider than the persistable failure vocabulary.+CLOSED_MEMORY_ERROR_CODES = frozenset(+ {+ "memory_disabled",+ "memory_invalid_input",+ "memory_access_denied",+ "memory_input_too_large",+ "memory_queue_full",+ "memory_low_disk_space",+ "memory_store_unavailable",+ "memory_runtime_missing",+ "memory_runtime_unsupported",+ "memory_runtime_install_failed",+ "memory_reconcile_failed",+ "memory_wake_failed",+ "memory_runtime_busy",+ "memory_permission_denied",+ "memory_disk_unavailable",+ "memory_sidecar_unavailable",+ "memory_provider_timeout",+ "memory_provider_response_invalid",+ "memory_capability_unavailable",+ "memory_processing_failed",+ "memory_loss_confirmation_required",+ "memory_local_data_unusable",+ "memory_legacy_recovery_required",+ "memory_embedding_unavailable",+ "memory_llm_unavailable",+ "memory_rerank_unavailable",+ "memory_multimodal_unavailable",+ "memory_repair_failed",+ "memory_repair_not_required",+ "memory_delete_data_failed",+ "memory_reconfigure_failed",+ "memory_operation_in_progress",+ "memory_implementation_unavailable",+ "memory_implementation_incompatible",+ }+)+++def is_memory_error_code(value: object) -> bool:+ """Return whether *value* is a closed Memory transport error code."""++ return isinstance(value, str) and value in CLOSED_MEMORY_ERROR_CODES+++class MemoryStoreUnavailableError(RuntimeError):+ """The optional Memory store cannot currently serve a host request."""+++class MemoryRuntimeBusyError(RuntimeError):+ """The provider root already belongs to another live Memory runtime."""+++class MemoryImplementationUnavailableError(RuntimeError):+ """The optional Memory implementation is absent or cannot be constructed."""+++class MemoryImplementationIncompatibleError(RuntimeError):+ """The optional Memory implementation lacks the required runtime surface."""diff --git a/core/memory/http_headers.py b/vibe/memory_http_headers.pysimilarity index 100%rename from core/memory/http_headers.pyrename to vibe/memory_http_headers.pydiff --git a/core/memory/project_ids.py b/vibe/memory_project_ids.pysimilarity index 94%rename from core/memory/project_ids.pyrename to vibe/memory_project_ids.pyindex b18a39e05..bda6cbb1b 100644--- a/core/memory/project_ids.py+++ b/vibe/memory_project_ids.py@@ -54,6 +54,12 @@ def is_persisted_memory_project_id(value: object) -> bool:return is_legacy_memory_project_id(value) or is_new_stored_memory_project_id(value)+def is_project_id(value: object) -> bool:+ """Validate any released or current Memory project identifier."""++ return is_persisted_memory_project_id(value)++def parse_writable_memory_project(value: object) -> str:"""Parse a remember/capture project. Missing/null is not handled here."""diff --git a/core/memory/ui_access.py b/vibe/memory_ui_access.pysimilarity index 100%rename from core/memory/ui_access.pyrename to vibe/memory_ui_access.pydiff --git a/vibe/package_shape.py b/vibe/package_shape.pynew file mode 100644index 000000000..538116a5b--- /dev/null+++ b/vibe/package_shape.py@@ -0,0 +1,17 @@+"""Package identities shared by the forward upgrade path."""++from packaging.version import Version+++CORE_PACKAGE_NAME = "avibe-os"+LEGACY_CORE_PACKAGE_NAME = "vibe-remote"+MEMORY_PACKAGE_NAME = "avibe-memory"+MEMORY_SPLIT_MIN_VERSION = Version("3.0.14.dev0")+++__all__ = [+ "CORE_PACKAGE_NAME",+ "LEGACY_CORE_PACKAGE_NAME",+ "MEMORY_PACKAGE_NAME",+ "MEMORY_SPLIT_MIN_VERSION",+]diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 3e14499e6..3fac33f3f 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -1,15 +1,10 @@from __future__ import annotationsimport argparse-import email.parser-import jsonimport loggingimport os-import shleximport subprocessimport time-import urllib.error-import urllib.requestimport uuidfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path@@ -17,64 +12,27 @@ from typing import NamedTuplefrom config import paths-# Imported here, at the top, rather than where the rollback path uses it. This-# process runs the version being rolled back FROM, and a pinned reinstall-# replaces the source tree underneath it, so a first import taken after that-# install reads the OTHER release's source into this process. Importing at module-# load makes every later use a `sys.modules` hit that touches no file. The module-# is pure stdlib, so paying for it on every restart costs nothing.-from storage.backups import find_restorable_backup, next_backup_sequence, restore_sqlite_backupfrom vibe import runtime-from vibe.build_identity import get_build_identityfrom vibe.upgrade import (- LEGACY_PACKAGE_NAME,- PACKAGE_NAME,RestartState,- RollbackTarget,- activate_launcher_target,- atomic_uv_install_root,atomic_upgrade_lock,- _launcher_generation,- get_cli_launcher_path,- _names_a_published_release,- build_upgrade_plan,get_restart_command,get_restart_environment,get_restart_invocation_command,get_safe_cwd,- installed_package_name,)logger = logging.getLogger(__name__)_RESTART_LOG_RETENTION = 10_SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS = 30.0-# Long enough for a package index to be slow, short enough that a hung download-# does not leave the machine sitting with no service forever. A rollback that-# times out is recorded as failed, which is a diagnosable state; a rollback that-# waits without a bound is not.-_ROLLBACK_INSTALL_TIMEOUT_SECONDS = 600.0-# A cold UI process has an interpreter to start and an ASGI app to import before-# it answers, so the 5s default of `wait_for_ui_server` -- sized for a UI started-# next to an already-warm CLI -- is not the right bound here. This one is only-# ever paid in full when the UI is genuinely not coming.-_ROLLBACK_UI_READY_TIMEOUT_SECONDS = 60.0class StartedRuntime(NamedTuple):- """What a start actually launched, and where its UI can be checked.-- The health target travels with the pids because `_start_runtime_processes` is- the only place that resolves it -- it loads the config to decide the bind host- and port -- and a caller that recomputed it would become a second answer to- "where is the UI", free to drift from the one the UI was actually started on.- It is `None` when this job does not own the UI, which is also the answer to- whether this job is in a position to judge the UI at all.- """+ """The process IDs launched by a restart."""service_pid: intui_pid: int | None- ui_health_target: tuple[str, int] | Nonedef _live_ui_pid(candidate: object) -> int | None:@@ -91,202 +49,6 @@ def _live_ui_pid(candidate: object) -> int | None:return candidate if runtime.pid_alive(candidate) else None-def _ui_is_serving(started: StartedRuntime) -> bool:- """Whether the UI this job started is answering its health endpoint."""-- if not started.ui_pid or started.ui_health_target is None:- return False- if not runtime.pid_alive(started.ui_pid):- return False- host, port = started.ui_health_target- return runtime.wait_for_ui_server(host, port, timeout=_ROLLBACK_UI_READY_TIMEOUT_SECONDS)---def _running_ui_version() -> str | None:- """Read the version that is still serving while an upgrade is being staged.-- Releases before the rollback protocol cannot pass a target into the detached- supervisor. The old service is still alive when that supervisor starts, so- its own version endpoint is the last authoritative answer before the old- install is stopped and replaced.- """-- from core.services import settings as settings_service-- config = settings_service.load_config(default_factory=settings_service.default_config)- host = runtime.effective_ui_bind_host(config)- if host in {"0.0.0.0", ""}:- host = "127.0.0.1"- elif host in {"::", "::0"}:- host = "::1"- if ":" in host and not host.startswith("["):- host = f"[{host}]"- base_url = f"http://{host}:{config.ui.setup_port}"- for endpoint in ("/api/version/local", "/api/version"):- try:- with urllib.request.urlopen(f"{base_url}{endpoint}", timeout=2.0) as response:- payload = json.loads(response.read().decode("utf-8"))- except (OSError, ValueError, TypeError, urllib.error.URLError):- continue- version = payload.get("current") if isinstance(payload, dict) else None- if isinstance(version, str) and _names_a_published_release(version):- return version- return None---def _launcher_from_python(python: str) -> runtime.ServiceLauncher | None:- """Pair an interpreter with the service entry point in its install."""-- python_path = Path(python)- package_root = python_path.parent.parent / "lib"- main_candidates = sorted(package_root.glob("python*/site-packages/vibe/service_main.py"))- if not main_candidates:- package_root = python_path.parent.parent / "Lib" / "site-packages"- main_candidates = sorted(package_root.glob("vibe/service_main.py"))- if not main_candidates:- return None- return runtime.ServiceLauncher(python=python, main=str(main_candidates[0]))---def _service_launcher_from_process(pid: int | None) -> runtime.ServiceLauncher | None:- """Read the old launcher from a still-running service or UI command line."""-- if not pid:- return None- command = runtime.get_process_command(pid)- if not command:- return None- try:- argv = [arg.strip("\"'") for arg in shlex.split(command, posix=(os.name != "nt"))]- if Path(argv[0]).name.lower() == "systemd-run" and "--" in argv:- argv = argv[argv.index("--") + 1 :]- if not argv or not Path(argv[0]).name.lower().startswith("python"):- return None- entry = next(- (arg for arg in argv[1:] if not arg.startswith("-") and Path(arg).name in {"main.py", "service_main.py"}),- None,- )- if entry is not None:- return runtime.ServiceLauncher(python=argv[0], main=entry)- # The UI is launched with ``python -c`` rather than service_main.py.- # Its interpreter still identifies the install that owns the old code.- return _launcher_from_python(argv[0])- except (IndexError, ValueError):- return None---def _legacy_service_launcher(- vibe_path: str | None, *, service_pid: int | None = None, ui_pid: int | None = None-) -> runtime.ServiceLauncher:- """Recover the launcher that existed before the package-manager replace.-- The service command is authoritative: the normal ``~/.local/bin/vibe``- symlink may already point at the replacement by the time this process starts.- """-- for pid in (service_pid, ui_pid):- process_launcher = _service_launcher_from_process(pid)- if process_launcher is not None:- return process_launcher-- fallback = runtime.current_service_launcher()- if not vibe_path:- return fallback-- try:- script = Path(vibe_path).resolve()- shebang = script.read_text(encoding="utf-8", errors="replace").splitlines()[0]- python = shebang[2:].strip().split()[0] if shebang.startswith("#!") else ""- python_path = Path(python)- if not python or not python_path.is_file():- return fallback- return _launcher_from_python(str(python_path)) or fallback- except (OSError, IndexError, ValueError):- return fallback---def _launcher_dist_metadata(launcher: runtime.ServiceLauncher) -> list[tuple[str, str]]:- """Read all supported distributions from the launcher's site-packages."""-- site_packages = Path(launcher.main).resolve().parent.parent- entries: list[tuple[str, str]] = []- try:- for metadata_path in sorted(site_packages.glob("*.dist-info/METADATA")):- payload = email.parser.Parser().parsestr(metadata_path.read_text(encoding="utf-8"))- name = str(payload.get("Name") or "").strip()- version = str(payload.get("Version") or "").strip()- if name in {PACKAGE_NAME, LEGACY_PACKAGE_NAME} and version:- entries.append((name, version))- except (OSError, UnicodeError, ValueError):- return []- return entries---def _launcher_package_name(launcher: runtime.ServiceLauncher, *, version: str | None = None) -> str:- """Infer the distribution name that owns a launcher when metadata is stale."""-- metadata = _launcher_dist_metadata(launcher)- if version:- exact = [name for name, candidate in metadata if candidate == version]- if exact:- return exact[0]-- executable = launcher.python.replace("\\", "/")- for package in (PACKAGE_NAME, LEGACY_PACKAGE_NAME):- if f"/uv/tools/{package}/" in executable:- return package- names = {name for name, _version in metadata}- if PACKAGE_NAME in names:- return PACKAGE_NAME- if LEGACY_PACKAGE_NAME in names:- return LEGACY_PACKAGE_NAME- return installed_package_name(python_executable=launcher.python) or PACKAGE_NAME---def _legacy_install_metadata(- launcher: runtime.ServiceLauncher, *, package_name: str-) -> tuple[str, str] | None:- """Read the old release metadata from the launcher-owned site-packages.-- A renamed distribution can leave an older ``vibe-remote`` dist-info beside- the current ``avibe-os`` install. The launcher identifies which side was- running, so unrelated metadata must never win by directory order.- """-- try:- from vibe import __version__ as replacement_version-- for name, version in _launcher_dist_metadata(launcher):- if (- name == package_name- and version- and version != replacement_version- and _names_a_published_release(version)- ):- return version, name- except (OSError, UnicodeError, ValueError):- return None- return None---def _discover_legacy_upgrade_target(*, trigger: str, vibe_path: str | None) -> RollbackTarget | None:- """Build a rollback target for an upgrade initiated by an older release."""-- if trigger != "upgrade":- return None- service_pid = _read_recorded_pid()- ui_pid = _read_recorded_ui_pid()- launcher = _legacy_service_launcher(vibe_path, service_pid=service_pid, ui_pid=ui_pid)- version = _running_ui_version()- package = _launcher_package_name(launcher, version=version)- if version is None:- metadata = _legacy_install_metadata(launcher, package_name=package)- if metadata is None:- return None- version, package = metadata- return RollbackTarget(version=version, package=package, launcher=launcher)--def _now_iso() -> str:return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())@@ -429,19 +191,10 @@ def _runtime_ready_for_config(config) -> bool:def _start_runtime_processes(start_ui: bool = True,- launcher: runtime.ServiceLauncher | None = None,) -> StartedRuntime:- """Start the service, and the UI when this job owns it.-- `launcher` is the install to start them from, and `None` means this one --- which is the right answer for every restart except a rollback, where this- process is running the release being replaced and so is the one install that- must not be started. It is taken once here and handed to both spawns, because- the service and the UI are two halves of one generation: starting them from- different installs is a state neither release was ever tested in.- """+ """Start the service, and the UI when this job owns it."""- from core.memory.ui_access import generate_ui_read_secret, process_ui_read_secret+ from vibe.memory_ui_access import generate_ui_read_secret, process_ui_read_secretfrom core.services import settings as settings_servicepaths.ensure_data_dirs()@@ -465,18 +218,14 @@ def _start_runtime_processes(wait_for_ready=False,initial_ready_timeout=0,memory_ui_secret=memory_ui_secret,- launcher=launcher,)- ui_health_target: tuple[str, int] | None = Noneif start_ui:bind_host = runtime.effective_ui_bind_host(config)- ui_health_target = (bind_host, config.ui.setup_port)ui_pid = runtime.start_ui(bind_host,config.ui.setup_port,wait_for_ready=False,memory_ui_secret=memory_ui_secret,- launcher=launcher,)else:ui_pid = preserved_ui_pid@@ -492,7 +241,7 @@ def _start_runtime_processes(runtime.write_status("error", "service process exited before startup completed", service_pid, ui_pid)raise RuntimeError(f"Vibe service process pid={service_pid} exited before acquiring the service lock")- return StartedRuntime(service_pid, ui_pid, ui_health_target)+ return StartedRuntime(service_pid, ui_pid)def _stop_ui_for_restart() -> tuple[bool, dict[str, float | bool], float, int | None]:@@ -523,282 +272,6 @@ def _stop_runtime_for_restart(stop_ui: bool = True) -> tuple[bool, dict[str, floreturn ui_stopped, ui_timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds-def _failed_generation_still_running(*, include_ui: bool) -> bool:- """Whether anything the failed generation left behind is still alive.-- Measured -- from the lock, the pid file and the process table -- and never- read off whether the stop helpers reported killing something. That report- answers a different question and answers it backwards on the ordinary case: a- version that died in its migration leaves nothing to kill, so `stop_service`- says it stopped nothing, exactly as it does for a process that refused to- die. The restart path above already knew this and asks- `_remaining_service_pids_after_stop` rather than believe the report; asking- it here too is what keeps one fact from having two answers.- """-- if _remaining_service_pids_after_stop():- return True- return bool(include_ui and runtime.ui_pid_file_points_to_running_ui())---def _restore_database_for_rollback(backup_watermark: int | None, write) -> dict:- """Put back the database the version being rolled back from migrated, if it did.-- Whether a migration happened is decided from a number this job read out of- the backup window itself before the new version was allowed to start. Any- rollback point recorded at or above it was written during that window, so it- was written by the version now being rolled back from -- measured by our own- code, before and after, with nothing in between that the failing version got- to report about itself.-- Every cheaper test compares labels and every one of them is wrong on a real- case: the revision stamp and the schema both stay put when a migration- commits rows and then fails, and the wall clock reverses the order of two- attempts if it is corrected backwards between them. `storage.backups` refuses- to answer from those for the same reason.-- No watermark means the job never reached the point of starting the new- version, so no migration of its doing can exist and there is nothing to put- back. That is a normal outcome, not a degraded one.- """-- if backup_watermark is None:- return {"restored": False, "reason": "no_migration_window"}-- backups_dir = paths.get_state_backups_dir()- rollback_point = find_restorable_backup(backups_dir, written_at_or_after=backup_watermark)- if rollback_point is None:- write(f"no rollback point was written at or after backup sequence {backup_watermark}; database left as it is")- return {"restored": False, "reason": "no_rollback_point"}-- db_path = paths.get_sqlite_state_path()- write(f"restoring the database from {rollback_point}")- replaced = restore_sqlite_backup(rollback_point, db_path)- write(f"database restored; the one it replaced is at {replaced}" if replaced else "database restored")- return {- "restored": True,- "restored_from": str(rollback_point),- "replaced_database": str(replaced) if replaced else None,- }---def _roll_back_failed_upgrade(- *,- rollback_to: RollbackTarget,- vibe_path: str | None,- start_ui: bool,- backup_watermark: int | None,- write,- record,-) -> dict:- """Put the machine back on the version it was upgrading from.-- Reached only when a restart has failed AND nothing holds the service lock.- That second half is the whole condition, and it is deliberately not a list of- the failure branches that ought to qualify: such a list is complete only- until the next branch is added, and the branch nobody remembered is exactly- the one that leaves an instance dark. "No service is running" is the property- the upgrade must not be able to produce, so it is what gets asked -- and it- answers correctly for free on the failures that changed nothing, like a stop- that did not stop, where the old service is still serving and rolling back- underneath it would be the damage.-- Nothing of the failed generation is left running first. "No service is- running" is a statement about the lock, and a process can be alive without it- -- one that died before reaching it, or one still on its way there. Left- alone that process is not merely litter: `start_service` adopts a live- recorded pid instead of launching what was just reinstalled, so the rollback- would report success while the failed version is what is running, and the- restore would rewrite the database file under a process holding it open.-- Install, then restore, then start. The install is the step that needs a- package index and so the step most likely to fail, and it is the only one- with no effect on the data: failing there leaves the database exactly as the- upgrade left it, and a rollback that changed nothing is a far better thing to- find than one that half-changed the schema. Restoring before starting is what- makes the started version able to read what it finds.-- Each step is recorded before the next begins, because this process can be- killed mid-rollback and what it has already done to the database has to be- readable afterwards from the status record rather than inferred from the- disk.-- Start comes from `rollback_to.launcher`, never from this process. This- process is the release the rollback is undoing: an upgrade spawns the restart- job through the `vibe` on PATH, which the install has already replaced, so by- the time this runs `sys.executable` names the failed generation. Reading it- here was how a rollback across the `vibe-remote` -> `avibe-os` rename- reinstalled the right release into the right directory, started the wrong one- out of the other directory, and recorded success.- """-- version = rollback_to.version- restore_stable_launcher = bool(- vibe_path and _launcher_generation(Path(vibe_path).expanduser(), atomic_uv_install_root()) is not None- )- rollback: dict = {- "target_version": version,- "state": RestartState.RUNNING.value,- "started_at": _now_iso(),- }- record(rollback)- write(f"rolling back to {version}: no service is running after the failed restart")-- # `start_ui` is also the answer to whether the UI is this job's to manage: a- # service-only restart left the running UI alone on purpose, and quiescing- # must not take it down when starting will not bring it back.- #- # The outcome is then measured rather than taken from what the stop helpers- # report, because a process that resists termination is the entire reason- # this step exists and "did the stop kill something" is not that question.- _stop_runtime_for_restart(stop_ui=start_ui)- quiesced = not _failed_generation_still_running(include_ui=start_ui)- rollback["quiesced"] = quiesced- record(rollback)- if not quiesced:- # Nothing further is safe. The restore rewrites a database file this- # process holds open, and the final start adopts its pid instead of- # launching what was reinstalled -- so a rollback that continued here- # would report success for the version it was rolling back from.- rollback.update(- state=RestartState.FAILED.value,- error=f"the failed generation is still running; not rolling back to {version}",- )- record(rollback)- write(f"cannot roll back to {version}: the failed generation did not stop")- return rollback-- # A staged upgrade leaves the previous tool generation untouched. Reuse it- # directly during rollback; reinstalling the old wheel would reintroduce a- # long, mutable operation into the one path that exists to recover quickly.- rollback_cli_launcher = get_cli_launcher_path(rollback_to.launcher) if restore_stable_launcher else None- if restore_stable_launcher and vibe_path and rollback_cli_launcher is not None:- rollback["install"] = {"method": "atomic", "ok": True, "reused": True}- record(rollback)- write(f"reusing the previous {version} generation")- else:- try:- plan = build_upgrade_plan(vibe_path=vibe_path, version=version, package_name=rollback_to.package)- except Exception as exc:- rollback.update(- state=RestartState.FAILED.value,- error=f"cannot build a pinned install for {version}: {exc}",- )- record(rollback)- return rollback-- rollback["install"] = {"method": plan.method, "ok": None}- record(rollback)- try:- result = subprocess.run(- plan.command,- capture_output=True,- text=True,- env=plan.env,- cwd=get_safe_cwd(),- timeout=_ROLLBACK_INSTALL_TIMEOUT_SECONDS,- )- except Exception as exc:- rollback["install"] = {"method": plan.method, "ok": False, "error": str(exc)}- rollback.update(- state=RestartState.FAILED.value,- error=f"installing {version} failed: {exc}",- )- record(rollback)- return rollback- if result.returncode != 0:- # The installer's own stderr, trimmed: it is the only account of why the- # rollback could not proceed, and the full text can be megabytes of- # resolver output.- detail = (result.stderr or result.stdout or "").strip()[-2000:]- rollback["install"] = {"method": plan.method, "ok": False, "error": detail or f"exit code {result.returncode}"}- rollback.update(- state=RestartState.FAILED.value,- error=f"installing {version} failed with exit code {result.returncode}",- )- record(rollback)- write(f"pinned install of {version} failed: {detail}")- return rollback- rollback["install"] = {"method": plan.method, "ok": True}- record(rollback)- write(f"installed {version} using {plan.method}")-- if restore_stable_launcher and vibe_path and rollback_cli_launcher is not None:- try:- with atomic_upgrade_lock():- activate_launcher_target(vibe_path, rollback_cli_launcher)- except Exception as exc: # noqa: BLE001- rollback.update(- state=RestartState.FAILED.value,- error=f"restoring the active launcher failed: {exc}",- )- record(rollback)- return rollback- rollback["launcher"] = {"restored": True, "path": str(rollback_cli_launcher)}- record(rollback)-- try:- rollback["database"] = _restore_database_for_rollback(backup_watermark, write)- except Exception as exc:- rollback["database"] = {"restored": False, "error": str(exc)}- rollback.update(- state=RestartState.FAILED.value,- error=f"restoring the database failed: {exc}",- )- record(rollback)- return rollback- record(rollback)-- try:- started = _start_runtime_processes(start_ui=start_ui, launcher=rollback_to.launcher)- except Exception as exc:- rollback.update(- state=RestartState.FAILED.value,- error=f"starting {version} failed: {exc}",- )- record(rollback)- return rollback- ready_pid = runtime.wait_for_service_ready(started.service_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS)- if ready_pid is None:- rollback.update(- state=RestartState.FAILED.value,- service_pid=started.service_pid,- error=f"{version} started but service pid {started.service_pid} did not finish starting",- )- record(rollback)- return rollback-- # The UI is checked too, and only here. It is started with- # `wait_for_ready=False` so a slow asset load cannot stall the service's own- # readiness, but not waiting for it is not the same as not checking it: this- # rollback is unattended and is the last line of defence, so "the machine is- # back" has to mean every process this job took down came back. An ordinary- # `vibe restart` deliberately does not gate on this -- a human is watching it,- # and failing a restart on a slow UI would be a worse answer than reporting- # it (see the PR's known-by-design ledger).- ui_serving: bool | None = None- if start_ui:- ui_serving = _ui_is_serving(started)- rollback["ui"] = {"pid": started.ui_pid, "serving": ui_serving}- runtime.write_status("running", f"pid={ready_pid}", ready_pid, _live_ui_pid(started.ui_pid))- if ui_serving is False:- rollback.update(- state=RestartState.FAILED.value,- service_pid=ready_pid,- error=(- f"rolled back to {version} and the service is running as pid {ready_pid}, "- f"but the Web UI this rollback restarted never started serving"- ),- )- record(rollback)- write(f"rolled back to {version} but the Web UI did not come back; service pid={ready_pid}")- return rollback- rollback.update(state=RestartState.SUCCEEDED.value, service_pid=ready_pid, error=None)- record(rollback)- write(f"rolled back to {version}; service pid={ready_pid}")- return rollback--def _wait_for_service_lock_release(timeout: float = _SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS) -> bool:deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:@@ -818,7 +291,6 @@ def _run_restart_job(trigger: str,scope: str = "all",prepare_show_runtime: bool = False,- rollback_to: RollbackTarget | None = None,) -> int:# "service": restart only the service process, leaving the Web UI process# running (a config change shouldn't tear down the open Web UI). "all"@@ -831,20 +303,6 @@ def _run_restart_job(safe_cwd = get_safe_cwd()_prune_restart_logs()- rollback_target_source = "explicit" if rollback_to else None- rollback_discovery_error: str | None = None- legacy_target_required = trigger == "upgrade" and get_build_identity().kind == "package"- if rollback_to is None and trigger == "upgrade":- try:- rollback_to = _discover_legacy_upgrade_target(trigger=trigger, vibe_path=vibe_path)- if rollback_to is not None:- rollback_target_source = "running_service"- except Exception as exc:- # Older releases do not know how to carry a target. Discovery is a- # compatibility aid; if it cannot identify one, the job fails closed- # before stopping the old runtime rather than creating a dark one.- rollback_discovery_error = str(exc)-with log_path.open("a", encoding="utf-8") as log:def write(message: str) -> None:log.write(f"{_now_iso()} {message}\n")@@ -862,56 +320,9 @@ def _run_restart_job(def mark_duration(name: str, started_at: float) -> float:return record_duration(name, _rounded_seconds(time.monotonic() - started_at))- # The backup sequence read just before the new version was allowed to- # start, which is what tells a rollback whether that version migrated the- # database. None until then, and None is the right answer for a failure- # that never got that far: nothing it could have migrated exists.- backup_watermark: int | None = None-- def record_rollback(rollback: dict) -> None:- payload["rollback"] = dict(rollback)- _write_status(payload)-def fail(error: str, return_code: int, *, started_at: float | None = None) -> int:- """End this job as failed, rolling back first when nothing is running.-- Every failure in this job goes through here rather than each branch- deciding whether it is the kind that warrants a rollback. Which- branches those are is not knowable as a list -- the next branch added- would not be on it -- so the decision is made once, from the state the- upgrade must never be able to produce: no service holding the lock.- """-- if rollback_to and not runtime.verified_service_running():- try:- _roll_back_failed_upgrade(- rollback_to=rollback_to,- vibe_path=vibe_path,- start_ui=restart_ui,- backup_watermark=backup_watermark,- write=write,- record=record_rollback,- )- except Exception as exc:- # A rollback that raises must not swallow the failure that- # caused it: the original error is what the operator needs,- # and the rollback's own is recorded beside it.- record_rollback(- {- "target_version": rollback_to.version,- "state": RestartState.FAILED.value,- "error": str(exc),- }- )- write(f"rollback to {rollback_to.version} raised: {exc}")- elif rollback_to:- record_rollback(- {- "target_version": rollback_to.version,- "state": RestartState.SKIPPED.value,- "reason": "service_running",- }- )+ """Record a terminal restart failure for operator-visible retry."""+return _fail(payload, error, log, return_code, started_at=started_at)old_pid = _read_recorded_pid()@@ -925,25 +336,10 @@ def _run_restart_job(# seeds with the spawned subprocess pid (this process is that pid)."supervisor_pid": os.getpid(),"supervisor_started_at": runtime.process_create_time(os.getpid()),- "state": (- RestartState.SCHEDULED.value- if delay_seconds > 0- else RestartState.RUNNING.value- ),+ "state": RestartState.SCHEDULED.value if delay_seconds > 0 else RestartState.RUNNING.value,"trigger": trigger,"delay_seconds": delay_seconds,"scope": scope,- # Recorded whether or not a rollback ends up happening, so a failed- # restart with no `rollback` record is readable: armed and killed- # before it could recover, versus never recoverable at all. All three- # fields of the target, because a record that named the version and- # the distribution but not the install would be silent about the one- # of the three that has actually been wrong in production.- "rollback_to": rollback_to.version if rollback_to else None,- "rollback_package": rollback_to.package if rollback_to else None,- "rollback_launcher": rollback_to.launcher._asdict() if rollback_to else None,- "rollback_target_source": rollback_target_source,- "rollback_discovery_error": rollback_discovery_error,"old_pid": old_pid,"new_pid": None,"log_path": str(log_path),@@ -964,13 +360,6 @@ def _run_restart_job(write("restart job started after delay")restart_started_at = time.monotonic()- if legacy_target_required and rollback_to is None:- return fail(- "legacy upgrade rollback target unavailable; existing runtime was left running",- 2,- started_at=restart_started_at,- )-write("stopping UI and service" if restart_ui else "stopping service (Web UI kept running)")stop_runtime_started_at = time.monotonic()try:@@ -1000,15 +389,6 @@ def _run_restart_job(return fail("service lock did not release after stopping runtime", 2, started_at=restart_started_at)mark_duration("wait_service_lock_release_seconds", wait_lock_release_started_at)- if rollback_to:- # Read here and nowhere else: the service is stopped, its lock is- # released, and the new version has not run yet, so this is the last- # instant at which the window still holds only what earlier versions- # put there. Every backup numbered at or above it afterwards was- # written by the version about to start.- backup_watermark = next_backup_sequence(paths.get_state_backups_dir())- write(f"pre-start backup sequence is {backup_watermark}; rollback target is {rollback_to.version}")-write("starting service")start_runtime_started_at = time.monotonic()try:@@ -1115,16 +495,11 @@ def schedule_restart(scope: str = "all",prepare_show_runtime: bool = False,memory_ui_secret: str | None = None,- rollback_to: RollbackTarget | None = None,python_executable: str | None = None,) -> dict:- """Serialize every restart seed with install activation and pruning."""-+ """Serialize restart seeding with staged install activation."""from storage.migrations import guard_source_checkout_default_state_bootstrap- # The lock lives under the runtime directory. Preserve the development- # guard's contract by checking it before lock acquisition can create that- # directory.guard_source_checkout_default_state_bootstrap()with atomic_upgrade_lock():return _schedule_restart_locked(@@ -1134,7 +509,6 @@ def schedule_restart(scope=scope,prepare_show_runtime=prepare_show_runtime,memory_ui_secret=memory_ui_secret,- rollback_to=rollback_to,python_executable=python_executable,)@@ -1147,34 +521,18 @@ def _schedule_restart_locked(scope: str,prepare_show_runtime: bool,memory_ui_secret: str | None,- rollback_to: RollbackTarget | None,python_executable: str | None,) -> dict:- """Spawn the detached restart job.-- `rollback_to` is the install currently on the machine, and passing it is what- makes this restart recoverable: if the restart fails and leaves nothing- holding the service lock, the job reinstalls exactly that release, puts back- the database if the new one migrated it, and starts the service again. Only- an upgrade has an answer for it -- a plain restart is already running the- version it would roll back to, so there is nothing to reinstall and the- failure is the operator's to look at.-- It arrives as one value from `rollback_target()` rather than as a version, a- distribution name and an install, because a caller that can pass one without- the others eventually does, and what it produces then is a pin naming a- release that was never published, or a reinstall of the right release- followed by a start of the wrong one. The argv below is the only place the- three are apart, and only because a command line has no other shape; `main()`- is the only place they are put back together.- """- from core.memory.ui_access import process_ui_read_secret+ """Spawn the detached restart job while the caller owns activation."""+ from vibe.memory_ui_access import process_ui_read_secret+memory_ui_secret = memory_ui_secret or process_ui_read_secret()job_id = uuid.uuid4().hex[:12]- if python_executable:- invocation = [python_executable, "-c", "from vibe.cli import main; main()", "restart"]- else:- invocation = get_restart_invocation_command(vibe_path=vibe_path)+ invocation = (+ [python_executable, "-c", "from vibe.cli import main; main()", "restart"]+ if python_executable+ else get_restart_invocation_command(vibe_path=vibe_path)+ )command = [*invocation[:-1], "__restart-supervisor"] if invocation and invocation[-1] == "restart" else [*(invocation or ["vibe"]),"__restart-supervisor",@@ -1186,28 +544,8 @@ def _schedule_restart_locked(command.extend(["--vibe-path", vibe_path])if prepare_show_runtime:command.append("--prepare-show-runtime")- if rollback_to:- command.extend(- [- "--rollback-to",- rollback_to.version,- # Not optional the way the package name is. A missing package- # name still leaves `build_upgrade_plan` a defensible default,- # while a missing launcher leaves the job with only its own --- # which, in the case this exists for, is the release being- # undone.- "--rollback-python",- rollback_to.launcher.python,- "--rollback-main",- rollback_to.launcher.main,- ]- )- if rollback_to.package:- command.extend(["--rollback-package", rollback_to.package])env = get_restart_environment(vibe_path=vibe_path)if python_executable:- # A candidate supervisor must import the staged wheel, never a source- # checkout inherited from the parent process.env = dict(os.environ if env is None else env)env.pop("PYTHONPATH", None)env.pop("PYTHONHOME", None)@@ -1273,7 +611,7 @@ def _schedule_restart_locked(def main(argv: list[str] | None = None) -> int:- from core.memory.ui_access import initialize_process_ui_read_secret+ from vibe.memory_ui_access import initialize_process_ui_read_secretinitialize_process_ui_read_secret()parser = argparse.ArgumentParser()@@ -1283,25 +621,16 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--scope", default="all", choices=("all", "service"))parser.add_argument("--vibe-path")parser.add_argument("--prepare-show-runtime", action="store_true")- parser.add_argument("--rollback-to")- parser.add_argument("--rollback-package")- parser.add_argument("--rollback-python")- parser.add_argument("--rollback-main")+ # A released scheduler can replace the package before launching this parser.+ # Accept its retired rollback argv so the normal restart still runs, but do+ # not carry any of these values into job state or behavior.+ parser.add_argument("--rollback-to", help=argparse.SUPPRESS)+ parser.add_argument("--rollback-package", help=argparse.SUPPRESS)+ parser.add_argument("--rollback-memory-package", action="store_true", help=argparse.SUPPRESS)+ parser.add_argument("--rollback-memory-version", help=argparse.SUPPRESS)+ parser.add_argument("--rollback-python", help=argparse.SUPPRESS)+ parser.add_argument("--rollback-main", help=argparse.SUPPRESS)args = parser.parse_args(argv)- # The one place a rollback target is apart, and so the one place it is put- # back together. Reassembling here rather than passing four values inward- # means nothing downstream can hold a version without the install it names --- # and an incomplete `--rollback-*` set is refused outright rather than- # quietly completed from this process, which is the failed release.- rollback_to = None- if args.rollback_to:- if not args.rollback_python or not args.rollback_main:- parser.error("--rollback-to requires --rollback-python and --rollback-main")- rollback_to = RollbackTarget(- version=args.rollback_to,- package=args.rollback_package,- launcher=runtime.ServiceLauncher(python=args.rollback_python, main=args.rollback_main),- )return _run_restart_job(job_id=args.job_id,delay_seconds=max(0.0, args.delay_seconds),@@ -1309,7 +638,6 @@ def main(argv: list[str] | None = None) -> int:trigger=args.trigger,scope=args.scope,prepare_show_runtime=args.prepare_show_runtime,- rollback_to=rollback_to,)diff --git a/vibe/runtime.py b/vibe/runtime.pyindex ac6fc5417..27e2d4a74 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -1035,7 +1035,7 @@ def _memory_ui_child_env() -> dict[str, str] | None:if memory_ui_secret is None:return env- from core.memory.ui_access import MEMORY_UI_SECRET_STDIN_ENV+ from vibe.memory_ui_access import MEMORY_UI_SECRET_STDIN_ENVchild_env = dict(os.environ if env is None else env)child_env[MEMORY_UI_SECRET_STDIN_ENV] = "1"@@ -1850,7 +1850,7 @@ def _resolve_service_pid("""from storage.migrations import guard_source_checkout_default_state_bootstrap- from core.memory.ui_access import process_ui_read_secret+ from vibe.memory_ui_access import process_ui_read_secretmemory_ui_secret = memory_ui_secret or process_ui_read_secret()guard_source_checkout_default_state_bootstrap()@@ -2079,7 +2079,7 @@ def start_ui(memory_ui_secret: str | None = None,launcher: ServiceLauncher | None = None,):- from core.memory.ui_access import process_ui_read_secret+ from vibe.memory_ui_access import process_ui_read_secretmemory_ui_secret = memory_ui_secret or process_ui_read_secret()pid_path = paths.get_runtime_ui_pid_path()diff --git a/vibe/ui_memory_routes.py b/vibe/ui_memory_routes.pyindex f80e75527..840f7c046 100644--- a/vibe/ui_memory_routes.py+++ b/vibe/ui_memory_routes.py@@ -81,7 +81,7 @@ def _processing_record_list_query(raise ValueError("invalid Processing Record limit")project = values.get("project")if project is not None:- from core.memory.project_ids import parse_agent_search_project+ from vibe.memory_project_ids import parse_agent_search_projectproject = parse_agent_search_project(project)return cursor, limit, project@@ -104,7 +104,7 @@ def _processing_record_entry_query(raise ValueError("invalid Processing Record entry id")project = values.get("project")if project is not None:- from core.memory.project_ids import parse_agent_search_project+ from vibe.memory_project_ids import parse_agent_search_projectproject = parse_agent_search_project(project)return memcell_id, project@@ -146,7 +146,7 @@ def _memory_settings_projection(memory: object) -> dict:def _memory_im_attachment_capture_available(config: V2Config) -> bool:- from core.memory.attachments import IM_ATTACHMENT_CAPTURE_PLATFORMS+ from vibe.memory_contract import IM_ATTACHMENT_CAPTURE_PLATFORMSreturn bool(IM_ATTACHMENT_CAPTURE_PLATFORMS.intersection(config.enabled_platforms())@@ -331,7 +331,7 @@ def _memory_preflight_projection(payload: dict) -> dict:def _memory_closed_error(payload: dict, *, fallback: str) -> str:- from core.memory.types import is_memory_error_code+ from vibe.memory_contract import is_memory_error_codevalue = payload.get("error")return value if is_memory_error_code(value) else fallback@@ -739,7 +739,7 @@ def register_memory_routes(app) -> None:query = payload.get("query")if not isinstance(query, str):return _memory_response({"status": "failed", "error": "memory_invalid_input"}, status_code=400)- from core.memory.types import RecallPolicy+ from vibe.memory_contract import RecallPolicytry:policy = RecallPolicy.from_payload(payload.get("policy"))@@ -795,8 +795,8 @@ def register_memory_routes(app) -> None:cursor = payload.get("cursor")limit = payload.get("limit", 20)origin = payload.get("origin")- from core.memory.runtime import MEMORY_LIST_CURSOR_MAX_BYTES- from core.memory.types import MAX_MEMORY_LIST_PAGE_SIZE+ from core.memory_loader import MEMORY_LIST_CURSOR_MAX_BYTES+ from vibe.memory_contract import MAX_MEMORY_LIST_PAGE_SIZEcursor_bytes: int | None = Noneif isinstance(cursor, str):diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex b10a4bee2..e54bfa36b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -6179,6 +6179,17 @@ def _web_push_user_key() -> str:return "local"+def _workbench_author_id() -> str | None:+ """Return an author only when the browser passes strict Memory admission."""++ memory_user_key = memory_ui_user_key()+ prefix = "avibe:"+ if not isinstance(memory_user_key, str) or not memory_user_key.startswith(prefix):+ return None+ author_id = memory_user_key[len(prefix) :].strip()+ return author_id or None++def _web_push_normal_delivery_diagnostics() -> dict:"""Explain the normal-path authorization gates for the calling owner.@@ -6215,22 +6226,6 @@ def _web_push_normal_delivery_diagnostics() -> dict:return evaluation-def _workbench_memory_user_id() -> str | None:- """Resolve only identities that may use scoped Memory commands."""-- if is_direct_loopback_memory_request():- return "local"- config = _load_remote_access_config()- if config is None:- return None- try:- payload = _resolved_remote_session_payload(config)- except Exception:- return None- subject = payload.get("sub") if isinstance(payload, dict) else None- return f"remote:{subject}" if isinstance(subject, str) and subject.strip() else None--@app.route("/api/web-push/status", methods=["GET", "POST"])def web_push_status():from core.web_push import load_or_create_vapid_keys@@ -6410,13 +6405,6 @@ def version():return jsonify(api.get_version_info())[email protected]("/api/version/local")-def local_version():- from vibe import api-- return jsonify(api.get_local_version_info())--# =============================================================================# POST Endpoints# =============================================================================@@ -7252,7 +7240,7 @@ def ui_reload():import sysimport timefrom config import paths as config_paths- from core.memory.ui_access import process_ui_read_secret+ from vibe.memory_ui_access import process_ui_read_secretcommand = f"from vibe.ui_server import run_ui_server; run_ui_server('{bind_host}', {port})"memory_ui_secret = process_ui_read_secret()@@ -7844,12 +7832,19 @@ def backend_restart(name):return jsonify(api.restart_backend(name, metadata=metadata))-_ALLOWED_DEPENDENCIES = {"askill", "avault", "show-runtime", "memory-runtime", "tmux"}+_ALLOWED_DEPENDENCIES = {+ "askill",+ "avault",+ "show-runtime",+ "memory-package",+ "memory-runtime",+ "tmux",+}@app.route("/api/dependencies")def get_dependencies():- """Status of required local runtime dependencies (askill, Show runtime, Node)."""+ """Status of local tool, package, and managed-runtime dependencies."""from vibe import apireturn jsonify(api.dependencies_status())@@ -11132,32 +11127,26 @@ async def sessions_messages_create(session_id: str):in Step 6 — the session-scoped stream replaced it."""- from core.memory.admission import (- MEMORY_CLI_ADMITTED_METADATA,- MEMORY_ORDINARY_TEXT_METADATA,- MEMORY_USER_ID_METADATA,- )from core.services import sessions as workbench_sessions_servicefrom core.web_push_notifications import (WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA,web_push_authorization_context_record,)- from modules.im.message_facts import is_ordinary_workbench_text+ from modules.im.message_facts import workbench_message_kindfrom storage import messages_service, resource_access_servicefrom storage.agent_session_rows import session_is_runtime_ownedfrom vibe import internal_clientpayload = request.json or {}- memory_user_id = _workbench_memory_user_id()- memory_cli_admitted = memory_user_id is not Nonetext = payload.get("text")content = payload.get("content")if text is None and not content:return jsonify({"error": "text or content is required"}), 400# A quick-reply click tags the row with the agent message it answers.quick_reply_for = (payload.get("metadata") or {}).get("quick_reply_for")- memory_ordinary_text = is_ordinary_workbench_text(payload, quick_reply_for)+ message_kind = workbench_message_kind(payload, quick_reply_for)web_push_user_key = _web_push_user_key()+ workbench_author_id = _workbench_author_id()web_push_authorization_context = web_push_authorization_context_record(web_push_user_key,getattr(g, "authorization_context", None),@@ -11237,9 +11226,6 @@ async def sessions_messages_create(session_id: str):{**(payload.get("metadata") or {}),"_web_push_user_key": web_push_user_key,- MEMORY_USER_ID_METADATA: memory_user_id,- MEMORY_CLI_ADMITTED_METADATA: memory_cli_admitted,- MEMORY_ORDINARY_TEXT_METADATA: memory_ordinary_text,},getattr(g, "authorization_context", None),)@@ -11263,8 +11249,9 @@ async def sessions_messages_create(session_id: str):text=text if isinstance(text, str) else None,content=content if isinstance(content, dict) else None,metadata=message_metadata,- author_id=web_push_user_key,+ author_id=workbench_author_id,author_name=payload.get("author_name"),+ message_kind=message_kind,),dispatch_text=dispatch_text,history_event={"kind": "admission", "priority": "p3", "state": "reserved"},@@ -11307,13 +11294,11 @@ async def sessions_messages_create(session_id: str):"display_text": message.get("text") or "","content": content if isinstance(content, dict) else None,"metadata": payload.get("metadata") or {},- "author_id": web_push_user_key,+ "author_id": workbench_author_id,"author_name": payload.get("author_name"),"files": attachment_specs,- "user_id": memory_user_id,"message_id": message.get("id"),- "memory_cli_admitted": memory_cli_admitted,- "is_ordinary_text": memory_ordinary_text,+ "message_kind": message_kind,}def _current_delivery_response() -> dict:@@ -16019,9 +16004,17 @@ app.add_event_handler("startup", _start_terminal_service)app.add_event_handler("shutdown", _stop_terminal_service)+async def _wait_for_ui_host_ready() -> None:+ """Do not mutate managed dependencies until Uvicorn accepts traffic."""++ while _server is None or not bool(getattr(_server, "started", False)):+ await asyncio.sleep(0.05)++async def _reconcile_startup_dependencies_task() -> None:start = time.monotonic()try:+ await _wait_for_ui_host_ready()from vibe import apiresult = await asyncio.to_thread(api.reconcile_startup_dependencies)@@ -16086,9 +16079,18 @@ async def _reconcile_startup_dependencies_task() -> None:logger.info("Startup dependencies reconciled in %sms", duration_ms)else:askill = result.get("askill") if isinstance(result.get("askill"), dict) else {}+ memory_package = (+ result.get("memory_package")+ if isinstance(result.get("memory_package"), dict)+ else {}+ )logger.warning(- "Startup dependency reconcile completed with issues in %sms: askill=%s show_runtime=%s",+ "Startup dependency reconcile completed with issues in %sms: memory_package=%s askill=%s show_runtime=%s",duration_ms,+ memory_package.get("message")+ or memory_package.get("reason")+ or memory_package.get("status")+ or memory_package.get("ok"),askill.get("message") or askill.get("status") or askill.get("ok"),show_runtime.get("reason") or show_runtime.get("status") or show_runtime.get("ok"),)@@ -16141,7 +16143,7 @@ def _bind_ui_socket(host: str, port: int) -> socket.socket:def run_ui_server(host: str, port: int) -> None:"""Start the FastAPI UI server."""- from core.memory.ui_access import initialize_process_ui_read_secret+ from vibe.memory_ui_access import initialize_process_ui_read_secretinitialize_process_ui_read_secret()global _UI_RUNTIME_ACTIVE, _serverdiff --git a/vibe/upgrade.py b/vibe/upgrade.pyindex 35731ac4b..2c2e220de 100644--- a/vibe/upgrade.py+++ b/vibe/upgrade.py@@ -12,14 +12,30 @@ import subprocessimport sysimport tempfileimport time+import urllib.parseimport urllib.request-from collections.abc import Mapping+from collections.abc import Callable, Mappingfrom dataclasses import dataclassfrom enum import Enumfrom pathlib import Path-from typing import NamedTuple, cast+from typing import castfrom uuid import uuid4+from packaging.requirements import InvalidRequirement, Requirement+from packaging.utils import (+ InvalidSdistFilename,+ InvalidWheelFilename,+ parse_sdist_filename,+ parse_wheel_filename,+)+from packaging.version import InvalidVersion, Version++from vibe.package_shape import (+ CORE_PACKAGE_NAME,+ LEGACY_CORE_PACKAGE_NAME,+ MEMORY_PACKAGE_NAME as SHAPE_MEMORY_PACKAGE_NAME,+)+from config import paths as config_pathsfrom core.install_integrity import (IntegrityResult,@@ -33,8 +49,11 @@ from vibe import runtime as runtime_modlogger = logging.getLogger(__name__)-PACKAGE_NAME = "avibe-os"-LEGACY_PACKAGE_NAME = "vibe-remote"+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}"DEFAULT_UPDATE_METADATA_URL = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"SHOW_RUNTIME_SKIP_ENV = "VIBE_INSTALL_SKIP_SHOW_RUNTIME"@@ -48,9 +67,6 @@ DEFERRED_ACTIVATION_TIMEOUT_SECONDS = 5 * 60# anything with a path separator, a URL scheme, extras, a marker, or a version# of its own is deliberately excluded. See `pinned_package_spec`._BARE_PACKAGE_NAME_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")-# uv names a tool's directory after the distribution it installed, so this reads-# back the name THIS process was installed under. See `installed_package_name`.-_UV_TOOL_PATH_RE = re.compile(r"/uv/tools/(?P<name>[^/]+)/")# PEP 440-ish parser: release + optional pre-release (a/b/rc) + optional# post + optional dev, plus a local version segment (``+local``) that we# accept but ignore for ordering. Word forms (alpha/beta/preview) are listed@@ -77,6 +93,10 @@ _PRE_ORDER = {}+class MemoryRequirementUnreadableError(ValueError):+ """Persisted configuration cannot safely decide Memory package shape."""++class RestartState(str, Enum):"""Closed restart-state vocabulary and its retention policy."""@@ -98,32 +118,82 @@ class RestartState(str, Enum):@dataclass(frozen=True)class UpgradePlan:- """A command that installs a version of avibe, and what it will replace.-- `rollback_to` travels with the command because of WHEN it has to be taken,- not because the two are related ideas. It describes the install this command- is about to overwrite, and running the command is what destroys the evidence- it is read from -- so the only safe moment to take it is before there is a- command to run.-- Left as a function the caller was told to call early, both call sites called- it late: after `subprocess.run(plan.command)` had already installed- `avibe-os` over a `vibe-remote` machine, so the question "what was this- install published as" had two answers and returned neither, and the rollback- pinned `avibe-os==2.x`, a release that was never published under that name.- Writing the ordering rule into a docstring is what failed; a field cannot be- called late, because there is no plan without the measurement and no install- without the plan.- """+ """A validated package-install command and its execution metadata."""command: list[str]env: dict[str, str] | Nonemethod: str- rollback_to: RollbackTarget | None = None+ preflight_command: list[str] | None = None+ preflight_fallback_command: list[str] | None = Noneactivation: "AtomicActivation | None" = Nonepreflight_error: str | None = None+def execute_upgrade_plan(+ plan: UpgradePlan,+ *,+ run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,+ **run_kwargs: object,+) -> subprocess.CompletedProcess[str]:+ """Run a validated plan after its non-mutating preflight.++ The caller owns package mutation sequencing. This helper deliberately does+ not acquire a lifecycle lock: callers can run the plan synchronously while+ the existing restart supervisor owns any later activation.+ """++ preflight = preflight_upgrade_plan(plan, run=run, **run_kwargs)+ if preflight is not None:+ if preflight.returncode != 0:+ return preflight++ return run(plan.command, env=plan.env, **run_kwargs)+++def preflight_upgrade_plan(+ plan: UpgradePlan,+ *,+ run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,+ **run_kwargs: object,+) -> subprocess.CompletedProcess[str] | None:+ """Resolve a plan without mutating the environment."""++ if plan.preflight_command is None:+ return None++ def run_preflight(command: list[str]) -> subprocess.CompletedProcess[str]:+ scratch_dir: str | None = None+ try:+ if PIP_DOWNLOAD_DEST_PLACEHOLDER in command:+ scratch_dir = tempfile.mkdtemp(prefix="avibe-pip-download-")+ command = [+ scratch_dir if argument == PIP_DOWNLOAD_DEST_PLACEHOLDER else argument+ for argument in command+ ]+ return run(command, env=plan.env, **run_kwargs)+ finally:+ if scratch_dir is not None:+ shutil.rmtree(scratch_dir, ignore_errors=True)++ preflight = run_preflight(plan.preflight_command)+ if (+ preflight.returncode == 0+ or plan.preflight_fallback_command is None+ or not _pip_dry_run_is_unsupported(preflight)+ ):+ return preflight++ return run_preflight(plan.preflight_fallback_command)+++def _pip_dry_run_is_unsupported(result: subprocess.CompletedProcess[str]) -> bool:+ output = f"{result.stdout or ''}\n{result.stderr or ''}".lower()+ return "--dry-run" in output and any(+ marker in output+ for marker in ("no such option", "unknown option", "unrecognized argument")+ )++@dataclass(frozen=True)class AtomicActivation:"""A validated candidate and the stable launcher it will replace."""@@ -267,7 +337,6 @@ def defer_upgrade_activation(activation: AtomicActivation,*,parent_pid: int,- rollback_to: "RollbackTarget | None" = None,restart_required: bool = False,prepare_show_runtime: bool = False,) -> subprocess.Popen:@@ -294,19 +363,6 @@ def defer_upgrade_activation(command.append("--restart")if prepare_show_runtime:command.append("--prepare-show-runtime")- if rollback_to is not None:- command.extend(- [- "--rollback-to",- rollback_to.version,- "--rollback-python",- rollback_to.launcher.python,- "--rollback-main",- rollback_to.launcher.main,- ]- )- if rollback_to.package:- command.extend(["--rollback-package", rollback_to.package])parent_started_at = runtime_mod.process_create_time(parent_pid)if parent_started_at is not None:command.extend(["--parent-started-at", str(parent_started_at)])@@ -571,12 +627,12 @@ def activate_installer_candidate(activation: AtomicActivation) -> None:def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:- """Atomically point a stable launcher at an already installed target."""+ """Atomically point a stable launcher at an installed target."""launcher_path = Path(launcher).expanduser()target_path = Path(target).expanduser()if not target_path.is_file() or not os.access(target_path, os.X_OK):- raise RuntimeError(f"rollback launcher is not executable: {target_path}")+ raise RuntimeError(f"launcher target is not executable: {target_path}")launcher_path.parent.mkdir(parents=True, exist_ok=True)replacement = launcher_path.parent / f".{launcher_path.name}.avibe-{uuid4().hex}.new"try:@@ -984,49 +1040,39 @@ def is_legacy_uv_tool_install(python_executable: str | None = None) -> bool:return f"/uv/tools/{LEGACY_PACKAGE_NAME}/" in executable-def installed_package_name(python_executable: str | None = None) -> str | None:- """The distribution this install was published as.-- Which distribution published the running version is not the same question as- which one the next install should ask for, and the two genuinely differ: a- machine still on `vibe-remote` upgrades to `avibe-os`, that being the rename.- Anything going FORWARD wants the configured spec. Anything going BACK wants- this, because `avibe-os==2.x` names a release that was never published under- that name and an install of it can only fail.-- Asked of the installed metadata first, because that is where the answer- actually is: the distribution that provides the running `vibe` package says- so itself, whatever layout it was installed into. Reading it off the- interpreter path recognised exactly one layout -- uv's tool directory -- and- answered `None` for every supported install that is not one, pip into a- virtualenv among them. `None` there is not neutral: the caller falls back to- the configured FORWARD package, so a `vibe-remote` install in a virtualenv- armed a rollback to `avibe-os==2.x` and spent the one recovery attempt on a- release that was never published.-- The path heuristic stays as the fallback for the case metadata genuinely- cannot answer -- a source checkout, or providers that record the same release,- where naming one would be a guess. `None` when neither can say, which is the- honest answer for a tree that was never installed at all.- """+def memory_package_installed() -> bool:+ """Return whether the optional Memory distribution is installed."""- executable = (python_executable or sys.executable or "").replace("\\", "/")- # Only this process can be asked about its own metadata. A path belonging to- # some OTHER interpreter is answerable only by the layout it is written in.- if not python_executable or executable == (sys.executable or "").replace("\\", "/"):- distributions = _distributions_providing_this_package()- if len(distributions) == 1:- return distributions[0]- # More than one provider is not an unanswerable environment. It is the- # state a rollback leaves behind and never cleans up, so it is the state- # every subsequent upgrade measures its own rollback target in -- see- # `_providers_describing_running_code`.- describing = _providers_describing_running_code()- if len(describing) == 1:- return describing[0]-- match = _UV_TOOL_PATH_RE.search(executable)- return match.group("name") if match else None+ try:+ from importlib.metadata import PackageNotFoundError, distribution++ distribution(MEMORY_PACKAGE_NAME)+ except PackageNotFoundError:+ return False+ except Exception:+ logger.warning("Could not inspect %s metadata; preserving package shape", MEMORY_PACKAGE_NAME, exc_info=True)+ return True+ return True+++def configured_memory_enabled() -> bool:+ """Read the persisted Memory switch for an explicit upgrade action."""++ try:+ from config.v2_config import V2Config++ required = V2Config.load().memory_required+ except FileNotFoundError:+ return False+ except Exception as exc:+ raise MemoryRequirementUnreadableError(+ "The persisted Memory requirement could not be read"+ ) from exc+ if required is None:+ raise MemoryRequirementUnreadableError(+ "The persisted Memory requirement could not be read"+ )+ return requireddef _distributions_providing_this_package() -> list[str]:@@ -1034,10 +1080,18 @@ def _distributions_providing_this_package() -> list[str]:try:from importlib.metadata import packages_distributions+ from packaging.utils import canonicalize_nameexcept ImportError: # pragma: no cover - importlib.metadata ships with 3.10+return []try:- return sorted(set(packages_distributions().get(__name__.split(".")[0], [])))+ memory_name = canonicalize_name(MEMORY_PACKAGE_NAME)+ return sorted(+ {+ name+ for name in packages_distributions().get(__name__.split(".")[0], [])+ if canonicalize_name(name) != memory_name+ }+ )except Exception: # pragma: no cover - a broken environment answers nothinglogger.debug("Failed to read installed distribution metadata", exc_info=True)return []@@ -1067,24 +1121,11 @@ def _providers_recording_a_published_release() -> list[tuple[str, str]]:def _providers_describing_running_code() -> list[str]:- """The providers whose recorded release is the one this process is running.-- One owner for a question two callers ask for different purposes:- `installed_package_name` wants WHICH provider describes the files on disk,- and `installed_metadata_describes_running_code` wants WHETHER they all do.- Answering them separately is how the rename pair got two different rulings one- function apart -- the second was taught that two providers is the state it- exists for, while the first went on reading it as unanswerable.-- That asymmetry is not academic, because the pair is permanent: installing- `avibe-os` over a `vibe-remote` machine never uninstalls the older- distribution, so once a rollback has crossed the rename the tree holds both- forever. `avibe-os` records the release that failed and `vibe-remote` records- the files actually running, and the metadata is what distinguishes them --- naming neither meant every later upgrade armed its rollback with no- distribution, and `pinned_package_spec` fell back to the configured forward- name. `avibe-os==2.9.0` was never published, so that one recovery attempt- could only fail, on a machine that is already down.+ """Return providers whose recorded release matches the running code.++ Multiple providers can remain after the `vibe-remote` to `avibe-os` rename.+ Comparing every published record prevents a forward install from becoming a+ silent no-op when stale metadata claims the requested release is present."""from vibe import __version__@@ -1097,35 +1138,12 @@ def _providers_describing_running_code() -> list[str]:def installed_metadata_describes_running_code() -> bool:- """Whether the installed distribution's recorded version matches the files.-- pip decides whether to act by reading metadata, and a rollback is the one- operation that makes metadata stop describing the code. Installing `avibe-os`- over a `vibe-remote` machine never uninstalls the older distribution, so- after the rollback reinstalls `vibe-remote==3.0.10` the tree holds two: the- files under `vibe/` are 3.0.10, and `avibe-os` still records 3.0.11 with- nothing on disk to back it.-- The next forward upgrade is then a silent no-op. `vibe upgrade` compares this- process's 3.0.10 against the published 3.0.11 and decides to install; pip- reads `avibe-os==3.0.11` as already satisfied and does nothing; the command- reports success and the machine keeps running 3.0.10. Same shape as the- rollback no-op, one release later and with a person watching it happen.-- Measured by comparing our own two answers rather than by trusting either --- the version this process bound at import against the version the metadata- records for each distribution providing it. Unknown answers `True`: only a- disagreement between two published releases is evidence, so a source checkout- or an editable install is never forced on a guess.-- Every provider is asked, not just a single one, because the rename pair is- the state this exists for: after a rollback across `vibe-remote` ->- `avibe-os` the tree holds BOTH, and only one of them can be describing the- files on disk. Treating "more than one provider" as unknown would have made- the exact state described above the one state that answers `True` -- the- check declining to fire on its own scenario. `installed_package_name` reads- the same measurement for the other half of that state; both go through- `_providers_describing_running_code` so neither can be taught it alone.+ """Whether every published provider record matches the running files.++ pip trusts installed metadata when deciding whether an upgrade has work to+ do. A mismatch therefore forces the forward reinstall. Unknown source or+ editable layouts remain unforced because they provide no reliable published+ version to compare."""from vibe import __version__@@ -1150,28 +1168,14 @@ def get_current_vibe_bin_dir(vibe_path: str | None = None) -> str | None:return get_launcher_bin_dir(current_vibe)-class RollbackTarget(NamedTuple):- """The install being replaced, described completely enough to restore it.-- Every field travels with the others because they are one measurement, and- splitting them is exactly how this went wrong, repeatedly and in the same- shape each time: the version was read in the process that predates the- install and the distribution in the one that follows it, so a `vibe-remote`- machine pinned `avibe-os==2.9.4`, a release that never existed. Then the same- seam reappeared one step later -- the right distribution reinstalled, and the- service started from whatever interpreter the restarting process happened to- be running, which after a rename is the tool that replaced this one. It put- the failed release back up and reported the rollback a success.-- So the rule is that nothing about the replaced install is looked up again- later. Anything a rollback needs to know about it is measured here, once, in- the only process that can still see it, and carried. There is no constructor- that reads one field.- """+def get_current_uv_tool_dir(python_executable: str | None = None) -> str | None:+ """Return the logical uv tool root containing the running interpreter."""- version: str- package: str | None- launcher: runtime_mod.ServiceLauncher+ executable = Path(python_executable or sys.executable).expanduser().absolute()+ for parent in executable.parents:+ if parent.name == "tools" and parent.parent.name == "uv":+ return str(parent)+ return Nonedef _names_a_published_release(version: str) -> bool:@@ -1180,10 +1184,7 @@ def _names_a_published_release(version: str) -> bool:A development build's version describes the tree it was built from ratherthan anything published: PEP 440 spells that as a `dev` segment, a localsegment (`+<sha>`), or both, and the regression builder emits exactly that- shape. Testing for one hard-coded sentinel string recognised the fallback- version and nothing else, so a regression instance armed a rollback to- `avibe-os==0.0.0.dev0+<sha>` and spent its one recovery attempt asking an- index for a release that cannot exist there.+ shape.Asking the property instead of listing the strings is what stops the nextunlisted shape from costing the same attempt. Unparseable reads as@@ -1197,74 +1198,93 @@ def _names_a_published_release(version: str) -> bool:return not (match.group("dev") or match.group("local"))-def rollback_target() -> RollbackTarget | None:- """The install a failed restart of THIS process could be put back on.-- Everything here is measured from the running process, and that is the whole- point rather than an implementation detail: this describes the install the- upgrade is about to replace, and once it has been replaced there is nothing- left on the machine to measure. Calling this from the detached restart job- would answer for the install that did the replacing, which is not a rollback.-- Which is why the only caller is :func:`build_upgrade_plan`, and why the- answer reaches everyone else as `UpgradePlan.rollback_to`. As a function- anyone could reach, it was reached at the wrong time -- both upgrade paths- called it after the install they were describing had already been overwritten.-- So: the version from this process's already-bound `__version__`, which the- install on disk cannot change underneath it; the distribution from this- install's own metadata; and the launcher that started this process, because- reinstalling a distribution does not tell anyone how to run it and a rollback- that crosses the `vibe-remote` -> `avibe-os` rename lands in a different tool- directory than the one this process is running out of.-- `None` when the running tree reports no release an index could serve -- a- source checkout, an editable install, a regression build. Handing that string- on as a target would spend the one recovery attempt on a round-trip that- fails, and then report a broken rollback mechanism to whoever is looking at a- dark instance, when the truth is that this install never had a release to go- back to.- """+def _with_memory_extra(package_spec: str) -> str:+ """Add the Memory extra without corrupting URL or local path specs."""- from vibe import __version__+ 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- if not _names_a_published_release(__version__):++def _published_version(value: str | None) -> str | None:+ if not isinstance(value, str):return None- return RollbackTarget(- version=__version__,- package=installed_package_name(),- launcher=runtime_mod.current_service_launcher(),- )+ try:+ version = str(Version(value))+ except InvalidVersion:+ return None+ return version if _names_a_published_release(version) else None+++def _memory_target_version(package_spec: str, target_version: str | None) -> str | None:+ """Choose the Memory pin from the artifact being installed or valid metadata."""++ try:+ requirement = Requirement(package_spec)+ except InvalidRequirement:+ artifact = package_spec+ else:+ if requirement.url is None:+ specifiers = list(requirement.specifier)+ if (+ len(specifiers) == 1+ and specifiers[0].operator == "=="+ and "*" not in specifiers[0].version+ ):+ return _published_version(specifiers[0].version)+ candidate = _published_version(target_version)+ if candidate is not None and requirement.specifier.contains(candidate, prereleases=True):+ return candidate+ return None+ artifact = requirement.url++ if artifact.startswith(("git+", "hg+", "svn+", "bz+")):+ return None+ try:+ parsed = urllib.parse.urlsplit(artifact)+ except ValueError:+ return None+ filename = Path(urllib.parse.unquote(parsed.path if parsed.scheme else artifact)).name+ try:+ _, version, _, _ = parse_wheel_filename(filename)+ except InvalidWheelFilename:+ try:+ _, version = parse_sdist_filename(filename)+ except InvalidSdistFilename:+ return None+ return _published_version(str(version))def pinned_package_spec(- version: str, *, python_executable: str | None = None, package_name: str | None = None+ version: str,+ *,+ package_name: str,) -> str:- """The distribution this install came from, pinned to exactly one version.-- `package_name` is the name measured before the forward install ran, and it- wins when given. Reading the name here instead would read it on the wrong side- of the event: the upgrade replaces the tool before it schedules the restart,- so by the time the detached supervisor asks, the install it can see is the new- one. Only the caller that ran before the install can answer for what was- replaced.-- Falling back to the install on disk, and to configuration after that. A pin is- a claim that a specific release exists under a specific name, and something- has to witness which name that was.-- Raises when the resulting name cannot carry a pin -- a local path, a direct- URL, or a spec that already states its own version. Refusing is the whole- point of the function existing: the caller that wants a pin is rolling back,- and an unpinned command resolves forward to the release it is rolling back- FROM, reinstalling the failure and reporting success. A rollback that cannot- be pinned has to fail loudly instead.+ """Pin one explicit distribution name to one exact published version.++ The explicit Memory install uses this to reinstall the running core release+ together with its matching optional package. The distribution name must be a+ bare package name; direct URLs and pre-versioned requirements are rejected.The message never quotes the spec. An operator-supplied spec can be an index- URL carrying credentials, and this error is written to a restart log.+ URL carrying credentials."""- spec = package_name or installed_package_name(python_executable) or get_upgrade_package_spec()+ spec = package_nameif _BARE_PACKAGE_NAME_RE.fullmatch(spec) is None:raise ValueError("The configured upgrade package spec cannot carry a version pin")return f"{spec}=={version}"@@ -1277,32 +1297,48 @@ def build_upgrade_plan(vibe_path: str | None = None,base_env: dict[str, str] | None = None,version: str | None = None,+ target_version: str | None = None,package_name: str | None = None,+ memory_enabled: bool = False,+ memory_package: bool | None = None,+ memory_version: str | None = None,+ package_spec: str | None = None,) -> UpgradePlan:"""How to install avibe: the newest release, or `version` exactly.- A pinned plan is not an upgrade plan with an extra argument. It never asks- for the newest release, because the caller pinning a version is going- backwards from one -- and both package managers treat "upgrade" as a- direction, not a preference: uv resolves forward past the pin's own- requirement, and pip's `--upgrade` declines to install an older version than- the one already there. So the pin replaces the upgrade request rather than- qualifying it, and `--force` becomes unconditional on the uv path, where- installing over an existing tool is otherwise refused.+ Exact-version plans support the explicit Memory package install action. They+ replace the ordinary upgrade request and force the installer so the matching+ optional distribution is applied even when core is already satisfied."""executable = python_executable or sys.executable- # Taken here, before the command below exists, because that command is what- # makes it unanswerable. A pinned plan is itself a rollback and has none of- # its own: the process building one is the release that failed, so measuring- # there would carry the failure forward as its own recovery target.- rollback_to = None if version else rollback_target()- uv_binary = find_uv_binary(uv_path=uv_path, base_env=base_env)+ # A caller targeting another interpreter (for example a test-owned venv)+ # can provide an explicit package-shape measurement. Only infer from this+ # process when the caller did not provide one; otherwise ambient metadata+ # would leak into the target plan and turn an intentional core-only install+ # into a Memory install.+ include_memory = (+ bool(memory_package)+ if version or memory_package is not None+ else bool(memory_enabled or memory_package_installed())+ )package_spec = (- pinned_package_spec(version, python_executable=executable, package_name=package_name)+ pinned_package_spec(+ version,+ package_name=package_name or PACKAGE_NAME,+ )if version- else get_upgrade_package_spec()+ else (package_spec or get_upgrade_package_spec()))+ if not version and include_memory:+ target_version = _memory_target_version(package_spec, target_version)+ 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+ pinned_memory_spec = f"{MEMORY_PACKAGE_NAME}=={memory_target}" if include_memory and memory_target else Noneif is_uv_tool_install(executable) and uv_binary:env = dict(base_env or os.environ)@@ -1316,19 +1352,34 @@ def build_upgrade_plan(env["UV_TOOL_DIR"] = str(tool_dir)env["UV_TOOL_BIN_DIR"] = str(bin_dir)else:+ current_tool_dir = get_current_uv_tool_dir(executable)vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)+ if current_tool_dir is None:+ preflight_error = "Cannot safely repair uv installation: current tool root is unavailable"+ else:+ env["UV_TOOL_DIR"] = current_tool_dirif vibe_bin_dir:env["UV_TOOL_BIN_DIR"] = vibe_bin_dircommand = [uv_binary, "tool", "install", package_spec]+ if pinned_memory_spec:+ command.extend(["--with", pinned_memory_spec])if not version:command.append("--upgrade")if version or package_spec != PACKAGE_NAME or is_legacy_uv_tool_install(executable):command.append("--force")+ preflight_command = None+ if include_memory:+ preflight_command = [uv_binary, "pip", "install", "--dry-run", "--python", executable]+ if not version:+ preflight_command.append("--upgrade")+ preflight_command.append(package_spec)+ if pinned_memory_spec:+ preflight_command.append(pinned_memory_spec)return UpgradePlan(command=command,env=env,method="uv",- rollback_to=rollback_to,+ preflight_command=preflight_command,activation=atomic,preflight_error=preflight_error,)@@ -1336,30 +1387,63 @@ def build_upgrade_plan(command = [executable, "-m", "pip", "install"]if not version:command.append("--upgrade")- # Neither a pin nor `--upgrade` makes pip act; metadata does, and a rollback- # is what makes metadata stop describing the code. So the command forces- # whenever the version being asked for is not already the version on disk --- # measured here, never read off the metadata that is the thing in doubt.- #- # A pinned plan always forces: it IS the rollback, running on a machine where- # `avibe-os` was just installed over `vibe-remote`, so `pip install- # vibe-remote==<old>` reads as already satisfied, pip does nothing, and the- # supervisor starts the failed generation again and reports success. The uv- # branch above has always forced a pinned install; this branch quietly did- # not. A forward plan forces only once that has happened -- the leftover- # `avibe-os==3.0.11` metadata would otherwise make the next upgrade a no-op- # too, silently, with a person watching it report success.+ # pip decides whether to act from metadata. Exact installs always force so a+ # matching optional package is applied even when core is already satisfied;+ # forward installs force only when published provider metadata disagrees with+ # the running files.if version or not installed_metadata_describes_running_code():command.append("--force-reinstall")command.append(package_spec)+ if pinned_memory_spec:+ command.append(pinned_memory_spec)+ preflight_command = None+ # Preflight only when the optional package shape is part of the operation.+ # Core-only forward installs retain the origin/dev synchronous behavior: the+ # service is still running while pip resolves, so a second resolver pass is+ # unnecessary general-updater machinery.+ preflight_fallback_command = None+ if include_memory and not version:+ preflight_command = [+ executable,+ "-m",+ "pip",+ "install",+ "--dry-run",+ "--upgrade",+ package_spec,+ ]+ preflight_fallback_command = [+ executable,+ "-m",+ "pip",+ "download",+ "--dest",+ PIP_DOWNLOAD_DEST_PLACEHOLDER,+ package_spec,+ ]+ if pinned_memory_spec:+ preflight_command.append(pinned_memory_spec)+ preflight_fallback_command.append(pinned_memory_spec)+ elif include_memory:+ preflight_command = [+ executable,+ "-m",+ "pip",+ "download",+ "--dest",+ PIP_DOWNLOAD_DEST_PLACEHOLDER,+ ]+ preflight_command.extend(["--no-deps", package_spec])+ if pinned_memory_spec:+ preflight_command.append(pinned_memory_spec)return UpgradePlan(command=command,env=dict(base_env or os.environ),method="pip",- rollback_to=rollback_to,+ preflight_command=preflight_command,+ preflight_fallback_command=preflight_fallback_command,)-def get_safe_cwd() -> str:"""Return a stable, existing absolute directory for subprocess cwd.