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: manage backend skills through Avibe (#1811)
Call White3f9d75f4b4d9
diff --git a/core/caller_context.py b/core/caller_context.pyindex e8ae61884..c152fbc8c 100644--- a/core/caller_context.py+++ b/core/caller_context.py@@ -25,6 +25,24 @@ AVIBE_CALLER_WORKSPACE_ID_ENV = "AVIBE_CALLER_WORKSPACE_ID"AVIBE_CALLER_REMOTE_ENV = "AVIBE_CALLER_REMOTE"AVIBE_CALLER_RESOURCE_CONTEXT_ENV = "AVIBE_CALLER_RESOURCE_CONTEXT"+CALLER_CONTEXT_ENV_NAMES = frozenset(+ {+ AVIBE_SESSION_ID_ENV,+ AVIBE_RUN_ID_ENV,+ AVIBE_CALLER_SOURCE_ENV,+ AVIBE_CALLER_BACKEND_ENV,+ AVIBE_NATIVE_SESSION_ID_ENV,+ AVIBE_CALLER_PLATFORM_ENV,+ AVIBE_CALLER_USER_ID_ENV,+ AVIBE_CALLER_CHANNEL_ID_ENV,+ AVIBE_CALLER_SESSION_KEY_ENV,+ AVIBE_CALLER_MESSAGE_ID_ENV,+ AVIBE_CALLER_WORKSPACE_ID_ENV,+ AVIBE_CALLER_REMOTE_ENV,+ AVIBE_CALLER_RESOURCE_CONTEXT_ENV,+ }+)+_RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"@@ -204,6 +222,18 @@ def caller_resource_user_context(context: Optional[CallerContext]) -> Optional[Mreturn dict(context.resource_user_context or {})+def validated_caller_env_snapshot(source: object) -> dict[str, str]:+ """Return only caller-context fields from a persisted internal snapshot."""++ if not isinstance(source, Mapping):+ return {}+ return {+ str(key): value+ for key, value in source.items()+ if key in CALLER_CONTEXT_ENV_NAMES and isinstance(value, str) and value+ }++def _scope_id_from_session_key(session_key: str) -> Optional[str]:parts = _clean(session_key).split("::")if len(parts) != 5:diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 0f6059c8a..1ef86e6f1 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -44,6 +44,11 @@ from core.agent_tool_policy import (from core.avibe_cloud import avibe_cloud_url_availablefrom core.agent_session_context import resolve_context_agent_session_targetfrom core.caller_context import caller_env_for_platform_payload+from core.managed_skills import (+ managed_skill_claude_cli_path,+ managed_skill_environment,+ managed_skill_project_base,+)from core.message_context import build_thread_session_anchor, resolve_context_thread_idfrom core.resource_governance import governor_from_controllerfrom core.runtime_activation import RuntimeActivationIdentity@@ -477,12 +482,13 @@ class SessionHandler(BaseHandler):)return None- next_system_prompt = self._build_claude_system_prompt(+ next_system_prompt = await self._build_claude_system_prompt(context=context,session_key=session_key,agent_name="claude",session_anchor=base_session_id,agent_system_prompt=agent_system_prompt,+ working_path=working_path,)cached_system_prompt = self.claude_system_prompts.get(composite_key)if cached_system_prompt != next_system_prompt:@@ -507,6 +513,21 @@ class SessionHandler(BaseHandler):retire_model_hub_scope=model_hub_launch.channel == "direct",)return None+ managed_skills_env = managed_skill_environment(+ working_path,+ project_base=managed_skill_project_base(context),+ claude_cli_path=managed_skill_claude_cli_path(self.config),+ )+ if getattr(client, "_vibe_managed_skills_env", {}) != managed_skills_env:+ logger.info(+ "Recreating cached Claude SDK client for %s because managed Skill bindings changed",+ composite_key,+ )+ await self._cleanup_session_locked(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )+ return Nonegit_path_state = self._claude_git_path_state(working_path)if getattr(client, "_vibe_git_path_state", None) != git_path_state:logger.info(@@ -583,12 +604,13 @@ class SessionHandler(BaseHandler):if next_agent_system_prompt is None:agent_data = self._load_agent_file(effective_agent, working_path)next_agent_system_prompt = agent_data.get("prompt") if agent_data else None- next_system_prompt = self._build_claude_system_prompt(+ next_system_prompt = await self._build_claude_system_prompt(context=context,session_key=session_key,agent_name="claude",session_anchor=base_session_id,agent_system_prompt=next_agent_system_prompt,+ working_path=working_path,)if self.claude_system_prompts.get(composite_key) != next_system_prompt:logger.info(@@ -611,6 +633,21 @@ class SessionHandler(BaseHandler):retire_model_hub_scope=model_hub_launch.channel == "direct",)return None+ managed_skills_env = managed_skill_environment(+ working_path,+ project_base=managed_skill_project_base(context),+ claude_cli_path=managed_skill_claude_cli_path(self.config),+ )+ if getattr(client, "_vibe_managed_skills_env", {}) != managed_skills_env:+ logger.info(+ "Recreating cached Claude subagent SDK client for %s because managed Skill bindings changed",+ composite_key,+ )+ await self._cleanup_session_locked(+ composite_key,+ retire_model_hub_scope=model_hub_launch.channel == "direct",+ )+ return Nonegit_path_state = self._claude_git_path_state(working_path)if getattr(client, "_vibe_git_path_state", None) != git_path_state:logger.info(@@ -1474,12 +1511,13 @@ class SessionHandler(BaseHandler):# Always append avibe system prompt injection so transport# capabilities remain available; reply_enhancements only controls# quick-reply button instructions.- final_system_prompt = self._build_claude_system_prompt(+ final_system_prompt = await self._build_claude_system_prompt(context,session_key=session_key,agent_name="claude",session_anchor=base_session_id,agent_system_prompt=agent_system_prompt,+ working_path=working_path,)# Echo native input frames so the long-lived receiver can correlate@@ -1512,6 +1550,13 @@ class SessionHandler(BaseHandler):if model_hub_launch is not None:claude_env = build_claude_hub_env(claude_env, model_hub_launch)claude_env.update(self._caller_env_for_context(context))+ claude_env.update(+ managed_skill_environment(+ working_path,+ project_base=managed_skill_project_base(context),+ claude_cli_path=managed_skill_claude_cli_path(self.config),+ )+ )prepend_vendored_git_to_path(claude_env,base_env=os.environ,@@ -1534,6 +1579,7 @@ class SessionHandler(BaseHandler):"extra_args": extra_args,"settings": CLAUDE_MEMORY_DISABLED_SETTINGS,"setting_sources": claude_setting_sources_for_launch(model_hub_launch),+ "skills": [],"sandbox": CLAUDE_REMOTE_SANDBOX,# Disable interactive-only Claude Code tools that remote IM sessions# cannot answer programmatically, plus any session-only background@@ -1581,6 +1627,15 @@ class SessionHandler(BaseHandler):client = ClaudeSDKClient(options=options)setattr(client, "_vibe_stderr_lines", claude_stderr_lines)setattr(client, "_vibe_caller_env", self._caller_env_for_context(context))+ setattr(+ client,+ "_vibe_managed_skills_env",+ managed_skill_environment(+ working_path,+ project_base=managed_skill_project_base(context),+ claude_cli_path=managed_skill_claude_cli_path(self.config),+ ),+ )setattr(client, "_vibe_git_path_state", git_path_state)setattr(client,@@ -1669,7 +1724,7 @@ class SessionHandler(BaseHandler):return client- def _build_claude_system_prompt(+ async def _build_claude_system_prompt(self,context: MessageContext,*,@@ -1677,6 +1732,7 @@ class SessionHandler(BaseHandler):agent_name: str,session_anchor: str,agent_system_prompt: Optional[str],+ working_path: Optional[str] = None,) -> str | Dict[str, str]:base_prompt = agent_system_prompt or self.config.claude.system_promptquick_replies_on = getattr(self.config, "reply_enhancements", True)@@ -1694,7 +1750,8 @@ class SessionHandler(BaseHandler):# that write.memory_cli_admitted = memory_cli_prompt_admitted(self.controller, context)- system_prompt_injection = build_system_prompt_injection(+ system_prompt_injection = await asyncio.to_thread(+ build_system_prompt_injection,include_quick_replies=quick_replies_on and platform != "wechat",include_show_pages=getattr(self.config, "show_pages_prompt", True),include_memory_cli=memory_cli_admitted,@@ -1703,6 +1760,9 @@ class SessionHandler(BaseHandler):fallback_platform=platform,enabled_agents=get_enabled_agents_for_prompt(self.controller),current_agent_backend="claude",+ skills_cwd=working_path,+ skills_project_base=managed_skill_project_base(context),+ skills_claude_cli_path=managed_skill_claude_cli_path(self.config),)if base_prompt:diff --git a/core/managed_skills.py b/core/managed_skills.pynew file mode 100644index 000000000..776dce24f--- /dev/null+++ b/core/managed_skills.py@@ -0,0 +1,1707 @@+"""Avibe-owned Skill discovery, catalog rendering, loading, and built-ins."""++from __future__ import annotations++import errno+import hashlib+import html+import json+import logging+import os+import re+import shutil+import stat+import struct+import subprocess+import threading+import time+import unicodedata+from dataclasses import dataclass, replace+from pathlib import Path+from typing import Any, Sequence++import yaml++from config import paths++try:+ import tomllib+except ModuleNotFoundError: # pragma: no cover - Python 3.10 compatibility+ import tomli as tomllib+++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"+SKILL_HOME_ENV = "AVIBE_SKILL_HOME"+SKILL_CODEX_HOME_ENV = "AVIBE_SKILL_CODEX_HOME"+SKILL_CLAUDE_HOME_ENV = "AVIBE_SKILL_CLAUDE_HOME"+SKILL_CLAUDE_CLI_PATH_ENV = "AVIBE_SKILL_CLAUDE_CLI_PATH"+SKILL_XDG_CONFIG_HOME_ENV = "AVIBE_SKILL_XDG_CONFIG_HOME"++CATALOG_PAGE_SIZE = 25+CATALOG_PAGE_MAX_BYTES = 16 * 1024+CATALOG_DESCRIPTION_MAX_CHARS = 1024+FRONTMATTER_MAX_BYTES = 64 * 1024+SKILL_BODY_MAX_BYTES = 256 * 1024+DISCOVERY_ROOT_MAX_CHILDREN = 1024+DISCOVERY_CLASS_MAX_CANDIDATES = 1024+DISCOVERY_CLASS_MAX_FRONTMATTER_BYTES = 8 * 1024 * 1024+DISCOVERY_CLASS_MAX_CHILDREN = 4096+PROJECT_ROOT_MAX_DIRECTORIES = 128+BUILTIN_TREE_MAX_ENTRIES = 4096+BUILTIN_TREE_MAX_BYTES = 32 * 1024 * 1024+CLAUDE_PLUGIN_LIST_MAX_BYTES = 1024 * 1024+CLAUDE_PLUGIN_LIST_MAX_ENTRIES = 256+CLAUDE_PLUGIN_LIST_TIMEOUT_SECONDS = 1++_SNAPSHOT_DOMAIN = b"avibe-builtin-snapshot-v1\0"+_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]?[+-]?$")+_CATALOG_FIELDS = frozenset({"name", "description", "disable-model-invocation"})+_WINDOWS_RESERVED = {+ "con",+ "prn",+ "aux",+ "nul",+ *(f"com{index}" for index in range(1, 10)),+ *(f"lpt{index}" for index in range(1, 10)),+}+_WINDOWS_INVALID_CHARS = frozenset('<>:"\\|?*')+_GENERATED_BYTECODE_SUFFIXES = (".pyc", ".pyo")+_PROJECT_FAMILIES = (+ (Path(".agents/skills"), 1),+ (Path(".codex/skills"), 2),+ (Path(".claude/skills"), 3),+ (Path(".opencode/skills"), 4),+)+@dataclass(frozen=True)+class ManagedSkill:+ name: str+ description: str+ directory: Path+ priority: tuple[object, ...]+ body: str | None = None+ directory_identity: tuple[int, int] | None = None+ source_directory: Path | None = None+ source_directory_identity: tuple[int, int] | None = None+ frontmatter_bytes: int = 0+ disable_model_invocation: bool = False+++@dataclass+class _DiscoveryBudget:+ candidates: int = 0+ frontmatter_bytes: int = 0+ direct_children: int = 0++ @property+ def exhausted(self) -> bool:+ return (+ self.candidates >= DISCOVERY_CLASS_MAX_CANDIDATES+ or self.frontmatter_bytes >= DISCOVERY_CLASS_MAX_FRONTMATTER_BYTES+ or self.direct_children >= DISCOVERY_CLASS_MAX_CHILDREN+ )++ @property+ def parse_exhausted(self) -> bool:+ return (+ self.candidates >= DISCOVERY_CLASS_MAX_CANDIDATES+ or self.frontmatter_bytes >= DISCOVERY_CLASS_MAX_FRONTMATTER_BYTES+ )++ @property+ def remaining_frontmatter(self) -> int:+ return max(0, DISCOVERY_CLASS_MAX_FRONTMATTER_BYTES - self.frontmatter_bytes)++ @property+ def remaining_children(self) -> int:+ return max(0, DISCOVERY_CLASS_MAX_CHILDREN - self.direct_children)+++@dataclass(frozen=True)+class _SnapshotEntry:+ path: Path+ relative: str+ relative_bytes: bytes+ is_directory: bool+++def _strip_yaml_comment(value: str) -> str:+ single_quoted = False+ double_quoted = False+ escaped = False+ index = 0+ while index < len(value):+ char = value[index]+ if double_quoted:+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ double_quoted = False+ elif single_quoted:+ if char == "'" and index + 1 < len(value) and value[index + 1] == "'":+ index += 1+ elif char == "'":+ single_quoted = False+ elif char == "'":+ single_quoted = True+ elif char == '"':+ double_quoted = True+ elif char == "#" and (index == 0 or value[index - 1].isspace()):+ return value[:index].rstrip()+ index += 1+ return value.rstrip()+++def _decode_scalar(value: str) -> str:+ value = value.strip()+ try:+ node = yaml.compose(value, Loader=yaml.BaseLoader)+ except Exception:+ node = None+ if isinstance(node, yaml.ScalarNode):+ return node.value.strip()+ return value.strip()+++def _quoted_scalar_is_closed(value: str) -> bool:+ """Return whether a leading YAML quote has a matching closing quote."""++ if not value or value[0] not in {"'", '"'}:+ return True+ quote = value[0]+ escaped = False+ index = 1+ while index < len(value):+ char = value[index]+ if quote == '"':+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == quote:+ return True+ elif char == quote:+ if index + 1 < len(value) and value[index + 1] == quote:+ index += 1+ else:+ return True+ index += 1+ return False+++def _normalize_description(value: str) -> str:+ without_controls = "".join(" " if unicodedata.category(char).startswith("C") else char for char in value)+ return " ".join(without_controls.split())+++class _BoundedBaseLoader(yaml.BaseLoader):+ """Compose bounded YAML nodes without constructing optional typed values."""++ def __init__(self, stream: str) -> None:+ super().__init__(stream)+ self._composed_nodes = 0+ self._aliases = 0++ def compose_node(self, parent, index):+ if self.check_event(yaml.AliasEvent):+ self._aliases += 1+ if self._aliases > 128:+ raise yaml.YAMLError("frontmatter contains too many YAML aliases")+ else:+ self._composed_nodes += 1+ if self._composed_nodes > 1024:+ raise yaml.YAMLError("frontmatter contains too many YAML nodes")+ return super().compose_node(parent, index)+++def _normalize_frontmatter_value(field: str, value: str) -> str:+ return _normalize_description(value) if field == "description" else value.strip()+++def _structured_frontmatter_fields(frontmatter: str) -> dict[str, str]:+ """Read only the root scalar fields needed by the managed catalog."""++ try:+ node = yaml.compose(frontmatter, Loader=_BoundedBaseLoader)+ except Exception:+ return {}+ if not isinstance(node, yaml.MappingNode):+ return {}++ fields: dict[str, str] = {}+ for key_node, value_node in node.value:+ if not isinstance(key_node, yaml.ScalarNode) or not isinstance(value_node, yaml.ScalarNode):+ continue+ field = key_node.value.strip()+ if field not in _CATALOG_FIELDS or field in fields:+ continue+ value = _normalize_frontmatter_value(field, value_node.value)+ if value:+ fields[field] = value+ return fields+++def _top_level_catalog_field(line: str) -> tuple[str, str] | None:+ """Split one top-level mapping line and decode its scalar key."""++ if not line or line[0].isspace() or line[0] == "#":+ return None+ single_quoted = False+ double_quoted = False+ escaped = False+ index = 0+ while index < len(line):+ char = line[index]+ if double_quoted:+ if escaped:+ escaped = False+ elif char == "\\":+ escaped = True+ elif char == '"':+ double_quoted = False+ elif single_quoted:+ if char == "'" and index + 1 < len(line) and line[index + 1] == "'":+ index += 1+ elif char == "'":+ single_quoted = False+ elif char == "'":+ single_quoted = True+ elif char == '"':+ double_quoted = True+ elif char == ":":+ field = _decode_scalar(line[:index])+ if field in _CATALOG_FIELDS:+ return field, line[index + 1 :]+ return None+ index += 1+ return None+++def _frontmatter_fields(lines: Sequence[str]) -> dict[str, str]:+ fields = _structured_frontmatter_fields("".join(lines))+ if "name" in fields and "description" in fields:+ return fields++ index = 0+ while index < len(lines):+ matched = _top_level_catalog_field(lines[index].rstrip("\r\n"))+ if matched is None:+ index += 1+ continue++ field, raw_value = matched+ if field in fields:+ index += 1+ continue++ value = _strip_yaml_comment(raw_value.strip())+ if _BLOCK_SCALAR_RE.match(value):+ continuation: list[str] = []+ index += 1+ while index < len(lines):+ line = lines[index].rstrip("\r\n")+ if line and not line[0].isspace() and _TOP_LEVEL_FIELD_RE.match(line):+ break+ continuation.append(line.strip())+ index += 1+ value = " ".join(part for part in continuation if part)+ elif not value:+ continuation = []+ index += 1+ while index < len(lines):+ line = lines[index].rstrip("\r\n")+ if line and not line[0].isspace():+ if line.startswith("#"):+ index += 1+ continue+ break+ continuation.append(_strip_yaml_comment(line.strip()))+ index += 1+ value = " ".join(part for part in continuation if part)+ elif value[0] in {"'", '"'} and not _quoted_scalar_is_closed(value):+ continuation = [value]+ index += 1+ while index < len(lines):+ line = lines[index].rstrip("\r\n")+ if line and not line[0].isspace():+ break+ continuation.append(line.strip())+ index += 1+ combined = " ".join(part for part in continuation if part)+ if _quoted_scalar_is_closed(combined):+ break+ value = _strip_yaml_comment(" ".join(part for part in continuation if part))+ elif field == "description":+ continuation = [value]+ index += 1+ while index < len(lines):+ line = lines[index].rstrip("\r\n")+ if line and not line[0].isspace():+ break+ continuation.append(_strip_yaml_comment(line.strip()))+ index += 1+ value = " ".join(part for part in continuation if part)+ else:+ index += 1++ decoded = _normalize_frontmatter_value(field, _decode_scalar(value))+ if decoded:+ fields[field] = decoded++ return fields+++def _body_has_terminal_controls(value: str) -> bool:+ return any(+ unicodedata.category(char) == "Cc" and char not in {"\t", "\n", "\r"}+ for char in value+ )+++def _stat_token(value: os.stat_result) -> tuple[int, int, int, int, int]:+ return (+ int(value.st_dev),+ int(value.st_ino),+ int(value.st_size),+ int(getattr(value, "st_mtime_ns", int(value.st_mtime * 1_000_000_000))),+ int(getattr(value, "st_ctime_ns", int(value.st_ctime * 1_000_000_000))),+ )+++def _directory_identity(value: os.stat_result) -> tuple[int, int]:+ return int(value.st_dev), int(value.st_ino)+++def _absolute_path(path: str | Path) -> Path:+ return Path(os.path.abspath(os.path.expanduser(os.fspath(path))))+++def _path_is_utf8(path: Path) -> bool:+ try:+ os.fspath(path).encode("utf-8", errors="strict")+ except UnicodeEncodeError:+ return False+ return True+++def _regular_open_flags() -> int:+ flags = os.O_RDONLY+ for name in ("O_BINARY", "O_CLOEXEC", "O_NONBLOCK", "O_NOFOLLOW"):+ flags |= int(getattr(os, name, 0))+ return flags+++def _open_regular_file(path: str | Path, *, dir_fd: int | None = None) -> tuple[int, os.stat_result]:+ raw_path = os.fspath(path)+ follow_guard = int(getattr(os, "O_NOFOLLOW", 0))+ before_path: os.stat_result | None = None+ if not follow_guard:+ try:+ before_path = os.stat(raw_path, dir_fd=dir_fd, follow_symlinks=False)+ except (OSError, TypeError, NotImplementedError):+ before_path = None+ if before_path is not None and not stat.S_ISREG(before_path.st_mode):+ raise OSError(errno.EINVAL, "Skill file is not a regular file", raw_path)++ try:+ fd = os.open(raw_path, _regular_open_flags(), dir_fd=dir_fd)+ except (TypeError, NotImplementedError):+ if dir_fd is not None:+ raise+ fd = os.open(raw_path, _regular_open_flags())+ try:+ opened = os.fstat(fd)+ if not stat.S_ISREG(opened.st_mode):+ raise OSError(errno.EINVAL, "Skill file is not a regular file", raw_path)+ if before_path is not None and _directory_identity(before_path) != _directory_identity(opened):+ raise OSError(errno.ESTALE, "Skill file changed while opening", raw_path)+ return fd, opened+ except BaseException:+ os.close(fd)+ raise+++def _frontmatter_bounds(data: bytes, *, complete: bool) -> tuple[int, int, int] | None:+ start = 3 if data.startswith(b"\xef\xbb\xbf") else 0+ opening_end = data.find(b"\n", start)+ if opening_end < 0:+ return None+ if data[start:opening_end].rstrip(b"\r") != b"---":+ return None++ position = opening_end + 1+ while position <= len(data):+ line_end = data.find(b"\n", position)+ if line_end < 0:+ if not complete:+ return None+ line_end = len(data)+ next_position = line_end+ else:+ next_position = line_end + 1+ if data[position:line_end].rstrip(b"\r") == b"---":+ return opening_end + 1, position, next_position+ if line_end >= len(data):+ return None+ position = next_position+ return None+++def _read_prefix(fd: int, *, limit: int, file_size: int) -> bytes:+ data = bytearray()+ while len(data) < limit:+ chunk = os.read(fd, min(4096, limit - len(data)))+ if not chunk:+ break+ data.extend(chunk)+ if _frontmatter_bounds(bytes(data), complete=len(data) >= file_size) is not None:+ break+ return bytes(data)+++def _read_all(fd: int, *, limit: int) -> bytes:+ data = bytearray()+ while len(data) <= limit:+ chunk = os.read(fd, min(64 * 1024, limit + 1 - len(data)))+ if not chunk:+ return bytes(data)+ data.extend(chunk)+ raise ValueError("Skill file exceeds the load limit")+++def _read_skill_path(+ skill_file: Path,+ *,+ priority: tuple[object, ...],+ include_body: bool,+ frontmatter_limit: int = FRONTMATTER_MAX_BYTES,+ dir_fd: int | None = None,+ source_directory: Path | None = None,+ source_directory_identity: tuple[int, int] | None = None,+ expected_directory_identity: tuple[int, int] | None = None,+) -> tuple[ManagedSkill | None, int]:+ fd: int | None = None+ try:+ fd, before = _open_regular_file(+ "SKILL.md" if dir_fd is not None else skill_file,+ dir_fd=dir_fd,+ )+ if before.st_size > FRONTMATTER_MAX_BYTES + SKILL_BODY_MAX_BYTES:+ return None, 0+ if include_body:+ data = _read_all(fd, limit=FRONTMATTER_MAX_BYTES + SKILL_BODY_MAX_BYTES)+ else:+ data = _read_prefix(+ fd,+ limit=min(FRONTMATTER_MAX_BYTES, max(0, frontmatter_limit)),+ file_size=int(before.st_size),+ )+ after = os.fstat(fd)+ if _stat_token(before) != _stat_token(after):+ return None, len(data)+ try:+ path_after = os.stat(+ "SKILL.md" if dir_fd is not None else skill_file,+ dir_fd=dir_fd,+ follow_symlinks=False,+ )+ except (OSError, TypeError, NotImplementedError):+ return None, len(data)+ if (+ not stat.S_ISREG(path_after.st_mode)+ or _directory_identity(path_after) != _directory_identity(before)+ ):+ return None, len(data)+ except (OSError, ValueError):+ return None, 0+ finally:+ if fd is not None:+ os.close(fd)++ bounds = _frontmatter_bounds(data, complete=include_body or len(data) >= before.st_size)+ if bounds is None:+ return None, min(len(data), frontmatter_limit)+ frontmatter_start, frontmatter_end, body_start = bounds+ if body_start > FRONTMATTER_MAX_BYTES or body_start > frontmatter_limit:+ return None, min(body_start, frontmatter_limit)+ if before.st_size - body_start > SKILL_BODY_MAX_BYTES:+ return None, body_start++ frontmatter = data[frontmatter_start:frontmatter_end].decode("utf-8", errors="replace")+ fields = _frontmatter_fields(frontmatter.splitlines(keepends=True))+ name = fields.get("name", "")+ description = fields.get("description", "")+ disable_model_invocation = fields.get("disable-model-invocation", "").casefold() in {+ "1",+ "on",+ "true",+ "yes",+ }+ if not description or not 1 <= len(name) <= 64 or _PORTABLE_NAME_RE.fullmatch(name) is None:+ return None, body_start+ if len(description) > CATALOG_DESCRIPTION_MAX_CHARS:+ description = description[: CATALOG_DESCRIPTION_MAX_CHARS - 3].rstrip() + "..."++ body: str | None = None+ if include_body:+ try:+ body = data[body_start:].decode("utf-8")+ except UnicodeDecodeError:+ return None, body_start++ directory = _absolute_path(skill_file.parent)+ if not _path_is_utf8(directory):+ return None, body_start+ source = _absolute_path(source_directory or directory)+ try:+ directory_stat = directory.stat(follow_symlinks=False)+ except OSError:+ return None, body_start+ if not stat.S_ISDIR(directory_stat.st_mode):+ return None, body_start+ directory_identity = _directory_identity(directory_stat)+ if expected_directory_identity is not None and directory_identity != expected_directory_identity:+ return None, body_start+ if not _source_directory_still_matches(+ source,+ directory,+ source_directory_identity or directory_identity,+ ):+ return None, body_start++ return (+ ManagedSkill(+ name=name,+ description=description,+ directory=directory,+ priority=priority,+ body=body,+ directory_identity=directory_identity,+ source_directory=source,+ source_directory_identity=source_directory_identity or directory_identity,+ frontmatter_bytes=body_start,+ disable_model_invocation=disable_model_invocation,+ ),+ body_start,+ )+++def parse_skill_file(+ skill_file: Path,+ *,+ priority: tuple[object, ...],+ include_body: bool = True,+) -> ManagedSkill | None:+ """Parse one Skill through the same bounded regular-file path as discovery."""++ normalized_priority = tuple(priority)+ if len(normalized_priority) == 3:+ normalized_priority = (*normalized_priority, str(_absolute_path(skill_file.parent)))+ skill, _ = _read_skill_path(+ skill_file,+ priority=normalized_priority,+ include_body=include_body,+ )+ return skill+++def _root_children(+ root: Path,+ *,+ ignored_names: frozenset[str] = frozenset(),+ budget: _DiscoveryBudget | None = None,+) -> list[tuple[str, Path, os.stat_result]] | None:+ children: list[tuple[str, Path, os.stat_result]] = []+ limit = DISCOVERY_ROOT_MAX_CHILDREN+ if budget is not None:+ if budget.remaining_children == 0:+ return None+ limit = min(limit, budget.remaining_children)+ enumerated = 0+ try:+ with os.scandir(root) as entries:+ for entry in entries:+ enumerated += 1+ if enumerated > limit:+ if budget is not None:+ budget.direct_children += enumerated+ return None+ if entry.name in ignored_names:+ continue+ try:+ entry_stat = entry.stat(follow_symlinks=False)+ except OSError:+ continue+ children.append((entry.name, Path(entry.path), entry_stat))+ except OSError:+ return []+ if budget is not None:+ budget.direct_children += enumerated+ children.sort(key=lambda item: item[0])+ return children+++def _resolved_candidate_directory(+ source: Path,+ source_stat: os.stat_result,+) -> tuple[Path, tuple[int, int], tuple[int, int]] | None:+ source_identity = _directory_identity(source_stat)+ if stat.S_ISDIR(source_stat.st_mode):+ return _absolute_path(source), source_identity, source_identity+ if not stat.S_ISLNK(source_stat.st_mode):+ return None+ try:+ target = source.resolve(strict=True)+ target_stat = target.stat(follow_symlinks=False)+ after = source.stat(follow_symlinks=False)+ except (OSError, RuntimeError):+ return None+ if (+ not stat.S_ISDIR(target_stat.st_mode)+ or not stat.S_ISLNK(after.st_mode)+ or _directory_identity(after) != source_identity+ ):+ return None+ return _absolute_path(target), source_identity, _directory_identity(target_stat)+++def _scan_root(+ root: Path,+ *,+ priority: tuple[int, int, int],+ budget: _DiscoveryBudget,+ seen_directory_identities: set[tuple[int, int]] | None = None,+ ignored_names: frozenset[str] = frozenset(),+) -> list[ManagedSkill]:+ children = _root_children(root, ignored_names=ignored_names, budget=budget)+ if children is None:+ logger.info("Omitting oversized Skill root: %s", root)+ return []++ skills: list[ManagedSkill] = []+ for _, child, child_stat in children:+ if budget.parse_exhausted:+ break+ resolved_directory = _resolved_candidate_directory(child, child_stat)+ if resolved_directory is None:+ continue+ directory, source_identity, directory_identity = resolved_directory+ if not _path_is_utf8(directory):+ continue+ if seen_directory_identities is not None:+ if directory_identity in seen_directory_identities:+ continue+ seen_directory_identities.add(directory_identity)+ budget.candidates += 1+ skill_file = directory / "SKILL.md"+ path_priority: tuple[object, ...] = (*priority, str(_absolute_path(child)))+ skill, consumed = _read_skill_path(+ skill_file,+ priority=path_priority,+ include_body=False,+ frontmatter_limit=min(FRONTMATTER_MAX_BYTES, budget.remaining_frontmatter),+ source_directory=child,+ source_directory_identity=source_identity,+ expected_directory_identity=directory_identity,+ )+ budget.frontmatter_bytes += consumed+ if skill is not None:+ skills.append(skill)+ return skills+++def _project_directories(+ cwd: Path,+ *,+ project_base: str | Path | None = None,+) -> list[Path]:+ current = cwd.expanduser().resolve()+ if not current.is_dir():+ return []+ boundary = _project_base_for_working_directory(current, project_base)+ directories: list[Path] = []+ directory = current+ for _ in range(PROJECT_ROOT_MAX_DIRECTORIES):+ directories.append(directory)+ if directory == boundary or (boundary is None and (directory / ".git").exists()):+ return directories+ if directory.parent == directory:+ break+ directory = directory.parent+ return [current]+++def _project_base_for_working_directory(+ working_directory: Path,+ project_base: str | Path | None,+) -> Path | None:+ if project_base is None:+ return None+ raw = Path(project_base).expanduser()+ if not raw.is_absolute():+ return None+ resolved = raw.resolve()+ try:+ relative = working_directory.relative_to(resolved)+ except ValueError:+ return None+ if len(relative.parts) >= PROJECT_ROOT_MAX_DIRECTORIES:+ return None+ return resolved+++def managed_skill_project_base(context: Any) -> str | None:+ """Return the project base bound to a resolved Avibe run target."""++ payload = getattr(context, "platform_specific", None) or {}+ target = payload.get("agent_run_target") if isinstance(payload, dict) else None+ value = target.get("project_base") if isinstance(target, dict) else None+ return str(value) if isinstance(value, str) and value else None+++def managed_skill_claude_cli_path(config: Any) -> str | None:+ """Return the Claude executable selected by the live runtime config."""++ claude = getattr(config, "claude", None)+ if claude is None:+ claude = getattr(getattr(config, "agents", None), "claude", None)+ value = getattr(claude, "cli_path", None)+ normalized = str(value).strip() if value is not None else ""+ return os.path.expanduser(normalized) if normalized else None+++def _working_directory(cwd: str | Path | None) -> Path:+ if cwd is not None:+ return Path(cwd).expanduser().resolve()+ bound = os.environ.get(SKILL_WORKING_DIR_ENV)+ return Path(bound or Path.cwd()).expanduser().resolve()+++def _selected_builtin_root(+ avibe_home: Path,+ *,+ snapshot_id: str | None = None,+ snapshot_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 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:+ try:+ selected = publish_builtin_skills(destination_root=avibe_home / "builtin-skills")+ 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 None+ if root is None:+ root = avibe_home / "builtin-skills" / selected+ try:+ root_stat = root.stat(follow_symlinks=False)+ except OSError:+ return None+ return root if stat.S_ISDIR(root_stat.st_mode) else None+++def _claude_plugin_skill_roots(+ working_directory: Path,+ claude_home: Path,+ claude_cli_path: str | None,+) -> list[Path]:+ registry = claude_home / "plugins" / "installed_plugins.json"+ try:+ if not registry.is_file():+ return []+ except OSError:+ return []++ command = (+ claude_cli_path+ or os.environ.get(SKILL_CLAUDE_CLI_PATH_ENV)+ or os.environ.get("CLAUDE_CLI_PATH")+ or shutil.which("claude")+ )+ if not command:+ return []+ environment = dict(os.environ)+ environment["CLAUDE_CONFIG_DIR"] = str(claude_home)+ output = _bounded_subprocess_stdout(+ [command, "plugin", "list", "--json"],+ cwd=working_directory,+ env=environment,+ timeout=CLAUDE_PLUGIN_LIST_TIMEOUT_SECONDS,+ max_bytes=CLAUDE_PLUGIN_LIST_MAX_BYTES,+ )+ if output is None:+ return []+ try:+ payload = json.loads(output.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError):+ return []+ if not isinstance(payload, list) or len(payload) > CLAUDE_PLUGIN_LIST_MAX_ENTRIES:+ return []++ roots: list[tuple[str, Path]] = []+ for item in payload:+ if not isinstance(item, dict) or item.get("enabled") is not True:+ continue+ plugin_id = item.get("id")+ install_path = item.get("installPath")+ if not isinstance(plugin_id, str) or not isinstance(install_path, str):+ continue+ raw_path = Path(install_path).expanduser()+ if not raw_path.is_absolute():+ continue+ root = _absolute_path(raw_path) / "skills"+ if not _path_is_utf8(root):+ continue+ roots.append((plugin_id, root))+ return [root for _, root in sorted(roots, key=lambda item: (item[0], str(item[1])))]+++def _bounded_subprocess_stdout(+ command: Sequence[str],+ *,+ cwd: Path,+ env: dict[str, str],+ timeout: float,+ max_bytes: int,+) -> bytes | None:+ """Capture stdout while bounding combined stdout and stderr in memory."""++ try:+ process = subprocess.Popen(+ command,+ cwd=cwd,+ env=env,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ except OSError:+ logger.info("Unable to start bounded subprocess", exc_info=True)+ return None++ stdout = bytearray()+ total_bytes = 0+ lock = threading.Lock()+ limit_exceeded = threading.Event()++ def drain(stream, *, collect: bool) -> None:+ nonlocal total_bytes+ try:+ while chunk := stream.read(64 * 1024):+ with lock:+ total_bytes += len(chunk)+ if collect and len(stdout) <= max_bytes:+ remaining = max_bytes + 1 - len(stdout)+ stdout.extend(chunk[:remaining])+ if total_bytes > max_bytes:+ limit_exceeded.set()+ except (OSError, ValueError):+ return++ assert process.stdout is not None+ assert process.stderr is not None+ streams = (process.stdout, process.stderr)+ threads = (+ threading.Thread(target=drain, args=(process.stdout,), kwargs={"collect": True}, daemon=True),+ threading.Thread(target=drain, args=(process.stderr,), kwargs={"collect": False}, daemon=True),+ )+ for thread in threads:+ thread.start()++ deadline = time.monotonic() + timeout+ timed_out = False+ while process.poll() is None:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ timed_out = True+ break+ if limit_exceeded.wait(min(0.02, remaining)):+ break++ if (timed_out or limit_exceeded.is_set()) and process.poll() is None:+ process.kill()+ try:+ process.wait(timeout=1)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()++ for thread in threads:+ thread.join(timeout=1)+ if any(thread.is_alive() for thread in threads):+ for stream in streams:+ stream.close()+ return None+ if timed_out or limit_exceeded.is_set() or process.returncode != 0:+ return None+ return bytes(stdout)+++def resolve_skills(+ cwd: str | Path | None = None,+ *,+ project_base: str | Path | None = None,+ home: str | Path | None = None,+ avibe_home: str | Path | None = None,+ codex_home: str | Path | None = None,+ 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,+) -> list[ManagedSkill]:+ """Resolve the live Skill catalog using Avibe's v1 precedence rules."""++ resolved_home = (+ Path(home).expanduser().resolve()+ if home is not None+ else Path(os.environ.get(SKILL_HOME_ENV) or Path.home()).expanduser().resolve()+ )+ resolved_avibe_home = (+ Path(avibe_home).expanduser().resolve()+ if avibe_home is not None+ else paths.get_vibe_remote_dir().expanduser().resolve()+ )+ resolved_codex_home = (+ Path(codex_home).expanduser().resolve()+ if codex_home is not None+ else Path(+ os.environ.get(SKILL_CODEX_HOME_ENV)+ or os.environ.get("CODEX_HOME")+ or resolved_home / ".codex"+ )+ .expanduser()+ .resolve()+ )+ if claude_home is not None:+ resolved_claude_home = Path(claude_home).expanduser().resolve()+ else:+ bound_claude_home = os.environ.get(SKILL_CLAUDE_HOME_ENV)+ if bound_claude_home:+ resolved_claude_home = Path(bound_claude_home).expanduser().resolve()+ else:+ from vibe.claude_config import get_claude_home++ resolved_claude_home = get_claude_home(resolved_home if home is not None else None).expanduser().resolve()+ resolved_xdg_home = (+ Path(xdg_config_home).expanduser().resolve()+ if xdg_config_home is not None+ else Path(+ os.environ.get(SKILL_XDG_CONFIG_HOME_ENV)+ or os.environ.get("XDG_CONFIG_HOME")+ or resolved_home / ".config"+ )+ .expanduser()+ .resolve()+ )++ candidates: list[ManagedSkill] = []+ builtin_budget = _DiscoveryBudget()+ builtin_root = _selected_builtin_root(+ resolved_avibe_home,+ snapshot_id=builtin_snapshot_id,+ snapshot_root=builtin_snapshot_root,+ )+ if builtin_root is not None:+ candidates.extend(_scan_root(builtin_root, priority=(0, 0, 0), budget=builtin_budget))++ compatibility_budget = _DiscoveryBudget()+ compatibility_directory_identities: set[tuple[int, int]] = set()+ working_directory = _working_directory(cwd)+ selected_project_base = (+ project_base+ if project_base is not None+ else os.environ.get(SKILL_PROJECT_BASE_ENV)+ )+ for depth, directory in enumerate(+ _project_directories(+ working_directory,+ project_base=selected_project_base,+ )+ ):+ for relative_root, family_rank in _PROJECT_FAMILIES:+ if compatibility_budget.exhausted:+ break+ candidates.extend(+ _scan_root(+ directory / relative_root,+ priority=(1, depth, family_rank),+ budget=compatibility_budget,+ seen_directory_identities=compatibility_directory_identities,+ )+ )+ if compatibility_budget.exhausted:+ break++ global_user_roots = (+ (resolved_home / ".agents" / "skills", 1, frozenset()),+ (resolved_codex_home / "skills", 2, frozenset({".system"})),+ (resolved_claude_home / "skills", 3, frozenset()),+ (resolved_xdg_home / "opencode" / "skills", 4, frozenset()),+ )+ for root, family_rank, ignored_names in global_user_roots:+ if compatibility_budget.exhausted:+ break+ candidates.extend(+ _scan_root(+ root,+ priority=(2, 0, family_rank),+ budget=compatibility_budget,+ seen_directory_identities=compatibility_directory_identities,+ ignored_names=ignored_names,+ )+ )++ for root in _claude_plugin_skill_roots(+ working_directory,+ resolved_claude_home,+ claude_cli_path,+ ):+ if compatibility_budget.exhausted:+ break+ candidates.extend(+ _scan_root(+ root,+ priority=(2, 0, 5),+ budget=compatibility_budget,+ seen_directory_identities=compatibility_directory_identities,+ )+ )++ if not compatibility_budget.exhausted:+ candidates.extend(+ _scan_root(+ resolved_codex_home / "skills" / ".system",+ priority=(2, 0, 6),+ budget=compatibility_budget,+ seen_directory_identities=compatibility_directory_identities,+ )+ )++ winners: dict[str, ManagedSkill] = {}+ for candidate in candidates:+ current = winners.get(candidate.name)+ if current is None or candidate.priority < current.priority:+ winners[candidate.name] = candidate+ return sorted(winners.values(), key=lambda skill: skill.name)+++def _catalog_pages(skills: Sequence[ManagedSkill]) -> list[list[ManagedSkill]]:+ pages: list[list[ManagedSkill]] = []+ current: list[ManagedSkill] = []+ current_bytes = 0+ for skill in skills:+ if skill.disable_model_invocation:+ continue+ row = f"- {skill.name}: {skill.description}"+ row_bytes = len(row.encode("utf-8")) + (1 if current else 0)+ if current and (len(current) >= CATALOG_PAGE_SIZE or current_bytes + row_bytes > CATALOG_PAGE_MAX_BYTES):+ pages.append(current)+ current = []+ current_bytes = 0+ row_bytes = len(row.encode("utf-8"))+ current.append(skill)+ current_bytes += row_bytes+ if current:+ pages.append(current)+ return pages+++def _page(skills: Sequence[ManagedSkill], page: int) -> tuple[Sequence[ManagedSkill], int | None]:+ if isinstance(page, bool) or page < 1:+ raise ValueError("page must be a positive integer")+ pages = _catalog_pages(skills)+ if page > len(pages):+ return (), None+ return pages[page - 1], page + 1 if page < len(pages) else None+++def render_skill_list(+ skills: Sequence[ManagedSkill],+ *,+ page: int = 1,+ more_notice: str | None = None,+) -> str:+ entries, next_page = _page(skills, page)+ lines = [f"- {skill.name}: {skill.description}" for skill in entries]+ if next_page is not None:+ lines.append(+ more_notice or f"More skills are available. Run `vibe skill list --page {next_page}` to view more."+ )+ return "\n".join(lines)+++def render_skill_catalog_prompt(skills: Sequence[ManagedSkill]) -> str:+ rows = render_skill_list(skills, page=1)+ if not rows:+ if any(skill.disable_model_invocation for skill in skills):+ return (+ "\n\n## Skills\n\n"+ "If the user requests a skill by exact name, run "+ "`vibe skill load -- <name>` before proceeding.\n"+ "Otherwise, do not guess skill names."+ )+ return ""+ _, next_page = _page(skills, 1)+ later_page_guidance = (+ "Use `vibe skill list --page 2` only when more discovery is useful; "+ "ordinary tasks do not require scanning every page.\n"+ if next_page is not None+ else ""+ )+ return (+ "\n\n## Skills\n\n"+ "Skills provide specialized instructions and workflows for specific tasks.\n"+ "When a task matches a skill's description, run `vibe skill load -- <name>` before proceeding.\n"+ "If the user requests a skill by exact name, load that name directly.\n"+ "Otherwise, only load skill names listed here or returned by `vibe skill list`; do not guess names.\n\n"+ f"{later_page_guidance}"+ "### Available skills\n"+ f"{rows}"+ )+++def render_skill_content(skill: ManagedSkill) -> str:+ if skill.body is None:+ raise ValueError("Skill body was not loaded")+ name = html.escape(skill.name, quote=True)+ directory = html.escape(str(skill.directory), quote=True)+ directory = "".join(+ f"&#x{ord(char):X};" if unicodedata.category(char).startswith("C") else char for char in directory+ )+ return f'<skill_content name="{name}" directory="{directory}">\n{skill.body}</skill_content>'+++def _open_selected_directory(skill: ManagedSkill) -> tuple[int | None, tuple[int, int]]:+ if not _source_directory_still_matches(+ skill.source_directory or skill.directory,+ skill.directory,+ skill.source_directory_identity or skill.directory_identity,+ ):+ raise OSError(errno.ESTALE, "Selected Skill source directory changed")+ try:+ before = skill.directory.stat(follow_symlinks=False)+ except OSError as exc:+ raise OSError(errno.ESTALE, "Selected Skill directory disappeared") from exc+ if not stat.S_ISDIR(before.st_mode):+ raise OSError(errno.ENOTDIR, "Selected Skill path is not a directory")+ identity = _directory_identity(before)+ if skill.directory_identity is not None and identity != skill.directory_identity:+ raise OSError(errno.ESTALE, "Selected Skill directory changed")++ flags = os.O_RDONLY+ for name in ("O_CLOEXEC", "O_NONBLOCK", "O_NOFOLLOW", "O_DIRECTORY"):+ flags |= int(getattr(os, name, 0))+ try:+ fd = os.open(skill.directory, flags)+ except OSError:+ if os.name != "nt":+ raise+ return None, identity+ opened = os.fstat(fd)+ if not stat.S_ISDIR(opened.st_mode) or _directory_identity(opened) != identity:+ os.close(fd)+ raise OSError(errno.ESTALE, "Selected Skill directory changed while opening")+ return fd, identity+++def _directory_path_still_matches(path: Path, identity: tuple[int, int]) -> bool:+ try:+ current = path.stat(follow_symlinks=False)+ except OSError:+ return False+ return stat.S_ISDIR(current.st_mode) and _directory_identity(current) == identity+++def _source_directory_still_matches(+ source: Path,+ target: Path,+ identity: tuple[int, int] | None,+) -> bool:+ try:+ before = source.stat(follow_symlinks=False)+ if identity is not None and _directory_identity(before) != identity:+ return False+ if source == target:+ return stat.S_ISDIR(before.st_mode)+ if not stat.S_ISLNK(before.st_mode):+ return False+ resolved = source.resolve(strict=True)+ after = source.stat(follow_symlinks=False)+ except (OSError, RuntimeError):+ return False+ return (+ resolved == target and stat.S_ISLNK(after.st_mode) and _directory_identity(after) == _directory_identity(before)+ )+++def load_skill(+ name: str,+ cwd: str | Path | None = None,+ *,+ resolved_skills: Sequence[ManagedSkill] | None = None,+) -> ManagedSkill | None:+ if _PORTABLE_NAME_RE.fullmatch(name) is None or not 1 <= len(name) <= 64:+ return None+ catalog = resolve_skills(cwd) if resolved_skills is None else resolved_skills+ winner = next((skill for skill in catalog if skill.name == name), None)+ if winner is None:+ return None++ directory_fd: int | None = None+ try:+ directory_fd, identity = _open_selected_directory(winner)+ loaded, _ = _read_skill_path(+ winner.directory / "SKILL.md",+ priority=winner.priority,+ include_body=True,+ dir_fd=directory_fd,+ )+ if (+ loaded is None+ or loaded.name != name+ or loaded.body is None+ or _body_has_terminal_controls(loaded.body)+ ):+ return None+ if not _directory_path_still_matches(winner.directory, identity) or not _source_directory_still_matches(+ winner.source_directory or winner.directory,+ winner.directory,+ winner.source_directory_identity or identity,+ ):+ return None+ return ManagedSkill(+ name=loaded.name,+ description=loaded.description,+ directory=winner.directory,+ priority=winner.priority,+ body=loaded.body,+ directory_identity=identity,+ source_directory=winner.source_directory,+ source_directory_identity=winner.source_directory_identity,+ frontmatter_bytes=loaded.frontmatter_bytes,+ disable_model_invocation=loaded.disable_model_invocation,+ )+ except OSError:+ return None+ finally:+ if directory_fd is not None:+ os.close(directory_fd)+++def builtin_skills_source() -> Path:+ checkout_root = Path(__file__).resolve().parents[1]+ checkout_source = checkout_root / "skills"+ pyproject = checkout_root / "pyproject.toml"+ pyproject_fd: int | None = None+ try:+ pyproject_fd, _ = _open_regular_file(pyproject)+ project_header = _read_all(pyproject_fd, limit=64 * 1024)+ project_metadata = tomllib.loads(project_header.decode("utf-8"))+ project_name = str(project_metadata.get("project", {}).get("name") or "")+ except (OSError, UnicodeDecodeError, ValueError):+ project_name = ""+ finally:+ if pyproject_fd is not None:+ os.close(pyproject_fd)+ if checkout_source.is_dir() and (checkout_root / "vibe" / "__init__.py").is_file() and project_name == "avibe-os":+ return checkout_source++ import vibe++ packaged_source = Path(vibe.__file__).resolve().parent / "builtin_skills_source"+ if packaged_source.is_dir():+ return packaged_source+ raise RuntimeError("Avibe built-in Skills are missing from this installation")+++def _validate_portable_component(component: str) -> None:+ if not component or component in {".", ".."}:+ raise RuntimeError("Built-in Skill paths must be relative")+ if unicodedata.normalize("NFC", component) != component:+ raise RuntimeError(f"Built-in Skill path is not NFC: {component!r}")+ if component[-1] in {".", " "}:+ raise RuntimeError(f"Built-in Skill path has a trailing dot or space: {component!r}")+ if any(ord(char) < 32 or char in _WINDOWS_INVALID_CHARS or char == "\x00" for char in component):+ raise RuntimeError(f"Built-in Skill path is not portable: {component!r}")+ basename = component.split(".", 1)[0].casefold()+ if basename in _WINDOWS_RESERVED:+ raise RuntimeError(f"Built-in Skill path uses a Windows-reserved name: {component!r}")+++def _snapshot_entries(root: Path) -> list[_SnapshotEntry]:+ entries: list[_SnapshotEntry] = []+ aliases: set[str] = set()+ file_bytes = 0+ pending: list[tuple[Path, tuple[str, ...]]] = [(root, ())]++ while pending:+ directory, relative_parts = pending.pop()+ try:+ with os.scandir(directory) as scanned:+ children = sorted(scanned, key=lambda item: item.name)+ except OSError as exc:+ raise RuntimeError(f"Cannot read built-in Skill source: {directory}") from exc+ accepted_children = 0+ child_directories: list[tuple[Path, tuple[str, ...]]] = []+ for child in children:+ # Installers may compile Skill scripts in place; bytecode is not part of the bundled tree.+ if child.name == "__pycache__" or child.name.endswith(_GENERATED_BYTECODE_SUFFIXES):+ continue+ accepted_children += 1+ _validate_portable_component(child.name)+ child_parts = (*relative_parts, child.name)+ relative = "/".join(child_parts)+ relative_bytes = relative.encode("utf-8")+ alias = relative.casefold()+ if alias in aliases:+ raise RuntimeError(f"Built-in Skill paths collide case-insensitively: {relative}")+ aliases.add(alias)+ if len(entries) >= BUILTIN_TREE_MAX_ENTRIES:+ raise RuntimeError(+ f"Built-in Skill tree exceeds {BUILTIN_TREE_MAX_ENTRIES:,} entries"+ )+ try:+ child_stat = child.stat(follow_symlinks=False)+ except OSError as exc:+ raise RuntimeError(f"Cannot inspect built-in Skill path: {relative}") from exc+ file_attributes = int(getattr(child_stat, "st_file_attributes", 0))+ 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}")+ if stat.S_ISDIR(child_stat.st_mode):+ entries.append(_SnapshotEntry(Path(child.path), relative, relative_bytes, True))+ child_directories.append((Path(child.path), child_parts))+ elif stat.S_ISREG(child_stat.st_mode):+ file_bytes += int(child_stat.st_size)+ if file_bytes > BUILTIN_TREE_MAX_BYTES:+ raise RuntimeError(+ f"Built-in Skill tree exceeds {BUILTIN_TREE_MAX_BYTES:,} bytes"+ )+ entries.append(_SnapshotEntry(Path(child.path), relative, relative_bytes, False))+ else:+ raise RuntimeError(f"Built-in Skill path is not a directory or regular file: {relative}")+ if relative_parts and accepted_children == 0:+ raise RuntimeError(f"Built-in Skill directories must not be empty: {'/'.join(relative_parts)}")+ pending.extend(reversed(child_directories))++ entries.sort(key=lambda entry: entry.relative_bytes)+ 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."""++ consumed_bytes = 0+ for entry in entries:+ target = destination.joinpath(*entry.relative.split("/"))+ if entry.is_directory:+ try:+ source_stat = entry.path.stat(follow_symlinks=False)+ except OSError as exc:+ raise RuntimeError(+ f"Cannot inspect built-in Skill path: {entry.relative}"+ ) from exc+ if not stat.S_ISDIR(source_stat.st_mode):+ raise RuntimeError(+ f"Built-in Skill directory changed during publication: {entry.relative}"+ )+ target.mkdir(mode=0o700)+ continue++ source_fd: int | None = None+ target_fd: int | None = None+ try:+ source_fd, before = _open_regular_file(entry.path)+ file_size = int(before.st_size)+ if file_size > BUILTIN_TREE_MAX_BYTES - consumed_bytes:+ raise RuntimeError(+ f"Built-in Skill tree exceeds {BUILTIN_TREE_MAX_BYTES:,} bytes"+ )+ consumed_bytes += file_size+ target_flags = (+ os.O_WRONLY+ | os.O_CREAT+ | os.O_EXCL+ | getattr(os, "O_BINARY", 0)+ )+ target_fd = os.open(target, target_flags, 0o600)+ remaining = file_size+ while remaining:+ chunk = os.read(source_fd, min(1024 * 1024, remaining))+ if not chunk:+ raise RuntimeError(+ f"Built-in Skill file changed during publication: {entry.relative}"+ )+ view = memoryview(chunk)+ while view:+ written = os.write(target_fd, view)+ view = view[written:]+ remaining -= len(chunk)+ if os.read(source_fd, 1):+ raise RuntimeError(+ f"Built-in Skill file grew during publication: {entry.relative}"+ )+ after = os.fstat(source_fd)+ if _stat_token(before) != _stat_token(after):+ raise RuntimeError(+ f"Built-in Skill file changed during publication: {entry.relative}"+ )+ if os.name != "nt" and callable(getattr(os, "fchmod", None)):+ os.fchmod(target_fd, 0o644 | int(before.st_mode & 0o111))+ finally:+ if target_fd is not None:+ os.close(target_fd)+ if source_fd is not None:+ os.close(source_fd)+++def _validate_builtin_catalog(root: Path) -> None:+ children = _root_children(root)+ if children is None:+ raise RuntimeError("Avibe packages at most 1,024 built-in Skills")+ frontmatter_bytes = 0+ declared_names: set[str] = set()+ for name, child, child_stat in children:+ if not stat.S_ISDIR(child_stat.st_mode):+ raise RuntimeError(f"Built-in Skill root entry is not a directory: {name}")+ skill, consumed = _read_skill_path(+ child / "SKILL.md",+ priority=(0, 0, 0, str(_absolute_path(child))),+ include_body=True,+ )+ if skill is None:+ raise RuntimeError(f"Built-in Skill is invalid: {name}")+ if skill.name in declared_names:+ raise RuntimeError(f"Built-in Skills must have unique declared names: {skill.name}")+ declared_names.add(skill.name)+ frontmatter_bytes += consumed+ if frontmatter_bytes > DISCOVERY_CLASS_MAX_FRONTMATTER_BYTES:+ raise RuntimeError("Built-in Skill frontmatter exceeds the 8 MiB catalog budget")+++def _remove_snapshot_staging(path: Path) -> None:+ try:+ value = path.stat(follow_symlinks=False)+ except FileNotFoundError:+ return+ except OSError as exc:+ raise RuntimeError(f"Cannot inspect built-in Skill staging path: {path}") from exc+ reparse_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:+ path.unlink()+++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."""++ source = Path(source_root).resolve() if source_root is not None else builtin_skills_source()+ umbrella = (+ Path(destination_root).expanduser().resolve()+ if destination_root is not None+ else (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++ from storage.lock import MigrationFileLock++ umbrella.mkdir(parents=True, exist_ok=True)+ lock_path = umbrella / f".publish-{snapshot_id}.lock"+ with MigrationFileLock(lock_path, timeout_seconds=None):+ staging = umbrella / f".snapshot-{snapshot_id}.staging"+ _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_id+ staging.mkdir(mode=0o700)+ try:+ _copy_snapshot_entries(_snapshot_entries(source), staging)+ _validate_builtin_catalog(staging)+ if snapshot_tree_digest(staging) != snapshot_id:+ raise RuntimeError("Built-in Skill source changed during publication")+ try:+ os.rename(staging, destination)+ except OSError as exc:+ if exc.errno not in {errno.EEXIST, errno.ENOTEMPTY}:+ raise+ finally:+ if os.path.lexists(staging):+ _remove_snapshot_staging(staging)+ return snapshot_id+++def prepare_builtin_skills() -> str:+ """Publish and bind the running artifact's built-in snapshot."""++ 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+++def 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,+ claude_cli_path: str | None = None,+) -> dict[str, str]:+ """Return the per-backend shell bindings consumed by ``vibe skill``."""++ env: dict[str, str] = {}+ if working_directory is not None:+ resolved_working_directory = Path(working_directory).expanduser().resolve()+ env[SKILL_WORKING_DIR_ENV] = str(resolved_working_directory)+ resolved_project_base = _project_base_for_working_directory(+ resolved_working_directory,+ project_base,+ )+ if resolved_project_base is not None:+ env[SKILL_PROJECT_BASE_ENV] = str(resolved_project_base)+ resolved_home = Path.home().resolve()+ resolved_codex_home = Path(os.environ.get("CODEX_HOME") or resolved_home / ".codex").expanduser().resolve()+ from vibe.claude_config import get_claude_home++ resolved_claude_home = get_claude_home().expanduser().resolve()+ resolved_xdg_home = Path(os.environ.get("XDG_CONFIG_HOME") or resolved_home / ".config").expanduser().resolve()+ env.update(+ {+ SKILL_HOME_ENV: str(resolved_home),+ SKILL_CODEX_HOME_ENV: str(resolved_codex_home),+ SKILL_CLAUDE_HOME_ENV: str(resolved_claude_home),+ SKILL_XDG_CONFIG_HOME_ENV: str(resolved_xdg_home),+ }+ )+ normalized_claude_cli_path = str(claude_cli_path or "").strip()+ if normalized_claude_cli_path:+ 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 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/core/services/agent_run_target.py b/core/services/agent_run_target.pyindex 3f553040e..160ee466a 100644--- a/core/services/agent_run_target.py+++ b/core/services/agent_run_target.py@@ -27,8 +27,10 @@ from core.message_context import (from config.v2_settings import make_thread_native_idfrom modules.im import MessageContextfrom storage.agent_session_rows import (+ SESSION_PROJECT_BASE_METADATA_KEY,create_agent_session_row,get_or_create_agent_session_row,+ normalize_session_project_base,utc_now_iso,)from storage.models import agent_sessions, scope_settings, scopes@@ -44,6 +46,7 @@ class AgentRunTarget:session_anchor: strworkdir: strsource: str+ project_base: Optional[str] = Nonescope_id: Optional[str] = Nonescope_type: Optional[str] = Noneagent_session_id: Optional[str] = None@@ -64,6 +67,7 @@ class AgentRunTarget:"session_anchor": self.session_anchor,"workdir": self.workdir,"source": self.source,+ "project_base": self.project_base,"scope_id": self.scope_id,"scope_type": self.scope_type,"agent_session_id": self.agent_session_id,@@ -128,8 +132,13 @@ def resolve_agent_run_target(select(agent_sessions,scopes.c.scope_type.label("_scope_type"),+ scope_settings.c.workdir.label("_scope_workdir"),+ )+ .select_from(+ agent_sessions+ .outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)+ .outerjoin(scope_settings, scope_settings.c.scope_id == agent_sessions.c.scope_id))- .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.id == target_id)).mappings().first()# An archived target is terminal — treat it as gone so no turn resumes it.@@ -179,8 +188,13 @@ def resolve_agent_run_target(select(agent_sessions,scopes.c.scope_type.label("_scope_type"),+ scope_settings.c.workdir.label("_scope_workdir"),+ )+ .select_from(+ agent_sessions+ .outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)+ .outerjoin(scope_settings, scope_settings.c.scope_id == agent_sessions.c.scope_id))- .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.scope_id == candidate_scope_id).where(agent_sessions.c.session_anchor == candidate_anchor)# Never resolve a turn onto an archived row. The archived row's@@ -327,8 +341,13 @@ def resolve_agent_run_target(select(agent_sessions,scopes.c.scope_type.label("_scope_type"),+ scope_settings.c.workdir.label("_scope_workdir"),+ )+ .select_from(+ agent_sessions+ .outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)+ .outerjoin(scope_settings, scope_settings.c.scope_id == agent_sessions.c.scope_id))- .select_from(agent_sessions.outerjoin(scopes, scopes.c.id == agent_sessions.c.scope_id)).where(agent_sessions.c.id == new_session_id)).mappings().one()return _cache_target(@@ -372,6 +391,7 @@ def _cached_target(session_anchor=str(cached.get("session_anchor") or base_session_id or ""),workdir=workdir,source=str(cached.get("source") or source),+ project_base=_project_base_for_workdir(workdir, cached.get("project_base")),scope_id=_optional_str(cached.get("scope_id")),scope_type=_optional_str(cached.get("scope_type")),agent_session_id=_optional_str(cached.get("agent_session_id")),@@ -698,6 +718,7 @@ def _target_from_session_row(session_anchor=str(row.get("session_anchor") or fallback_anchor),workdir=workdir,source=source,+ project_base=_session_project_base(row, workdir),scope_id=_optional_str(row.get("scope_id")),scope_type=_optional_str(row.get("_scope_type")),agent_session_id=_optional_str(row.get("id")),@@ -740,6 +761,10 @@ def _unpersisted_target(session_anchor=anchor,workdir=resolved_workdir,source=source,+ project_base=_project_base_for_workdir(+ resolved_workdir,+ scope_row.get("workdir") if scope_row else None,+ ),scope_id=_optional_str(scope_row.get("scope_id")) if scope_row else None,scope_type=_optional_str(scope_row.get("scope_type")) if scope_row else None,agent_id=agent_target.agent_id if agent_target else None,@@ -758,6 +783,22 @@ def _normalize_workdir(value: Any) -> Optional[str]:return os.path.abspath(os.path.expanduser(text))+def _project_base_for_workdir(workdir: str, candidate: Any) -> Optional[str]:+ return normalize_session_project_base(workdir, candidate)+++def _session_project_base(row: dict[str, Any], workdir: str) -> Optional[str]:+ try:+ metadata = json.loads(str(row.get("metadata_json") or "{}"))+ except (TypeError, ValueError):+ metadata = {}+ stored = metadata.get(SESSION_PROJECT_BASE_METADATA_KEY) if isinstance(metadata, dict) else None+ return _project_base_for_workdir(workdir, stored) or _project_base_for_workdir(+ workdir,+ row.get("_scope_workdir"),+ )++def _resolve_workdir(candidate: Optional[str],*,diff --git a/core/services/skills.py b/core/services/skills.pyindex 6b5243b45..59721d42d 100644--- a/core/services/skills.py+++ b/core/services/skills.py@@ -1,10 +1,10 @@"""Business API for Agent Skills — a thin shell over the ``askill`` CLI.Wraps ``askill <cmd> --json`` (github.com/avibe-bot/askill, v0.1.13+) so the-Web UI can manage global + project skills across backends without owning-install logic. The CLI is the source of truth; this layer maps avibe-concepts onto askill's flags, runs the binary, and parses the documented-``--json`` contract into plain dicts.+Web UI can manage one global or project Skill installation shared by every+backend without owning install logic. The CLI is the source of truth; this+layer maps Avibe concepts onto askill's flags, runs the binary, and parses the+documented ``--json`` contract into plain dicts.Layering (per ``docs/plans/workbench-dispatch-architecture.md`` §6, and thebuild plan in ``docs/plans/workbench-skills-page.md``):@@ -30,7 +30,7 @@ import jsonimport loggingimport osimport re-from typing import Any, Optional+from typing import Any, Optional, Sequencelogger = logging.getLogger(__name__)@@ -378,11 +378,14 @@ def _filter_skill_listing(if not result.get("ok") or not isinstance(result.get("skills"), list):return resultcontext = resolve_resource_access_context(user_context)- if _project_role_allows_editor(context, project_id):+ project_editor = _project_role_allows_editor(context, project_id)+ instance_editor = context.has_role("editor")+ if (project_editor and instance_editor) or (project_editor and scope == "project") or (+ instance_editor and scope == "global"+ ):return resultraw_skills = [dict(skill) for skill in result["skills"] if isinstance(skill, dict)]- instance_editor = context.has_role("editor")descriptors = _skill_resource_descriptors(raw_skills,requested_scope=scope,@@ -390,9 +393,8 @@ def _filter_skill_listing(project_id=project_id,backends=backends,)- if not descriptors:- filtered_skills: list[dict[str, Any]] = []- else:+ allowed: set[tuple[int, int | None]] = set()+ if descriptors:from storage import resource_access_servicefrom storage.db import get_cached_sqlite_engine@@ -405,24 +407,30 @@ def _filter_skill_listing(connection=connection,)allowed = {(item["skill_index"], item["agent_index"]) for item in accessible}- filtered_skills = []- for skill_index, skill in enumerate(raw_skills):- if instance_editor and _skill_scope(skill, scope) == "global":- filtered_skills.append(skill)- continue- matching = [item for item in descriptors if item["skill_index"] == skill_index]- if not matching or not any((item["skill_index"], item["agent_index"]) in allowed for item in matching):++ filtered_skills: list[dict[str, Any]] = []+ for skill_index, skill in enumerate(raw_skills):+ skill_scope = _skill_scope(skill, scope)+ if (project_editor and skill_scope == "project") or (+ instance_editor and skill_scope == "global"+ ):+ filtered_skills.append(skill)+ continue+ matching = [item for item in descriptors if item["skill_index"] == skill_index]+ if not matching or not any(+ (item["skill_index"], item["agent_index"]) in allowed for item in matching+ ):+ continue+ raw_agents = skill.get("agents")+ if isinstance(raw_agents, list):+ skill["agents"] = [+ agent+ for agent_index, agent in enumerate(raw_agents)+ if (skill_index, agent_index) in allowed+ ]+ if not skill["agents"]:continue- raw_agents = skill.get("agents")- if isinstance(raw_agents, list):- skill["agents"] = [- agent- for agent_index, agent in enumerate(raw_agents)- if (skill_index, agent_index) in allowed- ]- if not skill["agents"]:- continue- filtered_skills.append(_remote_safe_skill_payload(skill))+ filtered_skills.append(_remote_safe_skill_payload(skill))filtered = dict(result)filtered["skills"] = filtered_skills@@ -528,19 +536,24 @@ def _require_skill_management_access(returnengine = get_cached_sqlite_engine()with engine.connect() as connection:+ found_policy = Falsefor resource_id in resource_ids:policy = resource_access_service.get_resource_policy("skill", resource_id, connection=connection)if policy is None:- if allow_missing_policy or context.is_instance_owner:- continue- raise SkillAccessError()- if not resource_access_service.can_manage_resource_acl(+ continue+ found_policy = True+ if resource_access_service.can_manage_resource_acl(context,"skill",resource_id,connection=connection,):- raise SkillAccessError()+ # Backend ids are legacy aliases for one logical Skill. Any+ # manageable alias grants the same unified operation.+ return+ if not found_policy and (allow_missing_policy or context.is_instance_owner):+ return+ raise SkillAccessError()def _require_skill_create_access(user_context: Any) -> None:@@ -624,32 +637,6 @@ def _skill_names_from_payload(payload: dict[str, Any]) -> list[str]:return list(dict.fromkeys(name for name in names if name.strip()))-def _result_backends(result: dict[str, Any], fallback: Optional[list[str]]) -> list[str]:- for key in ("selectedAgents", "agents", "removedAgents"):- raw_agents = result.get(key)- if not isinstance(raw_agents, list):- continue- resolved = [backend for agent in raw_agents if (backend := _backend_from_agent_ref(agent)) is not None]- if resolved:- return list(dict.fromkeys(resolved))- return _normalized_backends(fallback) or list(BACKEND_TO_AGENT)---def _removed_backends(result: dict[str, Any], fallback: Optional[list[str]]) -> list[str]:- if "removedAgents" in result:- raw_agents = result.get("removedAgents")- if not isinstance(raw_agents, list):- return []- return list(- dict.fromkeys(- backend- for agent in raw_agents- if (backend := _backend_from_agent_ref(agent)) is not None- )- )- return _normalized_backends(fallback) or list(BACKEND_TO_AGENT)--def _register_created_skill_policies(names: list[str],*,@@ -791,14 +778,15 @@ async def list_skills("""context = resolve_resource_access_context(user_context)_require_skill_use_access(context, scope=scope, project_dir=project_dir)- args = ["list", *_list_scope_flag(scope), *_agent_flags(backends)]+ _agent_flags(backends) # Retained request field: validate, then apply unified semantics.+ args = ["list", *_list_scope_flag(scope)]result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))return _filter_skill_listing(result,scope=scope,project_dir=project_dir,project_id=project_id,- backends=backends,+ backends=None,user_context=context,)@@ -841,7 +829,7 @@ async def add_skill() -> dict[str, Any]:"""Install skill(s) from a source. Non-interactive (``-y``).- ``askill add <source> [-g] [-a <agent>...] [--all|--skill <name>] [--copy] -y``.+ ``askill add <source> [-g] -a claude-code opencode codex [--all|--skill <name>] [--copy] -y``.``skill`` installs one named skill from a multi-skill source (use this forlocal dirs, where ``source@name`` is ambiguous); ``all_skills`` installsevery discovered skill. ``scope`` must be ``global`` or ``project``.@@ -850,6 +838,7 @@ async def add_skill(raise SkillsError("missing_source", "no source provided")if scope not in ("global", "project"):raise SkillsError("invalid_scope", "install scope must be global or project")+ _agent_flags(backends) # Backward-compatible input validation; selection is intentionally ignored.context = resolve_resource_access_context(user_context)if scope == "project":require_project_editor_access(context, project_id)@@ -872,14 +861,14 @@ async def add_skill(scope=scope,project_dir=project_dir,project_id=project_id,- backends=backends,+ backends=None,),user_context=context,allow_missing_policy=True,)listing = await _run_askill(askill_path,- ["list", *_list_scope_flag(scope), *_agent_flags(backends)],+ ["list", *_list_scope_flag(scope)],cwd=_cwd_for(scope, project_dir),)for target_name in target_names:@@ -889,7 +878,7 @@ async def add_skill(scope=scope,project_dir=project_dir,project_id=project_id,- backends=backends,+ backends=None,)if installed_resource_ids:_require_skill_management_access(@@ -897,7 +886,12 @@ async def add_skill(user_context=context,allow_missing_policy=False,)- args = ["add", source, *_target_scope_flag(scope), *_agent_flags(backends)]+ args = [+ "add",+ source,+ *_target_scope_flag(scope),+ *_agent_flags(list(BACKEND_TO_AGENT)),+ ]if skill:args += ["--skill", skill]if all_skills:@@ -935,7 +929,7 @@ async def add_skill(scope=scope,project_dir=project_dir,project_id=project_id,- backends=_result_backends(result, backends),+ backends=list(BACKEND_TO_AGENT),user_context=context,)return result@@ -951,14 +945,15 @@ async def remove_skill(backends: Optional[list[str]] = None,user_context: Any = None,) -> dict[str, Any]:- """Remove an installed skill, optionally from specific backends only.+ """Remove one logical Skill installation from every managed backend link.- Maps to ``askill remove <name> [-g] [-a <agent>...]``.+ The optional legacy ``backends`` field is validated but no longer narrows removal."""if not name:raise SkillsError("missing_skill", "no skill name provided")if scope not in ("global", "project"):raise SkillsError("invalid_scope", "remove scope must be global or project")+ _agent_flags(backends)context = resolve_resource_access_context(user_context)if scope == "project":require_project_editor_access(context, project_id)@@ -973,24 +968,28 @@ async def remove_skill(scope=scope,project_dir=project_dir,project_id=project_id,- backends=backends,+ backends=None,)_require_skill_management_access(resource_ids,user_context=context,allow_missing_policy=False,)- args = ["remove", name, *_target_scope_flag(scope), *_agent_flags(backends)]+ args = [+ "remove",+ name,+ *_target_scope_flag(scope),+ *_agent_flags(list(BACKEND_TO_AGENT)),+ ]result = await _run_askill(askill_path, args, cwd=_cwd_for(scope, project_dir))if result.get("ok"):- removed_backends = _removed_backends(result, backends)_delete_skill_policies(_resource_ids_for_skill_name(name,scope=scope,project_dir=project_dir,project_id=project_id,- backends=removed_backends,+ backends=None,))return resultdiff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 33e6a8027..317123731 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -738,6 +738,9 @@ def build_system_prompt_injection(fallback_platform: Optional[str] = None,enabled_agents: Optional[Iterable[Any]] = None,current_agent_backend: Optional[str] = None,+ skills_cwd: str | Path | None = None,+ skills_project_base: str | Path | None = None,+ skills_claude_cli_path: str | None = None,) -> str:"""Build avibe system prompt additions for an agent backend."""@@ -769,6 +772,16 @@ def build_system_prompt_injection()if include_memory_cli:prompt += _MEMORY_CLI_PROMPT+ if skills_cwd is not None:+ from core.managed_skills import render_skill_catalog_prompt, resolve_skills++ prompt += render_skill_catalog_prompt(+ resolve_skills(+ skills_cwd,+ project_base=skills_project_base,+ claude_cli_path=skills_claude_cli_path,+ )+ )if context is not None:prompt += _build_session_end_prompt(context, fallback_platform=fallback_platform)return promptdiff --git a/docs/CLI.md b/docs/CLI.mdindex 73eea89db..6a9404c9d 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -119,6 +119,47 @@ vibe status}```+### `vibe skill`++Avibe gives Claude, Codex, and OpenCode one managed Skill catalog and suppresses+their native Skill catalogs on Avibe-dispatched Turns.++```bash+vibe skill list [--page N]+vibe skill load -- <name>+```++`list` prints the currently available names and descriptions in stable order,+25 per page. Page 1 is also included in the Agent's system prompt; use the+next-page command shown in the output when more Skills are available. `load`+prints only the selected Skill body inside a `skill_content` element. Its+`directory` attribute is an absolute path so the Agent can read references and+run scripts stored beside `SKILL.md`.++Avibe discovers existing Skills without moving them:++- project Skills under `.agents/skills`, `.codex/skills`, `.claude/skills`, or+ `.opencode/skills`, from the working directory up to the Session's bound Avibe+ project base. This boundary can sit above a nested Git checkout. Standalone+ commands without a bound project use the first Git root instead;+- global Skills under `~/.agents/skills`, the configured Codex and Claude Skill+ directories, the OpenCode directory under `XDG_CONFIG_HOME`, and enabled+ Claude plugin Skill directories; and+- Avibe built-ins plus Codex's bundled system Skills.++Built-ins win name conflicts, then project Skills, then global Skills. Within a+project the nearer directory wins; at the same depth the order is `.agents`,+`.codex`, `.claude`, then `.opencode`. User Skills win over Codex bundled+defaults; enabled Claude plugin Skills follow the four static user directories+but also win over those defaults. New global installs should use+`~/.agents/skills/<name>`; project installs should use+`<project>/.agents/skills/<name>`.++Every command resolves from disk, and every new Avibe-dispatched Turn rebuilds+the Catalog. Adding, editing, or deleting a Skill is therefore visible in an+existing Session without restarting Avibe or creating a new Session. Existing+conversation history is not rewritten.+### `vibe memory`Read scoped local Memory or submit context for best-effort, process-local capture — facts the user explicitly asked to remember, and conclusions the Agent distills on its own from the conversation and from work on this machine, including lasting environment or account facts it meets in files or tool output — through the existing mode-0600 controller socket. Acceptance does not guarantee provider delivery or persistence. This command does not start a service and has no clear, configuration, export, or delete subcommands.diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex c9ce8b3f6..5bb26d812 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -100,6 +100,40 @@ vibe status}```+### `vibe skill`++Avibe 为 Claude、Codex 和 OpenCode 提供统一的托管 Skill Catalog,并在由 Avibe+发起的 Turn 中关闭各 backend 自带的 Skill Catalog。++```bash+vibe skill list [--page N]+vibe skill load -- <name>+```++`list` 按稳定顺序输出当前可用的名称和描述,每页最多 25 个。第 1 页也会注入+Agent 的 system prompt;如有更多 Skill,按输出中的命令查看下一页。`load` 只在+`skill_content` 标签中输出所选 Skill 的正文。标签的 `directory` 属性是绝对路径,+Agent 可以据此读取 `SKILL.md` 同目录下的 reference 或运行 script。++Avibe 会直接发现现有 Skill,无需迁移:++- 项目级:从工作目录到 Session 绑定的 Avibe 项目根目录逐层查找 `.agents/skills`、+ `.codex/skills`、`.claude/skills` 和 `.opencode/skills`。该边界可以位于嵌套 Git+ 仓库之上;未绑定项目的独立命令则以遇到的第一个 Git 根目录为边界;+- 全局:查找 `~/.agents/skills`、Codex 与 Claude 配置的 Skill 目录,以及+ `XDG_CONFIG_HOME` 下的 OpenCode 目录和已启用的 Claude 插件 Skill 目录;+- Avibe 内置 Skill,以及 Codex 自带的 system Skill。++同名冲突时,内置 Skill 优先,其次是项目级,再次是全局。项目内更近的目录优先;+同一层级依次为 `.agents`、`.codex`、`.claude`、`.opencode`。用户 Skill 优先于+Codex 自带的默认项;已启用的 Claude 插件 Skill 排在四个静态用户目录之后,但同样+优先于这些默认项。新的全局 Skill 默认安装到 `~/.agents/skills/<name>`,项目级 Skill+安装到 `<project>/.agents/skills/<name>`。++每次命令都会从磁盘重新解析,每个由 Avibe 发起的新 Turn 也会重新生成 Catalog。+因此新增、修改或删除 Skill 后,已有 Session 无需重启 Avibe,也无需新建 Session;+历史对话内容不会被重写。+### `vibe memory`通过现有 mode-0600 控制器 socket 读取当前范围内的本地记忆,或提交内容进行尽力而为的进程内捕获——既包括用户明确要求记住的内容,也包括 Agent 从对话以及在本机工作中主动提炼的结论(含在文件或工具输出中遇到的持久环境、账户事实)。接受请求不保证提供方投递或持久化。该命令不会启动服务,也没有清空、配置、导出或删除子命令。diff --git a/main.py b/main.pyindex 0b2422acf..c9e19d497 100644--- a/main.py+++ b/main.py@@ -159,6 +159,14 @@ def main():setup_logging(config.runtime.log_level)logger = logging.getLogger(__name__)+ from core.managed_skills import BUILTIN_SKILLS_SNAPSHOT_ENV, prepare_builtin_skills++ try:+ prepare_builtin_skills()+ except Exception:+ os.environ[BUILTIN_SKILLS_SNAPSHOT_ENV] = ""+ logger.warning("Avibe built-in Skills are unavailable", exc_info=True)+apply_claude_sdk_patches()from vibe.sentry_integration import init_sentrydiff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 850a62ff1..462f80877 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -19,6 +19,11 @@ from core.avibe_cloud import avibe_cloud_url_availablefrom core.backend_failure import emit_backend_failurefrom core.caller_context import caller_env_for_platform_payloadfrom core.message_output import stop_output_for, terminal_output_for+from core.managed_skills import (+ managed_skill_claude_cli_path,+ managed_skill_environment,+ managed_skill_project_base,+)from core.native_dispatch_phase import mark_backend_dispatch_attemptedfrom core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.services.agent_steering import (@@ -1812,7 +1817,7 @@ class CodexAgent(BaseAgent):# this turn's shell needs in order to record where it came from. This env is# the only hop it can travel: the CLI runs as a subprocess of the Codex shell.context = getattr(request, "context", None)- return caller_env_for_platform_payload(+ env = caller_env_for_platform_payload(getattr(context, "platform_specific", None),message=context,# Defensively resolved: this is reached from payload-shaping helpers that@@ -1822,6 +1827,16 @@ class CodexAgent(BaseAgent):getattr(getattr(self, "controller", None), "config", None), "platform", None),)+ env.update(+ managed_skill_environment(+ getattr(request, "working_path", None),+ project_base=managed_skill_project_base(context),+ claude_cli_path=managed_skill_claude_cli_path(+ getattr(getattr(self, "controller", None), "config", None)+ ),+ )+ )+ return envdef _caller_env_script_path(self, request: AgentRequest) -> Path:caller_env = self._caller_env_for_request(request)@@ -1861,6 +1876,8 @@ class CodexAgent(BaseAgent):env = self._caller_env_for_request(request)config = dict(params.get("config") or {})+ config["skills.include_instructions"] = False+ params["config"] = configshell_policy = dict(config.get("shell_environment_policy") or {})set_env = dict(shell_policy.get("set") or {})had_path = "PATH" in set_env@@ -1906,7 +1923,7 @@ class CodexAgent(BaseAgent):"sandbox": "danger-full-access",}self.ensure_agent_session_id(request)- developer_instructions = self._build_thread_developer_instructions(request)+ developer_instructions = await self._build_thread_developer_instructions(request)if developer_instructions:params["developerInstructions"] = developer_instructionsgit_path_state, git_path_managed = self._inject_caller_env_config(params, request)@@ -1954,7 +1971,7 @@ class CodexAgent(BaseAgent):"approvalPolicy": "never","sandbox": "danger-full-access",}- developer_instructions = self._build_thread_developer_instructions(request)+ developer_instructions = await self._build_thread_developer_instructions(request)if developer_instructions:params["developerInstructions"] = developer_instructionsif effective_model:@@ -2132,9 +2149,10 @@ class CodexAgent(BaseAgent):if persisted:try:self.bind_agent_session_id(request, persisted)+ developer_instructions = await self._build_thread_developer_instructions(request)resume_params: Dict[str, Any] = {"threadId": persisted,- "developerInstructions": self._build_thread_developer_instructions(request),+ "developerInstructions": developer_instructions,}git_path_state, git_path_managed = self._inject_caller_env_config(resume_params,@@ -2289,7 +2307,7 @@ class CodexAgent(BaseAgent):# created under the ephemeral Hub provider can resume in Direct mode.return _CODEX_DEFAULT_PROVIDER_ID- def _build_thread_developer_instructions(self, request: AgentRequest) -> Optional[str]:+ async def _build_thread_developer_instructions(self, request: AgentRequest) -> Optional[str]:"""Build Codex thread-level developer instructions for start/resume.Codex treats these as session configuration, not appended chat history.@@ -2313,7 +2331,8 @@ class CodexAgent(BaseAgent):memory_cli_admitted = memory_cli_prompt_admitted(self.controller, request.context)instruction_parts.append(- build_system_prompt_injection(+ await asyncio.to_thread(+ build_system_prompt_injection,include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)and platform != "wechat",include_show_pages=getattr(self.controller.config, "show_pages_prompt", True),@@ -2324,6 +2343,11 @@ class CodexAgent(BaseAgent):fallback_platform=platform,enabled_agents=get_enabled_agents_for_prompt(self.controller),current_agent_backend="codex",+ skills_cwd=getattr(request, "working_path", None),+ skills_project_base=managed_skill_project_base(request.context),+ skills_claude_cli_path=managed_skill_claude_cli_path(+ getattr(getattr(self, "controller", None), "config", None)+ ),))@@ -2367,7 +2391,7 @@ class CodexAgent(BaseAgent):) -> None:"""Refresh thread-level instructions for already-cached Codex threads."""self.ensure_agent_session_id(request)- developer_instructions = self._build_thread_developer_instructions(request)+ developer_instructions = await self._build_thread_developer_instructions(request)# Building the instructions also grants/revokes the per-turn Memory CLI# capability, so resolve the caller environment only after that decision.caller_env = self._caller_env_for_request(request)diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 92ff82e7c..aa8ec8943 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -11,6 +11,7 @@ from __future__ import annotationsimport asyncioimport loggingimport os+import secretsimport timefrom dataclasses import dataclass, fieldfrom typing import Any, Dict, Optional@@ -19,7 +20,22 @@ import aiohttpfrom core.avibe_cloud import avibe_cloud_url_availablefrom core.backend_failure import emit_backend_failure+from core.caller_context import (+ AVIBE_CALLER_PLATFORM_ENV,+ AVIBE_CALLER_REMOTE_ENV,+ AVIBE_CALLER_USER_ID_ENV,+ AVIBE_SESSION_ID_ENV,+ caller_env_for_platform_payload,+ validated_caller_env_snapshot,+)from core.message_output import stop_output_for, terminal_output_for+from core.managed_skills import (+ BUILTIN_SKILLS_ROOT_ENV,+ BUILTIN_SKILLS_SNAPSHOT_ENV,+ managed_skill_claude_cli_path,+ managed_skill_environment,+ managed_skill_project_base,+)from core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.native_dispatch_phase import (mark_backend_dispatch_attempted,@@ -59,11 +75,16 @@ from modules.agents.model_hub import ()from vibe.i18n import t as i18n_t-from .caller_context import bind_session as bind_caller_context_session+from .caller_context import (+ bind_session as bind_caller_context_session,+ refresh_session as refresh_caller_context_session,+ unbind_session as unbind_caller_context_session,+)from .client_manager import OpenCodeClientManagerfrom .message_processor import OpenCodeMessageProcessorMixinfrom .poll_loop import (OpenCodePollLoop,+ restored_context_from_poll_info,restored_platform_from_poll_info,restored_session_key_from_poll_info,)@@ -82,6 +103,9 @@ from .utils import resolve_opencode_model_id, resolve_opencode_reasoning_effortlogger = logging.getLogger(__name__)_STEERING_SNAPSHOT_KEY = "opencode_native_steering"_MODEL_HUB_DISPLAY_MODEL_KEY = "model_hub_display_model"+_CALLER_CONTEXT_ENV_SNAPSHOT_KEY = "opencode_caller_context_env"+_MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY = "opencode_managed_skill_project_base"+_MANAGED_SKILL_BUILTIN_SNAPSHOT_KEY = "opencode_managed_skill_builtin_snapshot"_STATUS_RECONCILIATION_FAILURE_LIMIT = 3# OpenCode returns 204 after forking prompt work, before that worker necessarily# registers the session as busy.@@ -95,6 +119,23 @@ _ASYNC_PROMPT_RESULT_CONFIRMATION_TIMEOUT_SECONDS = 5.0_STEER_POST_WRITE_STATUS_SETTLE_SECONDS = 0.1_RESTORED_IM_REGISTRATION_RETRY_DELAY_SECONDS = 0.25_RESTORED_IM_PLATFORMS = {"slack", "discord", "telegram", "lark", "wechat"}+_CALLER_CONTEXT_BINDING_REFRESH_SECONDS = 60 * 60+_CALLER_CONTEXT_BINDING_RETRY_SECONDS = 1.0+++def _caller_context_path_for_server(server: object) -> str | None:+ resolver = getattr(server, "caller_context_binding_path", None)+ if not callable(resolver):+ return None+ try:+ value = os.fspath(resolver())+ except (TypeError, OSError):+ return None+ return value or None+++def _binding_path_kwargs(path: str | None) -> dict[str, str]:+ return {"path": path} if path else {}def _task_is_stopping(task: asyncio.Task) -> bool:@@ -692,6 +733,99 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self._attach_server_activation(server)return server+ async def _maintain_caller_context_binding(+ self,+ session_id: str,+ binding_token: str,+ binding_path: str | None,+ *,+ payload: dict[str, Any] | None,+ working_directory: str,+ extra_env: dict[str, str],+ initially_bound: bool,+ message: Any = None,+ fallback_platform: str | None = None,+ ) -> None:+ """Keep one Turn binding published and renewed for its full lifetime."""++ bound = initially_bound+ while True:+ await asyncio.sleep(+ _CALLER_CONTEXT_BINDING_REFRESH_SECONDS+ if bound+ else _CALLER_CONTEXT_BINDING_RETRY_SECONDS+ )+ if bound:+ try:+ refreshed = bool(+ await asyncio.to_thread(+ refresh_caller_context_session,+ session_id,+ binding_token=binding_token,+ **_binding_path_kwargs(binding_path),+ )+ )+ except Exception:+ logger.warning(+ "Failed to renew OpenCode caller context for session %s",+ session_id,+ exc_info=True,+ )+ bound = False+ else:+ if not refreshed:+ return+ bound = True+ continue+ try:+ bound = bool(+ await asyncio.to_thread(+ bind_caller_context_session,+ session_id,+ payload,+ base_env=os.environ,+ working_dir=working_directory,+ extra_env=extra_env,+ binding_token=binding_token,+ replace_existing=False,+ **_binding_path_kwargs(binding_path),+ message=message,+ fallback_platform=fallback_platform,+ )+ )+ if not bound:+ return+ except Exception:+ logger.warning(+ "Failed to republish OpenCode caller context for session %s",+ session_id,+ exc_info=True,+ )+ bound = False++ @staticmethod+ async def _stop_caller_context_binding_renewal(+ task: asyncio.Task[None] | None,+ ) -> None:+ if task is None:+ return+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ def _active_poll_is_persisted(self, session_id: str) -> bool:+ try:+ return session_id in self.sessions.get_all_active_polls()+ except Exception:+ logger.warning(+ "Could not verify OpenCode active poll retention for session %s",+ session_id,+ exc_info=True,+ )+ return True+@staticmethoddef _server_activation_identity(server: OpenCodeServerManager | None,@@ -1013,6 +1147,17 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):start_attempt_id = ""native_start_phase = "before_write"activation_identity: RuntimeActivationIdentity | None = None+ caller_context_binding_session_id: str | None = None+ caller_context_binding_token: str | None = None+ caller_context_binding_path: str | None = None+ caller_context_binding_renewal: asyncio.Task[None] | None = None+ active_poll_persisted = False++ def remove_active_poll() -> None:+ nonlocal active_poll_persisted+ if session_id:+ self.sessions.remove_active_poll(session_id)+ active_poll_persisted = Falsetry:model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)turn_mode = getattr(model_hub_runtime, "turn_mode", None)@@ -1031,6 +1176,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):model_hub_overlay)await server.ensure_running()+ caller_context_binding_path = _caller_context_path_for_server(server)activation_identity = self._attach_server_activation(server)except asyncio.CancelledError:await self._finish_prestart_cancellation(@@ -1293,27 +1439,33 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# CLI session scope as a side effect, so a second call per turn would# repeat that write.memory_cli_admitted = memory_cli_prompt_admitted(self.controller, request.context)-- system_prompt_injection = build_system_prompt_injection(- include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)- and platform != "wechat",- include_show_pages=getattr(self.controller.config, "show_pages_prompt", True),- include_memory_cli=memory_cli_admitted,- avibe_cloud_connected=avibe_cloud_url_available(self.controller.config),- context=request.context,+ caller_context_env = caller_env_for_platform_payload(+ request.context.platform_specific or {},+ message=request.context,fallback_platform=platform,- enabled_agents=get_enabled_agents_for_prompt(self.controller),- current_agent_backend="opencode",)- if request.vibe_agent_system_prompt:- system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"+ project_base = managed_skill_project_base(request.context)+ managed_skills_env = managed_skill_environment(+ request.working_path,+ project_base=project_base,+ claude_cli_path=managed_skill_claude_cli_path(+ getattr(getattr(self, "controller", None), "config", None)+ ),+ )+ binding_token = secrets.token_hex(16)+ binding_payload = request.context.platform_specific or {}+ binding_bound = Falsetry:- bind_caller_context_session(+ binding_bound = await asyncio.to_thread(+ bind_caller_context_session,session_id,- request.context.platform_specific or {},+ binding_payload,base_env=os.environ,working_dir=request.working_path,+ extra_env=managed_skills_env,+ binding_token=binding_token,+ **_binding_path_kwargs(caller_context_binding_path),# The creation origin travels with the identity: an OpenCode shell# command running ``vibe task add`` sources this binding, and it is# the only place the conversation behind the definition is visible.@@ -1321,7 +1473,46 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):fallback_platform=platform,)except Exception:- logger.warning("Failed to bind OpenCode caller context for session %s", session_id, exc_info=True)+ logger.warning(+ "Starting OpenCode turn without caller context for session %s",+ session_id,+ exc_info=True,+ )+ caller_context_binding_session_id = session_id+ caller_context_binding_token = binding_token+ caller_context_binding_renewal = asyncio.create_task(+ self._maintain_caller_context_binding(+ session_id,+ binding_token,+ caller_context_binding_path,+ payload=binding_payload,+ working_directory=request.working_path,+ extra_env=managed_skills_env,+ initially_bound=bool(binding_bound),+ message=request.context,+ fallback_platform=platform,+ )+ )++ system_prompt_injection = await asyncio.to_thread(+ build_system_prompt_injection,+ include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)+ and platform != "wechat",+ include_show_pages=getattr(self.controller.config, "show_pages_prompt", True),+ include_memory_cli=memory_cli_admitted,+ avibe_cloud_connected=avibe_cloud_url_available(self.controller.config),+ context=request.context,+ fallback_platform=platform,+ enabled_agents=get_enabled_agents_for_prompt(self.controller),+ current_agent_backend="opencode",+ skills_cwd=request.working_path if binding_bound else None,+ skills_project_base=project_base,+ skills_claude_cli_path=managed_skill_claude_cli_path(+ getattr(getattr(self, "controller", None), "config", None)+ ),+ )+ if request.vibe_agent_system_prompt:+ system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"raw_settings_key = _raw_settings_key_from_session_key(request.session_key)platform_payload = request.context.platform_specific or {}@@ -1332,6 +1523,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):processing_indicator = self.controller.processing_indicator.snapshot_request(request)+ if caller_context_env:+ processing_indicator[_CALLER_CONTEXT_ENV_SNAPSHOT_KEY] = 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],+ "root": managed_skills_env[BUILTIN_SKILLS_ROOT_ENV],+ }target_session_id = _target_agent_session_id(request)if target_session_id and logical_turn_id:processing_indicator[_STEERING_SNAPSHOT_KEY] = {@@ -1380,6 +1580,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):reasoning_effort=reasoning_effort,session_key=request.session_key,)+ active_poll_persisted = Truemark_backend_dispatch_attempted(request.context)native_start_phase = "may_have_written"await server.prompt_async(@@ -1391,7 +1592,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):model=model_dict,reasoning_effort=reasoning_effort,system=system_prompt_injection,- tools={"question": False},+ tools={"question": False, "skill": False},)try:read_prompt_started_at = getattr(server, "get_last_prompt_started_at", None)@@ -1474,7 +1675,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)if not should_emit:- self.sessions.remove_active_poll(session_id)+ remove_active_poll()await self._remove_ack_reaction(request)return@@ -1497,7 +1698,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)self._maybe_backfill_session_title(request, session_id, retry_delay_seconds=3.0)- self.sessions.remove_active_poll(session_id)+ remove_active_poll()except asyncio.CancelledError:logger.info(f"OpenCode request cancelled for {request.base_session_id}")@@ -1514,7 +1715,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):),)if session_id:- self.sessions.remove_active_poll(session_id)+ remove_active_poll()raiseexcept OpenCodePromptRejectedError as e:error_text = f"{type(e).__name__}: {e}"@@ -1561,7 +1762,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._remove_ack_reaction(request)if session_id and poll_can_be_removed:- self.sessions.remove_active_poll(session_id)+ remove_active_poll()await self.record_model_hub_native_failure(request.context, error_text)await emit_backend_failure(@@ -1587,7 +1788,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._remove_ack_reaction(request)if session_id and native_start_phase != "may_have_written":- self.sessions.remove_active_poll(session_id)+ remove_active_poll()elif session_id:logger.warning("Preserving OpenCode active poll after ambiguous native start "@@ -1606,6 +1807,27 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request=request,)finally:+ await self._stop_caller_context_binding_renewal(+ caller_context_binding_renewal+ )+ if (+ caller_context_binding_session_id+ and caller_context_binding_token+ and not active_poll_persisted+ ):+ try:+ await asyncio.to_thread(+ unbind_caller_context_session,+ caller_context_binding_session_id,+ binding_token=caller_context_binding_token,+ **_binding_path_kwargs(caller_context_binding_path),+ )+ except Exception:+ logger.warning(+ "Failed to unbind OpenCode caller context for session %s",+ caller_context_binding_session_id,+ exc_info=True,+ )if steer_state is not None:async with steer_state.lock:steer_state.closing = True@@ -1762,7 +1984,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):"model": state.model,"reasoning_effort": state.reasoning_effort,"system": state.system,- "tools": {"question": False},+ "tools": {"question": False, "skill": False},}if request.attempt_id:prompt_kwargs["attempt_id"] = request.attempt_id@@ -2272,6 +2494,94 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):f"(thread={poll_info.base_session_id}, cwd={poll_info.working_path})")+ restored_binding_token = secrets.token_hex(16)+ restored_binding_path = _caller_context_path_for_server(server)+ restored_caller_env = validated_caller_env_snapshot(+ processing_snapshot.get(_CALLER_CONTEXT_ENV_SNAPSHOT_KEY)+ )+ restored_context = restored_context_from_poll_info(poll_info)+ if (+ poll_platform == "avibe"+ and str(restored_context.user_id or "").startswith("remote:")+ ):+ # Legacy persisted polls do not carry the authorization snapshot.+ # Keep them remote-but-unprivileged instead of silently treating an+ # absent snapshot as a local caller.+ restored_caller_env.setdefault(AVIBE_SESSION_ID_ENV, poll_info.base_session_id)+ restored_caller_env.setdefault(AVIBE_CALLER_PLATFORM_ENV, "avibe")+ restored_caller_env.setdefault(+ AVIBE_CALLER_USER_ID_ENV,+ str(restored_context.user_id),+ )+ restored_caller_env.setdefault(AVIBE_CALLER_REMOTE_ENV, "1")+ restored_project_base = processing_snapshot.get(+ _MANAGED_SKILL_PROJECT_BASE_SNAPSHOT_KEY+ )+ restored_project_base = (+ restored_project_base+ if isinstance(restored_project_base, str) and restored_project_base+ else 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_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 ""+ ),+ }+ 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,+ )+ restored_bound = False+ for attempt in range(3):+ try:+ restored_bound = await asyncio.to_thread(+ bind_caller_context_session,+ poll_info.opencode_session_id,+ None,+ base_env=os.environ,+ working_dir=poll_info.working_path,+ extra_env={+ **restored_caller_env,+ **restored_managed_skills_env,+ },+ binding_token=restored_binding_token,+ **_binding_path_kwargs(restored_binding_path),+ )+ except Exception:+ logger.warning(+ "Failed to restore OpenCode caller context for session=%s (attempt %s/3)",+ poll_info.opencode_session_id,+ attempt + 1,+ exc_info=True,+ )+ if restored_bound:+ break+ if attempt < 2:+ await asyncio.sleep(0)+ if not restored_bound:+ logger.error(+ "Restoring OpenCode poll without caller context for session=%s",+ poll_info.opencode_session_id,+ )+restoration_ready = asyncio.get_running_loop().create_future()restoration_published = asyncio.Event()task = asyncio.create_task(@@ -2281,6 +2591,15 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):reconcile_after_message_ids=reconcile_after_message_ids,restoration_ready=restoration_ready,restoration_published=restoration_published,+ caller_context_binding_token=(+ restored_binding_token+ ),+ caller_context_binding_path=restored_binding_path,+ caller_context_binding_extra_env={+ **restored_caller_env,+ **restored_managed_skills_env,+ },+ caller_context_binding_initially_bound=restored_bound,))restoration_results.append(@@ -2339,11 +2658,30 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):reconcile_after_message_ids: set[str] | None = None,restoration_ready: asyncio.Future[bool] | None = None,restoration_published: asyncio.Event | None = None,+ caller_context_binding_token: str | None = None,+ caller_context_binding_path: str | None = None,+ caller_context_binding_extra_env: dict[str, str] | None = None,+ caller_context_binding_initially_bound: bool = False,) -> None:current_task = asyncio.current_task()steer_state = Noneserver = Nonerestoration_registered = False+ caller_context_binding_renewal = (+ asyncio.create_task(+ self._maintain_caller_context_binding(+ poll_info.opencode_session_id,+ caller_context_binding_token,+ caller_context_binding_path,+ payload=None,+ working_directory=poll_info.working_path,+ extra_env=caller_context_binding_extra_env or {},+ initially_bound=caller_context_binding_initially_bound,+ )+ )+ if caller_context_binding_token+ else None+ )try:poll_platform = restored_platform_from_poll_info(poll_info)registration_attempts = 2 if poll_platform in _RESTORED_IM_PLATFORMS else 1@@ -2479,6 +2817,25 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):err,)finally:+ await self._stop_caller_context_binding_renewal(+ caller_context_binding_renewal+ )+ if caller_context_binding_token and not self._active_poll_is_persisted(+ poll_info.opencode_session_id+ ):+ try:+ await asyncio.to_thread(+ unbind_caller_context_session,+ poll_info.opencode_session_id,+ binding_token=caller_context_binding_token,+ **_binding_path_kwargs(caller_context_binding_path),+ )+ except Exception:+ logger.warning(+ "Failed to clear restored OpenCode caller context for session %s",+ poll_info.opencode_session_id,+ exc_info=True,+ )if current_task is not None:self._restored_poll_servers.pop(current_task, None)if steer_state is not None:diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.pyindex a37991021..a71c80aaa 100644--- a/modules/agents/opencode/caller_context.py+++ b/modules/agents/opencode/caller_context.py@@ -13,6 +13,8 @@ from datetime import datetime, timedelta, timezoneimport jsonimport osfrom pathlib import Path+import secrets+import tempfilefrom typing import Any, Mappingfrom config import paths@@ -132,9 +134,28 @@ def _prune_sessions(sessions: dict[str, Any], now: datetime) -> dict[str, Any]:def _write_bindings(path: Path, data: dict[str, Any]) -> None:path.parent.mkdir(parents=True, exist_ok=True)- tmp_path = path.with_suffix(path.suffix + ".tmp")- tmp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")- tmp_path.replace(path)+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)+ tmp_path = Path(tmp_name)+ try:+ fchmod = getattr(os, "fchmod", None)+ if callable(fchmod):+ fchmod(fd, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ fd = -1+ json.dump(data, handle, ensure_ascii=False, indent=2, sort_keys=True)+ handle.flush()+ os.fsync(handle.fileno())+ tmp_path.replace(path)+ finally:+ if fd >= 0:+ os.close(fd)+ tmp_path.unlink(missing_ok=True)+++def _binding_lock(path: Path):+ from storage.lock import MigrationFileLock++ return MigrationFileLock(path.with_suffix(path.suffix + ".lock"))def bind_session(@@ -144,6 +165,10 @@ def bind_session(base_env: Mapping[str, str],working_dir: Path | str | None,ttl_hours: int = BINDING_TTL_HOURS,+ extra_env: Mapping[str, str] | None = None,+ binding_token: str | None = None,+ replace_existing: bool = True,+ path: str | Path | None = None,message: object | None = None,fallback_platform: object | None = None,) -> bool:@@ -166,36 +191,109 @@ def bind_session(fallback_platform=fallback_platform,)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))prepend_vendored_git_to_path(env,base_env=base_env,working_dir=working_dir,)- path = binding_path()+ path = Path(path) if path is not None else binding_path()now = _utc_now()- if not env:+ token = binding_token or secrets.token_hex(16)+ with _binding_lock(path):+ if not env:+ if not path.is_file():+ return False+ data = _load_bindings(path)+ existing_sessions = data.get("sessions", {})+ sessions = _prune_sessions(existing_sessions, now)+ sessions.pop(session_id, None)+ if sessions != existing_sessions:+ data["sessions"] = sessions+ _write_bindings(path, data)+ return False++ data = _load_bindings(path)+ sessions = _prune_sessions(data.get("sessions", {}), now)+ existing = sessions.get(session_id)+ if (+ not replace_existing+ and isinstance(existing, dict)+ and existing.get("binding_token") != token+ ):+ return False+ expires_at = now + timedelta(hours=max(1, int(ttl_hours)))+ entry = {+ "env": env,+ "updated_at": now.isoformat(),+ "expires_at": expires_at.isoformat(),+ "binding_token": token,+ }+ if caller is not None:+ entry["caller_context"] = caller.to_metadata()+ sessions[session_id] = entry+ data["sessions"] = sessions+ _write_bindings(path, data)+ return True+++def unbind_session(+ opencode_session_id: str,+ *,+ binding_token: str,+ path: str | Path | None = None,+) -> bool:+ """Remove exactly the active-Turn binding created by one caller."""++ session_id = str(opencode_session_id or "").strip()+ token = str(binding_token or "").strip()+ if not session_id or not token:+ return False+ path = Path(path) if path is not None else binding_path()+ with _binding_lock(path):if not path.is_file():return Falsedata = _load_bindings(path)- existing_sessions = data.get("sessions", {})- sessions = _prune_sessions(existing_sessions, now)+ sessions = data.get("sessions", {})+ entry = sessions.get(session_id)+ if not isinstance(entry, dict) or entry.get("binding_token") != token:+ return Falsesessions.pop(session_id, None)- if sessions != existing_sessions:- data["sessions"] = sessions- _write_bindings(path, data)- return False+ data["sessions"] = sessions+ _write_bindings(path, data)+ return True+++def refresh_session(+ opencode_session_id: str,+ *,+ binding_token: str,+ ttl_hours: int = BINDING_TTL_HOURS,+ path: str | Path | None = None,+) -> bool:+ """Extend exactly one live binding without changing its environment."""- expires_at = now + timedelta(hours=max(1, int(ttl_hours)))- data = _load_bindings(path)- sessions = _prune_sessions(data.get("sessions", {}), now)- entry = {- "env": env,- "updated_at": now.isoformat(),- "expires_at": expires_at.isoformat(),- }- if caller is not None:- entry["caller_context"] = caller.to_metadata()- sessions[session_id] = entry- data["sessions"] = sessions- _write_bindings(path, data)+ session_id = str(opencode_session_id or "").strip()+ token = str(binding_token or "").strip()+ if not session_id or not token:+ return False+ path = Path(path) if path is not None else binding_path()+ now = _utc_now()+ with _binding_lock(path):+ if not path.is_file():+ return False+ data = _load_bindings(path)+ sessions = _prune_sessions(data.get("sessions", {}), now)+ entry = sessions.get(session_id)+ if not isinstance(entry, dict) or entry.get("binding_token") != token:+ if sessions != data.get("sessions", {}):+ data["sessions"] = sessions+ _write_bindings(path, data)+ return False+ entry["updated_at"] = now.isoformat()+ entry["expires_at"] = (now + timedelta(hours=max(1, int(ttl_hours)))).isoformat()+ sessions[session_id] = entry+ data["sessions"] = sessions+ _write_bindings(path, data)return Truediff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex 149323794..8f79e9a38 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -703,7 +703,7 @@ class OpenCodePollLoop:agent=agent_to_use,model=model_dict,reasoning_effort=reasoning_effort,- tools={"question": False},+ tools={"question": False, "skill": False},awaiting_after_ids={str(_message_info(item).get("id"))for item in messagesdiff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex d64212a40..613869a49 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -309,6 +309,13 @@ class OpenCodeServerManager:def _caller_context_path(self) -> str:return server_environment()["AVIBE_OPENCODE_CALLER_CONTEXT_PATH"]+ def caller_context_binding_path(self) -> Path:+ info = self._read_pid_file()+ recorded = info.get("caller_context_path") if isinstance(info, dict) else None+ if isinstance(recorded, str) and recorded and os.path.isabs(recorded):+ return Path(recorded)+ return Path(self._caller_context_path())+def _get_lock(self) -> asyncio.Lock:"""Get or create an asyncio.Lock bound to the current event loop."""current_loop = asyncio.get_event_loop()@@ -859,7 +866,8 @@ class OpenCodeServerManager:def _pid_file_has_caller_context_binding(self, info: Optional[Dict[str, Any]]) -> bool:if not self._pid_file_references_current_server(info):return False- return bool(isinstance(info, dict) and info.get("caller_context_path") == self._caller_context_path())+ recorded = info.get("caller_context_path") if isinstance(info, dict) else None+ return bool(isinstance(recorded, str) and recorded and os.path.isabs(recorded))def _pid_file_was_started_by_current_process(self, info: Optional[Dict[str, Any]]) -> bool:return bool(isinstance(info, dict) and info.get("owner_pid") == _CURRENT_OWNER_PID)diff --git a/pyproject.toml b/pyproject.tomlindex c98de13cd..eb520bafe 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -117,6 +117,7 @@ exclude = ["vibe/memory_runtime_manifest.json"][tool.hatch.build.targets.wheel.force-include]"main.py" = "vibe/service_main.py""ui/dist" = "vibe/ui/dist"+"skills" = "vibe/builtin_skills_source"[tool.hatch.build.targets.sdist]# Include ui/dist for source distribution@@ -126,6 +127,7 @@ include = ["core/**","modules/**","storage/**",+ "skills/**","hatch_build.py","hatch_exact_peer.py","main.py",@@ -141,6 +143,9 @@ include = []exclude = ["vibe/memory_runtime_manifest.json"]+[tool.hatch.build.targets.sdist.force-include]+"skills" = "skills"+[tool.ruff]line-length = 120src = ["."]diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.pyindex 9991d3adc..25e5c4bc3 100644--- a/storage/agent_session_rows.py+++ b/storage/agent_session_rows.py@@ -5,6 +5,7 @@ import loggingimport osimport secretsfrom datetime import datetime, timezone+from pathlib import Pathfrom typing import Anyfrom sqlalchemy import Connection, func, select, update@@ -42,6 +43,7 @@ ASSIGNABLE_SESSION_VISIBILITIES = frozenset({"foreground", "background"})INBOX_SESSION_VISIBILITIES: tuple[str, ...] = ("foreground", "system")PRIVATE_AGENT_RUN_SCOPE_TYPE = "private_agent_run"+SESSION_PROJECT_BASE_METADATA_KEY = "project_base"logger = logging.getLogger(__name__)@@ -120,6 +122,22 @@ def normalize_workdir(value: Any) -> str | None:return os.path.abspath(os.path.expanduser(text))+def normalize_session_project_base(workdir: Any, candidate: Any) -> str | None:+ """Return an absolute project base only when it contains the Session cwd."""++ normalized_workdir = normalize_workdir(workdir)+ normalized_candidate = normalize_workdir(candidate)+ if not normalized_workdir or not normalized_candidate:+ return None+ resolved_workdir = Path(normalized_workdir).resolve()+ resolved_candidate = Path(normalized_candidate).resolve()+ try:+ resolved_workdir.relative_to(resolved_candidate)+ except ValueError:+ return None+ return str(resolved_candidate)++#: A write that changes nothing, used ONLY to reserve SQLite's writer slot inside a#: transaction that is already open, where ``BEGIN IMMEDIATE`` is illegal. SQLite takes#: the write lock at the START of an UPDATE program -- before its WHERE loop -- so a@@ -449,7 +467,8 @@ def create_agent_session_row(``agent_sessions.workdir`` and never re-resolve cwd from Scope."""- resolved_workdir = normalize_workdir(workdir) or snapshot_scope_workdir(conn, scope_id)+ scope_workdir = snapshot_scope_workdir(conn, scope_id)+ resolved_workdir = normalize_workdir(workdir) or scope_workdirif require_workdir and not resolved_workdir:raise ValueError(f"cannot create agent session without workdir for scope_id={scope_id!r}")@@ -463,6 +482,14 @@ def create_agent_session_row(backend = str(agent_backend or "")variant = str(agent_variant or backend or "default")title_value = title.strip() if (title or "").strip() else None+ metadata_value = dict(metadata or {})+ project_base = normalize_session_project_base(+ resolved_workdir,+ metadata_value.get(SESSION_PROJECT_BASE_METADATA_KEY),+ ) or normalize_session_project_base(resolved_workdir, scope_workdir)+ if project_base is not None:+ metadata_value[SESSION_PROJECT_BASE_METADATA_KEY] = project_base+conn.execute(agent_sessions.insert().values(id=row_id,@@ -480,7 +507,7 @@ def create_agent_session_row(status=status,visibility=visibility_value,agent_status=agent_status,- metadata_json=json.dumps(dict(metadata or {}), separators=(",", ":"), ensure_ascii=False),+ metadata_json=json.dumps(metadata_value, separators=(",", ":"), ensure_ascii=False),created_at=now_value,updated_at=now_value,last_active_at=now_value,diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 973061577..17249f929 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -31,10 +31,13 @@ from vibe.authorization import ()from storage.agent_session_rows import (ASSIGNABLE_SESSION_VISIBILITIES,+ SESSION_PROJECT_BASE_METADATA_KEY,WORKSPACE_NOTICE_SESSION_ID,create_agent_session_row,new_session_id,+ normalize_session_project_base,reserve_write_lock,+ snapshot_scope_workdir,)from storage.db import escape_sql_likefrom storage.session_reclaim import (@@ -96,6 +99,7 @@ def _row_to_payload(include_local_details: bool = True,) -> dict[str, Any]:metadata = _load_metadata(row.get("metadata_json"))+ metadata.pop(SESSION_PROJECT_BASE_METADATA_KEY, None)if not include_local_details:metadata = {}return {@@ -643,6 +647,7 @@ def update_session(agent_sessions.c.agent_backend,agent_sessions.c.native_session_id,agent_sessions.c.agent_status,+ agent_sessions.c.workdir,agent_sessions.c.metadata_json,agent_sessions.c.status,).where(agent_sessions.c.id == session_id)@@ -824,6 +829,13 @@ def update_session(target_scope = scopevalues["scope_id"] = target_scope_idif target_scope_id != existing.scope_id:+ if SESSION_PROJECT_BASE_METADATA_KEY not in existing_metadata:+ project_base = normalize_session_project_base(+ existing.workdir,+ snapshot_scope_workdir(conn, existing.scope_id),+ )+ if project_base is not None:+ existing_metadata[SESSION_PROJECT_BASE_METADATA_KEY] = project_base# Legacy IM caches still consult this metadata key first. A scope# move must stop pinning the session to the old channel; removing# the override lets the loader derive the key from the new scope.diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 0da42bdad..d0bff0c5a 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -1064,7 +1064,10 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):)agent.sessions = _CodexProviderBindingSessions()agent._session_mgr = SimpleNamespace(set_thread_id=lambda *_args: None)- agent._build_thread_developer_instructions = lambda _request: None+ async def build_thread_developer_instructions(_request):+ return None++ agent._build_thread_developer_instructions = build_thread_developer_instructionsrequest = SimpleNamespace(working_path="/tmp/work",context=SimpleNamespace(diff --git a/tests/test_agent_run_target.py b/tests/test_agent_run_target.pyindex 81fa1f0e6..a0d20442f 100644--- a/tests/test_agent_run_target.py+++ b/tests/test_agent_run_target.py@@ -113,8 +113,123 @@ def test_workbench_reserved_session_workdir_wins_over_process_cwd(tmp_path, monk)assert target.workdir == str(project_workdir)+ assert target.project_base == str(project_workdir)assert target.agent_session_id == session["id"]assert ctx.platform_specific["agent_run_target"]["workdir"] == str(project_workdir)+ assert ctx.platform_specific["agent_run_target"]["project_base"] == str(project_workdir)+++def test_existing_workbench_session_retains_non_git_project_base(tmp_path):+ project = tmp_path / "project"+ child = project / "packages" / "app"+ child.mkdir(parents=True)+ controller = _controller(tmp_path)+ with controller.sqlite_engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_non_git",+ now="2026-06-04T05:00:00Z",+ )+ _seed_scope_settings(conn, scope_id, workdir=str(project))+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="codex",+ )+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == session["id"])+ .values(+ workdir=str(child),+ metadata_json=json.dumps({"created_via": "workbench"}),+ )+ )+ other_scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_other",+ now="2026-06-04T05:00:00Z",+ )+ _seed_scope_settings(conn, other_scope_id, workdir=str(tmp_path / "other"))+ sessions_service.update_session(+ conn,+ session["id"],+ scope_id=other_scope_id,+ )+ session = {**session, "workdir": str(child)}++ context = MessageContext(+ user_id="workbench",+ channel_id=session["id"],+ platform="avibe",+ platform_specific={+ "agent_session_id": session["id"],+ "agent_session_target": {+ "id": session["id"],+ "workdir": session["workdir"],+ "session_anchor": session["session_anchor"],+ },+ },+ )++ target = resolve_agent_run_target(+ context,+ controller=controller,+ base_session_id=session["id"],+ )++ assert target.workdir == str(child)+ assert target.project_base == str(project)+++def test_legacy_workbench_session_uses_current_scope_as_project_base(tmp_path):+ project = tmp_path / "project"+ child = project / "packages" / "app"+ child.mkdir(parents=True)+ controller = _controller(tmp_path)+ with controller.sqlite_engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_legacy_non_git",+ now="2026-06-04T05:00:00Z",+ )+ _seed_scope_settings(conn, scope_id, workdir=str(project))+ session = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="codex",+ )+ conn.execute(+ agent_sessions.update()+ .where(agent_sessions.c.id == session["id"])+ .values(+ workdir=str(child),+ metadata_json=json.dumps({"created_via": "workbench"}),+ )+ )++ context = MessageContext(+ user_id="workbench",+ channel_id=session["id"],+ platform="avibe",+ platform_specific={"agent_session_id": session["id"]},+ )++ target = resolve_agent_run_target(+ context,+ controller=controller,+ base_session_id=session["id"],+ )++ assert target.workdir == str(child)+ assert target.project_base == str(project)def test_im_channel_scope_workdir_creates_session_snapshot(tmp_path):diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex 5cc9ae4fc..c4bf8ac31 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -653,7 +653,7 @@ async def test_opencode_steers_existing_runner_without_abort_or_new_turn() -> No"model": {"providerID": "openai", "modelID": "gpt-5"},"reasoning_effort": "high","system": "primary system prompt",- "tools": {"question": False},+ "tools": {"question": False, "skill": False},}]assert server.abort_calls == []@@ -894,6 +894,9 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(class _Server:prompt_count = 0+ def caller_context_binding_path(self):+ return "/old-avibe-home/runtime/opencode_caller_context.json"+async def ensure_running(self):return None@@ -1002,9 +1005,24 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner("modules.agents.opencode.agent.build_system_prompt_injection",lambda **kwargs: "system prompt",)+ binding_tokens: list[str] = []+ binding_paths: list[str] = []++ def bind_caller_context(*args, **kwargs):+ binding_tokens.append(kwargs["binding_token"])+ binding_paths.append(kwargs["path"])+ return True++ unbound: list[tuple[str, str, str]] = []monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session",- lambda *args, **kwargs: None,+ bind_caller_context,+ )+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda session_id, *, binding_token, path: unbound.append(+ (session_id, binding_token, path)+ ),)backend_failure = AsyncMock()monkeypatch.setattr(@@ -1040,6 +1058,15 @@ async def test_opencode_coordinator_error_aborts_through_steering_owner(assert receipt.outcome is SteerOutcome.ACCEPTEDassert events == ["primary", "steer", "abort"]+ assert len(binding_tokens) == 1+ assert binding_paths == ["/old-avibe-home/runtime/opencode_caller_context.json"]+ assert unbound == [+ (+ "opencode-session",+ binding_tokens[0],+ "/old-avibe-home/runtime/opencode_caller_context.json",+ )+ ]backend_failure.assert_awaited_once()@@ -1208,7 +1235,7 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(async def abort_session(self, session_id, directory):events.append("abort")- return True+ raise OSError("abort status unknown")async def mark_run_active(self, session_id):return None@@ -1242,10 +1269,14 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(return Falseclass _Sessions:+ active = False+def add_active_poll(self, **kwargs):+ self.active = Trueevents.append("persist_poll")def remove_active_poll(self, session_id):+ self.active = Falseevents.append("remove_poll")server = _Server()@@ -1284,9 +1315,20 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll("modules.agents.opencode.agent.build_system_prompt_injection",lambda **kwargs: "system prompt",)+ binding_tokens: list[str] = []++ def bind_caller_context(*args, **kwargs):+ binding_tokens.append(kwargs["binding_token"])+ return True++ unbound: list[tuple[str, str]] = []monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session",- lambda *args, **kwargs: None,+ bind_caller_context,+ )+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda session_id, *, binding_token: unbound.append((session_id, binding_token)),)backend_failure = AsyncMock()monkeypatch.setattr(@@ -1297,6 +1339,9 @@ async def test_opencode_ambiguous_start_failure_preserves_recovery_poll(await agent._process_message(primary)assert events == ["persist_poll", "prompt", "abort"]+ assert agent.sessions.active is True+ assert len(binding_tokens) == 1+ assert unbound == []backend_failure.assert_awaited_once()diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 73305aeae..03f4042da 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -177,6 +177,8 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_pathassert captured["connected"] is Trueassert captured["options"].cli_path == "/usr/local/bin/claude-proxy"assert captured["options"].max_buffer_size == CLAUDE_SDK_MAX_BUFFER_SIZE+ assert captured["options"].skills == []+ assert captured["options"].env["AVIBE_SKILL_WORKING_DIR"] == str(tmp_path.resolve())assert controller.claude_sessions[f"slack_C123:{tmp_path}"] is clientassert getattr(client, "_vibe_runtime_base_session_id") == "slack_C123"assert getattr(client, "_vibe_runtime_session_key") == f"slack_C123:{tmp_path}"@@ -305,20 +307,24 @@ def test_claude_system_prompt_follows_live_memory_enabled_state(tmp_path: Path)platform_specific={"memory_cli_admitted": True},)- disabled = handler._build_claude_system_prompt(- context,- session_key="test::C123",- agent_name="claude",- session_anchor="slack_C123",- agent_system_prompt=None,+ disabled = asyncio.run(+ handler._build_claude_system_prompt(+ context,+ session_key="test::C123",+ agent_name="claude",+ session_anchor="slack_C123",+ agent_system_prompt=None,+ ))controller.config.memory.enabled = True- enabled = handler._build_claude_system_prompt(- context,- session_key="test::C123",- agent_name="claude",- session_anchor="slack_C123",- agent_system_prompt=None,+ enabled = asyncio.run(+ handler._build_claude_system_prompt(+ context,+ session_key="test::C123",+ agent_name="claude",+ session_anchor="slack_C123",+ agent_system_prompt=None,+ ))assert "## Personal Memory" not in disabled["append"]@@ -718,6 +724,58 @@ def test_session_handler_reuses_cached_claude_client_when_system_prompt_is_unchaassert "slack/U456" not in first_client.options.system_prompt["append"]+def test_session_handler_recreates_cached_claude_client_when_skill_bindings_change(+ monkeypatch,+ tmp_path: Path,+) -> None:+ captured: dict[str, Any] = {"clients": []}+ skill_env = {"AVIBE_SKILL_WORKING_DIR": str(tmp_path)}++ class _PromptSessions(_Sessions):+ @staticmethod+ def ensure_agent_session_id(settings_key, agent_name, base_session_id, **_kwargs):+ return "sesk8m4q2p7x"++ @staticmethod+ def get_claude_session_id(settings_key, base_session_id):+ return None++ class _StubClaudeSDKClient:+ def __init__(self, options):+ self.options = options+ self.disconnects = 0+ captured["clients"].append(self)++ async def connect(self) -> None:+ return None++ async def disconnect(self) -> None:+ self.disconnects += 1++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)+ monkeypatch.setattr(+ session_handler_module,+ "managed_skill_environment",+ lambda _working_path, **_kwargs: dict(skill_env),+ )++ controller = _Controller(tmp_path)+ controller.settings_manager.sessions = _PromptSessions()+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")++ first_client = _run_session(handler, context)+ skill_env["AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID"] = "a" * 64+ second_client = _run_session(handler, context)++ assert first_client is not second_client+ assert first_client.disconnects == 1+ assert 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++def test_session_handler_recreates_terminated_cached_client_before_dispatch(monkeypatch,tmp_path: Path,diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.pyindex 2bb288daa..e9f834647 100644--- a/tests/test_cli_pagination.py+++ b/tests/test_cli_pagination.py@@ -74,6 +74,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:("task", "list"),("watch", "list"),}+ fixed_page_commands = {("skill", "list")}parser = cli.build_parser()discovered_list_commands = {path@@ -81,12 +82,17 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:if path[-1] == "list" and path[-1] != "ls"}- assert discovered_list_commands <= collection_commands+ assert discovered_list_commands <= collection_commands | fixed_page_commandsfor path in collection_commands:flags = _parser_flags(_command_parser(path))assert "--page" in flags, pathassert "--limit" in flags, pathassert "--all" not in flags, path+ for path in fixed_page_commands:+ flags = _parser_flags(_command_parser(path))+ assert "--page" in flags, path+ assert "--limit" not in flags, path+ assert "--all" not in flags, pathdef test_injected_vibe_commands_only_use_parser_supported_flags() -> None:diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 145cbae74..e143e8c11 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -1679,7 +1679,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):agent = object.__new__(CodexAgent)agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))agent._session_mgr = SimpleNamespace(set_thread_id=Mock())- agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)agent._start_thread = AsyncMock()request = SimpleNamespace(session_key="settings-1", base_session_id="session-1")transport = SimpleNamespace(send_request=AsyncMock(side_effect=ConnectionError("Codex app-server stdout closed")))@@ -1726,7 +1726,10 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent._inject_caller_env_config(params, request)set_env = params["config"]["shell_environment_policy"]["set"]- self.assertEqual(set_env, {"PATH": "/managed/git/bin"})+ self.assertEqual(set_env["PATH"], "/managed/git/bin")+ self.assertEqual(set_env["AVIBE_SKILL_WORKING_DIR"], str(Path("/tmp/workspace").resolve()))+ self.assertTrue(set_env["BASH_ENV"].endswith("/codex-caller-env/session.sh"))+ self.assertFalse(params["config"]["skills.include_instructions"])def test_inject_caller_env_config_merges_shell_environment_policy(self):agent = object.__new__(CodexAgent)@@ -1757,6 +1760,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(set_env["AVIBE_NATIVE_SESSION_ID"], "thread-parent")self.assertTrue(set_env["BASH_ENV"].endswith("/codex-caller-env/ses-parent.sh"))self.assertNotIn("PATH", set_env)+ self.assertFalse(params["config"]["skills.include_instructions"])def test_write_caller_env_script_refreshes_reused_thread_run_id(self):agent = object.__new__(CodexAgent)@@ -2112,7 +2116,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-projection"))agent.bind_agent_session_id = Mock()agent._session_mgr = SimpleNamespace(set_thread_id=Mock())- agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)request = SimpleNamespace(working_path="/tmp/work",@@ -2955,7 +2959,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-subagent"))agent.bind_agent_session_id = Mock()agent._session_mgr = SimpleNamespace(set_thread_id=Mock())- agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)request = SimpleNamespace(working_path="/tmp/work",@@ -2989,7 +2993,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent.bind_agent_session_id = Mock()agent._session_mgr = SimpleNamespace(set_thread_id=Mock())agent._start_thread = AsyncMock()- agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._build_thread_developer_instructions = AsyncMock(return_value=None)agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)request = SimpleNamespace(working_path="/tmp/work",@@ -3182,9 +3186,13 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):subagent_name=None,)- disabled_instructions = agent._build_thread_developer_instructions(request)+ disabled_instructions = asyncio.run(+ agent._build_thread_developer_instructions(request)+ )agent.controller.config.memory.enabled = True- enabled_instructions = agent._build_thread_developer_instructions(request)+ enabled_instructions = asyncio.run(+ agent._build_thread_developer_instructions(request)+ )self.assertNotIn("## Personal Memory", disabled_instructions)self.assertIn("## Personal Memory", enabled_instructions)@@ -3286,7 +3294,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent = object.__new__(CodexAgent)agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)- agent._build_thread_developer_instructions = Mock(return_value="stable instructions")+ agent._build_thread_developer_instructions = AsyncMock(return_value="stable instructions")agent._thread_developer_instructions = {"session-1": ("thread-existing", "stable instructions")}@@ -3338,7 +3346,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent = object.__new__(CodexAgent)agent.sessions = SimpleNamespace(ensure_agent_session_id=Mock(return_value="sesk8m4q2p7x"))agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)- agent._build_thread_developer_instructions = Mock(return_value="stable instructions")+ agent._build_thread_developer_instructions = AsyncMock(return_value="stable instructions")agent._thread_developer_instructions = {"session-1": ("thread-existing", "stable instructions")}diff --git a/tests/test_managed_skills.py b/tests/test_managed_skills.pynew file mode 100644index 000000000..b588a7b6e--- /dev/null+++ b/tests/test_managed_skills.py@@ -0,0 +1,1663 @@+from __future__ import annotations++import json+import os+import sys+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++from core import managed_skills+from core.managed_skills import (+ BUILTIN_SKILLS_ROOT_ENV,+ BUILTIN_SKILLS_SNAPSHOT_ENV,+ CATALOG_DESCRIPTION_MAX_CHARS,+ CATALOG_PAGE_MAX_BYTES,+ CATALOG_PAGE_SIZE,+ SKILL_BODY_MAX_BYTES,+ SKILL_CLAUDE_CLI_PATH_ENV,+ SKILL_CLAUDE_HOME_ENV,+ SKILL_CODEX_HOME_ENV,+ SKILL_HOME_ENV,+ SKILL_PROJECT_BASE_ENV,+ SKILL_XDG_CONFIG_HOME_ENV,+ SKILL_WORKING_DIR_ENV,+ load_skill,+ managed_skill_environment,+ parse_skill_file,+ 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_injection+from modules.im import MessageContext+++def _write_skill(+ root: Path,+ directory: str,+ name: str,+ description: str,+ body: str = "Body\n",+) -> Path:+ skill_dir = root / directory+ skill_dir.mkdir(parents=True, exist_ok=True)+ skill_file = skill_dir / "SKILL.md"+ skill_file.write_text(+ f"---\nname: {name}\ndescription: {description}\n---\n{body}",+ encoding="utf-8",+ )+ return skill_file+++def _isolated_resolve(cwd: Path, tmp_path: Path, **kwargs):+ return resolve_skills(+ cwd,+ home=kwargs.pop("home", tmp_path / "home"),+ avibe_home=kwargs.pop("avibe_home", tmp_path / "avibe-home"),+ 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", ""),+ **kwargs,+ )+++def _isolate_live_commands(monkeypatch, tmp_path: Path) -> tuple[Path, Path]:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ 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+++def test_loose_parser_requires_only_portable_name_and_description(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "unknown: [this is not valid yaml\n"+ "name: declared-name\n"+ "description: >\n"+ " First line.\n"+ " Second line.\n"+ "---\n"+ "# Instructions\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "declared-name"+ assert skill.description == "First line. Second line."+ assert skill.body == "# Instructions\n"+++def test_loose_parser_decodes_quoted_name_escapes_and_plain_description_folding(+ tmp_path: Path,+) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ 'name: "format\\u002dcode"\n'+ "description: Formats source files and\n"+ " applies repository conventions.\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "format-code"+ assert skill.description == "Formats source files and applies repository conventions."+++def test_invalid_optional_yaml_type_falls_back_to_required_fields(tmp_path: Path) -> None:+ skill_file = tmp_path / "typed" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "name: typed\n"+ "description: Still portable\n"+ "expires: 2022-99-99\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(0,))++ assert skill is not None+ assert skill.name == "typed"+ assert skill.description == "Still portable"+++def test_loose_parser_never_constructs_ignored_yaml_values(tmp_path: Path, monkeypatch) -> None:+ skill_file = tmp_path / "typed" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "name: typed\n"+ "description: Still portable\n"+ "metadata: &recursive [*recursive]\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(+ managed_skills.yaml,+ "load",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ AssertionError("optional YAML must not be constructed")+ ),+ )++ skill = parse_skill_file(skill_file, priority=(0,))++ assert skill is not None+ assert skill.name == "typed"+ assert skill.description == "Still portable"+++def test_loose_parser_accepts_quoted_required_keys(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "\"name\": format-code\n"+ "'description': Formats source files.\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "format-code"+ assert skill.description == "Formats source files."+++def test_loose_parser_decodes_escaped_required_keys(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ '"na\\u006de": format-code\n'+ '"descr\\u0069ption": Formats source files.\n'+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "format-code"+ assert skill.description == "Formats source files."+++def test_loose_parser_ignores_nested_required_field_names(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "metadata:\n"+ " name: nested-name\n"+ " description: Nested description\n"+ "name: top-level-name\n"+ "description: Top-level description\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "top-level-name"+ assert skill.description == "Top-level description"+++def test_loose_parser_accepts_yaml_comments_on_required_scalars(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ '---\nname: formatter # local tools\ndescription: "Format # headings" # shown in catalog\n---\nBody\n',+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "formatter"+ assert skill.description == "Format # headings"+++def test_loose_parser_ignores_comments_before_continued_required_scalars(tmp_path: Path) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "unknown: [invalid yaml\n"+ "name:\n"+ "# local name\n"+ " formatter # callable name\n"+ "description:\n"+ " # catalog copy\n"+ " Formats source files. # display text\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.name == "formatter"+ assert skill.description == "Formats source files."++[email protected]("quote", ["'", '"'])+def test_loose_parser_consumes_multiline_quoted_description(tmp_path: Path, quote: str) -> None:+ skill_file = tmp_path / "skill" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "name: formatter\n"+ f"description: {quote}Formats source files and\n"+ f" applies repository conventions.{quote} # catalog copy\n"+ "---\n"+ "Body\n",+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.description == "Formats source files and applies repository conventions."+++ "name",+ ["", "Uppercase", "two words", "-leading", "trailing-", "two--hyphens", "shell;word"],+)+def test_parser_omits_nonportable_names(tmp_path: Path, name: str) -> None:+ skill_file = _write_skill(tmp_path, "candidate", name, "Description")+ assert parse_skill_file(skill_file, priority=(1, 0, 1)) is None+++def test_resolution_applies_all_precedence_dimensions(tmp_path: Path) -> None:+ home = tmp_path / "home"+ avibe_home = home / ".avibe"+ project = tmp_path / "project"+ nested = project / "packages" / "app"+ nested.mkdir(parents=True)+ (project / ".git").mkdir()+ snapshot_id = "a" * 64+ builtin_root = avibe_home / "builtin-skills" / snapshot_id++ _write_skill(home / ".agents" / "skills", "shared", "shared", "global agents")+ _write_skill(home / ".codex" / "skills", "global-family", "global-family", "codex")+ global_agents = _write_skill(home / ".agents" / "skills", "global-family", "global-family", "agents")+ _write_skill(project / ".agents" / "skills", "depth", "depth", "project root")+ nearest = _write_skill(nested / ".agents" / "skills", "depth", "depth", "nearest")+ _write_skill(nested / ".claude" / "skills", "family", "family", "claude")+ project_agents = _write_skill(nested / ".agents" / "skills", "family", "family", "agents")+ builtin = _write_skill(builtin_root, "shared", "shared", "builtin")++ skills = resolve_skills(+ nested,+ home=home,+ avibe_home=avibe_home,+ codex_home=home / ".codex",+ claude_home=home / ".claude",+ xdg_config_home=home / ".config",+ builtin_snapshot_id=snapshot_id,+ )+ by_name = {skill.name: skill for skill in skills}++ assert list(by_name) == sorted(by_name)+ assert by_name["shared"].directory == builtin.parent.resolve()+ assert by_name["depth"].directory == nearest.parent.resolve()+ assert by_name["family"].directory == project_agents.parent.resolve()+ assert by_name["global-family"].directory == global_agents.parent.resolve()+++def test_global_roots_honor_backend_home_overrides(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ codex_home = tmp_path / "custom-codex"+ claude_home = tmp_path / "custom-claude"+ xdg_home = tmp_path / "custom-xdg"+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ 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, "")++ _write_skill(codex_home / "skills", "codex", "codex", "Codex")+ _write_skill(claude_home / "skills", "claude", "claude", "Claude")+ _write_skill(xdg_home / "opencode" / "skills", "opencode", "opencode", "OpenCode")++ assert [skill.name for skill in resolve_skills(cwd)] == ["claude", "codex", "opencode"]+++def test_bound_global_roots_do_not_follow_later_relative_overrides(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ other = tmp_path / "other"+ cwd.mkdir()+ other.mkdir()+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ monkeypatch.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, "")+ bound = managed_skill_environment(cwd)+ monkeypatch.setenv("CODEX_HOME", "relative-codex")+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", "relative-claude")+ monkeypatch.setenv("XDG_CONFIG_HOME", "relative-xdg")+ monkeypatch.chdir(other)+ for key, value in bound.items():+ monkeypatch.setenv(key, value)++ _write_skill(tmp_path / "bound-codex" / "skills", "codex", "codex", "Codex")+ _write_skill(tmp_path / "bound-claude" / "skills", "claude", "claude", "Claude")+ _write_skill(tmp_path / "bound-xdg" / "opencode" / "skills", "opencode", "opencode", "OpenCode")++ assert [skill.name for skill in resolve_skills()] == ["claude", "codex", "opencode"]+++def test_codex_system_skills_are_a_low_priority_global_compatibility_root(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ 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, "")++ user = _write_skill(home / ".agents" / "skills", "shared", "shared", "User")+ _write_skill(codex_home / "skills" / ".system", "shared", "shared", "System")+ system = _write_skill(codex_home / "skills" / ".system", "imagegen", "imagegen", "System")++ by_name = {skill.name: skill for skill in resolve_skills(cwd)}++ assert by_name["shared"].directory == user.parent.resolve()+ assert by_name["imagegen"].directory == system.parent.resolve()+++def test_codex_system_container_counts_toward_the_user_root_enumeration_limit(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ 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.setattr(managed_skills, "DISCOVERY_ROOT_MAX_CHILDREN", 1)++ _write_skill(codex_home / "skills", "user-skill", "user-skill", "User")+ _write_skill(codex_home / "skills" / ".system", "system-skill", "system-skill", "System")++ assert [skill.name for skill in resolve_skills(cwd)] == ["system-skill"]+++def test_empty_backend_home_overrides_fall_back_to_default_roots(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ monkeypatch.setenv("CODEX_HOME", "")+ monkeypatch.setenv("XDG_CONFIG_HOME", "")+ monkeypatch.setenv(BUILTIN_SKILLS_SNAPSHOT_ENV, "")++ _write_skill(home / ".codex" / "skills", "codex", "codex", "Codex")+ _write_skill(home / ".config" / "opencode" / "skills", "opencode", "opencode", "OpenCode")++ assert [skill.name for skill in resolve_skills(cwd)] == ["codex", "opencode"]+++def test_final_path_tie_breaker_is_independent_of_enumeration_order(tmp_path: Path, monkeypatch) -> None:+ cwd = tmp_path / "project"+ cwd.mkdir()+ root = cwd / ".agents" / "skills"+ first = _write_skill(root, "a-dir", "same", "First")+ _write_skill(root, "z-dir", "same", "Last")+ original = managed_skills._root_children++ def reversed_children(path: Path, **kwargs):+ children = original(path, **kwargs)+ return list(reversed(children)) if children else children++ monkeypatch.setattr(managed_skills, "_root_children", reversed_children)+ resolved = _isolated_resolve(cwd, tmp_path)++ assert len(resolved) == 1+ assert resolved[0].directory == first.parent.resolve()+++def test_reserved_root_and_non_git_ancestors_are_not_scanned(tmp_path: Path) -> None:+ cwd = tmp_path / "parent" / "child"+ cwd.mkdir(parents=True)+ _write_skill(tmp_path / "avibe-home" / "skills", "reserved", "reserved", "Reserved")+ _write_skill(tmp_path / "parent" / ".agents" / "skills", "parent", "parent", "Parent")+ _write_skill(cwd / ".agents" / "skills", "local", "local", "Local")++ assert [skill.name for skill in _isolated_resolve(cwd, tmp_path)] == ["local"]++[email protected](os.name == "nt", reason="directory symlink fixture requires POSIX semantics")+def test_compatibility_skill_directory_symlink_is_loaded_and_revalidated(tmp_path: Path) -> None:+ cwd = tmp_path / "project"+ root = cwd / ".agents" / "skills"+ root.mkdir(parents=True)+ target_file = _write_skill(tmp_path / "shared", "formatter", "formatter", "Format", "Linked\n")+ linked = root / "formatter"+ linked.symlink_to(target_file.parent, target_is_directory=True)++ resolved = _isolated_resolve(cwd, tmp_path)++ assert [skill.name for skill in resolved] == ["formatter"]+ assert resolved[0].directory == target_file.parent.resolve()+ loaded = load_skill("formatter", resolved_skills=resolved)+ assert loaded is not None+ assert loaded.body == "Linked\n"++ target_file.parent.rename(tmp_path / "old-shared")+ _write_skill(tmp_path / "shared", "formatter", "formatter", "Format", "Replacement\n")+ assert load_skill("formatter", resolved_skills=resolved) is None++ linked.unlink()+ assert load_skill("formatter", resolved_skills=resolved) is None+++def test_project_root_ascent_is_bounded(tmp_path: Path, monkeypatch) -> None:+ project = tmp_path / "project"+ cwd = project / "a" / "b" / "c"+ cwd.mkdir(parents=True)+ (project / ".git").mkdir()+ _write_skill(project / ".agents" / "skills", "root", "root", "Root")+ _write_skill(cwd / ".agents" / "skills", "local", "local", "Local")+ monkeypatch.setattr(managed_skills, "PROJECT_ROOT_MAX_DIRECTORIES", 3)++ assert [skill.name for skill in _isolated_resolve(cwd, tmp_path)] == ["local"]+++def test_bound_project_base_outside_ascent_limit_is_ignored(tmp_path: Path, monkeypatch) -> None:+ project = tmp_path / "project"+ cwd = project / "a" / "b" / "c"+ cwd.mkdir(parents=True)+ _write_skill(project / ".agents" / "skills", "root", "root", "Root")+ _write_skill(cwd / ".agents" / "skills", "local", "local", "Local")+ monkeypatch.setattr(managed_skills, "PROJECT_ROOT_MAX_DIRECTORIES", 3)++ assert [+ skill.name+ for skill in _isolated_resolve(cwd, tmp_path, project_base=project)+ ] == ["local"]+++def test_catalog_paginates_stably_without_exposing_directories(tmp_path: Path) -> None:+ skills = []+ for index in reversed(range(CATALOG_PAGE_SIZE + 1)):+ skill_file = _write_skill(+ tmp_path / "skills",+ f"skill-{index:02d}",+ f"skill-{index:02d}",+ f"Description {index}",+ )+ skill = parse_skill_file(skill_file, priority=(1, 0, 1))+ assert skill is not None+ skills.append(skill)+ skills.sort(key=lambda item: item.name)++ prompt = render_skill_catalog_prompt(skills)++ assert prompt.count("\n- skill-") == CATALOG_PAGE_SIZE+ assert "`vibe skill list --page 2`" in prompt+ assert "ordinary tasks do not require scanning every page" in prompt+ assert "load that name directly" in prompt+ assert render_skill_list(skills, page=2) == "- skill-25: Description 25"+ assert str(tmp_path) not in prompt+ assert render_skill_catalog_prompt([]) == ""+++def test_manual_only_skill_is_loadable_but_not_advertised(tmp_path: Path) -> None:+ skill_file = tmp_path / "manual" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ "---\n"+ "name: manual\n"+ "description: Run only when explicitly requested.\n"+ "disable-model-invocation: true\n"+ "---\n"+ "Manual body\n",+ encoding="utf-8",+ )+ manual = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert manual is not None+ assert manual.disable_model_invocation is True+ assert render_skill_list([manual]) == ""+ manual_prompt = render_skill_catalog_prompt([manual])+ assert "`vibe skill load -- <name>`" in manual_prompt+ assert "- manual:" not in manual_prompt+ assert "Run only when explicitly requested." not in manual_prompt++ loaded = load_skill("manual", resolved_skills=[manual])+ assert loaded is not None+ assert loaded.body == "Manual body\n"+ assert loaded.disable_model_invocation is True+++def test_catalog_bounds_descriptions_and_row_bytes(tmp_path: Path) -> None:+ skills = []+ for index in range(CATALOG_PAGE_SIZE):+ skill_file = _write_skill(+ tmp_path,+ f"skill-{index:02d}",+ f"skill-{index:02d}",+ "界" * (CATALOG_DESCRIPTION_MAX_CHARS + 50),+ )+ skill = parse_skill_file(skill_file, priority=(1, 0, 1))+ assert skill is not None+ assert len(skill.description) == CATALOG_DESCRIPTION_MAX_CHARS+ assert skill.description.endswith("...")+ skills.append(skill)++ rows, notice = render_skill_list(skills).rsplit("\n", 1)+ assert len(rows.encode("utf-8")) <= CATALOG_PAGE_MAX_BYTES+ assert notice == "More skills are available. Run `vibe skill list --page 2` to view more."++ first_page_names = [line.split(":", 1)[0][2:] for line in rows.splitlines()]+ second_page = render_skill_list(skills, page=2)+ assert second_page.splitlines()[0].startswith(+ f"- skill-{len(first_page_names):02d}:"+ )+++def test_catalog_neutralizes_yaml_decoded_terminal_controls(tmp_path: Path) -> None:+ skill_file = tmp_path / "controlled" / "SKILL.md"+ skill_file.parent.mkdir()+ skill_file.write_text(+ '---\nname: controlled\ndescription: "\\u001b[31mred\\u009b0m"\n---\nBody\n',+ encoding="utf-8",+ )++ skill = parse_skill_file(skill_file, priority=(1, 0, 1))++ assert skill is not None+ assert skill.description == "[31mred 0m"+ assert "\x1b" not in render_skill_list([skill])+ assert "\x9b" not in render_skill_list([skill])+++def test_system_prompt_catalog_reflects_add_edit_and_delete_each_render(tmp_path: Path, monkeypatch) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)++ before = build_system_prompt_injection(skills_cwd=cwd)+ skill_file = _write_skill(cwd / ".agents" / "skills", "live", "live", "First")+ after_install = build_system_prompt_injection(skills_cwd=cwd)+ skill_file.write_text(+ "---\nname: live\ndescription: Updated\n---\nUpdated body\n",+ encoding="utf-8",+ )+ after_update = build_system_prompt_injection(skills_cwd=cwd)+ skill_file.unlink()+ after_delete = build_system_prompt_injection(skills_cwd=cwd)++ assert "## Skills" not in before+ assert "- live: First" in after_install+ assert "- live: Updated" in after_update+ assert "## Skills" not in after_delete+++def test_system_prompt_catalog_is_backend_neutral_for_remote_sessions(+ tmp_path: Path,+ monkeypatch,+) -> None:+ cwd = tmp_path / "project"+ cwd.mkdir()+ 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, "")+ _write_skill(cwd / ".agents" / "skills", "shared", "shared", "Shared")+ resource_context = {+ "sub": "member-1",+ "instance_role": "editor",+ "is_remote": True,+ }+ context = MessageContext(+ user_id="remote:member-1",+ channel_id="workbench",+ platform="avibe",+ platform_specific={+ "agent_session_id": "sess-runtime",+ "message_metadata": {"resource_user_context": resource_context},+ },+ )+ prompts = {+ backend: build_system_prompt_injection(+ context=context,+ fallback_platform="avibe",+ current_agent_backend=backend,+ skills_cwd=cwd,+ )+ for backend in ("claude", "codex", "opencode")+ }++ assert all("- shared: Shared" in prompt for prompt in prompts.values())+++def test_load_emits_body_only_and_agent_accessible_directory(tmp_path: Path, monkeypatch) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ skill_file = _write_skill(+ cwd / ".agents" / "skills",+ "docs",+ "docs",+ "Description",+ "Use references/guide.md",+ )+ reference = skill_file.parent / "references" / "guide.md"+ reference.parent.mkdir()+ reference.write_text("Reference", encoding="utf-8")++ skill = load_skill("docs", cwd)++ assert skill is not None+ assert (skill.directory / "references" / "guide.md").read_text() == "Reference"+ assert render_skill_content(skill) == (+ f'<skill_content name="docs" directory="{skill_file.parent.resolve()}">\n'+ "Use references/guide.md</skill_content>"+ )+++def test_invalid_utf8_body_is_advertised_but_cannot_be_loaded(+ tmp_path: Path,+ monkeypatch,+) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ skill_file = cwd / ".agents" / "skills" / "binary" / "SKILL.md"+ skill_file.parent.mkdir(parents=True)+ skill_file.write_bytes(+ b"---\nname: binary\ndescription: Invalid text body\n---\n\xff\n"+ )++ assert [skill.name for skill in resolve_skills(cwd)] == ["binary"]+ assert load_skill("binary", cwd) is None+++def test_terminal_controls_in_body_are_advertised_but_cannot_be_loaded(+ tmp_path: Path,+ monkeypatch,+) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ skill_file = cwd / ".agents" / "skills" / "controlled" / "SKILL.md"+ skill_file.parent.mkdir(parents=True)+ skill_file.write_bytes(+ b"---\nname: controlled\ndescription: Controlled body\n---\n"+ b"Allowed tabs\tand newlines\nRejected escape: \x1b[31m\n"+ )++ assert [skill.name for skill in resolve_skills(cwd)] == ["controlled"]+ assert load_skill("controlled", cwd) is None+++ os.name == "nt" or sys.platform == "darwin",+ reason="fixture requires raw-byte filenames supported by the host filesystem",+)+def test_non_utf8_resolved_directory_is_not_advertised(+ tmp_path: Path,+ monkeypatch,+) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ root = cwd / ".agents" / "skills"+ root.mkdir(parents=True)+ raw_directory = os.path.join(os.fsencode(root), b"raw-\xff")+ os.mkdir(raw_directory)+ skill_fd = os.open(+ os.path.join(raw_directory, b"SKILL.md"),+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,+ 0o600,+ )+ try:+ os.write(skill_fd, b"---\nname: raw\ndescription: Raw path\n---\nBody\n")+ finally:+ os.close(skill_fd)++ assert resolve_skills(cwd) == []+ assert load_skill("raw", cwd) is None+++def test_load_escapes_directory_attribute_controls(tmp_path: Path, monkeypatch) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ working_directory = cwd / 'line\nbreak"&'+ working_directory.mkdir()+ _write_skill(working_directory / ".agents" / "skills", "demo", "demo", "Demo")++ skill = load_skill("demo", working_directory)++ assert skill is not None+ output = render_skill_content(skill)+ assert "line
break"&" in output+ assert output.count("\n") == 1 + skill.body.count("\n")+++def test_load_reparses_the_selected_file_and_rejects_a_changed_name(tmp_path: Path, monkeypatch) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ skill_file = _write_skill(cwd / ".agents" / "skills", "docs", "docs", "Description")+ winner = resolve_skills(cwd)[0]+ skill_file.write_text(+ "---\nname: renamed\ndescription: Changed\n---\nNew body\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(managed_skills, "resolve_skills", lambda _cwd=None: [winner])++ assert load_skill("docs", cwd) is None+++def test_load_does_not_fall_through_to_a_new_unadvertised_winner(tmp_path: Path, monkeypatch) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ project_file = _write_skill(cwd / ".agents" / "skills", "docs", "docs", "Project")+ _write_skill(home / ".agents" / "skills", "docs", "docs", "Global")+ advertised = resolve_skills(cwd)+ project_file.unlink()++ assert load_skill("docs", cwd, resolved_skills=advertised) is None++[email protected](os.name == "nt", reason="Windows cannot rename an open directory fixture")+def test_load_rejects_a_replaced_directory_before_output(tmp_path: Path, monkeypatch) -> None:+ _, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ skill_file = _write_skill(cwd / ".agents" / "skills", "docs", "docs", "Description")+ original_read = managed_skills._read_skill_path+ replaced = False++ def replace_after_read(*args, **kwargs):+ nonlocal replaced+ result = original_read(*args, **kwargs)+ if kwargs.get("include_body") and not replaced:+ replaced = True+ skill_file.parent.rename(skill_file.parent.with_name("docs-old"))+ _write_skill(skill_file.parent.parent, "docs", "docs", "Replacement")+ return result++ monkeypatch.setattr(managed_skills, "_read_skill_path", replace_after_read)++ assert load_skill("docs", cwd) is None++[email protected](os.name == "nt", reason="FIFO fixtures are POSIX-only")+def test_fifo_candidate_cannot_block_discovery_or_load(tmp_path: Path) -> None:+ cwd = tmp_path / "project"+ fifo = cwd / ".agents" / "skills" / "fifo" / "SKILL.md"+ fifo.parent.mkdir(parents=True)+ os.mkfifo(fifo)++ assert _isolated_resolve(cwd, tmp_path) == []+++def test_verified_read_rejects_a_file_changed_during_read(tmp_path: Path, monkeypatch) -> None:+ skill_file = _write_skill(tmp_path, "docs", "docs", "Description")+ original = managed_skills._stat_token+ calls = 0++ def changed_token(value):+ nonlocal calls+ calls += 1+ token = original(value)+ return (*token[:-1], token[-1] + (1 if calls == 2 else 0))++ monkeypatch.setattr(managed_skills, "_stat_token", changed_token)+ assert parse_skill_file(skill_file, priority=(1, 0, 1)) is None++[email protected](os.name == "nt", reason="Windows cannot replace an open file fixture")[email protected]("include_body", [False, True])+def test_verified_read_rejects_an_atomic_path_replacement(+ tmp_path: Path,+ monkeypatch,+ include_body: bool,+) -> None:+ skill_file = _write_skill(tmp_path, "docs", "docs", "Description", "Original\n")+ read_name = "_read_all" if include_body else "_read_prefix"+ original_read = getattr(managed_skills, read_name)++ def replace_after_read(*args, **kwargs):+ data = original_read(*args, **kwargs)+ replacement = skill_file.with_suffix(".replacement")+ replacement.write_text(+ "---\nname: docs\ndescription: Replacement\n---\nReplacement\n",+ encoding="utf-8",+ )+ os.replace(replacement, skill_file)+ return data++ monkeypatch.setattr(managed_skills, read_name, replace_after_read)++ assert parse_skill_file(+ skill_file,+ priority=(1, 0, 1),+ include_body=include_body,+ ) is None+++def test_frontmatter_body_and_root_limits_omit_candidates(tmp_path: Path) -> None:+ cwd = tmp_path / "project"+ too_much_frontmatter = cwd / ".agents" / "skills" / "frontmatter" / "SKILL.md"+ too_much_frontmatter.parent.mkdir(parents=True)+ too_much_frontmatter.write_text(+ "---\nname: frontmatter\ndescription: Description\nunknown: "+ + "x" * managed_skills.FRONTMATTER_MAX_BYTES+ + "\n---\nBody\n",+ encoding="utf-8",+ )+ _write_skill(+ cwd / ".agents" / "skills",+ "body",+ "body",+ "Description",+ "x" * (SKILL_BODY_MAX_BYTES + 1),+ )++ assert _isolated_resolve(cwd, tmp_path) == []++ oversized_root = tmp_path / "oversized" / ".agents" / "skills"+ for index in range(managed_skills.DISCOVERY_ROOT_MAX_CHILDREN + 1):+ (oversized_root / f"entry-{index:04d}").mkdir(parents=True)+ assert _isolated_resolve(tmp_path / "oversized", tmp_path) == []+++def test_aggregate_direct_child_budget_bounds_all_roots(tmp_path: Path, monkeypatch) -> None:+ cwd = tmp_path / "project"+ root = cwd / ".agents" / "skills"+ root.mkdir(parents=True)+ (root / "README.md").write_text("not a Skill\n", encoding="utf-8")+ (root / "notes.txt").write_text("not a Skill\n", encoding="utf-8")+ _write_skill(tmp_path / "home" / ".agents" / "skills", "global", "global", "Global")+ monkeypatch.setattr(managed_skills, "DISCOVERY_CLASS_MAX_CHILDREN", 2)++ assert _isolated_resolve(cwd, tmp_path) == []+++def test_aggregate_direct_child_budget_keeps_the_root_that_exactly_fills_it(+ tmp_path: Path,+ monkeypatch,+) -> None:+ cwd = tmp_path / "project"+ _write_skill(cwd / ".agents" / "skills", "local", "local", "Local")+ _write_skill(tmp_path / "home" / ".agents" / "skills", "global", "global", "Global")+ monkeypatch.setattr(managed_skills, "DISCOVERY_CLASS_MAX_CHILDREN", 1)++ assert [skill.name for skill in _isolated_resolve(cwd, tmp_path)] == ["local"]+++def test_builtin_and_compatibility_inputs_have_independent_budgets(tmp_path: Path, monkeypatch) -> None:+ cwd = 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")+ _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)++ skills = _isolated_resolve(+ cwd,+ tmp_path,+ avibe_home=avibe_home,+ builtin_snapshot_id=snapshot_id,+ )+ assert [skill.name for skill in skills] == ["builtin", "project"]++[email protected](os.name == "nt", reason="directory symlink fixture requires POSIX semantics")+def test_compatibility_aliases_share_one_candidate_budget_slot(tmp_path: Path, monkeypatch) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ canonical = _write_skill(home / ".agents" / "skills", "shared", "shared", "Shared")+ for root in (+ tmp_path / "codex-home" / "skills",+ tmp_path / "claude-home" / "skills",+ tmp_path / "xdg-home" / "opencode" / "skills",+ ):+ root.mkdir(parents=True)+ (root / "shared").symlink_to(canonical.parent, target_is_directory=True)+ _write_skill(tmp_path / "xdg-home" / "opencode" / "skills", "unique", "unique", "Unique")+ monkeypatch.setattr(managed_skills, "DISCOVERY_CLASS_MAX_CANDIDATES", 2)++ skills = _isolated_resolve(cwd, tmp_path)++ assert [skill.name for skill in skills] == ["shared", "unique"]+ assert skills[0].directory == canonical.parent.resolve()+++def test_bound_non_git_project_base_is_discovered_from_descendant(+ tmp_path: Path,+ monkeypatch,+) -> None:+ project = tmp_path / "project"+ working_directory = project / "packages" / "app"+ working_directory.mkdir(parents=True)+ _write_skill(project / ".agents" / "skills", "root-skill", "root-skill", "Root")++ assert _isolated_resolve(working_directory, tmp_path) == []+ assert [+ skill.name+ for skill in _isolated_resolve(+ working_directory,+ tmp_path,+ project_base=project,+ )+ ] == ["root-skill"]++ monkeypatch.setenv(SKILL_WORKING_DIR_ENV, str(working_directory))+ monkeypatch.setenv(SKILL_PROJECT_BASE_ENV, str(project))+ assert [+ skill.name+ for skill in _isolated_resolve(+ working_directory,+ tmp_path,+ project_base=None,+ )+ ] == ["root-skill"]+++def test_bound_project_base_wins_over_nested_git_boundary(tmp_path: Path) -> None:+ project = tmp_path / "project"+ nested_checkout = project / "packages" / "app"+ working_directory = nested_checkout / "src"+ working_directory.mkdir(parents=True)+ (nested_checkout / ".git").mkdir()+ _write_skill(project / ".agents" / "skills", "outer", "outer", "Outer")+ _write_skill(nested_checkout / ".agents" / "skills", "inner", "inner", "Inner")++ assert [+ skill.name+ for skill in _isolated_resolve(+ working_directory,+ tmp_path,+ project_base=project,+ )+ ] == ["inner", "outer"]++def test_project_base_outside_working_directory_is_ignored(tmp_path: Path) -> None:+ working_directory = tmp_path / "project" / "child"+ other = tmp_path / "other"+ working_directory.mkdir(parents=True)+ _write_skill(other / ".agents" / "skills", "other", "other", "Other")++ assert _isolated_resolve(+ working_directory,+ tmp_path,+ project_base=other,+ ) == []+++def test_distinct_same_name_candidates_keep_precedence_winner(tmp_path: Path) -> None:+ cwd = tmp_path / "project"+ _write_skill(cwd / ".codex" / "skills", "shared", "shared", "Codex")+ _write_skill(cwd / ".claude" / "skills", "shared", "shared", "Claude")++ skills = _isolated_resolve(cwd, tmp_path)++ assert len(skills) == 1+ assert skills[0].description == "Codex"+++def test_enabled_claude_plugin_skills_join_the_managed_catalog(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ claude_home = home / ".claude"+ registry = claude_home / "plugins" / "installed_plugins.json"+ registry.parent.mkdir(parents=True)+ registry.write_text('{"version": 2, "plugins": {}}', encoding="utf-8")+ plugin = tmp_path / "plugin-cache" / "formatter"+ _write_skill(plugin / "skills", "format-code", "format-code", "Format code")+ captured = {}++ def plugin_list(command, **kwargs):+ captured.update(command=command, **kwargs)+ return json.dumps(+ [+ {+ "id": "formatter@example",+ "enabled": True,+ "installPath": str(plugin),+ },+ {+ "id": "disabled@example",+ "enabled": False,+ "installPath": str(tmp_path / "disabled"),+ },+ ]+ ).encode()++ monkeypatch.setattr(managed_skills, "_bounded_subprocess_stdout", plugin_list)++ skills = resolve_skills(+ cwd,+ home=home,+ avibe_home=tmp_path / "avibe",+ codex_home=home / ".codex",+ claude_home=claude_home,+ claude_cli_path="/opt/claude-custom",+ xdg_config_home=home / ".config",+ builtin_snapshot_id="",+ )++ assert [skill.name for skill in skills] == ["format-code"]+ assert captured["command"] == [+ "/opt/claude-custom",+ "plugin",+ "list",+ "--json",+ ]+ assert captured["cwd"] == cwd+ assert captured["env"]["CLAUDE_CONFIG_DIR"] == str(claude_home)+ assert captured["timeout"] == managed_skills.CLAUDE_PLUGIN_LIST_TIMEOUT_SECONDS+ assert captured["max_bytes"] == managed_skills.CLAUDE_PLUGIN_LIST_MAX_BYTES+++ ("stdout_bytes", "stderr_bytes"),+ [(4097, 0), (0, 4097), (2049, 2049)],+)+def test_bounded_subprocess_capture_rejects_oversized_combined_output(+ tmp_path: Path,+ stdout_bytes: int,+ stderr_bytes: int,+) -> None:+ limit = 4096++ assert managed_skills._bounded_subprocess_stdout(+ [+ sys.executable,+ "-c",+ (+ "import os; "+ f"os.write(1, b'x' * {stdout_bytes}); "+ f"os.write(2, b'x' * {stderr_bytes})"+ ),+ ],+ cwd=tmp_path,+ env=dict(os.environ),+ timeout=1,+ max_bytes=limit,+ ) is None+++def test_bounded_subprocess_capture_rejects_timeout(tmp_path: Path) -> None:+ assert managed_skills._bounded_subprocess_stdout(+ [sys.executable, "-c", "import time; time.sleep(1)"],+ cwd=tmp_path,+ env=dict(os.environ),+ timeout=0.01,+ max_bytes=4096,+ ) is None+++def test_claude_plugin_discovery_fails_closed_when_capture_fails(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ claude_home = home / ".claude"+ registry = claude_home / "plugins" / "installed_plugins.json"+ registry.parent.mkdir(parents=True)+ registry.write_text("{}", encoding="utf-8")+ monkeypatch.setattr(managed_skills.shutil, "which", lambda _: "/usr/bin/claude")++ monkeypatch.setattr(managed_skills, "_bounded_subprocess_stdout", lambda *args, **kwargs: None)++ assert resolve_skills(+ cwd,+ home=home,+ avibe_home=tmp_path / "avibe",+ codex_home=home / ".codex",+ claude_home=claude_home,+ xdg_config_home=home / ".config",+ builtin_snapshot_id="",+ ) == []+++def test_enabled_claude_plugin_skill_overrides_codex_system_default(+ tmp_path: Path,+ monkeypatch,+) -> None:+ home, cwd = _isolate_live_commands(monkeypatch, tmp_path)+ claude_home = home / ".claude"+ registry = claude_home / "plugins" / "installed_plugins.json"+ registry.parent.mkdir(parents=True)+ registry.write_text("{}", encoding="utf-8")+ plugin = tmp_path / "plugin-cache" / "formatter"+ plugin_skill = _write_skill(plugin / "skills", "shared", "shared", "Plugin")+ _write_skill(home / ".codex" / "skills" / ".system", "shared", "shared", "System")+ payload = json.dumps(+ [{"id": "formatter@example", "enabled": True, "installPath": str(plugin)}]+ ).encode()+ monkeypatch.setattr(managed_skills, "_bounded_subprocess_stdout", lambda *args, **kwargs: payload)++ skills = resolve_skills(+ cwd,+ home=home,+ avibe_home=tmp_path / "avibe",+ codex_home=home / ".codex",+ claude_home=claude_home,+ claude_cli_path="/opt/claude-custom",+ xdg_config_home=home / ".config",+ builtin_snapshot_id="",+ )++ assert len(skills) == 1+ assert 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(+ tmp_path: Path,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ old_file = _write_skill(source, "retired", "retired", "Retired", "Old\n")+ helper = old_file.parent / "run.sh"+ 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()+ if os.name != "nt":+ assert (old_snapshot / "retired" / "run.sh").stat().st_mode & 0o111++ for 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)++ 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()+++def test_publication_opens_snapshot_files_in_binary_mode_when_available(+ tmp_path: Path,+ monkeypatch,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ _write_skill(source, "alpha", "alpha", "Alpha", "Line one\r\nLine two\n")+ binary_flag = 1 << 29+ original_open = os.open+ destination_flags: list[int] = []++ def tracking_open(path, flags, mode=0o777, *, dir_fd=None):+ if flags & os.O_CREAT:+ destination_flags.append(flags)+ flags &= ~binary_flag+ if dir_fd is None:+ return original_open(path, flags, mode)+ return original_open(path, flags, mode, dir_fd=dir_fd)++ 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)++ assert destination_flags+ assert all(flags & binary_flag for flags in destination_flags)+ assert (destination / snapshot_id / "alpha" / "SKILL.md").read_bytes().endswith(+ b"Line one\r\nLine two\n"+ )++[email protected](os.name == "nt", reason="Windows has no POSIX executable mode")+def test_publication_preserves_each_executable_bit(tmp_path: Path) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ helper = _write_skill(source, "alpha", "alpha", "Alpha").parent / "run.sh"+ helper.write_text("echo alpha\n", encoding="utf-8")+ helper.chmod(0o744)++ snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)++ assert (destination / snapshot_id / "alpha" / "run.sh").stat().st_mode & 0o111 == 0o100+++def test_publication_ignores_install_generated_python_bytecode(tmp_path: Path) -> None:+ source = tmp_path / "source"+ _write_skill(source, "alpha", "alpha", "Alpha")+ cache = source / "alpha" / "scripts" / "__pycache__"+ cache.mkdir(parents=True)+ (cache / "helper.cpython-312.pyc").write_bytes(b"generated")+ (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)++ assert not (destination / snapshot_id / "alpha" / "scripts" / "__pycache__").exists()+++def test_publication_rejects_empty_companion_directories(tmp_path: Path) -> None:+ source = tmp_path / "source"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha")+ (skill_file.parent / "assets").mkdir()++ with pytest.raises(RuntimeError, match="must not be empty"):+ publish_builtin_skills(source_root=source, destination_root=tmp_path / "runtime")+++def test_concurrent_publication_reuses_one_snapshot(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(+ pool.map(+ lambda _: publish_builtin_skills(+ source_root=source,+ destination_root=destination,+ ),+ range(2),+ )+ )++ assert ids[0] == ids[1]+ assert (destination / ids[0] / "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.mkdir(parents=True)+ (staging / "partial").write_text("interrupted", encoding="utf-8")++ assert publish_builtin_skills(source_root=source, destination_root=destination) == snapshot_id+ 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:+ destination = tmp_path / "builtin-skills"+ invalid_source = tmp_path / "invalid"+ _write_skill(invalid_source, "CON", "con-skill", "Invalid path")+ with pytest.raises(RuntimeError, match="Windows-reserved"):+ publish_builtin_skills(source_root=invalid_source, destination_root=destination)++ 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")+ with pytest.raises(RuntimeError, match="not a directory|unavailable"):+ publish_builtin_skills(source_root=valid_source, destination_root=destination)+++def test_publication_rejects_duplicate_declared_builtin_names(tmp_path: Path) -> None:+ source = tmp_path / "source"+ _write_skill(source, "first", "shared-name", "First")+ _write_skill(source, "second", "shared-name", "Second")++ with pytest.raises(RuntimeError, match="unique declared names"):+ publish_builtin_skills(source_root=source, destination_root=tmp_path / "out")+++def test_publication_rejects_invalid_utf8_builtin_body(tmp_path: Path) -> None:+ source = tmp_path / "source"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha")+ skill_file.write_bytes(+ b"---\nname: alpha\ndescription: Alpha\n---\ninvalid:\xff\n"+ )++ with pytest.raises(RuntimeError, match="Built-in Skill is invalid"):+ publish_builtin_skills(source_root=source, destination_root=tmp_path / "out")++[email protected](os.name == "nt", reason="Windows cannot create forbidden fixture names")[email protected]("component", ["bad?name", "bad*name", 'bad"name', "bad\x01name"])+def test_publication_rejects_all_windows_forbidden_path_classes(+ tmp_path: Path,+ component: str,+) -> None:+ source = tmp_path / "source"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha")+ (skill_file.parent / component).write_text("invalid", encoding="utf-8")++ with pytest.raises(RuntimeError, match="not portable"):+ publish_builtin_skills(source_root=source, destination_root=tmp_path / "out")+++def test_publication_rejects_builtins_outside_runtime_catalog_limits(+ tmp_path: Path,+ monkeypatch,+) -> None:+ destination = tmp_path / "builtin-skills"++ too_many_entries = tmp_path / "too-many-entries"+ _write_skill(too_many_entries, "alpha", "alpha", "Alpha")+ (too_many_entries / "README.md").write_text("extra\n", encoding="utf-8")+ monkeypatch.setattr(managed_skills, "DISCOVERY_ROOT_MAX_CHILDREN", 1)+ with pytest.raises(RuntimeError, match="at most"):+ publish_builtin_skills(source_root=too_many_entries, destination_root=destination)++ oversized_frontmatter = tmp_path / "oversized-frontmatter" / "alpha" / "SKILL.md"+ oversized_frontmatter.parent.mkdir(parents=True)+ oversized_frontmatter.write_text(+ "---\nname: alpha\ndescription: Alpha\nunknown: "+ + "x" * managed_skills.FRONTMATTER_MAX_BYTES+ + "\n---\nBody\n",+ encoding="utf-8",+ )+ with pytest.raises(RuntimeError, match="invalid"):+ publish_builtin_skills(+ source_root=oversized_frontmatter.parents[1],+ destination_root=destination,+ )++ oversized_body = tmp_path / "oversized-body"+ _write_skill(+ oversized_body,+ "alpha",+ "alpha",+ "Alpha",+ "x" * (SKILL_BODY_MAX_BYTES + 1),+ )+ with pytest.raises(RuntimeError, match="invalid"):+ publish_builtin_skills(source_root=oversized_body, destination_root=destination)+++def test_publication_bounds_the_complete_builtin_tree(+ tmp_path: Path,+ monkeypatch,+) -> None:+ destination = tmp_path / "builtin-skills"+ too_many_entries = tmp_path / "too-many-tree-entries"+ skill_file = _write_skill(too_many_entries, "alpha", "alpha", "Alpha")+ references = skill_file.parent / "references"+ references.mkdir()+ (references / "one.md").write_text("one\n", encoding="utf-8")+ monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_ENTRIES", 3)+ with pytest.raises(RuntimeError, match="3 entries"):+ publish_builtin_skills(source_root=too_many_entries, destination_root=destination)++ monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_ENTRIES", 4096)+ too_many_bytes = tmp_path / "too-many-tree-bytes"+ byte_skill = _write_skill(too_many_bytes, "alpha", "alpha", "Alpha")+ (byte_skill.parent / "reference.md").write_bytes(b"x" * 32)+ monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_BYTES", 64)+ with pytest.raises(RuntimeError, match="64 bytes"):+ publish_builtin_skills(source_root=too_many_bytes, destination_root=destination)+++def test_publication_copies_only_the_bounded_enumeration(+ tmp_path: Path,+ monkeypatch,+) -> None:+ 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_entries+ source_enumerations = 0++ def enumerate_then_add_late_entry(root: Path):+ nonlocal source_enumerations+ entries = original_snapshot_entries(root)+ if Path(root) == source:+ source_enumerations += 1+ if source_enumerations == 3:+ (source / "late.bin").write_bytes(b"x" * 129)+ return entries++ monkeypatch.setattr(managed_skills, "_snapshot_entries", enumerate_then_add_late_entry)++ snapshot_id = publish_builtin_skills(source_root=source, destination_root=destination)++ assert source_enumerations == 3+ assert not (destination / snapshot_id / "late.bin").exists()+++def test_publication_charges_file_growth_at_copy_time(+ tmp_path: Path,+ monkeypatch,+) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "builtin-skills"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha")+ monkeypatch.setattr(managed_skills, "BUILTIN_TREE_MAX_BYTES", 128)+ original_snapshot_entries = managed_skills._snapshot_entries+ source_enumerations = 0++ def enumerate_then_grow_file(root: Path):+ nonlocal source_enumerations+ entries = original_snapshot_entries(root)+ if Path(root) == source:+ source_enumerations += 1+ if source_enumerations == 3:+ 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"):+ publish_builtin_skills(source_root=source, destination_root=destination)+++def test_builtin_source_ignores_an_unrelated_top_level_skills_directory(+ tmp_path: Path,+ monkeypatch,+) -> None:+ site_packages = tmp_path / "site-packages"+ fake_core = site_packages / "core"+ fake_core.mkdir(parents=True)+ unrelated = site_packages / "skills"+ unrelated.mkdir()+ (site_packages / "pyproject.toml").write_text(+ '[tool.unrelated]\nname = "avibe-os"\n',+ encoding="utf-8",+ )+ package = site_packages / "vibe"+ packaged_source = package / "builtin_skills_source"+ packaged_source.mkdir(parents=True)+ init_file = package / "__init__.py"+ init_file.write_text("", encoding="utf-8")++ import vibe++ monkeypatch.setattr(managed_skills, "__file__", str(fake_core / "managed_skills.py"))+ monkeypatch.setattr(vibe, "__file__", str(init_file))++ assert managed_skills.builtin_skills_source() == packaged_source+++def test_workbench_management_acl_does_not_narrow_runtime_catalog(+ tmp_path: Path, monkeypatch+) -> None:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ avibe_home = home / ".avibe"+ snapshot_id = "d" * 64+ 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")+ _write_skill(cwd / ".agents" / "skills", "project", "project", "Project")+ skills = resolve_skills(cwd)++ assert [skill.name for skill in skills] == ["builtin", "project"]++[email protected](os.name == "nt", reason="symlink fixture requires POSIX semantics")+def test_publication_rejects_symlinks(tmp_path: Path) -> None:+ source = tmp_path / "source"+ skill_file = _write_skill(source, "alpha", "alpha", "Alpha")+ (skill_file.parent / "linked").symlink_to(skill_file)++ with pytest.raises(RuntimeError, match="not a directory or regular file"):+ 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:+ 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" * 64+ monkeypatch.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()+ ),+ SKILL_HOME_ENV: str(home.resolve()),+ SKILL_CODEX_HOME_ENV: str((home / ".codex").resolve()),+ SKILL_CLAUDE_HOME_ENV: str((home / ".claude").resolve()),+ SKILL_XDG_CONFIG_HOME_ENV: str((home / ".config").resolve()),+ }+++def test_managed_skill_environment_binds_valid_project_base(tmp_path: Path) -> None:+ project = tmp_path / "project"+ working_directory = project / "child"+ working_directory.mkdir(parents=True)++ env = managed_skill_environment(working_directory, project_base=project)++ assert env[SKILL_WORKING_DIR_ENV] == str(working_directory.resolve())+ assert env[SKILL_PROJECT_BASE_ENV] == str(project.resolve())+ assert SKILL_PROJECT_BASE_ENV not in managed_skill_environment(+ working_directory,+ project_base=tmp_path / "other",+ )+++def test_managed_skill_environment_binds_configured_claude_cli_path(+ tmp_path: Path,+) -> None:+ env = managed_skill_environment(+ tmp_path,+ claude_cli_path="~/tools/claude-custom",+ )++ assert env[SKILL_CLAUDE_CLI_PATH_ENV] == str(+ Path("~/tools/claude-custom").expanduser()+ )+++def test_managed_skill_environment_can_retain_an_explicit_builtin_snapshot(+ 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++ env = managed_skill_environment(+ working_directory,+ builtin_snapshot_id=snapshot_id,+ builtin_snapshot_root=snapshot_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+++def 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+ _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"))++ assert [skill.name for skill in resolve_skills(cwd)] == ["builtin"]diff --git a/tests/test_memory_distribution.py b/tests/test_memory_distribution.pyindex f4a07e017..63318af13 100644--- a/tests/test_memory_distribution.py+++ b/tests/test_memory_distribution.py@@ -479,6 +479,92 @@ def test_built_distributions_have_independent_contents_and_exact_peer_metadata()assert str(build_requirement.specifier) == ">=0.11.1"+def _assert_core_distribution_mirrors_builtin_skills(+ distribution: Path,+ *,+ environment: Path,+ tmp_path: Path,+) -> None:+ 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")+ _run(+ python,+ "-m",+ "pip",+ "install",+ "--disable-pip-version-check",+ str(distribution),+ cwd=tmp_path,+ )+ avibe_home = tmp_path / "avibe-home"+ result = subprocess.run(+ [+ str(python),+ "-c",+ (+ "from core.managed_skills import "+ "builtin_skills_source, load_skill, prepare_builtin_skills; "+ "source = builtin_skills_source(); "+ "assert source.name == 'builtin_skills_source'; "+ "snapshot = prepare_builtin_skills(); "+ "skill = load_skill('use-avibe'); "+ "assert skill is not None and skill.body; "+ "assert skill.directory.name == 'use-avibe'; "+ "print(snapshot)"+ ),+ ],+ check=True,+ capture_output=True,+ text=True,+ env={**os.environ, "AVIBE_HOME": str(avibe_home)},+ cwd=tmp_path,+ )++ snapshot_id = result.stdout.strip()+ assert len(snapshot_id) == 64+ expected = {+ path.relative_to(ROOT / "skills").as_posix()+ for path in (ROOT / "skills").rglob("*")+ if path.is_file() and "__pycache__" not in path.parts+ }+ mirrored = {+ path.relative_to(avibe_home / "builtin-skills" / snapshot_id).as_posix()+ for path in (avibe_home / "builtin-skills" / snapshot_id).rglob("*")+ if path.is_file()+ }+ assert mirrored == expected+ if os.name != "nt":+ for relative in expected:+ source_mode = (ROOT / "skills" / relative).stat().st_mode & 0o111+ mirrored_mode = (+ avibe_home / "builtin-skills" / snapshot_id / relative+ ).stat().st_mode & 0o111+ assert mirrored_mode == source_mode+++def test_core_wheel_installs_and_mirrors_builtin_skills_without_a_checkout(tmp_path: Path) -> None:+ core_wheel = _wheel_path("AVIBE_CORE_WHEEL")+ _assert_core_distribution_mirrors_builtin_skills(+ core_wheel,+ environment=tmp_path / "builtin-skills-wheel",+ tmp_path=tmp_path,+ )+++def test_core_sdist_installs_and_mirrors_builtin_skills_without_a_checkout(tmp_path: Path) -> None:+ core_sdist = _sdist_path(_wheel_path("AVIBE_CORE_WHEEL"), "avibe_os")+ _assert_core_distribution_mirrors_builtin_skills(+ core_sdist,+ environment=tmp_path / "builtin-skills-sdist",+ tmp_path=tmp_path,+ )++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")diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 5edfbb239..a6a314645 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -688,7 +688,11 @@ def test_opencode_restored_ack_preserves_wechat_typing_context():assert wechat.sent == [("clear_typing", "wechat", "user-1", "ctx-1")]-def test_opencode_prompt_disables_question_tool_for_all_platforms():+def test_opencode_prompt_disables_question_tool_for_all_platforms(monkeypatch):+ 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)calls = []active_polls = []active_poll_updates = []@@ -697,6 +701,16 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():configured_overlays = []active_registrations = []released_reservations = []+ prompt_skill_cwds = []++ def build_prompt(**kwargs):+ prompt_skill_cwds.append(kwargs.get("skills_cwd"))+ return "system prompt"++ monkeypatch.setattr(+ "modules.agents.opencode.agent.build_system_prompt_injection",+ build_prompt,+ )class _Server:async def configure_model_hub_overlay(self, overlay):@@ -853,7 +867,7 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():asyncio.run(_run())assert calls- assert calls[0]["tools"] == {"question": False}+ assert calls[0]["tools"] == {"question": False, "skill": False}assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}assert calls[0]["reasoning_effort"] == "high"assert calls[0]["attempt_id"] == ATTEMPT_ID@@ -866,6 +880,39 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():assert isinstance(active_poll_updates[0][1]["prompt_started_at"], float)steering_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}+ assert prompt_skill_cwds == ["/tmp/work"]++ binding_failures = []++ def fail_binding(*args, **kwargs):+ raise OSError("binding unavailable")++ async def record_failure(context, error_text):+ binding_failures.append(error_text)++ async def emit_failure(*args, **kwargs):+ return None++ monkeypatch.setattr(+ "modules.agents.opencode.agent.bind_caller_context_session",+ fail_binding,+ )+ monkeypatch.setattr(+ "modules.agents.opencode.agent.emit_backend_failure",+ emit_failure,+ )+ agent.record_model_hub_native_failure = record_failure+ calls.clear()++ asyncio.run(_run())++ assert calls+ assert calls[0]["tools"] == {"question": False, "skill": False}+ assert prompt_skill_cwds == ["/tmp/work", None]+ assert binding_failures == []def test_opencode_clears_default_variant_for_non_reasoning_model():diff --git a/tests/test_opencode_caller_context.py b/tests/test_opencode_caller_context.pyindex a948faa58..101c5e9de 100644--- a/tests/test_opencode_caller_context.py+++ b/tests/test_opencode_caller_context.py@@ -1,7 +1,10 @@from __future__ import annotations+from concurrent.futures import ThreadPoolExecutor+from datetime import datetime, timedelta, timezoneimport jsonfrom pathlib import Path+import threadingfrom core import git_runtimefrom modules.agents.opencode import caller_context as bridge@@ -41,6 +44,7 @@ def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:},base_env={"PATH": "/usr/bin"},working_dir=tmp_path / "workspace",+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path / "workspace")},)assert ok is True@@ -52,21 +56,92 @@ def test_bind_session_writes_env_binding(tmp_path: Path, monkeypatch) -> None:"AVIBE_CALLER_SOURCE": "agent_run","AVIBE_CALLER_BACKEND": "opencode","AVIBE_NATIVE_SESSION_ID": "oc-session",+ "AVIBE_SKILL_WORKING_DIR": str(tmp_path / "workspace"),}assert entry["caller_context"]["session_id"] == "ses123"+ assert isinstance(entry["binding_token"], str)assert "expires_at" in entry-def test_bind_session_skips_without_resolved_caller_context(tmp_path: Path, monkeypatch) -> None:+def test_prune_sessions_keeps_unexpired_released_entries() -> None:+ now = datetime(2026, 9, 2, tzinfo=timezone.utc)+ sessions = {+ "current": {"expires_at": (now + timedelta(hours=1)).isoformat()},+ "expired": {"expires_at": (now - timedelta(seconds=1)).isoformat()},+ "legacy": {"updated_at": "2026-09-02T00:00:00+00:00"},+ }++ assert bridge._prune_sessions(sessions, now) == {+ "current": sessions["current"],+ "legacy": sessions["legacy"],+ }+++def test_plugin_keeps_the_released_expiry_protocol() -> None:+ assert "binding.expires_at" in bridge.PLUGIN_SOURCE+ assert "execFileSync" not in bridge.PLUGIN_SOURCE+++def test_new_binding_preserves_an_unexpired_released_binding(+ tmp_path: Path,+ monkeypatch,+) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ path = bridge.binding_path()+ bridge._write_bindings(+ path,+ {+ "version": 1,+ "sessions": {+ "released-session": {+ "env": {"AVIBE_SESSION_ID": "released"},+ "updated_at": bridge._utc_now().isoformat(),+ "expires_at": (bridge._utc_now() + timedelta(hours=1)).isoformat(),+ }+ },+ },+ )++ assert bridge.bind_session(+ "new-session",+ None,+ base_env={},+ working_dir=tmp_path,+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path)},+ )++ sessions = json.loads(path.read_text(encoding="utf-8"))["sessions"]+ assert set(sessions) == {"released-session", "new-session"}+++def test_binding_write_does_not_require_posix_fchmod(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.delattr(bridge.os, "fchmod")+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)assert bridge.bind_session("oc-session",- {"platform": "slack"},- base_env={"PATH": "/usr/bin"},- working_dir=tmp_path / "workspace",- ) is False+ None,+ base_env={},+ working_dir=tmp_path,+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path)},+ )+++def test_bind_session_skips_without_resolved_caller_context(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)++ assert (+ bridge.bind_session(+ "oc-session",+ {"platform": "slack"},+ base_env={"PATH": "/usr/bin"},+ working_dir=tmp_path / "workspace",+ )+ is False+ )assert not bridge.binding_path().exists()@@ -85,12 +160,15 @@ def test_bind_session_writes_vendored_path_without_caller_context(monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", inject_git)- assert bridge.bind_session(- "oc-session",- {"platform": "slack"},- base_env={"PATH": ""},- working_dir=tmp_path / "workspace",- ) is True+ assert (+ bridge.bind_session(+ "oc-session",+ {"platform": "slack"},+ base_env={"PATH": ""},+ working_dir=tmp_path / "workspace",+ )+ is True+ )data = json.loads(bridge.binding_path().read_text(encoding="utf-8"))entry = data["sessions"]["oc-session"]assert entry["env"] == {"PATH": "/managed/git/bin"}@@ -122,3 +200,134 @@ def test_bind_session_clears_stale_path_when_git_override_disappears(assert bridge.bind_session("oc-session", {"platform": "slack"}, **kwargs) is Falsedata = json.loads(bridge.binding_path().read_text(encoding="utf-8"))assert "oc-session" not in data["sessions"]+++def test_unbind_session_removes_only_matching_turn_binding(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ kwargs = {+ "base_env": {"PATH": "/usr/bin"},+ "working_dir": tmp_path / "workspace",+ "extra_env": {"AVIBE_SKILL_WORKING_DIR": str(tmp_path / "workspace")},+ }+ assert bridge.bind_session("oc-session", {}, binding_token="new-turn", **kwargs) is True++ assert bridge.unbind_session("oc-session", binding_token="old-turn") is False+ assert "oc-session" in json.loads(bridge.binding_path().read_text(encoding="utf-8"))["sessions"]+ assert bridge.unbind_session("oc-session", binding_token="new-turn") is True+ assert "oc-session" not in json.loads(bridge.binding_path().read_text(encoding="utf-8"))["sessions"]+++def test_conditional_bind_cannot_replace_a_newer_turn(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ kwargs = {+ "base_env": {"PATH": "/usr/bin"},+ "working_dir": tmp_path / "workspace",+ "extra_env": {"AVIBE_SKILL_WORKING_DIR": str(tmp_path / "workspace")},+ }+ assert bridge.bind_session(+ "oc-session",+ {},+ binding_token="new-turn",+ **kwargs,+ )++ assert not bridge.bind_session(+ "oc-session",+ {},+ binding_token="old-restored-turn",+ replace_existing=False,+ **kwargs,+ )+ entry = json.loads(bridge.binding_path().read_text(encoding="utf-8"))["sessions"][+ "oc-session"+ ]+ assert entry["binding_token"] == "new-turn"+++def test_refresh_session_extends_only_the_matching_live_binding(+ tmp_path: Path,+ monkeypatch,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ initial = datetime(2026, 9, 2, tzinfo=timezone.utc)+ monkeypatch.setattr(bridge, "_utc_now", lambda: initial)+ assert bridge.bind_session(+ "oc-session",+ {},+ base_env={"PATH": "/usr/bin"},+ working_dir=tmp_path,+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path)},+ binding_token="owned-turn",+ )+ before = json.loads(bridge.binding_path().read_text(encoding="utf-8"))["sessions"][+ "oc-session"+ ]++ monkeypatch.setattr(bridge, "_utc_now", lambda: initial + timedelta(hours=1))+ assert bridge.refresh_session("oc-session", binding_token="other-turn") is False+ assert bridge.refresh_session("oc-session", binding_token="owned-turn") is True++ after = json.loads(bridge.binding_path().read_text(encoding="utf-8"))["sessions"][+ "oc-session"+ ]+ assert after["env"] == before["env"]+ assert datetime.fromisoformat(after["expires_at"]) == initial + timedelta(hours=25)+++def test_binding_operations_can_target_an_adopted_server_path(+ tmp_path: Path,+ monkeypatch,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "new-avibe-home"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ adopted_path = tmp_path / "old-avibe-home" / "runtime" / "opencode_caller_context.json"++ assert bridge.bind_session(+ "oc-session",+ {},+ base_env={"PATH": "/usr/bin"},+ working_dir=tmp_path,+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path)},+ binding_token="adopted-turn",+ path=adopted_path,+ )+ assert adopted_path.is_file()+ assert not bridge.binding_path().exists()+ assert bridge.refresh_session(+ "oc-session",+ binding_token="adopted-turn",+ path=adopted_path,+ )+ assert bridge.unbind_session(+ "oc-session",+ binding_token="adopted-turn",+ path=adopted_path,+ )+ assert "oc-session" not in json.loads(adopted_path.read_text(encoding="utf-8"))["sessions"]+++def test_concurrent_bindings_preserve_every_session(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "avibe"))+ monkeypatch.setattr(git_runtime, "prepend_vendored_git_to_path", lambda *args, **kwargs: False)+ barrier = threading.Barrier(2)++ def bind(session_id: str) -> bool:+ barrier.wait()+ return bridge.bind_session(+ session_id,+ {},+ base_env={"PATH": "/usr/bin"},+ working_dir=tmp_path / "workspace",+ extra_env={"AVIBE_SKILL_WORKING_DIR": str(tmp_path / "workspace")},+ binding_token=f"token-{session_id}",+ )++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(bind, ("session-a", "session-b")))++ assert results == [True, True]+ data = json.loads(bridge.binding_path().read_text(encoding="utf-8"))+ assert set(data["sessions"]) == {"session-a", "session-b"}diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex ff226b447..cab6b6814 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -84,6 +84,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enclass _PollLoop:async def run_restored_poll_loop(self, poll_info):+ active_polls.pop(poll_info.opencode_session_id, None)return Noneasync def remove_restored_ack(self, poll_info):@@ -109,6 +110,7 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enreturn dict(active_polls)def remove_active_poll(self, session_id):+ active_polls.pop(session_id, None)removed.append(session_id)class _Controller:@@ -149,6 +151,174 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enreturn agent, status_writes, removed, request_sessions+def test_restore_rebinds_persisted_remote_caller_context(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",+ "AVIBE_CALLER_RESOURCE_CONTEXT": '{"sub":"user-1"}',+ "IGNORED_ENV": "must-not-pass",+ },+ "opencode_managed_skill_project_base": "/tmp",+ "opencode_managed_skill_builtin_snapshot": {+ "id": "d" * 64,+ "root": "/old-avibe-home/builtin-skills/" + "d" * 64,+ },+ }+ agent, _, _, _ = _build_agent({"oc-1": poll})+ binding_path = "/old-avibe-home/runtime/opencode_caller_context.json"+ agent._test_server.caller_context_binding_path = lambda: binding_path+ bound: list[dict] = []+ unbound: list[tuple[str, str, str]] = []++ def bind(session_id, payload, **kwargs):+ bound.append({"session_id": session_id, "payload": payload, **kwargs})+ return True++ def unbind(session_id, *, binding_token, path):+ unbound.append((session_id, binding_token, path))+ return True++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr("modules.agents.opencode.agent.unbind_caller_context_session", unbind)++ 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 len(bound) == 1+ assert bound[0]["session_id"] == "oc-1"+ assert bound[0]["payload"] is None+ assert bound[0]["path"] == binding_path+ assert 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 bound[0]["extra_env"]["AVIBE_BUILTIN_SKILLS_ROOT"] == (+ "/old-avibe-home/builtin-skills/" + "d" * 64+ )+ assert "IGNORED_ENV" not in bound[0]["extra_env"]+ assert unbound == [("oc-1", bound[0]["binding_token"], binding_path)]+++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})+ attempts = 0++ def fail_bind(*_args, **_kwargs):+ nonlocal attempts+ attempts += 1+ raise OSError("temporary binding failure")++ monkeypatch.setattr(+ "modules.agents.opencode.agent.bind_caller_context_session",+ fail_bind,+ )++ 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 attempts == 3+ assert removed == []+++def test_restore_retries_binding_for_the_active_poll_lifetime(monkeypatch) -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ agent, _, _, _ = _build_agent({"oc-1": poll})+ attempts = 0+ unbound: list[str] = []++ def bind(*_args, **_kwargs):+ nonlocal attempts+ attempts += 1+ if attempts < 4:+ raise OSError("temporary binding failure")+ return True++ class _WaitForBindingPollLoop:+ async def run_restored_poll_loop(self, _poll_info):+ for _ in range(100):+ if attempts >= 4:+ agent.sessions.remove_active_poll("oc-1")+ return+ await asyncio.sleep(0)+ raise AssertionError("restored binding was not retried")++ async def remove_restored_ack(self, _poll_info):+ return None++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr(+ "modules.agents.opencode.agent.unbind_caller_context_session",+ lambda session_id, **_kwargs: unbound.append(session_id) or True,+ )+ monkeypatch.setattr(+ "modules.agents.opencode.agent._CALLER_CONTEXT_BINDING_RETRY_SECONDS",+ 0,+ )+ agent._poll_loop = _WaitForBindingPollLoop()++ 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 attempts == 4+ assert unbound == ["oc-1"]+++def test_restore_delayed_binding_does_not_replace_a_newer_turn(monkeypatch) -> None:+ poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")+ agent, _, _, _ = _build_agent({"oc-1": poll})+ attempts: list[dict] = []++ def bind(*_args, **kwargs):+ attempts.append(kwargs)+ if len(attempts) <= 3:+ raise OSError("temporary binding failure")+ return False++ class _WaitForConditionalAttemptPollLoop:+ async def run_restored_poll_loop(self, _poll_info):+ for _ in range(100):+ if len(attempts) >= 4:+ agent.sessions.remove_active_poll("oc-1")+ return+ await asyncio.sleep(0)+ raise AssertionError("restored binding was not retried")++ async def remove_restored_ack(self, _poll_info):+ return None++ monkeypatch.setattr("modules.agents.opencode.agent.bind_caller_context_session", bind)+ monkeypatch.setattr(+ "modules.agents.opencode.agent._CALLER_CONTEXT_BINDING_RETRY_SECONDS",+ 0,+ )+ agent._poll_loop = _WaitForConditionalAttemptPollLoop()++ 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 len(attempts) == 4+ assert "replace_existing" not in attempts[2]+ assert attempts[3]["replace_existing"] is False++def test_restore_registration_failure_terminalizes_exact_owner_before_release() -> None:poll = _make_poll(platform="avibe", base_session_id="ses_wb", opencode_session_id="oc-1")poll.processing_indicator = {@@ -320,7 +490,7 @@ def test_restored_poll_exposes_the_persisted_guarded_steering_owner() -> None:},"reasoning_effort": "high","system": "restored system prompt",- "tools": {"question": False},+ "tools": {"question": False, "skill": False},}]diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex f9d67dbf5..351d8e66e 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -2,6 +2,7 @@ import asyncioimport importlib.utilimport ioimport json+import osimport sysimport tempfileimport types@@ -17,6 +18,7 @@ from modules.agents.opencode.utils import (resolve_opencode_allowed_providers,)+MODULE_PATH = Path(__file__).resolve().parents[1] / "modules" / "agents" / "opencode" / "server.py"@@ -131,17 +133,20 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._clear_pid_file = Mock() # type: ignore[method-assign]manager._apply_resource_governance = Mock() # type: ignore[method-assign]terminate = AsyncMock()+ create_process = AsyncMock(return_value=process)+ user_config = '{"permission":"ask"}'with (patch.object(SERVER_MODULE.asyncio,"create_subprocess_exec",- AsyncMock(return_value=process),+ create_process,),patch.object(SERVER_MODULE.asyncio, "sleep", AsyncMock()),patch.object(SERVER_MODULE.time, "monotonic", side_effect=[0.0, 0.0, 61.0]),patch.object(SERVER_MODULE, "server_environment", return_value={}),patch.object(SERVER_MODULE, "terminate_process_tree", terminate),+ patch.dict(os.environ, {"OPENCODE_CONFIG_CONTENT": user_config}),):with self.assertRaisesRegex(RuntimeError, "failed to start within 60s"):await manager._start_server()@@ -155,6 +160,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(manager._clear_pid_file.call_count, 2)self.assertIsNone(manager._process)self.assertIsNone(manager._process_loop)+ self.assertEqual(create_process.await_args.kwargs["env"]["OPENCODE_CONFIG_CONTENT"], user_config)def test_terminate_instance_sync_stops_unadopted_managed_server(self):with tempfile.TemporaryDirectory() as tmp_dir:@@ -521,6 +527,35 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):manager._start_server.assert_not_awaited()self.assertTrue(manager._caller_context_plugin_refresh_pending)+ async def test_ensure_running_preserves_an_adopted_absolute_caller_context_path(self):+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ adopted_path = "/old-avibe-home/runtime/opencode_caller_context.json"+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]+ manager._cleanup_orphaned_managed_server = AsyncMock() # type: ignore[method-assign]+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]+ manager._start_server = AsyncMock() # type: ignore[method-assign]+ manager._read_pid_file = lambda: { # type: ignore[method-assign]+ "pid": 123,+ "port": 4096,+ "caller_context_path": adopted_path,+ "active_run_sessions": ["ses-active"],+ }+ manager._get_pid_command = lambda pid: "opencode serve --port=4096" # type: ignore[method-assign]+ manager._caller_context_path = lambda: "/new-avibe-home/runtime/opencode_caller_context.json" # type: ignore[method-assign]++ with patch.object(+ SERVER_MODULE,+ "ensure_plugin_installed",+ return_value=types.SimpleNamespace(path=Path("/tmp/plugin.js"), changed=False),+ ):+ base_url = await manager.ensure_running()++ self.assertEqual(base_url, "http://127.0.0.1:4096")+ self.assertEqual(manager.caller_context_binding_path(), Path(adopted_path))+ manager._restart_for_auth_refresh_locked.assert_not_awaited()+ manager._start_server.assert_not_awaited()+ self.assertFalse(manager._caller_context_plugin_refresh_pending)+async def test_mark_run_active_persists_pid_file_active_sessions(self):manager = OpenCodeServerManager(binary="opencode", port=4096)with tempfile.TemporaryDirectory() as tmp_dir:diff --git a/tests/test_skill_cli.py b/tests/test_skill_cli.pynew file mode 100644index 000000000..22d54b5fd--- /dev/null+++ b/tests/test_skill_cli.py@@ -0,0 +1,77 @@+from pathlib import Path+from types import SimpleNamespace++from core import managed_skills+from vibe.cli import build_parser, cmd_skill+++def _write_skill(root: Path, name: str, description: str, body: str) -> Path:+ skill_dir = root / name+ skill_dir.mkdir(parents=True)+ skill_file = skill_dir / "SKILL.md"+ skill_file.write_text(+ f"---\nname: {name}\ndescription: {description}\n---\n{body}",+ encoding="utf-8",+ )+ return skill_file+++def _isolate_catalog(monkeypatch, tmp_path: Path) -> Path:+ home = tmp_path / "home"+ cwd = tmp_path / "project"+ cwd.mkdir()+ empty_builtins = tmp_path / "builtins"+ empty_builtins.mkdir()+ monkeypatch.chdir(cwd)+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: home))+ monkeypatch.setenv("AVIBE_HOME", str(home / ".avibe"))+ monkeypatch.setattr(managed_skills, "builtin_skills_source", lambda: empty_builtins)+ return cwd+++def test_skill_list_and_load_follow_the_text_protocol(monkeypatch, tmp_path, capsys):+ cwd = _isolate_catalog(monkeypatch, tmp_path)+ skill_file = _write_skill(+ cwd / ".agents" / "skills",+ "docs",+ "Read project docs.",+ "Use references/guide.md\n",+ )++ assert cmd_skill(SimpleNamespace(skill_command="list", page=1)) == 0+ assert capsys.readouterr().out == "- docs: Read project docs.\n"++ assert cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0+ output = capsys.readouterr().out+ assert output == (+ f'<skill_content name="docs" directory="{skill_file.parent.resolve()}">\n'+ "Use references/guide.md\n"+ "</skill_content>\n"+ )+++def test_skill_load_failure_has_empty_stdout(monkeypatch, tmp_path, capsys):+ _isolate_catalog(monkeypatch, tmp_path)++ assert cmd_skill(SimpleNamespace(skill_command="load", name="missing")) == 1+ captured = capsys.readouterr()+ assert captured.out == ""+ assert captured.err == "Skill not found: missing\n"+++def test_skill_load_parser_accepts_the_canonical_separator_form():+ args = build_parser().parse_args(["skill", "load", "--", "pdf-processing"])++ assert args.skill_command == "load"+ assert args.name == "pdf-processing"+++def test_skill_cli_localizes_errors(monkeypatch, tmp_path, capsys):+ _isolate_catalog(monkeypatch, tmp_path)+ monkeypatch.setattr("vibe.cli._configured_cli_language", lambda: "zh")++ assert cmd_skill(SimpleNamespace(skill_command="load", name="missing")) == 1++ captured = capsys.readouterr()+ assert captured.out == ""+ assert captured.err == "未找到 Skill:missing\n"diff --git a/tests/test_skills_service.py b/tests/test_skills_service.pyindex c230a1da4..9aaa745ef 100644--- a/tests/test_skills_service.py+++ b/tests/test_skills_service.py@@ -132,12 +132,38 @@ def test_list_global_uses_g_no_cwd(monkeypatch):assert rec.calls[0]["cwd"] is None-def test_list_project_uses_p_and_cwd_and_agents(monkeypatch):+def test_mixed_runtime_catalog_does_not_grant_global_skills_to_project_editor(+ monkeypatch,+ tmp_path,+) -> None:+ engine = _skills_engine(monkeypatch, tmp_path)+ monkeypatch.setattr(skills, "_project_role_allows_editor", lambda context, project_id: True)+ try:+ filtered = skills._filter_skill_listing(+ {+ "ok": True,+ "skills": [+ {"name": "project-skill", "scope": "project"},+ {"name": "global-skill", "scope": "global", "agents": ["codex"]},+ ],+ },+ scope="all",+ project_dir=str(tmp_path / "project"),+ project_id="project-1",+ backends=["codex"],+ user_context=_organization_context("member-1", instance_role="viewer"),+ )+ finally:+ engine.dispose()++ assert [row["name"] for row in filtered["skills"]] == ["project-skill"]+++def test_list_project_uses_p_and_cwd_and_ignores_legacy_backend_filter(monkeypatch):rec = _Recorder({"ok": True, "skills": []})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.list_skills("askill", scope="project", project_dir="/p", backends=["claude", "codex"]))- # list supports -p; agents expand to askill ids under ONE variadic -a.- assert rec.calls[0]["args"] == ["list", "-p", "-a", "claude-code", "codex"]+ assert rec.calls[0]["args"] == ["list", "-p"]assert rec.calls[0]["cwd"] == "/p"@@ -145,7 +171,7 @@ def test_add_global_all(monkeypatch):rec = _Recorder({"ok": True, "action": "install"})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.add_skill("askill", "gh:o/r", scope="global", backends=["opencode"], all_skills=True))- assert rec.calls[0]["args"] == ["add", "gh:o/r", "-g", "-a", "opencode", "--all", "-y"]+ assert rec.calls[0]["args"] == ["add", "gh:o/r", "-g", "-a", "claude-code", "opencode", "codex", "--all", "-y"]def test_add_reports_nothing_installed_when_no_skill_matched(monkeypatch):@@ -180,7 +206,7 @@ def test_add_project_has_no_p_flag_and_uses_cwd(monkeypatch):rec = _Recorder({"ok": True, "action": "install"})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.add_skill("askill", "./pkg", scope="project", project_dir="/p", copy=True))- assert rec.calls[0]["args"] == ["add", "./pkg", "--copy", "-y"]+ assert rec.calls[0]["args"] == ["add", "./pkg", "-a", "claude-code", "opencode", "codex", "--copy", "-y"]assert rec.calls[0]["cwd"] == "/p"@@ -188,7 +214,7 @@ def test_add_with_skill_selector(monkeypatch):rec = _Recorder({"ok": True, "action": "install"})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.add_skill("askill", "./pkg", scope="project", project_dir="/p", skill="formatter", backends=["opencode"]))- assert rec.calls[0]["args"] == ["add", "./pkg", "-a", "opencode", "--skill", "formatter", "-y"]+ assert rec.calls[0]["args"] == ["add", "./pkg", "-a", "claude-code", "opencode", "codex", "--skill", "formatter", "-y"]def test_preview_uses_list_flag(monkeypatch):@@ -203,7 +229,7 @@ def test_remove_project_no_p_flag(monkeypatch):rec = _Recorder({"ok": True})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.remove_skill("askill", "pdf-tools", scope="project", project_dir="/p", backends=["claude"]))- assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-a", "claude-code"]+ assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-a", "claude-code", "opencode", "codex"]assert rec.calls[0]["cwd"] == "/p"@@ -211,7 +237,7 @@ def test_remove_global(monkeypatch):rec = _Recorder({"ok": True})monkeypatch.setattr(skills, "_run_askill", rec)_run(skills.remove_skill("askill", "pdf-tools", scope="global"))- assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-g"]+ assert rec.calls[0]["args"] == ["remove", "pdf-tools", "-g", "-a", "claude-code", "opencode", "codex"]assert rec.calls[0]["cwd"] is None@@ -629,7 +655,7 @@ def test_active_org_members_mutate_skills_without_owner_preflight(monkeypatch, t)) == {"ok": True}assert [call["args"] for call in member_recorder.calls] == [- ["remove", "private-skill", "-g"]+ ["remove", "private-skill", "-g", "-a", "claude-code", "opencode", "codex"]]with engine.connect() as connection:assert resource_access_service.get_resource_policy(@@ -685,6 +711,8 @@ def test_active_org_members_mutate_skills_without_owner_preflight(monkeypatch, t"gh:owner/repo","-g","-a",+ "claude-code",+ "opencode","codex","--skill","private-skill",@@ -695,7 +723,7 @@ def test_active_org_members_mutate_skills_without_owner_preflight(monkeypatch, tengine.dispose()-def test_remove_skill_deletes_only_policies_for_removed_backends(monkeypatch, tmp_path) -> None:+def test_remove_skill_deletes_all_legacy_backend_policies(monkeypatch, tmp_path) -> None:engine = _skills_engine(monkeypatch, tmp_path)try:with engine.begin() as connection:@@ -732,10 +760,10 @@ def test_remove_skill_deletes_only_policies_for_removed_backends(monkeypatch, tmassert result["ok"] is Trueassert [call["args"] for call in recorder.calls] == [- ["remove", "shared-skill", "-g", "-a", "codex", "claude-code"]+ ["remove", "shared-skill", "-g", "-a", "claude-code", "opencode", "codex"]]assert codex_policy is None- assert claude_policy is not None+ assert claude_policy is None@pytest.mark.parametrize("operation", ["add", "remove", "update"])@@ -857,7 +885,7 @@ def test_active_org_member_can_replace_installed_legacy_skill(monkeypatch, tmp_pengine.dispose()assert [call["args"] for call in member_recorder.calls] == [- ["add", "gh:owner/repo", "-g", "-a", "codex", "--skill", "legacy-skill", "-y"],+ ["add", "gh:owner/repo", "-g", "-a", "claude-code", "opencode", "codex", "--skill", "legacy-skill", "-y"],]assert result == install_resultassert policy is not None@@ -894,7 +922,7 @@ def test_instance_owner_skill_add_does_not_require_organization_membership(assert result == install_resultassert [call["args"] for call in recorder.calls] == [- ["add", "gh:owner/repo", "-g", "-a", "codex", "--skill", "legacy-skill", "-y"]+ ["add", "gh:owner/repo", "-g", "-a", "claude-code", "opencode", "codex", "--skill", "legacy-skill", "-y"]]diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex 4799382f6..7a14e950d 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -5264,7 +5264,7 @@ def test_native_bind_by_id_idempotent_rebind_cannot_resurrect_an_archived_sessio_UPDATE_SESSION_FAST_PATH_SELECT = ("SELECT agent_sessions.id, agent_sessions.scope_id, agent_sessions.agent_backend, ""agent_sessions.native_session_id, agent_sessions.agent_status, "- "agent_sessions.metadata_json, agent_sessions.status FROM agent_sessions "+ "agent_sessions.workdir, agent_sessions.metadata_json, agent_sessions.status FROM agent_sessions ""WHERE agent_sessions.id = ?")diff --git a/ui/src/components/workbench/SkillsPage.tsx b/ui/src/components/workbench/SkillsPage.tsxindex 2c4f18378..f0d2ca67a 100644--- a/ui/src/components/workbench/SkillsPage.tsx+++ b/ui/src/components/workbench/SkillsPage.tsx@@ -1,15 +1,13 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { ChevronDown, Compass, Download, Funnel, Info, Loader2, Lock, Plus, RefreshCw, Search, Terminal, WandSparkles } from 'lucide-react';+import { Compass, Download, Info, Loader2, Lock, Plus, RefreshCw, Search, Terminal, WandSparkles } from 'lucide-react';import clsx from 'clsx';import { useApi } from '../../context/ApiContext';import type { SkillBrief, SkillCheckItem, SkillScope, WorkbenchProject } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';-import { BACKEND_LABEL, BACKEND_ORDER, backendsFromAgents, type Backend } from '../../lib/backendAccent';import { Button } from '../ui/button';import { SegmentedRadio } from '../ui/segmented';-import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { WorkbenchPageHeader } from './WorkbenchPageHeader';import { CapabilityTabs } from './CapabilityTabs';import { SkillRow } from './skills/SkillRow';@@ -40,9 +38,7 @@ export const SkillsPage: React.FC = () => {const [installingAskill, setInstallingAskill] = useState(false);const [projectNoFolder, setProjectNoFolder] = useState(false);const [search, setSearch] = useState('');- const [backendFilter, setBackendFilter] = useState<Backend | 'all'>('all');const [selectedKey, setSelectedKey] = useState<string | null>(null);- const [busyBackend, setBusyBackend] = useState<Backend | null>(null);const [showAdd, setShowAdd] = useState(false);const [showBrowse, setShowBrowse] = useState(false);const [checkMap, setCheckMap] = useState<Record<string, SkillCheckItem>>({});@@ -145,12 +141,11 @@ export const SkillsPage: React.FC = () => {const matches = useCallback((skill: SkillBrief) => {- if (backendFilter !== 'all' && !backendsFromAgents(skill.agents).includes(backendFilter)) return false;const q = search.trim().toLowerCase();if (!q) return true;return skill.name.toLowerCase().includes(q) || (skill.description ?? '').toLowerCase().includes(q);},- [search, backendFilter],+ [search],);const filtered = useMemo(() => skills.filter(matches), [skills, matches]);@@ -165,23 +160,6 @@ export const SkillsPage: React.FC = () => {[skills, scope],);- const onToggleBackend = async (backend: Backend, next: boolean) => {- if (!selected) return;- setBusyBackend(backend);- try {- const projectArg = selected.scope === 'project' ? projectId ?? undefined : undefined;- const res = next- ? await api.addSkill({ source: selected.path, scope: selected.scope, projectId: projectArg, backends: [backend] })- : await api.removeSkill(selected.name, { scope: selected.scope, projectId: projectArg, backends: [backend] });- if (!res.ok) showToast(res.error?.message ?? BACKEND_LABEL[backend], 'error');- await refresh();- } catch (err) {- showToast(errorMessage(err) ?? String(err), 'error');- } finally {- setBusyBackend(null);- }- };-const onRemove = async () => {if (!selected) return;if (!window.confirm(t('skills.removeConfirm', { name: selected.name }))) return;@@ -284,8 +262,6 @@ export const SkillsPage: React.FC = () => {/></div>- <BackendFilter value={backendFilter} onChange={setBackendFilter} />-{projectCanManage ? (<><Button type="button" variant="outline" size="xs" onClick={() => setShowBrowse(true)}>@@ -403,11 +379,9 @@ export const SkillsPage: React.FC = () => {<SkillDetailPanelskill={selected}projectName={activeProject?.display_name}- busyBackend={busyBackend}check={checkMap[skillKey(selected)]}updating={updating}onClose={() => setSelectedKey(null)}- onToggleBackend={onToggleBackend}onUpdate={onUpdate}onRemove={onRemove}canManage={canManage && (selected.scope !== 'project' || Boolean(activeProject?.capabilities?.can_chat))}@@ -437,51 +411,3 @@ export const SkillsPage: React.FC = () => {</div>);};--interface BackendFilterProps {- value: Backend | 'all';- onChange: (next: Backend | 'all') => void;-}--// Compact funnel popover, mirroring AgentsPage's BackendFilter idiom.-const BackendFilter: React.FC<BackendFilterProps> = ({ value, onChange }) => {- const { t } = useTranslation();- const [open, setOpen] = useState(false);- const label = value === 'all' ? t('skills.backendAll') : BACKEND_LABEL[value];- const dot = (key: Backend | 'all') =>- key === 'all' ? 'bg-muted' : key === 'claude' ? 'bg-mint' : key === 'opencode' ? 'bg-cyan' : 'bg-violet';- return (- <Popover open={open} onOpenChange={setOpen}>- <PopoverTrigger asChild>- <button- type="button"- className="flex items-center gap-1.5 rounded-md border border-border-strong bg-surface px-3 py-2 text-[12px] font-medium text-foreground transition hover:bg-foreground/[0.04]"- >- <Funnel className="size-3 text-muted" />- <span className="text-muted">{t('skills.backendFilter')}:</span>- <span>{label}</span>- <ChevronDown className="size-3 text-muted" />- </button>- </PopoverTrigger>- <PopoverContent align="start" className="w-[180px] p-1">- {(['all', ...BACKEND_ORDER] as const).map((key) => (- <button- key={key}- type="button"- onClick={() => {- onChange(key);- setOpen(false);- }}- className={clsx(- 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] transition',- value === key ? 'bg-mint-soft text-mint-ink' : 'text-foreground hover:bg-foreground/[0.04]',- )}- >- <span className={clsx('size-2 rounded-full', dot(key))} />- <span>{key === 'all' ? t('skills.backendAll') : BACKEND_LABEL[key as Backend]}</span>- </button>- ))}- </PopoverContent>- </Popover>- );-};diff --git a/ui/src/components/workbench/skills/AddSkillDialog.tsx b/ui/src/components/workbench/skills/AddSkillDialog.tsxindex 5e521e4ac..f0a98a597 100644--- a/ui/src/components/workbench/skills/AddSkillDialog.tsx+++ b/ui/src/components/workbench/skills/AddSkillDialog.tsx@@ -1,5 +1,5 @@import { useMemo, useRef, useState } from 'react';-import { Check, Download, Github, Loader2, PackageCheck, PackagePlus, Search, Terminal, X } from 'lucide-react';+import { Download, Github, Loader2, PackageCheck, PackagePlus, Search, Terminal, X } from 'lucide-react';import clsx from 'clsx';import { useTranslation } from 'react-i18next';import { useApi } from '../../../context/ApiContext';@@ -8,12 +8,9 @@ import { useToast } from '../../../context/ToastContext';import { Button } from '../../ui/button';import { SegmentedRadio } from '../../ui/segmented';import { Checkbox } from '../../ui/checkbox';-import { BACKEND_CHIP, BACKEND_LABEL, BACKEND_ORDER, type Backend } from '../../../lib/backendAccent';import { FileDropzone } from './FileDropzone';import { errorMessage } from '@/lib/errorMessage';-const AGENT_OF: Record<Backend, string> = { claude: 'claude-code', opencode: 'opencode', codex: 'codex' };-export interface AddSkillDialogProps {defaultScope: SkillScope;projectId?: string;@@ -37,7 +34,6 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,const [discovered, setDiscovered] = useState<SkillDiscovered[] | null>(null);const [selected, setSelected] = useState<Set<string>>(new Set());const [scope, setScope] = useState<SkillScope>(projectId ? defaultScope : 'global');- const [backends, setBackends] = useState<Set<Backend>>(new Set(BACKEND_ORDER));const [busy, setBusy] = useState<'fetch' | 'install' | null>(null);const [error, setError] = useState<string | null>(null);// Monotonic token: a slow preview that resolves after the source changed must@@ -98,15 +94,6 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,}};- const toggleBackend = (backend: Backend) => {- setBackends((prev) => {- const next = new Set(prev);- if (next.has(backend)) next.delete(backend);- else next.add(backend);- return next;- });- };-const toggleSkill = (name: string) => {setSelected((prev) => {const next = new Set(prev);@@ -119,24 +106,27 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,const cliPreview = useMemo(() => {if (!baseSource) return '';const allSelected = discovered && selected.size === discovered.length;- // askill's -a is variadic — all agents share ONE flag.- const selectedAgents = BACKEND_ORDER.filter((b) => backends.has(b)).map((b) => AGENT_OF[b]);- const agentsArg = selectedAgents.length ? `-a ${selectedAgents.join(' ')}` : '';const selector = allSelected? '--all': selected.size === 1? `--skill ${[...selected][0]}`: `--skill … (×${selected.size})`;- return ['askill add', baseSource, selector, scope === 'global' ? '-g' : '', agentsArg, '-y']+ return [+ 'askill add',+ baseSource,+ '-a claude-code opencode codex',+ selector,+ scope === 'global' ? '-g' : '',+ '-y',+ ].filter(Boolean).join(' ');- }, [baseSource, discovered, selected, backends, scope]);+ }, [baseSource, discovered, selected, scope]);const install = async () => {- if (!baseSource || selected.size === 0 || backends.size === 0) return;+ if (!baseSource || selected.size === 0) return;setBusy('install');setError(null);- const targetBackends = [...backends];const targetProject = scope === 'project' ? projectId : undefined;const allSelected = discovered != null && selected.size === discovered.length;try {@@ -146,12 +136,12 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,// per call; --all is a single call covering everything.)let failed: Awaited<ReturnType<typeof api.addSkill>> | null = null;if (allSelected) {- const r = await api.addSkill({ source: baseSource, scope, projectId: targetProject, backends: targetBackends, all: true });+ const r = await api.addSkill({ source: baseSource, scope, projectId: targetProject, all: true });if (!r.ok) failed = r;} else {for (const name of selected) {// --skill keeps local-dir paths unambiguous (paths can contain '@').- const r = await api.addSkill({ source: baseSource, skill: name, scope, projectId: targetProject, backends: targetBackends });+ const r = await api.addSkill({ source: baseSource, skill: name, scope, projectId: targetProject });if (!r.ok) {failed = r;break;@@ -285,29 +275,6 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,<SegmentedRadio<SkillScope> value={scope} onChange={setScope} ariaLabel={t('skills.addDialog.installTo')} options={scopeOptions} disabled={!projectId} /></div>- <div className="flex flex-col gap-1.5">- <span className="font-mono text-[10px] font-bold uppercase tracking-[0.1em] text-muted">{t('skills.addDialog.backends')}</span>- <div className="flex flex-wrap items-center gap-2">- {BACKEND_ORDER.map((backend) => {- const on = backends.has(backend);- return (- <button- key={backend}- type="button"- onClick={() => toggleBackend(backend)}- className={clsx(- 'flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[12px] font-medium transition',- on ? BACKEND_CHIP[backend] : 'border-border-strong bg-surface text-muted hover:text-foreground',- )}- >- <Check className={clsx('size-3', on ? '' : 'opacity-0')} />- {BACKEND_LABEL[backend]}- </button>- );- })}- </div>- </div>-{error ? (<div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">{error}</div>) : null}@@ -327,7 +294,7 @@ export function AddSkillDialog({ defaultScope, projectId, projectName, onClose,variant="brand"size={null}onClick={install}- disabled={!discovered || selected.size === 0 || backends.size === 0 || busy === 'install'}+ disabled={!discovered || selected.size === 0 || busy === 'install'}className="gap-1.5 px-4 py-2 text-[12px] font-semibold">{busy === 'install' ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}diff --git a/ui/src/components/workbench/skills/BackendChip.tsx b/ui/src/components/workbench/skills/BackendChip.tsxdeleted file mode 100644index b7c6ab912..000000000--- a/ui/src/components/workbench/skills/BackendChip.tsx+++ /dev/null@@ -1,17 +0,0 @@-import clsx from 'clsx';-import { BACKEND_CHIP, BACKEND_DOT, BACKEND_LABEL, type Backend } from '../../../lib/backendAccent';--/** Small pill marking a backend a skill is linked to. Colour per backend. */-export function BackendChip({ backend }: { backend: Backend }) {- return (- <span- className={clsx(- 'inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5',- BACKEND_CHIP[backend],- )}- >- <span className={clsx('size-[5px] rounded-full', BACKEND_DOT[backend])} />- <span className="font-mono text-[10px] font-medium">{BACKEND_LABEL[backend]}</span>- </span>- );-}diff --git a/ui/src/components/workbench/skills/SkillDetailPanel.tsx b/ui/src/components/workbench/skills/SkillDetailPanel.tsxindex 8c8e5ceee..a6bc53384 100644--- a/ui/src/components/workbench/skills/SkillDetailPanel.tsx+++ b/ui/src/components/workbench/skills/SkillDetailPanel.tsx@@ -1,22 +1,16 @@import type { ReactNode } from 'react';-import { ArrowUp, Bot, Loader2, Trash2, WandSparkles, X } from 'lucide-react';-import clsx from 'clsx';+import { ArrowUp, Loader2, Trash2, WandSparkles, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import type { SkillBrief, SkillCheckItem } from '../../../context/ApiContext';-import { BACKEND_LABEL, BACKEND_ORDER, BACKEND_TEXT, backendsFromAgents, type Backend } from '../../../lib/backendAccent';import { Button } from '../../ui/button';-import { Switch } from '../../ui/switch';export interface SkillDetailPanelProps {skill: SkillBrief;projectName?: string;- /** Backend currently mid add/remove, to show a spinner on that row. */- busyBackend?: Backend | null;/** Update status from `askill check`; drives the "Update" affordance. */check?: SkillCheckItem | null;updating?: boolean;onClose: () => void;- onToggleBackend: (backend: Backend, next: boolean) => void;onUpdate?: () => void;onRemove: () => void;canManage?: boolean;@@ -27,26 +21,21 @@ function Eyebrow({ children }: { children: ReactNode }) {}/**- * Right-hand detail panel for a selected installed skill. The "Available to"- * switches are the core management surface: ON links the skill to that- * backend (askill add <path> -a <agent>), OFF unlinks it (askill remove -a).- * Registry-only data (AI quality, commands) isn't in askill `list --json`+ * Right-hand detail panel for a selected installed skill. Registry-only data+ * (AI quality, commands) isn't in askill `list --json`* yet (askill#11), so it's intentionally absent for installed skills.*/export function SkillDetailPanel({skill,projectName,- busyBackend,check,updating,onClose,- onToggleBackend,onUpdate,onRemove,canManage = true,}: SkillDetailPanelProps) {const { t } = useTranslation();- const linked = new Set(backendsFromAgents(skill.agents));const updateAvailable = check?.status === 'update_available';const versionDelta =check?.localVersion || check?.remoteVersion ? `${check?.localVersion ?? '?'} → ${check?.remoteVersion ?? '?'}` : undefined;@@ -86,32 +75,6 @@ export function SkillDetailPanel({{skill.description ? <p className="text-[12px] leading-relaxed text-muted">{skill.description}</p> : null}- <div className="flex flex-col gap-2">- <Eyebrow>{t('skills.detail.availableTo')}</Eyebrow>- <div className="flex flex-col gap-1.5">- {BACKEND_ORDER.map((backend) => {- const on = linked.has(backend);- const busy = busyBackend === backend;- return (- <div key={backend} className="flex items-center gap-2 rounded-lg border border-border bg-surface-3 px-3 py-2">- <Bot className={clsx('size-3.5', BACKEND_TEXT[backend])} />- <span className="flex-1 text-[12.5px] font-medium text-foreground">{BACKEND_LABEL[backend]}</span>- {busy ? (- <Loader2 className="size-3.5 animate-spin text-muted" />- ) : (- <Switch- checked={on}- disabled={!canManage}- onCheckedChange={(next) => onToggleBackend(backend, next)}- label={BACKEND_LABEL[backend]}- />- )}- </div>- );- })}- </div>- </div>-{canManage ? <div className="flex items-center gap-2 pt-1">{updateAvailable ? (<Button type="button" variant="brand-gold" size="xs" onClick={onUpdate} disabled={updating} title={versionDelta}>diff --git a/ui/src/components/workbench/skills/SkillRow.tsx b/ui/src/components/workbench/skills/SkillRow.tsxindex c2d6d8b96..8ad4e0c6e 100644--- a/ui/src/components/workbench/skills/SkillRow.tsx+++ b/ui/src/components/workbench/skills/SkillRow.tsx@@ -2,8 +2,6 @@ import { ArrowUp, Ellipsis, Github, Globe, WandSparkles } from 'lucide-react';import clsx from 'clsx';import { useTranslation } from 'react-i18next';import type { SkillBrief } from '../../../context/ApiContext';-import { backendsFromAgents } from '../../../lib/backendAccent';-import { BackendChip } from './BackendChip';export interface SkillRowProps {skill: SkillBrief;@@ -15,10 +13,9 @@ export interface SkillRowProps {onSelect?: () => void;}-/** One installed-skill row: lead icon · name + desc + source/version · backend chips. */+/** One installed-skill row: lead icon · name + description + source/version. */export function SkillRow({ skill, selected, inherited, updateAvailable, onSelect }: SkillRowProps) {const { t } = useTranslation();- const backends = backendsFromAgents(skill.agents);return (<buttontype="button"@@ -64,11 +61,6 @@ export function SkillRow({ skill, selected, inherited, updateAvailable, onSelect</span>) : null}</span>- <span className="flex shrink-0 items-center gap-1.5">- {backends.map((backend) => (- <BackendChip key={backend} backend={backend} />- ))}- </span><span className="flex size-7 shrink-0 items-center justify-center rounded-md text-muted opacity-0 transition group-hover:opacity-100"><Ellipsis className="size-3.5" /></span>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 8f7de9a0b..06acd9298 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -3566,15 +3566,13 @@},"skills": {"title": "Skills",- "subtitle": "Manage global and project skills across your agent backends · powered by askill.",+ "subtitle": "Manage global and project skills once for every agent backend · powered by askill.","remoteReadOnly": "Read-only","remoteReadOnlyHint": "Skills are read-only in remote mode.","scopeGlobal": "Global","scopeProject": "Project","searchPlaceholder": "Search installed skills…","searchProjectPlaceholder": "Search this project's skills…",- "backendFilter": "Backend",- "backendAll": "All","browseRegistry": "Browse registry","addSkill": "Add skill","empty": "No skills installed yet. Add one from GitHub, a .zip, or the registry.",@@ -3607,7 +3605,6 @@"source": "Source","viewOnGithub": "View on GitHub","quality": "AI quality",- "availableTo": "Available to","commands": "Commands","openSkillMd": "Open SKILL.md","remove": "Remove",@@ -3627,7 +3624,6 @@"replace": "Replace","found": "Found {{count}} skill(s) · select to install","installTo": "Install to",- "backends": "Install for backends","cancel": "Cancel","install": "Install {{count}} skill(s)","installing": "Installing…",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c7ce5e466..b36821958 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -3566,15 +3566,13 @@},"skills": {"title": "技能",- "subtitle": "跨各 Agent 后端管理全局与项目级技能 · 基于 askill。",+ "subtitle": "一次管理全局与项目级技能,所有 Agent 后端都可使用 · 基于 askill。","remoteReadOnly": "只读","remoteReadOnlyHint": "远程模式下技能为只读。","scopeGlobal": "全局","scopeProject": "项目","searchPlaceholder": "搜索已安装技能…","searchProjectPlaceholder": "搜索本项目的技能…",- "backendFilter": "Backend",- "backendAll": "全部","browseRegistry": "浏览注册表","addSkill": "添加技能","empty": "还没有安装技能。可从 GitHub、.zip 或注册表添加。",@@ -3607,7 +3605,6 @@"source": "来源","viewOnGithub": "在 GitHub 查看","quality": "AI 质量",- "availableTo": "可用于","commands": "命令","openSkillMd": "打开 SKILL.md","remove": "移除",@@ -3627,7 +3624,6 @@"replace": "更换","found": "发现 {{count}} 个技能 · 勾选要安装的","installTo": "安装到",- "backends": "为这些 Backend 安装","cancel": "取消","install": "安装 {{count}} 个技能","installing": "安装中…",diff --git a/vibe/cli.py b/vibe/cli.pyindex 3a8fab238..fe4b14ea4 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -838,6 +838,51 @@ def cmd_memory(args) -> int:return 0+def cmd_skill(args) -> int:+ """List or load Skills through Avibe's live resolver."""++ from core.managed_skills import (+ load_skill,+ render_skill_content,+ render_skill_list,+ resolve_skills,+ )++ language = _configured_cli_language()++ if args.skill_command == "list":+ try:+ output = render_skill_list(+ resolve_skills(),+ page=args.page,+ more_notice=i18n_t(+ "skill.cli.more",+ language,+ page=args.page + 1,+ ),+ )+ except ValueError:+ print(i18n_t("skill.cli.error.invalidPage", language), file=sys.stderr)+ return 1+ if output:+ print(output)+ return 0++ if args.skill_command == "load":+ allowed = resolve_skills()+ if args.name not in {skill.name for skill in allowed}:+ print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)+ return 1+ skill = load_skill(args.name, resolved_skills=allowed)+ if skill is None:+ print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)+ return 1+ print(render_skill_content(skill))+ return 0++ return 1++def _add_pagination_args(parser, *, help_command: str) -> None:parser.add_argument("--page", type=int, help="Page number to return. Defaults to 1.")parser.add_argument(@@ -15845,6 +15890,34 @@ def build_parser():metavar="{status,profile,list,search,remember}",)memory_subparsers.required = True+ skill_help_language = _configured_cli_language()+ skill_parser = subparsers.add_parser(+ "skill",+ help=i18n_t("skill.cli.help.command", skill_help_language),+ )+ skill_subparsers = skill_parser.add_subparsers(+ dest="skill_command",+ metavar="{list,load}",+ )+ skill_subparsers.required = True+ skill_list_parser = skill_subparsers.add_parser(+ "list",+ help=i18n_t("skill.cli.help.list", skill_help_language),+ )+ skill_list_parser.add_argument(+ "--page",+ type=int,+ default=1,+ help=i18n_t("skill.cli.help.page", skill_help_language),+ )+ skill_load_parser = skill_subparsers.add_parser(+ "load",+ help=i18n_t("skill.cli.help.load", skill_help_language),+ )+ skill_load_parser.add_argument(+ "name",+ help=i18n_t("skill.cli.help.name", skill_help_language),+ )memory_status_parser = memory_subparsers.add_parser("status",help=i18n_t("memory.cli.help.status", memory_help_language),@@ -17673,6 +17746,8 @@ def main():sys.exit(cmd_status())if args.command == "memory":sys.exit(cmd_memory(args))+ if args.command == "skill":+ sys.exit(cmd_skill(args))if args.command == "doctor":sys.exit(cmd_doctor(args))if args.command == "screenshot":diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 87882e046..7e77ee7fb 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -747,6 +747,22 @@"permission": {"adminOnly": "🔒 Only admins can change bot settings. Contact an admin if you need access."},+ "skill": {+ "cli": {+ "help": {+ "command": "List and load Skills through Avibe",+ "list": "List available Skills",+ "load": "Load one Skill",+ "page": "Catalog page (default: 1)",+ "name": "Skill name"+ },+ "more": "More skills are available. Run `vibe skill list --page {page}` to view more.",+ "error": {+ "invalidPage": "error: page must be a positive integer",+ "notFound": "Skill not found: {name}"+ }+ }+ },"memory": {"cli": {"help": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 03f5d7c8a..6ba915e21 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -747,6 +747,22 @@"permission": {"adminOnly": "🔒 仅管理员可以修改 Bot 设置。如需权限请联系管理员。"},+ "skill": {+ "cli": {+ "help": {+ "command": "通过 Avibe 列出和加载 Skills",+ "list": "列出可用的 Skills",+ "load": "加载一个 Skill",+ "page": "Catalog 页码(默认:1)",+ "name": "Skill 名称"+ },+ "more": "还有更多 Skills。运行 `vibe skill list --page {page}` 查看下一页。",+ "error": {+ "invalidPage": "错误:页码必须是正整数",+ "notFound": "未找到 Skill:{name}"+ }+ }+ },"memory": {"cli": {"help": {