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
fix(skills): publish built-ins by name in place (#2692)
Call Whitec8f04ba45ffb
diff --git a/core/managed_skills.py b/core/managed_skills.pyindex bba2764f1..5c54310c9 100644--- a/core/managed_skills.py+++ b/core/managed_skills.py@@ -3,7 +3,6 @@from __future__ import annotationsimport errno-import hashlibimport htmlimport jsonimport logging@@ -11,7 +10,6 @@ import osimport reimport shutilimport stat-import structimport subprocessimport threadingimport time@@ -35,8 +33,8 @@ logger = logging.getLogger(__name__)SKILL_WORKING_DIR_ENV = "AVIBE_SKILL_WORKING_DIR"SKILL_PROJECT_BASE_ENV = "AVIBE_SKILL_PROJECT_BASE"-BUILTIN_SKILLS_SNAPSHOT_ENV = "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"BUILTIN_SKILLS_ROOT_ENV = "AVIBE_BUILTIN_SKILLS_ROOT"+BUILTIN_SKILLS_SNAPSHOT_ENV = "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"SKILL_HOME_ENV = "AVIBE_SKILL_HOME"SKILL_CODEX_HOME_ENV = "AVIBE_SKILL_CODEX_HOME"SKILL_CLAUDE_HOME_ENV = "AVIBE_SKILL_CLAUDE_HOME"@@ -59,8 +57,7 @@ CLAUDE_PLUGIN_LIST_MAX_BYTES = 1024 * 1024CLAUDE_PLUGIN_LIST_MAX_ENTRIES = 256CLAUDE_PLUGIN_LIST_TIMEOUT_SECONDS = 1-_SNAPSHOT_DOMAIN = b"avibe-builtin-snapshot-v1\0"-_SNAPSHOT_ID_RE = re.compile(r"^[0-9a-f]{64}$")+_LEGACY_SNAPSHOT_ID_RE = re.compile(r"^[0-9a-f]{64}$")_PORTABLE_NAME_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")_TOP_LEVEL_FIELD_RE = re.compile(r"^[^ \t#][^:]*:")_BLOCK_SCALAR_RE = re.compile(r"^[|>][+-]?[1-9]?$|^[|>][1-9]?[+-]?$")@@ -131,6 +128,7 @@ class _SnapshotEntry:relative: strrelative_bytes: bytesis_directory: bool+ token: tuple[int, int, int, int, int]def _strip_yaml_comment(value: str) -> str:@@ -684,6 +682,7 @@ def _scan_root(budget: _DiscoveryBudget,seen_directory_identities: set[tuple[int, int]] | None = None,ignored_names: frozenset[str] = frozenset(),+ skip_catalog_noise: bool = False,) -> list[ManagedSkill]:children = _root_children(root, ignored_names=ignored_names, budget=budget)if children is None:@@ -691,7 +690,9 @@ def _scan_root(return []skills: list[ManagedSkill] = []- for _, child, child_stat in children:+ for name, child, child_stat in children:+ if skip_catalog_noise and _is_catalog_noise(name, child):+ continueif budget.parse_exhausted:breakresolved_directory = _resolved_candidate_directory(child, child_stat)@@ -792,37 +793,95 @@ def _working_directory(cwd: str | Path | None) -> Path:def _selected_builtin_root(avibe_home: Path,*,- snapshot_id: str | None = None,- snapshot_root: str | Path | None = None,+ catalog_root: str | Path | None = None,) -> Path | None:- selected = snapshot_id if snapshot_id is not None else os.environ.get(BUILTIN_SKILLS_SNAPSHOT_ENV)- bound_root = snapshot_root if snapshot_root is not None else os.environ.get(BUILTIN_SKILLS_ROOT_ENV)+ if catalog_root is not None:+ bound_root = catalog_root+ if not bound_root:+ return None+ elif BUILTIN_SKILLS_ROOT_ENV in os.environ:+ bound_root = os.environ.get(BUILTIN_SKILLS_ROOT_ENV)+ if not bound_root:+ return None+ else:+ bound_root = Noneif bound_root:raw_root = Path(bound_root).expanduser()if not raw_root.is_absolute():return None- root = _absolute_path(raw_root)- if selected is None:- selected = root.name- if selected and root.name != selected:- return None- else:- root = None- if selected is None:+ return _existing_directory(_live_or_backup_catalog(_absolute_path(raw_root)))+ root = avibe_home / "builtin-skills"+ if not _readable_builtin_catalog(root):try:- selected = publish_builtin_skills(destination_root=avibe_home / "builtin-skills")+ publish_builtin_skills(destination_root=root)except Exception:logger.warning("Failed to publish Avibe built-in Skills", exc_info=True)return None- if _SNAPSHOT_ID_RE.fullmatch(selected or "") is None:+ return _existing_directory(root)+++def _existing_directory(path: Path) -> Path | None:+ try:+ value = path.stat(follow_symlinks=False)+ except OSError:return None- if root is None:- root = avibe_home / "builtin-skills" / selected+ return path if stat.S_ISDIR(value.st_mode) else None+++def _catalog_backup_path(destination: Path) -> Path:+ return destination.parent / ".builtin-skills.previous"+++def _catalog_staging_path(destination: Path) -> Path:+ return destination.parent / ".builtin-skills.staging"+++def _live_or_backup_catalog(root: Path) -> Path:+ named = root+ if (+ _LEGACY_SNAPSHOT_ID_RE.fullmatch(root.name) is not None+ and root.parent.name == "builtin-skills"+ ):+ if _existing_directory(root) is not None:+ return root+ named = root.parent+ if _readable_builtin_catalog(named):+ return named+ backup = _catalog_backup_path(named)+ if _readable_builtin_catalog(backup):+ return backup+ return named+++def _is_catalog_noise(name: str, child: Path) -> bool:+ return name.startswith(".") or (+ _LEGACY_SNAPSHOT_ID_RE.fullmatch(name) is not None+ and not (child / "SKILL.md").is_file()+ )+++def _readable_builtin_catalog(root: Path) -> bool:try:root_stat = root.stat(follow_symlinks=False)except OSError:- return None- return root if stat.S_ISDIR(root_stat.st_mode) else None+ return False+ if not stat.S_ISDIR(root_stat.st_mode):+ return False+ try:+ with os.scandir(root) as scanned:+ for entry in scanned:+ child = Path(entry.path)+ if _is_catalog_noise(entry.name, child):+ continue+ try:+ child_stat = entry.stat(follow_symlinks=False)+ except OSError:+ continue+ if stat.S_ISDIR(child_stat.st_mode) and (child / "SKILL.md").is_file():+ return True+ except OSError:+ return False+ return Falsedef _claude_plugin_skill_roots(@@ -972,8 +1031,7 @@ def resolve_skills(claude_home: str | Path | None = None,claude_cli_path: str | None = None,xdg_config_home: str | Path | None = None,- builtin_snapshot_id: str | None = None,- builtin_snapshot_root: str | Path | None = None,+ builtin_catalog_root: str | Path | None = None,) -> list[ManagedSkill]:"""Resolve the live Skill catalog using Avibe's v1 precedence rules."""@@ -1024,11 +1082,17 @@ def resolve_skills(builtin_budget = _DiscoveryBudget()builtin_root = _selected_builtin_root(resolved_avibe_home,- snapshot_id=builtin_snapshot_id,- snapshot_root=builtin_snapshot_root,+ catalog_root=builtin_catalog_root,)if builtin_root is not None:- candidates.extend(_scan_root(builtin_root, priority=(0, 0, 0), budget=builtin_budget))+ candidates.extend(+ _scan_root(+ builtin_root,+ priority=(0, 0, 0),+ budget=builtin_budget,+ skip_catalog_noise=True,+ )+ )compatibility_budget = _DiscoveryBudget()compatibility_directory_identities: set[tuple[int, int]] = set()@@ -1402,8 +1466,11 @@ def _snapshot_entries(root: Path) -> list[_SnapshotEntry]:reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))if reparse_flag and file_attributes & reparse_flag:raise RuntimeError(f"Built-in Skill path is a reparse point: {relative}")+ token = _stat_token(child_stat)if stat.S_ISDIR(child_stat.st_mode):- entries.append(_SnapshotEntry(Path(child.path), relative, relative_bytes, True))+ entries.append(+ _SnapshotEntry(Path(child.path), relative, relative_bytes, True, token)+ )child_directories.append((Path(child.path), child_parts))elif stat.S_ISREG(child_stat.st_mode):file_bytes += int(child_stat.st_size)@@ -1411,7 +1478,9 @@ def _snapshot_entries(root: Path) -> list[_SnapshotEntry]:raise RuntimeError(f"Built-in Skill tree exceeds {BUILTIN_TREE_MAX_BYTES:,} bytes")- entries.append(_SnapshotEntry(Path(child.path), relative, relative_bytes, False))+ entries.append(+ _SnapshotEntry(Path(child.path), relative, relative_bytes, False, token)+ )else:raise RuntimeError(f"Built-in Skill path is not a directory or regular file: {relative}")if relative_parts and accepted_children == 0:@@ -1422,62 +1491,6 @@ def _snapshot_entries(root: Path) -> list[_SnapshotEntry]:return entries-def _update_digest_with_file(- digest: object,- entry: _SnapshotEntry,- *,- remaining_bytes: int,-) -> int:- fd: int | None = None- try:- fd, before = _open_regular_file(entry.path)- file_size = int(before.st_size)- if file_size > remaining_bytes:- raise RuntimeError(- f"Built-in Skill tree exceeds {BUILTIN_TREE_MAX_BYTES:,} bytes"- )- digest.update(struct.pack(">Q", file_size))- remaining = file_size- while remaining:- chunk = os.read(fd, min(1024 * 1024, remaining))- if not chunk:- raise RuntimeError(f"Built-in Skill file changed while hashing: {entry.relative}")- digest.update(chunk)- remaining -= len(chunk)- if os.read(fd, 1):- raise RuntimeError(f"Built-in Skill file grew while hashing: {entry.relative}")- after = os.fstat(fd)- if _stat_token(before) != _stat_token(after):- raise RuntimeError(f"Built-in Skill file changed while hashing: {entry.relative}")- executable = int(before.st_mode & 0o111) if os.name != "nt" else 0- digest.update(bytes((executable,)))- return file_size- finally:- if fd is not None:- os.close(fd)---def snapshot_tree_digest(root: str | Path) -> str:- """Return the frozen snapshot-v1 identifier for a validated tree."""-- source = Path(root).resolve()- if not source.is_dir():- raise RuntimeError(f"Built-in Skills source does not exist: {source}")- digest = hashlib.sha256(_SNAPSHOT_DOMAIN)- consumed_bytes = 0- for entry in _snapshot_entries(source):- digest.update(b"d" if entry.is_directory else b"f")- digest.update(struct.pack(">Q", len(entry.relative_bytes)))- digest.update(entry.relative_bytes)- if not entry.is_directory:- consumed_bytes += _update_digest_with_file(- digest,- entry,- remaining_bytes=BUILTIN_TREE_MAX_BYTES - consumed_bytes,- )- return digest.hexdigest()--def _copy_snapshot_entries(entries: Sequence[_SnapshotEntry], destination: Path) -> None:"""Copy one pre-enumerated tree while charging bytes actually opened."""@@ -1569,95 +1582,111 @@ def _validate_builtin_catalog(root: Path) -> None:raise RuntimeError("Built-in Skill frontmatter exceeds the 8 MiB catalog budget")+def _source_manifest(entries: Sequence[_SnapshotEntry]) -> tuple[tuple[bytes, bool, tuple[int, int, int, int, int]], ...]:+ return tuple((entry.relative_bytes, entry.is_directory, entry.token) for entry in entries)+++def _assert_source_unchanged(source: Path, entries: Sequence[_SnapshotEntry]) -> None:+ if _source_manifest(_snapshot_entries(source)) != _source_manifest(entries):+ raise RuntimeError("Built-in Skill source changed during publication")++def _remove_snapshot_staging(path: Path) -> None:try:- value = path.stat(follow_symlinks=False)+ value = path.lstat()except FileNotFoundError:returnexcept OSError as exc:raise RuntimeError(f"Cannot inspect built-in Skill staging path: {path}") from excreparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))file_attributes = int(getattr(value, "st_file_attributes", 0))- if stat.S_ISDIR(value.st_mode) and not (reparse_flag and file_attributes & reparse_flag):- shutil.rmtree(path)- elif stat.S_ISDIR(value.st_mode):- path.rmdir()- else:+ if stat.S_ISLNK(value.st_mode) or (reparse_flag and file_attributes & reparse_flag):+ if stat.S_ISDIR(value.st_mode):+ path.rmdir()+ else:+ path.unlink()+ return+ if not stat.S_ISDIR(value.st_mode):path.unlink()+ return+ try:+ children = os.listdir(path)+ except OSError as exc:+ raise RuntimeError(f"Cannot inspect built-in Skill staging path: {path}") from exc+ for name in children:+ _remove_snapshot_staging(path / name)+ path.rmdir()def publish_builtin_skills(*,source_root: str | Path | None = None,destination_root: str | Path | None = None,-) -> str:- """Publish this artifact's built-ins to one content-addressed snapshot."""+) -> Path:+ """Publish this artifact's built-ins by replacing the live named catalog."""source = Path(source_root).resolve() if source_root is not None else builtin_skills_source()- umbrella = (+ destination = (Path(destination_root).expanduser().resolve()if destination_root is not Noneelse (paths.get_vibe_remote_dir() / "builtin-skills").expanduser().resolve())- _snapshot_entries(source)_validate_builtin_catalog(source)- snapshot_id = snapshot_tree_digest(source)- destination = umbrella / snapshot_id+ entries = _snapshot_entries(source)from storage.lock import MigrationFileLock- umbrella.mkdir(parents=True, exist_ok=True)- lock_path = umbrella / f".publish-{snapshot_id}.lock"+ destination.parent.mkdir(parents=True, exist_ok=True)+ lock_path = destination.parent / ".publish-builtin-skills.lock"with MigrationFileLock(lock_path, timeout_seconds=None):- staging = umbrella / f".snapshot-{snapshot_id}.staging"+ staging = _catalog_staging_path(destination)+ backup = _catalog_backup_path(destination)_remove_snapshot_staging(staging)- if os.path.lexists(destination):- try:- destination_stat = destination.stat(follow_symlinks=False)- except OSError as exc:- raise RuntimeError(f"Built-in Skill snapshot is unavailable: {destination}") from exc- if not stat.S_ISDIR(destination_stat.st_mode):- raise RuntimeError(f"Built-in Skill snapshot is not a directory: {destination}")- try:- with os.scandir(destination):- pass- except OSError as exc:- raise RuntimeError(f"Built-in Skill snapshot is unreadable: {destination}") from exc- return snapshot_idstaging.mkdir(mode=0o700)try:- _copy_snapshot_entries(_snapshot_entries(source), staging)+ _copy_snapshot_entries(entries, staging)_validate_builtin_catalog(staging)- if snapshot_tree_digest(staging) != snapshot_id:- raise RuntimeError("Built-in Skill source changed during publication")+ _assert_source_unchanged(source, entries)+ if os.path.lexists(destination):+ try:+ destination_stat = destination.stat(follow_symlinks=False)+ except OSError as exc:+ raise RuntimeError(f"Built-in Skill catalog is unavailable: {destination}") from exc+ if not stat.S_ISDIR(destination_stat.st_mode):+ raise RuntimeError(f"Built-in Skill catalog is not a directory: {destination}")+ _remove_snapshot_staging(backup)+ os.rename(destination, backup)try:os.rename(staging, destination)- except OSError as exc:- if exc.errno not in {errno.EEXIST, errno.ENOTEMPTY}:- raise+ except OSError:+ if os.path.lexists(backup) and not os.path.lexists(destination):+ os.rename(backup, destination)+ raisefinally:if os.path.lexists(staging):_remove_snapshot_staging(staging)- return snapshot_id+ return destination-def prepare_builtin_skills() -> str:- """Publish and bind the running artifact's built-in snapshot."""+def prepare_builtin_skills() -> Path:+ """Publish and bind the running artifact's live built-in catalog."""- snapshot_id = publish_builtin_skills()- os.environ[BUILTIN_SKILLS_SNAPSHOT_ENV] = snapshot_id- os.environ[BUILTIN_SKILLS_ROOT_ENV] = str(- (paths.get_vibe_remote_dir() / "builtin-skills" / snapshot_id).expanduser().resolve()- )- return snapshot_id+ try:+ catalog = publish_builtin_skills()+ except Exception:+ os.environ.pop(BUILTIN_SKILLS_SNAPSHOT_ENV, None)+ os.environ[BUILTIN_SKILLS_ROOT_ENV] = ""+ raise+ os.environ.pop(BUILTIN_SKILLS_SNAPSHOT_ENV, None)+ os.environ[BUILTIN_SKILLS_ROOT_ENV] = str(catalog.expanduser().resolve())+ return catalogdef managed_skill_environment(working_directory: str | Path | None,*,project_base: str | Path | None = None,- builtin_snapshot_id: str | None = None,- builtin_snapshot_root: str | Path | None = None,+ builtin_catalog_root: str | Path | None = None,claude_cli_path: str | None = None,) -> dict[str, str]:"""Return the per-backend shell bindings consumed by ``vibe skill``."""@@ -1691,28 +1720,23 @@ def managed_skill_environment(env[SKILL_CLAUDE_CLI_PATH_ENV] = os.path.expanduser(normalized_claude_cli_path)- explicit_builtin_snapshot = builtin_snapshot_id is not None or builtin_snapshot_root is not None- snapshot_id = (- builtin_snapshot_id- if explicit_builtin_snapshot- else os.environ.get(BUILTIN_SKILLS_SNAPSHOT_ENV, "")- )- if isinstance(snapshot_id, str) and _SNAPSHOT_ID_RE.fullmatch(snapshot_id):- snapshot_root = (- builtin_snapshot_root- if explicit_builtin_snapshot- else os.environ.get(BUILTIN_SKILLS_ROOT_ENV)+ if builtin_catalog_root is not None:+ bound_root = builtin_catalog_root+ elif BUILTIN_SKILLS_ROOT_ENV in os.environ:+ bound_root = os.environ.get(BUILTIN_SKILLS_ROOT_ENV)+ else:+ bound_root = None+ if bound_root:+ root = Path(bound_root).expanduser()+ if root.is_absolute():+ env[BUILTIN_SKILLS_ROOT_ENV] = str(_absolute_path(root))+ else:+ logger.warning("Ignoring invalid built-in Skill catalog root: %s", bound_root)+ env[BUILTIN_SKILLS_ROOT_ENV] = ""+ elif builtin_catalog_root is not None or BUILTIN_SKILLS_ROOT_ENV in os.environ:+ env[BUILTIN_SKILLS_ROOT_ENV] = ""+ else:+ env[BUILTIN_SKILLS_ROOT_ENV] = str(+ (paths.get_vibe_remote_dir() / "builtin-skills").expanduser().resolve())- if snapshot_root:- root = Path(snapshot_root).expanduser()- if root.is_absolute() and root.name == snapshot_id:- env[BUILTIN_SKILLS_SNAPSHOT_ENV] = snapshot_id- env[BUILTIN_SKILLS_ROOT_ENV] = str(_absolute_path(root))- elif not explicit_builtin_snapshot:- env[BUILTIN_SKILLS_SNAPSHOT_ENV] = snapshot_id- env[BUILTIN_SKILLS_ROOT_ENV] = str(- (paths.get_vibe_remote_dir() / "builtin-skills" / snapshot_id)- .expanduser()- .resolve()- )return envdiff --git a/docs/plans/managed-skills.md b/docs/plans/managed-skills.mdindex 4c87f3721..8f847c649 100644--- a/docs/plans/managed-skills.md+++ b/docs/plans/managed-skills.md@@ -88,16 +88,18 @@ An installed Avibe artifact publishes its complete built-in set beneath theauthoritative runtime home returned by `config.paths.get_vibe_remote_dir()`:```text-<resolved-avibe-home>/builtin-skills/<runtime-snapshot>/<name>/+<resolved-avibe-home>/builtin-skills/<name>/```This honors an explicit `AVIBE_HOME` and the existing legacy-home migration-rules. Snapshot publication must not independently select or create-`$HOME/.avibe`, because a still-authoritative `$HOME/.vibe_remote` directory-must remain the single state home when migration cannot complete.+rules. Publication must not independently select or create `$HOME/.avibe`,+because a still-authoritative `$HOME/.vibe_remote` directory must remain the+single state home when migration cannot complete.-The runtime snapshot is directly readable by the agent. It is separate from-user-managed Skills and has the highest resolution priority.+The live catalog is directly readable by the agent. It is separate from+user-managed Skills and has the highest resolution priority. A later Avibe+version replaces that catalog in place, so overlapping processes and already+loaded companion scripts may observe the newer files.### 4.2 Project compatibility roots@@ -289,7 +291,7 @@ Therefore, without restarting Avibe or creating a new Session:`vibe skill list` and `vibe skill load` also resolve from disk on everyinvocation. Backend-bound commands use the same Session working directory,-project boundary, compatibility homes, and built-in snapshot that produced the+project boundary, compatibility homes, and built-in catalog that produced theTurn's Catalog. Binding is internal runtime state, not prompt text or a commandargument.@@ -329,18 +331,36 @@ that Avibe's normal backend calls expose only the Avibe Catalog and load route.## 10. Built-in LifecycleThe bundled `skills/` tree is authoritative for each Avibe artifact. Before-managed discovery, the artifact publishes a complete, agent-readable runtime-snapshot. A new version therefore adds new built-ins, replaces changed ones,-and omits retired ones as one coherent set.--Publication is atomic and content-addressed so overlapping old and new Avibe-processes can keep using the snapshot each one advertised. Published snapshots-are not a user customization surface. V1 does not garbage-collect old-snapshots, detect later manual tampering, or repair user changes there.+managed discovery, the artifact publishes a complete, agent-readable catalog+under `builtin-skills/<name>/`. A new version therefore adds new built-ins,+replaces changed ones, and omits retired ones as one coherent set.++Publication replaces that catalog by renaming the live directory aside and+swapping in a staging tree. The previous catalog remains at+`.builtin-skills.previous` until the next successful publication, so a reader+that selected it during the swap can finish. Overlapping old and new Avibe+processes share the live files after replacement; hashed per-version snapshots+are not retained. The published catalog is not a user customization surface.+V1 does not detect later manual tampering or repair user changes there.+Leftover content-addressed snapshot directories from earlier Avibe versions are+not discovered as Skills. A catalog that still contains only those hashed trees+is not treated as published; the next unbound discovery republishes the named+catalog in place. A bound path that still names a missing hashed snapshot falls+back to the parent named catalog when that catalog is readable.++Standalone `vibe skill` commands reuse a readable live catalog and do not+republish on every list or load. Upgrade publication is the service+`prepare_builtin_skills()` path.Wheels and source distributions include the authoritative built-in tree and-preserve companion files and executable script modes. A publication failure-omits built-ins without substituting a different version's content.+preserve companion files and executable script modes. Publication rechecks the+enumerated source before swapping so a mid-copy source change cannot land as a+hybrid catalog. A publication failure binds an empty+`AVIBE_BUILTIN_SKILLS_ROOT` so this process does not keep serving a previous+catalog, and omits built-ins without substituting a different version's+content. A nonempty but invalid explicit catalog root, such as a relative path+from a restored poll, also binds that empty sentinel so the shell cannot inherit+a different catalog.## 11. Installation Defaults@@ -398,7 +418,7 @@ consume it.Backend adapters own only native isolation, Session-bound command context, andapplication of a changed Avibe prompt. Built-in publication owns only the-artifact-to-runtime snapshot lifecycle.+artifact-to-runtime catalog lifecycle.The existing [Workbench Skills design](workbench-skills-page.md) remains themanagement surface. This protocol supersedes its backend selection and@@ -414,7 +434,7 @@ Automated and local Incus regression must prove:- body-only load plus direct access to companion scripts and references;- live add, edit, rename, and delete behavior in one existing Session;- equivalent Catalogs and native isolation across Claude, Codex, and OpenCode;-- installation and upgrade publication of complete built-in snapshots; and+- installation and upgrade publication of the complete live built-in catalog; and- bounded failure of malformed, oversized, unavailable, or concurrentlychanging inputs without taking down unrelated Skills or backend Turns.@@ -429,5 +449,5 @@ V1 does not include:- Skill editing or copy-on-write;- behavior for `${AVIBE_HOME:-$HOME/.avibe}/skills`;- historical-context invalidation;-- built-in snapshot garbage collection or self-healing; or+- built-in catalog self-healing; or- a filesystem security sandbox.diff --git a/main.py b/main.pyindex 737f5c1b2..a7ffbe9c3 100644--- a/main.py+++ b/main.py@@ -180,12 +180,17 @@ def main():setup_logging(config.runtime.log_level)logger = logging.getLogger(__name__)- from core.managed_skills import BUILTIN_SKILLS_SNAPSHOT_ENV, prepare_builtin_skills+ from core.managed_skills import (+ BUILTIN_SKILLS_ROOT_ENV,+ BUILTIN_SKILLS_SNAPSHOT_ENV,+ prepare_builtin_skills,+ )try:prepare_builtin_skills()except Exception:- os.environ[BUILTIN_SKILLS_SNAPSHOT_ENV] = ""+ os.environ.pop(BUILTIN_SKILLS_SNAPSHOT_ENV, None)+ os.environ[BUILTIN_SKILLS_ROOT_ENV] = ""logger.warning("Avibe built-in Skills are unavailable", exc_info=True)apply_claude_sdk_patches()diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 36624bb56..87e908133 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -32,7 +32,6 @@ from core.caller_context import (from core.message_output import stop_output_forfrom core.managed_skills import (BUILTIN_SKILLS_ROOT_ENV,- BUILTIN_SKILLS_SNAPSHOT_ENV,managed_skill_claude_cli_path,managed_skill_environment,managed_skill_project_base,@@ -122,7 +121,7 @@ _CALLER_CONTEXT_ENV_SNAPSHOT_KEY = "opencode_caller_context_env"# releases before generations lack it._GENERATION_SNAPSHOT_KEY = "opencode_generation_id"_MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY = "opencode_managed_skill_project_base"-_MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY = "opencode_managed_skill_builtin_snapshot"+_MANAGED_SKILL_BUILTIN_CATALOG_KEY = "opencode_managed_skill_builtin_catalog"_STATUS_RECONCILIATION_FAILURE_LIMIT = 3# A successful prompt_async response transfers ownership to a forked worker,# but does not prove that worker will publish its first message. Keep this@@ -1878,9 +1877,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):processing_indicator[_CALLER_CONTEXT_ENV_SNAPSHOT_KEY] = validated_caller_env_snapshot(caller_context_env)if project_base:processing_indicator[_MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY] = project_base- if BUILTIN_SKILLS_SNAPSHOT_ENV in managed_skills_env:- processing_indicator[_MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY] = {- "id": managed_skills_env[BUILTIN_SKILLS_SNAPSHOT_ENV],+ if BUILTIN_SKILLS_ROOT_ENV in managed_skills_env:+ processing_indicator[_MANAGED_SKILL_BUILTIN_CATALOG_KEY] = {"root": managed_skills_env[BUILTIN_SKILLS_ROOT_ENV],}target_session_id = _target_agent_session_id(request)@@ -2978,32 +2976,31 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):if isinstance(restored_project_base, str) and restored_project_baseelse None)- restored_snapshot_kwargs: dict[str, str] = {}- if _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY in processing_snapshot:- restored_snapshot = processing_snapshot.get(- _MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY+ restored_catalog_root = None+ catalog_present = (+ _MANAGED_SKILL_BUILTIN_CATALOG_KEY in processing_snapshot+ or "opencode_managed_skill_builtin_snapshot" in processing_snapshot+ )+ restored_catalog = processing_snapshot.get(+ _MANAGED_SKILL_BUILTIN_CATALOG_KEY+ )+ if restored_catalog is None:+ restored_catalog = processing_snapshot.get(+ "opencode_managed_skill_builtin_snapshot")- restored_snapshot_kwargs = {- "builtin_snapshot_id": (- restored_snapshot.get("id", "")- if isinstance(restored_snapshot, dict)- and isinstance(restored_snapshot.get("id"), str)- else ""- ),- "builtin_snapshot_root": (- restored_snapshot.get("root", "")- if isinstance(restored_snapshot, dict)- and isinstance(restored_snapshot.get("root"), str)- else ""- ),- }+ if isinstance(restored_catalog, dict) and isinstance(+ restored_catalog.get("root"), str+ ):+ restored_catalog_root = restored_catalog.get("root")+ elif catalog_present:+ restored_catalog_root = ""restored_managed_skills_env = managed_skill_environment(poll_info.working_path,project_base=restored_project_base,claude_cli_path=managed_skill_claude_cli_path(getattr(getattr(self, "controller", None), "config", None)),- **restored_snapshot_kwargs,+ builtin_catalog_root=restored_catalog_root,)restored_bound = Falsefor attempt in range(3):diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.pyindex 497996954..a767ce866 100644--- a/modules/agents/opencode/caller_context.py+++ b/modules/agents/opencode/caller_context.py@@ -52,7 +52,8 @@ function applyEnv(output, env) {if (!env || typeof env !== "object") returnoutput.env = output.env || {}for (const [key, value] of Object.entries(env)) {- if (typeof value === "string" && value.length > 0) output.env[key] = value+ if (typeof value !== "string") continue+ if (value.length > 0 || key === "AVIBE_BUILTIN_SKILLS_ROOT") output.env[key] = value}}@@ -233,7 +234,11 @@ def bind_session()env = caller.to_env() if caller is not None else {}if extra_env:- env.update((str(key), str(value)) for key, value in extra_env.items() if str(key) and str(value))+ env.update(+ (str(key), str(value))+ for key, value in extra_env.items()+ if str(key) and (str(value) or str(key) == "AVIBE_BUILTIN_SKILLS_ROOT")+ )prepend_managed_tools_to_path(env,base_env=base_env,diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex d0c73f48a..b5c66674d 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -1517,14 +1517,14 @@ def test_session_handler_recreates_cached_claude_client_when_skill_bindings_chancontext = MessageContext(user_id="U123", channel_id="C123", platform="slack")first_client = _run_session(handler, context)- skill_env["AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"] = "a" * 64+ skill_env["AVIBE_BUILTIN_SKILLS_ROOT"] = "/old-avibe-home/builtin-skills"second_client = _run_session(handler, context)assert first_client is not second_clientassert first_client.disconnects == 1assert len(captured["clients"]) == 2- assert "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID" not in first_client.options.env- assert second_client.options.env["AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"] == "a" * 64+ assert "AVIBE_BUILTIN_SKILLS_ROOT" not in first_client.options.env+ assert second_client.options.env["AVIBE_BUILTIN_SKILLS_ROOT"] == "/old-avibe-home/builtin-skills"def test_session_handler_recreates_terminated_cached_client_before_dispatch(diff --git a/tests/test_computer_use_backends.py b/tests/test_computer_use_backends.pyindex a4b7209c7..e8be545e4 100644--- a/tests/test_computer_use_backends.py+++ b/tests/test_computer_use_backends.py@@ -59,7 +59,7 @@ def test_builtin_computer_use_skill_loads_through_the_managed_resolver() -> Noneroot = Path(__file__).resolve().parents[1] / "skills"avibe_home = Path("/tmp/computer-use-test-avibe-home")- snapshot_id = publish_builtin_skills(+ catalog = publish_builtin_skills(source_root=root,destination_root=avibe_home / "builtin-skills",)@@ -69,8 +69,7 @@ def test_builtin_computer_use_skill_loads_through_the_managed_resolver() -> Nonecodex_home=Path("/tmp/computer-use-test-codex-home"),claude_home=Path("/tmp/computer-use-test-claude-home"),xdg_config_home=Path("/tmp/computer-use-test-xdg-home"),- builtin_snapshot_id=snapshot_id,- builtin_snapshot_root=avibe_home / "builtin-skills" / snapshot_id,+ builtin_catalog_root=catalog,)resolved = next(skill for skill in skills if skill.name == "computer-use")loaded = load_skill("computer-use", resolved_skills=skills)diff --git a/tests/test_distribution_artifacts.py b/tests/test_distribution_artifacts.pyindex 64caa1c60..5096cae6e 100644--- a/tests/test_distribution_artifacts.py+++ b/tests/test_distribution_artifacts.py@@ -145,15 +145,16 @@ from pathlib import Pathfrom core.managed_skills import builtin_skills_source, load_skill, prepare_builtin_skillssource = builtin_skills_source()assert source.name == "builtin_skills_source"-snapshot = prepare_builtin_skills()+catalog = prepare_builtin_skills()skill = load_skill("use-avibe")assert skill is not None and skill.body and skill.directory.name == "use-avibe"-root = Path(os.environ["AVIBE_HOME"]) / "builtin-skills" / snapshot+root = Path(os.environ["AVIBE_HOME"]) / "builtin-skills"+assert catalog == rootfiles = {}for path in root.rglob("*"):if path.is_file():files[path.relative_to(root).as_posix()] = {"sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "mode": path.stat().st_mode & 0o777}-print(json.dumps({"snapshot": snapshot, "files": files}, sort_keys=True))+print(json.dumps({"catalog": str(catalog), "files": files}, sort_keys=True))'''result = subprocess.run([str(python), "-c", probe], cwd=tmp_path,env={**os.environ, "AVIBE_HOME": str(avibe_home)},@@ -162,7 +163,7 @@ print(json.dumps({"snapshot": snapshot, "files": files}, sort_keys=True))observed = json.loads(result.stdout.strip())expected = _expected_builtin_skills_snapshot()assert observed["files"] == expected- assert len(observed["snapshot"]) == 64+ assert Path(observed["catalog"]).name == "builtin-skills"def _expected_builtin_skills_snapshot() -> dict[str, dict[str, int | str]]:diff --git a/tests/test_feedback_intake.py b/tests/test_feedback_intake.pyindex 06df833ff..50cda6a0a 100644--- a/tests/test_feedback_intake.py+++ b/tests/test_feedback_intake.py@@ -314,8 +314,8 @@ def test_real_named_vault_cli_stdin_and_detached_child(real_vault):def test_builtin_publication_preserves_helper(tmp_path):from core.managed_skills import publish_builtin_skills- snapshot = publish_builtin_skills(source_root=ROOT / "skills", destination_root=tmp_path / "builtin")- assert (tmp_path / "builtin" / snapshot / "use-avibe/scripts/feedback_intake.py").read_bytes() == HELPER.read_bytes()+ catalog = publish_builtin_skills(source_root=ROOT / "skills", destination_root=tmp_path / "builtin")+ assert (catalog / "use-avibe/scripts/feedback_intake.py").read_bytes() == HELPER.read_bytes()def _parent_clock_stopped_for(seconds):diff --git a/tests/test_feedback_intake_distribution.py b/tests/test_feedback_intake_distribution.pyindex 552fba740..c1d0a0af2 100644--- a/tests/test_feedback_intake_distribution.py+++ b/tests/test_feedback_intake_distribution.py@@ -39,14 +39,15 @@ from core.managed_skills import builtin_skills_source,prepare_builtin_skillssource=builtin_skills_source()assert 'builtin_skills_source' in str(source)assert Path(sys.argv[1]) in source.parents-snapshot=prepare_builtin_skills()+catalog=prepare_builtin_skills()root=Path(os.environ['AVIBE_BUILTIN_SKILLS_ROOT'])-assert root.name==snapshot+assert root==catalog+assert root.name=='builtin-skills'expected=json.loads(sys.argv[2])for path,digest in expected.items():assert hashlib.sha256((root/'use-avibe'/path).read_bytes()).hexdigest()==digest-print(json.dumps({'snapshot':snapshot,'source':str(source)}))+print(json.dumps({'catalog':str(catalog),'source':str(source)}))'''result = subprocess.run([sys.executable,"-c",script,str(installed),json.dumps(expected)], env=env,cwd=tmp_path, check=True, capture_output=True, text=True)- assert json.loads(result.stdout)["snapshot"]+ assert json.loads(result.stdout)["catalog"].endswith("builtin-skills")diff --git a/tests/test_managed_skills.py b/tests/test_managed_skills.pyindex bfb5d0cab..99ecc8a84 100644--- a/tests/test_managed_skills.py+++ b/tests/test_managed_skills.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport os+import statimport sysfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path@@ -11,7 +12,6 @@ import pytestfrom core import managed_skillsfrom core.managed_skills import (BUILTIN_SKILLS_ROOT_ENV,- BUILTIN_SKILLS_SNAPSHOT_ENV,CATALOG_DESCRIPTION_MAX_CHARS,CATALOG_PAGE_MAX_BYTES,CATALOG_PAGE_SIZE,@@ -26,12 +26,12 @@ from core.managed_skills import (load_skill,managed_skill_environment,parse_skill_file,+ prepare_builtin_skills,publish_builtin_skills,render_skill_catalog_prompt,render_skill_content,render_skill_list,resolve_skills,- snapshot_tree_digest,)from core.system_prompt_injection import build_system_prompt_injectionfrom modules.im import MessageContext@@ -62,7 +62,7 @@ def _isolated_resolve(cwd: Path, tmp_path: Path, **kwargs):codex_home=kwargs.pop("codex_home", tmp_path / "codex-home"),claude_home=kwargs.pop("claude_home", tmp_path / "claude-home"),xdg_config_home=kwargs.pop("xdg_config_home", tmp_path / "xdg-home"),- builtin_snapshot_id=kwargs.pop("builtin_snapshot_id", ""),+ builtin_catalog_root=kwargs.pop("builtin_catalog_root", ""),**kwargs,)@@ -73,7 +73,6 @@ def _isolate_live_commands(monkeypatch, tmp_path: Path) -> tuple[Path, Path]:cwd.mkdir()monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("AVIBE_HOME", str(home / ".avibe"))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")return home, cwd@@ -305,8 +304,7 @@ def test_resolution_applies_all_precedence_dimensions(tmp_path: Path) -> None:nested = project / "packages" / "app"nested.mkdir(parents=True)(project / ".git").mkdir()- snapshot_id = "a" * 64- builtin_root = avibe_home / "builtin-skills" / snapshot_id+ builtin_root = avibe_home / "builtin-skills"_write_skill(home / ".agents" / "skills", "shared", "shared", "global agents")_write_skill(home / ".codex" / "skills", "global-family", "global-family", "codex")@@ -324,7 +322,7 @@ def test_resolution_applies_all_precedence_dimensions(tmp_path: Path) -> None:codex_home=home / ".codex",claude_home=home / ".claude",xdg_config_home=home / ".config",- builtin_snapshot_id=snapshot_id,+ builtin_catalog_root=builtin_root,)by_name = {skill.name: skill for skill in skills}@@ -346,7 +344,7 @@ def test_global_roots_honor_backend_home_overrides(tmp_path: Path, monkeypatch)monkeypatch.setenv("CODEX_HOME", str(codex_home))monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_home))monkeypatch.setenv("XDG_CONFIG_HOME", str(xdg_home))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")_write_skill(codex_home / "skills", "codex", "codex", "Codex")_write_skill(claude_home / "skills", "claude", "claude", "Claude")@@ -365,7 +363,7 @@ def test_bound_global_roots_do_not_follow_later_relative_overrides(tmp_path: Patmonkeypatch.setenv("CODEX_HOME", str(tmp_path / "bound-codex"))monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(tmp_path / "bound-claude"))monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "bound-xdg"))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")bound = managed_skill_environment(cwd)monkeypatch.setenv("CODEX_HOME", "relative-codex")monkeypatch.setenv("CLAUDE_CONFIG_DIR", "relative-claude")@@ -391,7 +389,7 @@ def test_codex_system_skills_are_a_low_priority_global_compatibility_root(codex_home = home / ".codex"monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("CODEX_HOME", str(codex_home))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")user = _write_skill(home / ".agents" / "skills", "shared", "shared", "User")_write_skill(codex_home / "skills" / ".system", "shared", "shared", "System")@@ -413,7 +411,7 @@ def test_codex_system_container_counts_toward_the_user_root_enumeration_limit(codex_home = home / ".codex"monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("CODEX_HOME", str(codex_home))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")monkeypatch.setattr(managed_skills, "DISCOVERY_ROOT_MAX_CHILDREN", 1)_write_skill(codex_home / "skills", "user-skill", "user-skill", "User")@@ -429,7 +427,7 @@ def test_empty_backend_home_overrides_fall_back_to_default_roots(tmp_path: Path,monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("CODEX_HOME", "")monkeypatch.setenv("XDG_CONFIG_HOME", "")- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")_write_skill(home / ".codex" / "skills", "codex", "codex", "Codex")_write_skill(home / ".config" / "opencode" / "skills", "opencode", "opencode", "OpenCode")@@ -686,7 +684,7 @@ def test_system_prompt_catalog_is_backend_neutral_for_remote_sessions(home = tmp_path / "home"monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("AVIBE_HOME", str(home / ".avibe"))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")_write_skill(cwd / ".agents" / "skills", "shared", "shared", "Shared")resource_context = {"sub": "member-1",@@ -805,8 +803,7 @@ def test_discovery_ignores_zero_directory_entry_identities(tmp_path: Path, monke"""_, cwd = _isolate_live_commands(monkeypatch, tmp_path)- monkeypatch.delenv(BUILTIN_SKILLS_SNAPSHOT_ENV)- monkeypatch.delenv(BUILTIN_SKILLS_ROOT_ENV)+ monkeypatch.delenv(BUILTIN_SKILLS_ROOT_ENV, raising=False)root = cwd / ".agents" / "skills"_write_skill(root, "alpha", "alpha", "Alpha")_write_skill(root, "beta", "beta", "Beta")@@ -1024,8 +1021,8 @@ def test_builtin_and_compatibility_inputs_have_independent_budgets(tmp_path: Patcwd = tmp_path / "project"cwd.mkdir()avibe_home = tmp_path / "avibe-home"- snapshot_id = "b" * 64- _write_skill(avibe_home / "builtin-skills" / snapshot_id, "builtin", "builtin", "Built-in")+ builtin_root = avibe_home / "builtin-skills"+ _write_skill(builtin_root, "builtin", "builtin", "Built-in")_write_skill(cwd / ".agents" / "skills", "project", "project", "Project")_write_skill(tmp_path / "home" / ".agents" / "skills", "global", "global", "Global")monkeypatch.setattr(managed_skills, "DISCOVERY_CLASS_MAX_CANDIDATES", 1)@@ -1034,7 +1031,7 @@ def test_builtin_and_compatibility_inputs_have_independent_budgets(tmp_path: Patcwd,tmp_path,avibe_home=avibe_home,- builtin_snapshot_id=snapshot_id,+ builtin_catalog_root=builtin_root,)assert [skill.name for skill in skills] == ["builtin", "project"]@@ -1174,7 +1171,7 @@ def test_enabled_claude_plugin_skills_join_the_managed_catalog(claude_home=claude_home,claude_cli_path="/opt/claude-custom",xdg_config_home=home / ".config",- builtin_snapshot_id="",+ builtin_catalog_root="",)assert [skill.name for skill in skills] == ["format-code"]@@ -1248,7 +1245,7 @@ def test_claude_plugin_discovery_fails_closed_when_capture_fails(codex_home=home / ".codex",claude_home=claude_home,xdg_config_home=home / ".config",- builtin_snapshot_id="",+ builtin_catalog_root="",) == []@@ -1277,59 +1274,14 @@ def test_enabled_claude_plugin_skill_overrides_codex_system_default(claude_home=claude_home,claude_cli_path="/opt/claude-custom",xdg_config_home=home / ".config",- builtin_snapshot_id="",+ builtin_catalog_root="",)assert len(skills) == 1assert skills[0].directory == plugin_skill.parent.resolve()-def test_snapshot_v1_digest_fixture_is_stable(tmp_path: Path) -> None:- root = tmp_path / "source"- skill_file = root / "alpha" / "SKILL.md"- skill_file.parent.mkdir(parents=True)- skill_file.write_bytes(b"---\nname: alpha\ndescription: Alpha\n---\nAlpha body\n")- script = root / "alpha" / "scripts" / "run.sh"- script.parent.mkdir()- script.write_bytes(b"#!/bin/sh\nprintf alpha\n")- skill_file.chmod(0o644)- script.chmod(0o644)-- assert snapshot_tree_digest(root) == "00ee8932422279760a9cbe6a7b4e8ffb57c5a3e9ba3fee5a94c216ce2d72a848"--[email protected](os.name == "nt", reason="Windows has no POSIX executable mode")-def test_mode_only_change_produces_a_new_snapshot_id(tmp_path: Path) -> None:- root = tmp_path / "source"- script = _write_skill(root, "alpha", "alpha", "Alpha").parent / "run.sh"- script.write_text("echo alpha\n", encoding="utf-8")- script.chmod(0o644)- first = snapshot_tree_digest(root)- script.chmod(0o755)- assert snapshot_tree_digest(root) != first---def test_snapshot_digest_charges_file_growth_after_enumeration(- tmp_path: Path,- monkeypatch,-) -> None:- source = tmp_path / "source"- skill_file = _write_skill(source, "alpha", "alpha", "Alpha")- monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_BYTES", 128)- original_snapshot_entries = managed_skills._snapshot_entries-- def enumerate_then_grow_file(root: Path):- entries = original_snapshot_entries(root)- skill_file.write_bytes(b"x" * 129)- return entries-- monkeypatch.setattr(managed_skills, "_snapshot_entries", enumerate_then_grow_file)-- with pytest.raises(RuntimeError, match="128 bytes"):- snapshot_tree_digest(source)---def test_publication_keeps_complete_versioned_snapshots_and_executable_modes(+def test_publication_overwrites_the_named_catalog_and_preserves_executable_modes(tmp_path: Path,) -> None:source = tmp_path / "source"@@ -1339,22 +1291,22 @@ def test_publication_keeps_complete_versioned_snapshots_and_executable_modes(helper.write_text("echo old\n", encoding="utf-8")helper.chmod(0o755)- old_id = publish_builtin_skills(source_root=source, destination_root=destination)- old_snapshot = destination / old_id- assert (old_snapshot / "retired" / "SKILL.md").is_file()+ first = publish_builtin_skills(source_root=source, destination_root=destination)+ assert first == destination+ assert (destination / "retired" / "SKILL.md").is_file()if os.name != "nt":- assert (old_snapshot / "retired" / "run.sh").stat().st_mode & 0o111+ assert (destination / "retired" / "run.sh").stat().st_mode & 0o111for path in sorted((source / "retired").rglob("*"), reverse=True):path.unlink() if path.is_file() else path.rmdir()(source / "retired").rmdir()_write_skill(source, "current", "current", "Current", "New\n")- new_id = publish_builtin_skills(source_root=source, destination_root=destination)+ second = publish_builtin_skills(source_root=source, destination_root=destination)- assert new_id != old_id- assert (old_snapshot / "retired" / "SKILL.md").is_file()- assert not (destination / new_id / "retired").exists()- assert (destination / new_id / "current" / "SKILL.md").is_file()+ assert second == destination+ assert not (destination / "retired").exists()+ assert (destination / "current" / "SKILL.md").is_file()+ assert (destination.parent / ".builtin-skills.previous" / "retired" / "SKILL.md").is_file()def test_publication_opens_snapshot_files_in_binary_mode_when_available(@@ -1379,11 +1331,12 @@ def test_publication_opens_snapshot_files_in_binary_mode_when_available(monkeypatch.setattr(managed_skills.os, "O_BINARY", binary_flag, raising=False)monkeypatch.setattr(managed_skills.os, "open", tracking_open)- snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)+ catalog = publish_builtin_skills(source_root=source, destination_root=destination)+ assert catalog == destinationassert destination_flagsassert all(flags & binary_flag for flags in destination_flags)- assert (destination / snapshot_id / "alpha" / "SKILL.md").read_bytes().endswith(+ assert (destination / "alpha" / "SKILL.md").read_bytes().endswith(b"Line one\r\nLine two\n")@@ -1396,9 +1349,10 @@ def test_publication_preserves_each_executable_bit(tmp_path: Path) -> None:helper.write_text("echo alpha\n", encoding="utf-8")helper.chmod(0o744)- snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)+ catalog = publish_builtin_skills(source_root=source, destination_root=destination)- assert (destination / snapshot_id / "alpha" / "run.sh").stat().st_mode & 0o111 == 0o100+ assert catalog == destination+ assert (destination / "alpha" / "run.sh").stat().st_mode & 0o111 == 0o100def test_publication_ignores_install_generated_python_bytecode(tmp_path: Path) -> None:@@ -1410,9 +1364,10 @@ def test_publication_ignores_install_generated_python_bytecode(tmp_path: Path) -(cache.parent / "helper.py").write_text("print('source')\n", encoding="utf-8")destination = tmp_path / "runtime"- snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)+ catalog = publish_builtin_skills(source_root=source, destination_root=destination)- assert not (destination / snapshot_id / "alpha" / "scripts" / "__pycache__").exists()+ assert catalog == destination+ assert not (destination / "alpha" / "scripts" / "__pycache__").exists()def test_publication_rejects_empty_companion_directories(tmp_path: Path) -> None:@@ -1424,13 +1379,13 @@ def test_publication_rejects_empty_companion_directories(tmp_path: Path) -> Nonepublish_builtin_skills(source_root=source, destination_root=tmp_path / "runtime")-def test_concurrent_publication_reuses_one_snapshot(tmp_path: Path) -> None:+def test_concurrent_publication_replaces_one_named_catalog(tmp_path: Path) -> None:source = tmp_path / "source"destination = tmp_path / "builtin-skills"_write_skill(source, "alpha", "alpha", "Alpha")with ThreadPoolExecutor(max_workers=2) as pool:- ids = list(+ catalogs = list(pool.map(lambda _: publish_builtin_skills(source_root=source,@@ -1440,22 +1395,62 @@ def test_concurrent_publication_reuses_one_snapshot(tmp_path: Path) -> None:))- assert ids[0] == ids[1]- assert (destination / ids[0] / "alpha" / "SKILL.md").is_file()+ assert catalogs[0] == catalogs[1] == destination+ assert (destination / "alpha" / "SKILL.md").is_file()def test_publication_reclaims_interrupted_staging_and_retries(tmp_path: Path) -> None:source = tmp_path / "source"destination = tmp_path / "builtin-skills"_write_skill(source, "alpha", "alpha", "Alpha")- snapshot_id = snapshot_tree_digest(source)- staging = destination / f".snapshot-{snapshot_id}.staging"+ staging = destination.parent / ".builtin-skills.staging"staging.mkdir(parents=True)(staging / "partial").write_text("interrupted", encoding="utf-8")- assert publish_builtin_skills(source_root=source, destination_root=destination) == snapshot_id+ assert publish_builtin_skills(source_root=source, destination_root=destination) == destination+ assert not staging.exists()+ assert (destination / "alpha" / "SKILL.md").is_file()+++def test_publication_removes_directory_reparse_points_with_rmdir(+ tmp_path: Path,+ monkeypatch,+) -> None:+ staging = tmp_path / ".builtin-skills.staging"+ staging.mkdir()+ original_lstat = Path.lstat+ original_rmdir = Path.rmdir+ original_unlink = Path.unlink+ rmdir_paths: list[Path] = []+ unlink_paths: list[Path] = []++ class _ReparseStat:+ st_mode = stat.S_IFDIR+ st_file_attributes = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400))++ def lstat(self):+ if self == staging:+ return _ReparseStat()+ return original_lstat(self)++ def rmdir(self):+ rmdir_paths.append(self)+ return original_rmdir(self)++ def unlink(self):+ unlink_paths.append(self)+ return original_unlink(self)++ monkeypatch.setattr(Path, "lstat", lstat)+ monkeypatch.setattr(Path, "rmdir", rmdir)+ monkeypatch.setattr(Path, "unlink", unlink)+ monkeypatch.setattr(managed_skills.stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)++ managed_skills._remove_snapshot_staging(staging)++ assert rmdir_paths == [staging]+ assert unlink_paths == []assert not staging.exists()- assert (destination / snapshot_id / "alpha" / "SKILL.md").is_file()def test_publication_rejects_nonportable_and_wrong_type_paths(tmp_path: Path) -> None:@@ -1467,9 +1462,7 @@ def test_publication_rejects_nonportable_and_wrong_type_paths(tmp_path: Path) ->valid_source = tmp_path / "valid"_write_skill(valid_source, "alpha", "alpha", "Alpha")- snapshot_id = snapshot_tree_digest(valid_source)- destination.mkdir(parents=True)- (destination / snapshot_id).write_text("not a directory", encoding="utf-8")+ destination.write_text("not a directory", encoding="utf-8")with pytest.raises(RuntimeError, match="not a directory|unavailable"):publish_builtin_skills(source_root=valid_source, destination_root=destination)@@ -1577,7 +1570,6 @@ def test_publication_copies_only_the_bounded_enumeration(source = tmp_path / "source"destination = tmp_path / "builtin-skills"_write_skill(source, "alpha", "alpha", "Alpha")- monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_BYTES", 128)original_snapshot_entries = managed_skills._snapshot_entriessource_enumerations = 0@@ -1586,16 +1578,17 @@ def test_publication_copies_only_the_bounded_enumeration(entries = original_snapshot_entries(root)if Path(root) == source:source_enumerations += 1- if source_enumerations == 3:- (source / "late.bin").write_bytes(b"x" * 129)+ if source_enumerations == 1:+ (source / "late.bin").write_bytes(b"late")return entriesmonkeypatch.setattr(managed_skills, "_snapshot_entries", enumerate_then_add_late_entry)- snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)+ with pytest.raises(RuntimeError, match="source changed"):+ publish_builtin_skills(source_root=source, destination_root=destination)- assert source_enumerations == 3- assert not (destination / snapshot_id / "late.bin").exists()+ assert source_enumerations == 2+ assert not destination.exists()def test_publication_charges_file_growth_at_copy_time(@@ -1614,7 +1607,7 @@ def test_publication_charges_file_growth_at_copy_time(entries = original_snapshot_entries(root)if Path(root) == source:source_enumerations += 1- if source_enumerations == 3:+ if source_enumerations == 1:skill_file.write_bytes(b"x" * 129)return entries@@ -1678,17 +1671,159 @@ def test_workbench_management_acl_does_not_narrow_runtime_catalog(cwd = tmp_path / "project"cwd.mkdir()avibe_home = home / ".avibe"- snapshot_id = "d" * 64+ builtin_root = avibe_home / "builtin-skills"monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))monkeypatch.setenv("AVIBE_HOME", str(avibe_home))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, snapshot_id)- _write_skill(avibe_home / "builtin-skills" / snapshot_id, "builtin", "builtin", "Built-in")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, str(builtin_root))+ _write_skill(builtin_root, "builtin", "builtin", "Built-in")+ _write_skill(+ builtin_root / ("a" * 64),+ "legacy",+ "legacy",+ "Legacy hashed snapshot",+ )_write_skill(cwd / ".agents" / "skills", "project", "project", "Project")skills = resolve_skills(cwd)assert [skill.name for skill in skills] == ["builtin", "project"]+def test_unbound_legacy_hashed_catalog_is_replaced_on_resolve(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ monkeypatch.delenv(BUILTIN_SKILLS_ROOT_ENV, raising=False)+ hashed = home / ".avibe" / "builtin-skills" / ("a" * 64)+ _write_skill(hashed, "legacy", "legacy", "Legacy")++ names = {skill.name for skill in resolve_skills(cwd)}++ assert "legacy" not in names+ assert "use-avibe" in names+ assert (home / ".avibe" / "builtin-skills" / "use-avibe" / "SKILL.md").is_file()+ assert not hashed.exists()+++def test_missing_legacy_snapshot_bind_uses_named_catalog(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ catalog = home / ".avibe" / "builtin-skills"+ _write_skill(catalog, "builtin", "builtin", "Built-in")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, str(catalog / ("a" * 64)))++ assert [skill.name for skill in resolve_skills(cwd)] == ["builtin"]+++def test_prepare_failure_binds_an_empty_catalog_root(monkeypatch, tmp_path: Path) -> None:+ _isolate_live_commands(monkeypatch, tmp_path)+ monkeypatch.delenv(BUILTIN_SKILLS_ROOT_ENV, raising=False)+ monkeypatch.setenv("AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID", "a" * 64)+ monkeypatch.setattr(+ managed_skills,+ "publish_builtin_skills",+ lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("source invalid")),+ )++ with pytest.raises(RuntimeError, match="source invalid"):+ prepare_builtin_skills()++ assert os.environ[BUILTIN_SKILLS_ROOT_ENV] == ""+ assert "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID" not in os.environ+++def test_empty_binding_does_not_serve_a_stale_named_catalog(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ _write_skill(home / ".avibe" / "builtin-skills", "stale", "stale", "Stale")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, "")++ assert [skill.name for skill in resolve_skills(cwd)] == []+ assert managed_skill_environment(cwd)[BUILTIN_SKILLS_ROOT_ENV] == ""+++def test_bound_reader_uses_previous_catalog_while_live_is_missing(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ catalog = home / ".avibe" / "builtin-skills"+ previous = catalog.parent / ".builtin-skills.previous"+ _write_skill(previous, "previous", "previous", "Previous")+ monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, str(catalog))++ assert [skill.name for skill in resolve_skills(cwd)] == ["previous"]+++def test_publication_keeps_previous_catalog_after_successful_swap(+ tmp_path: Path,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ previous = destination.parent / ".builtin-skills.previous"+ _write_skill(source, "current", "current", "Current")+ _write_skill(destination, "previous", "previous", "Previous")++ assert publish_builtin_skills(source_root=source, destination_root=destination) == destination+ assert (destination / "current" / "SKILL.md").is_file()+ assert (previous / "previous" / "SKILL.md").is_file()+ assert not (destination / "previous").exists()+++def test_publication_rejects_source_changes_before_swap(+ tmp_path: Path,+ monkeypatch,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha", "Old\n")+ original_copy = managed_skills._copy_snapshot_entries++ def copy_then_rewrite(entries, destination_root):+ original_copy(entries, destination_root)+ skill_file.write_text(+ "---\nname: alpha\ndescription: Alpha\n---\nNew\n",+ encoding="utf-8",+ )++ monkeypatch.setattr(managed_skills, "_copy_snapshot_entries", copy_then_rewrite)++ with pytest.raises(RuntimeError, match="source changed"):+ publish_builtin_skills(source_root=source, destination_root=destination)+++def test_publication_restores_previous_if_live_swap_fails(+ tmp_path: Path,+ monkeypatch,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ previous = destination.parent / ".builtin-skills.previous"+ _write_skill(source, "current", "current", "Current")+ _write_skill(destination, "previous", "previous", "Previous")+ real_rename = os.rename+ failed_live_swap = False++ def fail_live_swap(src, dst):+ nonlocal failed_live_swap+ if Path(dst) == destination and not failed_live_swap:+ failed_live_swap = True+ raise OSError("swap failed")+ return real_rename(src, dst)++ monkeypatch.setattr(managed_skills.os, "rename", fail_live_swap)++ with pytest.raises(OSError, match="swap failed"):+ publish_builtin_skills(source_root=source, destination_root=destination)++ assert (destination / "previous" / "SKILL.md").is_file()+ assert not (destination / "current").exists()++@pytest.mark.skipif(os.name == "nt", reason="symlink fixture requires POSIX semantics")def test_publication_rejects_symlinks(tmp_path: Path) -> None:source = tmp_path / "source"@@ -1699,24 +1834,19 @@ def test_publication_rejects_symlinks(tmp_path: Path) -> None:publish_builtin_skills(source_root=source, destination_root=tmp_path / "out")-def test_bound_working_directory_and_snapshot_are_inherited(monkeypatch, tmp_path: Path) -> None:+def test_bound_working_directory_and_catalog_are_inherited(monkeypatch, tmp_path: Path) -> None:home, advertised_cwd = _isolate_live_commands(monkeypatch, tmp_path)other_cwd = tmp_path / "other"other_cwd.mkdir()_write_skill(advertised_cwd / ".agents" / "skills", "advertised", "advertised", "Here")_write_skill(other_cwd / ".agents" / "skills", "other", "other", "There")- snapshot_id = "c" * 64monkeypatch.setenv(SKILL_WORKING_DIR_ENV, str(advertised_cwd))- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, snapshot_id)monkeypatch.chdir(other_cwd)assert [skill.name for skill in resolve_skills()] == ["advertised"]assert managed_skill_environment(advertised_cwd) == {SKILL_WORKING_DIR_ENV: str(advertised_cwd.resolve()),- BUILTIN_SKILLS_SNAPSHOT_ENV: snapshot_id,- BUILTIN_SKILLS_ROOT_ENV: str(- (Path(os.environ["AVIBE_HOME"]) / "builtin-skills" / snapshot_id).resolve()- ),+ BUILTIN_SKILLS_ROOT_ENV: "",SKILL_HOME_ENV: str(home.resolve()),SKILL_CODEX_HOME_ENV: str((home / ".codex").resolve()),SKILL_CLAUDE_HOME_ENV: str((home / ".claude").resolve()),@@ -1752,37 +1882,42 @@ def test_managed_skill_environment_binds_configured_claude_cli_path()-def test_managed_skill_environment_can_retain_an_explicit_builtin_snapshot(+def test_managed_skill_environment_can_retain_an_explicit_builtin_catalog(tmp_path: Path,) -> None:working_directory = tmp_path / "project"working_directory.mkdir()- snapshot_id = "d" * 64- snapshot_root = tmp_path / "old-home" / "builtin-skills" / snapshot_id+ catalog_root = tmp_path / "old-home" / "builtin-skills"env = managed_skill_environment(working_directory,- builtin_snapshot_id=snapshot_id,- builtin_snapshot_root=snapshot_root,+ builtin_catalog_root=catalog_root,)- assert env[BUILTIN_SKILLS_SNAPSHOT_ENV] == snapshot_id- assert env[BUILTIN_SKILLS_ROOT_ENV] == str(snapshot_root.resolve())- invalid = managed_skill_environment(- working_directory,- builtin_snapshot_id="invalid",- builtin_snapshot_root=snapshot_root,- )- assert BUILTIN_SKILLS_SNAPSHOT_ENV not in invalid- assert BUILTIN_SKILLS_ROOT_ENV not in invalid+ assert env[BUILTIN_SKILLS_ROOT_ENV] == str(catalog_root.resolve())+++def test_managed_skill_environment_disables_an_invalid_explicit_catalog(+ tmp_path: Path,+ caplog,+) -> None:+ working_directory = tmp_path / "project"+ working_directory.mkdir()++ with caplog.at_level("WARNING", logger="core.managed_skills"):+ env = managed_skill_environment(+ working_directory,+ builtin_catalog_root="relative-catalog",+ )++ assert env[BUILTIN_SKILLS_ROOT_ENV] == ""+ assert "Ignoring invalid built-in Skill catalog root" in caplog.textdef test_bound_builtin_root_survives_avibe_home_change(monkeypatch, tmp_path: Path) -> None:home, cwd = _isolate_live_commands(monkeypatch, tmp_path)- snapshot_id = "e" * 64- original_root = home / "first-avibe" / "builtin-skills" / snapshot_id+ original_root = home / "first-avibe" / "builtin-skills"_write_skill(original_root, "builtin", "builtin", "Built-in")- monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, snapshot_id)monkeypatch.setenv(BUILTIN_SKILLS_ROOT_ENV, str(original_root.resolve()))monkeypatch.setenv("AVIBE_HOME", str(home / "second-avibe"))diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 763b081e5..f0df853b5 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -3911,10 +3911,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, cfrom core.system_prompt_injection import build_system_prompt_injectionmonkeypatch.setattr("core.managed_skills.resolve_skills", lambda *_args, **_kwargs: [])- snapshot_id = "f" * 64- snapshot_root = f"/old-avibe-home/builtin-skills/{snapshot_id}"- monkeypatch.setenv("AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID", snapshot_id)- monkeypatch.setenv("AVIBE_BUILTIN_SKILLS_ROOT", snapshot_root)+ catalog_root = "/old-avibe-home/builtin-skills"+ monkeypatch.setenv("AVIBE_BUILTIN_SKILLS_ROOT", catalog_root)calls = []active_polls = []active_poll_updates = []@@ -4101,8 +4099,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch, csteering_snapshot = active_polls[0]["processing_indicator"]["opencode_native_steering"]assert steering_snapshot["system"] == calls[0]["system"]assert active_polls[0]["processing_indicator"][- "opencode_managed_skill_builtin_snapshot"- ] == {"id": snapshot_id, "root": snapshot_root}+ "opencode_managed_skill_builtin_catalog"+ ] == {"root": catalog_root}assert prompt_skill_cwds == ["/tmp/work"]binding_failures = []diff --git a/tests/test_opencode_caller_context.py b/tests/test_opencode_caller_context.pyindex b2af22e09..c91bb799c 100644--- a/tests/test_opencode_caller_context.py+++ b/tests/test_opencode_caller_context.py@@ -171,6 +171,36 @@ def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:assert "expires_at" in entry+def test_bind_session_preserves_an_empty_builtin_catalog_root(+ tmp_path: Path,+ monkeypatch,+) -> None:+ avibe_home = tmp_path / "avibe"+ monkeypatch.setenv("AVIBE_HOME", str(avibe_home))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)++ ok = bridge.bind_session(+ "oc-session",+ {+ "task_execution_id": "run123",+ "task_trigger_kind": "agent_run",+ "agent_session_target": {+ "id": "ses123",+ "agent_backend": "opencode",+ "native_session_id": "oc-session",+ },+ },+ base_env={"PATH": "/usr/bin"},+ working_dir=tmp_path / "workspace",+ extra_env={"AVIBE_BUILTIN_SKILLS_ROOT": ""},+ )++ assert ok is True+ data = json.loads(bridge.binding_path().read_text(encoding="utf-8"))+ assert data["sessions"]["oc-session"]["env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == ""+ assert 'key === "AVIBE_BUILTIN_SKILLS_ROOT"' in bridge.PLUGIN_SOURCE++def test_prune_sessions_keeps_unexpired_released_entries() -> None:now = datetime(2026, 9, 2, tzinfo=timezone.utc)sessions = {diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex ec76bfc4f..5003bd4d1 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -182,9 +182,8 @@ def test_restore_rebinds_persisted_remote_caller_context(monkeypatch) -> None:"AVIBE_CALLER_SESSION_PROOF": "stale-process-proof",},"opencode_managed_skill_project_base": "/tmp",- "opencode_managed_skill_builtin_snapshot": {- "id": "d" * 64,- "root": "/old-avibe-home/builtin-skills/" + "d" * 64,+ "opencode_managed_skill_builtin_catalog": {+ "root": "/old-avibe-home/builtin-skills",},}agent, _, _, _ = _build_agent({"oc-1": poll})@@ -216,15 +215,120 @@ def test_restore_rebinds_persisted_remote_caller_context(monkeypatch) -> None:assert bound[0]["path"] == binding_pathassert bound[0]["extra_env"]["AVIBE_CALLER_RESOURCE_CONTEXT"] == '{"sub":"user-1"}'assert bound[0]["extra_env"]["AVIBE_SKILL_PROJECT_BASE"] == str(Path("/tmp").resolve())- assert bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"] == "d" * 64+ assert "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID" not in bound[0]["extra_env"]assert bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == (- "/old-avibe-home/builtin-skills/" + "d" * 64+ "/old-avibe-home/builtin-skills")assert "IGNORED_ENV" not in bound[0]["extra_env"]assert "AVIBE_CALLER_SESSION_PROOF" not in bound[0]["extra_env"]assert unbound == [("oc-1", bound[0]["binding_token"], binding_path)]+def test_restore_rebinds_an_explicitly_disabled_builtin_catalog(monkeypatch) -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ poll.processing_indicator = {+ "platform": "avibe",+ "user_id": "remote:user-1",+ "opencode_caller_context_env": {+ "AVIBE_SESSION_ID": "ses_wb",+ "AVIBE_CALLER_PLATFORM": "avibe",+ "AVIBE_CALLER_USER_ID": "remote:user-1",+ "AVIBE_CALLER_REMOTE": "1",+ },+ "opencode_managed_skill_builtin_catalog": {"root": ""},+ }+ agent, _, _, _ = _build_agent({"oc-1": poll})+ bound: list[dict] = []++ def bind(session_id, payload, **kwargs):+ bound.append({"session_id": session_id, "payload": payload, **kwargs})+ return True++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda *args, **kwargs: True,+ )++ async def run() -> int:+ restored = await agent.restore_active_polls()+ await asyncio.gather(*agent._active_requests.values())+ return restored++ assert asyncio.run(run()) == 1+ assert bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == ""+++def test_restore_disables_an_invalid_persisted_builtin_catalog(monkeypatch) -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ poll.processing_indicator = {+ "platform": "avibe",+ "user_id": "remote:user-1",+ "opencode_caller_context_env": {+ "AVIBE_SESSION_ID": "ses_wb",+ "AVIBE_CALLER_PLATFORM": "avibe",+ "AVIBE_CALLER_USER_ID": "remote:user-1",+ "AVIBE_CALLER_REMOTE": "1",+ },+ "opencode_managed_skill_builtin_catalog": {"root": "relative-catalog"},+ }+ agent, _, _, _ = _build_agent({"oc-1": poll})+ bound: list[dict] = []++ def bind(session_id, payload, **kwargs):+ bound.append({"session_id": session_id, "payload": payload, **kwargs})+ return True++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda *args, **kwargs: True,+ )++ async def run() -> int:+ restored = await agent.restore_active_polls()+ await asyncio.gather(*agent._active_requests.values())+ return restored++ assert asyncio.run(run()) == 1+ assert bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == ""+++def test_restore_disables_a_malformed_persisted_builtin_catalog(monkeypatch) -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ poll.processing_indicator = {+ "platform": "avibe",+ "user_id": "remote:user-1",+ "opencode_caller_context_env": {+ "AVIBE_SESSION_ID": "ses_wb",+ "AVIBE_CALLER_PLATFORM": "avibe",+ "AVIBE_CALLER_USER_ID": "remote:user-1",+ "AVIBE_CALLER_REMOTE": "1",+ },+ "opencode_managed_skill_builtin_catalog": {"root": None},+ }+ agent, _, _, _ = _build_agent({"oc-1": poll})+ bound: list[dict] = []++ def bind(session_id, payload, **kwargs):+ bound.append({"session_id": session_id, "payload": payload, **kwargs})+ return True++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda *args, **kwargs: True,+ )++ async def run() -> int:+ restored = await agent.restore_active_polls()+ await asyncio.gather(*agent._active_requests.values())+ return restored++ assert asyncio.run(run()) == 1+ assert bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == ""++def test_restore_binding_failure_does_not_strand_durable_poll(monkeypatch) -> None:poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")agent, _, removed, _ = _build_agent({"oc-1": poll})diff --git a/tests/test_prompt_studio_catalog.py b/tests/test_prompt_studio_catalog.pyindex bd7bef6f5..35a47fba5 100644--- a/tests/test_prompt_studio_catalog.py+++ b/tests/test_prompt_studio_catalog.py@@ -176,9 +176,9 @@ def test_use_avibe_entry_routes_to_all_bundled_references() -> None:def test_published_skill_keeps_references_available_without_eagerly_loading_them(tmp_path) -> None:- destination = tmp_path / "snapshots"- snapshot = publish_builtin_skills(source_root=ROOT / "skills", destination_root=destination)- directory = destination / snapshot / "use-avibe"+ destination = tmp_path / "builtin-skills"+ catalog = publish_builtin_skills(source_root=ROOT / "skills", destination_root=destination)+ directory = catalog / "use-avibe"skill = parse_skill_file(directory / "SKILL.md", priority=(0, 0, 0, str(directory)), include_body=True)assert skill is not Noneassert "references/global-config.md" in skill.body