Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(runtime): bound local logs and state backups (#854)
Call White21d4d2db3e62
diff --git a/docs/plans/local-data-lifecycle.md b/docs/plans/local-data-lifecycle.mdnew file mode 100644index 000000000..89393b82c--- /dev/null+++ b/docs/plans/local-data-lifecycle.md@@ -0,0 +1,39 @@+# Local Data Lifecycle++## Background++Ordinary Avibe service operation can produce application logs, raw subprocess+logs, and migration backups. These are Avibe-owned diagnostic or rollback+artifacts, but their previous lifecycle was either unbounded or only manual.+User-owned attachments, Show Pages, and conversation data are outside this+policy.++The Show Runtime install cache is handled by the separate+`fix/show-runtime-install-gc` lane. This change does not touch Show Runtime+downloads, sources, prebuilt assets, or version directories.++## Policy++- Rotate `vibe_remote.log` at 20 MiB and retain five rotated files. Stdout+ logging keeps its existing foreground/background behavior.+- Route each raw service/UI stdout or stderr stream through a dedicated bounded+ log sink. The sink is the file's single writer and compacts it in place after+ 10 MiB, retaining the newest 5 MiB. This preserves the inode used by live tail+ readers and avoids racing a subprocess that is actively appending output.+- Before an existing SQLite database advances to another schema revision,+ create a consistent SQLite online backup. Retain the newest two SQLite+ migration/repair rollback points and the newest three legacy JSON migration+ snapshots.+- Prune only strict Avibe formats: self-identifying managed backup directories,+ historical `sqlite-state-migration-*` directories with valid manifests, and+ the exact legacy `vibe-pre-<revision>[-release-head]-repair-<timestamp>` file+ family. Unknown files, symlinks, partial backups, active database files, WAL,+ SHM, attachments, and Show Pages are never candidates.++## Validation++- Logging handler tests cover rotation limits and stdout preservation.+- Runtime tests cover in-place tail preservation, symlink refusal, continuous+ size bounds, and spawn integration.+- Backup tests cover SQLite consistency, per-kind retention, legacy companion+ cleanup, unknown-file preservation, and active DB/WAL/SHM preservation.diff --git a/main.py b/main.pyindex 0067e939b..68cb559ee 100644--- a/main.py+++ b/main.py@@ -5,9 +5,11 @@ import osimport signalimport sysimport logging+from logging.handlers import RotatingFileHandlerfrom typing import Anyfrom config.paths import ensure_data_dirs, get_logs_dir+from vibe.logging_config import APPLICATION_LOG_BACKUP_COUNT, APPLICATION_LOG_MAX_BYTESfrom vibe.runtime import (ServiceAlreadyRunningError,acquire_service_instance_lock,@@ -18,7 +20,13 @@ from vibe.runtime import (def _build_logging_handlers(logs_dir: str) -> list[logging.Handler]:- handlers: list[logging.Handler] = [logging.FileHandler(f"{logs_dir}/vibe_remote.log")]+ handlers: list[logging.Handler] = [+ RotatingFileHandler(+ f"{logs_dir}/vibe_remote.log",+ maxBytes=APPLICATION_LOG_MAX_BYTES,+ backupCount=APPLICATION_LOG_BACKUP_COUNT,+ )+ ]if os.environ.get("VIBE_DISABLE_STDOUT_LOGGING", "").lower() not in {"1", "true", "yes"}:handlers.insert(0, logging.StreamHandler(sys.stdout))return handlersdiff --git a/scripts/docker-entrypoint.sh b/scripts/docker-entrypoint.shindex ad792e5c9..1093d0afb 100755--- a/scripts/docker-entrypoint.sh+++ b/scripts/docker-entrypoint.sh@@ -18,14 +18,15 @@ start_ui_process() {local ui_stderr="$runtime_dir/ui_stderr.log"echo "Starting UI server on 0.0.0.0:${VIBE_UI_PORT:-5123}..." >&2- python -c "+ (+ exec python -c "from vibe.ui_server import run_ui_serverrun_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})-" >>"$ui_stdout" 2>>"$ui_stderr" &+" > >(python -m vibe.log_sink "$ui_stdout") 2> >(python -m vibe.log_sink "$ui_stderr")+ ) >/dev/null 2>&1 &- local ui_pid=$!- echo "$ui_pid" > "$runtime_dir/vibe-ui.pid"- echo "$ui_pid"+ UI_PID=$!+ echo "$UI_PID" > "$runtime_dir/vibe-ui.pid"}resolve_runtime_dir() {@@ -198,7 +199,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})mkdir -p "$RUNTIME_DIR"echo "$SERVICE_PID" > "$RUNTIME_DIR/vibe.pid"- UI_PID="$(start_ui_process "$RUNTIME_DIR")"+ start_ui_process "$RUNTIME_DIR"write_runtime_status "running" "started" "$SERVICE_PID" "$UI_PID"@@ -211,7 +212,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})SERVICE_PID="$(ensure_service_pid "$RUNTIME_DIR" "${SERVICE_PID:-}" "${CURRENT_UI_PID:-$UI_PID}")"if [ -z "$CURRENT_UI_PID" ]; then- UI_PID="$(start_ui_process "$RUNTIME_DIR")"+ start_ui_process "$RUNTIME_DIR"CURRENT_STATE="$(read_runtime_state "$RUNTIME_DIR" 2>/dev/null || true)"if [ -z "$CURRENT_STATE" ]; thenif [ -n "${SERVICE_PID:-}" ]; then@@ -225,7 +226,7 @@ run_ui_server('0.0.0.0', ${VIBE_UI_PORT:-5123})UI_EXIT_CODE=0wait "$CURRENT_UI_PID" 2>/dev/null || UI_EXIT_CODE=$?echo "UI server exited unexpectedly (code: ${UI_EXIT_CODE:-unknown}), restarting..."- UI_PID="$(start_ui_process "$RUNTIME_DIR")"+ start_ui_process "$RUNTIME_DIR"CURRENT_STATE="$(read_runtime_state "$RUNTIME_DIR" 2>/dev/null || true)"if [ -z "$CURRENT_STATE" ]; thenif [ -n "${SERVICE_PID:-}" ]; thendiff --git a/storage/backups.py b/storage/backups.pynew file mode 100644index 000000000..e5f01627c--- /dev/null+++ b/storage/backups.py@@ -0,0 +1,250 @@+from __future__ import annotations++import json+import logging+import os+import re+import shutil+import sqlite3+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Iterable+++logger = logging.getLogger(__name__)++JSON_STATE_BACKUP_RETENTION = 3+SQLITE_BACKUP_RETENTION = 2+BACKUP_MANIFEST_VERSION = 1++_JSON_BACKUP_RE = re.compile(+ r"^sqlite-state-migration-(?P<timestamp>\d{8}T\d{6}Z)(?:-(?P<suffix>\d+))?$"+)+_SQLITE_BACKUP_RE = re.compile(+ r"^avibe-sqlite-migration-(?P<timestamp>\d{8}T\d{6}Z)(?:-(?P<suffix>\d+))?$"+)+_LEGACY_SQLITE_REPAIR_RE = re.compile(+ r"^vibe-pre-(?:live-)?\d{4}(?:-release-head)?-repair-"+ r"(?P<timestamp>\d{8}T\d{6}Z)\.sqlite$"+)+++@dataclass(frozen=True)+class _BackupCandidate:+ root: Path+ companions: tuple[Path, ...]+ kind: str+ timestamp: datetime+ suffix: int++ @property+ def order_key(self) -> tuple[datetime, int, str]:+ return self.timestamp, self.suffix, self.root.name+++def _parse_timestamp(value: str) -> datetime | None:+ try:+ return datetime.strptime(value, "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)+ except ValueError:+ return None+++def _read_manifest(path: Path) -> dict | None:+ if path.is_symlink():+ return None+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ return payload if isinstance(payload, dict) else None+++def _directory_candidate(path: Path) -> _BackupCandidate | None:+ if path.is_symlink() or not path.is_dir():+ return None++ json_match = _JSON_BACKUP_RE.fullmatch(path.name)+ sqlite_match = _SQLITE_BACKUP_RE.fullmatch(path.name)+ match = json_match or sqlite_match+ if match is None:+ return None++ manifest = _read_manifest(path / "manifest.json")+ if manifest is None:+ return None++ if json_match is not None:+ is_current_manifest = (+ manifest.get("managed_by") == "avibe"+ and manifest.get("kind") == "json-state-migration"+ and manifest.get("schema_version") == BACKUP_MANIFEST_VERSION+ )+ is_legacy_manifest = isinstance(manifest.get("created_at"), str) and isinstance(manifest.get("files"), dict)+ if not (is_current_manifest or is_legacy_manifest):+ return None+ kind = "json"+ else:+ if not (+ manifest.get("managed_by") == "avibe"+ and manifest.get("kind") == "sqlite-migration"+ and manifest.get("schema_version") == BACKUP_MANIFEST_VERSION+ and manifest.get("database") == "vibe.sqlite"+ ):+ return None+ if not (path / "vibe.sqlite").is_file() or (path / "vibe.sqlite").is_symlink():+ return None+ kind = "sqlite"++ timestamp = _parse_timestamp(match.group("timestamp"))+ if timestamp is None:+ return None+ return _BackupCandidate(+ root=path,+ companions=(),+ kind=kind,+ timestamp=timestamp,+ suffix=int(match.group("suffix") or 0),+ )+++def _legacy_sqlite_candidate(path: Path) -> _BackupCandidate | None:+ if path.is_symlink() or not path.is_file():+ return None+ match = _LEGACY_SQLITE_REPAIR_RE.fullmatch(path.name)+ if match is None:+ return None+ timestamp = _parse_timestamp(match.group("timestamp"))+ if timestamp is None:+ return None+ companions = tuple(+ companion+ for suffix in ("-wal", "-shm")+ if (companion := path.with_name(path.name + suffix)).is_file() and not companion.is_symlink()+ )+ return _BackupCandidate(+ root=path,+ companions=companions,+ kind="sqlite",+ timestamp=timestamp,+ suffix=0,+ )+++def _managed_candidates(backups_dir: Path) -> list[_BackupCandidate]:+ try:+ entries = list(backups_dir.iterdir())+ except OSError:+ return []++ candidates: list[_BackupCandidate] = []+ for entry in entries:+ candidate = _directory_candidate(entry) or _legacy_sqlite_candidate(entry)+ if candidate is not None:+ candidates.append(candidate)+ return candidates+++def _remove_candidate(candidate: _BackupCandidate) -> bool:+ if candidate.root.is_symlink():+ return False+ try:+ for companion in candidate.companions:+ companion.unlink(missing_ok=True)+ if candidate.root.is_dir():+ shutil.rmtree(candidate.root)+ else:+ candidate.root.unlink(missing_ok=True)+ except OSError:+ logger.warning("Failed to prune managed state backup %s", candidate.root, exc_info=True)+ return False+ return True+++def prune_state_backups(+ backups_dir: Path,+ *,+ json_retention: int | None = JSON_STATE_BACKUP_RETENTION,+ sqlite_retention: int | None = SQLITE_BACKUP_RETENTION,+) -> list[Path]:+ """Keep a bounded rollback window of backups created by Avibe.++ Unknown files, symlinks, incomplete backups, and directories without a+ recognized manifest are intentionally left untouched.+ """++ limits = {+ kind: max(0, retention)+ for kind, retention in (("json", json_retention), ("sqlite", sqlite_retention))+ if retention is not None+ }+ candidates = _managed_candidates(backups_dir)+ removed: list[Path] = []+ for kind, limit in limits.items():+ matching = sorted((candidate for candidate in candidates if candidate.kind == kind), key=lambda item: item.order_key)+ for candidate in matching[: max(0, len(matching) - limit)]:+ if _remove_candidate(candidate):+ removed.append(candidate.root)+ return removed+++def _unique_backup_dir(backups_dir: Path, *, now: datetime) -> Path:+ timestamp = now.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")+ suffixes = [+ int(match.group("suffix") or 0)+ for entry in backups_dir.iterdir()+ if (match := _SQLITE_BACKUP_RE.fullmatch(entry.name)) is not None+ and match.group("timestamp") == timestamp+ ]+ suffix = max(suffixes, default=-1) + 1+ candidate = backups_dir / f"avibe-sqlite-migration-{timestamp}{f'-{suffix}' if suffix else ''}"+ while candidate.exists() or candidate.is_symlink():+ suffix += 1+ candidate = backups_dir / f"avibe-sqlite-migration-{timestamp}-{suffix}"+ return candidate+++def create_sqlite_migration_backup(+ db_path: Path,+ *,+ backups_dir: Path | None = None,+ from_revisions: Iterable[str] = (),+ to_revisions: Iterable[str] = (),+ now: datetime | None = None,+) -> Path:+ """Create a consistent, self-identifying SQLite backup before migration."""++ source_path = db_path.expanduser().resolve()+ created_at = now or datetime.now(timezone.utc)+ target_root = (backups_dir or source_path.parent / "backups").expanduser().resolve()+ target_root.mkdir(parents=True, exist_ok=True)+ backup_dir = _unique_backup_dir(target_root, now=created_at)+ backup_dir.mkdir(mode=0o700)+ temp_db = backup_dir / "vibe.sqlite.tmp"+ backup_db = backup_dir / "vibe.sqlite"++ try:+ with sqlite3.connect(f"{source_path.as_uri()}?mode=ro", uri=True) as source:+ with sqlite3.connect(temp_db) as destination:+ source.backup(destination)+ destination.execute("PRAGMA journal_mode = DELETE")+ check = destination.execute("PRAGMA quick_check").fetchone()+ if check != ("ok",):+ raise sqlite3.DatabaseError(f"SQLite backup quick_check failed: {check!r}")+ os.chmod(temp_db, 0o600)+ temp_db.replace(backup_db)+ manifest = {+ "schema_version": BACKUP_MANIFEST_VERSION,+ "managed_by": "avibe",+ "kind": "sqlite-migration",+ "created_at": created_at.astimezone(timezone.utc).isoformat(),+ "database": "vibe.sqlite",+ "from_revisions": sorted(set(from_revisions)),+ "to_revisions": sorted(set(to_revisions)),+ }+ (backup_dir / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ except Exception:+ shutil.rmtree(backup_dir, ignore_errors=True)+ raise++ return backup_dirdiff --git a/storage/importer.py b/storage/importer.pyindex af53ae5cb..f597858f7 100644--- a/storage/importer.py+++ b/storage/importer.py@@ -21,6 +21,7 @@ from config.v2_sessions import (migrate_session_state_mappings,)from config.v2_settings import SettingsState, load_settings_state_from_json+from storage.backups import BACKUP_MANIFEST_VERSION, prune_state_backupsfrom storage.db import create_sqlite_enginefrom storage.lock import MigrationFileLockfrom storage.migrations import guard_source_checkout_default_state_migration, run_migrations@@ -71,8 +72,9 @@ def ensure_sqlite_state(lock_path = target_state_dir / "migration.lock"with MigrationFileLock(lock_path):- run_migrations(target_db)+ run_migrations(target_db, prune_backups_after_upgrade=False)engine = create_sqlite_engine(target_db)+ report: MigrationImportReport | None = Nonetry:backup_path: Path | None = Nonewith engine.begin() as conn:@@ -90,44 +92,49 @@ def ensure_sqlite_state(or background_counts.get("background_runs_imported"))data_migration_counts = _run_sqlite_data_migrations(conn)- return MigrationImportReport(+ report = MigrationImportReport(db_path=target_db,imported=imported_background,backup_path=backup_path,counts=_current_counts(conn) | background_counts | data_migration_counts,)+ else:+ _clear_imported_state(conn)- _clear_imported_state(conn)+ if report is None:+ backup_path = _backup_json_state(target_state_dir)+ parsed = _parse_json_state(target_state_dir, primary_platform=primary_platform)+ _write_parsed_state(target_db, parsed)- backup_path = _backup_json_state(target_state_dir)- parsed = _parse_json_state(target_state_dir, primary_platform=primary_platform)- _write_parsed_state(target_db, parsed)-- with engine.begin() as conn:- discovered_count = _import_discovered_chats(conn, parsed.discovered)- background_counts = _import_background_state(conn, target_state_dir)- data_migration_counts = _run_sqlite_data_migrations(conn)- counts = _current_counts(conn)- counts["discovered_scopes"] = discovered_count- counts.update(background_counts)- counts.update(data_migration_counts)- if parsed.discovered_skipped:- counts["discovered_chats_skipped"] = 1- _validate_import(conn, counts)- _set_import_marker(conn)- _set_background_import_marker(conn)- return MigrationImportReport(- db_path=target_db,- imported=True,- backup_path=backup_path,- counts=_current_counts(conn)- | {"discovered_scopes": discovered_count}- | background_counts- | data_migration_counts- | ({"discovered_chats_skipped": 1} if parsed.discovered_skipped else {}),- )+ with engine.begin() as conn:+ discovered_count = _import_discovered_chats(conn, parsed.discovered)+ background_counts = _import_background_state(conn, target_state_dir)+ data_migration_counts = _run_sqlite_data_migrations(conn)+ counts = _current_counts(conn)+ counts["discovered_scopes"] = discovered_count+ counts.update(background_counts)+ counts.update(data_migration_counts)+ if parsed.discovered_skipped:+ counts["discovered_chats_skipped"] = 1+ _validate_import(conn, counts)+ _set_import_marker(conn)+ _set_background_import_marker(conn)+ report = MigrationImportReport(+ db_path=target_db,+ imported=True,+ backup_path=backup_path,+ counts=_current_counts(conn)+ | {"discovered_scopes": discovered_count}+ | background_counts+ | data_migration_counts+ | ({"discovered_chats_skipped": 1} if parsed.discovered_skipped else {}),+ )finally:engine.dispose()+ if report is None:+ raise RuntimeError("SQLite state initialization completed without a report")+ prune_state_backups(target_state_dir / "backups")+ return reportdef _ensure_sqlite_target_dirs(*, target_state_dir: Path, target_db: Path, use_default_dirs: bool) -> None:@@ -232,41 +239,59 @@ def _backup_json_state(state_dir: Path) -> Path:backups_dir = state_dir / "backups"backups_dir.mkdir(parents=True, exist_ok=True)timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")- backup_path = backups_dir / f"sqlite-state-migration-{timestamp}"- suffix = 1+ existing_suffixes: list[int] = []+ prefix = f"sqlite-state-migration-{timestamp}"+ for entry in backups_dir.iterdir():+ if entry.name == prefix:+ existing_suffixes.append(0)+ continue+ if entry.name.startswith(prefix + "-") and entry.name[len(prefix) + 1 :].isdigit():+ existing_suffixes.append(int(entry.name[len(prefix) + 1 :]))+ suffix = max(existing_suffixes, default=-1) + 1+ backup_path = backups_dir / f"{prefix}{f'-{suffix}' if suffix else ''}"while backup_path.exists():suffix += 1- backup_path = backups_dir / f"sqlite-state-migration-{timestamp}-{suffix}"+ backup_path = backups_dir / f"{prefix}-{suffix}"backup_path.mkdir(parents=True)- manifest: dict[str, Any] = {"created_at": _utc_now_iso(), "files": {}}- for name in (- "settings.json",- "sessions.json",- "discovered_chats.json",- "scheduled_tasks.json",- "watches.json",- ):- source = state_dir / name- if not source.exists():- manifest["files"][name] = {"present": False}- continue- target = backup_path / name- shutil.copy2(source, target)- stat = source.stat()- manifest["files"][name] = {- "present": True,- "size": stat.st_size,- "mtime_ns": stat.st_mtime_ns,+ try:+ manifest: dict[str, Any] = {+ "schema_version": BACKUP_MANIFEST_VERSION,+ "managed_by": "avibe",+ "kind": "json-state-migration",+ "created_at": _utc_now_iso(),+ "files": {},}- task_requests = state_dir / "task_requests"- if task_requests.exists():- shutil.copytree(task_requests, backup_path / "task_requests")- manifest["files"]["task_requests"] = {"present": True}- else:- manifest["files"]["task_requests"] = {"present": False}-- (backup_path / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ for name in (+ "settings.json",+ "sessions.json",+ "discovered_chats.json",+ "scheduled_tasks.json",+ "watches.json",+ ):+ source = state_dir / name+ if not source.exists():+ manifest["files"][name] = {"present": False}+ continue+ target = backup_path / name+ shutil.copy2(source, target)+ stat = source.stat()+ manifest["files"][name] = {+ "present": True,+ "size": stat.st_size,+ "mtime_ns": stat.st_mtime_ns,+ }+ task_requests = state_dir / "task_requests"+ if task_requests.exists():+ shutil.copytree(task_requests, backup_path / "task_requests")+ manifest["files"]["task_requests"] = {"present": True}+ else:+ manifest["files"]["task_requests"] = {"present": False}++ (backup_path / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+ except Exception:+ shutil.rmtree(backup_path, ignore_errors=True)+ raisereturn backup_pathdiff --git a/storage/migrations.py b/storage/migrations.pyindex 91f2b8ea7..77795c956 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -2,16 +2,22 @@ from __future__ import annotationsimport osimport sqlite3+import loggingfrom importlib import import_modulefrom pathlib import Pathfrom types import SimpleNamespacefrom alembic import commandfrom alembic.config import Config+from alembic.script import ScriptDirectoryfrom config import paths+from storage.backups import create_sqlite_migration_backup, prune_state_backupsfrom storage.db import create_sqlite_engine, sqlite_url++logger = logging.getLogger(__name__)+INITIAL_REVISION = "20260501_0001"LATEST_SCHEMA_REVISION = "20260622_0023"REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"@@ -129,14 +135,51 @@ def alembic_config(db_path: Path | None = None) -> Config:return cfg-def run_migrations(db_path: Path | None = None, *, revision: str = "head") -> None:- target_db = db_path or paths.get_sqlite_state_path()+def run_migrations(+ db_path: Path | None = None,+ *,+ revision: str = "head",+ prune_backups_after_upgrade: bool = True,+) -> None:+ target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()guard_source_checkout_default_state_migration(target_db)cfg = alembic_config(target_db)+ backup_revisions = _migration_backup_revisions(target_db, cfg, revision)+ if backup_revisions is not None:+ current_revisions, target_revisions = backup_revisions+ backup_path = create_sqlite_migration_backup(+ target_db,+ from_revisions=current_revisions,+ to_revisions=target_revisions,+ )+ logger.info("Created pre-migration SQLite backup at %s", backup_path)_reset_unreleased_initial_schema_drift(target_db)_repair_unreleased_head_schema_drift(target_db)_stamp_existing_initial_schema(target_db, cfg)command.upgrade(cfg, revision)+ if prune_backups_after_upgrade:+ prune_state_backups(target_db.parent / "backups", json_retention=None)+++def _migration_backup_revisions(db_path: Path, cfg: Config, revision: str) -> tuple[set[str], set[str]] | None:+ if not db_path.exists() or db_path.stat().st_size == 0:+ return None++ with sqlite3.connect(db_path) as conn:+ tables = _table_names(conn)+ if not tables - {"alembic_version"}:+ return None+ current_revisions = (+ {str(row[0]) for row in conn.execute("select version_num from alembic_version")}+ if "alembic_version" in tables+ else set()+ )++ script = ScriptDirectory.from_config(cfg)+ target_revisions = {item.revision for item in script.get_revisions(revision)}+ if current_revisions == target_revisions:+ return None+ return current_revisions, target_revisionsdef background_tables_ready(db_path: Path | None = None) -> bool:@@ -150,12 +193,7 @@ def background_tables_ready(db_path: Path | None = None) -> bool:def initialize_background_tables(db_path: Path | None = None) -> None:target_db = db_path or paths.get_sqlite_state_path()- guard_source_checkout_default_state_migration(target_db)- cfg = alembic_config(target_db)- command.ensure_version(cfg)- _repair_unreleased_head_schema_drift(target_db)- _stamp_existing_initial_schema(target_db, cfg)- command.upgrade(cfg, "head")+ run_migrations(target_db)def guard_source_checkout_default_state_migration(db_path: Path) -> None:diff --git a/tests/test_docker_entrypoint_supervisor.py b/tests/test_docker_entrypoint_supervisor.pyindex 2adc1d74d..b87da4a1b 100644--- a/tests/test_docker_entrypoint_supervisor.py+++ b/tests/test_docker_entrypoint_supervisor.py@@ -15,6 +15,13 @@ ENTRYPOINT = REPO_ROOT / "scripts" / "docker-entrypoint.sh"class DockerEntrypointSupervisorTests(unittest.TestCase):+ def test_ui_process_uses_bounded_log_sinks(self):+ entrypoint = ENTRYPOINT.read_text(encoding="utf-8")++ self.assertIn('python -m vibe.log_sink "$ui_stdout"', entrypoint)+ self.assertIn('python -m vibe.log_sink "$ui_stderr"', entrypoint)+ subprocess.run(["bash", "-n", str(ENTRYPOINT)], check=True)+def test_full_mode_exits_when_service_process_dies(self):with tempfile.TemporaryDirectory() as tmpdir:tmp_path = Path(tmpdir)@@ -32,6 +39,10 @@ class DockerEntrypointSupervisorTests(unittest.TestCase):if args and args[0] == "main.py":sys.exit(42)+ if len(args) >= 2 and args[:2] == ["-m", "vibe.log_sink"]:+ sys.stdin.buffer.read()+ sys.exit(0)+if len(args) >= 2 and args[0] == "-c":code = args[1]if "get_runtime_dir" in code:diff --git a/tests/test_runtime_log_sink.py b/tests/test_runtime_log_sink.pynew file mode 100644index 000000000..bc2ab1428--- /dev/null+++ b/tests/test_runtime_log_sink.py@@ -0,0 +1,139 @@+from __future__ import annotations++import io+import sys+import threading+import time+from pathlib import Path++from storage.lock import MigrationFileLock+from vibe import runtime+from vibe.log_sink import RUNTIME_LOG_TRUNCATION_MARKER, copy_bounded_log+++def test_copy_bounded_log_preserves_inode_and_newest_output(tmp_path: Path) -> None:+ path = tmp_path / "service_stderr.log"+ path.write_bytes(b"old line\n" * 40)+ inode = path.stat().st_ino+ latest = b"latest diagnostic\n"++ copied = copy_bounded_log(+ io.BytesIO((b"new line\n" * 40) + latest),+ path,+ max_bytes=160,+ retain_bytes=80,+ chunk_bytes=32,+ )++ content = path.read_bytes()+ assert copied is True+ assert path.stat().st_ino == inode+ assert len(content) <= 160+ assert RUNTIME_LOG_TRUNCATION_MARKER in content+ assert content.endswith(latest)+++def test_copy_bounded_log_skips_symlink_and_drains_input(tmp_path: Path) -> None:+ target = tmp_path / "outside.log"+ target.write_bytes(b"outside\n" * 100)+ link = tmp_path / "ui_stderr.log"+ link.symlink_to(target)+ source = io.BytesIO(b"new output")++ assert copy_bounded_log(source, link, max_bytes=80, retain_bytes=40) is False+ assert source.tell() == len(b"new output")+ assert target.read_bytes() == b"outside\n" * 100+++def test_copy_bounded_log_drains_while_waiting_for_previous_sink(tmp_path: Path) -> None:+ path = tmp_path / "ui_stdout.log"+ lock = MigrationFileLock(path.with_name(f".{path.name}.sink.lock"))+ lock.acquire()+ source = io.BytesIO(b"noisy replacement startup\n" * 100)+ result: list[bool] = []+ thread = threading.Thread(+ target=lambda: result.append(+ copy_bounded_log(source, path, max_bytes=512, retain_bytes=256, chunk_bytes=64)+ )+ )+ thread.start()+ try:+ deadline = time.monotonic() + 2+ while source.tell() < len(source.getvalue()) and time.monotonic() < deadline:+ time.sleep(0.01)+ assert source.tell() == len(source.getvalue())+ time.sleep(0.35)+ assert thread.is_alive()+ finally:+ lock.release()+ thread.join(timeout=5)++ assert result == [True]+ assert path.read_bytes().endswith(b"noisy replacement startup\n")+++def test_copy_bounded_log_flushes_quiet_startup_burst_after_lock_release(tmp_path: Path) -> None:+ class StartupBurst:+ def __init__(self) -> None:+ self.burst_read = threading.Event()+ self.finish = threading.Event()+ self.delivered = False++ def read1(self, _size: int) -> bytes:+ if not self.delivered:+ self.delivered = True+ self.burst_read.set()+ return b"startup complete\n"+ self.finish.wait(timeout=5)+ return b""++ path = tmp_path / "ui_stderr.log"+ lock = MigrationFileLock(path.with_name(f".{path.name}.sink.lock"))+ lock.acquire()+ source = StartupBurst()+ result: list[bool] = []+ thread = threading.Thread(+ target=lambda: result.append(+ copy_bounded_log(source, path, max_bytes=512, retain_bytes=256, chunk_bytes=64)+ )+ )+ thread.start()+ try:+ assert source.burst_read.wait(timeout=2)+ lock.release()+ deadline = time.monotonic() + 2+ while not path.exists() and time.monotonic() < deadline:+ time.sleep(0.01)+ assert path.read_bytes() == b"startup complete\n"+ assert thread.is_alive()+ finally:+ lock.release()+ source.finish.set()+ thread.join(timeout=5)++ assert result == [True]+++def test_spawned_process_output_is_continuously_bounded(monkeypatch, tmp_path: Path) -> None:+ monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)+ monkeypatch.setattr(runtime, "RUNTIME_LOG_MAX_BYTES", 512)+ monkeypatch.setattr(runtime, "RUNTIME_LOG_RETAIN_BYTES", 256)+ payload = "output-line-" * 500++ process = runtime.spawn_service_background_process(+ [sys.executable, "-c", f"print({payload!r})"],+ "service_stdout.log",+ "service_stderr.log",+ )+ assert process.wait(timeout=10) == 0++ stdout_path = tmp_path / "service_stdout.log"+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ if stdout_path.exists() and stdout_path.read_bytes().endswith(b"output-line-\n"):+ break+ time.sleep(0.05)++ content = stdout_path.read_bytes()+ assert len(content) <= 512+ assert content.endswith(b"output-line-\n")diff --git a/tests/test_service_logging_handlers.py b/tests/test_service_logging_handlers.pyindex de4bc120c..87f977ccf 100644--- a/tests/test_service_logging_handlers.py+++ b/tests/test_service_logging_handlers.py@@ -5,6 +5,7 @@ import osimport signalimport subprocessimport sys+from logging.handlers import RotatingFileHandlerfrom pathlib import Pathimport main@@ -18,7 +19,9 @@ def test_build_logging_handlers_excludes_stdout_when_disabled(monkeypatch, tmp_phandlers = main._build_logging_handlers(str(tmp_path))assert len(handlers) == 1- assert isinstance(handlers[0], logging.FileHandler)+ assert isinstance(handlers[0], RotatingFileHandler)+ assert handlers[0].maxBytes == main.APPLICATION_LOG_MAX_BYTES+ assert handlers[0].backupCount == main.APPLICATION_LOG_BACKUP_COUNTdef test_build_logging_handlers_keeps_stdout_by_default(monkeypatch, tmp_path):@@ -28,7 +31,24 @@ def test_build_logging_handlers_keeps_stdout_by_default(monkeypatch, tmp_path):assert len(handlers) == 2assert isinstance(handlers[0], logging.StreamHandler)- assert isinstance(handlers[1], logging.FileHandler)+ assert isinstance(handlers[1], RotatingFileHandler)+++def test_application_log_rotates_at_configured_limit(monkeypatch, tmp_path):+ monkeypatch.setattr(main, "APPLICATION_LOG_MAX_BYTES", 128)+ monkeypatch.setattr(main, "APPLICATION_LOG_BACKUP_COUNT", 2)+ monkeypatch.setenv("VIBE_DISABLE_STDOUT_LOGGING", "1")+ handler = main._build_logging_handlers(str(tmp_path))[0]+ handler.setFormatter(logging.Formatter("%(message)s"))+ record = logging.LogRecord("rotation-test", logging.INFO, __file__, 1, "x" * 80, (), None)+ try:+ for _ in range(10):+ handler.emit(record)+ finally:+ handler.close()++ assert (tmp_path / "vibe_remote.log.1").exists()+ assert len(list(tmp_path.glob("vibe_remote.log*"))) == 3def test_start_service_disables_stdout_logging_for_background_process(monkeypatch, tmp_path):@@ -63,9 +83,20 @@ def test_start_service_disables_stdout_logging_for_background_process(monkeypatcdef test_spawn_background_detaches_stdin(monkeypatch, tmp_path):captured: dict[str, object] = {}+ sink_paths: list[Path] = []monkeypatch.setattr(runtime.paths, "get_runtime_dir", lambda: tmp_path)+ class FakeSink:+ def __init__(self, path: Path):+ self.stdin = path.open("wb")++ def fake_sinks(stdout_path: Path, stderr_path: Path):+ sink_paths.extend((stdout_path, stderr_path))+ return FakeSink(tmp_path / "stdout.pipe"), FakeSink(tmp_path / "stderr.pipe")++ monkeypatch.setattr(runtime, "_spawn_runtime_log_sinks", fake_sinks)+class FakePopen:pid = 12345@@ -82,6 +113,9 @@ def test_spawn_background_detaches_stdin(monkeypatch, tmp_path):assert stdin.name == os.devnullassert stdin.closed is Trueassert captured["kwargs"]["start_new_session"] is True+ assert captured["kwargs"]["stdout"].closed is True+ assert captured["kwargs"]["stderr"].closed is True+ assert sink_paths == [tmp_path / "stdout.log", tmp_path / "stderr.log"]def test_main_import_does_not_load_controller() -> None:diff --git a/tests/test_state_backups.py b/tests/test_state_backups.pynew file mode 100644index 000000000..79be1ab68--- /dev/null+++ b/tests/test_state_backups.py@@ -0,0 +1,303 @@+from __future__ import annotations++import json+import sqlite3+from datetime import datetime, timezone+from pathlib import Path++import pytest++from storage.backups import create_sqlite_migration_backup, prune_state_backups+from storage.background import SQLiteBackgroundTaskStore+from storage.importer import _backup_json_state, ensure_sqlite_state+from storage.migrations import run_migrations+++def _legacy_json_backup(backups_dir: Path, timestamp: str) -> Path:+ path = backups_dir / f"sqlite-state-migration-{timestamp}"+ path.mkdir(parents=True)+ (path / "manifest.json").write_text(+ json.dumps({"created_at": "2026-07-01T00:00:00+00:00", "files": {}}),+ encoding="utf-8",+ )+ return path+++def _legacy_sqlite_backup(backups_dir: Path, name: str) -> Path:+ path = backups_dir / name+ path.write_bytes(b"sqlite backup")+ path.with_name(path.name + "-wal").write_bytes(b"wal")+ path.with_name(path.name + "-shm").write_bytes(b"shm")+ return path+++def test_prune_state_backups_keeps_bounded_rollbacks_and_unknown_files(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ backups_dir = state_dir / "backups"+ backups_dir.mkdir(parents=True)+ json_backups = [+ _legacy_json_backup(backups_dir, f"2026070{day}T010000Z")+ for day in range(1, 6)+ ]+ sqlite_backups = [+ _legacy_sqlite_backup(backups_dir, f"vibe-pre-0026-repair-2026070{day}T020000Z.sqlite")+ for day in range(1, 5)+ ]+ unknown = backups_dir / "manual-keep.sqlite"+ unknown.write_bytes(b"user managed")+ active_named = [backups_dir / name for name in ("vibe.sqlite", "vibe.sqlite-wal", "vibe.sqlite-shm")]+ for path in active_named:+ path.write_bytes(b"not a managed backup")++ removed = prune_state_backups(backups_dir)++ assert set(removed) == set(json_backups[:2] + sqlite_backups[:2])+ assert all(not path.exists() for path in json_backups[:2])+ assert all(path.exists() for path in json_backups[2:])+ for path in sqlite_backups[:2]:+ assert not path.exists()+ assert not path.with_name(path.name + "-wal").exists()+ assert not path.with_name(path.name + "-shm").exists()+ assert all(path.exists() for path in sqlite_backups[2:])+ assert unknown.read_bytes() == b"user managed"+ assert all(path.exists() for path in active_named)+++def test_prune_state_backups_preserves_invalid_or_incomplete_candidates(tmp_path: Path) -> None:+ backups_dir = tmp_path / "backups"+ incomplete = backups_dir / "sqlite-state-migration-20260701T010000Z"+ incomplete.mkdir(parents=True)+ invalid = backups_dir / "avibe-sqlite-migration-20260701T010000Z"+ invalid.mkdir()+ (invalid / "manifest.json").write_text("{}", encoding="utf-8")+ invalid_date = backups_dir / "sqlite-state-migration-20269999T999999Z"+ invalid_date.mkdir()+ (invalid_date / "manifest.json").write_text(+ json.dumps({"created_at": "invalid", "files": {}}),+ encoding="utf-8",+ )++ assert prune_state_backups(backups_dir, json_retention=0, sqlite_retention=0) == []+ assert incomplete.exists()+ assert invalid.exists()+ assert invalid_date.exists()+++def test_create_sqlite_migration_backup_is_consistent_without_copying_live_sidecars(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ db_path = state_dir / "vibe.sqlite"+ writer = sqlite3.connect(db_path)+ try:+ writer.execute("PRAGMA journal_mode = WAL")+ writer.execute("PRAGMA wal_autocheckpoint = 0")+ writer.execute("create table records (value text not null)")+ writer.execute("insert into records values ('preserved')")+ writer.commit()+ assert db_path.with_name("vibe.sqlite-wal").exists()+ backups_dir = state_dir / "backups"+ backups_dir.mkdir()+ oldest = _legacy_sqlite_backup(backups_dir, "vibe-pre-0026-repair-20260708T020000Z.sqlite")+ previous = _legacy_sqlite_backup(backups_dir, "vibe-pre-0026-repair-20260709T020000Z.sqlite")++ backup_dir = create_sqlite_migration_backup(+ db_path,+ from_revisions={"old"},+ to_revisions={"new"},+ now=datetime(2026, 7, 10, 3, 0, tzinfo=timezone.utc),+ )++ with sqlite3.connect(backup_dir / "vibe.sqlite") as backup:+ assert backup.execute("select value from records").fetchone() == ("preserved",)+ manifest = json.loads((backup_dir / "manifest.json").read_text(encoding="utf-8"))+ assert manifest["managed_by"] == "avibe"+ assert manifest["kind"] == "sqlite-migration"+ assert manifest["from_revisions"] == ["old"]+ assert manifest["to_revisions"] == ["new"]+ assert oldest.exists()+ assert previous.exists()+ assert not (backup_dir / "vibe.sqlite-wal").exists()+ assert not (backup_dir / "vibe.sqlite-shm").exists()+ assert db_path.exists()+ assert db_path.with_name("vibe.sqlite-wal").exists()+ finally:+ writer.close()+++def test_json_backup_creation_applies_retention(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ (state_dir / "settings.json").write_text("{}", encoding="utf-8")++ for _ in range(5):+ _backup_json_state(state_dir)++ assert len(list((state_dir / "backups").glob("sqlite-state-migration-*"))) == 5+ ensure_sqlite_state(db_path=state_dir / "vibe.sqlite", state_dir=state_dir)++ backups = sorted((state_dir / "backups").glob("sqlite-state-migration-*"))+ assert len(backups) == 3+ assert all(json.loads((path / "manifest.json").read_text(encoding="utf-8"))["managed_by"] == "avibe" for path in backups)+++def test_failed_json_backup_removes_its_incomplete_directory(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ (state_dir / "settings.json").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(+ "storage.importer.shutil.copy2",+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("full")),+ )++ with pytest.raises(OSError, match="full"):+ _backup_json_state(state_dir)++ assert list((state_dir / "backups").iterdir()) == []+++def test_failed_sqlite_backup_keeps_existing_rollback_window(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ backups_dir = state_dir / "backups"+ backups_dir.mkdir(parents=True)+ db_path = state_dir / "vibe.sqlite"+ db_path.write_bytes(b"not opened")+ existing = [+ _legacy_sqlite_backup(backups_dir, f"vibe-pre-0026-repair-2026070{day}T020000Z.sqlite")+ for day in (8, 9)+ ]+ monkeypatch.setattr("storage.backups.sqlite3.connect", lambda *args, **kwargs: (_ for _ in ()).throw(OSError("full")))++ with pytest.raises(OSError, match="full"):+ create_sqlite_migration_backup(db_path)++ assert all(path.exists() for path in existing)+++def test_startup_prunes_only_after_migration_backup_succeeds(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ db_path = state_dir / "vibe.sqlite"+ run_migrations(db_path, revision="20260627_0025")+ backups_dir = state_dir / "backups"+ backups_dir.mkdir()+ existing = [+ _legacy_sqlite_backup(backups_dir, f"vibe-pre-0026-repair-2026070{day}T020000Z.sqlite")+ for day in (7, 8, 9)+ ]+ monkeypatch.setattr(+ "storage.migrations.create_sqlite_migration_backup",+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("full")),+ )++ with pytest.raises(OSError, match="full"):+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir)++ assert all(path.exists() for path in existing)+++def test_startup_keeps_json_rollbacks_when_new_snapshot_fails(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ backups_dir = state_dir / "backups"+ backups_dir.mkdir(parents=True)+ existing = [+ _legacy_json_backup(backups_dir, f"2026070{day}T010000Z")+ for day in range(1, 6)+ ]+ monkeypatch.setattr(+ "storage.importer._backup_json_state",+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("full")),+ )++ with pytest.raises(OSError, match="full"):+ ensure_sqlite_state(db_path=state_dir / "vibe.sqlite", state_dir=state_dir)++ assert all(path.exists() for path in existing)+++def test_startup_keeps_json_rollbacks_when_import_after_snapshot_fails(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ backups_dir = state_dir / "backups"+ backups_dir.mkdir(parents=True)+ existing = [+ _legacy_json_backup(backups_dir, f"2026070{day}T010000Z")+ for day in range(1, 6)+ ]+ monkeypatch.setattr(+ "storage.importer._parse_json_state",+ lambda *args, **kwargs: (_ for _ in ()).throw(ValueError("invalid import")),+ )++ with pytest.raises(ValueError, match="invalid import"):+ ensure_sqlite_state(db_path=state_dir / "vibe.sqlite", state_dir=state_dir)++ assert all(path.exists() for path in existing)+++def test_startup_keeps_sqlite_rollbacks_when_import_after_upgrade_fails(monkeypatch, tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ db_path = state_dir / "vibe.sqlite"+ run_migrations(db_path, revision="20260627_0025")+ backups_dir = state_dir / "backups"+ backups_dir.mkdir()+ existing = [+ _legacy_sqlite_backup(backups_dir, f"vibe-pre-0026-repair-2026070{day}T020000Z.sqlite")+ for day in (7, 8, 9)+ ]+ monkeypatch.setattr(+ "storage.importer._parse_json_state",+ lambda *args, **kwargs: (_ for _ in ()).throw(ValueError("invalid import")),+ )++ with pytest.raises(ValueError, match="invalid import"):+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir)++ assert all(path.exists() for path in existing)+++def test_failed_schema_upgrade_keeps_existing_sqlite_rollbacks(monkeypatch, tmp_path: Path) -> None:+ db_path = tmp_path / "state" / "vibe.sqlite"+ db_path.parent.mkdir()+ run_migrations(db_path, revision="20260627_0025")+ backups_dir = db_path.parent / "backups"+ backups_dir.mkdir()+ existing = [+ _legacy_sqlite_backup(backups_dir, f"vibe-pre-0026-repair-2026070{day}T020000Z.sqlite")+ for day in (7, 8, 9)+ ]+ monkeypatch.setattr(+ "storage.migrations.command.upgrade",+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("upgrade failed")),+ )++ with pytest.raises(RuntimeError, match="upgrade failed"):+ run_migrations(db_path)++ assert all(path.exists() for path in existing)+++def test_run_migrations_backs_up_only_when_existing_schema_advances(tmp_path: Path) -> None:+ db_path = tmp_path / "state" / "vibe.sqlite"+ db_path.parent.mkdir()++ run_migrations(db_path, revision="20260627_0025")+ assert not list((db_path.parent / "backups").glob("avibe-sqlite-migration-*"))++ run_migrations(db_path)+ first_backups = list((db_path.parent / "backups").glob("avibe-sqlite-migration-*"))+ assert len(first_backups) == 1++ run_migrations(db_path)+ assert list((db_path.parent / "backups").glob("avibe-sqlite-migration-*")) == first_backups+++def test_background_store_schema_upgrade_uses_migration_backup(tmp_path: Path) -> None:+ db_path = tmp_path / "state" / "vibe.sqlite"+ db_path.parent.mkdir()+ run_migrations(db_path, revision="20260627_0025")++ store = SQLiteBackgroundTaskStore(db_path)+ store.close()++ backups = list((db_path.parent / "backups").glob("avibe-sqlite-migration-*"))+ assert len(backups) == 1diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.pyindex 08062ba65..49d94525a 100644--- a/tests/test_ui_server_logs.py+++ b/tests/test_ui_server_logs.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport osfrom datetime import datetime+from pathlib import Pathfrom config import pathsfrom vibe.ui_server import app@@ -49,6 +50,50 @@ def test_logs_endpoint_returns_multiple_sources(monkeypatch, tmp_path):assert payload["logs"][0]["source"] == "ui_stderr"+def test_logs_endpoint_reads_rotated_service_generations(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ (paths.get_logs_dir() / "vibe_remote.log.1").write_text(+ "2026-03-25 15:51:17,428 - service.main - ERROR - retained failure\n",+ encoding="utf-8",+ )++ client = app.test_client()+ response = client.post("/api/logs", json={"lines": 20, "source": "service"}, headers=csrf_headers(client))++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["total"] == 1+ assert payload["logs"][0]["message"] == "retained failure"+ assert next(source for source in payload["sources"] if source["key"] == "service")["exists"] is True+++def test_logs_endpoint_skips_generation_removed_during_rotation(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ rotated = paths.get_logs_dir() / "vibe_remote.log.1"+ rotated.write_text("old generation\n", encoding="utf-8")+ (paths.get_logs_dir() / "vibe_remote.log").write_text(+ "2026-03-25 15:51:17,428 - service.main - INFO - current line\n",+ encoding="utf-8",+ )+ real_open = Path.open++ def open_with_rotation_race(path: Path, *args, **kwargs):+ if path == rotated:+ raise FileNotFoundError(path)+ return real_open(path, *args, **kwargs)++ monkeypatch.setattr(Path, "open", open_with_rotation_race)+ client = app.test_client()+ response = client.post("/api/logs", json={"lines": 20, "source": "service"}, headers=csrf_headers(client))++ assert response.status_code == 200+ payload = response.get_json()+ assert payload["total"] == 1+ assert payload["logs"][0]["message"] == "current line"++def test_logs_endpoint_returns_aggregated_all_view(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_ui_server_reload.py b/tests/test_ui_server_reload.pyindex 0e48a9ce6..2ff7e2b44 100644--- a/tests/test_ui_server_reload.py+++ b/tests/test_ui_server_reload.py@@ -45,6 +45,11 @@ class _NoopThread:return None+class _ImmediateThread(_NoopThread):+ def start(self) -> None:+ self._target(*self._args, **self._kwargs)++def test_ui_reload_overrides_bind_host_when_tunnel_enabled(monkeypatch):captured_calls: list[dict] = []original = runtime.effective_ui_bind_host@@ -128,3 +133,33 @@ def test_ui_reload_uses_requested_host_when_tunnel_disabled(monkeypatch):assert response.status_code == 200assert captured["requested_host"] == "192.168.1.5"assert captured["enabled"] is False+++def test_ui_reload_routes_replacement_output_through_runtime_log_sinks(monkeypatch):+ captured: dict = {}+ monkeypatch.setattr(+ "core.services.settings.load_config",+ lambda *a, **k: _config_with_tunnel(enabled=False),+ )+ monkeypatch.setattr(threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(runtime, "read_status", lambda: {"state": "running", "service_pid": 111})+ monkeypatch.setattr(runtime, "write_status", lambda *args: captured.setdefault("status", args))++ def fake_spawn(args, pid_path, stdout_name, stderr_name, env=None):+ captured["spawn"] = (args, pid_path, stdout_name, stderr_name, env)+ return 222++ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)++ client = app.test_client()+ response = client.post(+ "/api/ui/reload",+ json={"host": "127.0.0.1", "port": 5123},+ headers=csrf_headers(client, "http://127.0.0.1:5123"),+ base_url="http://127.0.0.1:5123",+ )++ assert response.status_code == 200+ assert captured["spawn"][1] == runtime.paths.get_runtime_ui_pid_path()+ assert captured["spawn"][2:4] == ("ui_stdout.log", "ui_stderr.log")+ assert captured["status"][-1] == 222diff --git a/vibe/cli.py b/vibe/cli.pyindex 1289c0a0e..6c4a195ee 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1112,21 +1112,7 @@ def _spawn_background(stdout_name: str = "service_stdout.log",stderr_name: str = "service_stderr.log",):- stdout_path = paths.get_runtime_dir() / stdout_name- stderr_path = paths.get_runtime_dir() / stderr_name- stdout_path.parent.mkdir(parents=True, exist_ok=True)- stdout = stdout_path.open("ab")- stderr = stderr_path.open("ab")- process = subprocess.Popen(- args,- stdout=stdout,- stderr=stderr,- start_new_session=True,- )- stdout.close()- stderr.close()- pid_path.write_text(str(process.pid), encoding="utf-8")- return process.pid+ return runtime.spawn_background(args, pid_path, stdout_name, stderr_name)def _stop_process(pid_path):diff --git a/vibe/log_sink.py b/vibe/log_sink.pynew file mode 100644index 000000000..4f1668ad2--- /dev/null+++ b/vibe/log_sink.py@@ -0,0 +1,235 @@+from __future__ import annotations++import argparse+import os+import stat+import sys+import threading+import time+from collections import deque+from pathlib import Path+from typing import BinaryIO++from storage.lock import MigrationFileLock, MigrationLockTimeout+++RUNTIME_LOG_MAX_BYTES = 10 * 1024 * 1024+RUNTIME_LOG_RETAIN_BYTES = 5 * 1024 * 1024+RUNTIME_LOG_TRUNCATION_MARKER = b"[avibe: older runtime output truncated]\n"+_COPY_CHUNK_BYTES = 64 * 1024+++def _open_regular_log(path: Path) -> BinaryIO | None:+ try:+ if path.is_symlink():+ return None+ path.parent.mkdir(parents=True, exist_ok=True)+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)+ descriptor = os.open(path, flags, 0o600)+ if not stat.S_ISREG(os.fstat(descriptor).st_mode):+ os.close(descriptor)+ return None+ return os.fdopen(descriptor, "r+b", buffering=0)+ except OSError:+ return None+++def _compact_log(log_file: BinaryIO, *, max_bytes: int, retain_bytes: int) -> None:+ marker = RUNTIME_LOG_TRUNCATION_MARKER[:max_bytes]+ retained_limit = min(max(0, retain_bytes), max(0, max_bytes - len(marker)))+ log_file.seek(0, os.SEEK_END)+ size = log_file.tell()+ if size <= max_bytes:+ return+ log_file.seek(max(0, size - retained_limit))+ tail = log_file.read(retained_limit)+ if size > retained_limit:+ first_newline = tail.find(b"\n")+ if first_newline >= 0:+ tail = tail[first_newline + 1 :]+ log_file.seek(0)+ log_file.write(marker)+ log_file.write(tail)+ log_file.truncate()+++def _write_bounded_chunk(+ log_file: BinaryIO,+ chunk: bytes,+ *,+ max_bytes: int,+ retain_bytes: int,+) -> None:+ if len(chunk) >= max_bytes:+ marker = RUNTIME_LOG_TRUNCATION_MARKER+ bounded = (+ marker + chunk[-(max_bytes - len(marker)) :]+ if max_bytes > len(marker)+ else chunk[-max_bytes:]+ )+ log_file.seek(0)+ log_file.write(bounded)+ log_file.truncate()+ return+ log_file.seek(0, os.SEEK_END)+ threshold = max_bytes - len(chunk)+ if log_file.tell() > threshold:+ _compact_log(log_file, max_bytes=threshold, retain_bytes=retain_bytes)+ log_file.seek(0, os.SEEK_END)+ log_file.write(chunk)+++def _append_bounded_chunk(+ chunks: deque[bytes],+ chunk: bytes,+ *,+ buffered_bytes: int,+ max_bytes: int,+) -> int:+ if len(chunk) >= max_bytes:+ chunks.clear()+ chunks.append(chunk[-max_bytes:])+ return max_bytes++ chunks.append(chunk)+ buffered_bytes += len(chunk)+ overflow = buffered_bytes - max_bytes+ while overflow > 0:+ oldest = chunks[0]+ if len(oldest) <= overflow:+ chunks.popleft()+ buffered_bytes -= len(oldest)+ overflow -= len(oldest)+ continue+ chunks[0] = oldest[overflow:]+ buffered_bytes -= overflow+ overflow = 0+ return buffered_bytes+++def copy_bounded_log(+ source: BinaryIO,+ path: Path,+ *,+ max_bytes: int = RUNTIME_LOG_MAX_BYTES,+ retain_bytes: int = RUNTIME_LOG_RETAIN_BYTES,+ chunk_bytes: int = _COPY_CHUNK_BYTES,+) -> bool:+ """Drain one subprocess stream into a bounded, live-tail-friendly file."""++ max_bytes = max(1, max_bytes)+ chunk_bytes = max(1, chunk_bytes)+ lock = MigrationFileLock(path.with_name(f".{path.name}.sink.lock"), timeout_seconds=0.25)+ lock_ready = threading.Event()+ lock_stop = threading.Event()+ lock_acquired = False+ pending: deque[bytes] = deque()+ pending_bytes = 0+ source_eof = False+ source_failed = False+ pending_ready = threading.Condition()++ def _acquire_lock() -> None:+ nonlocal lock_acquired+ while not lock_stop.is_set():+ try:+ lock.acquire()+ lock_acquired = True+ break+ except MigrationLockTimeout:+ continue+ except OSError:+ break+ lock_ready.set()++ lock_thread = threading.Thread(target=_acquire_lock, name=f"log-sink-lock-{path.name}", daemon=True)+ lock_thread.start()++ def _read_source() -> None:+ nonlocal pending_bytes, source_eof, source_failed+ read_chunk = getattr(source, "read1", None) or source.read+ try:+ while chunk := read_chunk(chunk_bytes):+ with pending_ready:+ pending_bytes = _append_bounded_chunk(+ pending,+ chunk,+ buffered_bytes=pending_bytes,+ max_bytes=max_bytes,+ )+ pending_ready.notify()+ except OSError:+ source_failed = True+ finally:+ with pending_ready:+ source_eof = True+ pending_ready.notify_all()++ reader_thread = threading.Thread(target=_read_source, name=f"log-sink-reader-{path.name}", daemon=True)+ reader_thread.start()+ try:+ eof_wait_deadline: float | None = None+ while not lock_ready.wait(timeout=0.05):+ with pending_ready:+ reached_eof = source_eof+ if not reached_eof:+ continue+ if eof_wait_deadline is None:+ eof_wait_deadline = time.monotonic() + 31.0+ elif time.monotonic() >= eof_wait_deadline:+ break+ if not lock_acquired:+ reader_thread.join()+ return False++ log_file = _open_regular_log(path)+ if log_file is None:+ raise OSError(f"runtime log path is not a regular file: {path}")+ with log_file:+ _compact_log(log_file, max_bytes=max_bytes, retain_bytes=retain_bytes)+ while True:+ with pending_ready:+ while not pending and not source_eof:+ pending_ready.wait()+ chunk = b"".join(pending)+ pending.clear()+ pending_bytes = 0+ finished = source_eof and not chunk+ if chunk:+ _write_bounded_chunk(+ log_file,+ chunk,+ max_bytes=max_bytes,+ retain_bytes=retain_bytes,+ )+ if finished:+ break+ reader_thread.join()+ return not source_failed+ except OSError:+ reader_thread.join()+ return False+ finally:+ lock_stop.set()+ lock_thread.join(timeout=1.0)+ if lock_acquired:+ lock.release()+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("path", type=Path)+ parser.add_argument("--max-bytes", type=int, default=RUNTIME_LOG_MAX_BYTES)+ parser.add_argument("--retain-bytes", type=int, default=RUNTIME_LOG_RETAIN_BYTES)+ args = parser.parse_args(argv)+ copied = copy_bounded_log(+ sys.stdin.buffer,+ args.path,+ max_bytes=max(1, args.max_bytes),+ retain_bytes=max(0, args.retain_bytes),+ )+ return 0 if copied else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/vibe/logging_config.py b/vibe/logging_config.pynew file mode 100644index 000000000..e4db26d05--- /dev/null+++ b/vibe/logging_config.py@@ -0,0 +1,16 @@+from __future__ import annotations++from pathlib import Path+++APPLICATION_LOG_MAX_BYTES = 20 * 1024 * 1024+APPLICATION_LOG_BACKUP_COUNT = 5+++def application_log_paths(current_path: Path) -> list[Path]:+ """Return application log generations from oldest to current."""++ return [+ *(current_path.with_name(f"{current_path.name}.{index}") for index in range(APPLICATION_LOG_BACKUP_COUNT, 0, -1)),+ current_path,+ ]diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 17bf21eb6..9774b4030 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -27,6 +27,7 @@ from config.v2_config import (SlackConfig,V2Config,)+from vibe.log_sink import RUNTIME_LOG_MAX_BYTES, RUNTIME_LOG_RETAIN_BYTESlogger = logging.getLogger(__name__)@@ -782,19 +783,56 @@ def _log_path(name: str) -> Path:return paths.get_runtime_dir() / name+def _spawn_runtime_log_sink(path: Path) -> subprocess.Popen:+ return subprocess.Popen(+ [+ sys.executable,+ "-m",+ "vibe.log_sink",+ str(path),+ "--max-bytes",+ str(RUNTIME_LOG_MAX_BYTES),+ "--retain-bytes",+ str(RUNTIME_LOG_RETAIN_BYTES),+ ],+ stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ cwd=str(get_working_dir()),+ close_fds=True,+ )+++def _spawn_runtime_log_sinks(stdout_path: Path, stderr_path: Path) -> tuple[subprocess.Popen, subprocess.Popen]:+ stdout_sink = _spawn_runtime_log_sink(stdout_path)+ try:+ stderr_sink = _spawn_runtime_log_sink(stderr_path)+ except Exception:+ if stdout_sink.stdin is not None:+ stdout_sink.stdin.close()+ raise+ if stdout_sink.stdin is None or stderr_sink.stdin is None:+ if stdout_sink.stdin is not None:+ stdout_sink.stdin.close()+ if stderr_sink.stdin is not None:+ stderr_sink.stdin.close()+ raise RuntimeError("Failed to create runtime log sink pipes")+ return stdout_sink, stderr_sink++def spawn_background(args, pid_path, stdout_name: str, stderr_name: str, env: dict[str, str] | None = None):stdout_path = _log_path(stdout_name)stderr_path = _log_path(stderr_name)stdout_path.parent.mkdir(parents=True, exist_ok=True)- stdout = stdout_path.open("ab")- stderr = stderr_path.open("ab")+ stdout_sink, stderr_sink = _spawn_runtime_log_sinks(stdout_path, stderr_path)stdin = open(os.devnull, "rb")try:process = subprocess.Popen(args,stdin=stdin,- stdout=stdout,- stderr=stderr,+ stdout=stdout_sink.stdin,+ stderr=stderr_sink.stdin,start_new_session=True,cwd=str(get_working_dir()),close_fds=True,@@ -802,8 +840,8 @@ def spawn_background(args, pid_path, stdout_name: str, stderr_name: str, env: di)finally:stdin.close()- stdout.close()- stderr.close()+ stdout_sink.stdin.close()+ stderr_sink.stdin.close()pid_path.write_text(str(process.pid), encoding="utf-8")return process.pid@@ -817,15 +855,14 @@ def spawn_service_background_process(stdout_path = _log_path(stdout_name)stderr_path = _log_path(stderr_name)stdout_path.parent.mkdir(parents=True, exist_ok=True)- stdout = stdout_path.open("ab")- stderr = stderr_path.open("ab")+ stdout_sink, stderr_sink = _spawn_runtime_log_sinks(stdout_path, stderr_path)stdin = open(os.devnull, "rb")try:process = subprocess.Popen(args,stdin=stdin,- stdout=stdout,- stderr=stderr,+ stdout=stdout_sink.stdin,+ stderr=stderr_sink.stdin,start_new_session=True,cwd=str(get_working_dir()),close_fds=True,@@ -833,8 +870,8 @@ def spawn_service_background_process()finally:stdin.close()- stdout.close()- stderr.close()+ stdout_sink.stdin.close()+ stderr_sink.stdin.close()return processdiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 94caf0f2b..66a36faf8 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -17,7 +17,7 @@ import socketimport subprocessimport threadingimport time-from collections import OrderedDict+from collections import OrderedDict, dequefrom contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Path@@ -48,6 +48,7 @@ from core.show_session_events import show_event_payload_session_mismatchfrom core.terminal_service import TERMINAL_SUPPORTED, TerminalService, TerminalServiceError, sanitize_session_idfrom modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refreshfrom vibe.i18n import get_supported_languages, t+from vibe.logging_config import application_log_pathsfrom vibe.runtime import get_ui_dist_path, get_working_dirfrom vibe.sentry_integration import init_sentry@@ -2225,17 +2226,25 @@ def renew_remote_access_cookie(response: Response) -> Response:def _read_log_entries(log_path: Path, source_key: str, lines: int) -> tuple[list[dict[str, Any]], int]:- if not log_path.exists():+ log_paths = application_log_paths(log_path) if source_key == "service" else [log_path]+ existing_paths = [path for path in log_paths if path.exists()]+ if not existing_paths:return [], 0- with log_path.open("r", encoding="utf-8", errors="replace") as f:- all_lines = f.readlines()- recent_lines = all_lines[-lines:] if len(all_lines) > lines else all_lines- file_sort_ns = log_path.stat().st_mtime_ns- first_recent_line_index = len(all_lines) - len(recent_lines)+ recent_lines: deque[tuple[str, int, int]] = deque(maxlen=lines)+ total_lines = 0+ for path in existing_paths:+ try:+ file_sort_ns = path.stat().st_mtime_ns+ with path.open("r", encoding="utf-8", errors="replace") as log_file:+ for raw_line in log_file:+ recent_lines.append((raw_line, file_sort_ns, total_lines))+ total_lines += 1+ except OSError:+ continuelogs_list: list[dict[str, Any]] = []- for line_offset, raw_line in enumerate(recent_lines):+ for raw_line, file_sort_ns, line_index in recent_lines:line = raw_line.rstrip("\n")match = STRUCTURED_LOG_PATTERN.match(line)if match:@@ -2248,7 +2257,7 @@ def _read_log_entries(log_path: Path, source_key: str, lines: int) -> tuple[list"message": match.group(4),"source": source_key,"_sort_ns": _timestamp_to_sort_ns(parsed_timestamp) or file_sort_ns,- "_sort_index": first_recent_line_index + line_offset,+ "_sort_index": line_index,})continue@@ -2262,10 +2271,10 @@ def _read_log_entries(log_path: Path, source_key: str, lines: int) -> tuple[listfallback_entry = _fallback_log_entry(line, source_key)fallback_entry["_sort_ns"] = file_sort_ns- fallback_entry["_sort_index"] = first_recent_line_index + line_offset+ fallback_entry["_sort_index"] = line_indexlogs_list.append(fallback_entry)- return logs_list, len(all_lines)+ return logs_list, total_linesdef _resolve_log_sources() -> list[dict[str, Any]]:@@ -2279,12 +2288,13 @@ def _resolve_log_sources() -> list[dict[str, Any]]:]for key, filename, path_factory in LOG_SOURCES:path = path_factory()+ exists = any(candidate.exists() for candidate in application_log_paths(path)) if key == "service" else path.exists()resolved.append({"key": key,"filename": filename,"path": str(path),- "exists": path.exists(),+ "exists": exists,})return resolved@@ -4179,33 +4189,22 @@ def ui_reload():def _restart():global _server- import subprocessimport sysimport timefrom config import paths as config_paths- working_dir = get_working_dir()command = f"from vibe.ui_server import run_ui_server; run_ui_server('{bind_host}', {port})"- stdout_path = config_paths.get_runtime_dir() / "ui_stdout.log"- stderr_path = config_paths.get_runtime_dir() / "ui_stderr.log"- stdout = stdout_path.open("ab")- stderr = stderr_path.open("ab")- process = subprocess.Popen(+ pid = runtime.spawn_background([sys.executable, "-c", command],- stdout=stdout,- stderr=stderr,- start_new_session=True,- cwd=str(working_dir),- close_fds=True,+ config_paths.get_runtime_ui_pid_path(),+ "ui_stdout.log",+ "ui_stderr.log",)- stdout.close()- stderr.close()- config_paths.get_runtime_ui_pid_path().write_text(str(process.pid), encoding="utf-8")runtime.write_status(status.get("state", "running"),status.get("detail"),status.get("service_pid"),- process.pid,+ pid,)time.sleep(0.2)# Shutdown the old server to release the port