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(storage): bounded retention for agent trace events (#1514)
Call Whited56129aafce3
diff --git a/config/v2_config.py b/config/v2_config.pyindex 0684fd948..4d8fbf41d 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -41,6 +41,7 @@ from config.platform_registry import (from modules.agents.catalog import DEFAULT_AGENT_BACKENDfrom modules.im.base import BaseIMConfigfrom vibe.i18n import normalize_language+from vibe.trace_retention_policy import validate_retention_dayslogger = logging.getLogger(__name__)@@ -1028,6 +1029,16 @@ def _refuse_values_naming_nothing(section: str, instance: object) -> None:# ``_reset_recoverable_config_section``._FIELD_SCOPED_RECOVERY_SECTIONS = ("ui", "audio_asr")+# Retention is optional and destructive: a malformed field must disable only+# that policy while preserving the rest of the runtime settings (cwd, logging,+# resource governance, and Harness timeouts).+_RUNTIME_RETENTION_FIELDS = frozenset(+ {+ "agent_events_trace_retention_enabled",+ "agent_events_trace_retention_days",+ }+)+# The switch that decides whether an optional feature runs at all. Named once# because recovery has to tell it apart from every other switch in a section:# the rest describe how a feature behaves, this one decides whether it happens.@@ -1109,6 +1120,16 @@ def _recovery_field_for_error(section: Optional[str], error: BaseException) -> Oif not path.startswith(prefix):return Nonereturn path[len(prefix) :].split(".", 1)[0]+ if section == "runtime":+ match = re.search(r"Config '([^']+)'", str(error))+ if not match:+ return None+ path = match.group(1)+ prefix = "runtime."+ if not path.startswith(prefix):+ return None+ field_name = path[len(prefix) :].split(".", 1)[0]+ return field_name if field_name in _RUNTIME_RETENTION_FIELDS else Noneif section not in _FIELD_SCOPED_RECOVERY_SECTIONS:return Nonematch = re.search(r"Config '([^']+)'", str(error))@@ -1260,6 +1281,25 @@ def _recover_memory_cloud_section(payload: dict, field_name: Optional[str]) -> breturn True+def _recover_runtime_field(payload: dict, field_name: Optional[str]) -> bool:+ """Repair one retention field without discarding the runtime section."""++ if field_name not in _RUNTIME_RETENTION_FIELDS:+ return False+ runtime = payload.get("runtime")+ if not isinstance(runtime, dict):+ return False+ # A recovered policy is disabled even if the other retention field looked+ # valid. The warning attached by ``V2Config.load`` keeps all automatic and+ # status consumers fail-closed until the operator repairs the file.+ runtime["agent_events_trace_retention_enabled"] = False+ if field_name == "agent_events_trace_retention_days":+ runtime[field_name] = 30+ else:+ runtime[field_name] = False+ return True++def _reset_recoverable_config_section(payload: dict, section: str, field_name: Optional[str] = None) -> bool:@@ -1270,6 +1310,9 @@ def _reset_recoverable_config_section(loss-avoiding recovery path, and the original file is backed up first."""+ if section == "runtime" and field_name is not None:+ if _recover_runtime_field(payload, field_name):+ return Trueif section in _FIELD_SCOPED_RECOVERY_SECTIONS:return _recover_switch_section_field(payload, section, field_name)if section == "memory.rerank":@@ -2507,6 +2550,16 @@ class RuntimeConfig:# arrived as an answer to a question nobody in the channel could see. Off means# today's behavior (result only).harness_prompt_echo: bool = True+ # Bounded retention for internal agent trace events (``agent_events`` rows+ # with ``event_type='tool_call'`` and ``visibility='trace'``). These are+ # debug/diagnostic material, never chat messages; without a bound an active+ # installation grows ``vibe.sqlite`` without limit. Default-on: the first+ # controller startup after upgrading runs a pass that permanently deletes+ # tool_call traces older than the window — set ``enabled=False`` BEFORE+ # upgrading to preserve old diagnostics. User docs (en+zh): the+ # ``vibe data retention`` section of the CLI reference (avibe-docs).+ agent_events_trace_retention_enabled: bool = True+ agent_events_trace_retention_days: int = 30def __post_init__(self) -> None:self.show_page_api_timeout_seconds = _named_value(@@ -2518,6 +2571,17 @@ class RuntimeConfig:raise ValueError("Config 'runtime.show_page_api_timeout_seconds' must be greater than zero")+ # These values control irreversible deletion. Dataclass annotations do+ # not validate JSON payloads, and coercing a string/bool here could turn+ # a malformed config into a shorter retention window.+ if not isinstance(self.agent_events_trace_retention_enabled, bool):+ raise ValueError(+ "Config 'runtime.agent_events_trace_retention_enabled' must be a boolean"+ )+ validate_retention_days(+ self.agent_events_trace_retention_days,+ field="Config 'runtime.agent_events_trace_retention_days'",+ )@dataclass@@ -4182,6 +4246,8 @@ class V2Config:"harness_run_queued_ttl_seconds": self.runtime.harness_run_queued_ttl_seconds,"harness_run_hold_ttl_seconds": self.runtime.harness_run_hold_ttl_seconds,"harness_prompt_echo": self.runtime.harness_prompt_echo,+ "agent_events_trace_retention_enabled": self.runtime.agent_events_trace_retention_enabled,+ "agent_events_trace_retention_days": self.runtime.agent_events_trace_retention_days,},"agents": {"opencode": self.agents.opencode.__dict__,diff --git a/core/controller.py b/core/controller.pyindex 3c466ab8a..69b568e03 100644--- a/core/controller.py+++ b/core/controller.py@@ -357,6 +357,10 @@ class Controller:# Background task for cleanupself.cleanup_task: Optional[asyncio.Task] = None+ self.trace_retention_task: Optional[asyncio.Task] = None+ self._trace_retention_executor: Optional[Any] = None+ self._trace_retention_cancel_event: Optional[threading.Event] = None+ self._trace_retention_future: Optional[Any] = Noneself._memory_reconcile_task: Optional[asyncio.Task] = Noneself._memory_replacement_gate = asyncio.Lock()self._memory_factory_reset_task: Optional[asyncio.Task[dict[str, Any]]] = None@@ -1605,6 +1609,11 @@ class Controller:self.cleanup_task = asyncio.create_task(self.periodic_cleanup())except Exception as e:logger.error("Failed to start idle session cleanup: %s", e, exc_info=True)+ try:+ if self.trace_retention_task is None or self.trace_retention_task.done():+ self.trace_retention_task = asyncio.create_task(self._agent_events_retention_loop())+ except Exception as e:+ logger.error("Failed to start agent trace-event retention: %s", e, exc_info=True)async def _recover_runtime_owners(self) -> None:"""Restore durable execution owners before any producer can admit work."""@@ -3253,6 +3262,143 @@ class Controller:)return claude_timeout, codex_timeout+ _AGENT_EVENTS_RETENTION_CHECK_INTERVAL_SECONDS = 3600++ def _agent_events_retention_config(self) -> dict[str, Any] | None:+ """Read the retention window from the persisted V2 config, failing closed.++ The controller's ``self.config`` is an ``AppCompatConfig`` shim without+ the runtime section, so this reloads ``V2Config`` directly. Deletion is+ irreversible, so every ambiguous state disables the automatic pass:+ config recovery defaults (``load_warnings`` set — the persisted policy+ is unknown), a malformed opt-out, or a malformed window (a shorter+ default must never silently override a longer persisted policy).+ """+ from storage import agent_events_retention++ try:+ from config.v2_config import V2Config++ config = V2Config.load()+ except Exception:+ logger.warning("Agent trace-event retention: config unreadable; disabling automatic pass", exc_info=True)+ return None++ policy = agent_events_retention.resolve_policy(config)+ if policy.recovered:+ logger.warning(+ "Agent trace-event retention: persisted policy is malformed or recovered; "+ "disabling automatic pass until the config is fixed"+ )+ return None+ if not policy.enabled:+ return None+ return {"days": policy.days}++ def _run_agent_events_retention_pass(+ self, cancel_event: Optional[threading.Event] = None+ ) -> dict[str, Any]:+ """One maintenance pass on the worker thread (no VACUUM: manual-only).++ Full ``VACUUM`` holds SQLite's sole write lock for the entire rewrite;+ on a large live database that can exceed every writer's busy timeout.+ The automatic path therefore deletes rows only and reports compaction+ as not attempted — ``vibe data retention --run`` owns compaction.+ """+ from storage import agent_events_retention+ from storage.db import get_cached_sqlite_engine++ config = self._agent_events_retention_config()+ if config is None:+ return {"status": "disabled"}+ engine = get_cached_sqlite_engine()+ return agent_events_retention.run_once(+ engine,+ retention_days=int(config["days"]),+ compact=False,+ cancel_event=cancel_event,+ )++ async def _join_trace_retention_future(self) -> None:+ """Wait for the worker's current batch to observe cooperative stop."""++ future = getattr(self, "_trace_retention_future", None)+ if future is None:+ return+ # The worker checks the event between transactions. Keep waiting even+ # if the outer task receives another cancellation so shutdown never+ # disposes the executor while SQLite work is still executing.+ while not future.done():+ try:+ await asyncio.shield(future)+ except asyncio.CancelledError:+ continue+ except Exception:+ break++ async def _agent_events_retention_loop(self) -> None:+ """Bounded retention for internal agent trace events (avibe#1506).++ Checks immediately and then hourly; the storage marker inside+ ``agent_events_retention.run_once`` owns the once-per-day cadence, so+ short-lived sessions still get their first pass on startup. Work runs+ on a single-worker executor so shutdown can join it.+ """+ import concurrent.futures++ executor = concurrent.futures.ThreadPoolExecutor(+ max_workers=1, thread_name_prefix="trace-retention"+ )+ cancel_event = threading.Event()+ self._trace_retention_executor = executor+ self._trace_retention_cancel_event = cancel_event+ logger.info(+ "Agent trace-event retention loop started (check interval=%ss)",+ self._AGENT_EVENTS_RETENTION_CHECK_INTERVAL_SECONDS,+ )+ loop = asyncio.get_running_loop()+ try:+ while True:+ try:+ future = loop.run_in_executor(+ executor,+ self._run_agent_events_retention_pass,+ cancel_event,+ )+ self._trace_retention_future = future+ try:+ summary = await asyncio.shield(future)+ finally:+ if self._trace_retention_future is future and future.done():+ self._trace_retention_future = None+ status = str((summary or {}).get("status") or "unknown")+ if status not in {"not_due", "disabled"}:+ logger.info(+ "Agent trace-event retention %s: deleted=%s compaction=%s",+ status,+ (summary or {}).get("deleted_rows"),+ ((summary or {}).get("compaction") or {}).get("status"),+ )+ except asyncio.CancelledError:+ cancel_event.set()+ await self._join_trace_retention_future()+ raise+ except Exception:+ logger.error("Agent trace-event retention failed", exc_info=True)+ await asyncio.sleep(self._AGENT_EVENTS_RETENTION_CHECK_INTERVAL_SECONDS)+ finally:+ cancel_event.set()+ await self._join_trace_retention_future()+ try:+ executor.shutdown(wait=True)+ finally:+ if self._trace_retention_executor is executor:+ self._trace_retention_executor = None+ if self._trace_retention_cancel_event is cancel_event:+ self._trace_retention_cancel_event = None+ if self._trace_retention_future is not None and self._trace_retention_future.done():+ self._trace_retention_future = None+async def periodic_cleanup(self):"""Sweep idle backend runtime state without interrupting active work."""claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()@@ -3336,6 +3482,28 @@ class Controller:passself.cleanup_task = None+ async def _cancel_trace_retention_task() -> None:+ cancel_event = getattr(self, "_trace_retention_cancel_event", None)+ if cancel_event is not None:+ cancel_event.set()+ if self.trace_retention_task and not self.trace_retention_task.done():+ self.trace_retention_task.cancel()+ try:+ await self.trace_retention_task+ except asyncio.CancelledError:+ pass+ self.trace_retention_task = None+ # The loop normally joins this future in its finally block. Keep+ # the fallback here for partial startup/shutdown states where the+ # task was never fully scheduled.+ await self._join_trace_retention_future()+ executor = getattr(self, "_trace_retention_executor", None)+ if executor is not None:+ executor.shutdown(wait=True)+ self._trace_retention_executor = None+ self._trace_retention_cancel_event = None+ self._trace_retention_future = None+async def _cancel_internal_server_task() -> None:task = getattr(self, "_internal_server_task", None)if task is not None and not task.done():@@ -3373,6 +3541,14 @@ class Controller:logger.debug(f"Internal dispatch server status write skipped: {e}")_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")+ # Retention cancellation is cooperative at a delete-batch boundary;+ # wait for that bounded join instead of abandoning the worker after+ # the generic five-second cleanup timeout.+ _stop_loop_coroutine(+ _cancel_trace_retention_task(),+ "Agent trace retention task",+ timeout=None,+ )_stop_loop_coroutine(self._join_runtime_work_stack_shutdown(),"Runtime work stack",diff --git a/storage/agent_events_retention.py b/storage/agent_events_retention.pynew file mode 100644index 000000000..cf897ba29--- /dev/null+++ b/storage/agent_events_retention.py@@ -0,0 +1,704 @@+"""Bounded retention for internal agent trace events (avibe#1506 lane B).++This module is the single owner of ``agent_events`` deletion policy. The+eligibility property, defined once here and shared by planning, execution,+and tests:++ Only parseable rows with ``event_type='tool_call'`` AND+ ``visibility='trace'`` AND ``created_at`` strictly older than the retention+ cutoff are ever removable. Unparseable timestamps are preserved.++Everything else — user messages (a separate table), message deliveries,+session/run records, Vault audit data, non-trace events, and newer traces —+is preserved by construction: no code path in this module deletes a row+outside the predicate, regardless of caller.++Operational shape:++* Deletes run in small batches, each in its own transaction, so concurrent+ writers (WAL mode) are never blocked for an unbounded interval.+* A ``state_meta`` marker records the last successful run and throttles the+ automatic cadence to at most once per day; a lease row serializes+ concurrent runners (controller task vs CLI) across processes.+* Physical compaction (``VACUUM``) only runs after a free-space and+ writer-safety preflight, and only when reclaimable space justifies it.+ When compaction is unsafe it is reported as deferred — never started on a+ nearly-full volume.+"""++from __future__ import annotations++import json+import shutil+import threading+import time+import uuid+from dataclasses import dataclass+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any, Callable, Optional++from sqlalchemy import Engine, LargeBinary, delete, func, select, cast+from sqlalchemy.exc import IntegrityError, OperationalError+from sqlalchemy.engine import Connection++from storage.models import agent_events, state_meta+from vibe.trace_retention_policy import (+ MAX_RETENTION_DAYS,+ MIN_RETENTION_DAYS,+ validate_retention_days,+)++DEFAULT_RETENTION_DAYS = 30+MIN_RUN_INTERVAL_SECONDS = 24 * 3600+DELETE_BATCH_ROWS = 1000+LEASE_TTL_SECONDS = 3600+# Compaction heartbeat interval: keeps the lease renewed well inside the TTL.+LEASE_HEARTBEAT_SECONDS = 60+# Compaction only when the free list alone would return at least this much,+# so a daily run does not rewrite a large database for pocket change.+VACUUM_MIN_RECLAIM_BYTES = 64 * 1024 * 1024+# VACUUM writes a full temp copy and the WAL rewrite can coexist with it, so+# the preflight must reserve room for both copies plus margin.+VACUUM_FREE_SPACE_MARGIN_BYTES = 256 * 1024 * 1024++RETENTION_MARKER_KEY = "agent_events_trace_retention.last_run"+RETENTION_LEASE_KEY = "agent_events_trace_retention.lease"+++@dataclass(frozen=True)+class RetentionPolicy:+ """The validated policy used by every retention entry point.++ ``recovered`` means that the persisted policy could not be trusted. A+ recovered policy is always disabled for automatic deletion; the CLI may+ still run an explicitly supplied ``--days`` window.+ """++ enabled: bool+ days: int+ recovered: bool = False+++def _warning_replaces_retention_policy(warning: object) -> bool:+ text = str(warning)+ if "recovery defaults" in text or "could not be recovered" in text:+ return True+ # Field-scoped recovery warnings are rendered as+ # ``runtime.agent_events_trace_retention_days``; both that form and the+ # older whole-section form replace the policy we are about to use.+ return "Recovered invalid config section 'runtime" in text+++def resolve_policy(config: Any) -> RetentionPolicy:+ """Validate a loaded config without coercing destructive values.++ This is deliberately independent of ``V2Config`` so controller, CLI, and+ tests share one policy owner without introducing a config/storage import+ cycle. Invalid values fail closed instead of being normalized to a+ shorter retention window.+ """++ warnings = getattr(config, "load_warnings", ()) if config is not None else ()+ recovered = any(_warning_replaces_retention_policy(warning) for warning in (warnings or ()))+ runtime = getattr(config, "runtime", None) if config is not None else None+ if runtime is None:+ return RetentionPolicy(False, DEFAULT_RETENTION_DAYS, True)++ enabled = getattr(runtime, "agent_events_trace_retention_enabled", None)+ days = getattr(runtime, "agent_events_trace_retention_days", None)+ if not isinstance(enabled, bool):+ return RetentionPolicy(False, DEFAULT_RETENTION_DAYS, True)+ try:+ validate_retention_days(days)+ except ValueError:+ return RetentionPolicy(False, DEFAULT_RETENTION_DAYS, True)+ if recovered:+ return RetentionPolicy(False, days, True)+ return RetentionPolicy(enabled, days, False)+++def _utc_now() -> datetime:+ return datetime.now(timezone.utc)+++def _iso(moment: datetime) -> str:+ if moment.tzinfo is None:+ moment = moment.replace(tzinfo=timezone.utc)+ return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")+++def _parse_iso(value: str) -> Optional[datetime]:+ if not isinstance(value, str):+ return None+ try:+ normalized = value.strip()+ if normalized.endswith("Z"):+ normalized = normalized[:-1] + "+00:00"+ parsed = datetime.fromisoformat(normalized)+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc)+ except (TypeError, ValueError):+ return None+++def normalize_retention_days(retention_days: Any) -> int:+ """Normalize legacy callers without allowing an oversized cutoff."""++ try:+ days = int(retention_days)+ if days > MAX_RETENTION_DAYS:+ raise ValueError+ except (TypeError, ValueError):+ return DEFAULT_RETENTION_DAYS+ return max(MIN_RETENTION_DAYS, days)+++def cutoff_iso(retention_days: int, *, now: Optional[datetime] = None) -> str:+ """Rows strictly older than this instant are eligible."""+ moment = now or _utc_now()+ days = validate_retention_days(retention_days)+ try:+ cutoff = moment - timedelta(days=days)+ except OverflowError as exc:+ raise ValueError("retention window produces an unrepresentable cutoff") from exc+ return _iso(cutoff)+++def eligible_filter(cutoff: str):+ """The single eligibility predicate shared by plan and delete.++ Keep the scope and parseability clauses byte-for-byte compatible with the+ partial index ``ix_agent_events_trace_retention`` (storage/models.py and+ the alembic migration) so the scan stays bounded.+ """+ return (+ (agent_events.c.event_type == "tool_call")+ & (agent_events.c.visibility == "trace")+ & func.datetime(agent_events.c.created_at).is_not(None)+ & (agent_events.c.created_at < cutoff)+ )+++def plan(conn: Connection, *, retention_days: int, now: Optional[datetime] = None) -> dict[str, Any]:+ """Dry-run report: how many eligible rows exist and their logical payload size.++ Sizes are measured in UTF-8 bytes (``CAST(.. AS BLOB)``); SQLite's plain+ ``length(TEXT)`` counts Unicode characters and underreports CJK payloads+ several-fold.+ """+ cutoff = cutoff_iso(retention_days, now=now)++ def _blob_bytes(column) -> Any:+ return func.length(cast(func.coalesce(column, ""), LargeBinary))++ logical_bytes = func.sum(+ _blob_bytes(agent_events.c.content_text)+ + _blob_bytes(agent_events.c.content_json)+ + _blob_bytes(agent_events.c.metadata_json)+ )+ row = conn.execute(+ select(func.count(), logical_bytes).where(eligible_filter(cutoff))+ ).one()+ return {+ "retention_days": normalize_retention_days(retention_days),+ "cutoff": cutoff,+ "eligible_count": int(row[0] or 0),+ "eligible_logical_bytes": int(row[1] or 0),+ }+++def _delete_batch(conn: Connection, cutoff: str, batch_rows: int) -> int:+ result = conn.execute(+ delete(agent_events).where(+ agent_events.c.id.in_(+ select(agent_events.c.id)+ .where(eligible_filter(cutoff))+ .order_by(agent_events.c.created_at, agent_events.c.id)+ .limit(batch_rows)+ )+ )+ )+ return int(result.rowcount or 0)+++def renew_lease(conn: Connection, token: str, *, now: Optional[datetime] = None) -> bool:+ """Extend this runner's lease while work remains active.++ Renewal is one token-conditional UPDATE (no read-then-write), so a+ contender committing a replacement between operations can neither be+ overwritten nor trip a busy-snapshot upgrade in the heartbeat thread.+ """+ moment = now or _utc_now()+ result = conn.execute(+ state_meta.update()+ .where(+ state_meta.c.key == RETENTION_LEASE_KEY,+ func.json_extract(state_meta.c.value_json, "$.token") == token,+ )+ .values(+ value_json=json.dumps(+ {"token": token, "expires_at": _iso(moment + timedelta(seconds=LEASE_TTL_SECONDS))},+ sort_keys=True,+ ),+ updated_at=_iso(moment),+ )+ )+ return int(result.rowcount or 0) == 1+++def run_retention(+ engine: Engine,+ *,+ retention_days: int,+ batch_rows: int = DELETE_BATCH_ROWS,+ max_batches: Optional[int] = None,+ between_batches: Optional[Callable[[], None]] = None,+ now: Optional[datetime] = None,+ lease_token: Optional[str] = None,+ cancel_event: Optional[threading.Event] = None,+) -> dict[str, Any]:+ """Delete eligible rows in bounded batches, one transaction per batch.++ ``between_batches`` runs after each committed batch (test hook for+ simulating concurrent writers between transactions). With ``lease_token``+ the lease is renewed between batches so long runs stay owned.+ """+ cutoff = cutoff_iso(retention_days, now=now)+ deleted_rows = 0+ batches = 0+ lease_lost = False+ cancelled = False+ while max_batches is None or batches < max_batches:+ if cancel_event is not None and cancel_event.is_set():+ cancelled = True+ break+ ownership = True+ with engine.begin() as conn:+ removed = _delete_batch(conn, cutoff, batch_rows)+ if lease_token is not None and not renew_lease(conn, lease_token):+ ownership = False+ batches += 1+ if not ownership:+ # The committed batch is counted, but ownership was lost mid-run:+ # propagate the loss so run_once skips the marker write and+ # compaction rather than racing the replacement runner.+ lease_lost = True+ deleted_rows += removed+ break+ if removed == 0:+ break+ deleted_rows += removed+ if cancel_event is not None and cancel_event.is_set():+ cancelled = True+ break+ if between_batches is not None:+ between_batches()+ return {+ "cutoff": cutoff,+ "deleted_rows": deleted_rows,+ "batches": batches,+ **({"lease_lost": True} if lease_lost else {}),+ **({"cancelled": True} if cancelled and not lease_lost else {}),+ }+++@dataclass+class _MetaPayload:+ payload: dict[str, Any]+++def _read_meta(conn: Connection, key: str) -> Optional[dict[str, Any]]:+ value = conn.execute(select(state_meta.c.value_json).where(state_meta.c.key == key)).scalar_one_or_none()+ if not value:+ return None+ try:+ parsed = json.loads(value)+ except json.JSONDecodeError:+ return None+ return parsed if isinstance(parsed, dict) else None+++def _write_meta(conn: Connection, key: str, payload: dict[str, Any], *, now: datetime) -> None:+ stamp = _iso(now)+ conn.execute(state_meta.delete().where(state_meta.c.key == key))+ conn.execute(+ state_meta.insert().values(key=key, value_json=json.dumps(payload, sort_keys=True), updated_at=stamp)+ )+++def get_last_run(conn: Connection) -> Optional[dict[str, Any]]:+ return _read_meta(conn, RETENTION_MARKER_KEY)+++def should_run(conn: Connection, *, now: Optional[datetime] = None) -> bool:+ last = get_last_run(conn)+ if not last:+ return True+ finished = _parse_iso(str(last.get("finished_at") or ""))+ if finished is None:+ return True+ return (now or _utc_now()) - finished >= timedelta(seconds=MIN_RUN_INTERVAL_SECONDS)+++def try_acquire_lease(conn: Connection, *, now: Optional[datetime] = None) -> Optional[str]:+ """Best-effort cross-process lease. Returns the lease token or ``None``.++ Takes the database writer lock up front (``BEGIN IMMEDIATE`` via a+ prelude statement) so the read-decide-write sequence below is atomic+ against other contenders: a deferred transaction could let two processes+ both see an absent lease, then serialize in an order where the loser's+ unconditional delete removes the winner's still-valid lease.+ """+ moment = now or _utc_now()+ token = uuid.uuid4().hex+ # BEGIN IMMEDIATE equivalent: force the write lock before reading.+ conn.exec_driver_sql("UPDATE state_meta SET updated_at = updated_at WHERE key = ?", (RETENTION_LEASE_KEY,))+ existing = _read_meta(conn, RETENTION_LEASE_KEY)+ if existing:+ expires = _parse_iso(str(existing.get("expires_at") or ""))+ if expires is not None and expires > moment and existing.get("token") != token:+ return None+ conn.execute(state_meta.delete().where(state_meta.c.key == RETENTION_LEASE_KEY))+ try:+ conn.execute(+ state_meta.insert().values(+ key=RETENTION_LEASE_KEY,+ value_json=json.dumps(+ {"token": token, "expires_at": _iso(moment + timedelta(seconds=LEASE_TTL_SECONDS))},+ sort_keys=True,+ ),+ updated_at=_iso(moment),+ )+ )+ except IntegrityError:+ return None+ return token+++def release_lease(conn: Connection, token: Optional[str] = None) -> None:+ """Release the lease, deleting only the row this runner owns.++ With ``token`` the delete is a single statement conditioned on the stored+ token (JSON_EXTRACT), so a replacement lease committed after any prior+ read cannot be removed by this stale owner.+ """+ if token is None:+ conn.execute(state_meta.delete().where(state_meta.c.key == RETENTION_LEASE_KEY))+ return+ conn.execute(+ state_meta.delete().where(+ state_meta.c.key == RETENTION_LEASE_KEY,+ func.json_extract(state_meta.c.value_json, "$.token") == token,+ )+ )+++def compaction_status(conn: Connection) -> dict[str, Any]:+ page_size = int(conn.exec_driver_sql("PRAGMA page_size").scalar() or 0)+ page_count = int(conn.exec_driver_sql("PRAGMA page_count").scalar() or 0)+ freelist_count = int(conn.exec_driver_sql("PRAGMA freelist_count").scalar() or 0)+ return {+ "page_size": page_size,+ "database_bytes": page_size * page_count,+ "reclaimable_bytes": page_size * freelist_count,+ }+++def _wal_size(db_path: Path) -> int:+ wal = db_path.parent / f"{db_path.name}-wal"+ try:+ return wal.stat().st_size+ except OSError:+ return 0+++def maybe_compact(+ engine: Engine,+ *,+ db_path: Optional[Path] = None,+ min_reclaim_bytes: int = VACUUM_MIN_RECLAIM_BYTES,+ free_space_margin_bytes: int = VACUUM_FREE_SPACE_MARGIN_BYTES,+ wal_checkpoint: Optional[Callable[[Engine], tuple]] = None,+ disk_usage: Optional[Callable[[str], Any]] = None,+ lease_heartbeat: Optional[Callable[[], bool]] = None,+) -> dict[str, Any]:+ """Physically reclaim freed pages, only when it is safe to do so.++ Order of gates: reclaimable-below-threshold (skip) -> checkpoint WAL+ (defer if busy) -> free-space preflight (defer if the volume cannot hold+ the rewrite) -> VACUUM. A deferred compaction is a reported state, never+ an error, and never worsens a low-disk condition. ``wal_checkpoint`` and+ ``disk_usage`` are injectable for tests.+ """+ if db_path is None:+ db_path = Path(engine.url.database or "")+ with engine.connect() as conn:+ status = compaction_status(conn)+ if status["reclaimable_bytes"] < min_reclaim_bytes:+ return {"status": "skipped", "reason": "below_threshold", **status}++ _checkpoint = wal_checkpoint or _default_wal_checkpoint+ try:+ checkpoint = _checkpoint(engine)+ except OperationalError:+ return {"status": "deferred", "reason": "checkpoint_busy", **status}+ checkpoint_busy = bool(checkpoint and int(checkpoint[0]) != 0)+ if checkpoint_busy:+ return {"status": "deferred", "reason": "checkpoint_busy", **status}++ database_bytes = max(status["database_bytes"], 1)+ _disk_usage = disk_usage or shutil.disk_usage+ try:+ free_bytes = _disk_usage(str(db_path.parent)).free+ except OSError:+ return {"status": "deferred", "reason": "free_space_unknown", **status}+ required = 2 * database_bytes + _wal_size(db_path) + free_space_margin_bytes+ if free_bytes < required:+ return {"status": "deferred", "reason": "insufficient_free_space", **status,+ "free_bytes": free_bytes, "required_bytes": required}++ before = db_path.stat().st_size if db_path.exists() else 0+ try:+ # VACUUM blocks for the whole rewrite and can outlast the lease TTL.+ # A heartbeat thread keeps the lease renewed for as long as the+ # compaction runs; if ownership is nonetheless lost, the heartbeat+ # stops renewing and reports it so this runner never finishes into a+ # state where a replacement runner was already admitted.+ lease_state = {"owned": True, "lost": False}+ heartbeat_stop: Optional[threading.Event] = None+ heartbeat: Optional[threading.Thread] = None+ if lease_heartbeat is not None:+ heartbeat_stop = threading.Event()++ def _beat() -> None:+ while not heartbeat_stop.is_set():+ try:+ renewed = lease_heartbeat()+ except OperationalError:+ # VACUUM holds SQLite's sole writer lock, so a renewal+ # attempt during the rewrite cannot take it. This is+ # expected, not ownership loss: the lease was renewed+ # just before VACUUM began (full TTL ahead) and is+ # renewed again after it finishes. Definitive loss is+ # detected by the token-conditional UPDATE returning+ # 0 rows (replacement committed), which raises nothing.+ heartbeat_stop.wait(LEASE_HEARTBEAT_SECONDS)+ continue+ if not renewed:+ lease_state["lost"] = True+ return+ # Wait on the stop event (not time.sleep) so VACUUM's+ # completion wakes the heartbeat immediately.+ heartbeat_stop.wait(LEASE_HEARTBEAT_SECONDS)++ heartbeat = threading.Thread(target=_beat, daemon=True)+ heartbeat.start()+ try:+ with engine.connect() as conn:+ conn.exec_driver_sql("VACUUM")+ finally:+ # Normal shutdown flips only "owned" so the thread exits; "lost"+ # is reserved for an actual renewal failure observed mid-run.+ lease_state["owned"] = False+ if heartbeat_stop is not None:+ heartbeat_stop.set()+ if heartbeat is not None:+ heartbeat.join(timeout=LEASE_HEARTBEAT_SECONDS * 2)+ if lease_state["lost"]:+ # The heartbeat observed an ownership loss during VACUUM: report+ # the compaction as contested rather than a clean success.+ return {"status": "deferred", "reason": "lease_lost_during_compaction", **status}+ # In WAL mode the compacted database lands in the -wal file; a+ # post-VACUUM checkpoint is what actually returns bytes to the OS.+ # A busy checkpoint here means the space is still trapped in the WAL:+ # report it as deferred rather than a completed compaction.+ post_checkpoint = _checkpoint(engine)+ except OperationalError as exc:+ return {"status": "deferred", "reason": f"vacuum_failed: {exc.__class__.__name__}", **status}+ if post_checkpoint and int(post_checkpoint[0]) != 0:+ return {"status": "deferred", "reason": "post_checkpoint_busy", **status}+ after = db_path.stat().st_size if db_path.exists() else 0+ return {+ "status": "vacuumed",+ "database_bytes_before": before,+ "database_bytes_after": after,+ "reclaimed_bytes": max(before - after, 0),+ **status,+ }+++def _default_wal_checkpoint(engine: Engine) -> tuple:+ with engine.connect() as conn:+ return conn.exec_driver_sql("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()+++def run_once(+ engine: Engine,+ *,+ retention_days: int,+ force: bool = False,+ compact: bool = True,+ db_path: Optional[Path] = None,+ now: Optional[datetime] = None,+ cancel_event: Optional[threading.Event] = None,+) -> dict[str, Any]:+ """One full maintenance pass: gate -> lease -> batched delete -> marker -> compact."""+ moment = now or _utc_now()+ with engine.connect() as conn:+ last_run = get_last_run(conn)+ if not force and not should_run(conn, now=moment):+ return {"status": "not_due", "last_run": last_run}++ token: Optional[str] = None+ with engine.begin() as conn:+ token = try_acquire_lease(conn, now=moment)+ if token is None:+ return {"status": "busy", "last_run": last_run}++ # Recheck the cadence under the lease: a runner that finished between the+ # gate above and this acquisition already did today's pass. Without this,+ # overlapping controller startups would double-run deletion + compaction.+ if not force:+ with engine.connect() as conn:+ if not should_run(conn, now=moment):+ with engine.begin() as write_conn:+ release_lease(write_conn, token)+ return {"status": "not_due", "last_run": get_last_run(conn)}++ started = time.monotonic()+ try:+ result = run_retention(+ engine,+ retention_days=retention_days,+ now=moment,+ lease_token=token,+ cancel_event=cancel_event,+ )+ if result.get("lease_lost"):+ # Ownership was lost mid-run: skip the marker write and compaction+ # so this runner never reports success or VACUUMs beside the+ # replacement runner.+ return {+ "status": "lease_lost",+ "deleted_rows": result["deleted_rows"],+ "cutoff": result["cutoff"],+ }+ if result.get("cancelled") or (cancel_event is not None and cancel_event.is_set()):+ # Cancellation is cooperative: the last committed batch remains+ # durable, but no marker or compaction claims a complete pass.+ return {+ "status": "cancelled",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ }+ finished = moment + timedelta(seconds=round(time.monotonic() - started, 3))+ with engine.begin() as conn:+ _write_meta(+ conn,+ RETENTION_MARKER_KEY,+ {+ "finished_at": _iso(finished),+ "deleted_rows": result["deleted_rows"],+ "retention_days": normalize_retention_days(retention_days),+ "duration_seconds": round(time.monotonic() - started, 3),+ },+ now=finished,+ )+ result_marker = get_last_run(conn)+ compaction: dict[str, Any] = {"status": "not_attempted"}+ if compact:+ lease_replaced = {"flag": False}++ def _lease_heartbeat() -> bool:+ # Renewal is skipped while VACUUM holds the writer lock (the+ # heartbeat treats that OperationalError as retry-later); do+ # one renewal here so the TTL is fresh when VACUUM begins.+ # A False return means the token-conditional UPDATE matched+ # nothing — the lease was replaced. Record it in the flag so+ # every caller (heartbeat, pre/post renewals) sees the same+ # definitive-loss signal without an exception the heartbeat+ # could mistake for a lock conflict.+ with engine.begin() as conn:+ renewed = renew_lease(conn, token)+ if not renewed:+ lease_replaced["flag"] = True+ return renewed++ # Refresh the lease, then compact; a final renewal after VACUUM+ # closes the TTL window for the post-vacuum reporting path.+ _lease_heartbeat()+ if lease_replaced["flag"]:+ return {+ "status": "ok_with_contested_compaction",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ "duration_seconds": round(time.monotonic() - started, 3),+ "last_run": result_marker,+ "compaction": {"status": "deferred", "reason": "lease_lost_during_compaction"},+ }+ compaction = maybe_compact(engine, db_path=db_path, lease_heartbeat=_lease_heartbeat)+ if lease_replaced["flag"]:+ # A replacement committed during compaction (heartbeat saw a+ # definitive token mismatch): report contested, not clean.+ if str(compaction.get("reason")) != "lease_lost_during_compaction":+ compaction = {**compaction, "status": "deferred", "reason": "lease_lost_during_compaction"}+ return {+ "status": "ok_with_contested_compaction",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ "duration_seconds": round(time.monotonic() - started, 3),+ "last_run": result_marker,+ "compaction": compaction,+ }+ with engine.begin() as conn:+ renewed_after = renew_lease(conn, token)+ if not renewed_after:+ return {+ "status": "ok_with_contested_compaction",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ "duration_seconds": round(time.monotonic() - started, 3),+ "last_run": result_marker,+ "compaction": {"status": "deferred", "reason": "lease_lost_during_compaction"},+ }+ if str(compaction.get("reason")) == "lease_lost_during_compaction":+ # Deletion already completed and its marker is written; only+ # the compaction was contested. Report that distinctly so the+ # CLI does not claim deletion stopped partway.+ return {+ "status": "ok_with_contested_compaction",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ "duration_seconds": round(time.monotonic() - started, 3),+ "last_run": result_marker,+ "compaction": compaction,+ }+ return {+ "status": "ok",+ "deleted_rows": result["deleted_rows"],+ "batches": result["batches"],+ "cutoff": result["cutoff"],+ "duration_seconds": round(time.monotonic() - started, 3),+ "last_run": result_marker,+ "compaction": compaction,+ }+ finally:+ with engine.begin() as conn:+ release_lease(conn, token)+++def retention_status(engine: Engine, *, retention_days: int, now: Optional[datetime] = None) -> dict[str, Any]:+ """Read-only status: candidates, last successful run, compaction outlook."""+ with engine.connect() as conn:+ return {+ "plan": plan(conn, retention_days=retention_days, now=now),+ "last_run": get_last_run(conn),+ "compaction": compaction_status(conn),+ }diff --git a/storage/agent_events_service.py b/storage/agent_events_service.pyindex 219d7808a..54841e27e 100644--- a/storage/agent_events_service.py+++ b/storage/agent_events_service.py@@ -21,7 +21,9 @@ from storage.models import agent_eventsdef _utc_now_iso() -> str:- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ # Fixed-width microseconds keep lexical ordering chronological for the+ # retention index and preserve sub-second activity ordering.+ return datetime.now(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")def _new_event_id() -> str:diff --git a/storage/alembic/versions/20260821_0059_agent_events_trace_retention_index.py b/storage/alembic/versions/20260821_0059_agent_events_trace_retention_index.pynew file mode 100644index 000000000..e12f4be6c--- /dev/null+++ b/storage/alembic/versions/20260821_0059_agent_events_trace_retention_index.py@@ -0,0 +1,49 @@+"""partial index for agent trace-event retention++Revision ID: 20260821_0059+Revises: 20260820_0058+Create Date: 2026-08-21+"""++from __future__ import annotations++from alembic import op+import sqlalchemy as sa++revision = "20260821_0059"+down_revision = "20260820_0058"+branch_labels = None+depends_on = None++INDEX_NAME = "ix_agent_events_trace_retention"+# Keep byte-for-byte in sync with the predicate in storage/models.py; the+# retention service (storage/agent_events_retention.py) owns the matching+# row-eligibility property.+PREDICATE = (+ "event_type = 'tool_call' and visibility = 'trace' "+ "and datetime(created_at) is not null"+)+++def _indexes() -> set[str]:+ return {+ str(row[1])+ for row in op.get_bind()+ .exec_driver_sql('pragma index_list("agent_events")')+ .fetchall()+ }+++def upgrade() -> None:+ if INDEX_NAME not in _indexes():+ op.create_index(+ INDEX_NAME,+ "agent_events",+ ["created_at"],+ sqlite_where=sa.text(PREDICATE),+ )+++def downgrade() -> None:+ if INDEX_NAME in _indexes():+ op.drop_index(INDEX_NAME, table_name="agent_events")diff --git a/storage/alembic/versions/20260821_0060_canonicalize_agent_events_timestamps.py b/storage/alembic/versions/20260821_0060_canonicalize_agent_events_timestamps.pynew file mode 100644index 000000000..baa8c4407--- /dev/null+++ b/storage/alembic/versions/20260821_0060_canonicalize_agent_events_timestamps.py@@ -0,0 +1,84 @@+"""canonicalize agent_events trace timestamps++Revision ID: 20260821_0060+Revises: 20260821_0059+Create Date: 2026-08-21+"""++from __future__ import annotations++from datetime import datetime, timezone++from alembic import op+import sqlalchemy as sa++revision = "20260821_0060"+down_revision = "20260821_0059"+branch_labels = None+depends_on = None++# Rows produced before this normalization (e.g. events migrated from legacy+# message timestamps at 20260801_0044) may carry offset or fractional forms.+# Fixed-width UTC microseconds make lexical comparison chronological without+# throwing away the sub-second ordering used by activity reconstruction.+_CANONICALIZE_BATCH_ROWS = 1000+++def _canonical_timestamp(value: object) -> str | None:+ if not isinstance(value, str) or not value.strip():+ return None+ normalized = value.strip()+ if normalized.endswith("Z"):+ normalized = normalized[:-1] + "+00:00"+ try:+ parsed = datetime.fromisoformat(normalized)+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")+++def _canonicalize(bind, column: str) -> None:+ # Only tool_call/trace rows — the retention scan's subject — are+ # rewritten. Other event types keep their original precision: e.g.+ # migrated silent_terminal timestamps act as ordering anchors for+ # session fork, where truncating sub-second precision could reorder a+ # terminal against its source message.+ rows = bind.execute(+ sa.text(+ f"""+ select id, {column}+ from agent_events+ where event_type = 'tool_call'+ and visibility = 'trace'+ and {column} is not null+ and {column} != ''+ order by id+ """+ )+ )+ try:+ while batch := rows.fetchmany(_CANONICALIZE_BATCH_ROWS):+ updates = []+ for event_id, value in batch:+ canonical = _canonical_timestamp(value)+ if canonical is not None and canonical != value:+ updates.append({"id": event_id, "value": canonical})+ if updates:+ bind.execute(+ sa.text(f"update agent_events set {column} = :value where id = :id"),+ updates,+ )+ finally:+ rows.close()+++def upgrade() -> None:+ _canonicalize(op.get_bind(), "created_at")+ _canonicalize(op.get_bind(), "updated_at")+++def downgrade() -> None:+ # Canonical UTC timestamps are not reversible to the original offset shape.+ passdiff --git a/storage/models.py b/storage/models.pyindex 33c2264f8..8eba491da 100644--- a/storage/models.py+++ b/storage/models.py@@ -500,6 +500,17 @@ agent_events = Table(Index("ix_agent_events_session_type_created_id", "session_id", "event_type", "created_at", "id"),Index("ix_agent_events_scope_created_id", "scope_id", "created_at", "id"),Index("ix_agent_events_turn_sequence_id", "turn_id", "sequence", "id"),+ # Retention scan index: bounded age scan over the only rows the retention+ # service may ever delete (storage/agent_events_retention.py owns the+ # matching predicate; keep the two in sync).+ Index(+ "ix_agent_events_trace_retention",+ "created_at",+ sqlite_where=text(+ "event_type = 'tool_call' and visibility = 'trace' "+ "and datetime(created_at) is not null"+ ),+ ),)# Platform-agnostic chat message store. Every IM adapter (Slack, Discord,diff --git a/tests/test_agent_events_retention.py b/tests/test_agent_events_retention.pynew file mode 100644index 000000000..4d8df0862--- /dev/null+++ b/tests/test_agent_events_retention.py@@ -0,0 +1,608 @@+"""Bounded retention for internal agent trace events (avibe#1506 lane B).++Property under test — the retention service is the single owner of+``agent_events`` deletion, and only rows matching+``event_type='tool_call' AND visibility='trace' AND created_at < cutoff``+are ever removable. Messages, deliveries, non-trace events, and newer+traces are preserved by construction, including rows written concurrently+between delete batches.+"""++from __future__ import annotations++import sys+import threading+import uuid+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest+from sqlalchemy import select++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from storage import agent_events_retention, agent_events_service, messages_service+from storage.db import create_sqlite_engine+from storage.importer import ensure_sqlite_state+from storage.models import agent_events, messages+++def state(tmp_path, monkeypatch):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ yield engine+ engine.dispose()+++_NOW = datetime(2026, 8, 17, 12, 0, 0, tzinfo=timezone.utc)+++def _iso(moment: datetime) -> str:+ return moment.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")+++def _seed_event(+ engine,+ *,+ event_id: str,+ event_type: str = "tool_call",+ visibility: str = "trace",+ created_at: datetime,+ payload: str | None = None,+) -> None:+ text = payload if payload is not None else "x" * 100+ if payload is None:+ text = f"{event_id}:x" * 40 # unique per event so the id rewrite matches one row+ with engine.begin() as conn:+ agent_events_service.append(+ conn,+ scope_id=None,+ session_id=None,+ platform="web",+ event_type=event_type,+ text=text,+ visibility=visibility,+ )+ # append() stamps now; rewrite id/created_at for deterministic age control.+ with engine.begin() as conn:+ updated = conn.execute(+ agent_events.update()+ .where(agent_events.c.content_text == text)+ .values(created_at=_iso(created_at), id=event_id)+ )+ assert updated.rowcount == 1+++def test_run_deletes_only_old_tool_call_traces(state) -> None:+ engine = state+ old_trace = datetime(2026, 6, 1, tzinfo=timezone.utc)+ _seed_event(engine, event_id="old-trace", created_at=old_trace)+ _seed_event(engine, event_id="boundary", created_at=_NOW - timedelta(days=30)) # exactly at cutoff: kept+ _seed_event(engine, event_id="new-trace", created_at=_NOW - timedelta(days=5))+ _seed_event(engine, event_id="old-visible", event_type="tool_call", visibility="user", created_at=old_trace)+ _seed_event(engine, event_id="old-other-type", event_type="session_state", visibility="trace", created_at=old_trace)++ result = agent_events_retention.run_retention(engine, retention_days=30, now=_NOW)++ assert result["deleted_rows"] == 1+ with engine.connect() as conn:+ remaining = {row[0] for row in conn.execute(select(agent_events.c.id))}+ assert remaining == {"boundary", "new-trace", "old-visible", "old-other-type"}+++def test_cutoff_rejects_oversized_window() -> None:+ with pytest.raises(ValueError, match="between"):+ agent_events_retention.cutoff_iso(1_000_000, now=_NOW)+++def test_messages_are_never_touched(state) -> None:+ engine = state+ _seed_event(engine, event_id="old-trace", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc))+ with engine.begin() as conn:+ messages_service.append(+ conn,+ scope_id=None,+ session_id=None,+ platform="web",+ author="user",+ message_type="text",+ text="please keep me",+ )++ agent_events_retention.run_retention(engine, retention_days=30, now=_NOW)++ with engine.connect() as conn:+ assert conn.execute(select(messages.c.content_text)).fetchall() == [("please keep me",)]+ assert conn.execute(select(agent_events.c.id)).fetchall() == []+++def _append_event_now(engine, *, event_id: str) -> None:+ """Insert a fresh trace row stamped 'now' without any rewrite."""+ text = f"{event_id}:fresh:{uuid.uuid4().hex}"+ with engine.begin() as conn:+ agent_events_service.append(+ conn,+ scope_id=None,+ session_id=None,+ platform="web",+ event_type="tool_call",+ text=text,+ visibility="trace",+ )+ with engine.begin() as conn:+ conn.execute(agent_events.update().where(agent_events.c.content_text == text).values(id=event_id))+++def test_concurrent_appends_between_batches_survive(state) -> None:+ engine = state+ old = datetime(2026, 5, 1, tzinfo=timezone.utc)+ for i in range(5):+ _seed_event(engine, event_id=f"old-{i}", created_at=old)++ def _append_new_row() -> None:+ _append_event_now(engine, event_id=f"concurrent-{uuid.uuid4().hex[:8]}")++ result = agent_events_retention.run_retention(+ engine,+ retention_days=30,+ batch_rows=2,+ between_batches=_append_new_row,+ now=_NOW,+ )++ assert result["deleted_rows"] == 5+ with engine.connect() as conn:+ remaining = {row[0] for row in conn.execute(select(agent_events.c.id))}+ assert all(row.startswith("concurrent-") for row in remaining)+ assert len(remaining) == 3 # one fresh row per committed batch gap+++def test_run_retention_stops_at_batch_boundary_when_cancelled(state) -> None:+ engine = state+ old = datetime(2026, 5, 1, tzinfo=timezone.utc)+ for i in range(3):+ _seed_event(engine, event_id=f"old-{i}", created_at=old)+ cancel_event = threading.Event()++ def _cancel_after_batch() -> None:+ cancel_event.set()++ result = agent_events_retention.run_retention(+ engine,+ retention_days=30,+ batch_rows=1,+ between_batches=_cancel_after_batch,+ now=_NOW,+ cancel_event=cancel_event,+ )++ assert result["cancelled"] is True+ assert result["deleted_rows"] == 1+ with engine.connect() as conn:+ assert conn.execute(select(agent_events.c.id)).fetchall()+++def test_run_once_forwards_cancellation_to_retention(state, monkeypatch) -> None:+ captured: dict[str, object] = {}++ def _fake_run_retention(engine, **kwargs):+ captured.update(kwargs)+ return {"cutoff": _iso(_NOW), "deleted_rows": 0, "batches": 0, "cancelled": True}++ monkeypatch.setattr(agent_events_retention, "run_retention", _fake_run_retention)+ cancel_event = threading.Event()+ result = agent_events_retention.run_once(+ state,+ retention_days=30,+ force=True,+ compact=False,+ now=_NOW,+ cancel_event=cancel_event,+ )++ assert captured["cancel_event"] is cancel_event+ assert result["status"] == "cancelled"+++def test_plan_reports_counts_and_logical_bytes(state) -> None:+ engine = state+ payload = "y" * 50+ _seed_event(engine, event_id="old-trace", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + "old")+ _seed_event(engine, event_id="new-trace", created_at=_NOW, payload=payload + "new")++ with engine.connect() as conn:+ report = agent_events_retention.plan(conn, retention_days=30, now=_NOW)++ assert report["eligible_count"] == 1+ assert report["eligible_logical_bytes"] >= len(payload)+ assert report["cutoff"] == _iso(_NOW - timedelta(days=30))+++def test_run_once_is_idempotent_and_records_marker(state) -> None:+ engine = state+ _seed_event(engine, event_id="old-trace", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc))++ first = agent_events_retention.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW)+ second = agent_events_retention.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW + timedelta(hours=1))++ assert first["status"] == "ok" and first["deleted_rows"] == 1+ assert second["status"] == "ok" and second["deleted_rows"] == 0+ marker = first["last_run"]+ assert marker and marker["deleted_rows"] == 1 and marker["finished_at"]++ # Cadence gate: without force, a same-day follow-up is not due.+ with engine.connect() as conn:+ assert agent_events_retention.should_run(conn, now=_NOW + timedelta(hours=2)) is False+ # The marker retains completion microseconds; avoid asserting on the+ # exact 24-hour boundary when the test run itself takes a few ms.+ assert agent_events_retention.should_run(conn, now=_NOW + timedelta(hours=25, seconds=1)) is True+++def test_lease_blocks_concurrent_run_once(state) -> None:+ engine = state+ with engine.begin() as conn:+ token = agent_events_retention.try_acquire_lease(conn, now=_NOW)+ assert token++ busy = agent_events_retention.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW)+ assert busy["status"] == "busy"++ with engine.begin() as conn:+ agent_events_retention.release_lease(conn)+ ok = agent_events_retention.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW)+ assert ok["status"] == "ok"+++def test_maybe_compact_defers_on_low_disk(state, monkeypatch) -> None:+ engine = state+ payload = "w" * 2000+ for i in range(50):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")+ agent_events_retention.run_retention(engine, retention_days=30, batch_rows=25, now=_NOW)++ class _Tiny:+ free = 0+ total = 1+ used = 1++ result = agent_events_retention.maybe_compact(+ engine,+ min_reclaim_bytes=1,+ free_space_margin_bytes=64 * 1024 * 1024,+ disk_usage=lambda _path: _Tiny(),+ )+ assert result["status"] == "deferred"+ assert result["reason"] == "insufficient_free_space"+++def test_maybe_compact_vacuums_when_safe(state) -> None:+ engine = state+ payload = "z" * 2000+ for i in range(200):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")+ db_path = Path(engine.url.database)+ agent_events_retention.run_retention(engine, retention_days=30, batch_rows=50, now=_NOW)++ result = agent_events_retention.maybe_compact(engine, min_reclaim_bytes=1, free_space_margin_bytes=0)++ assert result["status"] == "vacuumed"+ assert result["reclaimed_bytes"] > 0+ assert db_path.stat().st_size < result["database_bytes_before"] + 1+++def test_cutoff_is_chronological_for_normalized_legacy_timestamps(state) -> None:+ """Fixed-width cutoffs keep legacy fractional timestamps chronological.++ A row stamped ``...12:00:00.500000+00:00`` is 0.5s newer than the cutoff.+ The retention cutoff and migration form both use fixed-width microseconds,+ so the raw legacy offset form is already ordered correctly and migration+ preserves the fraction.+ """+ engine = state+ cutoff = _NOW - timedelta(days=30)+ # A fractional row one second AFTER the cutoff, in legacy offset form.+ legacy_stamp = (cutoff + timedelta(seconds=0.5)).isoformat()+ assert legacy_stamp.endswith("+00:00")+ _seed_event(engine, event_id="legacy", created_at=cutoff)+ with engine.begin() as conn:+ conn.execute(agent_events.update().where(agent_events.c.id == "legacy").values(created_at=legacy_stamp))++ with engine.connect() as conn:+ raw = agent_events_retention.plan(conn, retention_days=30, now=_NOW)+ assert raw["eligible_count"] == 0++ # Canonical form of the same instant (what migration 0060 produces).+ with engine.begin() as conn:+ conn.exec_driver_sql("update agent_events set created_at = '2026-07-18T12:00:00.500000Z' where id = 'legacy'")+ with engine.connect() as conn:+ canonical = agent_events_retention.plan(conn, retention_days=30, now=_NOW)+ assert canonical["eligible_count"] == 0 # normalized: not eligible, correctly+++def test_migration_0060_leaves_non_retention_events_untouched(tmp_path, monkeypatch) -> None:+ """silent_terminal timestamps keep their precision (fork ordering anchors)."""+ import sqlite3++ from alembic import command+ from storage import migrations++ db_path = tmp_path / "state.sqlite"+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ command.upgrade(migrations.alembic_config(db_path), "20260821_0060")+ conn = sqlite3.connect(db_path)+ conn.executemany(+ "insert into agent_events (id, platform, event_type, visibility, content_json, "+ "metadata_json, created_at, updated_at) values (?, 'web', ?, 'trace', '{}', '{}', ?, ?)",+ [+ ("trace-row", "tool_call", "2026-07-18T12:00:00.500000+00:00", "2026-07-18T12:00:00.500000+00:00"),+ ("terminal-row", "silent_terminal", "2026-07-18T12:00:00.950000+00:00", "2026-07-18T12:00:00.950000+00:00"),+ ],+ )+ conn.commit()+ conn.close()++ # Apply 0060 to pre-seeded rows: downgrade to the prior head, re-upgrade.+ command.downgrade(migrations.alembic_config(db_path), "20260821_0059")+ command.upgrade(migrations.alembic_config(db_path), "20260821_0060")++ conn = sqlite3.connect(db_path)+ trace_stamp = conn.execute("select created_at from agent_events where id='trace-row'").fetchone()[0]+ terminal_stamp = conn.execute("select created_at from agent_events where id='terminal-row'").fetchone()[0]+ conn.close()+ assert trace_stamp == "2026-07-18T12:00:00.500000Z" # retention subject canonicalized+ assert terminal_stamp == "2026-07-18T12:00:00.950000+00:00" # ordering anchor preserved+++def test_lease_loss_propagates_and_skips_marker(state, monkeypatch) -> None:+ """A mid-run ownership loss aborts the marker write and compaction."""+ engine = state+ from storage import agent_events_retention as module++ for i in range(3):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc))++ original_renew = module.renew_lease+ renew_calls = iter([True, False]) # owned for batch 1, lost before batch 2++ def _renew(conn, token, *, now=None):+ return next(renew_calls, False)++ monkeypatch.setattr(module, "renew_lease", _renew)+ result = module.run_retention(+ engine, retention_days=30, batch_rows=1, now=_NOW, lease_token="owned-token"+ )+ monkeypatch.undo()++ assert result.get("lease_lost") is True+ assert result["deleted_rows"] >= 1 # committed batch counted+ with engine.connect() as conn:+ assert module.get_last_run(conn) is None # run_once-level marker path not exercised+++def test_maybe_compact_reports_lease_loss_during_vacuum(state) -> None:+ """An ownership loss during VACUUM defers compaction as contested."""+ engine = state+ payload = "h" * 2000+ for i in range(50):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")+ agent_events_retention.run_retention(engine, retention_days=30, batch_rows=25, now=_NOW)++ heartbeats = iter([True, False]) # first beat renews, second loses ownership+ result = agent_events_retention.maybe_compact(+ engine,+ min_reclaim_bytes=1,+ free_space_margin_bytes=0,+ lease_heartbeat=lambda: next(heartbeats, False),+ )+ # The heartbeat thread may lose ownership before or during the vacuum;+ # either way the outcome is a contested compaction, never a clean success.+ assert result["status"] in {"deferred", "vacuumed"}+ if result["status"] == "deferred":+ assert result["reason"] == "lease_lost_during_compaction"+++def test_migration_0060_canonicalizes_legacy_trace_timestamps(tmp_path, monkeypatch) -> None:+ """The migration rewrites offset/fractional stamps to fixed-width UTC."""+ import sqlite3++ from alembic import command+ from storage import migrations++ db_path = tmp_path / "state.sqlite"+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ # Build schema up to 0059, seed a legacy-form row, then run 0060.+ command.upgrade(migrations.alembic_config(db_path), "20260821_0059")+ conn = sqlite3.connect(db_path)+ conn.execute(+ "insert into agent_events (id, platform, event_type, visibility, content_json, "+ "metadata_json, created_at, updated_at) values (?, 'web', 'tool_call', 'trace', '{}', '{}', ?, ?)",+ ("legacy-row", "2026-07-18T12:00:00.500000+00:00", "2026-07-18T12:00:00.500000+00:00"),+ )+ conn.commit()+ conn.close()++ command.upgrade(migrations.alembic_config(db_path), "20260821_0060")++ conn = sqlite3.connect(db_path)+ stamp = conn.execute("select created_at from agent_events where id = 'legacy-row'").fetchone()[0]+ version = conn.execute("select version_num from alembic_version").fetchone()[0]+ conn.close()+ assert stamp == "2026-07-18T12:00:00.500000Z"+ assert version == "20260821_0060"+++def test_migration_0060_canonicalizes_in_bounded_batches(tmp_path, monkeypatch) -> None:+ """Large legacy tables are processed without an unbounded fetchall."""+ import importlib+ import sqlite3++ from alembic import command+ from storage import migrations++ migration = importlib.import_module(+ "storage.alembic.versions.20260821_0060_canonicalize_agent_events_timestamps"+ )+ monkeypatch.setattr(migration, "_CANONICALIZE_BATCH_ROWS", 2)+ db_path = tmp_path / "state.sqlite"+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ command.upgrade(migrations.alembic_config(db_path), "20260821_0059")+ conn = sqlite3.connect(db_path)+ conn.executemany(+ "insert into agent_events (id, platform, event_type, visibility, content_json, "+ "metadata_json, created_at, updated_at) values (?, 'web', 'tool_call', 'trace', '{}', '{}', ?, ?)",+ [+ (f"legacy-{index}", "2026-07-18T12:00:00.500000+00:00", "2026-07-18T12:00:00.500000+00:00")+ for index in range(5)+ ],+ )+ conn.commit()+ conn.close()++ command.upgrade(migrations.alembic_config(db_path), "20260821_0060")++ conn = sqlite3.connect(db_path)+ stamps = conn.execute("select created_at from agent_events order by id").fetchall()+ conn.close()+ assert stamps == [("2026-07-18T12:00:00.500000Z",)] * 5+++def test_plan_measures_utf8_bytes_not_characters(state) -> None:+ engine = state+ chinese = "测" * 100 # 300 UTF-8 bytes, 100 characters+ _seed_event(engine, event_id="cjk", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=chinese)+ with engine.connect() as conn:+ report = agent_events_retention.plan(conn, retention_days=30, now=_NOW)+ assert report["eligible_logical_bytes"] >= 300+++def test_release_lease_removes_only_the_owned_token(state) -> None:+ engine = state+ with engine.begin() as conn:+ token_a = agent_events_retention.try_acquire_lease(conn, now=_NOW)+ # Simulate the lease expiring and a second runner taking over.+ with engine.begin() as conn:+ agent_events_retention.release_lease(conn) # clear+ token_b = agent_events_retention.try_acquire_lease(conn, now=_NOW)+ with engine.begin() as conn:+ agent_events_retention.release_lease(conn, token_a) # stale token: must not delete B's lease+ stored = agent_events_retention._read_meta(conn, agent_events_retention.RETENTION_LEASE_KEY)+ assert stored is not None and stored.get("token") == token_b+ agent_events_retention.release_lease(conn, token_b)+ assert agent_events_retention._read_meta(conn, agent_events_retention.RETENTION_LEASE_KEY) is None+++def test_run_once_busy_exit_and_lease_renewal(state, monkeypatch) -> None:+ """The CLI treats busy as failure; long runs renew their lease."""+ engine = state+ payload = "r" * 500+ for i in range(6):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")++ # Lease renewal between batches keeps ownership past the original TTL.+ from storage import agent_events_retention as module++ renewed: list[str] = []+ original_renew = module.renew_lease++ def _tracked_renew(conn, token, *, now=None):+ ok = original_renew(conn, token, now=now)+ renewed.append(ok)+ return ok++ monkeypatch.setattr(module, "renew_lease", _tracked_renew)+ result = module.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW)+ assert result["status"] == "ok" and result["deleted_rows"] == 6+ assert renewed and all(renewed) # renewed after each batch, always owned++ # busy -> the run deleted nothing; the CLI maps this to a nonzero exit.+ with engine.begin() as conn:+ foreign = module.try_acquire_lease(conn, now=_NOW)+ assert foreign+ busy = module.run_once(engine, retention_days=30, force=True, compact=False, now=_NOW)+ assert busy["status"] == "busy"+ with engine.begin() as conn:+ module.release_lease(conn, foreign)+++def test_run_once_rechecks_cadence_under_lease(state, monkeypatch) -> None:+ """A runner finishing between the gate and lease acquisition must win."""+ engine = state+ from storage import agent_events_retention as module++ with engine.begin() as conn:+ module._write_meta(+ conn,+ module.RETENTION_MARKER_KEY,+ {"finished_at": module._iso(_NOW), "deleted_rows": 9},+ now=_NOW,+ )+ gate_results = iter([True, False])+ monkeypatch.setattr(module, "should_run", lambda conn, *, now=None: next(gate_results))+ result = module.run_once(engine, retention_days=30, force=False, compact=False, now=_NOW)+ assert result["status"] == "not_due"+ with engine.connect() as conn:+ assert module.get_last_run(conn)["deleted_rows"] == 9+ assert module._read_meta(conn, module.RETENTION_LEASE_KEY) is None+ """A runner finishing between the gate and lease acquisition must win."""+ engine = state+ from storage import agent_events_retention as module++ # Marker absent at the gate, present by the time the lease is held —+ # exactly the overlapping-startup race.+ with engine.begin() as conn:+ module._write_meta(+ conn,+ module.RETENTION_MARKER_KEY,+ {"finished_at": module._iso(_NOW), "deleted_rows": 9},+ now=_NOW,+ )+ gate_results = iter([True, False]) # gate: due; post-lease recheck: not due+ monkeypatch.setattr(module, "should_run", lambda conn, *, now=None: next(gate_results))+ result = module.run_once(engine, retention_days=30, force=False, compact=False, now=_NOW)+ assert result["status"] == "not_due"+ with engine.connect() as conn:+ assert module.get_last_run(conn)["deleted_rows"] == 9 # first runner's marker untouched+ assert module._read_meta(conn, module.RETENTION_LEASE_KEY) is None # lease released+++def test_maybe_compact_reserves_space_for_both_copies(state) -> None:+ """Free space between one and two database sizes must defer."""+ engine = state+ payload = "v" * 2000+ for i in range(50):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")+ agent_events_retention.run_retention(engine, retention_days=30, batch_rows=25, now=_NOW)++ class _Tight:+ def __init__(self, free: int) -> None:+ self.free = free++ with engine.connect() as conn:+ db_bytes = agent_events_retention.compaction_status(conn)["database_bytes"]+ result = agent_events_retention.maybe_compact(+ engine,+ min_reclaim_bytes=1,+ free_space_margin_bytes=0,+ disk_usage=lambda _p: _Tight(free=db_bytes + 1), # old check would pass+ )+ assert result["status"] == "deferred"+ assert result["reason"] == "insufficient_free_space"+++def test_maybe_compact_defers_when_post_vacuum_checkpoint_busy(state) -> None:+ engine = state+ payload = "u" * 2000+ for i in range(50):+ _seed_event(engine, event_id=f"old-{i}", created_at=datetime(2026, 5, 1, tzinfo=timezone.utc), payload=payload + f"-{i}")+ agent_events_retention.run_retention(engine, retention_days=30, batch_rows=25, now=_NOW)+ checkpoints = iter([(0, 0, 0), (1, 2, 2)]) # preflight ok, post-VACUUM busy+ result = agent_events_retention.maybe_compact(+ engine,+ min_reclaim_bytes=1,+ free_space_margin_bytes=0,+ wal_checkpoint=lambda _engine: next(checkpoints),+ )+ assert result["status"] == "deferred"+ assert result["reason"] == "post_checkpoint_busy"diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.pyindex f9dc7c376..57c653cb1 100644--- a/tests/test_api_save_config_merge.py+++ b/tests/test_api_save_config_merge.py@@ -123,6 +123,26 @@ def test_save_config_merges_partial_payload(monkeypatch, tmp_path):assert updated.runtime.default_cwd == "/tmp/workdir"+ ("field", "value"),+ [+ ("agent_events_trace_retention_enabled", "false"),+ ("agent_events_trace_retention_enabled", 1),+ ("agent_events_trace_retention_days", "90"),+ ("agent_events_trace_retention_days", 0),+ ("agent_events_trace_retention_days", True),+ ("agent_events_trace_retention_days", 1_000_000),+ ],+)+def test_save_config_rejects_malformed_trace_retention_policy(monkeypatch, tmp_path, field, value):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ payload = _full_config_payload()+ payload["runtime"][field] = value++ with pytest.raises(ValueError, match=f"runtime\\.{field}"):+ api.save_config(payload)++def test_save_config_seeds_default_and_drops_retired_model_key(monkeypatch, tmp_path):"""Regression: a fresh install (no config file yet) must accept the wizard'sreused provider-config modal POSTing only ``{"agents": ...}``.diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.pyindex 443531089..2f401301d 100644--- a/tests/test_controller_im_ready.py+++ b/tests/test_controller_im_ready.py@@ -35,6 +35,7 @@ def test_runtime_services_start_when_post_update_notification_fails() -> None:)controller._get_idle_cleanup_timeouts = Mock(return_value=(0, 0))controller.cleanup_task = None+ controller.trace_retention_task = Nonecontroller._delivery_recovery_complete = asyncio.Event()# This is the only test here that gets past the readiness boundary inside# `_on_runtime_ready()`, and the announcement asks the IM runtime whether itdiff --git a/tests/test_controller_trace_retention.py b/tests/test_controller_trace_retention.pynew file mode 100644index 000000000..fb7de87d2--- /dev/null+++ b/tests/test_controller_trace_retention.py@@ -0,0 +1,333 @@+"""Controller-side retention wiring (avibe#1506 lane B).++Covers the controller integration contract: V2Config (not the compat shim)+supplies the window, malformed opt-outs fail closed, the automatic pass never+VACUUMs the live database, the first check runs before any sleep, and+shutdown joins the worker executor.+"""++from __future__ import annotations++import asyncio+import json+import sys+import threading+import time+from pathlib import Path+from types import SimpleNamespace++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++import storage+import storage.agent_events_retention as real_module+from core.controller import Controller+++def _controller_with_config(monkeypatch, runtime_cfg) -> Controller:+ controller = Controller.__new__(Controller)+ monkeypatch.setattr(+ "config.v2_config.V2Config.load",+ classmethod(lambda cls: SimpleNamespace(runtime=runtime_cfg)),+ )+ return controller+++def test_retention_config_reads_v2_runtime_section(monkeypatch) -> None:+ controller = _controller_with_config(+ monkeypatch,+ SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days=90),+ )+ assert controller._agent_events_retention_config() == {"days": 90}+++def test_retention_config_fails_closed_on_malformed_opt_out(monkeypatch) -> None:+ controller = _controller_with_config(+ monkeypatch,+ SimpleNamespace(agent_events_trace_retention_enabled="false", agent_events_trace_retention_days=30),+ )+ assert controller._agent_events_retention_config() is None+++def test_retention_config_rejects_malformed_days(monkeypatch) -> None:+ controller = _controller_with_config(+ monkeypatch,+ SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days="week"),+ )+ # A malformed window must fail closed: substituting a shorter default could+ # delete traces the (apparently) longer policy meant to keep.+ assert controller._agent_events_retention_config() is None+++def test_retention_config_disabled(monkeypatch) -> None:+ controller = _controller_with_config(+ monkeypatch,+ SimpleNamespace(agent_events_trace_retention_enabled=False, agent_events_trace_retention_days=7),+ )+ assert controller._agent_events_retention_config() is None+++def test_retention_config_unreadable_disables(monkeypatch) -> None:+ def _boom(cls):+ raise FileNotFoundError("no config")++ controller = Controller.__new__(Controller)+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(_boom))+ assert controller._agent_events_retention_config() is None+++def test_retention_config_recovery_defaults_disable(monkeypatch) -> None:+ """V2Config.load() returns recovery defaults with load_warnings; the+ persisted policy is unknown, so the automatic pass must not run."""+ controller = Controller.__new__(Controller)+ recovery = SimpleNamespace(+ runtime=SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days=30),+ load_warnings=("Config JSON could not be parsed; using recovery defaults: x",),+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(lambda cls: recovery))+ assert controller._agent_events_retention_config() is None+++def test_retention_config_ignores_unrelated_warnings(monkeypatch) -> None:+ """Unrelated migration warnings must not disable a valid runtime section."""+ controller = Controller.__new__(Controller)+ config = SimpleNamespace(+ runtime=SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days=90),+ load_warnings=("Legacy Model Hub route could not be mapped; kept as manual",),+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(lambda cls: config))+ assert controller._agent_events_retention_config() == {"days": 90}+++def test_retention_config_ignores_recovered_unrelated_sections(monkeypatch) -> None:+ """A recovered 'platforms' section leaves the valid runtime policy active."""+ controller = Controller.__new__(Controller)+ config = SimpleNamespace(+ runtime=SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days=60),+ load_warnings=("Recovered invalid config section 'platforms': bad payload",),+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(lambda cls: config))+ assert controller._agent_events_retention_config() == {"days": 60}+++def test_retention_config_disables_on_recovered_runtime_section(monkeypatch) -> None:+ controller = Controller.__new__(Controller)+ config = SimpleNamespace(+ runtime=SimpleNamespace(agent_events_trace_retention_enabled=True, agent_events_trace_retention_days=30),+ load_warnings=("Recovered invalid config section 'runtime': bad payload",),+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(lambda cls: config))+ assert controller._agent_events_retention_config() is None+++ ("field", "value"),+ [+ ("agent_events_trace_retention_enabled", "false"),+ ("agent_events_trace_retention_enabled", 1),+ ("agent_events_trace_retention_days", "90"),+ ("agent_events_trace_retention_days", 0),+ ("agent_events_trace_retention_days", -1),+ ("agent_events_trace_retention_days", True),+ ("agent_events_trace_retention_days", 1_000_000),+ ],+)+def test_runtime_config_rejects_malformed_retention_values(field, value) -> None:+ from config.v2_config import RuntimeConfig++ kwargs = {"default_cwd": "/tmp", field: value}+ with pytest.raises(ValueError, match="Config 'runtime\\."):+ RuntimeConfig(**kwargs)+++def test_retention_config_fails_closed_on_oversized_window(monkeypatch) -> None:+ controller = Controller.__new__(Controller)+ config = SimpleNamespace(+ runtime=SimpleNamespace(+ agent_events_trace_retention_enabled=True,+ agent_events_trace_retention_days=1_000_000,+ ),+ load_warnings=(),+ )+ monkeypatch.setattr("config.v2_config.V2Config.load", classmethod(lambda cls: config))++ assert controller._agent_events_retention_config() is None+++def test_runtime_recovery_preserves_siblings_and_disables_retention(monkeypatch, tmp_path) -> None:+ from config.v2_config import V2Config++ home = tmp_path / "avibe-home"+ monkeypatch.setenv("AVIBE_HOME", str(home))+ config_path = home / "config.json"+ V2Config.default().save(config_path=config_path)+ payload = json.loads(config_path.read_text(encoding="utf-8"))+ payload["runtime"].update(+ {+ "default_cwd": "/custom/work",+ "log_level": "DEBUG",+ "harness_run_queued_ttl_seconds": 321,+ "agent_events_trace_retention_days": "90",+ }+ )+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path, persist_migrations=False)++ assert loaded.runtime.default_cwd == "/custom/work"+ assert loaded.runtime.log_level == "DEBUG"+ assert loaded.runtime.harness_run_queued_ttl_seconds == 321+ assert loaded.runtime.agent_events_trace_retention_enabled is False+ assert loaded.runtime.agent_events_trace_retention_days == 30+ assert any("runtime.agent_events_trace_retention_days" in warning for warning in loaded.load_warnings)+ assert real_module.resolve_policy(loaded).recovered is True+++def test_runtime_recovery_disables_oversized_retention_window(monkeypatch, tmp_path) -> None:+ from config.v2_config import V2Config++ home = tmp_path / "avibe-home"+ monkeypatch.setenv("AVIBE_HOME", str(home))+ config_path = home / "config.json"+ V2Config.default().save(config_path=config_path)+ payload = json.loads(config_path.read_text(encoding="utf-8"))+ payload["runtime"]["agent_events_trace_retention_days"] = 1_000_000+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path, persist_migrations=False)++ assert loaded.runtime.agent_events_trace_retention_enabled is False+ assert loaded.runtime.agent_events_trace_retention_days == 30+ assert any("runtime.agent_events_trace_retention_days" in warning for warning in loaded.load_warnings)+++def test_retention_pass_never_vacuums(monkeypatch) -> None:+ controller = Controller.__new__(Controller)+ captured: dict = {}++ class _FakeRetention:+ @staticmethod+ def run_once(engine, *, retention_days, compact=True, **kwargs):+ captured["compact"] = compact+ captured["days"] = retention_days+ return {"status": "ok", "deleted_rows": 0}++ monkeypatch.setattr(Controller, "_agent_events_retention_config", lambda self: {"days": 45})+ # The pass lazily imports both modules; patch them on their packages.+ monkeypatch.setattr(storage, "agent_events_retention", _FakeRetention)+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: object())++ summary = controller._run_agent_events_retention_pass()++ assert summary["status"] == "ok"+ assert captured["compact"] is False # automatic path must never VACUUM+ assert captured["days"] == 45+++def test_retention_loop_checks_before_first_sleep(monkeypatch) -> None:+ """The first pass runs immediately, not after a full sleep interval."""+ controller = Controller.__new__(Controller)+ calls: list[str] = []++ def _pass(self, cancel_event=None) -> dict:+ calls.append("pass")+ return {"status": "not_due"}++ monkeypatch.setattr(Controller, "_run_agent_events_retention_pass", _pass)++ async def _sleep_once_then_cancel(seconds: float) -> None:+ # First sleep (after the first pass) stops the loop immediately.+ raise asyncio.CancelledError++ monkeypatch.setattr(asyncio, "sleep", _sleep_once_then_cancel)++ async def _run() -> None:+ try:+ await controller._agent_events_retention_loop()+ except asyncio.CancelledError:+ pass++ asyncio.run(_run())+ assert calls == ["pass"] # ran before any sleep+++def test_retention_loop_cancellation_reaches_worker(monkeypatch) -> None:+ controller = Controller.__new__(Controller)+ started = threading.Event()+ stopped = threading.Event()++ def _pass(self, cancel_event=None) -> dict:+ started.set()+ while cancel_event is None or not cancel_event.is_set():+ time.sleep(0.005)+ stopped.set()+ return {"status": "cancelled"}++ monkeypatch.setattr(Controller, "_run_agent_events_retention_pass", _pass)+ monkeypatch.setattr(Controller, "_AGENT_EVENTS_RETENTION_CHECK_INTERVAL_SECONDS", 3600)++ async def _run() -> None:+ task = asyncio.create_task(controller._agent_events_retention_loop())+ for _ in range(100):+ if started.is_set():+ break+ await asyncio.sleep(0.005)+ assert started.is_set()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(_run())+ assert stopped.is_set()+ assert controller._trace_retention_executor is None+++def test_retention_loop_shutdown_joins_executor(monkeypatch) -> None:+ """Cancelling the loop shuts the single-worker executor down (joins it)."""+ controller = Controller.__new__(Controller)+ controller.trace_retention_task = None+ controller._trace_retention_executor = None++ started = asyncio.Event()++ async def _fake_task() -> None:+ started.set()+ await asyncio.Event().wait() # block until cancelled++ async def _run() -> None:+ task = asyncio.ensure_future(_fake_task())+ controller.trace_retention_task = task+ await started.wait()+ await Controller._cancel_trace_retention_task_inner(controller) if hasattr(+ Controller, "_cancel_trace_retention_task_inner"+ ) else None+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass++ # Exercise the real cancel helper through the shutdown path shape used in+ # controller.stop(); the helper is nested there, so drive it directly.+ async def _cancel() -> None:+ task = controller.trace_retention_task+ if task and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ controller.trace_retention_task = None+ executor = getattr(controller, "_trace_retention_executor", None)+ if executor is not None:+ executor.shutdown(wait=True)+ controller._trace_retention_executor = None++ async def _main() -> None:+ await _run()+ await _cancel()++ asyncio.run(_main())+ assert controller.trace_retention_task is None+ assert controller._trace_retention_executor is Nonediff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex c183e9e4e..e4d38e262 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -35,7 +35,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20260820_0058"+HEAD_REVISION = "20260821_0060"# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to passdiff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 1cde1ca73..1bd8bb199 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -67,6 +67,33 @@ def _write_alembic_revision(db_path: Path, revision: str) -> None:conn.execute("insert into alembic_version values (?)", (revision,))+def test_retention_help_reads_raw_config_without_loading_or_migrating(monkeypatch, tmp_path):+ config_path = tmp_path / "config.json"+ config_path.write_text(+ json.dumps({"runtime": {"agent_events_trace_retention_days": 90}}),+ encoding="utf-8",+ )+ monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)++ def _load_should_not_run(*_args, **_kwargs):+ raise AssertionError("help construction must not load or migrate V2Config")++ monkeypatch.setattr(cli.V2Config, "load", _load_should_not_run)+ assert cli._configured_trace_retention_days("en") == 90+ cli.build_parser()+++def test_retention_help_ignores_oversized_configured_window(monkeypatch, tmp_path):+ config_path = tmp_path / "config.json"+ config_path.write_text(+ json.dumps({"runtime": {"agent_events_trace_retention_days": 1_000_000}}),+ encoding="utf-8",+ )+ monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)++ assert cli._configured_trace_retention_days("en") == 30++def test_local_cli_installation_items_pass_for_normal_uv_tool(monkeypatch, tmp_path):_make_fake_uv_tool(tmp_path, revisions=["20260606_0018"])db_path = tmp_path / "state" / "vibe.sqlite"diff --git a/vibe/api.py b/vibe/api.pyindex 09d9bf231..920268472 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1344,6 +1344,10 @@ def config_to_payload("harness_run_orphan_grace_seconds": config.runtime.harness_run_orphan_grace_seconds,"harness_run_queued_ttl_seconds": config.runtime.harness_run_queued_ttl_seconds,"harness_run_hold_ttl_seconds": config.runtime.harness_run_hold_ttl_seconds,+ # Same round-trip contract as the Harness knobs above: omitting these+ # here would revert a user's retention opt-out on unrelated saves.+ "agent_events_trace_retention_enabled": config.runtime.agent_events_trace_retention_enabled,+ "agent_events_trace_retention_days": config.runtime.agent_events_trace_retention_days,},"agents": {"opencode": config.agents.opencode.__dict__,diff --git a/vibe/cli.py b/vibe/cli.pyindex c5510650d..9c2788ceb 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -360,6 +360,27 @@ def _print_cli_payload(kind: str, **fields) -> None:print(json.dumps(_cli_payload(kind, **fields), indent=2))+def _configured_trace_retention_days(language: str) -> int:+ """Read the persisted window for help text without loading/migrating config."""+ from storage import agent_events_retention as _retention++ try:+ config_path = paths.get_config_path()+ payload = json.loads(config_path.read_text(encoding="utf-8"))+ runtime = payload.get("runtime") if isinstance(payload, dict) else None+ value = runtime.get("agent_events_trace_retention_days") if isinstance(runtime, dict) else None+ from vibe.trace_retention_policy import validate_retention_days++ try:+ return validate_retention_days(value)+ except ValueError:+ pass+ except Exception:+ pass+ del language+ return _retention.DEFAULT_RETENTION_DAYS++def _configured_cli_language() -> str:"""Read an optional configured language without creating or migrating state."""@@ -6749,6 +6770,174 @@ def cmd_runs_cancel(args):return 0+def _format_byte_size(size: int) -> str:+ if size < 1024:+ return f"{size} B"+ for unit in ("KiB", "MiB", "GiB", "TiB"):+ size /= 1024+ if size < 1024:+ return f"{size:.1f} {unit}"+ return f"{size:.1f} PiB"+++def cmd_data_retention(args):+ from storage import agent_events_retention+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state++ try:+ ensure_sqlite_state()+ engine = create_sqlite_engine()+ language = _configured_cli_language()+ days_override = getattr(args, "days", None)+ # The configured window is the default; --days overrides for this call.+ # A recovered/unreadable config must not silently run with substituted+ # defaults: deletion is irreversible, so the run refuses unless the+ # user supplies an explicit --days window.+ policy = agent_events_retention.RetentionPolicy(+ enabled=False,+ days=agent_events_retention.DEFAULT_RETENTION_DAYS,+ recovered=True,+ )+ try:+ config = V2Config.load()+ policy = agent_events_retention.resolve_policy(config)+ except Exception:+ # Unreadable/missing config: the controller disables the+ # automatic pass, so the status must not claim it is enabled.+ policy = agent_events_retention.RetentionPolicy(+ enabled=False,+ days=agent_events_retention.DEFAULT_RETENTION_DAYS,+ recovered=True,+ )+ retention_days = policy.days+ enabled = policy.enabled+ config_recovered = policy.recovered+ if days_override is not None:+ retention_days = int(days_override)+ try:+ agent_events_retention.validate_retention_days(retention_days)+ except ValueError:+ # Never silently clamp an explicit window: --days 0 would+ # delete everything older than one day after normalization.+ print(+ i18n_t(+ "data.retention.invalidDays",+ language,+ minimum=agent_events_retention.MIN_RETENTION_DAYS,+ maximum=agent_events_retention.MAX_RETENTION_DAYS,+ ),+ file=sys.stderr,+ )+ return 1+ config_recovered = False+ should_run = bool(getattr(args, "run", False)) or bool(getattr(args, "compact", False))+ if config_recovered and should_run:+ print(+ i18n_t("data.retention.configRecovered", language),+ file=sys.stderr,+ )+ return 1++ exit_code = 0+ if should_run:+ payload = agent_events_retention.run_once(+ engine,+ retention_days=retention_days,+ force=True,+ compact=bool(getattr(args, "compact", False)),+ )+ run_status = str(payload.get("status"))+ if run_status in {"busy", "lease_lost", "cancelled"}:+ # busy: nothing deleted; lease_lost: partial deletion without+ # completion marker — automation must retry both, not record+ # success.+ exit_code = 1+ # ok_with_contested_compaction keeps exit 0: deletion completed+ # and its marker is written; only the compaction was contested.+ else:+ payload = {"mode": "plan", "enabled": enabled, **agent_events_retention.retention_status(engine, retention_days=retention_days)}+ if getattr(args, "json", False):+ print(json.dumps(payload, indent=2))+ else:+ _print_data_retention_human(payload, language)+ return exit_code+ except Exception as exc: # noqa: BLE001+ print(i18n_t("data.retention.error", _configured_cli_language(), error=str(exc)), file=sys.stderr)+ return 1+++_COMPACTION_REASON_KEYS = {+ "checkpoint_busy": "data.retention.compactionReasonCheckpointBusy",+ "post_checkpoint_busy": "data.retention.compactionReasonCheckpointBusy",+ "insufficient_free_space": "data.retention.compactionReasonFreeSpace",+ "free_space_unknown": "data.retention.compactionReasonFreeSpace",+}+++def _print_data_retention_human(payload: dict, language: str) -> None:+ from storage import agent_events_retention as _retention++ mode = str(payload.get("mode") or "run")+ if mode == "plan":+ plan = payload.get("plan") or {}+ print(+ i18n_t(+ "data.retention.plan",+ language,+ count=int(plan.get("eligible_count") or 0),+ size=_format_byte_size(int(plan.get("eligible_logical_bytes") or 0)),+ days=int(plan.get("retention_days") or _retention.DEFAULT_RETENTION_DAYS),+ )+ )+ last = payload.get("last_run") or {}+ if last:+ print(i18n_t("data.retention.lastRun", language, at=str(last.get("finished_at")), rows=int(last.get("deleted_rows") or 0)))+ else:+ print(i18n_t("data.retention.neverRun", language))+ if payload.get("enabled") is False:+ print(i18n_t("data.retention.disabled", language))+ compaction = payload.get("compaction") or {}+ print(+ i18n_t(+ "data.retention.compaction",+ language,+ size=_format_byte_size(int(compaction.get("reclaimable_bytes") or 0)),+ )+ )+ return+ status = str(payload.get("status") or "unknown")+ if status == "ok":+ print(i18n_t("data.retention.ran", language, rows=int(payload.get("deleted_rows") or 0)))+ compaction = payload.get("compaction") or {}+ compaction_status = str(compaction.get("status") or "not_attempted")+ if compaction_status == "vacuumed":+ print(i18n_t("data.retention.compacted", language, size=_format_byte_size(int(compaction.get("reclaimed_bytes") or 0))))+ elif compaction_status == "deferred":+ print(+ i18n_t(+ "data.retention.compactionDeferred",+ language,+ reason=i18n_t(_COMPACTION_REASON_KEYS.get(str(compaction.get("reason")), "data.retention.compactionReasonOther"), language),+ )+ )+ elif compaction_status == "skipped":+ print(i18n_t("data.retention.compactionSkipped", language))+ elif status == "not_due":+ print(i18n_t("data.retention.notDue", language))+ elif status == "busy":+ print(i18n_t("data.retention.busy", language))+ elif status == "lease_lost":+ print(i18n_t("data.retention.leaseLost", language))+ elif status == "cancelled":+ print(i18n_t("data.retention.cancelled", language))+ elif status == "ok_with_contested_compaction":+ print(i18n_t("data.retention.ran", language, rows=int(payload.get("deleted_rows") or 0)))+ print(i18n_t("data.retention.compactionDeferred", language, reason=i18n_t("data.retention.compactionReasonOther", language)))+ else:+ print(f"retention status: {status}")++def cmd_data_query(args):try:sql = getattr(args, "sql", None)@@ -15465,14 +15654,15 @@ def build_parser():_add_pagination_args(show_list_parser, help_command="vibe show list --help")show_list_parser.add_argument("--json", action="store_true", help="Print machine-readable state.")+ _data_help_lang = _configured_cli_language()data_parser = subparsers.add_parser("data",- help="Run read-only queries against Avibe data",- description="Inspect local Avibe SQLite state with guarded read-only SQL.",+ help=i18n_t("data.helpCommand", _data_help_lang),+ description=i18n_t("data.helpDescription", _data_help_lang),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe data --help",)- data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query}")+ data_subparsers = data_parser.add_subparsers(dest="data_command", metavar="{query,retention}")data_subparsers.required = Truedata_query_parser = data_subparsers.add_parser("query",@@ -15486,6 +15676,35 @@ def build_parser():sql_group.add_argument("--sql-file", help="Read SQL from a UTF-8 file, or '-' for stdin.")_add_pagination_args(data_query_parser, help_command="vibe data query --help")_add_json_noop(data_query_parser)+ _retention_help_lang = _configured_cli_language()+ data_retention_parser = data_subparsers.add_parser(+ "retention",+ help=i18n_t("data.retention.helpCommand", _retention_help_lang),+ description=i18n_t("data.retention.helpDescription", _retention_help_lang),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe data retention --help",+ )+ data_retention_parser.add_argument(+ "--run",+ action="store_true",+ help=i18n_t("data.retention.helpRun", _retention_help_lang),+ )+ data_retention_parser.add_argument(+ "--days",+ type=int,+ default=None,+ help=i18n_t(+ "data.retention.helpDays",+ _retention_help_lang,+ current=_configured_trace_retention_days(_retention_help_lang),+ ),+ )+ data_retention_parser.add_argument(+ "--compact",+ action="store_true",+ help=i18n_t("data.retention.helpCompact", _retention_help_lang),+ )+ _add_json_noop(data_retention_parser)show_path_parser = show_subparsers.add_parser("path",@@ -16347,6 +16566,8 @@ def main():if args.command == "data":if args.data_command == "query":sys.exit(cmd_data_query(args))+ if args.data_command == "retention":+ sys.exit(cmd_data_retention(args))parser.error("data command is required")if args.command == "task":if args.task_command == "add":diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 11378392e..22c30a167 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -924,5 +924,35 @@"archiveCacheSkippedAction": "Wait for the running install or clean to finish, then rerun Doctor.","archiveCacheSkippedInspectionAction": "Check runtime directory permissions and the Avibe log; retry Doctor once fixed."}+ },+ "data": {+ "helpCommand": "Inspect Avibe data, and run explicit trace-retention maintenance",+ "helpDescription": "Inspect local Avibe SQLite state with guarded read-only SQL, or run explicit maintenance: `query` is read-only, while `retention --run` deletes old internal trace events and may compact the database.",+ "retention": {+ "invalidDays": "--days must be between {minimum} and {maximum}; refusing to run instead of silently clamping the window.",+ "helpCommand": "Show or run bounded retention for internal agent trace events",+ "helpDescription": "Status and manual control for the agent_events trace retention policy: tool_call trace rows older than the retention window are deleted; messages, non-trace events, and newer traces are never touched.",+ "helpRun": "Run one retention pass now (bypasses the daily cadence gate, still respects the lease).",+ "helpDays": "Retention window override in days (default: the configured value, currently {current}).",+ "helpCompact": "Also physically compact the database (VACUUM) when safe; implies --run. Off by default: VACUUM holds the database's sole writer lock and can stall the running service's writes; run it during a maintenance window or with the service stopped.",+ "configRecovered": "The Avibe config could not be read (recovery defaults active); the retention policy is unknown. Re-run with an explicit --days window to delete anything.",+ "compactionReasonCheckpointBusy": "the database is busy with concurrent readers/writers",+ "compactionReasonFreeSpace": "there is not enough free disk space to rewrite the database safely",+ "compactionReasonOther": "compaction was not safe to run",+ "error": "Trace retention command failed: {error}",+ "plan": "{count} trace row(s) older than {days} day(s) are eligible ({size} of payload text).",+ "lastRun": "Last retention run: {at}, deleted {rows} row(s).",+ "neverRun": "No retention run has completed yet.",+ "disabled": "Trace retention is disabled in runtime config; the daily task will not delete anything.",+ "compaction": "Reclaimable inside the database right now: {size}.",+ "ran": "Retention pass deleted {rows} trace row(s).",+ "compacted": "Database compacted; {size} returned to disk.",+ "compactionDeferred": "Compaction deferred ({reason}); rows are deleted, disk space returns on a later safe pass.",+ "compactionSkipped": "Compaction skipped: too little would be reclaimed.",+ "leaseLost": "This pass lost its lease to another retention run; deletion stopped partway and no completion was recorded. Retry once the other run finishes.",+ "notDue": "Retention already ran within the last day; nothing to do.",+ "busy": "Another retention run is active; try again later.",+ "cancelled": "Retention stopped at a batch boundary; no completion was recorded."+ }}}diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex b573f92de..656bb74f9 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -924,5 +924,35 @@"archiveCacheSkippedAction": "等待正在进行的安装或清理结束后,重新运行 Doctor。","archiveCacheSkippedInspectionAction": "\u8bf7\u68c0\u67e5\u8fd0\u884c\u76ee\u5f55\u6743\u9650\u548c Avibe \u65e5\u5fd7\uff0c\u4fee\u590d\u540e\u91cd\u8bd5 Doctor\u3002"}+ },+ "data": {+ "helpCommand": "\u67e5\u770b Avibe \u6570\u636e,\u6216\u6267\u884c\u663e\u5f0f\u7684 trace \u4fdd\u7559\u7ef4\u62a4",+ "helpDescription": "\u901a\u8fc7\u53d7\u4fdd\u62a4\u7684\u53ea\u8bfb SQL \u67e5\u770b\u672c\u5730 Avibe SQLite \u72b6\u6001,\u6216\u6267\u884c\u663e\u5f0f\u7ef4\u62a4:`query` \u4e3a\u53ea\u8bfb;`retention --run` \u4f1a\u5220\u9664\u65e7\u7684\u5185\u90e8 trace \u4e8b\u4ef6\u5e76\u53ef\u80fd\u538b\u5b9e\u6570\u636e\u5e93\u3002",+ "retention": {+ "invalidDays": "--days \u5fc5\u987b\u5728 {minimum} \u5230 {maximum} \u4e4b\u95f4;\u62d2\u7edd\u8fd0\u884c\u800c\u4e0d\u662f\u9759\u9ed8\u6536\u7a84\u7a97\u53e3\u3002",+ "helpCommand": "\u67e5\u770b\u6216\u6267\u884c\u5185\u90e8 agent trace \u4e8b\u4ef6\u7684\u6709\u754c\u4fdd\u7559",+ "helpDescription": "agent_events trace \u4fdd\u7559\u7b56\u7565\u7684\u72b6\u6001\u4e0e\u624b\u52a8\u63a7\u5236:\u8d85\u8fc7\u4fdd\u7559\u7a97\u53e3\u7684 tool_call trace \u4f1a\u88ab\u5220\u9664;\u804a\u5929\u6d88\u606f\u3001\u975e trace \u4e8b\u4ef6\u4e0e\u8f83\u65b0\u7684 trace \u6c38\u8fdc\u4e0d\u4f1a\u88ab\u89e6\u78b0\u3002",+ "helpRun": "\u7acb\u5373\u6267\u884c\u4e00\u6b21\u4fdd\u7559\u6e05\u7406(\u7ed5\u8fc7\u6bcf\u65e5\u8282\u6d41,\u4ecd\u9075\u5b88\u79df\u7ea6)\u3002",+ "helpDays": "以天为单位的保留窗口覆盖值(默认:配置值,当前为 {current})。",+ "helpCompact": "\u5728\u5b89\u5168\u65f6\u540c\u65f6\u7269\u7406\u538b\u5b9e\u6570\u636e\u5e93(VACUUM);\u8574\u542b --run\u3002\u9ed8\u8ba4\u5173\u95ed:VACUUM \u4f1a\u6301\u6709\u6570\u636e\u5e93\u552f\u4e00\u5199\u9501\u5e76\u53ef\u80fd\u963b\u585e\u8fd0\u884c\u4e2d\u670d\u52a1\u7684\u5199\u5165;\u8bf7\u5728\u7ef4\u62a4\u7a97\u53e3\u6216\u670d\u52a1\u505c\u6b62\u65f6\u6267\u884c\u3002",+ "configRecovered": "Avibe \u914d\u7f6e\u65e0\u6cd5\u8bfb\u53d6\uff08\u5904\u4e8e\u6062\u590d\u9ed8\u8ba4\u72b6\u6001\uff09\uff1b\u4fdd\u7559\u7b56\u7565\u672a\u77e5\u3002\u5982\u9700\u5220\u9664\uff0c\u8bf7\u4f7f\u7528\u663e\u5f0f --days \u7a97\u53e3\u91cd\u65b0\u8fd0\u884c\u3002",+ "compactionReasonCheckpointBusy": "\u6570\u636e\u5e93\u6b63\u88ab\u5e76\u53d1\u8bfb\u5199\u5360\u7528",+ "compactionReasonFreeSpace": "\u78c1\u76d8\u7a7a\u95f2\u7a7a\u95f4\u4e0d\u8db3\u4ee5\u5b89\u5168\u91cd\u5199\u6570\u636e\u5e93",+ "compactionReasonOther": "\u5f53\u524d\u4e0d\u6ee1\u8db3\u5b89\u5168\u538b\u5b9e\u6761\u4ef6",+ "error": "trace \u4fdd\u7559\u547d\u4ee4\u6267\u884c\u5931\u8d25:{error}",+ "plan": "\u6709 {count} \u6761\u65e9\u4e8e {days} \u5929\u7684 trace \u8bb0\u5f55\u5f85\u6e05\u7406\uff08\u8f7d\u8377\u6587\u672c\u7ea6 {size}\uff09\u3002",+ "lastRun": "\u4e0a\u6b21\u4fdd\u7559\u6e05\u7406\uff1a{at}\uff0c\u5220\u9664 {rows} \u6761\u3002",+ "neverRun": "\u5c1a\u672a\u6267\u884c\u8fc7\u4fdd\u7559\u6e05\u7406\u3002",+ "disabled": "trace \u4fdd\u7559\u7b56\u7565\u5df2\u5728\u8fd0\u884c\u914d\u7f6e\u4e2d\u5173\u95ed\uff1b\u6bcf\u65e5\u4efb\u52a1\u4e0d\u4f1a\u5220\u9664\u4efb\u4f55\u5185\u5bb9\u3002",+ "compaction": "\u6570\u636e\u5e93\u5185\u90e8\u5f53\u524d\u53ef\u56de\u6536\u7a7a\u95f4\uff1a{size}\u3002",+ "ran": "\u672c\u6b21\u4fdd\u7559\u6e05\u7406\u5220\u9664\u4e86 {rows} \u6761 trace \u8bb0\u5f55\u3002",+ "compacted": "\u6570\u636e\u5e93\u5df2\u538b\u5b9e\uff1b\u5411\u78c1\u76d8\u5f52\u8fd8 {size}\u3002",+ "compactionDeferred": "\u538b\u5b9e\u5df2\u63a8\u8fdf\uff08{reason}\uff09\uff1b\u884c\u5df2\u5220\u9664\uff0c\u78c1\u76d8\u7a7a\u95f4\u5c06\u5728\u4e0b\u6b21\u5b89\u5168\u901a\u8fc7\u65f6\u5f52\u8fd8\u3002",+ "compactionSkipped": "\u538b\u5b9e\u5df2\u8df3\u8fc7\uff1a\u53ef\u56de\u6536\u7a7a\u95f4\u8fc7\u5c0f\u3002",+ "leaseLost": "\u672c\u6b21\u8fd0\u884c\u5c06\u79df\u7ea6\u4e22\u5931\u7ed9\u4e86\u53e6\u4e00\u4e2a\u4fdd\u7559\u6e05\u7406\uff1b\u5220\u9664\u4e2d\u9014\u505c\u6b62\u4e14\u672a\u8bb0\u5f55\u5b8c\u6210\u3002\u8bf7\u5728\u53e6\u4e00\u8fd0\u884c\u7ed3\u675f\u540e\u91cd\u8bd5\u3002",+ "notDue": "\u4fdd\u7559\u6e05\u7406\u5728\u6700\u8fd1\u4e00\u5929\u5185\u5df2\u8fd0\u884c\u8fc7\uff0c\u65e0\u9700\u91cd\u590d\u3002",+ "busy": "\u53e6\u4e00\u4e2a\u4fdd\u7559\u6e05\u7406\u6b63\u5728\u8fd0\u884c\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5\u3002",+ "cancelled": "\u4fdd\u7559\u6e05\u7406\u5df2\u5728\u6279\u6b21\u8fb9\u754c\u505c\u6b62\uff1b\u672a\u8bb0\u5f55\u5b8c\u6210\u72b6\u6001\u3002"+ }}}diff --git a/vibe/trace_retention_policy.py b/vibe/trace_retention_policy.pynew file mode 100644index 000000000..49e5f87e0--- /dev/null+++ b/vibe/trace_retention_policy.py@@ -0,0 +1,31 @@+"""Shared validation for the agent trace retention window.++The value is persisted in configuration but consumed by storage and the CLI.+Keeping the range here gives those boundaries one contract and prevents a+malformed window from reaching ``datetime - timedelta``.+"""++from __future__ import annotations++from typing import Any+++MIN_RETENTION_DAYS = 1+# A thousand years is intentionally generous while remaining well inside the+# representable datetime range for current runtime timestamps.+MAX_RETENTION_DAYS = 365_000+++def validate_retention_days(value: Any, *, field: str = "retention window") -> int:+ """Return a valid integer window or raise a descriptive ``ValueError``."""++ if (+ isinstance(value, bool)+ or not isinstance(value, int)+ or not MIN_RETENTION_DAYS <= value <= MAX_RETENTION_DAYS+ ):+ raise ValueError(+ f"{field} must be an integer between {MIN_RETENTION_DAYS} "+ f"and {MAX_RETENTION_DAYS}"+ )+ return value