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(vibey): record cache metrics and lifetime cost estimates (#3122)
Call Whiteceb23f328502
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex 723c51b02..e097cfc83 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -85,6 +85,7 @@ from core.agent_core.ai.provider import (ThinkingDelta,)from core.agent_core.cancel import CancelToken+from core.agent_core.harness.cache_metrics import CacheTrackerfrom core.agent_core.harness.context import (CLEAR_SOFT_RATIO,DEFAULT_MAX_OUTPUT_TOKENS,@@ -336,6 +337,7 @@ class _Attempt:error: Optional[ProviderError] = Nonecommitted: bool = Falseaudited: bool = False+ cache: Optional[dict[str, Any]] = None@dataclass(frozen=True)@@ -432,6 +434,11 @@ class Agent:# The C-9 cache clock deliberately keys the served provider/model boundary;# canonical rows also retain Source identity, but it is not a separate clock.self._last_model_at: dict[tuple[str, str], float] = {}+ self.cache_causes: tuple[Mapping[str, Any], ...] = ()+ self.prompt_pending = False+ self.prompt_notice = False+ self._cache_tracker = CacheTracker()+ self._cache_fork = Falseself._seq = 0@property@@ -750,7 +757,7 @@ class Agent:await self._save_state()# The attempt this response answered: the ledger's latest conversation attempt (the C-9 anchor).attempt = next((item for item in reversed(self._attempts) if item.purpose == "conversation"), None)- facts = {"request": request_facts(attempt.request)} if self.context is not None and attempt else {}+ facts = {"request": request_facts(attempt.request), "cache": attempt.cache} if self.context is not None and attempt else {}row = await self._scope.call(lambda: self.store.append_response(self.session_id,@@ -785,6 +792,11 @@ class Agent:selected = await self._scope.call(self.models.resolve)self._check_model_route(selected)self._rows = list(await self._scope.call(lambda: self.store.load(self.session_id)))+ if self.context is not None:+ attempts = await self._scope.call(lambda: self.store.load_cache_attempts(self.session_id))+ self._cache_tracker = CacheTracker()+ self._cache_tracker.restore(self._rows, attempts)+ self._cache_fork = bool(self._rows) and not any(row.session_id == self.session_id for row in self._rows)projection = project(self._rows)self._ctx.state = deepcopy(dict(projection.state))self._committed_state_json = state_representation(self._ctx.state)@@ -1045,6 +1057,13 @@ class Agent:yield retry_error, toolsreturnself._scope.check()+ cache = None+ if self.context is not None:+ cache = await self._scope.call(lambda: asyncio.to_thread(+ self._cache_tracker.begin, request, self._rows, now=self.context.clock(),+ causes=self.cache_causes, fork=self._cache_fork,+ ))+ cache.update(prompt_pending=self.prompt_pending, prompt_notice=self.prompt_notice)stream = self.models.provider_for(request.endpoint.protocol).stream(request, self._ctx.cancel)streamed = Falseterminal = None@@ -1069,12 +1088,16 @@ class Agent:served = terminal.message if isinstance(terminal, Done) else terminal.partialupstream = served.origin if served is not None else endpoint_origin(request.endpoint)self._last_model_at[_cache_of(upstream)] = self.context.clock()+ self._cache_tracker.finish(cache, served, rows=self._rows)+ if served is not None and served.usage is not None:+ self.cache_causes, self._cache_fork = (), Falseself._attempts.append(_Attempt(purpose,request,terminal.message if isinstance(terminal, Done) else terminal.partial,None if isinstance(terminal, Done) else terminal,+ cache=cache,))relieve = (@@ -1179,23 +1202,26 @@ class Agent:raiseasync def _settle_attempts(self, first: int, *, error: Optional[BaseException] = None) -> None:- """Every conversation attempt since ``first`` that reported usage and did not become a response row:- exactly one non-context ``ModelAttempt`` audit row, in every mode, with or without ``ContextConfig``.+ """Every uncommitted conversation attempt since ``first`` with usage or optional cache facts:+ exactly one non-context ``ModelAttempt`` audit row. Missing usage is unknown, never zero.- It is the one place that usage is kept. ``error`` is why the model call ended, for an attempt that+ It is the one place that uncommitted usage is kept. ``error`` is why the model call ended, for an attempt thatcarries no provider error of its own (a response refused at admission, a failed commit)."""for attempt in self._attempts[first:]:message = attempt.messageif attempt.purpose != "conversation" or attempt.committed or attempt.audited:continue- if message is None or message.usage is None:+ usage = message.usage if message is not None else None+ if usage is None and attempt.cache is None:continueattempt.audited = Truecause = attempt.errorpayload: dict[str, Any] = {"version": 1,- "usage": usage_to_dict(message.usage),+ **({"usage": usage_to_dict(usage)} if usage is not None else {}),+ **({"cache": attempt.cache, "cache_state": list(self._cache_tracker.latest.values())}+ if attempt.cache is not None else {}),"error": f"{cause.kind}: {cause.message}" if cause is not None else str(error) if error else None,}await self._audit("attempt", payload)@@ -2570,6 +2596,13 @@ class Agent:usage = self._turn_usage(start)if usage is not None:record["usage"] = usage_to_dict(usage)+ cache_attempts = [+ {"cache": item.cache, **({"usage": usage_to_dict(item.message.usage)} if item.message and item.message.usage else {})}+ for item in self._attempts[start:] if item.cache is not None+ ]+ if cache_attempts:+ record["cache_attempts"] = cache_attempts+ record["cache_state"] = list(self._cache_tracker.latest.values())return {**record, **finished}async def _side_tool(diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex e20c76d43..c7f22a8de 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -1340,12 +1340,18 @@ def _anthropic_usage(value: Any, *, current: Any = None) -> Any:return currentif current is None:current = _usage()+ from core.agent_core.ai.cache_usage import write_ttls++ total = _anthropic_cache_write_tokens(value, current.cache_write_tokens)return _usage(_pick(value, "input_tokens", current.input_tokens),_pick(value, "output_tokens", current.output_tokens),_pick(value, "cache_read_input_tokens", current.cache_read_tokens),- _anthropic_cache_write_tokens(value, current.cache_write_tokens),+ total,_pick_nested(value, "output_tokens_details", "thinking_tokens", current.reasoning_tokens),+ write_ttls(value.get("cache_creation"),+ {"ephemeral_5m_input_tokens": "5m", "ephemeral_1h_input_tokens": "1h"}, total,+ current=current.cache_writes_by_ttl),)@@ -1367,7 +1373,10 @@ def _anthropic_cache_write_tokens(value: Mapping[str, Any], fallback: int = 0) -return fallback-def _usage(input_tokens: int = 0, output_tokens: int = 0, cache_read: int = 0, cache_write: int = 0, reasoning: int | None = None) -> Any:+def _usage(+ input_tokens: int = 0, output_tokens: int = 0, cache_read: int = 0, cache_write: int = 0,+ reasoning: int | None = None, writes_by_ttl: Mapping[str, int] | None = None,+) -> Any:from core.agent_core.messages import Usagereturn Usage(@@ -1376,6 +1385,7 @@ def _usage(input_tokens: int = 0, output_tokens: int = 0, cache_read: int = 0, ccache_read_tokens=cache_read,cache_write_tokens=cache_write,reasoning_tokens=reasoning,+ cache_writes_by_ttl=writes_by_ttl,)diff --git a/core/agent_core/ai/cache_usage.py b/core/agent_core/ai/cache_usage.pynew file mode 100644index 000000000..4f257cae0--- /dev/null+++ b/core/agent_core/ai/cache_usage.py@@ -0,0 +1,23 @@+"""Cache-write decompositions shared by the wire adapters, independent of Model Hub."""++from typing import Any, Mapping+++def write_ttls(+ value: Any, fields: Mapping[str, str], total: int | None, *, current: Mapping[str, int] | None = None,+) -> dict[str, int] | None:+ """Merge reported counters; a missing breakdown stays unknown, not inferred from requested TTL.++ Contradictory counters cannot be priced honestly. Keep the aggregate and drop+ the decomposition rather than changing billed totals or double counting it.+ """+ result = dict(current) if current is not None else None+ if isinstance(value, Mapping):+ for field, ttl in fields.items():+ if field in value and value[field] is not None:+ if type(value[field]) is not int or value[field] < 0:+ return None+ if result is None:+ result = {}+ result[ttl] = value[field]+ return result if result is None or total is None or sum(result.values()) <= total else Nonediff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.pyindex 7273e22b6..6c0c7a388 100644--- a/core/agent_core/ai/openai_responses.py+++ b/core/agent_core/ai/openai_responses.py@@ -1675,6 +1675,7 @@ def _responses_usage(value: Any) -> Any:if not isinstance(value, Mapping):return Nonefrom core.agent_core.messages import Usage+ from core.agent_core.ai.cache_usage import write_ttlsinput_details = value.get("input_tokens_details")output_details = value.get("output_tokens_details")@@ -1683,16 +1684,21 @@ def _responses_usage(value: Any) -> Any:if isinstance(input_details, Mapping)else 0)- cache_write_tokens = (- _nonnegative(input_details.get("cache_write_tokens"))- if isinstance(input_details, Mapping)- else 0- )+ write_details = input_details.get("cache_write_tokens_details") if isinstance(input_details, Mapping) else None+ aggregate_write = input_details.get("cache_write_tokens") if isinstance(input_details, Mapping) else None+ aggregate_reported = type(aggregate_write) is int and aggregate_write >= 0+ cache_write_tokens = _nonnegative(aggregate_write)+ # TTL detail is optional telemetry: it must not invent a canonical aggregate.return Usage(input_tokens=max(0, _nonnegative(value.get("input_tokens")) - cache_read_tokens - cache_write_tokens),output_tokens=_nonnegative(value.get("output_tokens")),cache_read_tokens=cache_read_tokens,cache_write_tokens=cache_write_tokens,+ cache_writes_by_ttl=write_ttls(+ write_details, {"ttl_30m_tokens": "30m", "ttl_12h_tokens": "12h"},+ cache_write_tokens if aggregate_reported else None,+ ),+ cache_write_total_reported=aggregate_reported,reasoning_tokens=_nonnegative(output_details.get("reasoning_tokens")) if isinstance(output_details, Mapping) and "reasoning_tokens" in output_details else None,)diff --git a/core/agent_core/harness/cache_metrics.py b/core/agent_core/harness/cache_metrics.pynew file mode 100644index 000000000..de4ef0b1c--- /dev/null+++ b/core/agent_core/harness/cache_metrics.py@@ -0,0 +1,199 @@+"""Request-start cache observations; diagnostics never control C-9's clearing clock.++The durable fingerprint is a chain of hashes and C-9 token estimates, not another+copy of the prompt. A whole shared request uses its reported input count; partial+prefixes are estimates, explicitly distinguished from provider measurements.+"""++from __future__ import annotations++import hashlib+import json+import math+from dataclasses import asdict+from typing import Any, Mapping, Sequence++from core.agent_core.ai._common import native_hosted_tools+from core.agent_core.ai.provider import ModelRequest+from core.agent_core.harness.context import cache_ttl_s, message_tokens, request_tokens+from core.agent_core.harness.store import ContextEntry+from core.agent_core.messages import AssistantMessage, message_to_dict+++MAX_PREFIX_BOUNDARIES = 32+++def _digest(value: Any) -> str:+ # 128-bit digests are sufficient for non-adversarial diagnostic comparisons.+ return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()[:32]+++def prefix_fingerprint(request: ModelRequest) -> list[list[Any]]:+ native = native_hosted_tools(request)+ definitions = [dict(native[tool.name].declaration or {}) if tool.name in native else asdict(tool) for tool in request.tools]+ parts = [(definitions, request_tokens("", request.tools, (), native)),+ (request.system, request_tokens(request.system, (), ()))]+ parts.extend((message_to_dict(message), message_tokens(message)) for message in request.messages)+ chain, digest, tokens = [], "", 0+ for index, (part, size) in enumerate(parts):+ digest = _digest([digest, part])+ tokens += size+ chain.append([digest, tokens, index])+ return chain+++def compact_prefix(prefix: list[list[Any]]) -> list[list[Any]]:+ """Keep tools, system and the exact final boundary, plus bounded partial-prefix samples."""+ if len(prefix) <= MAX_PREFIX_BOUNDARIES:+ return prefix+ stride = math.ceil((len(prefix) - 3) / (MAX_PREFIX_BOUNDARIES - 3))+ return [*prefix[:2], *prefix[2:-1:stride], prefix[-1]]+++def route_fingerprint(request: ModelRequest) -> str:+ endpoint = request.endpoint+ return _digest([endpoint.provider, endpoint.protocol, endpoint.model_id, endpoint.base_url,+ endpoint.cache_ttl, endpoint.cache_ttl_wire, endpoint.source_id,+ endpoint.source_identity, request.reasoning_effort])+++def valid_record(value: Any) -> bool:+ """Optional old/damaged metadata is absent, never a Turn failure."""+ try:+ return (+ isinstance(value, Mapping) and value.get("version") == 1+ and all(isinstance(value.get(key), str) for key in ("provider", "model", "route"))+ and type(value["started_at"]) in (float, int) and math.isfinite(value["started_at"])+ and value["started_at"] >= 0 and type(value["context_seq"]) is int and value["context_seq"] >= 0+ and isinstance(value["prefix"], list) and bool(value["prefix"])+ and all(isinstance(part, list) and len(part) == 3 and isinstance(part[0], str)+ and type(part[1]) is int and part[1] >= 0+ and type(part[2]) is int and part[2] >= 0 for part in value["prefix"])+ and all(a[1] <= b[1] and a[2] < b[2] for a, b in zip(value["prefix"], value["prefix"][1:]))+ and (value.get("input_tokens") is None or (type(value["input_tokens"]) is int and value["input_tokens"] >= 0))+ )+ except (KeyError, TypeError, ValueError, OverflowError):+ return False+++def write_breakdown(message: AssistantMessage | None) -> dict[str, int]:+ usage = message.usage if message is not None else None+ if usage is None:+ return {}+ known = dict(usage.cache_writes_by_ttl or {})+ unknown = max(0, usage.cache_write_tokens - sum(known.values()))+ if unknown:+ known["unknown"] = unknown+ return known+++class CacheTracker:+ """One Session's most recent request per served provider/model, across restarts."""++ def __init__(self) -> None:+ self.latest: dict[tuple[str, str], Mapping[str, Any]] = {}++ def restore(self, rows: Sequence[ContextEntry], attempts: Sequence[Mapping[str, Any]]) -> None:+ for raw in [*(row.payload.get("cache") for row in rows if row.kind == "response"), *attempts]:+ if not valid_record(raw) or raw.get("input_tokens") is None:+ continue+ key = (raw["provider"], raw["model"])+ old = self.latest.get(key)+ if old is None or raw["started_at"] >= old["started_at"]:+ self.latest[key] = raw++ def begin(+ self, request: ModelRequest, rows: Sequence[ContextEntry], *, now: float,+ causes: Sequence[Mapping[str, Any]] = (), fork: bool = False,+ ) -> dict[str, Any]:+ endpoint = request.endpoint+ record = {+ "version": 1, "started_at": now, "provider": endpoint.provider,+ "protocol": endpoint.protocol, "model": endpoint.model_id, "source_id": endpoint.source_id,+ "route": route_fingerprint(request), "prefix": prefix_fingerprint(request),+ "context_seq": max((row.context_seq for row in rows), default=0),+ "lifetime_s": cache_ttl_s(endpoint, request=request), "input_tokens": None,+ "causes": [dict(cause) for cause in causes], "writes_by_ttl": {}, "cache_write_basis": "unknown",+ }+ self._changes(record, rows)+ if fork:+ record["causes"].append({"kind": "fork_start"})+ self._expectation(record)+ return record++ def _changes(self, record: dict[str, Any], rows: Sequence[ContextEntry]) -> None:+ # Recomputed after a gateway supplies the actual served provider/model.+ computed = {"route_changed", "tools_changed", "tool_results_cleared", "checkpoint"}+ record["causes"] = [cause for cause in record["causes"] if cause.get("kind") not in computed]+ previous = self.latest.get((record["provider"], record["model"]))+ if previous is not None:+ if record["route"] != previous["route"]:+ record["causes"].append({"kind": "route_changed"})+ if record["prefix"][0][0] != previous["prefix"][0][0]:+ record["causes"].append({"kind": "tools_changed"})+ for kind, cause in (("context_edit", "tool_results_cleared"), ("compaction", "checkpoint")):+ if any(row.kind == kind and row.context_seq > previous["context_seq"] for row in rows):+ record["causes"].append({"kind": cause})++ def _expectation(self, record: dict[str, Any]) -> None:+ old = self.latest.get((record["provider"], record["model"]))+ idle = max(0.0, record["started_at"] - old["started_at"]) if old is not None else None+ record.update(idle_s=idle, expected_read=0, expected_read_basis="no_previous_request", reusable_tokens=0,+ reusable_static_tokens=0, previous_input_tokens=old.get("input_tokens") if old else None)+ if old is None:+ return+ shared = 0+ shared_static = 0+ complete = False+ if old["route"] == record["route"]:+ current = {part[2]: part for part in record["prefix"]}+ for before in old["prefix"]:+ after = current.get(before[2])+ if after is None or before[0] != after[0]:+ break+ shared = before[1]+ if before[2] <= 1:+ shared_static = before[1]+ else:+ complete = True+ total = old["prefix"][-1][1]+ reported = old.get("input_tokens")+ expected = shared * reported // total if reported is not None and total else shared+ basis = "reported_input" if reported is not None and complete else "estimated_prefix"+ static = shared_static * reported // total if reported is not None and total else shared_static+ record.update(reusable_tokens=expected, reusable_static_tokens=static, expected_read_basis=basis)+ if idle <= record["lifetime_s"]:+ record["expected_read"] = expected+ else:+ record["expected_read_basis"] = "expired"++ def finish(+ self, record: dict[str, Any], message: AssistantMessage | None, *, rows: Sequence[ContextEntry] = (),+ ) -> None:+ if message is not None:+ # A gateway can serve a different provider/model from the requested alias.+ record.update(provider=message.origin.provider, model=message.origin.model)+ self._changes(record, rows)+ self._expectation(record)+ if message.usage is not None:+ usage = message.usage+ record["input_tokens"] = usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens+ total = record["prefix"][-1][1]+ static = record["prefix"][min(1, len(record["prefix"]) - 1)][1]+ record["static_tokens"] = static * record["input_tokens"] // total if total else 0+ record["writes_by_ttl"] = write_breakdown(message)+ usage = message.usage if message is not None else None+ if usage is None:+ record["cache_write_basis"] = "unknown"+ elif not usage.cache_write_total_reported:+ record["cache_write_basis"] = "incomplete_total"+ elif usage.cache_write_tokens == 0:+ record["cache_write_basis"] = "none"+ elif usage.cache_writes_by_ttl is None:+ record["cache_write_basis"] = "unknown"+ else:+ record["cache_write_basis"] = "reported"+ record["prefix"] = compact_prefix(record["prefix"])+ # A refusal without usage is no evidence that the provider populated its cache.+ if usage is not None:+ self.latest[(record["provider"], record["model"])] = recorddiff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 7e6f10614..5ef402491 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -473,6 +473,12 @@ def add_usage(total: Optional[Usage], usage: Optional[Usage]) -> Optional[Usage]cache_read_tokens=total.cache_read_tokens + usage.cache_read_tokens,cache_write_tokens=total.cache_write_tokens + usage.cache_write_tokens,reasoning_tokens=reasoning,+ cache_writes_by_ttl=(+ None if total.cache_writes_by_ttl is None and usage.cache_writes_by_ttl is None else+ {ttl: (total.cache_writes_by_ttl or {}).get(ttl, 0) + (usage.cache_writes_by_ttl or {}).get(ttl, 0)+ for ttl in (total.cache_writes_by_ttl or {}).keys() | (usage.cache_writes_by_ttl or {}).keys()}+ ),+ cache_write_total_reported=total.cache_write_total_reported and usage.cache_write_total_reported,)diff --git a/core/agent_core/harness/store.py b/core/agent_core/harness/store.pyindex 10fb3ad82..14d021072 100644--- a/core/agent_core/harness/store.py+++ b/core/agent_core/harness/store.py@@ -44,6 +44,10 @@ class TranscriptStore(Protocol):"""Context entries of the Session and its fork ancestry, ordered by ``context_seq``."""...+ async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping[str, Any]]:+ """Latest optional request-cache record per route from this Session's non-context attempts."""+ ...+async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:"""Admit an already stored input row into the context as rendered for the model."""...@@ -55,6 +59,7 @@ class TranscriptStore(Protocol):*,final: bool,request: Optional[Mapping[str, Any]] = None,+ cache: Optional[Mapping[str, Any]] = None,replied: Optional[bool] = None,images: Sequence[HostedImage] = (),superseded: bool = False,diff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex 0fd9ec76a..6ed20e321 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -816,14 +816,27 @@ class Usage:cache_read_tokens: int = 0cache_write_tokens: int = 0reasoning_tokens: Optional[int] = None+ # Transient provider diagnostics: only ModelResponse.cache persists these.+ # Keeping the canonical Usage shape unchanged permits older releases to read the transcript.+ cache_writes_by_ttl: Optional[Mapping[str, int]] = field(default=None, compare=False, repr=False)+ # False when a provider exposed TTL detail but omitted the aggregate write total; the+ # detail may be retained for diagnostics but must not be treated as complete billing input.+ cache_write_total_reported: bool = field(default=True, compare=False, repr=False)def __post_init__(self) -> None:for name in ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"):_require(getattr(self, name), int, name)_require(self.reasoning_tokens, int, "reasoning_tokens", optional=True)+ _require(self.cache_write_total_reported, bool, "cache_write_total_reported")counts = (self.input_tokens, self.output_tokens, self.cache_read_tokens, self.cache_write_tokens)if any(c < 0 for c in counts) or (self.reasoning_tokens is not None and self.reasoning_tokens < 0):raise ValueError("token counts must not be negative")+ if self.cache_writes_by_ttl is not None:+ if (not isinstance(self.cache_writes_by_ttl, Mapping)+ or any(key not in {"5m", "1h", "30m", "12h"} or type(value) is not int or value < 0+ for key, value in self.cache_writes_by_ttl.items())+ or (self.cache_write_total_reported and sum(self.cache_writes_by_ttl.values()) > self.cache_write_tokens)):+ raise ValueError("invalid cache write TTL decomposition")@dataclass(frozen=True)diff --git a/core/handlers/cache_metrics.py b/core/handlers/cache_metrics.pynew file mode 100644index 000000000..85690dfc3--- /dev/null+++ b/core/handlers/cache_metrics.py@@ -0,0 +1,272 @@+"""Read-only Vibey cache report: current-list valuation, never a historical bill."""++from __future__ import annotations++from collections import defaultdict+from datetime import datetime, timezone+import json+import math+from pathlib import Path+import re+from typing import Any, Mapping, Sequence++from storage.cache_metrics import count, object_value, seconds+from .model_hub.pricing import (+ Cost, PriceTable, context_tier_price, context_tier_size, load_price_table, row_cost,+)+++def cached_prices(state_dir: Path) -> PriceTable:+ from vibe.models_dev_catalog import cached_models_dev_catalog, load_model_vendor_map++ # The cached-only API exposes no fetch date. File mtime is not a price-table date.+ return load_price_table(+ state_dir, catalog_loader=lambda: (cached_models_dev_catalog(), None, False),+ vendor_map_loader=load_model_vendor_map,+ )+++def _rate_metadata(price) -> dict[str, dict[str, float | str | None]]:+ input_rate = price.input++ def multiplier(rate: float) -> float | None:+ return rate / input_rate if input_rate else None++ rates = {+ "input": price.input, "output": price.output, "cache_read": price.cache_read,+ "cache_write": price.cache_write, "cache_write_1h": price.cache_write_1h,+ "cache_write_30m": price.cache_write_30m, "cache_write_12h": price.cache_write_12h,+ }+ sources = {key: "listed" if key in price.listed_cache_rates else "default"+ for key in rates if key.startswith("cache_")}+ return {+ "multipliers": {key: multiplier(rate) for key, rate in rates.items()},+ "sources": sources,+ }+++def ledger_row(usage: Mapping[str, Any], ttls: Mapping[str, Any], price, *, write_basis: str = "reported") -> dict[str, Any]:+ total = sum(count(usage.get(key)) for key in ("input_tokens", "cache_read_tokens", "cache_write_tokens"))+ return {+ "requests": 1, "token_reports": int(bool(usage)), "input_tokens": total,+ "output_tokens": count(usage.get("output_tokens")), "cached_input_tokens": count(usage.get("cache_read_tokens")),+ "cache_write_input_tokens": count(usage.get("cache_write_tokens")),+ "cache_write_1h_input_tokens": count(ttls.get("1h")),+ "cache_write_30m_input_tokens": count(ttls.get("30m")), "cache_write_12h_input_tokens": count(ttls.get("12h")),+ "cache_write_ttl_uncaptured_reports": int(+ write_basis == "incomplete_total" or (+ count(usage.get("cache_write_tokens")) > 0+ and (write_basis not in {"reported", "none"} or count(ttls.get("unknown")) > 0)+ )+ ),+ "context_tier": context_tier_size(price, total),+ }+++def valuation(model: str | None, usage_raw: Any, ttls_raw: Any, prices: PriceTable, write_basis: str = "reported") -> dict[str, Any]:+ usage, ttls = object_value(usage_raw), object_value(ttls_raw)+ price = prices.price(model) if isinstance(model, str) else None+ row = ledger_row(usage, ttls, price, write_basis=write_basis)+ cost = row_cost(row, price)+ result = {"basis": "current_standard_list", "usd": cost.api_cost_usd if price and usage else None,+ "lower_bound": cost.api_cost_lower_bound or cost.excluded_tokens > 0,+ "excluded_tokens": cost.excluded_tokens, "price_table_date": prices.price_table_date,+ "price_key": prices.price_key(model) if price and isinstance(model, str) else None,+ "cache_write_basis": write_basis}+ if price:+ rate = context_tier_price(price, row["context_tier"])+ result["rates_per_million"] = {+ key: getattr(rate, key) for key in ("input", "output", "cache_read", "cache_write", "cache_write_1h", "cache_write_30m", "cache_write_12h")+ }+ metadata = _rate_metadata(rate)+ result["rate_multipliers"] = metadata["multipliers"]+ result["rate_sources"] = metadata["sources"]+ result["read_discount_known"] = "cache_read" in rate.listed_cache_rates+ result["context_tier"] = row["context_tier"]+ return result+++def _usage(row: Mapping[str, Any]) -> dict[str, int]:+ return {"input_tokens": count(row.get("fresh_input_tokens")), "output_tokens": count(row.get("output_tokens")),+ "cache_read_tokens": count(row.get("cache_read_tokens")), "cache_write_tokens": count(row.get("cache_write_tokens"))} if row.get("token_reported") else {}+++def _band(idle: float | None) -> str:+ if idle is None:+ return "unknown"+ for upper, label in ((300, "up_to_5m"), (1800, "5_to_30m"), (3600, "30_to_60m"), (43200, "1_to_12h")):+ if idle <= upper:+ return label+ return "over_12h"+++def _options(provider: str, protocol: str, model: str) -> tuple[tuple[str, int], ...]:+ if provider == "anthropic" and protocol == "anthropic" and model.startswith("claude-"):+ return (("5m", 300), ("1h", 3600))+ gpt = re.fullmatch(r"gpt-(\d+)(?:\.(\d+))?(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?", model)+ if provider == "openai" and protocol == "openai_responses" and gpt and (int(gpt[1]), int(gpt[2] or 0)) >= (5, 6):+ return (("30m", 1800), ("12h", 43200))+ return ()+++def lifetime_cost(rows: Sequence[Mapping[str, Any]], *, label: str, lifetime: int, prices: PriceTable) -> dict[str, Any]:+ """Counterfactual input cost: only expiry recovers writes; other misses stay misses.++ All writes pay the candidate's price, not just recovered tokens. Anthropic's+ static prefix remains at one hour; its size is an explicitly estimated share.+ """+ usd, priced, unpriced, recovered, expired, incomplete = 0.0, 0, 0, 0, 0, 0+ rates = {}+ for row in rows:+ price = prices.price(row["model"])+ writes = object_value(row.get("writes_by_ttl"))+ if (price is None or not row.get("token_reported")+ or row.get("cache_write_basis") == "incomplete_total"+ or count(writes.get("unknown")) > 0):+ unpriced += count(row.get("input_tokens"))+ incomplete += 1+ continue+ price = context_tier_price(price, context_tier_size(price, count(row.get("input_tokens"))))+ priced += 1+ fresh, read, write = (count(row.get(key)) for key in ("fresh_input_tokens", "cache_read_tokens", "cache_write_tokens"))+ eligible = min(count(row.get("reusable_tokens")), fresh + read + write)+ static = min(eligible, count(row.get("reusable_static_tokens"))) if row["protocol"] == "anthropic" else 0+ idle = row.get("idle_s")+ capacity = eligible if idle is not None and idle <= lifetime else (static if idle is not None and idle <= 3600 else 0)+ if row["classification"] == "passive_expiry":+ recover = min(max(0, capacity - read), fresh + write)+ from_write = min(write, recover)+ write -= from_write+ fresh -= recover - from_write+ read += recover+ recovered += recover+ if idle is not None and idle > lifetime:+ expire = max(0, min(read, eligible) - capacity)+ read -= expire+ write += expire+ expired += expire+ write_rate = {"5m": price.cache_write, "1h": price.cache_write_1h,+ "30m": price.cache_write_30m, "12h": price.cache_write_12h}[label]+ static_write = min(write, max(0, count(row.get("static_tokens")) - read)) if row["protocol"] == "anthropic" else 0+ usd += (fresh * price.input + read * price.cache_read + (write - static_write) * write_rate + static_write * price.cache_write_1h) / 1e6+ incomplete += int(row.get("cache_write_basis") not in {"reported", "none"})+ rate_meta = _rate_metadata(price)+ rates[str(context_tier_size(prices.price(row["model"]), count(row.get("input_tokens"))))] = {+ "input": price.input, "read": price.cache_read, "write": write_rate,+ "static_write_1h": price.cache_write_1h if row["protocol"] == "anthropic" else None,+ "multipliers": rate_meta["multipliers"], "sources": rate_meta["sources"],+ }+ return {"lifetime": label, "lifetime_s": lifetime, "input_cost_usd": round(usd, 6) if priced else None,+ "estimated": True, "incomplete_requests": incomplete, "excluded_input_tokens": unpriced,+ "recovered_tokens": recovered, "newly_expired_tokens": expired, "rates_per_million_by_context_tier": rates,+ "rate_basis": "local catalog/overrides including catalog defaults; standard speed"}+++def _percentile(values: list[float], fraction: float) -> float | None:+ return sorted(values)[max(0, math.ceil(len(values) * fraction) - 1)] if values else None+++def summarize(rows: Sequence[Mapping[str, Any]], events: Sequence[Mapping[str, Any]], prices: PriceTable) -> dict[str, Any]:+ grouped = defaultdict(list)+ for row in rows:+ grouped[(row.get("provider"), row.get("protocol"), row.get("model"), row.get("source_id"))].append(row)+ routes = []+ for (provider, protocol, model, source), requests in sorted(grouped.items(), key=lambda item: repr(item[0])):+ totals = Cost()+ classes, causes, bands, ttls = {}, {}, {}, defaultdict(int)+ actual_reads = total_input = 0+ for row in requests:+ usage, writes = _usage(row), object_value(row.get("writes_by_ttl"))+ price = prices.price(model) if isinstance(model, str) else None+ cost = row_cost(ledger_row(usage, writes, price, write_basis=str(row.get("cache_write_basis") or "unknown")), price)+ totals.add(cost)+ actual_reads += count(row.get("cache_read_tokens"))+ total_input += count(row.get("input_tokens"))+ for ttl, tokens in writes.items():+ ttls[ttl] += count(tokens)+ cause_names = set()+ try:+ parsed_causes = json.loads(row.get("causes") or "[]")+ cause_names = {item["kind"] + (":" + item["reason"] if item.get("reason") else "") for item in parsed_causes}+ except (TypeError, ValueError, KeyError):+ pass+ for target, keys in ((classes, [row["classification"]]), (bands, [_band(row.get("idle_s"))]), (causes, cause_names)):+ for key in keys:+ bucket = target.setdefault(key, {"requests": 0, "cache_write_tokens": 0, "uncached_input_tokens": 0,+ "missed_prefix_tokens": 0, "reusable_tokens": 0, "cost": Cost()})+ bucket["requests"] += 1+ for output, column in (("cache_write_tokens", "cache_write_tokens"), ("uncached_input_tokens", "fresh_input_tokens"),+ ("missed_prefix_tokens", "missed_prefix_tokens"), ("reusable_tokens", "reusable_tokens")):+ bucket[output] += count(row.get(column))+ bucket["cost"].add(cost)+ for buckets in (classes, causes, bands):+ for bucket in buckets.values():+ cost = bucket.pop("cost")+ bucket.update(cost.fields())+ routes.append({"provider": provider, "protocol": protocol, "model": model, "source_id": source,+ "requests": len(requests), "timestamp_inferred_requests": sum(row.get("data_basis") != "observed" for row in requests),+ "cache_read_tokens": actual_reads, "input_tokens": total_input,+ "hit_rate_tokens": actual_reads / total_input if total_input else None,+ "classes": classes, "causes": causes, "idle_bands": bands, "writes_by_ttl": dict(ttls),+ "valuation": {**totals.fields(), "price_key": prices.price_key(model) if isinstance(model, str) else None},+ "what_if": [lifetime_cost(requests, label=label, lifetime=ttl, prices=prices)+ for label, ttl in _options(provider or "", protocol or "", model or "")]})+ waits = defaultdict(list)+ forced = defaultdict(int)+ for event in events:+ data = object_value(event.get("content_json"))+ if event.get("event_type") != "prompt.applied":+ continue+ components = data.get("components")+ for item in components if isinstance(components, list) else ():+ wait = seconds(item.get("wait_s")) if isinstance(item, dict) else None+ if wait is not None and type(item.get("tier")) is int and item["tier"] in (1, 2, 3):+ waits[item["tier"]].append(wait)+ if data.get("reason") == "deadline":+ forced[(event["session_id"], str(event.get("created_at", ""))[:10])] += 1+ turns = {(row["session_id"], row.get("turn_id") or row["request_id"]) for row in rows if row["purpose"] == "conversation"}+ pending_turns = {(row["session_id"], row.get("turn_id") or row["request_id"]) for row in rows+ if row["purpose"] == "conversation" and row.get("prompt_notice")}+ return {+ "routes": routes, "requests": len(rows), "pricing": prices.fields(),+ "freshness": {"tiers": {str(tier): {"applied_components": len(waits[tier]), "median_s": _percentile(waits[tier], .5),+ "p90_s": _percentile(waits[tier], .9), "max_s": max(waits[tier], default=None)} for tier in (1, 2, 3)},+ "forced_refreshes": [{"session_id": session, "day_utc": day, "count": amount} for (session, day), amount in sorted(forced.items())],+ "turns": len(turns), "turns_with_pending_notice": len(pending_turns),+ "pending_notice_share": len(pending_turns) / len(turns) if turns else None},+ "notes": [+ "Current standard list valuations, not historical or subscription bills; aliases/default prices may apply. Fast-mode premiums are not observed.",+ "Legacy rows infer gaps from response timestamps and use current route lifetime assumptions; they cannot prove an active break.",+ "Expected reads and static-prefix sizes can be token estimates. A provider_miss classification is diagnostic, not proof of provider fault.",+ "Lifetime what-ifs are estimates: only passive expiry recovers tokens; every write pays the proposed rate. Claude static prefixes stay at one hour.",+ "Unknown TTL writes and missing aggregate write totals are excluded from lifetime what-ifs, never assigned a lifetime.",+ "OpenAI retention is a minimum, not a deterministic eviction deadline; estimated expiry counts are upper bounds.",+ "Cause buckets overlap when one request has multiple causes; do not sum them. Model Hub totals include additional hosted/proxy traffic.",+ ],+ }+++def report(*, since: datetime, until: datetime, session_id: str | None, model: str | None, user_context, db_path: Path) -> dict[str, Any]:+ from storage.read_only_query import run_read_only_query++ def literal(value: str) -> str:+ return "'" + value.replace("'", "''") + "'"++ filters = [f"started_at >= {since.timestamp()}", f"started_at < {until.timestamp()}"]+ if session_id:+ filters.append("session_id = " + literal(session_id))+ if model:+ filters.append("model = " + literal(model))+ rows = run_read_only_query("SELECT * FROM cache_requests WHERE " + " AND ".join(filters),+ page_request=None, db_path=db_path, user_context=user_context).rows+ event_filters = ["event_type IN ('prompt.pending', 'prompt.applied')",+ "created_at >= " + literal(since.astimezone(timezone.utc).isoformat()),+ "created_at < " + literal(until.astimezone(timezone.utc).isoformat())]+ if session_id:+ event_filters.append("session_id = " + literal(session_id))+ elif model:+ sessions = sorted({row["session_id"] for row in rows})+ event_filters.append("session_id IN (" + ",".join(literal(session) for session in sessions) + ")" if sessions else "0")+ events = run_read_only_query("SELECT session_id, event_type, created_at, content_json FROM agent_events WHERE " + " AND ".join(event_filters),+ page_request=None, db_path=db_path, user_context=user_context).rows+ return {"since": since.isoformat(), "until": until.isoformat(), **summarize(rows, events, cached_prices(db_path.parent))}diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.pyindex cdb090a10..35f158cd8 100644--- a/core/handlers/model_hub/pricing.py+++ b/core/handlers/model_hub/pricing.py@@ -26,7 +26,7 @@ import jsonimport loggingimport mathimport re-from dataclasses import dataclass, replace+from dataclasses import dataclass, field, replacefrom datetime import date, datetime, timedeltafrom pathlib import Pathfrom typing import Any, Callable, Final, Mapping, Optional@@ -128,6 +128,8 @@ class ModelPrice:# `experimental.modes.fast.cost`: a call its response says ran fast is billed# at these rates, read by the same rules. None when the table lists none.fast: Optional["ModelPrice"] = None+ # Diagnostic provenance only; does not change accounting or price equality.+ listed_cache_rates: frozenset[str] = field(default_factory=frozenset, compare=False, repr=False)def _bounded(value: object, ceiling: float) -> Optional[float]:@@ -251,6 +253,9 @@ def _flat_price(cost: object) -> Optional[ModelPrice]:),cache_write_30m=input_price * 1.25 if cache_write_30m is None else cache_write_30m,cache_write_12h=input_price * 2.5 if cache_write_12h is None else cache_write_12h,+ listed_cache_rates=frozenset(key for key in (+ "cache_read", "cache_write", "cache_write_1h", "cache_write_30m", "cache_write_12h",+ ) if _price(cost.get(key)) is not None),charges_cache_writes=any(price is not None and price > input_price for price in (cache_write, cache_write_1h)),@@ -410,6 +415,25 @@ class PriceTable:self._memo[key] = self._resolve(key, hops=0)return self._memo[key]+ def price_key(self, model_id: str) -> Optional[str]:+ """The concrete table/override key used by ``price(model_id)``."""+ return self._resolve_key(normalize_model_id(model_id), hops=0)++ def _resolve_key(self, key: str, *, hops: int) -> Optional[str]:+ if hops > _MAX_ALIAS_HOPS or not key:+ return None+ override = self._model_overrides.get(key)+ if override is not None:+ alias, price = override+ if alias is not None:+ return self._resolve_key(alias, hops=hops + 1)+ if price is not None:+ return key+ if self._catalog_price(key) is not None:+ return key+ alias = MODEL_ALIASES.get(key)+ return self._resolve_key(alias, hops=hops + 1) if alias is not None else None+def _resolve(self, key: str, *, hops: int) -> Optional[ModelPrice]:if hops > _MAX_ALIAS_HOPS or not key:return Nonediff --git a/docs/CLI.md b/docs/CLI.mdindex f8fde8805..39b2e37d6 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -367,9 +367,10 @@ vibe data query --sql "select id, status, created_at from agent_runs order by crvibe data query --sql-file query.sql --limit 50```-Four views give every query a stable way into conversation history; the raw+Four history views give every query a stable way into conversation history; the rawtables stay queryable. Start from `digests` to recognize a Session, then read-its details in `transcript` or `turns`:+its details in `transcript` or `turns`. Cache diagnostics add two connection-local+views described below; they do not create database tables:| View | Columns | Meaning || --- | --- | --- |@@ -377,6 +378,8 @@ its details in `transcript` or `turns`:| `sessions` | `session_id`, `title`, `agent_name`, `backend`, `model`, `status`, `workdir`, `created_at`, `last_active_at`, `parent_session_id` | One row per Session. `parent_session_id` is the Session whose Agent started it with `vibe agent run`. || `transcript` | `session_id`, `at`, `role`, `kind`, `text`, `turn_id`, `message_id` | Every message with text, in delivery time `at`. `role` is `user`, `agent`, or `harness` (input Avibe delivered: another Agent's brief, a callback, a Watch or Task); `kind` is the message type, such as `result` for an Agent's reply. || `turns` | `session_id`, `turn_id`, `started_at`, `ended_at`, `outcome`, `input`, `reply` | One row per recorded Agent Turn: the text it was given and its final reply. Older history without Turn records is in `transcript`. |+| `_cache_rows` | Internal source view for cache diagnostics | Response, attempt, and fork-turn rows normalized before `cache_requests`; use `cache_requests` for a stable public shape. |+| `cache_requests` | `request_id`, `session_id`, `turn_id`, `at`, `started_at`, `provider`, `protocol`, `model`, `purpose`, classification/facts, valuation | Per-request Vibey cache facts and a current-list cost valuation. Rows with no `cache` object are explicitly `timestamp_inferred`; `valuation` is JSON and may be a lower bound or have no USD value. |Two functions help with long text. `excerpt(text, 'term')` returns about 300characters of `text` around the first case-insensitive match of `term` (pass a@@ -402,6 +405,33 @@ are refused. The schema PRAGMAs `table_list`, `table_info`, `table_xinfo`,names and the table list, or the referenced tables' columns. Tasks and Watchesare rows of `run_definitions` (`definition_type` is `scheduled` or `watch`).+### `vibe data cache`++Summarize Vibey cache behavior for the last seven days, or an explicit UTC time+range. This command is read-only and requires the Member-level diagnostic access+needed to inspect `agent_events`.++```bash+vibe data cache+vibe data cache --since 30d --until 2026-10-31T00:00:00Z+vibe data cache --session-id sesk8m4q2p7x --model claude-opus-5-5+```++The report groups request facts by served route and includes idle bands,+active/passive/provider-miss/estimated-miss classes, causes, TTL write buckets, prompt freshness+by tier, and lifetime what-if estimates where the route supports an override.+Cost values use the cached local standard price list, including any local alias or+default rate; they are not historical provider bills or subscription charges.+Missing usage, unknown TTLs, inferred legacy timestamps, aliases, default rates,+and unavailable fast-mode information remain labeled in the JSON result. Valuation+also reports the concrete price key, per-token rate multipliers, and whether cache+rates are listed or defaulted, with an explicit flag when the read discount is+unknown. What-if+figures keep active breaks and provider misses as misses, recover only passive+expiry, and reprice all known writes at the candidate lifetime's rate (Claude's+static tools/system prefix stays at one hour). Requests with unknown TTL writes or+an unreported aggregate write count are excluded from what-ifs, not reassigned.+### `vibe data skill-usage`Instance Owner-only local maintenance; these commands return JSON diagnostics,diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex cce21fa56..1aea20dc4 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -270,8 +270,9 @@ vibe data query --sql "select id, status, created_at from agent_runs order by crvibe data query --sql-file query.sql --limit 50```-四个视图为每次查询提供读取对话历史的稳定入口;原始表照样可以直接查询。先用 `digests`-认出 Session,再到 `transcript` 或 `turns` 里读细节:+四个历史视图为每次查询提供读取对话历史的稳定入口;原始表照样可以直接查询。先用 `digests`+认出 Session,再到 `transcript` 或 `turns` 里读细节。缓存诊断另外提供两个仅连接内+存在的临时视图,不会创建数据库表:| 视图 | 列 | 含义 || --- | --- | --- |@@ -279,6 +280,8 @@ vibe data query --sql-file query.sql --limit 50| `sessions` | `session_id`、`title`、`agent_name`、`backend`、`model`、`status`、`workdir`、`created_at`、`last_active_at`、`parent_session_id` | 每个 Session 一行。`parent_session_id` 是用 `vibe agent run` 启动它的那个 Session。 || `transcript` | `session_id`、`at`、`role`、`kind`、`text`、`turn_id`、`message_id` | 所有有正文的消息,`at` 是送达时间。`role` 为 `user`、`agent` 或 `harness`(Avibe 投递的输入:其他 Agent 的任务说明、回调、Watch 或 Task);`kind` 是消息类型,例如 Agent 的回复是 `result`。 || `turns` | `session_id`、`turn_id`、`started_at`、`ended_at`、`outcome`、`input`、`reply` | 每个有记录的 Agent 回合一行:它收到的原文和最终回复。没有回合记录的更早历史在 `transcript` 里。 |+| `_cache_rows` | 内部来源视图 | 把响应、attempt 和 fork-turn 行规范化;稳定的对外查询应使用 `cache_requests`。 |+| `cache_requests` | `request_id`、`session_id`、`turn_id`、`at`、`started_at`、`provider`、`protocol`、`model`、`purpose`、分类/事实、估值 | 每个 Vibey 请求的缓存事实和当前价目表估值。缺少 `cache` 对象的旧行会明确标为 `timestamp_inferred`;`valuation` 是 JSON,可能是下限或没有 USD 值。 |两个函数用来处理长文本。`excerpt(text, 'term')` 返回 `text` 中第一个匹配 `term`(不区分大小写)的位置前后约 300 个字符,第三个参数可以调整宽度;没有匹配时返回开头。@@ -299,6 +302,26 @@ PRAGMA 一律拒绝。`no such table` 或 `no such column` 错误会带上 `hint名称以及表清单,或所引用表的列。Task 和 Watch 都是 `run_definitions` 的行(`definition_type` 为 `scheduled` 或 `watch`)。+### `vibe data cache`++汇总 Vibey 最近七天的缓存行为,也可以指定 UTC 时间范围。命令只读,要求具备读取+`agent_events` 所需的 Member 级诊断权限。++```bash+vibe data cache+vibe data cache --since 30d --until 2026-10-31T00:00:00Z+vibe data cache --session-id sesk8m4q2p7x --model claude-opus-5-5+```++报告按服务路由汇总请求事实,包含空闲区间、active/passive/provider-miss/estimated-miss 分类、原因、+TTL 写入桶、按 tier 的提示词新鲜度,以及支持指定 lifetime 的 what-if 估算。费用使用+本地缓存的当前标准价目表(含本地别名或缺省倍率),不是历史供应商账单或订阅费用。+缺失 usage、未知 TTL、旧行时间推断、别名、缺省价格和无法观测的 fast 模式都会在 JSON+结果中明确标注;估值还会返回实际使用的 price key、各 token 费率倍率、明确列出或缺省的+费率来源,以及读折扣是否已知。what-if 保持主动变更和 provider miss 不恢复,只恢复 passive expiry,+并让所有已知写入按候选 lifetime 重新计费(Claude 的 tools/system 静态前缀保持 1 小时)。+TTL 未知或供应商未报告 aggregate 写入总量的请求从 what-if 排除,不会被重新分配 lifetime。+### `vibe data skill-usage`仅限实例所有者使用的本地维护命令,返回 JSON 诊断信息,不是 Skill 热度排名。diff --git a/docs/plans/agent-core-contracts/context.md b/docs/plans/agent-core-contracts/context.mdindex ae0316075..daf29c215 100644--- a/docs/plans/agent-core-contracts/context.md+++ b/docs/plans/agent-core-contracts/context.md@@ -663,7 +663,12 @@ every-exit audit: `test_loop.py`) that fails when its order or owner is broken.conversation attempt that did not become a response row (retried, relieved, a usage-only terminal, refused atadmission, or a failed commit): one non-context `ModelAttempt` audit row, never a response row, written in everymode, with or without `ContextConfig`, on every exit of the model call but an abort; a failed audit write is a- diagnostic and is not retried. The cancelled run scope admits no further store write, so an aborted call's+ diagnostic and is not retried. When cache metrics are enabled, an attempt without usage also keeps optional+ request-start diagnostics in this audit; absent usage is unknown, never a zero-token report. Only a+ usage-bearing attempt advances the diagnostic cache clock or consumes pending change causes. Responses keep+ optional `ModelResponse.cache`; attempt/side-turn audits keep `cache`/`cache_attempts` and the latest per-route+ `cache_state`. These diagnostics do not alter the C-9 response-end clock or canonical Usage.+ The cancelled run scope admits no further store write, so an aborted call'sunaudited attempts are not kept. It is the one place that usage is kept. A checkpoint attempt's partials andusage are kept in its side turn's `fork_turn` audit row (§6, C-10 F7), written by the same rule: once, on everyexit but an abort, whichever step ends it (compose, provider, admission, the host's state or hint, building thediff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex c31da533e..b1e53df06 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -288,9 +288,9 @@ There is one normalizer per adapter, not separate initial/delta/choice mappers.Mapped counters are shape-validated before normalization. Ignored fields arenot revalidated or retained: they do not influence canonical usage. Thecanonical schema deliberately has no per-modality, TTL, request-count, tier,-geography, cost or redundant-total field. This inventory does not add any.-Reasoning is already included in output, never added to it; a missing optional-reasoning count remains `None`, unlike Pi's default zero.+geography, cost or redundant-total field. This inventory does not add any. Reasoning is already included in output, never added to it; a missing optional reasoning count remains `None`, unlike Pi's default zero.++This optional decomposition is deliberately outside canonical `Usage`: it is a transient adapter diagnostic and, when a response is committed, is carried once by `ModelResponse.cache.writes_by_ttl`. Bad or contradictory optional TTL data is dropped to `unknown`; it never makes an otherwise valid provider response terminal. The aggregate write total remains the source of token accounting, and a missing OpenAI aggregate is marked incomplete even when both TTL details are present.#### Anthropic: `_anthropic_usage`@@ -307,8 +307,8 @@ Pi's separate `cacheWrite1h` (`:840-847`) has no canonical counterpart.| `cache_read_input_tokens` | `cache_read_tokens` || `cache_creation_input_tokens` | `cache_write_tokens`; non-null aggregate wins over every TTL value, including when aggregate is zero || `cache_creation` | Nullable TTL breakdown container. If aggregate is missing/null, sum its non-null counters as the reported snapshot; missing/null/empty/all-null breakdown preserves current aggregate. Do not add a TTL snapshot to previous usage. |-| `cache_creation.ephemeral_5m_input_tokens` | Part of fallback `cache_write_tokens` sum only; absent/null contributes nothing. Explicit zero is a reported value. No separate TTL field. |-| `cache_creation.ephemeral_1h_input_tokens` | Same fallback policy as 5m; never added on top of an aggregate. No separate 1h billing field; Model Hub's usage ledger meters the one-hour part (`cache_write_1h_input_tokens`, `model-hub-contracts/api.md`). |+| `cache_creation.ephemeral_5m_input_tokens` | Part of the transient `Usage.cache_writes_by_ttl["5m"]` diagnostic when the aggregate is compatible; absent/null contributes nothing. Explicit zero is a reported value. It is never added to canonical totals or persisted in canonical `Usage`. |+| `cache_creation.ephemeral_1h_input_tokens` | Same transient diagnostic policy for `"1h"`; never added on top of an aggregate. Model Hub's separate usage ledger meters the one-hour part (`cache_write_1h_input_tokens`, `model-hub-contracts/api.md`). || `output_tokens_details` | Nullable decomposition container; not itself a count || `output_tokens_details.thinking_tokens` | `reasoning_tokens`; non-null merge at both message start and delta. This observability subset does not increase `output_tokens`. || `server_tool_use` | Ignored: server-side request-count metadata, not tokens or canonical tool calls |@@ -373,8 +373,8 @@ reasoning follows the canonical optional-field rule.| `input_tokens_details` | Input breakdown container; not itself a count || `input_tokens_details.cached_tokens` | `cache_read_tokens`, default zero || `input_tokens_details.cache_write_tokens` | `cache_write_tokens`, default zero; distinct from cache reads |-| `input_tokens_details.cache_write_tokens_details.ttl_30m_tokens` | `cache_write_30m_input_tokens`; disjoint from the 12h count |-| `input_tokens_details.cache_write_tokens_details.ttl_12h_tokens` | `cache_write_12h_input_tokens`; disjoint from the 30m count |+| `input_tokens_details.cache_write_tokens_details.ttl_30m_tokens` | Transient `Usage.cache_writes_by_ttl["30m"]`; the decomposition is persisted only in the optional response `cache.writes_by_ttl` object, not in canonical Usage. |+| `input_tokens_details.cache_write_tokens_details.ttl_12h_tokens` | Transient `Usage.cache_writes_by_ttl["12h"]`; disjoint from the 30m count. If the aggregate write total is absent, the response is marked incomplete rather than treating the detail sum as a complete total. || `output_tokens` | `output_tokens`, inclusive of reasoning || `output_tokens_details` | Output decomposition container; not itself a count || `output_tokens_details.reasoning_tokens` | `reasoning_tokens`; absent field is `None`. Accepted compatible null counter normalizes to zero, matching Pi. |diff --git a/docs/plans/agent-core-contracts/transcript-rows.schema.json b/docs/plans/agent-core-contracts/transcript-rows.schema.jsonindex a42a41565..bf8766a50 100644--- a/docs/plans/agent-core-contracts/transcript-rows.schema.json+++ b/docs/plans/agent-core-contracts/transcript-rows.schema.json@@ -4,6 +4,17 @@"title": "TranscriptRowPayloads","description": "C-5 payloads of context rows (transcript.md). Written by the adapter's TranscriptStore for the `harness`; read by projection, fork, resume, and the Workbench model view. All shapes are persisted and versioned.","definitions": {+ "CacheObservation": {+ "description": "Optional request-start diagnostics (system-prompt-cache-tiers.md). Never canonical usage or a C-9 control clock. Damaged diagnostics are ignored by readers; unknown fields permit additions without a migration.",+ "type": "object",+ "required": ["version"],+ "properties": {"version": {"const": 1}}+ },+ "CacheState": {+ "description": "Latest usage-bearing request per served provider/model; bounded sampled prefix hashes, never message content.",+ "type": "array",+ "items": {"$ref": "#/definitions/CacheObservation"}+ },"ModelInput": {"description": "`messages.content_json.model` on user, harness, agent_initiated, and annotation rows, set when the loop consumes the input.","type": "object",@@ -38,6 +49,7 @@"$ref": "message.schema.json#/definitions/AssistantMessage","description": "Verbatim, including quick-reply blocks and file:// links that the display copy rewrites."},+ "cache": {"$ref": "#/definitions/CacheObservation"},"request": {"type": "object","description": "C-9 (context.md section 2): the request this response answered, as sent, for the estimate anchor. Written only when context management is on.",@@ -524,24 +536,39 @@"$ref": "message.schema.json"}},+ "cache_state": {"$ref": "#/definitions/CacheState"},+ "cache_attempts": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["cache"],+ "additionalProperties": false,+ "properties": {+ "cache": {"$ref": "#/definitions/CacheObservation"},+ "usage": {"$ref": "message.schema.json#/definitions/Usage"}+ }+ }+ },"usage": {"$ref": "message.schema.json#/definitions/Usage"}}},"ModelAttempt": {- "description": "`agent_events.content_json` of a `model_attempt` audit row (`TranscriptStore.append_audit(kind='attempt')`, `visibility = 'audit'`, no `context_seq`): a conversation attempt that reported usage and did not become a response row (retried, relieved, a usage-only terminal, refused at admission, or a failed commit), written by the attempt ledger in every mode, with or without context management (context.md section 10, invariant 4). Never context.",+ "description": "`agent_events.content_json` of a `model_attempt` audit row (`TranscriptStore.append_audit(kind='attempt')`, `visibility = 'audit'`, no `context_seq`): a conversation attempt with usage or cache diagnostics that did not become a response row (retried, relieved, a usage-only terminal, refused at admission, or a failed commit), written by the attempt ledger in every mode, with or without context management (context.md section 10, invariant 4). Never context.","type": "object","required": ["version",- "usage","error"],+ "anyOf": [{"required": ["usage"]}, {"required": ["cache"]}],"additionalProperties": false,"properties": {"version": {"const": 1},+ "cache": {"$ref": "#/definitions/CacheObservation"},+ "cache_state": {"$ref": "#/definitions/CacheState"},"usage": {"$ref": "message.schema.json#/definitions/Usage"},diff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.mdindex c72e77fde..cf7825b6c 100644--- a/docs/plans/agent-core-contracts/transcript.md+++ b/docs/plans/agent-core-contracts/transcript.md@@ -34,11 +34,18 @@ an `output` that is not a committed response, queued or removed inputs, and theeither: `agent_events` with `visibility = 'audit'` and no `context_seq`, written by `append_audit`, as`fork_turn` (`ForkTurn`, C-10 `fork.md` §7: one side turn, such as a C-9 checkpoint, with its own attempts' partialsand usage) or-`model_attempt` (`ModelAttempt`: the usage of a conversation attempt that did not become a response row, C-9+`model_attempt` (`ModelAttempt`: the usage and/or optional cache diagnostics of a conversation attempt that did not become a response row, C-9`context.md` §10, invariant 4). The activity panel does not read them.## 2. Writing+Cache diagnostics are optional version-1 objects, outside canonical `Usage`:+`ModelResponse.cache`, `ModelAttempt.cache/cache_state`, and `ForkTurn.cache_attempts/cache_state`.+Old readers ignore them. Only usage-bearing records restore the request-start clock; two indexed latest-audit+lookups recover the per-route state without scanning history. Each persisted prefix holds at most 32 sampled+128-bit hash boundaries (including tools, system, and the exact final boundary), not copied prompt content.+Partial-prefix counts are estimates/lower bounds; a fully retained request uses its reported input count.+- Every store implements the whole `TranscriptStore` protocol (`harness/store.py`) with the same behavior: an appendreturns exactly the entry `load` reads back, `created_at` (epoch seconds) included; a response keeps C-9's requestfacts in `content_json.model.request`; a payload row needs a payload kind and version 1, and `append_payloads`diff --git a/docs/plans/cache-metrics-implementation.md b/docs/plans/cache-metrics-implementation.mdnew file mode 100644index 000000000..37a272502--- /dev/null+++ b/docs/plans/cache-metrics-implementation.md@@ -0,0 +1,16 @@+# Vibey cache metrics — implementation contract (Delivery plan PR 3b)++Owner: `system-prompt-cache-tiers.md`, Metrics. Base: merged PR #3117. Only Vibey's loop and its diagnostics; no prompt/behavior change for native backends, no migration, deployment, or cache-policy retuning.++## Invariants and boundaries++- Capture request admission time, assumed route lifetime, unchanged-prefix expectation and causal facts in the one model-attempt pipeline. Persist `cache` beside the response payload's request/message and on non-context attempt records; never duplicate billed usage. Record TTL writes as a decomposition of existing total writes, not extra tokens.+- Cache clocks are keyed by served provider/model and start time, distinct from the existing C-9 response-end clearing clock. A restart restores committed response facts and audited attempts. No metrics read or write blocks the controller loop.+- Persist only hashes and token estimates for prefix comparison, never a second copy of prompts, credentials, headers, or tool content. Whole unchanged requests use their previous reported input count; partial matches use the existing C-9 estimator and are explicitly marked estimates. Unknown usage/prices/TTL breakdowns remain unknown, never zero-priced facts. A provider TTL detail without its aggregate write total is retained as an incomplete diagnostic, not promoted to a complete billable total.+- `prompt.pending` records newly detected/revised components; `prompt.applied` records reason and each component's wait. Preserve the decision's exact tiers, revisions and deadline; previews neither emit events nor write state.+- A read-only `cache_requests` TEMP view exposes facts/classification, with a labeled timestamp inference for pre-metrics rows. Full-prefix misses can be classified as provider misses only when their basis is `reported_input`; partial-prefix misses remain `estimated_miss`. A CLI `vibe data cache` report groups by route/period: idle bands, class/cause/TTL writes, lifetime what-if costs, and tier freshness. Reads reuse guarded query access and local price data; no provider/network calls and no mutation of historical rows.+- New fields are optional at persisted boundaries; old rows load unchanged. Invalid optional diagnostics degrade to unknown without breaking a Turn. Query/report timestamps and price basis remain visible so estimates cannot be mistaken for historical bills.++## Acceptance++Tests at the accounting boundary cover warm/cold request starts (including a long response), route switches, retries, restart/fork, checkpoint and result-clearing causes, and TTL decompositions without double counting. Store contract tests cover optional cache round trips and indexed session-scoped audit recovery. Adapter tests cover prompt events/no-op previews. Isolated database/CLI tests cover every classification, timestamp-derived legacy rows, unknown rates, what-if arithmetic and freshness summaries. Existing C-9, wire conversion, snapshot, fork and shared-prompt tests guard intentional non-changes.diff --git a/docs/plans/system-prompt-cache-tiers.md b/docs/plans/system-prompt-cache-tiers.mdindex 6cd5f5a18..7fc730353 100644--- a/docs/plans/system-prompt-cache-tiers.md+++ b/docs/plans/system-prompt-cache-tiers.md@@ -283,28 +283,41 @@ The loop records a `cache` object beside `usage` on each Vibey response row:| Field | Meaning || --- | --- |-| `idle_s` | Seconds since the start of the previous request on the same provider and model (providers count lifetimes from the request start) |+| `idle_s` | Seconds since the start of the previous usage-bearing request on the same provider and model; a failed attempt with no usage cannot establish a populated cache || `lifetime_s` | The lifetime Avibe assumed for the route at that moment || `expected_read` | Tokens Avibe expected the provider to read: the prefix it left unchanged since that previous request, or 0 when the route is cold by the clock |-| `writes_by_ttl` | Write tokens by lifetime as the provider reports them (Anthropic 5 m and 1 h, OpenAI 30 m and 12 h) |-| `causes` | What Avibe changed in the prefix before this request: `prompt_applied` with its reason (`tier1`, `deadline`, `cold`, `route_change`, `checkpoint`, `session_start`), `tools_changed`, `tool_results_cleared`, `checkpoint`, `route_changed`, `fork_start` |--A query view classifies each request from these facts:--- **Active break**: Avibe changed the prefix (`causes` is not empty); the- missed tokens are charged to the cause.+| `writes_by_ttl` | Write tokens by lifetime as the provider reports them (Anthropic 5 m and 1 h, OpenAI 30 m and 12 h); unreported or contradictory portions stay in `unknown` and remain a lower-bound signal in valuation |+| `cache_write_basis` | `reported`, `unknown`, `incomplete_total`, `none`, or `timestamp_inferred`; this prevents a missing aggregate or legacy row from looking like a complete TTL bill |+| `causes` | What Avibe changed in the prefix before this request: `prompt_applied` with its reason (`tier1`, `deadline`, `cold`, `route_change`, `checkpoint`, `session_start`, `persistence_failure`), `tools_changed`, `tool_results_cleared`, `checkpoint`, `route_changed`, `fork_start` |++A query view classifies each request from these facts. The `cache` object is+optional and sits beside the canonical response `message`/`request`; TTL+breakdowns are not added to canonical `Usage`, so older releases can still read+these rows. A malformed optional cache object is treated as unknown rather than+making a response or report fail.++- **Unknown**: no usage was reported; a failed attempt is not a measured cache miss.+- **Active break**: Avibe changed the prefix and input tokens were missed; the+ missed tokens are charged to the cause. `fork_start` and `prompt_applied:session_start`+ are informational, not evidence of a broken prefix. A full hit remains a hit.- **Passive expiry**: nothing changed and `idle_s` exceeded the provider'slifetime.- **Provider miss**: nothing changed, the route was warm by the clock, and- the provider read less than `expected_read` (eviction, routing, overflow).--Each class carries its tokens and their cost at the route's rates. The-measurements in Background had to infer these classes from timestamps; with-the facts recorded, the inference becomes exact.+ the provider read less than `expected_read` when the basis is+ `reported_input`, beyond a tolerance of max(128 tokens, 1% of expected input)+ (eviction, routing, overflow). Partial-prefix expectations+ are classified separately as `estimated_miss` rather than blamed on the+ provider.++Each class carries its tokens and current-list valuation. Recorded request-start+timing supersedes legacy timestamp inference; estimated token boundaries and provider+retention assumptions remain estimates, not exact proof of a provider fault. Each+persisted prefix has at most 32 sampled 128-bit hash boundaries, retaining the exact+final boundary for whole-request reuse. Sampling can undercount partial-prefix reuse.### Per snapshot change: how current the context was-Two `agent_events` rows per Session:+Two `agent_events` types at snapshot transitions:- `prompt.pending`: a change first seen at a Turn start, with its componentsand tiers.@@ -318,8 +331,12 @@ Turns that ran with a pending notice.### Reports- A read-only `vibe data query` view of the per-request facts and their- classification, so any Agent can answer a new question directly, as the- measurements in this document were made.+ classification, so any Agent can answer a new question directly.+- `vibe data cache` is the supported summary entry point. It is read-only and+ requires the Member-level diagnostic access needed to read `agent_events`.+ It uses the cached local price table only; its USD figures are current+ standard-list valuations, not historical provider bills. Legacy rows are+ labeled timestamp-inferred, and what-if lifetimes are estimates.- A summary by route and period: hit rate; writes by class, cause, andlifetime; the idle-gap distribution (under 5 m, 5 to 30 m, 30 to 60 m, 1 to12 h, over 12 h) with the tokens at stake in each band; what each lifetimediff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 42729b6ea..4ab535ccd 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -1047,16 +1047,51 @@ class VibeyAgent(BaseAgent):if not self.prompt_snapshots.save(agent.session_id, decision.state, snapshot=decision.reason is not None):# Without a durable first-seen time, retaining a warm prefix could# reset a tier-2 deadline forever. Lose the optimization, not freshness.- return decide(None, candidate, now=now, route=decision.state.snapshot.route,- checkpoint_seq=decision.state.observed_checkpoint_seq, cold=False).state- return decision.state-- state = await to_thread_joined(prepare)+ failed = decision+ decision = decide(None, candidate, now=now, route=failed.state.snapshot.route,+ checkpoint_seq=failed.state.observed_checkpoint_seq, cold=False)+ decision = replace(decision, reason="persistence_failure", detected=failed.detected,+ applied=failed.applied or failed.state.pending)+ if persist and (decision.detected or decision.reason):+ self._record_prompt_events(request, agent.session_id, decision, now)+ return decision++ decision = await to_thread_joined(prepare)+ state = decision.state+ agent.cache_causes = (({"kind": "prompt_applied", "reason": decision.reason},) if decision.reason else ())+ agent.prompt_pending = bool(state.pending)+ agent.prompt_notice = state.notice != "current"agent.system = state.snapshot.prefix.systemagent.set_tools(frozen_tools(state.snapshot.prefix.tools, agent.tools))router.prefix_declarations = (route_identity(endpoint), state.snapshot.prefix.hosted)return state+ def _record_prompt_events(self, request: AgentRequest, session_id: str, decision, now: float) -> None:+ """Worker-only diagnostics: a failed metrics write cannot fail a Turn."""+ from dataclasses import asdict+ from storage import agent_events_service++ events = []+ if decision.detected:+ events.append(("prompt.pending", {"components": [asdict(item) for item in decision.detected]}))+ if decision.reason:+ events.append(("prompt.applied", {+ "reason": decision.reason,+ "components": [{**asdict(item), "wait_s": max(0, now - item.pending_since)} for item in decision.applied],+ }))+ try:+ with self._engine.begin() as conn:+ scope_id = conn.execute(select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)).scalar()+ for event_type, data in events:+ agent_events_service.append(+ conn, scope_id=scope_id, session_id=session_id, platform=request.context.platform or "avibe",+ event_type=event_type, content={"version": 1, "at": now, **data}, visibility="trace",+ backend=BACKEND, agent_name=request.vibe_agent_name,+ turn_id=(request.context.platform_specific or {}).get("turn_token"),+ )+ except Exception:+ logger.warning("Could not record optional prompt metrics for Session %s", session_id)+async def preview_request(self, session_id: str, request: AgentRequest, *, context_seq: int | None = None,) -> RequestPreview:diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.pyindex babf292b2..72d47da13 100644--- a/modules/agents/vibey/store.py+++ b/modules/agents/vibey/store.py@@ -128,6 +128,9 @@ class AdapterTranscriptStore:"""Small response facts; only legacy rows need their canonical body decoded."""return await self._store.load_turn_response_metadata(session_id, turn_id)+ async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping[str, Any]]:+ return await self._store.load_cache_attempts(session_id)+async def consume_input(self, session_id: str, message_id: str, message: UserMessage) -> ContextEntry:await self._await_input_row(session_id, message_id)previous = self._env_state.get(session_id)@@ -153,6 +156,7 @@ class AdapterTranscriptStore:*,final: bool,request: Optional[Mapping[str, Any]] = None,+ cache: Optional[Mapping[str, Any]] = None,replied: Optional[bool] = None,images: Sequence[HostedImage] = (),superseded: bool = False,@@ -162,6 +166,7 @@ class AdapterTranscriptStore:message,final=final,request=request,+ cache=cache,replied=replied,images=images,superseded=superseded,diff --git a/storage/agent_transcript.py b/storage/agent_transcript.pyindex 5d48afe1e..f76bcfa97 100644--- a/storage/agent_transcript.py+++ b/storage/agent_transcript.py@@ -123,6 +123,14 @@ _AUDIT_EVENT_TYPE: dict[str, str] = {"attempt": "model_attempt", "fork_turn": "fCONTEXT_WRITER = "vibey"PAYLOAD_VERSION = 1+# Two bounded index seeks recover all route clocks; no per-Turn audit-history scan.+CACHE_ATTEMPTS_SQL = """+SELECT CASE WHEN json_valid(content_json) THEN json_extract(content_json, '$.cache_state') END+FROM agent_events+WHERE session_id = :session_id AND event_type = :event_type+ORDER BY created_at DESC, id DESC LIMIT 1+"""+PayloadKind = Literal["compaction", "context_edit", "agent_state", "replay_refusal"]_EVENT_TYPE_BY_KIND: dict[str, str] = {"tool_result": "tool_result",@@ -306,6 +314,25 @@ class SQLiteTranscriptStore:return await self._write(session_id, work)+ async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping[str, Any]]:+ """Read only optional diagnostics, by the existing Session index and on a worker."""+ from core.agent_core.harness.cache_metrics import CacheTracker++ def read():+ tracker = CacheTracker()+ with self._engine.connect() as conn:+ for event_type in ("model_attempt", "fork_turn"):+ raw = conn.execute(text(CACHE_ATTEMPTS_SQL), {"session_id": session_id, "event_type": event_type}).scalar()+ try:+ records = json.loads(raw) if raw else []+ if isinstance(records, list):+ tracker.restore((), records)+ except (ValueError, TypeError):+ continue+ return list(tracker.latest.values())++ return await asyncio.to_thread(read)+async def append_response(self,session_id: str,@@ -313,6 +340,7 @@ class SQLiteTranscriptStore:*,final: bool,request: Optional[Mapping[str, Any]] = None,+ cache: Optional[Mapping[str, Any]] = None,replied: Optional[bool] = None,images: Sequence[HostedImage] = (),superseded: bool = False,@@ -327,6 +355,8 @@ class SQLiteTranscriptStore:response: dict[str, Any] = {"version": PAYLOAD_VERSION, "message": message_to_dict(stored_message)}if request is not None:response["request"] = dict(request) # C-9 ``ModelResponse.request``: the anchor's request facts+ if cache is not None:+ response["cache"] = dict(cache)model = _canonical(response, "response")if replied is None:replied = has_reply(stored_message)diff --git a/storage/cache_metrics.py b/storage/cache_metrics.pynew file mode 100644index 000000000..d46c007f9--- /dev/null+++ b/storage/cache_metrics.py@@ -0,0 +1,238 @@+"""Read-only cache diagnostic views and safe normalization of optional facts.++These are connection-local views, not persisted schema. Legacy timings use+response timestamps and current lifetime assumptions, explicitly labeled inferred.+"""++from __future__ import annotations++import json+import math+from typing import Any+++def object_value(raw: Any) -> dict[str, Any]:+ try:+ value = json.loads(raw) if isinstance(raw, str) else raw+ except (TypeError, ValueError, RecursionError):+ return {}+ return value if isinstance(value, dict) else {}+++def count(value: Any) -> int:+ return value if type(value) is int and value >= 0 else 0+++def seconds(value: Any) -> float | None:+ if type(value) not in (int, float):+ return None+ try:+ value = float(value)+ except (OverflowError, ValueError):+ return None+ return value if math.isfinite(value) and value >= 0 else None+++def legacy_lifetime(provider: Any, protocol: Any, model: Any) -> float:+ """Best-effort current route lifetime for a row without request-start cache facts."""+ try:+ from core.agent_core.ai.provider import ModelEndpoint+ from core.agent_core.harness.context import cache_ttl_s++ endpoint = ModelEndpoint(+ str(protocol or ""), "http://diagnostic.invalid", str(model or ""), "",+ provider=str(provider or ""),+ )+ return cache_ttl_s(endpoint)+ except Exception: # noqa: BLE001 - damaged legacy rows are diagnostic unknowns, not query failures+ return 3600.0+++def observation(+ cache_raw: Any,+ usage_raw: Any,+ provider: Any,+ protocol: Any,+ model: Any,+ started_raw: Any,+ previous_started_raw: Any,+ previous_input_raw: Any,+) -> str:+ """Normalize one row into JSON so SQLite can expose stable scalar columns."""+ cache = object_value(cache_raw)+ usage = object_value(usage_raw)+ cache_started = seconds(cache.get("started_at"))+ observed = (+ cache.get("version") == 1+ and cache_started is not None+ and seconds(cache.get("lifetime_s")) is not None+ )+ started = cache_started if observed else seconds(started_raw)+ previous_started = seconds(previous_started_raw)+ idle = seconds(cache.get("idle_s")) if observed else (+ max(0.0, started - previous_started)+ if started is not None and previous_started is not None+ else None+ )+ lifetime = seconds(cache.get("lifetime_s")) if observed else legacy_lifetime(provider, protocol, model)+ reusable = count(cache.get("reusable_tokens")) if observed else count(previous_input_raw)+ expected = count(cache.get("expected_read")) if observed else (+ reusable if idle is not None and idle <= lifetime else 0+ )+ read = count(usage.get("cache_read_tokens"))+ writes = count(usage.get("cache_write_tokens"))+ fresh = count(usage.get("input_tokens"))+ total = fresh + read + writes+ causes = cache.get("causes", []) if observed else []+ if not isinstance(causes, list):+ causes = []+ causes = [{"kind": item["kind"], **({"reason": item["reason"]} if isinstance(item.get("reason"), str) else {})}+ for item in causes if isinstance(item, dict) and isinstance(item.get("kind"), str)]+ active = [item for item in causes if item["kind"] != "fork_start"+ and not (item["kind"] == "prompt_applied" and item.get("reason") == "session_start")]+ previous_input = count(cache.get("previous_input_tokens")) if observed else count(previous_input_raw)+ missed = max(0, min(previous_input, total) - read)+ tolerance = max(128, expected // 100)++ if not usage:+ classification = "unknown"+ elif active and missed > 0:+ classification = "active_break"+ elif read and missed == 0:+ classification = "hit"+ elif idle is not None and idle > lifetime:+ classification = "passive_expiry"+ elif expected - read > tolerance and cache.get("expected_read_basis") == "reported_input":+ classification = "provider_miss"+ elif expected > read and cache.get("expected_read_basis") != "reported_input":+ classification = "estimated_miss"+ elif read:+ classification = "hit"+ else:+ classification = "cold_start" if idle is None else "uncached"++ ttl_raw = cache.get("writes_by_ttl") if observed else None+ ttl = {+ key: value+ for key, value in (ttl_raw.items() if isinstance(ttl_raw, dict) else ())+ if key in {"5m", "1h", "30m", "12h"} and type(value) is int and value >= 0+ }+ incomplete = observed and cache.get("cache_write_basis") == "incomplete_total"+ if not incomplete and sum(ttl.values()) > writes:+ ttl = {}+ known_writes = sum(ttl.values())+ if writes > known_writes:+ ttl["unknown"] = writes - known_writes++ reusable_static = count(cache.get("reusable_static_tokens")) if observed else 0+ payload = {+ "idle_s": idle,+ "lifetime_s": lifetime,+ "expected_read": expected,+ "expected_read_basis": cache.get("expected_read_basis", "unknown") if observed else "timestamp_inferred",+ "data_basis": "observed" if observed else "timestamp_inferred",+ "classification": classification,+ "reusable_tokens": reusable,+ "reusable_static_tokens": reusable_static,+ "static_tokens": count(cache.get("static_tokens")) if observed else 0,+ "previous_input_tokens": previous_input,+ "missed_prefix_tokens": missed,+ "writes_by_ttl": ttl,+ "cache_write_basis": cache.get("cache_write_basis", "unknown") if observed else "timestamp_inferred",+ "causes": causes,+ "prompt_pending": bool(cache.get("prompt_pending")) if observed else False,+ "prompt_notice": bool(cache.get("prompt_notice")) if observed else False,+ "token_reported": bool(usage),+ "fresh_input_tokens": fresh,+ "cache_read_tokens": read,+ "cache_write_tokens": writes,+ "input_tokens": total,+ "output_tokens": count(usage.get("output_tokens")),+ }+ return json.dumps(payload, separators=(",", ":"), allow_nan=False)+++# Keep malformed optional JSON as empty objects. json_extract on a scalar string+# would otherwise feed non-JSON text into a second json_extract and abort a report.+_MODEL = (+ "CASE WHEN json_valid(m.content_json) AND json_type(m.content_json, '$.model') = 'object' "+ "THEN json_extract(m.content_json, '$.model') ELSE '{}' END"+)+_EVENT = (+ "CASE WHEN json_valid(a.content_json) AND json_type(a.content_json) = 'object' "+ "THEN a.content_json ELSE '{}' END"+)++_FIELDS = (+ "idle_s", "lifetime_s", "expected_read", "expected_read_basis", "data_basis", "classification",+ "reusable_tokens", "reusable_static_tokens", "static_tokens", "previous_input_tokens", "missed_prefix_tokens",+ "writes_by_ttl", "cache_write_basis", "causes", "prompt_pending", "prompt_notice", "token_reported", "fresh_input_tokens",+ "cache_read_tokens", "cache_write_tokens", "input_tokens", "output_tokens",+)++CACHE_VIEWS = {+ "_cache_rows": f"""+ SELECT m.id AS request_id, m.session_id,+ CASE WHEN json_valid(m.metadata_json) AND json_type(m.metadata_json) = 'object'+ THEN json_extract(m.metadata_json, '$.turn_id') END AS turn_id,+ m.created_at AS at,+ CASE WHEN json_type({_MODEL}, '$.cache') = 'object' THEN json_extract({_MODEL}, '$.cache') ELSE '{{}}' END AS cache,+ CASE WHEN json_type({_MODEL}, '$.message.usage') = 'object' THEN json_extract({_MODEL}, '$.message.usage') ELSE '{{}}' END AS usage,+ json_extract({_MODEL}, '$.message.origin.provider') AS provider,+ json_extract({_MODEL}, '$.message.origin.api') AS protocol,+ json_extract({_MODEL}, '$.message.origin.model') AS model,+ 'conversation' AS purpose+ FROM messages m+ WHERE m.context_seq IS NOT NULL+ AND m.author = 'agent' AND m.type IN ('assistant', 'output', 'result', 'error')+ UNION ALL+ SELECT a.id, a.session_id, a.turn_id, a.created_at,+ CASE WHEN json_type({_EVENT}, '$.cache') = 'object' THEN json_extract({_EVENT}, '$.cache') ELSE '{{}}' END,+ CASE WHEN json_type({_EVENT}, '$.usage') = 'object' THEN json_extract({_EVENT}, '$.usage') ELSE '{{}}' END,+ json_extract({_EVENT}, '$.cache.provider'), json_extract({_EVENT}, '$.cache.protocol'),+ json_extract({_EVENT}, '$.cache.model'), 'attempt'+ FROM agent_events a+ WHERE a.visibility = 'audit' AND a.event_type = 'model_attempt'+ AND json_type({_EVENT}, '$.cache') = 'object'+ UNION ALL+ SELECT a.id || ':' || j.key, a.session_id, a.turn_id, a.created_at,+ CASE WHEN json_type(j.value, '$.cache') = 'object' THEN json_extract(j.value, '$.cache') ELSE '{{}}' END,+ CASE WHEN json_type(j.value, '$.usage') = 'object' THEN json_extract(j.value, '$.usage') ELSE '{{}}' END,+ json_extract(j.value, '$.cache.provider'), json_extract(j.value, '$.cache.protocol'),+ json_extract(j.value, '$.cache.model'), 'fork_turn'+ FROM agent_events a,+ json_each(CASE WHEN json_type({_EVENT}, '$.cache_attempts') = 'array'+ THEN json_extract({_EVENT}, '$.cache_attempts') ELSE '[]' END) AS j+ WHERE a.visibility = 'audit' AND a.event_type = 'fork_turn' AND j.type = 'object'+ """,+ "cache_requests": """+ WITH timed AS (+ SELECT *,+ coalesce(json_extract(cache, '$.started_at'),+ (julianday(at) - 2440587.5) * 86400) AS started_at,+ coalesce(json_extract(usage, '$.input_tokens'), 0)+ + coalesce(json_extract(usage, '$.cache_read_tokens'), 0)+ + coalesce(json_extract(usage, '$.cache_write_tokens'), 0) AS total_input+ FROM _cache_rows+ ), compared AS (+ SELECT *,+ lag(started_at) OVER history AS previous_started,+ lag(total_input) OVER history AS previous_input+ FROM timed+ WINDOW history AS (PARTITION BY session_id, provider, model ORDER BY started_at, request_id)+ ), normalized AS (+ SELECT *, cache_observation(+ cache, usage, provider, protocol, model, started_at, previous_started, previous_input+ ) AS facts+ FROM compared+ )+ SELECT request_id, session_id, turn_id, at, started_at, provider, protocol, model, purpose,+ json_extract(cache, '$.source_id') AS source_id,+ """ + ", ".join(f"json_extract(facts, '$.{field}') AS {field}" for field in _FIELDS) + """,+ cache_valuation(model, usage, json_extract(facts, '$.writes_by_ttl'), json_extract(facts, '$.cache_write_basis')) AS valuation+ FROM normalized+ """,+}++# Explicit name used by read_only_query's connection-local UDF registration.+cache_observation = observationdiff --git a/storage/read_only_query.py b/storage/read_only_query.pyindex 5fde72257..a912762b7 100644--- a/storage/read_only_query.py+++ b/storage/read_only_query.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport difflibimport functools+import jsonimport reimport sqlite3from dataclasses import dataclass@@ -10,6 +11,7 @@ from typing import Anyfrom urllib.parse import quotefrom config import paths+from storage.cache_metrics import CACHE_VIEWS, cache_observationfrom storage.importer import ensure_sqlite_state, resolve_primary_platform_from_configfrom storage.models import MESSAGE_TURN_ID_SQLfrom storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one@@ -105,6 +107,7 @@ RECALL_VIEWS = {"WHERE text IS NOT NULL"),}+RECALL_VIEWS.update(CACHE_VIEWS)EXCERPT_DEFAULT_WIDTH = 300@@ -157,6 +160,8 @@ def _regexp(pattern: Any, value: Any) -> int | None:_FUNCTION_HINTS = {"excerpt": "Call excerpt(text, 'term') or excerpt(text, 'term', width).","regexp": "REGEXP takes a Python regular expression; add (?i) to ignore case.",+ "cache_observation": "The cache diagnostic views own this function; query cache_requests rather than calling it directly.",+ "cache_valuation": "The cache diagnostic views own this function; query cache_requests rather than calling it directly.",}@@ -216,6 +221,18 @@ def run_read_only_query(try:conn.create_function("excerpt", -1, reporting("excerpt", _excerpt), deterministic=True)conn.create_function("regexp", 2, reporting("regexp", _regexp), deterministic=True)+ conn.create_function("cache_observation", 8, reporting("cache_observation", cache_observation), deterministic=True)+ price_table = None++ def cache_valuation(model, usage, writes, write_basis):+ nonlocal price_table+ from core.handlers.cache_metrics import cached_prices, valuation++ if price_table is None:+ price_table = cached_prices(resolved_db_path.parent)+ return json.dumps(valuation(model, usage, writes, price_table, str(write_basis or "unknown")), separators=(",", ":"))++ conn.create_function("cache_valuation", 4, reporting("cache_valuation", cache_valuation))# TEMP objects live in this connection only, so a read-only database still# takes them; they must exist before query_only and the authorizer forbid it.for name, select in RECALL_VIEWS.items():@@ -351,6 +368,8 @@ def _unknown_column_hint(schema: dict[str, list[str]], statement: str, referencereferenced = [aliases[qualifier]]referenced = list(dict.fromkeys(referenced))owners = [table for table, columns in schema.items() if column in columns]+ preferred = {name: index for index, name in enumerate(("transcript", "turns", "agent_events"))}+ owners.sort(key=lambda name: (preferred.get(name, len(preferred)), name))parts = []if referenced:parts.append(f"No column '{column}' on {', '.join(referenced)}.")diff --git a/tests/agent_core/agent/test_cache_metrics.py b/tests/agent_core/agent/test_cache_metrics.pynew file mode 100644index 000000000..b0a862021--- /dev/null+++ b/tests/agent_core/agent/test_cache_metrics.py@@ -0,0 +1,194 @@+"""Cache facts at their owning boundary: request admission, not response commit.++The previous C-9 clock alone cannot explain expiry after a long response, and+nothing before PR3b preserves prefix comparisons or TTL write decompositions.+"""++from dataclasses import replace++import pytest++from core.agent_core.ai.anthropic import _anthropic_usage+from core.agent_core.ai.openai_responses import _responses_usage+from core.agent_core.ai.provider import Done, ModelRequest, ProviderError+from core.agent_core.agent.loop import RetryPolicy+from core.agent_core.harness.cache_metrics import CacheTracker+from core.agent_core.harness.context import ContextConfig, cache_cold+from core.agent_core.harness.store import ContextEntry+from core.agent_core.messages import Usage, usage_from_dict, usage_to_dict+from core.agent_core.tools.base import ToolSpec+from tests.agent_core.agent.test_compaction import Model, make_agent, run+from tests.agent_core.fakes import ENDPOINT, InMemoryTranscriptStore, assistant, user+++def request():+ return ModelRequest(endpoint=ENDPOINT, system="fixed instructions", tools=(ToolSpec("read", "Read", {}),),+ messages=(user("hello"),), max_tokens=100)+++async def test_request_start_clock_survives_restart_without_changing_the_c9_response_end_clock():+ now = [100.0]+ store = InMemoryTranscriptStore(clock=lambda: now[0])++ def long_response(_):+ now[0] = 500.0+ return [Done(replace(assistant(), usage=Usage(input_tokens=100, output_tokens=10)))]++ model = Model(conversation=[long_response, [Done(replace(assistant(), usage=Usage(cache_write_tokens=100)))]],+ checkpoint=[])+ config = ContextConfig(clock=lambda: now[0])+ await run(make_agent(model, store=store, context=config, system="fixed instructions"), row="first")+ first = next(row for row in store.rows["session"] if row.kind == "response")+ assert first.payload["cache"]["started_at"] == 100+ now[0] = 510.0+ assert not cache_cold(model.requests[0], store.rows["session"], now=now[0])+ await run(make_agent(model, store=store, context=config, system="fixed instructions"), row="after-restart")+ cache = [row.payload["cache"] for row in store.rows["session"] if row.kind == "response"][-1]+ assert cache["idle_s"] == 410+ assert cache["lifetime_s"] == 300+ assert cache["expected_read"] == 0+ assert cache["reusable_tokens"] == 100+ assert cache["expected_read_basis"] == "expired"+ assert cache["writes_by_ttl"] == {"unknown": 100}++[email protected]("change,cause", [+ ("none", None), ("tools", "tools_changed"), ("route", "route_changed"),+ ("context_edit", "tool_results_cleared"), ("compaction", "checkpoint"),+])+def test_fingerprints_and_context_facts_explain_active_changes(change, cause):+ tracker = CacheTracker()+ original = request()+ first = tracker.begin(original, (), now=100)+ tracker.finish(first, replace(assistant(), usage=Usage(input_tokens=100)))+ candidate, rows = original, []+ if change == "tools":+ candidate = replace(original, tools=())+ elif change == "route":+ candidate = replace(original, endpoint=replace(ENDPOINT, source_id="new-source"))+ elif cause:+ rows = [ContextEntry("session", 1, change, "change", payload={})]+ after = tracker.begin(candidate, rows, now=101)+ assert {item["kind"] for item in after["causes"]} == ({cause} if cause else set())+ if change == "none":+ assert after["expected_read"] == 100 and after["expected_read_basis"] == "reported_input"+ if change in {"tools", "route"}:+ assert after["expected_read"] == 0+ # A different provider/model's most recent request must not explain this route.+ if change == "none":+ other = replace(original, endpoint=replace(original.endpoint, model_id="other-model"))+ other_start = tracker.begin(other, (), now=102)+ other_origin = replace(assistant().origin, model="other-model")+ tracker.finish(other_start, replace(assistant(), origin=other_origin, usage=Usage(input_tokens=100)))+ same_route = tracker.begin(original, (), now=103)+ assert {item["kind"] for item in same_route["causes"]} == set()+ # Fingerprints contain no prompt or tool text.+ assert all("fixed instructions" not in part[0] for part in after["prefix"])+++def test_ttl_details_are_transient_usage_metadata_and_have_one_persisted_source_of_truth():+ initial = _anthropic_usage({"input_tokens": 10, "cache_creation_input_tokens": 15,+ "cache_creation": {"ephemeral_5m_input_tokens": 5, "ephemeral_1h_input_tokens": 10}})+ later = _anthropic_usage({"output_tokens": 3}, current=initial)+ assert later.cache_writes_by_ttl == {"5m": 5, "1h": 10}+ assert later.cache_write_tokens == 15+ canonical = usage_to_dict(later)+ assert canonical == {"input_tokens": 10, "output_tokens": 3, "cache_read_tokens": 0, "cache_write_tokens": 15}+ assert usage_from_dict(canonical).cache_writes_by_ttl is None+ tracker = CacheTracker()+ cache = tracker.begin(request(), (), now=100)+ tracker.finish(cache, replace(assistant(), usage=later))+ assert cache["writes_by_ttl"] == {"5m": 5, "1h": 10}++[email protected]("details,expected", [+ ({"ttl_30m_tokens": 10, "ttl_12h_tokens": 20}, {"30m": 10, "12h": 20}),+ ({"ttl_30m_tokens": 10}, {"30m": 10}),+ ({"ttl_30m_tokens": 10, "ttl_12h_tokens": 20, "future_ttl_tokens": 1}, {"30m": 10, "12h": 20}),+ ({"ttl_30m_tokens": 100}, None),+ ({"ttl_12h_tokens": "invalid"}, None),+ ([], None),+])+def test_bad_or_incomplete_optional_ttl_details_do_not_invent_counts(details, expected):+ usage = _responses_usage({"input_tokens": 100, "input_tokens_details": {+ "cached_tokens": 50, "cache_write_tokens": 30, "cache_write_tokens_details": details,+ }})+ assert usage.cache_writes_by_ttl == expected+ assert (usage.input_tokens, usage.cache_read_tokens, usage.cache_write_tokens) == (20, 50, 30)+++def test_missing_openai_write_total_is_marked_incomplete_even_when_ttl_details_are_valid():+ usage = _responses_usage({"input_tokens": 100, "input_tokens_details": {+ "cached_tokens": 50,+ "cache_write_tokens_details": {"ttl_30m_tokens": 10, "ttl_12h_tokens": 20},+ }})+ assert usage.cache_write_tokens == 0+ assert usage.input_tokens == 50+ assert usage.cache_writes_by_ttl == {"30m": 10, "12h": 20}+ assert usage.cache_write_total_reported is False+ assert usage_to_dict(usage)["cache_write_tokens"] == 0+ tracker = CacheTracker()+ cache = tracker.begin(request(), (), now=100)+ tracker.finish(cache, replace(assistant(), usage=usage))+ assert cache["writes_by_ttl"] == {"30m": 10, "12h": 20}+ assert cache["cache_write_basis"] == "incomplete_total"+++def test_missing_openai_write_total_with_partial_details_does_not_fail_the_response():+ usage = _responses_usage({"input_tokens": 100, "input_tokens_details": {+ "cached_tokens": 50, "cache_write_tokens_details": {"ttl_30m_tokens": 10},+ }})+ assert usage.input_tokens == 50+ assert usage.cache_write_tokens == 0+ assert usage.cache_write_total_reported is False+++def test_corrupt_optional_clock_is_ignored():+ tracker = CacheTracker()+ for bad in (None, [], {}, {"version": 1, "started_at": 10**400}):+ tracker.restore((), (bad,))+ assert tracker.begin(request(), (), now=100)["idle_s"] is None+++def test_sampled_prefix_is_bounded_but_keeps_exact_reuse_and_fork_clock():+ # Long histories used to append every message hash to every response row.+ tracker = CacheTracker()+ original = replace(request(), messages=tuple(user(f"message {i}") for i in range(600)))+ first = tracker.begin(original, (), now=100)+ tracker.finish(first, replace(assistant(), usage=Usage(input_tokens=10000)))+ assert len(first["prefix"]) <= 32+ assert len(__import__("json").dumps(first["prefix"])) < 2000+ restored = CacheTracker()+ restored.restore((ContextEntry("parent", 1, "response", "row", payload={"cache": first}),), ())+ following = replace(original, messages=(*original.messages, user("new tail")))+ warm = restored.begin(following, (), now=150, fork=True)+ assert warm["idle_s"] == 50+ assert warm["expected_read"] == 10000+ assert warm["expected_read_basis"] == "reported_input"+ assert warm["causes"] == [{"kind": "fork_start"}]+ changed = replace(original, messages=(*original.messages[:300], user("changed"), *original.messages[301:]))+ partial = restored.begin(changed, (), now=151)+ assert 0 < partial["expected_read"] < 10000+ assert partial["expected_read_basis"] == "estimated_prefix"+++async def test_usage_less_retry_preserves_expiry_and_prompt_cause_until_a_billed_request():+ # Audit-only failures used to refresh the clock and consume the pending reason.+ now = [100.0]+ store = InMemoryTranscriptStore(clock=lambda: now[0])+ model = Model(conversation=[+ [Done(replace(assistant(), usage=Usage(input_tokens=2000)))],+ [ProviderError("rate_limit", "busy", True, status=429)],+ [Done(replace(assistant(), usage=Usage(cache_write_tokens=2000)))],+ ])+ context = ContextConfig(clock=lambda: now[0])+ await run(make_agent(model, store=store, context=context), row="initial")+ now[0] = 500+ restarted = make_agent(model, store=store, context=context, retry=RetryPolicy(initial_delay_s=0))+ restarted.cache_causes = ({"kind": "prompt_applied", "reason": "tier1"},)+ await run(restarted, row="retry")+ cache = [row.payload["cache"] for row in store.rows["session"] if row.kind == "response"][-1]+ assert cache["idle_s"] == 400+ assert cache["expected_read_basis"] == "expired"+ assert {item["reason"] for item in cache["causes"] if item["kind"] == "prompt_applied"} == {"tier1"}+ assert restarted.cache_causes == ()diff --git a/tests/agent_core/fakes.py b/tests/agent_core/fakes.pyindex d865c5fd4..e092d09ff 100644--- a/tests/agent_core/fakes.py+++ b/tests/agent_core/fakes.py@@ -137,6 +137,15 @@ class InMemoryTranscriptStore:prefix = [row for row in await self.load(anchor.session_id) if row.context_seq <= anchor.context_seq]return deepcopy(prefix + self.rows.get(session_id, []))+ async def load_cache_attempts(self, session_id: str) -> Sequence[Mapping]:+ from core.agent_core.harness.cache_metrics import CacheTracker++ tracker = CacheTracker()+ for records in (self.attempts, self.audits):+ payload = next((payload for owner, _, payload in reversed(records) if owner == session_id), {})+ tracker.restore((), payload.get("cache_state", []))+ return deepcopy(list(tracker.latest.values()))+def _entries(self, session_id, items) -> list[ContextEntry]:"""Rows for ``(kind, message, payload, row_id)`` items, numbered after the Session's context."""entries = self.rows.get(session_id, [])@@ -166,9 +175,11 @@ class InMemoryTranscriptStore:return (await self._append(session_id, [("input", message, {}, message_id)]))[0]async def append_response(- self, session_id, message: AssistantMessage, *, final: bool, request=None, replied=None, images=(), superseded=False+ self, session_id, message: AssistantMessage, *, final: bool, request=None, cache=None, replied=None, images=(), superseded=False) -> ContextEntry:payload = {"request": dict(request)} if request is not None else {}+ if cache is not None:+ payload["cache"] = dict(cache)row = (await self._append(session_id, [("response", message, payload, None)]))[0]self.final[row.row_id] = finalreturn rowdiff --git a/tests/test_cache_metrics_report.py b/tests/test_cache_metrics_report.pynew file mode 100644index 000000000..4cca09f09--- /dev/null+++ b/tests/test_cache_metrics_report.py@@ -0,0 +1,120 @@+"""Owning report tests: monetary estimates must preserve uncertainty and never fetch prices."""++from datetime import datetime, timezone+import json+import sqlite3++import pytest++from core.handlers.cache_metrics import lifetime_cost, summarize, valuation+from core.handlers.model_hub.pricing import PriceTable+from tests.test_cache_metrics_storage import _response, _session, state_db # noqa: F401+from vibe import cli+++def prices():+ return PriceTable(catalog={}, vendor_map={}, price_table_date=None, overrides={"models": {+ "claude-test": {"input": 1, "output": 5, "cache_read": .1, "cache_write": 1.25},+ "claude-alias": {"alias": "claude-test"},+ }})+++def row(**values):+ return {"session_id": "ses-cache", "request_id": "r", "turn_id": "t", "purpose": "conversation",+ "provider": "anthropic", "protocol": "anthropic", "model": "claude-test", "source_id": "src",+ "token_reported": True, "data_basis": "observed", "classification": "cold_start", "causes": "[]",+ "input_tokens": 1000, "fresh_input_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 1000,+ "output_tokens": 0, "writes_by_ttl": '{"5m":800,"1h":200}', "cache_write_basis": "reported",+ "static_tokens": 200, "reusable_tokens": 1000, "reusable_static_tokens": 200, "idle_s": None,+ **values}++[email protected]("classification,idle,read,write,label,lifetime,cost,recovered,expired", [+ ("cold_start", None, 0, 1000, "5m", 300, .0014, 0, 0),+ ("cold_start", None, 0, 1000, "1h", 3600, .002, 0, 0),+ ("passive_expiry", 600, 0, 1000, "1h", 3600, .0001, 1000, 0),+ ("active_break", 600, 0, 1000, "1h", 3600, .002, 0, 0),+ ("provider_miss", 60, 0, 1000, "1h", 3600, .002, 0, 0),+ ("hit", 300, 1000, 0, "5m", 300, .0001, 0, 0),+ ("hit", 600, 1000, 0, "5m", 300, .00102, 0, 800),+])+def test_lifetime_cost_reprices_all_writes_keeps_static_at_one_hour_and_recovers_only_expiry(+ prices, classification, idle, read, write, label, lifetime, cost, recovered, expired,+):+ result = lifetime_cost([row(classification=classification, idle_s=idle, cache_read_tokens=read,+ cache_write_tokens=write)], label=label, lifetime=lifetime, prices=prices)+ assert result["input_cost_usd"] == pytest.approx(cost)+ assert result["recovered_tokens"] == recovered+ assert result["newly_expired_tokens"] == expired+ assert result["estimated"] is True++[email protected]("changes", [+ {"writes_by_ttl": '{"unknown":1000}'}, {"cache_write_basis": "incomplete_total"},+ {"token_reported": False}, {"model": "unlisted"},+])+def test_unknown_counts_prices_and_lifetimes_are_not_assigned_candidate_costs(prices, changes):+ result = lifetime_cost([row(**changes)], label="1h", lifetime=3600, prices=prices)+ assert result["input_cost_usd"] is None+ assert result["incomplete_requests"] == 1+ assert result["excluded_input_tokens"] == 1000+++def test_valuation_exposes_real_alias_and_rate_provenance_without_inventing_legacy_write_loss(prices):+ result = valuation("claude-alias", {"input_tokens": 1000}, {}, prices, "timestamp_inferred")+ assert result["usd"] == .001+ assert result["lower_bound"] is False+ assert result["price_key"] == "claude-test"+ assert result["rate_sources"]["cache_read"] == "listed"+ assert result["rate_sources"]["cache_write_1h"] == "default"+ assert result["rate_multipliers"]["cache_write_1h"] == 2+ assert valuation("unlisted", {"input_tokens": 1000}, {}, prices)["usd"] is None+ assert valuation("claude-test", {}, {}, prices)["usd"] is None+++def test_freshness_summarizes_per_turn_waits_and_ignores_damaged_optional_components(prices):+ events = [{"session_id": "ses-cache", "event_type": "prompt.applied", "created_at": "2026-10-01T01:00:00Z",+ "content_json": json.dumps({"reason": "deadline", "components": components})}+ for components in (None, 1, [{"tier": 2, "wait_s": 1800}], [{"tier": 2, "wait_s": 2000}])]+ result = summarize([row(prompt_notice=True), row(request_id="r2", prompt_notice=True)], events, prices)+ freshness = result["freshness"]+ assert freshness["turns"] == freshness["turns_with_pending_notice"] == 1+ assert freshness["tiers"]["2"] == {"applied_components": 2, "median_s": 1800, "p90_s": 2000, "max_s": 2000}+ assert result["routes"][0]["valuation"]["price_key"] == "claude-test"+++def test_cache_cli_end_to_end_is_read_only_offline_and_honors_time_and_session_filters(state_db, monkeypatch, capsys):+ from vibe import models_dev_catalog++ def denied(*args, **kwargs):+ raise AssertionError("read-only report attempted a network refresh")++ monkeypatch.setattr(models_dev_catalog, "_refresh_in_background", denied)+ state_db.with_name("model_hub_prices.json").write_text(json.dumps({"models": {+ "claude-test": {"input": 1, "output": 5, "cache_read": .1, "cache_write": 1.25},+ }}))+ start = datetime(2026, 10, 1, tzinfo=timezone.utc).timestamp()+ cache = {"version": 1, "started_at": start, "lifetime_s": 300, "idle_s": 600,+ "previous_input_tokens": 1000, "expected_read": 0, "reusable_tokens": 1000,+ "reusable_static_tokens": 200, "static_tokens": 200,+ "causes": [], "writes_by_ttl": {"5m": 800, "1h": 200}, "cache_write_basis": "reported"}+ with sqlite3.connect(state_db) as conn:+ _session(conn)+ _session(conn, "excluded")+ for i, (session, at) in enumerate((("ses-cache", "2026-10-01T00:00:01Z"),+ ("ses-cache", "2026-09-01T00:00:01Z"),+ ("excluded", "2026-10-01T00:00:01Z"))):+ _response(conn, str(i), at, session_id=session, context_seq=i + 1,+ cache=cache if i != 1 else None, usage={"cache_write_tokens": 1000})+ conn.commit()+ before = state_db.read_bytes()+ args = cli.build_parser().parse_args(["data", "cache", "--since", "2026-10-01T00:00:00Z",+ "--until", "2026-10-02T00:00:00Z", "--session-id", "ses-cache"])+ assert cli.cmd_data_cache(args) == 0+ result = json.loads(capsys.readouterr().out)+ assert result["kind"] == "data_cache" and result["requests"] == 1+ route = result["routes"][0]+ assert route["classes"]["passive_expiry"]["requests"] == 1+ assert route["what_if"][1]["input_cost_usd"] == .0001+ assert state_db.read_bytes() == beforediff --git a/tests/test_cache_metrics_storage.py b/tests/test_cache_metrics_storage.pynew file mode 100644index 000000000..2a25dcad1--- /dev/null+++ b/tests/test_cache_metrics_storage.py@@ -0,0 +1,205 @@+"""Owning tests for cache diagnostic views, permissions, and read-only CLI shape."""++from __future__ import annotations++import json+import sqlite3+from pathlib import Path++import pytest++from config import paths+from storage.agent_transcript import CACHE_ATTEMPTS_SQL+from storage.background import SQLiteBackgroundTaskStore+from storage.pagination import PageRequest+from storage.read_only_query import ReadOnlyQueryError, run_read_only_query+from storage.cache_metrics import observation+from vibe.authorization import AuthorizationContext, instance_owner_context+from vibe.cli import build_parser+++def state_db(monkeypatch, tmp_path: Path) -> Path:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ SQLiteBackgroundTaskStore().close()+ return paths.get_sqlite_state_path()+++def _session(conn: sqlite3.Connection, session_id: str = "ses-cache") -> None:+ conn.execute(+ "insert into agent_sessions (id, agent_backend, agent_variant, session_anchor, native_session_id, status, "+ "metadata_json, created_at, updated_at, last_active_at, title, agent_name) "+ "values (?, 'vibey', 'default', ?, '', 'active', '{}', ?, ?, ?, 'Cache', 'vibey')",+ (session_id, session_id, "2026-10-01T00:00:00Z", "2026-10-01T00:00:00Z", "2026-10-01T00:00:00Z"),+ )+++def _response(+ conn: sqlite3.Connection,+ message_id: str,+ at: str,+ *,+ cache: dict | None,+ usage: dict | None,+ context_seq: int,+ session_id: str = "ses-cache",+ content_json: object | None = None,+) -> None:+ message = {+ "version": 1,+ "message": {+ "role": "assistant",+ "content": [],+ "origin": {"provider": "anthropic", "api": "anthropic", "model": "claude-test"},+ "stop_reason": "stop",+ **({"usage": usage} if usage is not None else {}),+ },+ **({"cache": cache} if cache is not None else {}),+ }+ body = {"model": message} if content_json is None else content_json+ conn.execute(+ "insert into messages (id, session_id, platform, author, type, content_text, content_json, metadata_json, "+ "created_at, updated_at, context_seq) values (?, ?, 'avibe', 'agent', 'result', '', ?, '{}', ?, ?, ?)",+ (message_id, session_id, json.dumps(body), at, at, context_seq),+ )+++def test_cache_view_reads_observed_rows_and_ignores_scalar_optional_json(state_db: Path) -> None:+ cache = {+ "version": 1,+ "started_at": 1790812800,+ "provider": "anthropic",+ "protocol": "anthropic",+ "model": "claude-test",+ "route": "route",+ "prefix": [["hash", 100]],+ "context_seq": 1,+ "lifetime_s": 300,+ "input_tokens": 110,+ "idle_s": 10,+ "expected_read": 100,+ "expected_read_basis": "reported_input",+ "reusable_tokens": 100,+ "reusable_static_tokens": 20,+ "previous_input_tokens": 100,+ "writes_by_ttl": {"5m": 10},+ "cache_write_basis": "reported",+ "causes": [],+ }+ with sqlite3.connect(state_db) as conn:+ _session(conn)+ _response(+ conn, "m-observed", "2026-10-01T00:00:00Z", cache=cache,+ usage={"input_tokens": 0, "output_tokens": 2, "cache_read_tokens": 100, "cache_write_tokens": 10},+ context_seq=1,+ )+ _response(conn, "m-scalar", "2026-10-01T00:01:00Z", cache=None, usage=None, context_seq=2,+ content_json={"model": "not-an-object"})+ _response(conn, "m-invalid", "2026-10-01T00:02:00Z", cache=None, usage=None, context_seq=3,+ content_json="not-json")+ conn.execute(+ "insert into agent_events (id, session_id, platform, event_type, visibility, content_json, metadata_json, created_at, updated_at) "+ "values ('evt-attempt', 'ses-cache', 'avibe', 'model_attempt', 'audit', ?, '{}', '2026-10-01T00:03:00Z', '2026-10-01T00:03:00Z')",+ (json.dumps({"cache": cache, "usage": {"input_tokens": 0, "cache_read_tokens": 100, "cache_write_tokens": 10}, "cache_state": [cache]}),),+ )+ conn.execute(+ "insert into agent_events (id, session_id, platform, event_type, visibility, content_json, metadata_json, created_at, updated_at) "+ "values ('evt-fork', 'ses-cache', 'avibe', 'fork_turn', 'audit', ?, '{}', '2026-10-01T00:04:00Z', '2026-10-01T00:04:00Z')",+ (json.dumps({"cache_attempts": [{"cache": cache, "usage": {"input_tokens": 0, "cache_read_tokens": 100, "cache_write_tokens": 10}}]}),),+ )+ conn.execute("update messages set content_json = 'not-json' where id = 'm-invalid'")+ conn.execute("update agent_sessions set agent_backend = 'codex' where id = 'ses-cache'")+ conn.execute("update messages set type = 'output' where id = 'm-observed'")+ conn.commit()++ result = run_read_only_query(+ "select request_id, purpose, idle_s, classification, data_basis, input_tokens, cache_write_basis, writes_by_ttl "+ "from cache_requests order by request_id",+ db_path=state_db, page_request=PageRequest(), user_context=instance_owner_context(),+ )+ by_id = {row["request_id"]: row for row in result.rows}+ assert by_id["m-observed"]["idle_s"] == 10+ assert by_id["m-observed"]["classification"] == "hit"+ assert by_id["m-observed"]["data_basis"] == "observed"+ assert by_id["m-observed"]["cache_write_basis"] == "reported"+ assert json.loads(by_id["m-observed"]["writes_by_ttl"]) == {"5m": 10}+ assert by_id["m-scalar"]["classification"] == "unknown"+ assert by_id["m-invalid"]["classification"] == "unknown"+ purposes = {row["purpose"] for row in result.rows if row["request_id"] != "m-observed" and row["request_id"] not in {"m-scalar", "m-invalid"}}+ assert purposes == {"attempt", "fork_turn"}++def test_cache_view_requires_member_access_for_audit_union(state_db: Path) -> None:+ with sqlite3.connect(state_db) as conn:+ _session(conn)+ conn.commit()+ editor = AuthorizationContext(instance_role="editor")+ with pytest.raises(ReadOnlyQueryError, match="agent_events"):+ run_read_only_query("select * from cache_requests", db_path=state_db, page_request=PageRequest(), user_context=editor)+++def test_cache_attempt_recovery_uses_the_session_type_index_without_sorting_history(state_db: Path) -> None:+ with sqlite3.connect(state_db) as conn:+ _session(conn)+ for index in range(3):+ conn.execute(+ "insert into agent_events (id, session_id, platform, event_type, visibility, content_json, "+ "metadata_json, created_at, updated_at) values (?, ?, 'avibe', 'model_attempt', 'audit', ?, '{}', ?, ?)",+ (f"evt-{index}", "ses-cache", json.dumps({"cache_state": []}), f"2026-10-01T00:0{index}:00Z", f"2026-10-01T00:0{index}:00Z"),+ )+ plan = [+ row[3]+ for row in conn.execute(+ "explain query plan " + CACHE_ATTEMPTS_SQL.replace(":session_id", "'ses-cache'").replace(":event_type", "'model_attempt'")+ )+ ]+ assert any("ix_agent_events_session_type_created_id" in detail for detail in plan), plan+ assert not any("TEMP B-TREE" in detail for detail in plan), plan+++def test_partial_prefix_expectations_are_not_called_provider_misses() -> None:+ facts = json.loads(+ observation(+ json.dumps({"version": 1, "started_at": 10, "lifetime_s": 300, "expected_read": 100,+ "expected_read_basis": "estimated_prefix", "reusable_tokens": 100,+ "reusable_static_tokens": 10, "previous_input_tokens": 100,+ "writes_by_ttl": {}, "causes": []}),+ json.dumps({"input_tokens": 1, "cache_read_tokens": 50, "cache_write_tokens": 0}),+ "anthropic", "anthropic", "claude-test", 10, 11, 100,+ )+ )+ assert facts["classification"] == "estimated_miss"+++def test_data_cache_parser_accepts_documented_filters():+ args = build_parser().parse_args(+ ["data", "cache", "--since", "6h", "--until", "2026-10-01T01:00:00Z", "--session-id", "ses-cache", "--model", "claude-test"]+ )+ assert args.data_command == "cache"+ assert args.since == "6h"+ assert args.until.endswith("Z")+ assert args.session_id == "ses-cache"+ assert args.model == "claude-test"++[email protected]("usage,causes,idle,expected,basis,classification", [+ ({}, [], 10, 2000, "reported_input", "unknown"),+ ({}, [], 500, 0, "expired", "unknown"),+ ({"cache_read_tokens": 2000}, [{"kind": "fork_start"}], 10, 2000, "reported_input", "hit"),+ ({"cache_write_tokens": 2000}, [{"kind": "prompt_applied", "reason": "session_start"}], None, 0, "no_previous_request", "cold_start"),+ ({"cache_write_tokens": 2000}, [{"kind": "tools_changed"}], 10, 0, "estimated_prefix", "active_break"),+ ({"cache_write_tokens": 2000}, [], 500, 0, "expired", "passive_expiry"),+ ({"cache_read_tokens": 1000, "cache_write_tokens": 1000}, [], 10, 2000, "reported_input", "provider_miss"),+ ({"cache_read_tokens": 1900, "cache_write_tokens": 100}, [], 10, 2000, "reported_input", "hit"),+])+def test_classification_preserves_unknown_usage_informational_causes_and_provider_tolerance(+ usage, causes, idle, expected, basis, classification,+):+ facts = json.loads(observation(+ {"version": 1, "started_at": 1000, "lifetime_s": 300, "idle_s": idle,+ "expected_read": expected, "expected_read_basis": basis,+ "previous_input_tokens": 2000, "causes": causes}, usage,+ "anthropic", "anthropic", "claude-test", 1000, 999, 2000,+ ))+ assert facts["classification"] == classification+ assert facts["idle_s"] == idlediff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.pyindex 50f6267ea..8e9da697d 100644--- a/tests/test_cli_pagination.py+++ b/tests/test_cli_pagination.py@@ -599,6 +599,30 @@ def test_data_query_cli_runs_read_only_sql(monkeypatch, tmp_path, capsys) -> Nonassert payload["rows"] == [{"id": "run-1", "status": "succeeded"}]+def test_data_cache_cli_passes_filters_to_read_only_report(monkeypatch, capsys) -> None:+ from core.handlers import cache_metrics++ seen = {}++ def fake_report(**kwargs):+ seen.update(kwargs)+ return {"since": "x", "until": "y", "routes": []}++ monkeypatch.setattr(cache_metrics, "report", fake_report)+ args = cli.build_parser().parse_args([+ "data", "cache", "--since", "2026-10-01T00:00:00Z", "--until", "2026-10-02T00:00:00Z",+ "--session-id", "ses-cache", "--model", "claude-test",+ ])+ assert cli.cmd_data_cache(args) == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["kind"] == "data_cache"+ assert payload["routes"] == []+ assert seen["session_id"] == "ses-cache"+ assert seen["model"] == "claude-test"+ assert seen["since"].isoformat() == "2026-10-01T00:00:00+00:00"+ assert seen["until"].isoformat() == "2026-10-02T00:00:00+00:00"++def test_data_query_cli_omits_next_command_for_stdin_sql(monkeypatch, tmp_path, capsys) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_session_request_preview.py b/tests/test_session_request_preview.pyindex 6510db62d..c4a997620 100644--- a/tests/test_session_request_preview.py+++ b/tests/test_session_request_preview.py@@ -79,7 +79,7 @@ async def commit_input(host):def deny_effects(host, monkeypatch):- for name in ("_preflight", "_resume", "_accept_native_start", "handle_message", "recover_runtime_state"):+ for name in ("_preflight", "_resume", "_accept_native_start", "handle_message", "recover_runtime_state", "_record_prompt_events"):monkeypatch.setattr(host.harness.agent, name, forbidden)monkeypatch.setattr(host.harness.agent, "_providers", forbidden)monkeypatch.setattr(host.router, "resolve", forbidden)diff --git a/tests/test_transcript_store_contract.py b/tests/test_transcript_store_contract.pyindex 3536d072d..2d26c6598 100644--- a/tests/test_transcript_store_contract.py+++ b/tests/test_transcript_store_contract.py@@ -223,6 +223,42 @@ async def test_each_append_returns_the_entry_load_reads_back_in_commit_order(bacassert times == sorted(times)+async def test_cache_facts_round_trip_and_latest_audits_restore_without_entering_context(backend):+ from dataclasses import replace+ from core.agent_core.ai.provider import ModelRequest+ from core.agent_core.harness.cache_metrics import CacheTracker+ from tests.agent_core.fakes import ENDPOINT++ store = backend.store+ await _started(backend)+ tracker = CacheTracker()+ request = ModelRequest(endpoint=ENDPOINT, system="fixed", tools=(), messages=(user("hello"),), max_tokens=10)+ message = replace(assistant(), usage=Usage(input_tokens=100))+ cache = tracker.begin(request, (), now=100)+ tracker.finish(cache, message)+ response = await store.append_response(SESSION, message, final=True, cache=cache)+ loaded = await store.load(SESSION)+ assert loaded[-1].payload["cache"] == cache+ backend.fork("child", SESSION, response)+ inherited = await store.load("child")+ assert inherited[-1].payload["cache"] == cache+ later = tracker.begin(request, loaded, now=200)+ tracker.finish(later, message)+ await store.append_audit(SESSION, "attempt", {+ "version": 1, "error": "commit failed", "usage": usage_to_dict(message.usage),+ "cache": later, "cache_state": list(tracker.latest.values()),+ })+ assert list(await store.load_cache_attempts(SESSION)) == [later]+ assert list(await store.load(SESSION)) == list(loaded)+ # A failure with no usage retains the last usage-bearing state, rather than a new clock.+ failed = tracker.begin(request, loaded, now=300)+ tracker.finish(failed, None)+ await store.append_audit(SESSION, "attempt", {+ "version": 1, "error": "rate limited", "cache": failed, "cache_state": list(tracker.latest.values()),+ })+ assert list(await store.load_cache_attempts(SESSION)) == [later]++async def test_a_payload_row_needs_a_payload_kind_and_the_current_version(backend):store = backend.storebefore = [await _started(backend)]diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 445118b9c..c8ec00c30 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -2749,6 +2749,18 @@ async def test_the_instruction_files_enter_between_the_head_and_avibes_sections_rows = await harness.context_rows()last_input = [row.message for row in rows if row.kind == "input"][-1]assert f"instructions: pending {tmp_path / 'AGENTS.md'}@" in last_input.content[0].text+ # Diagnostics belong to actual snapshot transitions, not every warm no-op Turn.+ with engine.connect() as conn:+ events = conn.execute(select(agent_events.c.event_type, agent_events.c.content_json).where(+ agent_events.c.session_id == session,+ agent_events.c.event_type.in_(("prompt.pending", "prompt.applied")),+ )).all()+ applied = [json.loads(body) for kind, body in events if kind == "prompt.applied"]+ pending = [json.loads(body) for kind, body in events if kind == "prompt.pending"]+ assert len(pending) == 2+ assert {event["reason"] for event in applied} == {"session_start", "tier1"}+ assert len(applied) == 2+ assert {item["tier"] for event in applied for item in event["components"]} == {1, 2}@pytest.mark.parametrize("own_content", ["My own revision.", "", " \n", "\ufeff"])diff --git a/tests/test_vibey_resume_ownership.py b/tests/test_vibey_resume_ownership.pyindex 9ed0d2af3..42601b770 100644--- a/tests/test_vibey_resume_ownership.py+++ b/tests/test_vibey_resume_ownership.py@@ -195,12 +195,18 @@ async def test_retry_events_and_recovered_job_belong_to_retry_turn_not_last_inpuharness = _Harness(engine, tmp_path, "avibe", [[ProviderError("invalid_request", "failed", False)]], suite=suite)original = harness.request("运行检查")await harness.agent.handle_message(original)+ with engine.connect() as conn:+ before = {row["id"]: dict(row) for row in conn.execute(+ select(agent_events).where(agent_events.c.session_id == SESSION)+ ).mappings()}+ # The failed Turn now has non-context prompt/attempt diagnostics of its own.+ assert {row["turn_id"] for row in before.values()} == {_turn(original.context)}retry = _retry_request(harness, original)retry_turn = _turn(retry.context)harness.controller._native_start(retry.context)# Simulate the retry process dying after the tool call was committed, before its result.harness.agent.store.bind_agent(SESSION, "vibey", turn_id=retry_turn)- response = await harness.agent.store.append_response(+ await harness.agent.store.append_response(SESSION, assistant("", calls=[ToolCallBlock("retry_bash", "bash", {"command": "pytest"})]), final=False)await harness.agent.store.append_audit(SESSION, "attempt", {"version": 1, "test": "retry"})@@ -211,7 +217,8 @@ async def test_retry_events_and_recovered_job_belong_to_retry_turn_not_last_inpuwith engine.connect() as conn:events = conn.execute(select(agent_events).where(agent_events.c.session_id == SESSION)).mappings().all()- retry_events = [row for row in events if row["context_seq"] is None or row["context_seq"] > response.context_seq]+ assert {row["id"]: dict(row) for row in events if row["id"] in before} == before+ retry_events = [row for row in events if row["id"] not in before]assert {row["turn_id"] for row in retry_events} == {retry_turn}assert jobs.watches == {"job_retry": "watch_job_retry"}[result] = [entry for entry in await harness.context_rows() if entry.kind == "tool_result"]diff --git a/vibe/cli.py b/vibe/cli.pyindex cb2b3f159..52dd8b816 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -7857,8 +7857,49 @@ def cmd_data_query(args):return 1-# ``vibe session`` — Agent-facing session management. ``list`` / ``get`` are-# read-only; ``update`` edits title, visibility, or scope placement. All three go through the shared+def cmd_data_cache(args):+ """Summarize Vibey cache behavior from read-only diagnostic views."""+ help_command = "vibe data cache --help"+ try:+ now = datetime.now(timezone.utc)+ since_text = _parse_cli_time_filter(+ getattr(args, "since", None) or "7d", field_name="--since", help_command=help_command+ )+ until_text = _parse_cli_time_filter(+ getattr(args, "until", None), field_name="--until", help_command=help_command+ )+ since = datetime.fromisoformat(since_text.replace("Z", "+00:00")) if since_text else now - timedelta(days=7)+ until = datetime.fromisoformat(until_text.replace("Z", "+00:00")) if until_text else now+ if since.tzinfo is None:+ since = since.replace(tzinfo=timezone.utc)+ if until.tzinfo is None:+ until = until.replace(tzinfo=timezone.utc)+ since = since.astimezone(timezone.utc)+ until = until.astimezone(timezone.utc)+ if until <= since:+ raise TaskCliError("--until must be later than --since", code="invalid_time_range", help_command=help_command)+ from core.handlers.cache_metrics import report++ payload = report(+ since=since,+ until=until,+ session_id=getattr(args, "session_id", None),+ model=getattr(args, "model", None),+ user_context=caller_resource_user_context(caller_context_from_env()),+ db_path=paths.get_sqlite_state_path(),+ )+ _print_cli_payload("data_cache", **payload)+ return 0+ except ReadOnlyQueryError as exc:+ _print_task_error(TaskCliError(str(exc), code=exc.code, hint=exc.hint, help_command=help_command))+ return 1+ except Exception as exc:+ _print_task_error(exc, help_command=help_command)+ return 1+++# Session commands: list/get are read-only; update changes title, visibility or scope placement.+# All three use the shared# ``core.services.sessions`` business API (same entry the UI server uses) and# never surface archived (soft-deleted) sessions.# Lean list row: enough to locate a session and tell whether it is busy.@@ -18639,7 +18680,7 @@ 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,skill-usage}")+ data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query,cache,retention,skill-usage}")data_subparsers.required = Trueskill_usage_parser = data_subparsers.add_parser("skill-usage", help="Inspect or clear local Skill statistics (Instance Member or Owner)",@@ -18649,18 +18690,33 @@ def build_parser():skill_usage_parser.add_argument("--clear", action="store_true", help="Clear Skill events and daily statistics.")skill_usage_parser.add_argument("--yes", action="store_true", help="Confirm clearing Skill statistics.")_add_json_noop(skill_usage_parser)+ data_cache_parser = data_subparsers.add_parser(+ "cache",+ help="Summarize Vibey cache behavior and current-list cost estimates",+ description=(+ "Read Vibey cache request facts without changing local state. Cost figures use the cached current "+ "standard price list, not historical bills; unknown or inferred facts are labeled in the result."+ ),+ error_help_command="vibe data cache --help",+ )+ data_cache_parser.add_argument("--since", help="Start time (ISO 8601 or relative value such as 6h or 7d; default 7d).")+ data_cache_parser.add_argument("--until", help="Exclusive end time (ISO 8601 or relative value; default now).")+ data_cache_parser.add_argument("--session-id", help="Limit the report to one Session.")+ data_cache_parser.add_argument("--model", help="Limit the report to one served model id.")+ _add_json_noop(data_cache_parser)data_query_parser = data_subparsers.add_parser("query",help="Run one read-only SQL query",description="Run one guarded read-only SQL query against the local SQLite state database.",epilog=(- "Recall earlier work through four views (the raw tables stay queryable):\n"+ "Recall earlier work through four history views (the raw tables stay queryable):\n"" digests(session_id, title, agent_name, last_active_at, parent_session_id, digest_at, mind, memo, now, text)\n"" what each Session is about and where it stands: a Vibey Session's latest checkpoint memory\n"" (mind, memo, now; text holds all three), else its first input and latest reply\n"" sessions(session_id, title, agent_name, backend, model, status, workdir, created_at, last_active_at, parent_session_id)\n"" transcript(session_id, at, role, kind, text, turn_id, message_id) role: user, agent, harness\n"" turns(session_id, turn_id, started_at, ended_at, outcome, input, reply)\n"+ " cache_requests: Vibey cache classification, TTL writes and current-list valuation (Member access).\n""excerpt(text, 'term'[, width]) shows the text around a match; REGEXP takes a Python pattern.\n"" vibe data query --sql \"select session_id, title, excerpt(text, 'tax') from digests where text like '%tax%' order by last_active_at desc\" --format text\n"" vibe data query --sql \"select session_id, at, excerpt(text, 'watch list') from transcript where text like '%watch list%' order by at desc\" --format text\n"@@ -19603,6 +19659,7 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {("skill", "list"): "editor",("skill", "load"): "editor",("data", "query"): "editor",+ ("data", "cache"): "member",("data", "skill-usage"): "editor",# Kept model requests hold whole prompts, tool definitions and output of every Session, as raw bytes: Owner# only, listing included.@@ -19937,6 +19994,8 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:if args.command == "data":if args.data_command == "query":sys.exit(cmd_data_query(args))+ if args.data_command == "cache":+ sys.exit(cmd_data_cache(args))if args.data_command == "skill-usage":sys.exit(cmd_data_skill_usage(args))if args.data_command == "retention":