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(skills): add local usage statistics for Harness optimization (#1929)
Call White150d8c4761aa
diff --git a/config/v2_config.py b/config/v2_config.pyindex c821a08b3..bef51813d 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -1014,7 +1014,7 @@ def _recovery_field_for_error(section: Optional[str], error: BaseException) -> Oif not path.startswith(prefix):return Nonefield_name = path[len(prefix) :].split(".", 1)[0]- return field_name if field_name in _RUNTIME_RETENTION_FIELDS else None+ return field_name if field_name in _RUNTIME_RETENTION_FIELDS or field_name == "skill_observability_enabled" else Noneif section not in _FIELD_SCOPED_RECOVERY_SECTIONS:return Nonematch = re.search(r"Config '([^']+)'", str(error))@@ -1181,13 +1181,16 @@ def _recover_memory_cloud_section(payload: dict, field_name: Optional[str]) -> bdef _recover_runtime_field(payload: dict, field_name: Optional[str]) -> bool:- """Repair one retention field without discarding the runtime section."""+ """Repair one retention or collection field without discarding runtime."""- if field_name not in _RUNTIME_RETENTION_FIELDS:+ if field_name not in _RUNTIME_RETENTION_FIELDS and field_name != "skill_observability_enabled":return Falseruntime = payload.get("runtime")if not isinstance(runtime, dict):return False+ if field_name == "skill_observability_enabled":+ runtime[field_name] = False+ return True# A recovered policy is disabled even if the other retention field looked# valid. The warning attached by ``V2Config.load`` keeps all automatic and# status consumers fail-closed until the operator repairs the file.@@ -2415,8 +2418,11 @@ class RuntimeConfig:# ``vibe data retention`` section of the CLI reference (avibe-docs).agent_events_trace_retention_enabled: bool = Trueagent_events_trace_retention_days: int = 30+ skill_observability_enabled: bool = Truedef __post_init__(self) -> None:+ if not isinstance(self.skill_observability_enabled, bool):+ raise ValueError("Config 'runtime.skill_observability_enabled' must be a boolean")self.show_page_api_timeout_seconds = _named_value("runtime.show_page_api_timeout_seconds",float,@@ -4444,6 +4450,7 @@ class V2Config:"harness_prompt_echo": self.runtime.harness_prompt_echo,"agent_events_trace_retention_enabled": self.runtime.agent_events_trace_retention_enabled,"agent_events_trace_retention_days": self.runtime.agent_events_trace_retention_days,+ "skill_observability_enabled": self.runtime.skill_observability_enabled,},"agents": {"opencode": self.agents.opencode.__dict__,diff --git a/core/controller.py b/core/controller.pyindex 1a8797b60..c16f52676 100644--- a/core/controller.py+++ b/core/controller.py@@ -4109,10 +4109,13 @@ class Controller:from storage import agent_events_retentionfrom storage.db import get_cached_sqlite_engine+ # Skill privacy retention remains active when collection/tool retention+ # is disabled; both policies share this bounded maintenance worker.+ engine = get_cached_sqlite_engine()+ agent_events_retention.run_skill_retention(engine, cancel_event=cancel_event)config = self._agent_events_retention_config()if config is None:return {"status": "disabled"}- engine = get_cached_sqlite_engine()return agent_events_retention.run_once(engine,retention_days=int(config["days"]),diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex f9f5e18d0..1cbeccc62 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1522,12 +1522,14 @@ class SessionHandler(BaseHandler):# Always append avibe system prompt injection so transport# capabilities remain available; reply_enhancements only controls# quick-reply button instructions.+ skill_catalog_sink: list[dict] = []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,+ skill_catalog_sink=skill_catalog_sink,working_path=working_path,)@@ -1636,6 +1638,7 @@ class SessionHandler(BaseHandler):# Create new Claude clientclient = ClaudeSDKClient(options=options)+ setattr(client, "_vibe_pending_skill_catalog", skill_catalog_sink[0] if skill_catalog_sink else None)setattr(client, "_vibe_stderr_lines", claude_stderr_lines)setattr(client, "_vibe_caller_env", self._caller_env_for_context(context))setattr(@@ -1744,6 +1747,7 @@ class SessionHandler(BaseHandler):session_anchor: str,agent_system_prompt: Optional[str],working_path: Optional[str] = None,+ skill_catalog_sink: list[dict] | None = None,) -> str | Dict[str, str]:base_prompt = agent_system_prompt or self.config.claude.system_promptquick_replies_on = getattr(self.config, "reply_enhancements", True)@@ -1771,6 +1775,7 @@ class SessionHandler(BaseHandler):skills_cwd=working_path,skills_project_base=managed_skill_project_base(context),skills_claude_cli_path=managed_skill_claude_cli_path(self.config),+ skill_catalog_sink=skill_catalog_sink,)if base_prompt:diff --git a/core/internal_server.py b/core/internal_server.pyindex 7362226ec..e1379f3dd 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -192,6 +192,34 @@ def create_app(redoc_url=None,openapi_url=None,)+ from core.skill_observability import SkillObservationRecorder++ skill_recorder = SkillObservationRecorder()+ controller.skill_observability = skill_recorder++ @app.post("/internal/skill-observations", status_code=202)+ async def _skill_observation(request: Request) -> Any:+ from storage.skill_observability import ObservationError, utc_now, validate++ # Bounded payloads contain descriptors only, never Skill bodies.+ body = bytearray()+ async for chunk in request.stream():+ body.extend(chunk)+ if len(body) > 32 * 1024:+ skill_recorder.counts["rejected"] += 1+ raise HTTPException(status_code=413, detail="observation_too_large")+ try:+ event = validate(json.loads(body), now=utc_now())+ if event["metadata"]["observation_channel"] != "avibe_cli":+ raise ObservationError("runtime_observation_required")+ except (ValueError, TypeError, RecursionError):+ skill_recorder.counts["rejected"] += 1+ raise HTTPException(status_code=400, detail="invalid_observation") from None+ return {"status": skill_recorder.enqueue(event)}++ @app.get("/internal/skill-observations/health")+ async def _skill_observation_health() -> Any:+ return skill_recorder.health()# In-flight ``dispatch_turn`` tasks per session, each a ``Turn`` holding the# task + the routing ``MessageContext`` the turn STARTED under. The cancel@@ -2158,28 +2186,34 @@ async def serve(controller: "Controller", *, socket_path: Optional[Path] = None)import uvicornapp = create_app(controller)- recovery_complete = getattr(controller, "_delivery_recovery_complete", None)- if recovery_complete is not None:- await recovery_complete.wait()- config = uvicorn.Config(- app,- log_config=None,- access_log=False,- loop="asyncio",- lifespan="off",- )- server = _create_controller_loop_server(config)-- listener, target = _bind_socket(socket_path)- _write_internal_server_status("ready")+ skill_recorder = controller.skill_observabilitytry:- await server.serve(sockets=[listener])- finally:+ recovery_complete = getattr(controller, "_delivery_recovery_complete", None)+ if recovery_complete is not None:+ await recovery_complete.wait()+ config = uvicorn.Config(+ app,+ log_config=None,+ access_log=False,+ loop="asyncio",+ lifespan="off",+ )+ server = _create_controller_loop_server(config)++ listener, target = _bind_socket(socket_path)try:- listener.close()- except OSError:- pass- _remove_owned_socket(target)+ _write_internal_server_status("ready")+ await server.serve(sockets=[listener])+ finally:+ try:+ listener.close()+ except OSError:+ pass+ _remove_owned_socket(target)+ finally:+ # Lifespan is disabled: this server task owns the recorder's cleanup,+ # including cancellation during controller recovery or socket setup.+ await skill_recorder.close()def _bind_socket(socket_path: Optional[Path] = None) -> tuple[socket.socket, Path]:diff --git a/core/managed_skills.py b/core/managed_skills.pyindex f5d6a5ea5..5a529313c 100644--- a/core/managed_skills.py+++ b/core/managed_skills.py@@ -1138,7 +1138,7 @@ def _catalog_pages(skills: Sequence[ManagedSkill]) -> list[list[ManagedSkill]]:return pages-def _page(skills: Sequence[ManagedSkill], page: int) -> tuple[Sequence[ManagedSkill], int | None]:+def catalog_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)@@ -1153,7 +1153,7 @@ def render_skill_list(page: int = 1,more_notice: str | None = None,) -> str:- entries, next_page = _page(skills, page)+ entries, next_page = catalog_page(skills, page)lines = _skill_list_rows(entries)if next_page is not None:lines.append(@@ -1171,7 +1171,7 @@ def render_skill_catalog_prompt(skills: Sequence[ManagedSkill]) -> str:def render_skill_catalog_blocks(skills: Sequence[ManagedSkill]) -> list[RenderedPromptBlock]:- entries, next_page = _page(skills, 1)+ entries, next_page = catalog_page(skills, 1)rows = "\n".join(_skill_list_rows(entries))if not rows:if any(skill.disable_model_invocation for skill in skills):diff --git a/core/skill_observability.py b/core/skill_observability.pynew file mode 100644index 000000000..32daa4b71--- /dev/null+++ b/core/skill_observability.py@@ -0,0 +1,273 @@+"""Skill payload construction and bounded, optional runtime recording."""++from __future__ import annotations++import asyncio+from collections import Counter+import hashlib+import json+import logging+import os+from pathlib import Path+import sys+import time+from typing import Any, Sequence+import uuid++from core.caller_context import caller_context_from_env+from core.managed_skills import ManagedSkill, SKILL_PROJECT_BASE_ENV, SKILL_WORKING_DIR_ENV, catalog_page+from storage import skill_observability as store+from vibe import __version__++logger = logging.getLogger(__name__)+MAX_PENDING_OBSERVATIONS = 128+_CLI_HEALTH: Counter[str] = Counter()+++def _digest(value: Any) -> str:+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")).hexdigest()+++def skill_descriptor(skill: ManagedSkill) -> dict[str, Any]:+ source = {0: "builtin", 1: "project", 2: "global"}[skill.priority[0]]+ identity = [1, "builtin", skill.name] if source == "builtin" else [1, source, str(skill.directory), skill.name]+ return {+ "skill_key": _digest(identity),+ "skill_name": skill.name,+ "source_kind": source,+ "descriptor_sha256": _digest([1, skill.name, skill.description, skill.disable_model_invocation]),+ }+++def catalog_result(+ skills: Sequence[ManagedSkill],+ *,+ page: int = 1,+ entry_point: str = "cli_list",+ error_code: str | None = None,+) -> dict[str, Any]:+ entries, next_page = catalog_page(skills, page) if error_code is None else ([], None)+ rows = [{**skill_descriptor(skill), "position": index} for index, skill in enumerate(entries, 1)]+ return {+ "entry_point": entry_point,+ "outcome": "failure" if error_code else "success",+ "error_code": error_code,+ "page": page if type(page) is int and page >= 0 else 0,+ "has_more": next_page is not None,+ "catalog_digest": _digest(rows) if not error_code else None,+ "entries": rows,+ }+++def load_result(+ name: str,+ skill: ManagedSkill | None,+ *,+ duration_ms: int,+ error_code: str | None = None,+) -> dict[str, Any]:+ revision = None+ body_bytes = None+ if skill is not None:+ descriptor = skill_descriptor(skill)+ if skill.body is not None:+ revision = _digest([1, skill.name, skill.description, skill.disable_model_invocation, skill.body])+ body_bytes = len(skill.body.encode("utf-8"))+ else:+ valid_name = isinstance(name, str) and len(name) <= 64 and store.NAME_RE.fullmatch(name)+ project = os.environ.get(SKILL_PROJECT_BASE_ENV) or os.environ.get(SKILL_WORKING_DIR_ENV) or os.getcwd()+ descriptor = {+ "skill_key": _digest([1, "unresolved", str(Path(project).resolve()), name]) if valid_name else None,+ "skill_name": name if valid_name else None,+ "source_kind": "unresolved",+ "descriptor_sha256": None,+ }+ if not valid_name:+ error_code = "invalid_name"+ return {+ **descriptor,+ "skill_revision": revision,+ "outcome": "failure" if error_code else "success",+ "error_code": error_code,+ "duration_ms": duration_ms,+ "body_bytes": body_bytes,+ }+++def observation(+ event_type: str,+ content: dict,+ *,+ session_id: str | None = None,+ turn_id: str | None = None,+ trigger_kind: str = "unknown",+ backend: str | None = None,+) -> dict[str, Any]:+ return {+ "id": "evt_skill_" + uuid.uuid4().hex,+ "session_id": session_id,+ "turn_id": turn_id,+ "event_type": event_type,+ "content": content,+ "metadata": {+ "schema_version": 1,+ "observed_at": store.timestamp(store.utc_now()),+ "observation_channel": "runtime_prompt" if content.get("entry_point") == "runtime_prompt" else "avibe_cli",+ "trigger_kind": trigger_kind,+ "backend": backend,+ "model": None,+ "avibe_version": __version__,+ },+ }+++def submit_cli(event_type: str, content: dict) -> None:+ """Never change command stdout or its exit outcome for optional telemetry."""+ try:+ from vibe.internal_client import record_skill_observation_sync++ caller = caller_context_from_env()+ event = observation(+ event_type,+ content,+ session_id=caller.session_id if caller else None,+ backend=caller.backend if caller else None,+ trigger_kind="standalone" if caller is None and sys.stdin.isatty() else "unknown",+ )+ result = record_skill_observation_sync(event)+ status = result.get("status", "dropped")+ _CLI_HEALTH[status] += 1+ if status not in {"queued", "disabled"}:+ logger.info("Skill observation not queued: %s", status if status == "dropped" else "rejected")+ except Exception:+ _CLI_HEALTH["dropped"] += 1+ logger.info("Skill observation unavailable; command result preserved")+++def finish_cli_load(name: str, skill: ManagedSkill | None, started_at: float, error_code: str | None) -> None:+ try:+ submit_cli(+ "skill.load_result", load_result(name, skill, duration_ms=elapsed_ms(started_at), error_code=error_code)+ )+ except Exception:+ _CLI_HEALTH["dropped"] += 1+ logger.info("Skill observation construction failed")+++def finish_cli_catalog(skills: Sequence[ManagedSkill], page: int, error_code: str | None) -> None:+ try:+ submit_cli("skill.catalog_result", catalog_result(skills, page=page, error_code=error_code))+ except Exception:+ _CLI_HEALTH["dropped"] += 1+ logger.info("Skill catalog observation construction failed")+++def accept_catalog(controller: Any, context: Any, candidate: dict | None, *, backend: str | None = None) -> None:+ """Called only after positive native acceptance, never from a renderer."""+ if not candidate:+ return+ recorder = getattr(controller, "skill_observability", None)+ if recorder is None:+ return+ try:+ payload = getattr(context, "platform_specific", None) or {}+ event = observation(+ "skill.catalog_result",+ candidate,+ session_id=payload.get("agent_session_id"),+ turn_id=payload.get("turn_token"),+ backend=backend,+ )+ recorder.enqueue(event, trusted_runtime=True)+ except Exception:+ logger.warning("Skill catalog observation dropped after native acceptance")+++def collection_enabled() -> bool:+ from config.v2_config import V2Config++ try:+ config = V2Config.load()+ except Exception:+ logger.info("Skill observation collection disabled: config unavailable")+ return False+ if any(+ any(marker in str(warning) for marker in ("runtime", "recovery defaults", "could not be recovered"))+ for warning in getattr(config, "load_warnings", ())+ ):+ return False+ return config.runtime.skill_observability_enabled is True+++class SkillObservationRecorder:+ """One bounded queue and one serial writer, owned by the internal server."""++ def __init__(self, *, engine=None, enabled=collection_enabled):+ self.engine = engine+ self.enabled = enabled+ self.queue: asyncio.Queue = asyncio.Queue(maxsize=MAX_PENDING_OBSERVATIONS)+ self.worker: asyncio.Task | None = None+ self.closed = False+ self.counts: Counter[str] = Counter(+ dict.fromkeys(+ ("queued", "accepted", "duplicate", "disabled", "rejected", "dropped", "uncorrelated"),+ 0,+ )+ )+ self.started_at = store.timestamp(store.utc_now())++ def enqueue(self, event: dict, *, trusted_runtime: bool = False) -> str:+ if self.closed or self.queue.full():+ self.counts["dropped"] += 1+ return "dropped"+ self.queue.put_nowait((event, trusted_runtime))+ if self.worker is None:+ self.worker = asyncio.create_task(self._drain(), name="skill-observations")+ self.counts["queued"] += 1+ return "queued"++ def _write(self, event: dict, trusted_runtime: bool) -> str:+ from storage.db import get_cached_sqlite_engine++ engine = self.engine if self.engine is not None else get_cached_sqlite_engine()+ with engine.begin() as conn:+ return store.record(conn, event, enabled=self.enabled, trusted_runtime=trusted_runtime)++ async def _drain(self) -> None:+ while True:+ event, trusted = await self.queue.get()+ try:+ result = await asyncio.to_thread(self._write, event, trusted)+ self.counts[result] += 1+ if result == "accepted" and event["session_id"] is None:+ self.counts["uncorrelated"] += 1+ except store.ObservationError as exc:+ self.counts["rejected"] += 1+ logger.warning("Skill observation rejected: %s", exc)+ except Exception:+ self.counts["dropped"] += 1+ logger.warning("Skill observation storage unavailable")+ finally:+ self.queue.task_done()++ def health(self) -> dict:+ return {"started_at": self.started_at, "pending": self.queue.qsize(), **self.counts}++ async def close(self) -> None:+ self.closed = True+ # Drop queued optional work; join at most the one in-flight DB write.+ while not self.queue.empty():+ self.queue.get_nowait()+ self.queue.task_done()+ self.counts["dropped"] += 1+ await self.queue.join()+ if self.worker is not None:+ self.worker.cancel()+ try:+ await self.worker+ except asyncio.CancelledError:+ pass+++def elapsed_ms(started_at: float) -> int:+ return min(86_400_000, max(0, int((time.monotonic() - started_at) * 1000)))diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex c7d428f6d..609f79dc7 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -201,6 +201,7 @@ def build_system_prompt_blocks(skills_cwd: str | Path | None = None,skills_project_base: str | Path | None = None,skills_claude_cli_path: str | None = None,+ skill_catalog_sink: list[dict[str, Any]] | None = None,) -> list[RenderedPromptBlock]:"""The production composition, also exported by the debug command."""@@ -251,6 +252,13 @@ def build_system_prompt_blocks(from core.managed_skills import render_skill_catalog_blocksblocks.extend(render_skill_catalog_blocks(skills))+ if skill_catalog_sink is not None:+ try:+ from core.skill_observability import catalog_result++ skill_catalog_sink.append(catalog_result(skills, entry_point="runtime_prompt"))+ except Exception:+ logger.info("Skill catalog observation unavailable during prompt preparation")if context is not None:platform = resolve_context_platform(context, fallback_platform=fallback_platform, default="<platform>")if _is_web_platform(platform):diff --git a/docs/CLI.md b/docs/CLI.mdindex 8e7303bea..5e96a99fe 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -160,6 +160,75 @@ the Catalog. Adding, editing, or deleting a Skill is therefore visible in anexisting Session without restarting Avibe or creating a new Session. Existingconversation history is not rewritten.+#### Local Skill statistics and privacy++Skill statistics are **enabled by default**, including after an upgrade when+`runtime.skill_observability_enabled` is absent from the configuration. Avibe+records catalog offers and load outcomes locally for future Harness optimization;+an offer or load does not prove that the Agent followed a Skill or completed a task.++The records include Skill names (including private project/global Skills), source+categories, SHA-256 identity/descriptor/content-version hashes, timestamps,+load results, durations, body byte counts, and available Session/project/Turn,+backend/platform, and Avibe-version associations. Names and Session links remain+identifiable: hashing does not make these statistics anonymous. Unknown execution+attribution stays unknown. Statistics are stored in the local SQLite database,+using `agent_events` and `skill_usage_daily`; there is no statistics dashboard or+cloud upload. This feature adds no stored copies of Skill bodies, descriptions,+prompts, credentials, or plaintext filesystem paths. Normal delivery of a loaded+Skill to your configured Agent/model is unchanged.++To stop new recording, set `runtime.skill_observability_enabled` to JSON `false`+in the active `config/config.json` under the Avibe state root. That root is+`$AVIBE_HOME` when explicitly configured, otherwise `$HOME/.avibe` (or the+legacy `$HOME/.vibe_remote` when the new root is absent). Merge this field into+the existing configuration; do not replace the whole file with this fragment:++```json+{+ "runtime": {+ "skill_observability_enabled": false+ }+}+```++The recorder rereads this setting before writing, so a restart is not required.+Disabling statistics does not disable Skill discovery/loading or delete history.+If you do not want future records or retained history, disable first, then clear.++### `vibe data skill-usage`++Instance Owner-only local maintenance; these commands return JSON diagnostics,+not a Skill popularity ranking. The same owner boundary applies to reading these+statistics through `vibe data query`.++```bash+vibe data skill-usage --json+vibe data skill-usage --clear --yes --json+```++The first command reports `enabled`, raw-event and daily-row counts, retention+windows, the first-observation marker, and `cleared_through`. After opting out,+confirm `enabled` is `false`. The clear command requires both `--clear` and+`--yes`; it deletes only Skill statistics, leaves conversations and other event+types intact, and reports deleted row counts. A clear watermark rejects delayed+pre-clear observations. Clearing does not disable collection: new activity can+immediately create new records while the setting remains enabled.++Raw Skill events have a 90-day retention window; daily statistics retain 365 UTC+dates including today. Daily rows are still Session-associated, not anonymous+global totals. Cleanup runs in bounded background batches while the controller+runs, so expired rows can remain until maintenance catches up. These windows+apply independently of the Skill-collection and tool-trace-retention switches.+Archiving a Session does not delete its statistics; physically purging the+Session removes its associated Skill events and daily rows.++Clear and retention are logical deletion, not secure erasure or guaranteed disk+space reclamation: old data may remain in SQLite WAL/free pages or backups.+Restoring a database backup also restores its historical statistics and clear+watermark; clear again after a restore when needed. No historical conversation+scan or backfill is performed by this feature.+### `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 557d80de4..492aaba18 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -134,6 +134,64 @@ Codex 自带的默认项;已启用的 Claude 插件 Skill 排在四个静态因此新增、修改或删除 Skill 后,已有 Session 无需重启 Avibe,也无需新建 Session;历史对话内容不会被重写。+#### 本地 Skill 统计与隐私++Skill 统计**默认开启**;升级后,若配置中没有+`runtime.skill_observability_enabled`,也会采用开启状态。Avibe 在本地记录+Catalog 提供情况及加载结果,用于未来的 Harness 优化;提供或加载过某个 Skill,+并不能证明 Agent 遵循了它,也不能证明任务已经完成。++记录包括 Skill 名称(含私有项目及全局 Skill)、来源类别、SHA-256 身份/描述/+内容版本哈希、时间戳、加载结果、耗时、正文的字节数,以及可确认的 Session/+项目/Turn、backend/platform 和 Avibe 版本关联。名称与 Session 关联仍可识别,+哈希并不使这些统计成为匿名数据;无法确认的执行归属保持未知。统计保存在本地+SQLite 数据库的 `agent_events` 与 `skill_usage_daily` 中,没有统计面板,也不+上传云端。此功能不会额外保存 Skill 正文、描述、prompt、凭据或明文文件路径。+正常向已配置的 Agent/model 提供所加载 Skill 的行为不变。++若要停止新增记录,请在当前 Avibe 状态根目录下的 `config/config.json` 中,将+`runtime.skill_observability_enabled` 设为 JSON 布尔值 `false`。显式配置了+`AVIBE_HOME` 时,根目录为 `$AVIBE_HOME`;否则为 `$HOME/.avibe`(新目录不存在+时兼容旧的 `$HOME/.vibe_remote`)。请把下面的字段合并到现有配置中,不要用+这个片段覆盖整个文件:++```json+{+ "runtime": {+ "skill_observability_enabled": false+ }+}+```++记录器每次写入前都会重新读取此设置,无需重启。关闭统计不影响 Skill 发现或+加载,也不会删除已有历史。若希望既不再记录,也不保留历史,请先关闭,再清除。++### `vibe data skill-usage`++仅限实例所有者使用的本地维护命令,返回 JSON 诊断信息,不是 Skill 热度排名。+通过 `vibe data query` 读取这些统计也受相同的所有者权限限制。++```bash+vibe data skill-usage --json+vibe data skill-usage --clear --yes --json+```++第一条命令返回 `enabled`、原始事件及每日统计行数、保留窗口、首次记录标记和+`cleared_through`。关闭后应确认 `enabled` 为 `false`。清除命令必须同时提供+`--clear` 和 `--yes`,仅删除 Skill 统计,保留对话及其他事件类型,并返回删除+行数。清除水位会拒绝延迟到达的清除前记录。清除不会关闭统计:设置仍开启时,+后续活动可以立即产生新记录。++原始 Skill 事件的保留窗口为 90 天;每日统计保留含当天在内的 365 个 UTC 日期。+每日统计仍关联 Session,并不是匿名的全局汇总。控制器运行期间会在后台分批清理,+因此过期数据可能要等维护任务追上后才被删除。这些窗口不受 Skill 统计开关或+工具 trace 保留开关影响。归档 Session 不删除其统计;物理清除 Session 会删除+与它关联的 Skill 事件及每日统计。++清除与保留清理都是逻辑删除,不代表安全擦除或保证释放磁盘空间;旧数据可能+仍存在于 SQLite WAL、空闲页或备份中。恢复数据库备份也会恢复其中的历史统计+及清除水位,必要时应在恢复后再次清除。此功能不会扫描或回填历史对话。+### `vibe memory`通过现有 mode-0600 控制器 socket 读取当前范围内的本地记忆,或提交内容进行尽力而为的进程内捕获——既包括用户明确要求记住的内容,也包括 Agent 从对话以及在本机工作中主动提炼的结论(含在文件或工具输出中遇到的持久环境、账户事实)。接受请求不保证提供方投递或持久化。该命令不会启动服务,也没有清空、配置、导出或删除子命令。diff --git a/docs/plans/harness-skill-observability.md b/docs/plans/harness-skill-observability.mdnew file mode 100644index 000000000..46515edc5--- /dev/null+++ b/docs/plans/harness-skill-observability.md@@ -0,0 +1,465 @@+# Harness Skill Observability++Status: Implemented in an isolated development worktree; not deployed.+Date: 2026-09-07.+Design baseline: `e8060055d291fa1f4f0897b4a8947b1a5854c1ee`.+Implementation migration: `20260907_0061` (parent `20260821_0060`).+Schema contract: [harness-skill-observability.sql](harness-skill-observability.sql).++## Decision++Add **one table**, `skill_usage_daily`, for session-grained daily Skill metrics.+Reuse `agent_events` for structured observations, adding one partial index and+two event types without adding columns. Keep operational Sessions, Turns, Runs,+deliveries, and Model Hub usage under their existing owners.++The first release answers which Skills Avibe offered and successfully loaded,+how broadly they were loaded, and where loading failed. These are observable+facts, not evidence that a Skill was followed or caused task success.++For example, one Session loads the same Skill twice on Monday and once on+Tuesday. The report shows three loads, two active days, and **one** distinct+Session. Adding two daily distinct-Session counts would incorrectly report two.+Keeping Session identity in the aggregate preserves the correct answer after+raw-event retention expires.++This design adds local statistics only. It does not create a dashboard, change+Skill ranking or instructions, add agent self-reporting commands, run task-content+classification, or upload data. No cloud table or telemetry vendor is required.++## Baseline Sources and Gaps++| Existing owner | Reuse | Boundary |+| --- | --- | --- |+| `vibe/cli.py:cmd_skill` | Explicit list/load operation boundary | Currently resolves, reads, and prints; it does not record Skill observations. |+| `core/managed_skills.py` | Actual winning Skill, catalog pagination, loaded body | Discovery reads frontmatter, not every body. Ordinary filesystem reads can bypass the command. |+| `storage/agent_events_service.py` | Internal events with Session/Turn/Run references | Existing tool events often contain presentation text, not structured tool results. |+| `core/caller_context.py` | Session, backend, optional Run and origin | No uniform exact Turn identity; a long-lived Claude environment cannot carry changing authors or Turns reliably. |+| `session_turns`, `agent_runs`, `message_deliveries` | Operational state, timestamps, parent/child links, receipts | A completed Turn is not independently verified task success. Not all IM turns have a durable Workbench Turn. |+| Model Hub usage and provenance | Existing token normalization and routing evidence | Gateway observations are partial coverage, not a complete ledger of all backend activity. |++Existing tool traces expire under a separate policy, currently defaulting to+30 days. The existing retention predicate only deletes `tool_call` trace rows.+Adding Skill event types alone would therefore leave them indefinitely retained;+implementation must add an explicit Skill policy to the existing retention owner.++## Observation Contract++### Common envelope++Use existing `agent_events` columns as follows:++| Column | Meaning for Skill observations |+| --- | --- |+| `id` | Producer-allocated immutable observation ID; reused only for retransmission. |+| `scope_id`, `session_id` | Validated local execution ownership; nullable. |+| `turn_id`, `run_id` | Exact, independently validated links when available; otherwise null. |+| `platform`, `backend`, `agent_name` | Execution snapshot; unknown values stay unknown. |+| `event_type` | `skill.catalog_result` or `skill.load_result`. |+| `visibility`, `source` | `trace`, `runtime`; never transcript or Inbox content. |+| `content_text` | Null; no copied Skill text, shell command, or free-form error. |+| `content_json` | Typed event payload below. |+| `metadata_json` | Observation schema and execution provenance below. |+| `created_at`, `updated_at` | Existing recorder timestamps, not the producer's clock. |+| `sequence` | Null unless supplied by an existing authoritative execution sequence. |++Common `metadata_json` fields:++```json+{+ "schema_version": 1,+ "observed_at": "2026-09-07T03:00:00.000000Z",+ "observation_channel": "avibe_cli",+ "correlation_level": "session_only",+ "trigger_kind": "human",+ "model": null,+ "avibe_version": "fixture-release",+ "context_ref": null+}+```++`observation_channel` is `avibe_cli` or `runtime_prompt`.+`correlation_level` is `exact_turn`, `session_only`, or `unattributed`.+`context_ref` is an optional execution-context reference from the runtime, not+an agent-generated description. Record the model only from evidence applicable+to this execution; do not read the Session's current model later and backfill it.+The trigger taxonomy is declared in the SQL contract; an unknown origin is not+automatically human. A direct terminal command is `standalone` only when that+origin is established, not merely because its Session reference is missing.++The IPC metadata also carries `backend`, which the writer moves into the+existing event column. It comes from the bound CLI environment or the backend+adapter, not a later Session configuration lookup. Scope, platform, and agent+label are resolved from validated Session ownership at receipt time; they are+not independently observed historical execution facts.++### Catalog result++Emit `skill.catalog_result` when a `vibe skill list` result has been written to+stdout, or when a catalog-bearing prompt has positive backend acceptance. Also+record failed list operations with a bounded reason code and an empty entry list.+Pure resolver scans, preview pages, and prompt rendering are not offers.++Payload fields:++| Field | Type | Meaning |+| --- | --- | --- |+| `entry_point` | string | `cli_list` or `runtime_prompt`. |+| `outcome` | string | `success` or `failure`. |+| `error_code` | string/null | Stable reason, such as `invalid_page` or `output_interrupted`. |+| `page` | integer | Actual returned catalog page; first prompt page is 1. |+| `has_more` | boolean | Whether another page was available at the observation. |+| `catalog_digest` | string/null | SHA-256 of this exact ordered page descriptor, including descriptor versions. |+| `entries` | array | Actual returned entries, each with `skill_key`, `skill_name`, `source_kind`, `descriptor_sha256`, and 1-based page position. |++Each entry increments `catalog_offer_count` once in a bucket whose+`skill_revision` is empty. A body revision is not available during discovery;+do not read all Skill bodies merely to assign one. The descriptor digest covers+the normalized name, description, and model-invocation setting. Store the digest,+not the description. Empty or failed pages contribute no per-Skill buckets.++An accepted prompt is an offer to the backend, not proof of model attention.+Reusing an unchanged prompt in a persistent backend does not emit another offer+unless there is evidence of another catalog submission. Replaying the same+acceptance receipt does not create another offer. An actual new submission gets+a new observation ID even when the catalog digest is unchanged.++Do not label loads divided by offers a selection probability: repeated loads,+retained context, direct user requests, and incomplete prompt-acceptance coverage+make the populations different. Page/position analysis is diagnostic only until+an evaluation defines a common exposure and selection unit.++### Load result++Emit `skill.load_result` once after a load operation finishes, including failure.+Success means the selected body was read and output completed, including flush;+it does not assert that downstream tools avoided truncation or the model read it.++| Field | Type | Meaning |+| --- | --- | --- |+| `skill_key` | string/null | Resolved local identity, or unresolved lookup identity. |+| `skill_name` | string/null | Validated portable Skill name. Invalid arbitrary input is not persisted. |+| `source_kind` | string | `builtin`, `project`, `global`, or `unresolved`. |+| `skill_revision` | string/null | Digest of the successfully read instruction snapshot; may exist even when output later fails. |+| `descriptor_sha256` | string/null | Descriptor version from that same read. |+| `outcome` | string | `success` or `failure`. |+| `error_code` | string/null | `invalid_name`, `not_found`, `unreadable_or_invalid`, `output_interrupted`, or `internal_error`. |+| `duration_ms` | integer/null | Monotonic duration from resolution start through output completion, excluding observation persistence. |+| `body_bytes` | integer/null | UTF-8 byte length of the loaded body, excluding the wrapper; not a token estimate. |++Preserve the existing public CLI output contract. Internal error classification+may become more precise later, but a loader returning `None` only justifies+`unreadable_or_invalid`, not an invented parse or permission diagnosis.+An invalid name still produces a failure event without a Skill bucket.+Successful loads require a nonempty identity and revision. Failed loads increment+failure counters; only successful loads contribute `loaded_body_bytes_sum`.++### Skill identity and revision++`skill_key` is SHA-256 over a versioned canonical JSON tuple:++- Built-in: `[1, "builtin", declared_name]`; published snapshot directories do+ not change the logical identity on every Avibe upgrade.+- Resolved user Skill: `[1, source_kind, canonical_directory, declared_name]`.+ Symlink aliases resolving to the same winning directory share identity;+ different project installations remain distinct.+- Valid but unresolved lookup: `[1, "unresolved", canonical_project_base_or_cwd,+ requested_name]`. It cannot be confused with a resolved Skill.++Canonical JSON uses UTF-8, ordered tuple elements, no optional whitespace, and no+ASCII escaping. Paths are inputs to the local key, not persisted fields. These+hashes are local correlation identifiers, **not anonymous or globally portable+identities**. A moved directory becomes a new identity; v1 has no identity-merger.+Plugin locations use their effective global/project scope, not another registry.++`skill_revision` hashes the canonical tuple `[1, name, description,+disable_model_invocation, body]` from the same successful read. It identifies the+observed instruction snapshot, not the entire package: supporting scripts,+references, and assets are excluded. Full package manifests belong in a later+reproducible-evaluation contract if required. No new frontmatter is required.++## Daily Table++The SQL file is the exact proposed DDL. One row has this grain:++```text+UTC day x scope x Session x Skill identity x instruction revision+ x backend x model x trigger kind x platform x Avibe version+```++| Fields | Responsibility |+| --- | --- |+| `id` | Local surrogate primary key. |+| `day` | Validated UTC calendar date. Query windows use half-open UTC dates. |+| `scope_id`, `session_id` | Nullable local ownership with cascade deletion. |+| `skill_key`, `skill_name`, `source_kind`, `skill_revision` | Immutable observed Skill dimensions. |+| `backend`, `model`, `trigger_kind`, `platform`, `avibe_version` | Runtime snapshot dimensions, not joins to today's settings. |+| `catalog_offer_count` | Number of recorded successful offers of this Skill. |+| `load_success_count`, `load_failure_count` | Number of terminal load observations by result. |+| `load_duration_samples`, `load_duration_ms_sum`, `load_duration_ms_max` | Sample count, sum, and maximum for load durations across both outcomes. |+| `loaded_body_bytes_sum` | Body bytes from successful loads only. |+| `first_observed_at`, `last_observed_at` | Earliest/latest observation contributing to this bucket. |++Use empty strings for an unknown revision/backend/model in bucket keys, while+the raw event uses JSON null. Normalize optional scope/Session IDs with+`coalesce` in the unique index: SQLite's ordinary NULL uniqueness would otherwise+allow duplicate standalone buckets. No fabricated Session is created.++The writer validates ISO dates, fixed-width UTC microsecond timestamps, bounded+strings, integer counters, and consistent identity descriptors before insertion.+Check constraints defend the stored shape; they do not replace input validation.+Catalog offers have unknown instruction revisions and must be grouped across+revisions to compare with loads of the same logical Skill.++No lifetime counter is added to a Skill registry: a registry entry is mutable,+and removal/reinstallation must not redefine historical observations.++## Recording, Correlation, and Reliability++Use one shared storage operation to insert the event and update its daily+projection in the **same SQLite transaction**. The existing generic append+function currently allocates a fresh ID; the Skill recording operation must+accept the producer's immutable observation ID explicitly.++1. Resolve and validate ownership and the event schema.+2. Insert with `ON CONFLICT (id) DO NOTHING`.+3. Only if a new event was inserted, upsert its daily contributions.+4. Commit both, then mark the observation accepted. Any error rolls back both.++HTTP 202 with `status=queued` acknowledges bounded queue admission only, not a+durable commit. The runtime health counters distinguish queued, accepted,+duplicate, rejected, disabled, and dropped observations. There is no retry spool.++A duplicate ID with a different semantic payload is a contract violation, not+another observation. Do not use a broad ignore that masks other constraints.+Actual repeated CLI invocations allocate new IDs and therefore remain visible.++CLI producers submit through bounded internal IPC to the existing local service;+the catalog-prompt producer uses the same recorder in the runtime. The CLI's+resolved metadata describes the file it actually read. Do not re-resolve in the+server's working directory. Use the existing trusted local-caller boundary;+Skill names, environment strings, or an agent-supplied Session ID alone are not+authorization to inspect another user's observations.++Session linkage is useful even without a Turn. Exact Turn/Run attribution+requires execution-scoped evidence tied to the originating request. In particular,+do not pick the Session's currently active Turn at receipt time: delayed tools,+background children, and persistent backend processes can belong to earlier work.+Stale or unverifiable Run/model/trigger fields remain unknown. Native backend+subagents inheriting a parent environment are not independently attributed unless+the runtime supplies a distinct execution identity. Cross-backend and Web/IM+coverage must be reported separately until those paths have verified parity.++Statistics must not turn an otherwise successful Skill load into a failure.+IPC and storage waits have finite budgets; a full recorder queue or unavailable+service drops the observation with a bounded diagnostic and producer-side+health counter. Do not add an offline spool or retry indefinitely in v1.+If transport retries an unacknowledged submission within its budget, it reuses+the ID. Reject submissions outside a 24-hour observation-age bound so deleted+dedupe evidence cannot be reintroduced after retention. Validate future clock+skew as well; rejected observations count as collection failures.++Diagnostic counters cover accepted, rejected, dropped, and uncorrelated+observations and expose their process start/reset time. They are best-effort:+an abrupt producer crash can lose both an event and its counter. Reports state+collection start, retention limits, unknown attribution, and observed gaps;+they never claim complete usage coverage. Existing `state_meta` may hold the+first-accepted-observation timestamp and the clear-history watermark described below; it is+not another metric-series store.++No browser SSE subscription is used as a recording source. UI availability and+display settings cannot decide whether an operation contributes to statistics.++## Queries and Guarantees++Example: successful-load ranking for the 30 complete UTC days before September 8.++```sql+SELECT skill_key, skill_name, source_kind,+ SUM(load_success_count) AS successful_loads,+ COUNT(DISTINCT CASE WHEN load_success_count > 0+ THEN session_id END) AS distinct_sessions,+ COUNT(DISTINCT CASE WHEN load_success_count > 0+ THEN day END) AS active_days,+ SUM(CASE WHEN session_id IS NULL+ THEN load_success_count ELSE 0 END) AS unassociated_loads+FROM skill_usage_daily+WHERE day >= '2026-08-09' AND day < '2026-09-08'+GROUP BY skill_key, skill_name, source_kind+HAVING SUM(load_success_count) > 0+ORDER BY distinct_sessions DESC, successful_loads DESC, skill_key;+```++- Distinct Sessions are computed across the whole requested window, all+ revisions, and all selected runtime dimensions. Never sum distinct counts+ from days, backends, or Skills. Unassociated loads do not invent a user.+- Built-in versus non-built-in is an available filter; being built-in does not+ imply a Skill is only operational guidance.+- Load failure rate is failures / (successes + failures); a zero denominator+ is undefined. Invalid-name failures are available separately from raw events.+- Average duration is sum / sample count. Daily maxima can be combined with+ `MAX`; P50/P95 cannot be reconstructed from this summary and require retained+ raw observations. Byte counts are not token or money measurements.+- Same-Turn reloads, error classifications, catalog page/position comparisons,+ and exact execution joins use raw events within retention. Same-Session loads+ on different days are not automatically redundant work.+- Access uses the existing scope/Session authorization boundary. Instance-wide+ reports and unassociated observations require local-owner/admin access.+ Querying statistics must not bypass Skill or project authorization.++Internal queries are sufficient for v1. An implementation may extend the+existing read-only data-query catalog with the same access controls; it must not+make a global statistics endpoint implicitly available to every remote caller.++## Retention and Deletion++- Raw Skill events: 90 days by recorder `created_at`; own explicit event-type+ allowlist within the existing retention service. Tool and silent-terminal+ policies stay independent.+- Daily rows: 365 UTC dates including today; prune in bounded batches by `day`.+ This is a session-grained local history, not an anonymous global aggregate.+- Daily rows are updated transactionally at recording time, so raw pruning+ cannot erase pending aggregation work. Do not rebuild older daily rows from+ a partially retained raw window or reset them on upgrade.+- Purging a Session deletes its Skill events before the existing event FK can+ set `session_id` to null; daily rows cascade. Purging a scope removes both.+ Archiving is not purging. Restore/replay must not resurrect purged events.+ Late submissions referencing deleted ownership are rejected, not reassigned+ to an unassociated bucket.+- Clearing statistics deletes only these event types and their daily rows. In+ the same transaction, set `state_meta` key+ `skill_observability.cleared_through` to the current UTC timestamp. The recorder+ rejects observations at or before that watermark, including retried old IDs;+ validate observation time against the receiving local clock so a future-dated+ event cannot evade clearing. Recheck this watermark and collection enablement+ inside the recording transaction, after taking the writer lock. Disabling+ future collection and clearing history are separate actions.+- Time bounds limit history, not event rate. Queue and batch bounds protect the+ foreground path; monitor row growth before introducing cardinality eviction.+ Any future eviction must report reduced coverage rather than silently bias+ the ranking.++Alembic revision `20260907_0061` creates this table/index and updates model+metadata, with no historical backfill from free-form tool text. Downgrade removes+only the new objects and these event types. Existing data is unchanged by+upgrade and downgrade. DDL tolerates the existing head-schema repair/replay path.++## Further Harness Measurements++These remain a prioritized roadmap, not additional empty tables in this change.++| Priority | Measurement and producer | Decision supported |+| --- | --- | --- |+| Next | Queue/start/terminal and callback latency from delivery, Turn, and Run owners; distinguish start from useful first output | Locate scheduling, backend startup, and delivery delays. |+| Next | Structured tool completion, stable tool category, error class, retry/recovery links from shared adapter events | Improve tool contracts and recovery without parsing shell text. |+| Next | Actual model and normalized reported usage from existing Model Hub/backend owners, with source and coverage | Compare resource use without double-counting gateway and SDK reports. |+| Later | Actual prompt-injection bytes, compaction boundaries, Memory retrieval latency/result counts | Improve context supply; a retrieval hit does not establish usefulness. |+| Later | Task/Watch firing delay, no-event cycles, parent/child Runs, callback accepted versus processed | Reduce empty wakeups and lost or delayed follow-ups. |+| Later | Explicit user corrections, stop/steer/approval events and verified task outcomes | Measure human intervention and outcome quality separately. |++Use existing operational rows for facts they already own. New observations can+use typed internal events when needed; do not create another Turn state machine,+token ledger, task registry, or generic metric-name/value table preemptively.+Per-task outcome identity and its evaluator need a separate contract before+claiming task success rate. Agent self-report, process exit, test evidence, and+human acceptance are different evidence types. Multiple Skills in one task do+not each receive the task's entire cost or causal credit.++Build a versioned, consented, sanitized evaluation set from representative+failures. Compare the same cases across Harness changes; field usage is a+diagnostic signal and cannot itself establish causal improvement.++## Local Collection and Future Fleet Analysis++Local metadata collection uses `runtime.skill_observability_enabled`, defaulting+to `true`. Set it to `false` in the existing runtime configuration to stop new+collection; the writer rereads it before each transaction commits. Invalid or+unreadable configuration fails closed. It stores no new Skill bodies,+conversation text, tool arguments, filesystem paths, credentials, or raw errors.+Names and locally correlatable hashes are still private local data.++Fleet analysis is a separate opt-in capability and is off in this design.+Before implementing it, define consent, upload/delete behavior, and server+retention. Public Skills require verified registry/source identities, not names+or unverified local hashes. Private Skills contribute only explicitly permitted+coarse categories. Do not upload Session IDs, paths, names of private Skills, or+body hashes. Deduplicated installations are not deduplicated people, and daily+installation counts cannot be summed into monthly unique installations. A cloud+schema must be designed against that future consent and identity contract.++## Operations and Coverage++- `vibe data skill-usage --json` reports enablement, first accepted observation,+ clear watermark, row counts, and retention windows. It is not a usage ranking UI.+- `vibe data query --sql 'SELECT ...' --json` runs the queries above.+- `vibe data skill-usage --clear --yes --json` clears only Skill statistics.+ Disabling collection does not clear history, and clearing does not disable it.+ This is logical deletion, not secure erasure of SQLite free pages, WAL, or+ pre-existing database backups. Explicitly restoring an older full database+ also restores its historical statistics and watermark; clear again afterward+ if that restored history must be removed.+- These statistics require Instance Owner access. Non-owner SQL requests cannot+ read either `skill_usage_daily` or `agent_events`, including through CTEs,+ because the generic SQL reader has no per-resource row filter.+- The owner-only internal Unix socket provides+ `GET /internal/skill-observations/health`. Counters reset at controller restart;+ an event dropped before reaching the controller cannot appear in its counters.+- CLI IPC uses a 250 ms timeout per transport phase. Payloads are capped at+ 32 KiB, the queue at 128 observations, and there is one serial database writer.+ Shutdown drops queued optional work and joins the single in-flight write.+- The existing maintenance worker prunes up to ten 1,000-row batches per surface+ per pass. It never vacuums automatically and runs independently of collection+ and tool-trace retention enablement.+- Claude offers a catalog once after the new client's first accepted query.+ Codex counts positively acknowledged developer-item injections, not prompt+ rendering or unchanged cached instructions. OpenCode counts accepted initial+ prompts and matching catalog resubmissions during live steering/retries.+- Restored OpenCode polls have no trusted catalog candidate and are not counted+ retrospectively. Native subagents, direct filesystem reads, and ambiguous+ native acknowledgements are not claimed as complete coverage.+- Run/model linkage remains unknown in this release. Exact Turn linkage is used+ only when the runtime request names a matching durable `session_turns` row.+ CLI attribution remains Session-only even if an inherited shell names a Turn.++## Verification++The proposed DDL was executed in an in-memory SQLite database with minimal+fixtures for the three referenced existing tables. Seven SQL assertions passed:+cross-day/version/backend distinct counting, nullable-key upsert, aggregate+survival after raw deletion, duplicate observation handling, transactional+rollback, Session cascade deletion, and scope cascade deletion. Foreign-key+checking returned no violations.++Implementation tests additionally exercise real migration upgrade/downgrade and+replay, models/migration parity, concurrent duplicate receipts, atomic rollback,+nullable buckets, UTC retention boundaries, indexed pruning, narrow clear with+a watermark, physical Session purge versus archive, owner-only SQL, strict+configuration, bounded IPC/queue behavior, and backend acceptance boundaries.+The combined targeted suite passes 1,908 tests and 28 subtests (one platform+capability skip). This includes the installed Codex binary's three loopback+prompt-contract tests, release migration guards, unrelated settings saves that+preserve the collection opt-out, localized CLI errors/help, and recorder cleanup+on server exit, cancellation, or startup failure. The expanded suite also passes+with the CI-resolved FastAPI 0.141.1 and Starlette 1.6.0 versions. Ruff and+whitespace validation also pass.+No production database or runtime configuration was migrated or deployed.+Container regression is unverified: the workstation's Incus client has no+configured Linux daemon. No remote operational environment was substituted.++## Implementation Acceptance++- [x] CLI and accepted prompt boundaries produce factual, typed observations;+ scans/rendering alone do not change counts.+- [x] An observation changes the event log and aggregate together exactly once;+ retries, concurrency, and transaction rollback preserve that property.+- [x] Distinct-Session queries remain correct across dates, revisions, models,+ and missing Session linkage, including after raw-event pruning.+- [x] Unproven execution attribution stays unknown on every backend and platform.+- [x] Observation failure leaves the original Skill operation's output and exit+ semantics intact and exposes the observed collection gap.+- [x] Invalid inputs, missing bodies, and interrupted output cannot count as a+ successful load or introduce arbitrary command text into statistics.+- [x] Authorization, purge, disable, and retention apply consistently to raw and+ aggregate data; existing unrelated row shapes survive migration unchanged.+- [x] SQL models and migration agree on columns, constraints, and indexes. All+ verification uses test-owned databases, never the local running service.diff --git a/docs/plans/harness-skill-observability.sql b/docs/plans/harness-skill-observability.sqlnew file mode 100644index 000000000..6c0d2aa44--- /dev/null+++ b/docs/plans/harness-skill-observability.sql@@ -0,0 +1,99 @@+-- Reference DDL. Runtime upgrades are owned by Alembic revision 20260907_0061.+-- Not an operational script; use only isolated schema-verification fixtures.+-- Contract: harness-skill-observability.md.++CREATE TABLE skill_usage_daily (+ id INTEGER PRIMARY KEY,+ day TEXT NOT NULL,+ scope_id TEXT REFERENCES scopes(id) ON DELETE CASCADE,+ session_id TEXT REFERENCES agent_sessions(id) ON DELETE CASCADE,+ skill_key TEXT NOT NULL,+ skill_name TEXT NOT NULL,+ source_kind TEXT NOT NULL,+ skill_revision TEXT NOT NULL DEFAULT '',+ backend TEXT NOT NULL DEFAULT '',+ model TEXT NOT NULL DEFAULT '',+ trigger_kind TEXT NOT NULL DEFAULT 'unknown',+ platform TEXT NOT NULL DEFAULT 'unknown',+ avibe_version TEXT NOT NULL,+ catalog_offer_count INTEGER NOT NULL DEFAULT 0,+ load_success_count INTEGER NOT NULL DEFAULT 0,+ load_failure_count INTEGER NOT NULL DEFAULT 0,+ load_duration_samples INTEGER NOT NULL DEFAULT 0,+ load_duration_ms_sum INTEGER NOT NULL DEFAULT 0,+ load_duration_ms_max INTEGER NOT NULL DEFAULT 0,+ loaded_body_bytes_sum INTEGER NOT NULL DEFAULT 0,+ first_observed_at TEXT NOT NULL,+ last_observed_at TEXT NOT NULL,++ CONSTRAINT ck_skill_usage_day CHECK (+ day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'+ ),+ CONSTRAINT ck_skill_usage_ids CHECK (+ (scope_id IS NULL OR length(scope_id) > 0)+ AND (session_id IS NULL OR length(session_id) > 0)+ ),+ CONSTRAINT ck_skill_usage_key CHECK (+ length(skill_key) = 64 AND skill_key NOT GLOB '*[^0-9a-f]*'+ ),+ CONSTRAINT ck_skill_usage_name CHECK (length(skill_name) BETWEEN 1 AND 64),+ CONSTRAINT ck_skill_usage_source CHECK (+ source_kind IN ('builtin', 'project', 'global', 'unresolved')+ ),+ CONSTRAINT ck_skill_usage_revision CHECK (+ skill_revision = '' OR (+ length(skill_revision) = 64+ AND skill_revision NOT GLOB '*[^0-9a-f]*'+ )+ ),+ CONSTRAINT ck_skill_usage_trigger CHECK (+ trigger_kind IN (+ 'human', 'task', 'watch', 'agent_run', 'callback',+ 'standalone', 'unknown'+ )+ ),+ CONSTRAINT ck_skill_usage_counts CHECK (+ typeof(catalog_offer_count) = 'integer' AND catalog_offer_count >= 0+ AND typeof(load_success_count) = 'integer' AND load_success_count >= 0+ AND typeof(load_failure_count) = 'integer' AND load_failure_count >= 0+ AND catalog_offer_count + load_success_count + load_failure_count > 0+ AND (load_success_count = 0 OR skill_revision <> '')+ AND (catalog_offer_count = 0 OR skill_revision = '')+ ),+ CONSTRAINT ck_skill_usage_duration CHECK (+ typeof(load_duration_samples) = 'integer'+ AND load_duration_samples BETWEEN 0 AND load_success_count + load_failure_count+ AND typeof(load_duration_ms_sum) = 'integer' AND load_duration_ms_sum >= 0+ AND typeof(load_duration_ms_max) = 'integer'+ AND load_duration_ms_max BETWEEN 0 AND load_duration_ms_sum+ AND (load_duration_samples > 0 OR load_duration_ms_sum = 0)+ ),+ CONSTRAINT ck_skill_usage_bytes CHECK (+ typeof(loaded_body_bytes_sum) = 'integer' AND loaded_body_bytes_sum >= 0+ AND (load_success_count > 0 OR loaded_body_bytes_sum = 0)+ ),+ CONSTRAINT ck_skill_usage_observed CHECK (+ length(first_observed_at) = 27 AND length(last_observed_at) = 27+ AND substr(first_observed_at, 1, 10) = day+ AND substr(last_observed_at, 1, 10) = day+ AND first_observed_at <= last_observed_at+ )+);++-- SQLite normally treats two NULLs as distinct in a UNIQUE key. Normalize+-- optional IDs here so unassociated observations share one real bucket.+CREATE UNIQUE INDEX uq_skill_usage_daily_grain ON skill_usage_daily (+ day, coalesce(scope_id, ''), coalesce(session_id, ''), skill_key,+ skill_revision, backend, model, trigger_kind, platform, avibe_version+);+CREATE INDEX ix_skill_usage_daily_skill_day+ ON skill_usage_daily (skill_key, day);+CREATE INDEX ix_skill_usage_daily_session_day+ ON skill_usage_daily (session_id, day);+CREATE INDEX ix_skill_usage_daily_scope_day+ ON skill_usage_daily (scope_id, day);++-- Existing table: no new columns, no change to existing rows or event types.+CREATE INDEX ix_agent_events_skill_created_id ON agent_events (created_at, id)+ WHERE visibility = 'trace'+ AND event_type IN ('skill.catalog_result', 'skill.load_result');diff --git a/modules/agents/base.py b/modules/agents/base.pyindex 607247b7c..28efc9079 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -81,6 +81,7 @@ class AgentRequest:# settled after delivery. The shared dispatcher sees only ``output``.output_activities: List[Any] = field(default_factory=list)input_metadata: AgentInputMetadata | None = None+ skill_catalog_observation: Optional[dict[str, Any]] = None@dataclassdiff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 7efd65859..0f98414ca 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -214,6 +214,10 @@ class ClaudeAgent(BaseAgent):self._remove_native_input_receipt(runtime_session_key, input_receipt)raiseinput_receipt.state = "accepted"+ from core.skill_observability import accept_catalog++ accept_catalog(self.controller, context, getattr(client, "_vibe_pending_skill_catalog", None), backend="claude")+ setattr(client, "_vibe_pending_skill_catalog", None)if (runtime_session_key not in self.receiver_tasksor self.receiver_tasks[runtime_session_key].done()diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 80b89fb68..d11786472 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -2518,6 +2518,7 @@ class CodexAgent(BaseAgent):# that write.configure_memory_cli_access(self.controller, request.context)+ skill_catalog_sink: list[dict] = []instruction_parts.append(await asyncio.to_thread(build_system_prompt_injection,@@ -2535,9 +2536,11 @@ class CodexAgent(BaseAgent):skills_claude_cli_path=managed_skill_claude_cli_path(getattr(getattr(self, "controller", None), "config", None)),+ skill_catalog_sink=skill_catalog_sink,))+ request.skill_catalog_observation = skill_catalog_sink[0] if skill_catalog_sink else Nonereturn "".join(part for part in instruction_parts if part) or Noneasync def _inject_forked_session_correction(@@ -2884,6 +2887,11 @@ class CodexAgent(BaseAgent):raise CodexPromptRefreshUnavailableError("Codex rejected developer prompt injection; check app-server API compatibility") from exc+ from core.skill_observability import accept_catalog++ candidate = getattr(request, "skill_catalog_observation", None)+ if candidate is not None:+ accept_catalog(self.controller, request.context, candidate, backend="codex")if not self._persist_prompt_strategy(request,thread_id,diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex d0d04df4d..47f54159a 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -159,6 +159,7 @@ class _OpenCodeSteerState:reasoning_effort: Optional[str]system: Optional[str]baseline_message_ids: set[str]+ catalog_accepted: Any = Nonelock: asyncio.Lock = field(default_factory=asyncio.Lock)closing: bool = Falseawaiting_after_message_ids: set[str] | None = None@@ -685,6 +686,8 @@ class _SteeringAwareOpenCodeServer:self._state.awaiting_active_status_observed = Falseself._state.awaiting_result_confirmation_deadline = Noneawait self._server.prompt_async(*args, **{k: v for k, v in kwargs.items() if k != "awaiting_after_ids"})+ if kwargs.get("system") == self._state.system and self._state.catalog_accepted:+ self._state.catalog_accepted()if snapshot_ids is not None:self._state.awaiting_prompt_accepted = Trueself._state.awaiting_prompt_activity_deadline = (@@ -1555,6 +1558,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):))+ skill_catalog_sink: list[dict] = []system_prompt_injection = await asyncio.to_thread(build_system_prompt_injection,include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)@@ -1570,6 +1574,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):skills_claude_cli_path=managed_skill_claude_cli_path(getattr(getattr(self, "controller", None), "config", None)),+ skill_catalog_sink=skill_catalog_sink,)if request.vibe_agent_system_prompt:from core.prompt_registry import render_prompt@@ -1659,6 +1664,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):system=system_prompt_injection,tools={"question": False, "skill": False},)+ from core.skill_observability import accept_catalog++ accept_catalog(self.controller, request.context, skill_catalog_sink[0] if skill_catalog_sink else None, backend="opencode")try:read_prompt_started_at = getattr(server, "get_last_prompt_started_at", None)prompt_started_at = (@@ -1700,6 +1708,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):reasoning_effort=reasoning_effort,system=system_prompt_injection,baseline_message_ids=set(baseline_message_ids),+ catalog_accepted=lambda: accept_catalog(+ self.controller, request.context, skill_catalog_sink[0] if skill_catalog_sink else None,+ backend="opencode",+ ),awaiting_after_message_ids=set(baseline_message_ids),awaiting_user_text=prompt_text,awaiting_prompt_accepted=True,@@ -2092,6 +2104,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):state.awaiting_after_message_ids = before_insertstate.awaiting_user_text = prompt_textstate.awaiting_prompt_accepted = True+ if state.catalog_accepted:+ state.catalog_accepted()state.awaiting_prompt_activity_deadline = (time.monotonic()+ _ASYNC_PROMPT_ACCEPTED_ACTIVITY_TIMEOUT_SECONDSdiff --git a/storage/agent_events_retention.py b/storage/agent_events_retention.pyindex cf897ba29..47735ebc8 100644--- a/storage/agent_events_retention.py+++ b/storage/agent_events_retention.py@@ -1,17 +1,16 @@"""Bounded retention for internal agent trace events (avibe#1506 lane B).-This module is the single owner of ``agent_events`` deletion policy. The-eligibility property, defined once here and shared by planning, execution,-and tests:+This module owns automatic ``agent_events`` retention. Tool-trace retention+and Skill retention have independent allowlists and time windows. The tool+eligibility property, shared by planning, execution, and tests:Only parseable rows with ``event_type='tool_call'`` AND``visibility='trace'`` AND ``created_at`` strictly older than the retentioncutoff are ever removable. Unparseable timestamps are preserved.-Everything else — user messages (a separate table), message deliveries,-session/run records, Vault audit data, non-trace events, and newer traces —-is preserved by construction: no code path in this module deletes a row-outside the predicate, regardless of caller.+``run_skill_retention`` separately removes only the two Skill trace types and+expired Skill daily buckets. User messages, deliveries, session/run records,+Vault audit data, non-trace events, and newer traces remain untouched.Operational shape:@@ -42,7 +41,7 @@ from sqlalchemy import Engine, LargeBinary, delete, func, select, castfrom sqlalchemy.exc import IntegrityError, OperationalErrorfrom sqlalchemy.engine import Connection-from storage.models import agent_events, state_meta+from storage.models import agent_events, skill_usage_daily, state_metafrom vibe.trace_retention_policy import (MAX_RETENTION_DAYS,MIN_RETENTION_DAYS,@@ -66,6 +65,37 @@ RETENTION_MARKER_KEY = "agent_events_trace_retention.last_run"RETENTION_LEASE_KEY = "agent_events_trace_retention.lease"+def run_skill_retention(engine: Engine, *, now=None, cancel_event=None, max_batches: int = 10) -> dict:+ """Independent fixed retention, on the existing maintenance worker.++ Each pass is bounded; concurrent passes are harmless because selection and+ deletion share one statement. No rebuild from raw events and no VACUUM.+ """+ from storage.skill_observability import DAILY_RETENTION_DAYS, RAW_RETENTION_DAYS, SKILL_TRACE_FILTER++ instant = now or _utc_now()+ raw_cutoff = _iso(instant - timedelta(days=RAW_RETENTION_DAYS))+ daily_cutoff = (instant.astimezone(timezone.utc).date() - timedelta(days=DAILY_RETENTION_DAYS - 1)).isoformat()+ targets = (+ (agent_events, SKILL_TRACE_FILTER+ & func.datetime(agent_events.c.created_at).is_not(None)+ & (agent_events.c.created_at < raw_cutoff)),+ (skill_usage_daily, skill_usage_daily.c.day < daily_cutoff),+ )+ deleted = {"events": 0, "daily_rows": 0}+ for key, (table, predicate) in zip(deleted, targets):+ for _ in range(max_batches):+ if cancel_event is not None and cancel_event.is_set():+ return deleted+ with engine.begin() as conn:+ ids = select(table.c.id).where(predicate).limit(DELETE_BATCH_ROWS)+ count = conn.execute(table.delete().where(table.c.id.in_(ids))).rowcount+ deleted[key] += count+ if count < DELETE_BATCH_ROWS:+ break+ return deleted++@dataclass(frozen=True)class RetentionPolicy:"""The validated policy used by every retention entry point.diff --git a/storage/alembic/versions/20260907_0061_skill_observability.py b/storage/alembic/versions/20260907_0061_skill_observability.pynew file mode 100644index 000000000..e9a5b1cda--- /dev/null+++ b/storage/alembic/versions/20260907_0061_skill_observability.py@@ -0,0 +1,135 @@+"""Local Skill observations and daily usage.++Revision ID: 20260907_0061+Revises: 20260821_0060+"""++from __future__ import annotations++import sqlite3++from alembic import op++revision = "20260907_0061"+down_revision = "20260821_0060"+branch_labels = None+depends_on = None+MIGRATION_SAFETY = "additive"++_DDL = """+-- Contract: harness-skill-observability.md.++CREATE TABLE IF NOT EXISTS skill_usage_daily (+ id INTEGER PRIMARY KEY,+ day TEXT NOT NULL,+ scope_id TEXT REFERENCES scopes(id) ON DELETE CASCADE,+ session_id TEXT REFERENCES agent_sessions(id) ON DELETE CASCADE,+ skill_key TEXT NOT NULL,+ skill_name TEXT NOT NULL,+ source_kind TEXT NOT NULL,+ skill_revision TEXT NOT NULL DEFAULT '',+ backend TEXT NOT NULL DEFAULT '',+ model TEXT NOT NULL DEFAULT '',+ trigger_kind TEXT NOT NULL DEFAULT 'unknown',+ platform TEXT NOT NULL DEFAULT 'unknown',+ avibe_version TEXT NOT NULL,+ catalog_offer_count INTEGER NOT NULL DEFAULT 0,+ load_success_count INTEGER NOT NULL DEFAULT 0,+ load_failure_count INTEGER NOT NULL DEFAULT 0,+ load_duration_samples INTEGER NOT NULL DEFAULT 0,+ load_duration_ms_sum INTEGER NOT NULL DEFAULT 0,+ load_duration_ms_max INTEGER NOT NULL DEFAULT 0,+ loaded_body_bytes_sum INTEGER NOT NULL DEFAULT 0,+ first_observed_at TEXT NOT NULL,+ last_observed_at TEXT NOT NULL,++ CONSTRAINT ck_skill_usage_day CHECK (+ day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'+ ),+ CONSTRAINT ck_skill_usage_ids CHECK (+ (scope_id IS NULL OR length(scope_id) > 0)+ AND (session_id IS NULL OR length(session_id) > 0)+ ),+ CONSTRAINT ck_skill_usage_key CHECK (+ length(skill_key) = 64 AND skill_key NOT GLOB '*[^0-9a-f]*'+ ),+ CONSTRAINT ck_skill_usage_name CHECK (length(skill_name) BETWEEN 1 AND 64),+ CONSTRAINT ck_skill_usage_source CHECK (+ source_kind IN ('builtin', 'project', 'global', 'unresolved')+ ),+ CONSTRAINT ck_skill_usage_revision CHECK (+ skill_revision = '' OR (+ length(skill_revision) = 64+ AND skill_revision NOT GLOB '*[^0-9a-f]*'+ )+ ),+ CONSTRAINT ck_skill_usage_trigger CHECK (+ trigger_kind IN (+ 'human', 'task', 'watch', 'agent_run', 'callback',+ 'standalone', 'unknown'+ )+ ),+ CONSTRAINT ck_skill_usage_counts CHECK (+ typeof(catalog_offer_count) = 'integer' AND catalog_offer_count >= 0+ AND typeof(load_success_count) = 'integer' AND load_success_count >= 0+ AND typeof(load_failure_count) = 'integer' AND load_failure_count >= 0+ AND catalog_offer_count + load_success_count + load_failure_count > 0+ AND (load_success_count = 0 OR skill_revision <> '')+ AND (catalog_offer_count = 0 OR skill_revision = '')+ ),+ CONSTRAINT ck_skill_usage_duration CHECK (+ typeof(load_duration_samples) = 'integer'+ AND load_duration_samples BETWEEN 0 AND load_success_count + load_failure_count+ AND typeof(load_duration_ms_sum) = 'integer' AND load_duration_ms_sum >= 0+ AND typeof(load_duration_ms_max) = 'integer'+ AND load_duration_ms_max BETWEEN 0 AND load_duration_ms_sum+ AND (load_duration_samples > 0 OR load_duration_ms_sum = 0)+ ),+ CONSTRAINT ck_skill_usage_bytes CHECK (+ typeof(loaded_body_bytes_sum) = 'integer' AND loaded_body_bytes_sum >= 0+ AND (load_success_count > 0 OR loaded_body_bytes_sum = 0)+ ),+ CONSTRAINT ck_skill_usage_observed CHECK (+ length(first_observed_at) = 27 AND length(last_observed_at) = 27+ AND substr(first_observed_at, 1, 10) = day+ AND substr(last_observed_at, 1, 10) = day+ AND first_observed_at <= last_observed_at+ )+);++-- SQLite normally treats two NULLs as distinct in a UNIQUE key. Normalize+-- optional IDs here so unassociated observations share one real bucket.+CREATE UNIQUE INDEX IF NOT EXISTS uq_skill_usage_daily_grain ON skill_usage_daily (+ day, coalesce(scope_id, ''), coalesce(session_id, ''), skill_key,+ skill_revision, backend, model, trigger_kind, platform, avibe_version+);+CREATE INDEX IF NOT EXISTS ix_skill_usage_daily_skill_day+ ON skill_usage_daily (skill_key, day);+CREATE INDEX IF NOT EXISTS ix_skill_usage_daily_session_day+ ON skill_usage_daily (session_id, day);+CREATE INDEX IF NOT EXISTS ix_skill_usage_daily_scope_day+ ON skill_usage_daily (scope_id, day);++-- Existing table: no new columns, no change to existing rows or event types.+CREATE INDEX IF NOT EXISTS ix_agent_events_skill_created_id ON agent_events (created_at, id)+ WHERE visibility = 'trace'+ AND event_type IN ('skill.catalog_result', 'skill.load_result');+"""+++def upgrade() -> None:+ statement = ""+ for line in _DDL.splitlines(keepends=True):+ statement += line+ if sqlite3.complete_statement(statement):+ op.get_bind().exec_driver_sql(statement)+ statement = ""+++def downgrade() -> None:+ op.get_bind().exec_driver_sql(+ "delete from agent_events where event_type in "+ "('skill.catalog_result', 'skill.load_result') and visibility = 'trace'"+ )+ op.drop_index("ix_agent_events_skill_created_id", table_name="agent_events")+ op.drop_table("skill_usage_daily")diff --git a/storage/migrations.py b/storage/migrations.pyindex d728ed037..2e6000450 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -60,6 +60,7 @@ HEAD_TABLES = INITIAL_TABLES | {"message_deliveries","session_turns","agent_events",+ "skill_usage_daily","show_session_events","media_objects","media_object_references",diff --git a/storage/models.py b/storage/models.pyindex 6b52557df..fdce0cc5f 100644--- a/storage/models.py+++ b/storage/models.py@@ -500,9 +500,16 @@ agent_events = Table(Index("ix_agent_events_session_type_created_id", "session_id", "event_type", "created_at", "id"),Index("ix_agent_events_scope_created_id", "scope_id", "created_at", "id"),Index("ix_agent_events_turn_sequence_id", "turn_id", "sequence", "id"),- # Retention scan index: bounded age scan over the only rows the retention- # service may ever delete (storage/agent_events_retention.py owns the- # matching predicate; keep the two in sync).+ Index(+ "ix_agent_events_skill_created_id",+ "created_at",+ "id",+ sqlite_where=text(+ "visibility = 'trace' and event_type in ('skill.catalog_result', 'skill.load_result')"+ ),+ ),+ # Tool retention has its own allowlist, independent of Skill retention.+ # Keep this index aligned with storage/agent_events_retention.py.Index("ix_agent_events_trace_retention","created_at",@@ -513,6 +520,98 @@ agent_events = Table(),)+skill_usage_daily = Table(+ "skill_usage_daily",+ metadata,+ Column("id", Integer, primary_key=True),+ Column("day", Text, nullable=False),+ Column("scope_id", Text, ForeignKey("scopes.id", ondelete="CASCADE"), nullable=True),+ Column("session_id", Text, ForeignKey("agent_sessions.id", ondelete="CASCADE"), nullable=True),+ Column("skill_key", Text, nullable=False),+ Column("skill_name", Text, nullable=False),+ Column("source_kind", Text, nullable=False),+ Column("skill_revision", Text, nullable=False, server_default=""),+ Column("backend", Text, nullable=False, server_default=""),+ Column("model", Text, nullable=False, server_default=""),+ Column("trigger_kind", Text, nullable=False, server_default="unknown"),+ Column("platform", Text, nullable=False, server_default="unknown"),+ Column("avibe_version", Text, nullable=False),+ Column("catalog_offer_count", Integer, nullable=False, server_default=text("0")),+ Column("load_success_count", Integer, nullable=False, server_default=text("0")),+ Column("load_failure_count", Integer, nullable=False, server_default=text("0")),+ Column("load_duration_samples", Integer, nullable=False, server_default=text("0")),+ Column("load_duration_ms_sum", Integer, nullable=False, server_default=text("0")),+ Column("load_duration_ms_max", Integer, nullable=False, server_default=text("0")),+ Column("loaded_body_bytes_sum", Integer, nullable=False, server_default=text("0")),+ Column("first_observed_at", Text, nullable=False),+ Column("last_observed_at", Text, nullable=False),+ CheckConstraint(+ "day GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'",+ name="ck_skill_usage_day",+ ),+ CheckConstraint(+ "(scope_id is null or length(scope_id) > 0) and "+ "(session_id is null or length(session_id) > 0)",+ name="ck_skill_usage_ids",+ ),+ CheckConstraint(+ "length(skill_key) = 64 and skill_key not glob '*[^0-9a-f]*'",+ name="ck_skill_usage_key",+ ),+ CheckConstraint("length(skill_name) between 1 and 64", name="ck_skill_usage_name"),+ CheckConstraint(+ "source_kind in ('builtin', 'project', 'global', 'unresolved')",+ name="ck_skill_usage_source",+ ),+ CheckConstraint(+ "skill_revision = '' or (length(skill_revision) = 64 and skill_revision not glob '*[^0-9a-f]*')",+ name="ck_skill_usage_revision",+ ),+ CheckConstraint(+ "trigger_kind in ('human', 'task', 'watch', 'agent_run', 'callback', 'standalone', 'unknown')",+ name="ck_skill_usage_trigger",+ ),+ CheckConstraint(+ "typeof(catalog_offer_count) = 'integer' and catalog_offer_count >= 0 "+ "and typeof(load_success_count) = 'integer' and load_success_count >= 0 "+ "and typeof(load_failure_count) = 'integer' and load_failure_count >= 0 "+ "and catalog_offer_count + load_success_count + load_failure_count > 0 "+ "and (load_success_count = 0 or skill_revision <> '') "+ "and (catalog_offer_count = 0 or skill_revision = '')",+ name="ck_skill_usage_counts",+ ),+ CheckConstraint(+ "typeof(load_duration_samples) = 'integer' "+ "and load_duration_samples between 0 and load_success_count + load_failure_count "+ "and typeof(load_duration_ms_sum) = 'integer' and load_duration_ms_sum >= 0 "+ "and typeof(load_duration_ms_max) = 'integer' "+ "and load_duration_ms_max between 0 and load_duration_ms_sum "+ "and (load_duration_samples > 0 or load_duration_ms_sum = 0)",+ name="ck_skill_usage_duration",+ ),+ CheckConstraint(+ "typeof(loaded_body_bytes_sum) = 'integer' and loaded_body_bytes_sum >= 0 "+ "and (load_success_count > 0 or loaded_body_bytes_sum = 0)",+ name="ck_skill_usage_bytes",+ ),+ CheckConstraint(+ "length(first_observed_at) = 27 and length(last_observed_at) = 27 "+ "and substr(first_observed_at, 1, 10) = day "+ "and substr(last_observed_at, 1, 10) = day "+ "and first_observed_at <= last_observed_at",+ name="ck_skill_usage_observed",+ ),+ Index(+ "uq_skill_usage_daily_grain",+ "day", text("coalesce(scope_id, '')"), text("coalesce(session_id, '')"),+ "skill_key", "skill_revision", "backend", "model", "trigger_kind", "platform", "avibe_version",+ unique=True,+ ),+ Index("ix_skill_usage_daily_skill_day", "skill_key", "day"),+ Index("ix_skill_usage_daily_session_day", "session_id", "day"),+ Index("ix_skill_usage_daily_scope_day", "scope_id", "day"),+)+# Platform-agnostic chat message store. Every IM adapter (Slack, Discord,# Telegram, Lark, WeChat, Avibe/Web UI) writes user+agent turns here so the# workbench Inbox and per-session history can read from a single ORMdiff --git a/storage/read_only_query.py b/storage/read_only_query.pyindex 1e2c3c116..664b467cc 100644--- a/storage/read_only_query.py+++ b/storage/read_only_query.py@@ -38,7 +38,11 @@ def run_read_only_query(page_request: PageRequest | None,db_path: Path | None = None,step_limit: int = DEFAULT_QUERY_STEP_LIMIT,+ user_context=None,) -> QueryResult:+ from storage.resource_access_service import resolve_resource_access_context++ allow_skill_statistics = resolve_resource_access_context(user_context).is_instance_ownerstatement = _validate_single_statement(sql)resolved_db_path = db_path or paths.get_sqlite_state_path()if db_path is None:@@ -55,7 +59,15 @@ def run_read_only_query(try:conn.execute("PRAGMA query_only = ON")- conn.set_authorizer(_authorizer)+ def authorize(action, arg1, arg2, db_name, source):+ # SQL has no resource-row filter. Raw Skill observations share+ # agent_events, so non-owners cannot query that table wholesale.+ if (not allow_skill_statistics and action == sqlite3.SQLITE_READ+ and arg1 in {"skill_usage_daily", "agent_events"}):+ return sqlite3.SQLITE_DENY+ return _authorizer(action, arg1, arg2, db_name, source)++ conn.set_authorizer(authorize)conn.set_progress_handler(progress, 1000)cursor = conn.execute(statement)columns = [item[0] for item in cursor.description or []]diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 41d78dbc5..1ce38c747 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -30,6 +30,7 @@ from storage.agent_session_rows import ()from storage.models import (agents,+ agent_events,agent_runs,agent_sessions,message_deliveries,@@ -2587,6 +2588,14 @@ def _delete_agent_session_rows()deleted += 1continue+ # Skill traces must not survive as unassociated rows after FK SET NULL.+ from storage.skill_observability import EVENT_TYPES++ conn.execute(agent_events.delete().where(+ agent_events.c.session_id == session_id,+ agent_events.c.visibility == "trace",+ agent_events.c.event_type.in_(EVENT_TYPES),+ ))removed = bool(conn.execute(agent_sessions.delete().where(agent_sessions.c.id == session_id)diff --git a/storage/skill_observability.py b/storage/skill_observability.pynew file mode 100644index 000000000..8756092ea--- /dev/null+++ b/storage/skill_observability.py@@ -0,0 +1,425 @@+"""Typed Skill observations and their transactionally maintained projection."""++from __future__ import annotations++import json+import re+from datetime import datetime, timedelta, timezone+from typing import Any, Callable++from sqlalchemy import func, select, text+from sqlalchemy.dialects.sqlite import insert+from sqlalchemy.engine import Connection++from storage.models import agent_events, agent_sessions, scopes, session_turns, skill_usage_daily, state_meta++EVENT_TYPES = ("skill.catalog_result", "skill.load_result")+# Literal allowlist matches the partial index; bound IN values do not let+# SQLite prove that a query is covered by this index.+SKILL_TRACE_FILTER = text("visibility = 'trace' and event_type in ('skill.catalog_result', 'skill.load_result')")+RAW_RETENTION_DAYS = 90+DAILY_RETENTION_DAYS = 365+CLEARED_THROUGH_KEY = "skill_observability.cleared_through"+FIRST_OBSERVED_KEY = "skill_observability.first_observed_at"+NAME_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z")+DIGEST_RE = re.compile(r"[0-9a-f]{64}\Z")+ID_RE = re.compile(r"[A-Za-z0-9_.:-]{1,200}\Z")+SOURCES = frozenset({"builtin", "project", "global", "unresolved"})+TRIGGERS = frozenset({"human", "task", "watch", "agent_run", "callback", "standalone", "unknown"})+COUNTERS = (+ "catalog_offer_count",+ "load_success_count",+ "load_failure_count",+ "load_duration_samples",+ "load_duration_ms_sum",+ "loaded_body_bytes_sum",+)+++class ObservationError(ValueError):+ """An invalid observation; exception text is a bounded reason code."""+++def utc_now() -> datetime:+ return datetime.now(timezone.utc)+++def timestamp(value: datetime) -> str:+ return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")+++def _string(value: Any, *, limit: int = 200, optional: bool = False) -> str | None:+ if value is None and optional:+ return None+ if not isinstance(value, str) or not value or len(value) > limit or any(ord(c) < 32 for c in value):+ raise ObservationError("invalid_string")+ return value+++def _identifier(value: Any, *, optional: bool = False) -> str | None:+ result = _string(value, optional=optional)+ if result is not None and not ID_RE.fullmatch(result):+ raise ObservationError("invalid_identifier")+ return result+++def _digest(value: Any, *, optional: bool = False) -> str | None:+ if value is None and optional:+ return None+ if not isinstance(value, str) or not DIGEST_RE.fullmatch(value):+ raise ObservationError("invalid_digest")+ return value+++def _integer(value: Any, *, maximum: int, optional: bool = False) -> int | None:+ if value is None and optional:+ return None+ if type(value) is not int or not 0 <= value <= maximum:+ raise ObservationError("invalid_integer")+ return value+++def _fields(value: Any, allowed: set[str], required: set[str] | None = None) -> dict:+ if not isinstance(value, dict) or set(value) - allowed or (required or allowed) - set(value):+ raise ObservationError("invalid_fields")+ return value+++def _skill_fields(value: dict, *, unresolved: bool = False) -> None:+ _digest(value["skill_key"], optional=unresolved)+ name = value["skill_name"]+ if name is not None or not unresolved:+ if not isinstance(name, str) or not 1 <= len(name) <= 64 or not NAME_RE.fullmatch(name):+ raise ObservationError("invalid_skill_name")+ if (value["skill_key"] is None) != (name is None):+ raise ObservationError("invalid_skill_identity")+ if value["source_kind"] not in SOURCES:+ raise ObservationError("invalid_skill_source")+ _digest(value["descriptor_sha256"], optional=unresolved)+++def validate(observation: Any, *, now: datetime) -> dict[str, Any]:+ envelope = _fields(observation, {"id", "session_id", "turn_id", "event_type", "content", "metadata"})+ _identifier(envelope["id"])+ _identifier(envelope["session_id"], optional=True)+ _identifier(envelope["turn_id"], optional=True)+ if envelope["event_type"] not in EVENT_TYPES:+ raise ObservationError("invalid_event_type")+ metadata = _fields(+ envelope["metadata"],+ {+ "schema_version",+ "observed_at",+ "observation_channel",+ "trigger_kind",+ "backend",+ "model",+ "avibe_version",+ },+ )+ if type(metadata["schema_version"]) is not int or metadata["schema_version"] != 1:+ raise ObservationError("unsupported_schema")+ value = _string(metadata["observed_at"], limit=27)+ try:+ observed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if timestamp(observed) != value:+ raise ValueError+ except (ValueError, TypeError):+ raise ObservationError("invalid_observed_at") from None+ if observed > now or observed < now - timedelta(hours=24):+ raise ObservationError("observation_expired_or_future")+ if metadata["observation_channel"] not in {"avibe_cli", "runtime_prompt"}:+ raise ObservationError("invalid_channel")+ if metadata["trigger_kind"] not in TRIGGERS:+ raise ObservationError("invalid_trigger")+ _string(metadata["model"], optional=True)+ _identifier(metadata["backend"], optional=True)+ _string(metadata["avibe_version"], limit=80)+ content = envelope["content"]+ if envelope["event_type"] == "skill.load_result":+ content = _fields(+ content,+ {+ "skill_key",+ "skill_name",+ "source_kind",+ "skill_revision",+ "descriptor_sha256",+ "outcome",+ "error_code",+ "duration_ms",+ "body_bytes",+ },+ )+ _skill_fields(content, unresolved=True)+ _digest(content["skill_revision"], optional=True)+ _integer(content["duration_ms"], maximum=86_400_000, optional=True)+ _integer(content["body_bytes"], maximum=32 * 1024 * 1024, optional=True)+ errors = {"invalid_name", "not_found", "unreadable_or_invalid", "output_interrupted", "internal_error"}+ if content["outcome"] == "success":+ if any(content[key] is None for key in ("skill_key", "skill_revision", "descriptor_sha256", "body_bytes")):+ raise ObservationError("incomplete_success")+ if content["source_kind"] == "unresolved" or content["error_code"] is not None:+ raise ObservationError("invalid_success")+ elif content["outcome"] != "failure" or content["error_code"] not in errors:+ raise ObservationError("invalid_load_outcome")+ if metadata["observation_channel"] != "avibe_cli":+ raise ObservationError("invalid_channel")+ else:+ content = _fields(+ content, {"entry_point", "outcome", "error_code", "page", "has_more", "catalog_digest", "entries"}+ )+ if content["entry_point"] not in {"cli_list", "runtime_prompt"}:+ raise ObservationError("invalid_entry_point")+ if (content["entry_point"] == "runtime_prompt") != (metadata["observation_channel"] == "runtime_prompt"):+ raise ObservationError("invalid_channel")+ _integer(content["page"], maximum=1_000_000)+ if (+ type(content["has_more"]) is not bool+ or not isinstance(content["entries"], list)+ or len(content["entries"]) > 25+ ):+ raise ObservationError("invalid_catalog")+ _digest(content["catalog_digest"], optional=content["outcome"] == "failure")+ if content["outcome"] == "failure":+ if content["entries"] or content["error_code"] not in {+ "invalid_page",+ "output_interrupted",+ "internal_error",+ }:+ raise ObservationError("invalid_catalog_failure")+ elif content["outcome"] != "success" or content["error_code"] is not None or content["page"] < 1:+ raise ObservationError("invalid_catalog_outcome")+ seen = set()+ for position, entry in enumerate(content["entries"], 1):+ entry = _fields(entry, {"skill_key", "skill_name", "source_kind", "descriptor_sha256", "position"})+ _skill_fields(entry)+ if (+ entry["source_kind"] == "unresolved"+ or type(entry["position"]) is not int+ or entry["position"] != position+ ):+ raise ObservationError("invalid_catalog_entry")+ if entry["skill_key"] in seen:+ raise ObservationError("duplicate_catalog_entry")+ seen.add(entry["skill_key"])+ return envelope+++def record(+ conn: Connection,+ observation: dict,+ *,+ enabled: Callable[[], bool],+ trusted_runtime: bool = False,+ now: datetime | None = None,+) -> str:+ """Caller owns the transaction. Accepted event and buckets commit together."""+ now = now or utc_now()+ event = validate(observation, now=now)+ # Acquire SQLite's writer reservation before reading clear/disable state.+ conn.execute(text("update state_meta set updated_at = updated_at where key = :key"), {"key": CLEARED_THROUGH_KEY})+ if not enabled():+ return "disabled"+ cleared = conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == CLEARED_THROUGH_KEY)+ ).scalar_one_or_none()+ if cleared is not None and event["metadata"]["observed_at"] <= json.loads(cleared):+ raise ObservationError("observation_cleared")+ if not trusted_runtime and event["metadata"]["observation_channel"] != "avibe_cli":+ raise ObservationError("runtime_observation_required")++ session = None+ platform = "unknown"+ if event["session_id"] is not None:+ session = (+ conn.execute(select(agent_sessions).where(agent_sessions.c.id == event["session_id"]))+ .mappings()+ .one_or_none()+ )+ if session is None:+ raise ObservationError("session_missing")+ platform = (+ conn.execute(select(scopes.c.platform).where(scopes.c.id == session["scope_id"])).scalar_one_or_none()+ or "unknown"+ )+ turn_id = None+ if trusted_runtime and event["turn_id"] and session:+ turn_id = conn.execute(+ select(session_turns.c.id).where(+ session_turns.c.id == event["turn_id"],+ session_turns.c.session_id == session["id"],+ )+ ).scalar_one_or_none()+ meta = dict(event["metadata"])+ backend = meta.pop("backend")+ meta["correlation_level"] = "exact_turn" if turn_id else ("session_only" if session else "unattributed")+ # A Session-stable shell may outlive its originating Turn and author.+ if not trusted_runtime:+ meta["model"] = None+ meta["trigger_kind"] = "standalone" if not session and meta["trigger_kind"] == "standalone" else "unknown"+ meta["context_ref"] = turn_id+ body = json.dumps(event["content"], ensure_ascii=False, sort_keys=True, separators=(",", ":"))+ meta_json = json.dumps(meta, ensure_ascii=False, sort_keys=True, separators=(",", ":"))+ payload = {+ "id": event["id"],+ "session_id": event["session_id"],+ "scope_id": session["scope_id"] if session else None,+ "turn_id": turn_id,+ "run_id": None,+ "platform": platform,+ "agent_name": session["agent_name"] if session else None,+ "backend": backend,+ "event_type": event["event_type"],+ "visibility": "trace",+ "content_text": None,+ "content_json": body,+ "metadata_json": meta_json,+ "source": "runtime",+ "created_at": timestamp(now),+ "updated_at": timestamp(now),+ }+ inserted = conn.execute(+ insert(agent_events).values(**payload).on_conflict_do_nothing(index_elements=["id"])+ ).rowcount+ if not inserted:+ previous = conn.execute(select(agent_events).where(agent_events.c.id == event["id"])).mappings().one()+ # Scope/agent labels may have changed since the first receipt. Compare+ # immutable submitted content and identity, not today's mutable joins.+ if any(+ previous[key] != payload[key]+ for key in (+ "session_id",+ "turn_id",+ "backend",+ "event_type",+ "content_json",+ "metadata_json",+ "source",+ "visibility",+ )+ ):+ raise ObservationError("observation_id_conflict")+ return "duplicate"++ entries = event["content"]["entries"] if event["event_type"] == "skill.catalog_result" else [event["content"]]+ for entry in entries:+ if entry["skill_key"] is None:+ continue+ counts = dict.fromkeys(COUNTERS, 0)+ maximum = 0+ revision = ""+ if event["event_type"] == "skill.catalog_result":+ counts["catalog_offer_count"] = 1+ else:+ success = entry["outcome"] == "success"+ counts["load_success_count" if success else "load_failure_count"] = 1+ duration = entry["duration_ms"]+ if duration is not None:+ counts["load_duration_samples"] = 1+ counts["load_duration_ms_sum"] = maximum = duration+ if success:+ counts["loaded_body_bytes_sum"] = entry["body_bytes"]+ revision = entry["skill_revision"] or ""+ observed = meta["observed_at"]+ values = {+ "day": observed[:10],+ "scope_id": payload["scope_id"],+ "session_id": payload["session_id"],+ "skill_key": entry["skill_key"],+ "skill_name": entry["skill_name"],+ "source_kind": entry["source_kind"],+ "skill_revision": revision,+ "backend": payload["backend"] or "",+ "model": meta["model"] or "",+ "trigger_kind": meta["trigger_kind"],+ "platform": platform,+ "avibe_version": meta["avibe_version"],+ **counts,+ "load_duration_ms_max": maximum,+ "first_observed_at": observed,+ "last_observed_at": observed,+ }+ stmt = insert(skill_usage_daily).values(**values)+ conn.execute(+ stmt.on_conflict_do_update(+ index_elements=[+ skill_usage_daily.c.day,+ text("coalesce(scope_id, '')"),+ text("coalesce(session_id, '')"),+ *[+ skill_usage_daily.c[key]+ for key in (+ "skill_key",+ "skill_revision",+ "backend",+ "model",+ "trigger_kind",+ "platform",+ "avibe_version",+ )+ ],+ ],+ set_={+ **{key: skill_usage_daily.c[key] + stmt.excluded[key] for key in COUNTERS},+ "load_duration_ms_max": func.max(+ skill_usage_daily.c.load_duration_ms_max, stmt.excluded.load_duration_ms_max+ ),+ "first_observed_at": func.min(+ skill_usage_daily.c.first_observed_at, stmt.excluded.first_observed_at+ ),+ "last_observed_at": func.max(skill_usage_daily.c.last_observed_at, stmt.excluded.last_observed_at),+ },+ )+ )+ conn.execute(+ insert(state_meta)+ .values(+ key=FIRST_OBSERVED_KEY,+ value_json=json.dumps(timestamp(now)),+ updated_at=timestamp(now),+ )+ .on_conflict_do_nothing(index_elements=["key"])+ )+ return "accepted"+++def clear(conn: Connection, *, now: datetime | None = None) -> dict[str, int]:+ instant = timestamp(now or utc_now())+ conn.execute(+ insert(state_meta)+ .values(+ key=CLEARED_THROUGH_KEY,+ value_json=json.dumps(instant),+ updated_at=instant,+ )+ .on_conflict_do_update(index_elements=["key"], set_={"value_json": json.dumps(instant), "updated_at": instant})+ )+ events = conn.execute(agent_events.delete().where(SKILL_TRACE_FILTER)).rowcount+ daily = conn.execute(skill_usage_daily.delete()).rowcount+ return {"events": events, "daily_rows": daily}+++def status(conn: Connection) -> dict:+ """Bounded local diagnostics, without copying transcript content."""+ markers = dict(+ conn.execute(+ select(state_meta.c.key, state_meta.c.value_json).where(+ state_meta.c.key.in_((FIRST_OBSERVED_KEY, CLEARED_THROUGH_KEY)),+ )+ ).all()+ )+ return {+ "raw_retention_days": RAW_RETENTION_DAYS,+ "daily_retention_days": DAILY_RETENTION_DAYS,+ "first_observed_at": json.loads(markers[FIRST_OBSERVED_KEY]) if FIRST_OBSERVED_KEY in markers else None,+ "cleared_through": json.loads(markers[CLEARED_THROUGH_KEY]) if CLEARED_THROUGH_KEY in markers else None,+ "events": conn.execute(+ select(func.count())+ .select_from(agent_events)+ .where(+ SKILL_TRACE_FILTER,+ )+ ).scalar_one(),+ "daily_rows": conn.execute(select(func.count()).select_from(skill_usage_daily)).scalar_one(),+ }diff --git a/tests/conftest.py b/tests/conftest.pyindex 153f01f9d..079ac0189 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -211,6 +211,16 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):"AVIBE_CALLER_WORKSPACE_ID","AVIBE_CALLER_REMOTE","AVIBE_CALLER_RESOURCE_CONTEXT",+ "VIBE_INTERNAL_DISPATCH_SOCKET",+ "AVIBE_SKILL_WORKING_DIR",+ "AVIBE_SKILL_PROJECT_BASE",+ "AVIBE_SKILL_HOME",+ "AVIBE_SKILL_CODEX_HOME",+ "AVIBE_SKILL_CLAUDE_HOME",+ "AVIBE_SKILL_CLAUDE_CLI_PATH",+ "AVIBE_SKILL_XDG_CONFIG_HOME",+ "AVIBE_BUILTIN_SKILLS_ROOT",+ "AVIBE_BUILTIN_SKILLS_SNAPSHOT_ID",):monkeypatch.delenv(name, raising=False)isolated_home = tmp_path / "home"diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex fc7329d6b..eb34fff4f 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -1220,6 +1220,24 @@ def test_save_config_preserves_ui_fields_on_unrelated_partial_save(monkeypatch,assert updated.ui.instance_name == "OwnerBox"[email protected]("enabled", [False, True])[email protected]("patch", [{"show_duration": False}, {"runtime": {"log_level": "DEBUG"}}])+def test_partial_save_preserves_skill_observability_policy(+ monkeypatch, tmp_path, sqlite_schema_db_factory, enabled, patch+):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ sqlite_schema_db_factory(tmp_path / "state" / "vibe.sqlite")+ full = _full_config_payload()+ full["runtime"]["skill_observability_enabled"] = enabled+ api.save_config(full)++ updated = api.save_config(patch)++ assert updated.runtime.skill_observability_enabled is enabled+ assert api.config_to_payload(updated)["runtime"]["skill_observability_enabled"] is enabled+ assert V2Config.load().runtime.skill_observability_enabled is enabled++def test_full_config_serializers_cover_every_config_field(monkeypatch, tmp_path, sqlite_schema_db_factory):"""Mechanism guard for the whole class: both full-config serializers(``V2Config.save`` on disk and ``config_to_payload``, the save merge base)diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex bc5fc3f33..0480fe630 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -24,6 +24,35 @@ from modules.agents.service import AgentServicefrom modules.claude_sdk_compat import TextBlock, UserMessage+async def test_skill_catalog_is_offered_once_per_accepted_claude_client(monkeypatch):+ controller = _StubController()+ client = SimpleNamespace(query=AsyncMock(), _vibe_pending_skill_catalog={"entries": []})+ controller.session_handler.get_or_create_claude_session = AsyncMock(return_value=client)+ agent = ClaudeAgent(controller)+ agent._prepare_message_with_files = lambda request: request.message+ agent._delete_ack = AsyncMock()+ agent._receive_messages = AsyncMock()+ accepted = Mock()+ monkeypatch.setattr("core.skill_observability.accept_catalog", accepted)+ context = SimpleNamespace(platform_specific={"agent_session_id": "ses"})+ request = SimpleNamespace(+ context=context, message="hello", working_path="/fixture", base_session_id="ses",+ composite_session_id="runtime", session_key="scope", subagent_name=None,+ subagent_model=None, subagent_reasoning_effort=None, ack_message_id=None,+ ack_reaction_message_id=None, ack_reaction_emoji=None, files=None,+ )+ await agent.handle_message(request)+ await asyncio.sleep(0)+ assert accepted.call_args.args[2] == {"entries": []}+ assert client._vibe_pending_skill_catalog is None+ await agent.handle_message(request)+ await asyncio.sleep(0)+ # The helper gets no candidate on reuse and therefore cannot enqueue an event.+ assert accepted.call_args.args[2] is None+ for task in controller.receiver_tasks.values():+ await task++class _StubSessions:@staticmethoddef list_agent_sessions(settings_key, agent_name):diff --git a/tests/test_controller_trace_retention.py b/tests/test_controller_trace_retention.pyindex fb7de87d2..90907a2c3 100644--- a/tests/test_controller_trace_retention.py+++ b/tests/test_controller_trace_retention.py@@ -207,6 +207,11 @@ def test_retention_pass_never_vacuums(monkeypatch) -> None:captured: dict = {}class _FakeRetention:+ @staticmethod+ def run_skill_retention(engine, **kwargs):+ captured["skill_retention"] = True+ return {"events": 0, "daily_rows": 0}+@staticmethoddef run_once(engine, *, retention_days, compact=True, **kwargs):captured["compact"] = compactdiff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 2b56b0d6e..b21e5c140 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -9275,6 +9275,7 @@ def test_boot_publishes_app_then_waits_for_controller_recovery(controller = SimpleNamespace(session_turns=manager,_delivery_recovery_complete=recovery_complete,+ skill_observability=SimpleNamespace(close=AsyncMock()),)class _Server:@@ -9314,6 +9315,7 @@ def test_boot_publishes_app_then_waits_for_controller_recovery(asyncio.run(_run())assert calls == ["app", "serve", "close"]+ controller.skill_observability.close.assert_awaited_once()def _seed_slack_dm_session(conn, tmp_path, *, dm_chat_id: str, user_id: str = "U_DM"):diff --git a/tests/test_skill_observability.py b/tests/test_skill_observability.pynew file mode 100644index 000000000..52af0f33e--- /dev/null+++ b/tests/test_skill_observability.py@@ -0,0 +1,608 @@+"""Skill statistics are optional, attributable facts, not inferred task success."""++from __future__ import annotations++import asyncio+from concurrent.futures import ThreadPoolExecutor+from copy import deepcopy+from dataclasses import replace+from datetime import datetime, timedelta, timezone+import json+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import httpx+import pytest+from sqlalchemy import func, select, text+from sqlalchemy.exc import IntegrityError++from core import skill_observability as runtime+from core.managed_skills import ManagedSkill+from storage import agent_events_retention, skill_observability as store+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_events, agent_sessions, scopes, skill_usage_daily+++NOW = datetime(2026, 9, 7, 12, tzinfo=timezone.utc)+++def engine():+ ensure_sqlite_state()+ result = create_sqlite_engine()+ yield result+ result.dispose()+++def skill(name="docs", *, body="Read the docs.\n", source=1):+ return ManagedSkill(name, "Project documentation", Path("/fixture/project/skills") / name, (source, 0), body)+++def load(*, instant=NOW, session_id=None, item=None, error=None):+ result = runtime.observation(+ "skill.load_result",+ runtime.load_result("docs", item or skill(), duration_ms=12, error_code=error),+ session_id=session_id,+ )+ result["metadata"]["observed_at"] = store.timestamp(instant)+ return result+++def write(engine, event, **kwargs):+ with engine.begin() as conn:+ return store.record(conn, event, enabled=lambda: True, now=NOW, **kwargs)+++def counts(engine):+ with engine.connect() as conn:+ return (+ conn.execute(select(func.count()).select_from(agent_events)).scalar_one(),+ conn.execute(select(func.sum(skill_usage_daily.c.load_success_count))).scalar_one(),+ )+++def seed_session(engine, session_id="ses-test"):+ instant = store.timestamp(NOW)+ with engine.begin() as conn:+ conn.execute(+ scopes.insert().values(+ id="scope-test",+ platform="web",+ scope_type="channel",+ native_id="native-scope",+ is_private=1,+ supports_threads=1,+ metadata_json="{}",+ first_seen_at=instant,+ last_seen_at=instant,+ updated_at=instant,+ )+ )+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id="scope-test",+ agent_name="codex",+ agent_backend="codex",+ agent_variant="default",+ session_anchor="anchor",+ native_session_id="native",+ status="active",+ metadata_json="{}",+ model="mutable-current-model",+ created_at=instant,+ updated_at=instant,+ )+ )+ return session_id+++def test_idempotence_and_real_repeats(engine):+ event = load()+ assert write(engine, event) == "accepted"+ assert write(engine, event) == "duplicate"+ assert write(engine, load()) == "accepted"+ assert counts(engine) == (2, 2)+ with engine.connect() as conn:+ row = conn.execute(select(skill_usage_daily)).mappings().one()+ assert row["session_id"] is None+ assert row["load_duration_samples"] == 2+ assert row["load_duration_ms_sum"] == 24+ assert row["load_duration_ms_max"] == 12+ assert row["loaded_body_bytes_sum"] == 2 * len(skill().body.encode())+ conflicting = deepcopy(event)+ conflicting["content"]["duration_ms"] = 99+ with pytest.raises(store.ObservationError, match="observation_id_conflict"):+ write(engine, conflicting)+ assert counts(engine) == (2, 2)+++def test_concurrent_duplicate_receipts_and_null_grain(engine):+ event = load()+ with ThreadPoolExecutor(max_workers=4) as executor:+ results = list(executor.map(lambda _: write(engine, event), range(12)))+ assert results.count("accepted") == 1+ assert results.count("duplicate") == 11+ with ThreadPoolExecutor(max_workers=4) as executor:+ list(executor.map(lambda _: write(engine, load()), range(12)))+ assert counts(engine) == (13, 13)+++def test_event_and_projection_rollback_together(engine):+ with engine.begin() as conn:+ conn.execute(+ text(+ "CREATE TRIGGER reject_skill_bucket BEFORE INSERT ON skill_usage_daily "+ "BEGIN SELECT RAISE(ABORT, 'projection rejected'); END"+ )+ )+ with pytest.raises(IntegrityError, match="projection rejected"):+ write(engine, load())+ assert counts(engine) == (0, None)+++def test_session_only_never_guesses_model_or_turn(engine):+ session_id = seed_session(engine)+ event = load(session_id=session_id)+ event["turn_id"] = "old-shell-turn"+ event["metadata"]["model"] = "old-shell-model"+ event["metadata"]["backend"] = "claude"+ event["metadata"]["trigger_kind"] = "task"+ write(engine, event)+ with engine.connect() as conn:+ row = conn.execute(select(agent_events)).mappings().one()+ meta = json.loads(row["metadata_json"])+ assert (row["scope_id"], row["backend"], row["platform"]) == ("scope-test", "claude", "web")+ assert row["turn_id"] is None and row["run_id"] is None+ assert meta["model"] is None and meta["trigger_kind"] == "unknown"+ assert meta["correlation_level"] == "session_only"+ with pytest.raises(store.ObservationError, match="session_missing"):+ write(engine, load(session_id="missing-session"))+++def test_clear_is_narrow_and_rejects_late_receipts(engine):+ event = load()+ write(engine, event)+ with engine.begin() as conn:+ row = dict(conn.execute(select(agent_events)).mappings().one())+ conn.execute(agent_events.insert().values(**{**row, "id": "keep-tool", "event_type": "tool_call"}))+ conn.execute(agent_events.insert().values(**{**row, "id": "keep-user", "visibility": "user"}))+ assert store.clear(conn, now=NOW) == {"events": 1, "daily_rows": 1}+ with pytest.raises(store.ObservationError, match="observation_cleared"):+ write(engine, event)+ with engine.begin() as conn:+ assert (+ store.record(+ conn, load(instant=NOW + timedelta(seconds=1)), enabled=lambda: True, now=NOW + timedelta(seconds=1)+ )+ == "accepted"+ )+ assert store.status(conn)["cleared_through"] == store.timestamp(NOW)+ assert counts(engine) == (3, 1)+++def test_disabled_writer_creates_nothing(engine):+ with engine.begin() as conn:+ assert store.record(conn, load(), enabled=lambda: False, now=NOW) == "disabled"+ assert counts(engine) == (0, None)+++def test_retention_boundaries_and_unrelated_rows(engine):+ ages = (366, 365, 364, 91, 90, 89, 0)+ for days in ages:+ instant = NOW - timedelta(days=days)+ with engine.begin() as conn:+ store.record(conn, load(instant=instant), enabled=lambda: True, now=instant)+ with engine.begin() as conn:+ row = dict(conn.execute(select(agent_events).limit(1)).mappings().one())+ conn.execute(agent_events.insert().values(**{**row, "id": "old-tool", "event_type": "tool_call"}))+ conn.execute(agent_events.insert().values(**{**row, "id": "old-visible", "visibility": "user"}))+ result = agent_events_retention.run_skill_retention(engine, now=NOW)+ assert result == {"events": 4, "daily_rows": 2}+ assert counts(engine) == (5, 5)+ with engine.connect() as conn:+ assert conn.execute(select(agent_events.c.id).where(agent_events.c.id == "old-tool")).scalar_one()+++def test_physical_session_purge_removes_both_surfaces(engine):+ from storage.sessions_service import _delete_agent_session_rows++ session_id = seed_session(engine)+ write(engine, load(session_id=session_id))+ with engine.begin() as conn:+ row = dict(conn.execute(select(agent_events)).mappings().one())+ conn.execute(agent_events.insert().values(**{**row, "id": "keep-tool", "event_type": "tool_call"}))+ assert (+ _delete_agent_session_rows(+ conn,+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id),+ reclaim_mode="pause",+ reclaim_reason=None,+ )+ == 1+ )+ assert conn.execute(select(agent_sessions.c.id)).first() is None+ assert conn.execute(select(skill_usage_daily.c.id)).first() is None+ assert conn.execute(select(agent_events.c.id, agent_events.c.session_id)).all() == [("keep-tool", None)]+ with pytest.raises(store.ObservationError, match="session_missing"):+ write(engine, load(session_id=session_id))+++def test_scope_delete_cascades_statistics(engine):+ session_id = seed_session(engine)+ write(engine, load(session_id=session_id))+ with engine.begin() as conn:+ conn.execute(scopes.delete().where(scopes.c.id == "scope-test"))+ assert counts(engine) == (0, None)+++def test_archiving_retained_session_keeps_statistics(engine):+ from storage import messages_service+ from storage.sessions_service import _delete_agent_session_rows++ session_id = seed_session(engine)+ write(engine, load(session_id=session_id))+ with engine.begin() as conn:+ messages_service.append(+ conn,+ session_id=session_id,+ scope_id="scope-test",+ platform="web",+ author="user",+ message_type="user",+ text="Keep this conversation",+ )+ _delete_agent_session_rows(conn, select(agent_sessions.c.id), reclaim_mode="pause", reclaim_reason=None)+ assert conn.execute(select(agent_sessions.c.status)).scalar_one() == "archived"+ assert counts(engine) == (1, 1)+++def test_schema_models_match_real_migration(engine, tmp_path):+ import re+ from sqlalchemy import inspect+ from storage.models import metadata++ declared = create_sqlite_engine(tmp_path / "declared.sqlite")+ try:+ metadata.create_all(declared)+ with engine.connect() as migrated, declared.connect() as model:++ def snapshot(conn):+ columns = conn.exec_driver_sql("PRAGMA table_info(skill_usage_daily)").all()+ # SQLite's INTEGER PRIMARY KEY is implicitly non-null either way.+ columns = [tuple(row) if row[1] != "id" else (*row[:3], 1, *row[4:]) for row in columns]+ checks = {+ item["name"]: re.sub(r"\s+", "", item["sqltext"]).lower()+ for item in inspect(conn).get_check_constraints("skill_usage_daily")+ }+ indexes = {+ row[1]: (row[2], row[4]) for row in conn.exec_driver_sql("PRAGMA index_list(skill_usage_daily)")+ }+ foreign_keys = sorted(+ tuple(row[2:]) for row in conn.exec_driver_sql("PRAGMA foreign_key_list(skill_usage_daily)")+ )+ return columns, checks, indexes, foreign_keys++ assert snapshot(migrated) == snapshot(model)+ finally:+ declared.dispose()+++def test_whole_window_unique_sessions_not_daily_sum(engine):+ session_id = seed_session(engine)+ write(engine, load(session_id=session_id))+ write(engine, load(session_id=session_id, instant=NOW - timedelta(days=1)))+ with engine.connect() as conn:+ assert conn.execute(select(func.count(func.distinct(skill_usage_daily.c.session_id)))).scalar_one() == 1+ assert conn.execute(select(func.count()).select_from(skill_usage_daily)).scalar_one() == 2+++def test_revision_identity_and_privacy():+ original = skill(body="Chinese: \u4e2d\u6587\n")+ body_changed = replace(original, body="Changed\n")+ description_changed = replace(original, description="Changed description")+ a = runtime.load_result("docs", original, duration_ms=0)+ b = runtime.load_result("docs", body_changed, duration_ms=0)+ c = runtime.load_result("docs", description_changed, duration_ms=0)+ assert a["skill_key"] == b["skill_key"] == c["skill_key"]+ assert a["descriptor_sha256"] == b["descriptor_sha256"] != c["descriptor_sha256"]+ assert len({a["skill_revision"], b["skill_revision"], c["skill_revision"]}) == 3+ assert a["body_bytes"] == len(original.body.encode("utf-8"))+ assert "/fixture" not in json.dumps(a) and "Chinese" not in json.dumps(a)+ builtin = replace(original, priority=(0,), directory=Path("/snapshot/a/docs"))+ moved = replace(builtin, directory=Path("/snapshot/b/docs"))+ assert runtime.skill_descriptor(builtin) == runtime.skill_descriptor(moved)+++def test_catalog_counts_actual_page_and_failures_only_load_attempts(engine):+ items = [skill(f"skill-{i}") for i in range(26)]+ content = runtime.catalog_result(items, page=2)+ assert len(content["entries"]) == 1+ assert content["entries"][0]["skill_name"] == "skill-9"+ event = runtime.observation("skill.catalog_result", content)+ event["metadata"]["observed_at"] = store.timestamp(NOW)+ write(engine, event)+ failure = load(error="output_interrupted")+ write(engine, failure)+ with engine.connect() as conn:+ totals = conn.execute(+ select(+ func.sum(skill_usage_daily.c.catalog_offer_count),+ func.sum(skill_usage_daily.c.load_success_count),+ func.sum(skill_usage_daily.c.load_failure_count),+ )+ ).one()+ assert totals == (1, 0, 1)+++ "mutate",+ [+ lambda e: e["content"].update(body="private prompt"),+ lambda e: e["content"].update(skill_name="../private/path"),+ lambda e: e["content"].update(duration_ms=True),+ lambda e: e["metadata"].update(schema_version=2),+ lambda e: e["metadata"].update(observed_at=store.timestamp(NOW + timedelta(seconds=1))),+ lambda e: e["metadata"].update(observed_at=store.timestamp(NOW - timedelta(days=2))),+ ],+)+def test_invalid_observations_do_not_write(engine, mutate):+ event = load()+ mutate(event)+ with pytest.raises(store.ObservationError):+ write(engine, event)+ assert counts(engine) == (0, None)+++def test_owner_only_sql_access_including_cte(engine):+ from storage.read_only_query import ReadOnlyQueryError, run_read_only_query+ from vibe.authorization import AuthorizationContext++ write(engine, load())+ remote = AuthorizationContext(is_remote=True, instance_role="editor")+ for table in ("skill_usage_daily", "agent_events"):+ with pytest.raises(ReadOnlyQueryError):+ run_read_only_query(+ f"WITH stats AS (SELECT * FROM {table}) SELECT count(*) FROM stats",+ page_request=None,+ user_context=remote,+ )+ assert run_read_only_query("SELECT count(*) AS n FROM skill_usage_daily", page_request=None).rows == [{"n": 1}]+++def test_cli_transport_failure_preserves_output_and_exit(monkeypatch, capsys):+ from vibe import cli+ from core import managed_skills++ monkeypatch.setattr(managed_skills, "resolve_skills", lambda: [skill()])+ monkeypatch.setattr(managed_skills, "load_skill", lambda *args, **kwargs: skill())+ monkeypatch.setattr("vibe.internal_client.record_skill_observation_sync", Mock(side_effect=TimeoutError))+ assert cli.cmd_skill(SimpleNamespace(skill_command="list", page=1)) == 0+ assert capsys.readouterr().out == "- docs: Project documentation\n"+ assert cli.cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0+ output = capsys.readouterr()+ assert "Read the docs." in output.out and output.err == ""+++def test_cli_observes_actual_loaded_snapshot(monkeypatch):+ from vibe import cli++ winner = replace(skill(), body=None)+ loaded = replace(skill(), body="New body\n")+ monkeypatch.setattr("core.managed_skills.resolve_skills", lambda: [winner])+ monkeypatch.setattr("core.managed_skills.load_skill", lambda *args, **kwargs: loaded)+ submitted = Mock(return_value={"status": "queued"})+ monkeypatch.setattr("vibe.internal_client.record_skill_observation_sync", submitted)+ assert cli.cmd_skill(SimpleNamespace(skill_command="load", name="docs")) == 0+ event = submitted.call_args.args[0]+ assert event["content"]["skill_revision"] == runtime.load_result("docs", loaded, duration_ms=0)["skill_revision"]+++def test_runtime_candidate_requires_acceptance(monkeypatch):+ from core.system_prompt_injection import build_system_prompt_injection++ sink = []+ recorder = Mock()+ controller = SimpleNamespace(skill_observability=recorder)+ context = SimpleNamespace(platform_specific={"agent_session_id": "ses-test", "turn_token": "turn-test"})+ monkeypatch.setattr("core.managed_skills.resolve_skills", lambda *args, **kwargs: [skill()])+ prompt = build_system_prompt_injection(skills_cwd="/fixture", skill_catalog_sink=sink)+ assert "docs" in prompt and len(sink) == 1+ recorder.enqueue.assert_not_called()+ runtime.accept_catalog(controller, context, sink[0])+ event = recorder.enqueue.call_args.args[0]+ assert event["session_id"] == "ses-test" and event["turn_id"] == "turn-test"+ assert event["metadata"]["observation_channel"] == "runtime_prompt"+ assert recorder.enqueue.call_args.kwargs == {"trusted_runtime": True}+++async def test_recorder_disabled_storage_failure_and_backpressure(engine, monkeypatch):+ recorder = runtime.SkillObservationRecorder(engine=engine, enabled=lambda: False)+ event = load(instant=store.utc_now())+ assert recorder.enqueue(event) == "queued"+ await recorder.queue.join()+ assert recorder.health()["disabled"] == 1+ recorder.enabled = lambda: True+ monkeypatch.setattr(recorder, "_write", Mock(side_effect=RuntimeError("db unavailable")))+ recorder.enqueue(event)+ await recorder.queue.join()+ assert recorder.health()["dropped"] == 1+ for _ in range(runtime.MAX_PENDING_OBSERVATIONS):+ assert recorder.enqueue(event) == "queued"+ assert recorder.enqueue(event) == "dropped"+ await recorder.close()+ assert recorder.health()["pending"] == 0+ assert recorder.enqueue(event) == "dropped"+ assert counts(engine) == (0, None)+++async def test_internal_observation_boundary(engine):+ from core.internal_server import create_app++ controller = SimpleNamespace()+ app = create_app(controller)+ recorder = controller.skill_observability+ recorder.engine = engine+ recorder.enabled = lambda: True+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://internal") as client:+ event = load(instant=store.utc_now())+ assert (await client.post("/internal/skill-observations", json=event)).json() == {"status": "queued"}+ await recorder.queue.join()+ assert counts(engine) == (1, 1)+ event["metadata"]["observation_channel"] = "runtime_prompt"+ assert (await client.post("/internal/skill-observations", json=event)).status_code == 400+ assert (await client.post("/internal/skill-observations", content=b"x" * 33000)).status_code == 413+ assert (await client.get("/internal/skill-observations/health")).json()["accepted"] == 1+ await recorder.close()++[email protected]("exit_mode", ["return", "error", "cancel", "recovery_cancel", "bind_error"])+async def test_internal_server_owns_recorder_cleanup(engine, monkeypatch, tmp_path, exit_mode):+ from core import internal_server++ controller = SimpleNamespace(_delivery_recovery_complete=asyncio.Event())+ started = asyncio.Event()+ listener = SimpleNamespace(close=Mock())++ async def serve(*, sockets):+ assert sockets == [listener]+ recorder = controller.skill_observability+ recorder.engine = engine+ recorder.enabled = lambda: True+ assert recorder.enqueue(load(instant=store.utc_now())) == "queued"+ await recorder.queue.join()+ started.set()+ if exit_mode == "error":+ raise RuntimeError("server failed")+ if exit_mode == "cancel":+ await asyncio.Event().wait()++ def bind_socket(_path):+ if exit_mode == "bind_error":+ raise OSError("socket unavailable")+ return listener, tmp_path / "dispatch.sock"++ monkeypatch.setattr(internal_server, "_create_controller_loop_server", lambda _config: SimpleNamespace(serve=serve))+ monkeypatch.setattr(internal_server, "_bind_socket", bind_socket)+ monkeypatch.setattr(internal_server, "_write_internal_server_status", Mock())+ monkeypatch.setattr(internal_server, "_remove_owned_socket", Mock())+ if exit_mode != "recovery_cancel":+ controller._delivery_recovery_complete.set()+ task = asyncio.create_task(internal_server.serve(controller))+ if exit_mode == "cancel":+ await asyncio.wait_for(started.wait(), timeout=5)+ task.cancel()+ elif exit_mode == "recovery_cancel":+ await asyncio.sleep(0)+ task.cancel()+ if exit_mode in {"cancel", "recovery_cancel"}:+ with pytest.raises(asyncio.CancelledError):+ await task+ elif exit_mode in {"error", "bind_error"}:+ with pytest.raises((RuntimeError, OSError)):+ await task+ else:+ await task++ recorder = controller.skill_observability+ assert recorder.closed+ assert recorder.worker is None or recorder.worker.done()+ assert recorder.enqueue(load()) == "dropped"+ if exit_mode not in {"recovery_cancel", "bind_error"}:+ assert counts(engine) == (1, 1)+ listener.close.assert_called_once()+++def test_config_flag_is_strict_and_serialized():+ from config.v2_config import RuntimeConfig, V2Config++ assert RuntimeConfig(default_cwd=".").skill_observability_enabled is True+ assert RuntimeConfig(default_cwd=".", skill_observability_enabled=False).skill_observability_enabled is False+ for value in ("false", 0, 1, None):+ with pytest.raises(ValueError, match="skill_observability_enabled"):+ RuntimeConfig(default_cwd=".", skill_observability_enabled=value)+ config = V2Config.default()+ config.runtime.skill_observability_enabled = False+ config.save()+ assert V2Config.load().runtime.skill_observability_enabled is False+++def test_collection_recovery_fails_closed(monkeypatch):+ config = SimpleNamespace(+ runtime=SimpleNamespace(skill_observability_enabled=True),+ load_warnings=["Config JSON could not be parsed; using recovery defaults"],+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", lambda: config)+ assert runtime.collection_enabled() is False+ config.load_warnings = ["Recovered invalid config section 'runtime.skill_observability_enabled'"]+ assert runtime.collection_enabled() is False+ config.load_warnings = []+ assert runtime.collection_enabled() is True+++def test_retention_uses_skill_partial_index(engine):+ with engine.connect() as conn:+ plan = conn.execute(+ text(+ "EXPLAIN QUERY PLAN SELECT id FROM agent_events WHERE "+ + str(store.SKILL_TRACE_FILTER)+ + " AND datetime(created_at) IS NOT NULL AND created_at < :cutoff LIMIT 1000"+ ),+ {"cutoff": store.timestamp(NOW)},+ ).all()+ assert "ix_agent_events_skill_created_id" in str(plan)+++def test_clear_command_requires_explicit_confirmation(engine, capsys):+ from vibe.cli import cmd_data_skill_usage++ write(engine, load())+ assert cmd_data_skill_usage(SimpleNamespace(clear=True, yes=False)) == 1+ assert counts(engine) == (1, 1)+ assert cmd_data_skill_usage(SimpleNamespace(clear=True, yes=True)) == 0+ assert counts(engine) == (0, None)++[email protected]("language", ["en", "zh"])+ "owner,clear,yes,code,key",+ [+ (False, False, False, "forbidden", "ownerRequired"),+ (True, True, False, "confirmation_required", "confirmationRequired"),+ (True, False, True, "invalid_arguments", "clearRequired"),+ ],+)+def test_skill_usage_errors_follow_cli_language(monkeypatch, capsys, language, owner, clear, yes, code, key):+ from vibe import cli+ from vibe.i18n import t++ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ monkeypatch.setattr(+ "storage.resource_access_service.resolve_resource_access_context",+ lambda _caller: SimpleNamespace(is_instance_owner=owner),+ )+ assert cli.cmd_data_skill_usage(SimpleNamespace(clear=clear, yes=yes)) == 1+ captured = capsys.readouterr()+ assert captured.out == ""+ payload = json.loads(captured.err)+ assert payload["code"] == code+ assert payload["error"] == t(f"data.skillUsage.{key}", language)++[email protected]("language", ["en", "zh"])+def test_skill_usage_help_follows_cli_language(monkeypatch, capsys, language):+ from vibe import cli+ from vibe.i18n import t++ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ with pytest.raises(SystemExit) as exit_info:+ cli.build_parser().parse_args(["data", "skill-usage", "--help"])+ assert exit_info.value.code == 0+ output = capsys.readouterr().out+ for key in ("helpCommand", "helpClear", "helpYes"):+ assert t(f"data.skillUsage.{key}", language) in outputdiff --git a/tests/test_skill_observability_backends.py b/tests/test_skill_observability_backends.pynew file mode 100644index 000000000..5f33f4227--- /dev/null+++ b/tests/test_skill_observability_backends.py@@ -0,0 +1,69 @@+"""Observe positively accepted prompt writes, not attempted or cached prompts."""++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from modules.agents.codex.agent import CodexAgent+from modules.agents.opencode.agent import _OpenCodeSteerState, _SteeringAwareOpenCodeServer+++async def test_codex_counts_only_positive_injection_acknowledgements(monkeypatch):+ agent = object.__new__(CodexAgent)+ agent.controller = SimpleNamespace()+ agent._read_persisted_prompt_strategy_marker = Mock(return_value=None)+ agent._persist_prompt_strategy = Mock(return_value=True)+ agent._thread_prompt_strategies = {}+ request = SimpleNamespace(+ base_session_id="ses", context=SimpleNamespace(), skill_catalog_observation={"entries": []}+ )+ transport = SimpleNamespace(send_request=AsyncMock(side_effect=TimeoutError))+ accepted = Mock()+ monkeypatch.setattr("core.skill_observability.accept_catalog", accepted)+ with pytest.raises(TimeoutError):+ await agent._inject_thread_developer_instructions(transport, request, "thread", "instructions")+ accepted.assert_not_called()+ transport.send_request.side_effect = None+ await agent._inject_thread_developer_instructions(transport, request, "thread", "instructions")+ accepted.assert_called_once_with(+ agent.controller, request.context, request.skill_catalog_observation, backend="codex"+ )+ # A fresh native thread is another actual exposure even on one retried request.+ await agent._inject_thread_developer_instructions(transport, request, "new-thread", "instructions")+ assert accepted.call_count == 2+++async def test_opencode_retry_counts_only_matching_accepted_catalog():+ accepted = Mock()+ state = _OpenCodeSteerState(+ task=asyncio.current_task(),+ base_session_id="base",+ target_session_id="target",+ logical_turn_id="turn",+ native_session_id="native",+ directory="/fixture",+ agent=None,+ model=None,+ reasoning_effort=None,+ system="catalog prompt",+ baseline_message_ids=set(),+ catalog_accepted=accepted,+ )+ native = SimpleNamespace(prompt_async=AsyncMock(side_effect=TimeoutError))+ wrapped = _SteeringAwareOpenCodeServer(native, state)+ kwargs = {"system": state.system, "awaiting_after_ids": set(), "text": "continue"}+ with pytest.raises(TimeoutError):+ await wrapped.prompt_async(**kwargs)+ accepted.assert_not_called()+ native.prompt_async.side_effect = None+ await wrapped.prompt_async(**kwargs)+ accepted.assert_called_once()+ await wrapped.prompt_async(**{**kwargs, "system": None})+ accepted.assert_called_once()+ state.terminal_status_failure_messages = [{"info": {"id": "terminal"}}]+ await wrapped.prompt_async(**kwargs)+ accepted.assert_called_once()diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.pynew file mode 100644index 000000000..3634170f3--- /dev/null+++ b/tests/test_skill_observability_migration.py@@ -0,0 +1,59 @@+"""Exercise the real migration chain, never a models-only substitute."""++import sqlite3++from alembic import command++from storage import migrations++import pytest+++pytestmark = pytest.mark.no_sqlite_template+++def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):+ path = tmp_path / "state.sqlite"+ migrations.run_migrations(path, revision="20260821_0060")+ with sqlite3.connect(path) as conn:+ conn.executemany(+ "INSERT INTO agent_events (id, platform, event_type, visibility, content_json, "+ "metadata_json, created_at, updated_at) VALUES (?, 'web', ?, ?, '{}', '{}', ?, ?)",+ [+ (key, kind, visibility, stamp, stamp)+ for key, kind, visibility, stamp in (+ ("tool", "tool_call", "trace", "2026-08-01T00:00:00.000000Z"),+ ("message", "result", "user", "2026-08-02T00:00:00Z"),+ ("unknown", "future.event", "trace", "unparseable"),+ )+ ],+ )+ original = conn.execute("SELECT * FROM agent_events ORDER BY id").fetchall()+ migrations.run_migrations(path)+ with sqlite3.connect(path) as conn:+ assert conn.execute("SELECT * FROM agent_events ORDER BY id").fetchall() == original+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20260907_0061",)+ assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)+ assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {+ "scopes",+ "agent_sessions",+ }+ index_sql = conn.execute("SELECT sql FROM sqlite_master WHERE name='uq_skill_usage_daily_grain'").fetchone()[0]+ assert "coalesce(scope_id, '')" in index_sql and "coalesce(session_id, '')" in index_sql+ assert conn.execute("PRAGMA foreign_key_check").fetchall() == []+ conn.execute(+ "INSERT INTO agent_events (id, platform, event_type, visibility, content_json, metadata_json, "+ "created_at, updated_at) VALUES ('skill', 'web', 'skill.load_result', 'trace', '{}', '{}', 'now', 'now')"+ )+ command.downgrade(migrations.alembic_config(path), "20260821_0060")+ with sqlite3.connect(path) as conn:+ assert conn.execute("SELECT * FROM agent_events ORDER BY id").fetchall() == original+ assert conn.execute("SELECT name FROM sqlite_master WHERE name='skill_usage_daily'").fetchone() is None+ assert (+ conn.execute("SELECT name FROM sqlite_master WHERE name='ix_agent_events_skill_created_id'").fetchone()+ is None+ )+ migrations.run_migrations(path)+ with sqlite3.connect(path) as conn:+ assert conn.execute("SELECT * FROM agent_events ORDER BY id").fetchall() == original+ assert conn.execute("PRAGMA integrity_check").fetchone() == ("ok",)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex f2934d992..1eec89471 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -37,7 +37,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260821_0060"+HEAD_REVISION = "20260907_0061"# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to passdiff --git a/vibe/api.py b/vibe/api.pyindex 90629aae2..b86b98659 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1471,6 +1471,7 @@ def config_to_payload(# here would revert a user's retention opt-out on unrelated saves."agent_events_trace_retention_enabled": config.runtime.agent_events_trace_retention_enabled,"agent_events_trace_retention_days": config.runtime.agent_events_trace_retention_days,+ "skill_observability_enabled": config.runtime.skill_observability_enabled,},"agents": {"opencode": config.agents.opencode.__dict__,diff --git a/vibe/cli.py b/vibe/cli.pyindex 5d1eca131..479f49358 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -849,13 +849,17 @@ def cmd_skill(args) -> int:render_skill_list,resolve_skills,)+ from core.skill_observability import finish_cli_catalog, finish_cli_loadlanguage = _configured_cli_language()if args.skill_command == "list":+ resolved = []+ observation_error = "internal_error"try:+ resolved = resolve_skills()output = render_skill_list(- resolve_skills(),+ resolved,page=args.page,more_notice=i18n_t("skill.cli.more",@@ -863,24 +867,45 @@ def cmd_skill(args) -> int:page=args.page + 1,),)+ if output:+ print(output, flush=True)+ observation_error = None+ return 0except ValueError:+ observation_error = "invalid_page"print(i18n_t("skill.cli.error.invalidPage", language), file=sys.stderr)return 1- if output:- print(output)- return 0+ except BrokenPipeError:+ observation_error = "output_interrupted"+ raise+ finally:+ finish_cli_catalog(resolved, args.page, observation_error)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+ started_at = time.monotonic()+ skill = None+ observation_error = "internal_error"+ try:+ allowed = resolve_skills()+ skill = next((entry for entry in allowed if entry.name == args.name), None)+ if skill is None:+ observation_error = "not_found"+ print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)+ return 1+ loaded = load_skill(args.name, resolved_skills=allowed)+ if loaded is None:+ observation_error = "unreadable_or_invalid"+ print(i18n_t("skill.cli.error.notFound", language, name=args.name), file=sys.stderr)+ return 1+ skill = loaded+ print(render_skill_content(skill), flush=True)+ observation_error = None+ return 0+ except BrokenPipeError:+ observation_error = "output_interrupted"+ raise+ finally:+ finish_cli_load(args.name, skill, started_at, observation_error)return 1@@ -7268,6 +7293,35 @@ def _print_data_retention_human(payload: dict, language: str) -> None:print(f"retention status: {status}")+def cmd_data_skill_usage(args):+ """Instance-owner maintenance; statistics remain off the user-facing UI."""+ try:+ from storage.resource_access_service import resolve_resource_access_context+ from storage import skill_observability+ from core.skill_observability import collection_enabled+ from storage.db import get_cached_sqlite_engine++ language = _configured_cli_language()+ caller = caller_resource_user_context(caller_context_from_env())+ if not resolve_resource_access_context(caller).is_instance_owner:+ raise TaskCliError(i18n_t("data.skillUsage.ownerRequired", language), code="forbidden")+ if args.clear and not args.yes:+ raise TaskCliError(i18n_t("data.skillUsage.confirmationRequired", language), code="confirmation_required")+ if args.yes and not args.clear:+ raise TaskCliError(i18n_t("data.skillUsage.clearRequired", language), code="invalid_arguments")+ enabled = collection_enabled()+ from storage.importer import ensure_sqlite_state++ ensure_sqlite_state()+ with get_cached_sqlite_engine().begin() as conn:+ result = skill_observability.clear(conn) if args.clear else skill_observability.status(conn)+ _print_cli_payload("skill_usage", enabled=enabled, **result)+ return 0+ except Exception as exc:+ _print_task_error(exc, help_command="vibe data skill-usage --help")+ return 1++def cmd_data_query(args):try:sql = getattr(args, "sql", None)@@ -7275,7 +7329,10 @@ def cmd_data_query(args):if sql_file:sql = sys.stdin.read() if sql_file == "-" else Path(sql_file).read_text(encoding="utf-8")page_request = _page_request_from_args(args, help_command="vibe data query --help")- result = run_read_only_query(sql or "", page_request=page_request)+ result = run_read_only_query(+ sql or "", page_request=page_request,+ user_context=caller_resource_user_context(caller_context_from_env()),+ )command = ["vibe", "data", "query"]if getattr(args, "sql", None):_add_optional_arg(command, "--sql", getattr(args, "sql", None))@@ -16925,8 +16982,16 @@ def build_parser():formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe data --help",)- data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query,retention}")+ data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query,retention,skill-usage}")data_subparsers.required = True+ skill_usage_parser = data_subparsers.add_parser(+ "skill-usage", help=i18n_t("data.skillUsage.helpCommand", _data_help_lang),+ description=i18n_t("data.skillUsage.helpCommand", _data_help_lang),+ error_help_command="vibe data skill-usage --help",+ )+ skill_usage_parser.add_argument("--clear", action="store_true", help=i18n_t("data.skillUsage.helpClear", _data_help_lang))+ skill_usage_parser.add_argument("--yes", action="store_true", help=i18n_t("data.skillUsage.helpYes", _data_help_lang))+ _add_json_noop(skill_usage_parser)data_query_parser = data_subparsers.add_parser("query",help="Run one read-only SQL query",@@ -17935,6 +18000,8 @@ def main():if args.command == "data":if args.data_command == "query":sys.exit(cmd_data_query(args))+ if args.data_command == "skill-usage":+ sys.exit(cmd_data_skill_usage(args))if args.data_command == "retention":sys.exit(cmd_data_retention(args))parser.error("data command is required")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 331418bf8..2954f4fb3 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1470,6 +1470,14 @@"data": {"helpCommand": "Inspect Avibe data, and run explicit trace-retention maintenance","helpDescription": "Inspect local Avibe SQLite state with guarded read-only SQL, or run explicit maintenance: `query` is read-only, while `retention --run` deletes old internal trace events and may compact the database.",+ "skillUsage": {+ "ownerRequired": "Instance Owner access is required.",+ "confirmationRequired": "Clearing Skill statistics requires --yes.",+ "clearRequired": "--yes requires --clear.",+ "helpCommand": "Inspect or clear local Skill statistics (Instance Owner only)",+ "helpClear": "Clear Skill events and daily statistics.",+ "helpYes": "Confirm clearing Skill statistics."+ },"retention": {"invalidDays": "--days must be between {minimum} and {maximum}; refusing to run instead of silently clamping the window.","helpCommand": "Show or run bounded retention for internal agent trace events",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex d3cf072b0..561aa0d3b 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1470,6 +1470,14 @@"data": {"helpCommand": "\u67e5\u770b Avibe \u6570\u636e,\u6216\u6267\u884c\u663e\u5f0f\u7684 trace \u4fdd\u7559\u7ef4\u62a4","helpDescription": "\u901a\u8fc7\u53d7\u4fdd\u62a4\u7684\u53ea\u8bfb SQL \u67e5\u770b\u672c\u5730 Avibe SQLite \u72b6\u6001,\u6216\u6267\u884c\u663e\u5f0f\u7ef4\u62a4:`query` \u4e3a\u53ea\u8bfb;`retention --run` \u4f1a\u5220\u9664\u65e7\u7684\u5185\u90e8 trace \u4e8b\u4ef6\u5e76\u53ef\u80fd\u538b\u5b9e\u6570\u636e\u5e93\u3002",+ "skillUsage": {+ "ownerRequired": "需要实例所有者权限。",+ "confirmationRequired": "清除 Skill 统计需要使用 --yes 确认。",+ "clearRequired": "--yes 必须与 --clear 一起使用。",+ "helpCommand": "查看或清除本地 Skill 统计(仅限实例所有者)",+ "helpClear": "清除 Skill 事件及每日统计。",+ "helpYes": "确认清除 Skill 统计。"+ },"retention": {"invalidDays": "--days \u5fc5\u987b\u5728 {minimum} \u5230 {maximum} \u4e4b\u95f4;\u62d2\u7edd\u8fd0\u884c\u800c\u4e0d\u662f\u9759\u9ed8\u6536\u7a84\u7a97\u53e3\u3002","helpCommand": "\u67e5\u770b\u6216\u6267\u884c\u5185\u90e8 agent trace \u4e8b\u4ef6\u7684\u6709\u754c\u4fdd\u7559",diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex e14218f7a..b14423203 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -298,6 +298,26 @@ def publish_event_sync(raise InternalServerUnavailable(str(exc)) from exc+def record_skill_observation_sync(+ observation: dict[str, Any], *, socket_path: Optional[Path] = None,+ timeout: float = 0.25,+) -> dict[str, Any]:+ """Best-effort queue submission; the response is not a durable receipt."""+ target = _verified_socket_path(socket_path)+ try:+ with httpx.Client(+ transport=httpx.HTTPTransport(uds=str(target)),+ base_url="http://localhost",+ timeout=httpx.Timeout(timeout),+ ) as client:+ response = client.post("/internal/skill-observations", json=observation)+ if response.status_code != 202:+ raise InternalServerUnavailable("Skill observation rejected")+ return response.json()+ except _SOCKET_ERRORS as exc:+ raise InternalServerUnavailable("Skill observation transport unavailable") from exc++async def dispatch_async(payload: dict[str, Any],*,