Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(show): platform-owned git checkpoints for show workspaces (#869)

Call White84527206dc1b
diff --git a/config/paths.py b/config/paths.py
index 2535a7234..41f60ba67 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -134,6 +134,14 @@ def get_show_page_dir(session_id: str) -> Path:
return get_show_pages_dir() / session_id
+def get_show_git_dir(session_id: str) -> Path:
+ return get_vibe_remote_dir() / "show-git" / f"{session_id}.git"
+
+
+def get_show_git_runtime_status_path() -> Path:
+ return get_runtime_dir() / "show-git-checkpoints.json"
+
+
def get_runtime_pid_path() -> Path:
return get_runtime_dir() / "vibe.pid"
diff --git a/core/controller.py b/core/controller.py
index 7dd3bbf9c..f2314359f 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -30,6 +30,7 @@ from core.message_output import MessageOutput
from core.processing_indicator import ProcessingIndicatorService
from core.runtime_commands import RuntimeCommandWatcher
from core.scheduled_tasks import ScheduledTaskService
+from core.show_git import ShowGitCheckpointService
from core.update_checker import UpdateChecker
from core.watches import ManagedWatchService
from core.vibe_agents import VibeAgent, VibeAgentStore
@@ -247,6 +248,7 @@ class Controller:
self.scheduled_task_service = ScheduledTaskService(self)
self.watch_service = ManagedWatchService(self)
self.runtime_command_watcher = RuntimeCommandWatcher(self)
+ self.show_git_checkpoint_service = ShowGitCheckpointService()
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
@@ -676,6 +678,10 @@ class Controller:
from core.services.dispatch import dispatch_turn
async def _on_im_message(context, text):
+ checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
+ mark_im_turn = getattr(checkpoint_service, "mark_im_turn", None)
+ if callable(mark_im_turn):
+ mark_im_turn(context)
await dispatch_turn(self, context, text)
# Register callbacks with the IM client
@@ -1105,7 +1111,11 @@ class Controller:
return self.platform_settings_managers.get(platform, self.platform_settings_managers[self.primary_platform])
def update_thread_message_id(self, context: MessageContext) -> None:
- """Update message tracking for consolidated log dispatch."""
+ """Run real-turn-start hooks after the runtime gate is acquired."""
+ checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
+ begin_im_turn = getattr(checkpoint_service, "begin_im_turn", None)
+ if callable(begin_im_turn):
+ begin_im_turn(self, context)
self.message_dispatcher.update_thread_message_id(context)
async def clear_consolidated_message_id(
@@ -1267,17 +1277,28 @@ class Controller:
output: MessageOutput | None = None,
):
"""Backward-compatible entrypoint; delegated to message dispatcher."""
- return await self.message_dispatcher.emit_agent_message(
- context=context,
- message_type=message_type,
- text=text,
- parse_mode=parse_mode,
- is_error=is_error,
- level=level,
- status_label=status_label,
- result_footer=result_footer,
- output=output,
+ checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
+ should_end_im_turn = getattr(checkpoint_service, "should_end_im_turn", None)
+ publish_checkpoint_end = bool(
+ should_end_im_turn(self, context, message_type, output=output)
+ if callable(should_end_im_turn)
+ else False
)
+ try:
+ return await self.message_dispatcher.emit_agent_message(
+ context=context,
+ message_type=message_type,
+ text=text,
+ parse_mode=parse_mode,
+ is_error=is_error,
+ level=level,
+ status_label=status_label,
+ result_footer=result_footer,
+ output=output,
+ )
+ finally:
+ if publish_checkpoint_end:
+ checkpoint_service.end_im_turn(context)
def note_session_tokens(self, context: MessageContext, *, total: int) -> None:
"""Report the session's current context-window occupancy for the status
@@ -1306,6 +1327,7 @@ class Controller:
try:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
+ self.show_git_checkpoint_service.start()
self._im_thread = threading.Thread(target=self._run_im_runtime, name="im-runtime", daemon=True)
self._im_thread.start()
# Internal Unix-socket ASGI server for the Web UI / future
@@ -1449,6 +1471,9 @@ class Controller:
_stop_loop_coroutine(self.scheduled_task_service.stop(), "Scheduled task service")
_stop_loop_coroutine(self.watch_service.stop(), "Watch service")
_stop_loop_coroutine(self.runtime_command_watcher.stop(), "Runtime command watcher")
+ show_git_checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
+ if show_git_checkpoint_service is not None:
+ show_git_checkpoint_service.stop()
try:
codex_agent = self.agent_service.agents.get("codex")
diff --git a/core/git_binary.py b/core/git_binary.py
new file mode 100644
index 000000000..58d57a954
--- /dev/null
+++ b/core/git_binary.py
@@ -0,0 +1,49 @@
+"""Resolve the Git executable used by platform-owned features."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class ResolvedGit:
+ path: Path
+ source: str # "vendored" | "system"
+
+
+def _resolve_vendored() -> ResolvedGit | None:
+ # TODO(#867): resolve the managed minimal Git bundle once it ships.
+ return None
+
+
+def _macos_command_line_tools_available() -> bool:
+ try:
+ result = subprocess.run(
+ ["/usr/bin/xcode-select", "-p"],
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+ return result.returncode == 0 and bool(result.stdout.strip())
+
+
+def resolve_git() -> ResolvedGit | None:
+ vendored = _resolve_vendored()
+ if vendored is not None:
+ return vendored
+
+ candidate = shutil.which("git")
+ if not candidate:
+ return None
+ path = Path(candidate)
+ if sys.platform == "darwin" and path == Path("/usr/bin/git"):
+ if not _macos_command_line_tools_available():
+ return None
+ return ResolvedGit(path=path, source="system")
diff --git a/core/inbox_events.py b/core/inbox_events.py
index aba59622b..c8128063a 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -15,7 +15,7 @@ from __future__ import annotations
import asyncio
import logging
import threading
-from typing import Any
+from typing import Any, Callable
logger = logging.getLogger(__name__)
@@ -37,6 +37,7 @@ def is_controller_process() -> bool:
class InboxEventBus:
def __init__(self) -> None:
self._subscribers: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Queue]] = {}
+ self._callbacks: dict[int, Callable[[str, Any], None]] = {}
self._next_id = 0
self._lock = threading.Lock()
@@ -49,9 +50,24 @@ class InboxEventBus:
self._subscribers[sub_id] = (loop, queue)
return sub_id, queue
+ def subscribe_callback(self, callback: Callable[[str, Any], None]) -> int:
+ """Register an in-process callback run synchronously before queue fan-out.
+
+ Turn-boundary owners use this path when the work triggered by an event
+ must finish before the publisher continues. Exceptions are isolated so a
+ diagnostic/checkpoint subscriber can never break message delivery.
+ """
+
+ with self._lock:
+ sub_id = self._next_id
+ self._next_id += 1
+ self._callbacks[sub_id] = callback
+ return sub_id
+
def unsubscribe(self, sub_id: int) -> None:
with self._lock:
self._subscribers.pop(sub_id, None)
+ self._callbacks.pop(sub_id, None)
def subscriber_count(self) -> int:
with self._lock:
@@ -61,8 +77,12 @@ class InboxEventBus:
"""Fan ``(event_type, data)`` out to every subscriber. No-op when none."""
with self._lock:
subs = list(self._subscribers.values())
- if not subs:
- return
+ callbacks = list(self._callbacks.values())
+ for callback in callbacks:
+ try:
+ callback(event_type, data)
+ except Exception:
+ logger.exception("inbox event callback failed for %s", event_type)
for loop, queue in subs:
try:
loop.call_soon_threadsafe(self._put_nowait, queue, event_type, data)
diff --git a/core/internal_server.py b/core/internal_server.py
index e97b9ce46..47236140a 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -72,7 +72,7 @@ def create_app(controller: "Controller") -> FastAPI:
Factored out so tests can mount the same routes against a fake
controller without spinning up uvicorn.
"""
- from core.inbox_events import mark_controller_process
+ from core.inbox_events import bus, mark_controller_process
mark_controller_process()
@@ -299,12 +299,23 @@ def create_app(controller: "Controller") -> FastAPI:
logger.exception("internal dispatch failed for session=%s", session_id)
await chunk_queue.put({"kind": "error", "text": str(err)})
finally:
+ # This legacy streaming route invokes dispatch_turn directly, so it
+ # bypasses SessionTurnManager._run_turn, which owns lifecycle bus
+ # events for Chat/scheduled turns. The two paths are exclusive:
+ # streaming lifecycle is owned here; manager lifecycle stays in
+ # core/session_turns.py. Publishing before the sentinel also makes
+ # post-turn subscribers finish before queued work can be flushed.
+ if isinstance(session_id, str) and session_id:
+ bus.publish("turn.end", {"session_id": session_id})
# Sentinel signals end-of-stream to the consumer below.
await chunk_queue.put(None)
task = asyncio.create_task(_runner(), name="internal-dispatch")
if isinstance(session_id, str) and session_id:
in_flight[session_id] = Turn(task=task, context=context)
+ # create_task cannot run until this coroutine yields, so synchronous
+ # pre-turn subscribers complete before the backend can touch files.
+ bus.publish("turn.start", {"session_id": session_id})
async def _stream():
saw_cancel = False
diff --git a/core/show_git.py b/core/show_git.py
new file mode 100644
index 000000000..49c73fdfb
--- /dev/null
+++ b/core/show_git.py
@@ -0,0 +1,781 @@
+"""Native Git checkpoints for existing Show Page workspaces."""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import shutil
+import subprocess
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from config import paths
+from core.git_binary import ResolvedGit, resolve_git
+from core.message_output import MessageOutput
+
+logger = logging.getLogger(__name__)
+
+PRE_TURN = "pre-turn"
+POST_TURN = "post-turn"
+ADOPT = "adopt"
+MAX_COMMITS = 500
+MAX_GITDIR_BYTES = 200 * 1024 * 1024
+STALE_INDEX_LOCK_SECONDS = 5 * 60
+GIT_COMMAND_TIMEOUT_SECONDS = 60
+GIT_MAINTENANCE_TIMEOUT_SECONDS = 5 * 60
+
+_PLATFORM_EXCLUDES = ("node_modules/", "dist/", ".vite/")
+_CHECKPOINT_KINDS = {PRE_TURN, POST_TURN, ADOPT}
+_MANAGED_POINTER_PARENT = "show-git"
+_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
+_MAIN_ANCHOR_REF = "refs/avibe/checkpoint-main"
+_IM_TURN_STATE_KEY = "_avibe_show_git_checkpoint"
+_CHECKPOINT_STATUS_VERSION = 1
+_checkpoint_service_active: bool | None = None
+_SCRUBBED_GIT_ENV = {
+ "GIT_DIR",
+ "GIT_WORK_TREE",
+ "GIT_INDEX_FILE",
+ "GIT_OBJECT_DIRECTORY",
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
+ "GIT_COMMON_DIR",
+ "GIT_CONFIG_PARAMETERS",
+ "GIT_AUTHOR_NAME",
+ "GIT_AUTHOR_EMAIL",
+ "GIT_AUTHOR_DATE",
+ "GIT_COMMITTER_NAME",
+ "GIT_COMMITTER_EMAIL",
+ "GIT_COMMITTER_DATE",
+ "EMAIL",
+}
+
+SHOW_GIT_AGENT_CONTRACT = (
+ "History is saved automatically around each turn; do not manage versions yourself.",
+ "Read freely: `git -C <workspace> status / log / diff / show`.",
+ "Restore only via `git restore --source=<ref> -- <path>`; the turn-end checkpoint records it as a forward commit.",
+ "Never move HEAD, switch branches, rewrite history, or run gc; if you do, the platform self-heals with the worktree as truth.",
+ "Never add remotes, push, or publish the workspace anywhere unless the user explicitly asks.",
+)
+SHOW_GIT_SELF_MANAGED_AGENT_CONTRACT = (
+ "Avibe's shadow history continues automatically in the background; you don't manage it.",
+ "`git -C <workspace>` addresses the **user's repo**, not Avibe history: never commit, push, or publish on their behalf, and never use it for Avibe restore.",
+ "Never locate or mutate Avibe's shadow gitdir on your own initiative. Only if the user explicitly asks to recover from Avibe history, use standard git with explicit `--git-dir` and `--work-tree` against the session's shadow gitdir for read or restore only; never commit to it.",
+)
+SHOW_GIT_UNAVAILABLE_AGENT_CONTRACT = (
+ "Automatic Show Page history is unavailable because Git could not be resolved for this process. Continue editing normally, but do not use history or restore commands for this workspace.",
+)
+
+
+class ShowGitError(RuntimeError):
+ """A platform Git operation failed."""
+
+
+@dataclass(frozen=True)
+class TurnCheckpointContext:
+ message: str = ""
+ run_id: str | None = None
+ message_id: str | None = None
+
+
+@dataclass(frozen=True)
+class _ActiveTurnCheckpoint:
+ context: TurnCheckpointContext
+ started_at: str
+
+
+def _record_checkpoint_service_state(active: bool) -> None:
+ global _checkpoint_service_active
+
+ _checkpoint_service_active = active
+ status_path = paths.get_show_git_runtime_status_path()
+ temporary = status_path.with_name(f".{status_path.name}.{os.getpid()}.tmp")
+ payload = {
+ "version": _CHECKPOINT_STATUS_VERSION,
+ "active": active,
+ "service_pid": os.getpid(),
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ }
+ try:
+ status_path.parent.mkdir(parents=True, exist_ok=True)
+ temporary.write_text(json.dumps(payload, sort_keys=True) + "\n", encoding="utf-8")
+ os.replace(temporary, status_path)
+ except OSError:
+ logger.warning("failed to persist Show Page checkpoint service state", exc_info=True)
+ finally:
+ try:
+ temporary.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+def show_git_checkpointing_active() -> bool:
+ """Return the running service's startup-latched checkpoint capability."""
+
+ if _checkpoint_service_active is not None:
+ return _checkpoint_service_active
+ try:
+ payload = json.loads(paths.get_show_git_runtime_status_path().read_text(encoding="utf-8"))
+ if payload.get("version") != _CHECKPOINT_STATUS_VERSION or payload.get("active") is not True:
+ return False
+ service_pid = int(payload.get("service_pid") or 0)
+ from vibe.runtime import resolve_service_owner_pid
+
+ return service_pid > 0 and resolve_service_owner_pid(include_starting=False) == service_pid
+ except (OSError, TypeError, ValueError, json.JSONDecodeError):
+ return False
+
+
+def _read_git_pointer(pointer: Path) -> Path | None:
+ if pointer.is_symlink() or not pointer.is_file():
+ return None
+ try:
+ lines = pointer.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ return None
+ if len(lines) != 1 or not lines[0].startswith("gitdir: "):
+ return None
+ raw = lines[0].removeprefix("gitdir: ").strip()
+ if not raw:
+ return None
+ target = Path(raw).expanduser()
+ if not target.is_absolute():
+ target = pointer.parent / target
+ return target.resolve(strict=False)
+
+
+def _workspace_ownership(workspace: Path, gitdir: Path) -> tuple[bool, bool]:
+ pointer = workspace / ".git"
+ if not pointer.exists() and not pointer.is_symlink():
+ return True, False
+ target = _read_git_pointer(pointer)
+ if target is None:
+ return False, False
+ expected = gitdir.resolve(strict=False)
+ if target == expected:
+ return True, False
+ if not target.exists() and target.name == gitdir.name and target.parent.name == _MANAGED_POINTER_PARENT:
+ return True, True
+ return False, False
+
+
+def _workspace_is_self_managed(session_id: str) -> bool:
+ if not _SESSION_ID_PATTERN.fullmatch(str(session_id or "")):
+ return True
+ managed, _rewrite_pointer = _workspace_ownership(
+ paths.get_show_page_dir(session_id),
+ paths.get_show_git_dir(session_id),
+ )
+ return not managed
+
+
+def format_agent_contract(
+ *,
+ numbered: bool = False,
+ checkpointing_available: bool | None = None,
+ session_id: str | None = None,
+) -> str:
+ if checkpointing_available is None:
+ checkpointing_available = show_git_checkpointing_active()
+ if not checkpointing_available:
+ lines = SHOW_GIT_UNAVAILABLE_AGENT_CONTRACT
+ elif session_id is not None and _workspace_is_self_managed(session_id):
+ lines = SHOW_GIT_SELF_MANAGED_AGENT_CONTRACT
+ else:
+ lines = SHOW_GIT_AGENT_CONTRACT
+ if numbered:
+ return "\n".join(f"{index}. {line}" for index, line in enumerate(lines, start=1))
+ return "\n".join(f"- {line}" for line in lines)
+
+
+def _single_line(value: Any) -> str:
+ without_controls = "".join(" " if ord(char) < 32 or ord(char) == 127 else char for char in str(value or ""))
+ return " ".join(without_controls.split())
+
+
+def sanitize_checkpoint_subject(message: str | None) -> str:
+ return _single_line(message)[:72].rstrip() or "checkpoint"
+
+
+def _checkpoint_message(subject: str, *, session_id: str, run_id: str | None, checkpoint: str) -> str:
+ safe_run_id = _single_line(run_id) or "-"
+ return (
+ f"{subject}\n\n"
+ f"Avibe-Session: {session_id}\n"
+ f"Avibe-Run: {safe_run_id}\n"
+ f"Avibe-Checkpoint: {checkpoint}"
+ )
+
+
+def _git_environment() -> dict[str, str]:
+ env = dict(os.environ)
+ for key in list(env):
+ if key in _SCRUBBED_GIT_ENV or key.startswith("GIT_CONFIG_KEY_") or key.startswith("GIT_CONFIG_VALUE_"):
+ env.pop(key, None)
+ env.pop("GIT_CONFIG_COUNT", None)
+ env["GIT_CONFIG_GLOBAL"] = os.devnull
+ env["GIT_CONFIG_SYSTEM"] = os.devnull
+ return env
+
+
+def _read_message_text(content_text: Any, content_json: Any) -> str:
+ text = str(content_text or "").strip()
+ if text:
+ return text
+ try:
+ content = json.loads(content_json or "{}")
+ except (TypeError, ValueError):
+ return ""
+ return str(content.get("text") or "").strip() if isinstance(content, dict) else ""
+
+
+def _run_id_from_native_message_id(value: Any) -> str | None:
+ native_id = str(value or "").strip()
+ if not native_id.startswith("agent_run:"):
+ return None
+ run_id = native_id.removeprefix("agent_run:").strip()
+ return run_id or None
+
+
+def load_turn_checkpoint_context(session_id: str, *, after: str | None = None) -> TurnCheckpointContext:
+ """Read the driving message/run without changing the turn event payload."""
+
+ try:
+ from sqlalchemy import select
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import agent_runs, messages
+
+ with get_cached_sqlite_engine().connect() as conn:
+ active_run = conn.execute(
+ select(agent_runs.c.id, agent_runs.c.message, agent_runs.c.prompt)
+ .where(agent_runs.c.session_id == session_id)
+ .where(agent_runs.c.status.in_(("running", "processing")))
+ .where(agent_runs.c.run_type != "watch_runtime")
+ .order_by(agent_runs.c.started_at.desc(), agent_runs.c.created_at.desc(), agent_runs.c.id.desc())
+ .limit(1)
+ ).first()
+ if active_run is not None:
+ text = str(active_run.message or active_run.prompt or "").strip()
+ run_id = str(active_run.id)
+ return TurnCheckpointContext(message=text, run_id=run_id, message_id=f"agent_run:{run_id}")
+
+ message_query = select(
+ messages.c.id,
+ messages.c.type,
+ messages.c.content_text,
+ messages.c.content_json,
+ messages.c.native_message_id,
+ ).where(messages.c.session_id == session_id)
+ if after is None:
+ message_query = (
+ message_query.where(messages.c.type.not_in(("queued", "draft", "harness_dedupe")))
+ .order_by(messages.c.created_at.desc(), messages.c.id.desc())
+ .limit(1)
+ )
+ else:
+ message_query = (
+ message_query.where(messages.c.type.in_(("user", "pending")))
+ .where(messages.c.created_at >= after)
+ .order_by(messages.c.created_at.asc(), messages.c.id.asc())
+ .limit(1)
+ )
+ message_row = conn.execute(message_query).first()
+ if message_row is None or message_row.type not in {"user", "pending"}:
+ return TurnCheckpointContext()
+ return TurnCheckpointContext(
+ message=_read_message_text(message_row.content_text, message_row.content_json),
+ run_id=_run_id_from_native_message_id(message_row.native_message_id),
+ message_id=str(message_row.id),
+ )
+ except Exception:
+ logger.debug("show checkpoint metadata lookup failed for session=%s", session_id, exc_info=True)
+ return TurnCheckpointContext()
+
+
+class ShowGitRepository:
+ def __init__(
+ self,
+ session_id: str,
+ git: ResolvedGit,
+ *,
+ workspace: Path | None = None,
+ gitdir: Path | None = None,
+ ) -> None:
+ if not _SESSION_ID_PATTERN.fullmatch(str(session_id or "")):
+ raise ValueError("invalid Show Page session id")
+ self.session_id = session_id
+ self.git = git
+ self.workspace = workspace or paths.get_show_page_dir(session_id)
+ self.gitdir = gitdir or paths.get_show_git_dir(session_id)
+ self.hooks_dir = self.gitdir / "avibe-empty-hooks"
+
+ def checkpoint(self, checkpoint: str, *, message: str = "", run_id: str | None = None) -> bool:
+ if checkpoint not in {PRE_TURN, POST_TURN}:
+ raise ValueError(f"unsupported checkpoint kind: {checkpoint}")
+ if not self.workspace.is_dir():
+ return False
+
+ managed, rewrite_pointer = self._workspace_ownership()
+ initialized = self._ensure_repository()
+ self._remove_stale_index_lock()
+ self._ensure_platform_config()
+ self._ensure_empty_hooks_dir()
+ self._ensure_platform_excludes()
+ if managed:
+ self._ensure_pointer(rewrite=rewrite_pointer)
+ self._reattach_main()
+ self._restore_forward_main()
+
+ if initialized or not self._has_commits():
+ created = self._commit_all(
+ "adopt existing workspace",
+ run_id=run_id,
+ checkpoint=ADOPT,
+ allow_empty=True,
+ )
+ else:
+ subject = "out-of-band changes" if checkpoint == PRE_TURN else sanitize_checkpoint_subject(message)
+ created = self._commit_if_dirty(subject, run_id=run_id, checkpoint=checkpoint)
+
+ self._prune_if_needed()
+ self._record_main_anchor()
+ return created
+
+ def _workspace_ownership(self) -> tuple[bool, bool]:
+ return _workspace_ownership(self.workspace, self.gitdir)
+
+ def _ensure_repository(self) -> bool:
+ valid = (self.gitdir / "HEAD").is_file() and (self.gitdir / "objects").is_dir()
+ if valid:
+ return False
+ self.gitdir.parent.mkdir(parents=True, exist_ok=True)
+ result = self._run_raw(
+ ["init", "--bare", str(self.gitdir)],
+ timeout=GIT_COMMAND_TIMEOUT_SECONDS,
+ )
+ if result.returncode != 0:
+ raise ShowGitError(result.stderr.strip() or "failed to initialize Show Page checkpoint repository")
+ self._run_checked(["symbolic-ref", "HEAD", "refs/heads/main"])
+ return True
+
+ def _ensure_platform_config(self) -> None:
+ self._run_checked(["config", "core.bare", "false"])
+
+ def _ensure_empty_hooks_dir(self) -> None:
+ if self.hooks_dir.is_symlink() or (self.hooks_dir.exists() and not self.hooks_dir.is_dir()):
+ self.hooks_dir.unlink()
+ self.hooks_dir.mkdir(parents=True, exist_ok=True)
+ for child in self.hooks_dir.iterdir():
+ if child.is_dir() and not child.is_symlink():
+ shutil.rmtree(child)
+ else:
+ child.unlink()
+
+ def _ensure_platform_excludes(self) -> None:
+ exclude = self.gitdir / "info" / "exclude"
+ exclude.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ existing = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
+ except OSError as exc:
+ raise ShowGitError(f"failed to read checkpoint excludes: {exc}") from exc
+ existing_lines = set(existing.splitlines())
+ missing = [pattern for pattern in _PLATFORM_EXCLUDES if pattern not in existing_lines]
+ if not missing:
+ return
+ prefix = existing
+ if prefix and not prefix.endswith("\n"):
+ prefix += "\n"
+ exclude.write_text(prefix + "\n".join(missing) + "\n", encoding="utf-8")
+
+ def _ensure_pointer(self, *, rewrite: bool) -> None:
+ pointer = self.workspace / ".git"
+ if pointer.exists() or pointer.is_symlink():
+ if not rewrite:
+ return
+ if pointer.is_symlink() or not pointer.is_file():
+ return
+ temporary = self.gitdir / f"avibe-git-pointer-{os.getpid()}.tmp"
+ try:
+ temporary.write_text(f"gitdir: {self.gitdir.resolve(strict=False)}\n", encoding="utf-8")
+ os.replace(temporary, pointer)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+ def _remove_stale_index_lock(self) -> None:
+ lock = self.gitdir / "index.lock"
+ try:
+ age = time.time() - lock.stat().st_mtime
+ except OSError:
+ return
+ if age <= STALE_INDEX_LOCK_SECONDS:
+ return
+ try:
+ lock.unlink()
+ except OSError:
+ logger.warning("failed to remove stale Show Page checkpoint index lock: %s", lock, exc_info=True)
+
+ def _reattach_main(self) -> None:
+ current = self._run(["symbolic-ref", "-q", "HEAD"], check=False)
+ if current.returncode == 0 and current.stdout.strip() == "refs/heads/main":
+ return
+ self._run_checked(["symbolic-ref", "HEAD", "refs/heads/main"])
+
+ def _restore_forward_main(self) -> None:
+ anchor = self._run(["rev-parse", "--verify", _MAIN_ANCHOR_REF], check=False)
+ if anchor.returncode != 0:
+ return
+ anchor_oid = anchor.stdout.strip()
+ current = self._run(["rev-parse", "--verify", "refs/heads/main"], check=False)
+ if current.returncode != 0:
+ self._run_checked(["update-ref", "refs/heads/main", anchor_oid])
+ return
+ current_oid = current.stdout.strip()
+ ancestry = self._run(["merge-base", "--is-ancestor", anchor_oid, current_oid], check=False)
+ if ancestry.returncode == 0:
+ return
+ if ancestry.returncode != 1:
+ raise ShowGitError(ancestry.stderr.strip() or "failed to verify Show Page checkpoint ancestry")
+ self._run_checked(["update-ref", "refs/heads/main", anchor_oid, current_oid])
+
+ def _record_main_anchor(self) -> None:
+ head = self._run_checked(["rev-parse", "refs/heads/main"]).stdout.strip()
+ self._run_checked(["update-ref", _MAIN_ANCHOR_REF, head])
+
+ def _has_commits(self) -> bool:
+ return self._run(["rev-parse", "--verify", "HEAD"], check=False).returncode == 0
+
+ def _commit_if_dirty(self, subject: str, *, run_id: str | None, checkpoint: str) -> bool:
+ status = self._run_checked(["status", "--porcelain=v1", "--untracked-files=all"])
+ if not status.stdout:
+ return False
+ return self._commit_all(subject, run_id=run_id, checkpoint=checkpoint, allow_empty=False)
+
+ def _commit_all(self, subject: str, *, run_id: str | None, checkpoint: str, allow_empty: bool) -> bool:
+ if checkpoint not in _CHECKPOINT_KINDS:
+ raise ValueError(f"unsupported commit checkpoint kind: {checkpoint}")
+ self._run_checked(["add", "-A"])
+ command = ["commit"]
+ if allow_empty:
+ command.append("--allow-empty")
+ command.extend(
+ [
+ "-m",
+ _checkpoint_message(
+ subject,
+ session_id=self.session_id,
+ run_id=run_id,
+ checkpoint=checkpoint,
+ ),
+ ]
+ )
+ result = self._run(command, check=False)
+ if result.returncode == 0:
+ return True
+ if not allow_empty and "nothing to commit" in result.stdout.lower():
+ return False
+ raise ShowGitError(result.stderr.strip() or result.stdout.strip() or "failed to commit Show Page checkpoint")
+
+ def _prune_if_needed(self) -> None:
+ if not self._has_commits():
+ return
+ count_result = self._run_checked(["rev-list", "--count", "refs/heads/main"])
+ try:
+ commit_count = int(count_result.stdout.strip())
+ except ValueError:
+ commit_count = 0
+ if commit_count <= MAX_COMMITS and self._gitdir_size_at_most(MAX_GITDIR_BYTES):
+ return
+
+ remotes = self._run_checked(["remote"])
+ if remotes.stdout.strip():
+ self._run_checked(["gc"], timeout=GIT_MAINTENANCE_TIMEOUT_SECONDS)
+ return
+
+ old_head = self._run_checked(["rev-parse", "refs/heads/main"]).stdout.strip()
+ tree = self._run_checked(["rev-parse", "refs/heads/main^{tree}"]).stdout.strip()
+ message = self._run_checked(["log", "-1", "--format=%B", "refs/heads/main"]).stdout.rstrip()
+ baseline = self._run_checked(["commit-tree", tree], input_text=message + "\n").stdout.strip()
+ self._run_checked(["update-ref", "refs/heads/main", baseline, old_head])
+
+ refs = self._run_checked(["for-each-ref", "--format=%(refname)"]).stdout.splitlines()
+ for ref in refs:
+ if ref and ref != "refs/heads/main":
+ self._run_checked(["update-ref", "-d", ref])
+ self._run_checked(["reflog", "expire", "--expire=now", "--all"])
+ self._run_checked(["gc", "--prune=now"], timeout=GIT_MAINTENANCE_TIMEOUT_SECONDS)
+
+ def _gitdir_size_at_most(self, limit: int) -> bool:
+ total = 0
+ try:
+ for root, _dirs, files in os.walk(self.gitdir):
+ for filename in files:
+ try:
+ total += (Path(root) / filename).stat().st_size
+ except OSError:
+ continue
+ if total > limit:
+ return False
+ except OSError:
+ return True
+ return True
+
+ def _base_command(self) -> list[str]:
+ return [
+ str(self.git.path),
+ "-c",
+ "user.name=avibe-checkpoint",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "-c",
+ f"core.hooksPath={self.hooks_dir}",
+ "-c",
+ "gc.auto=0",
+ ]
+
+ def _run_raw(
+ self,
+ args: list[str],
+ *,
+ timeout: int,
+ input_text: str | None = None,
+ ) -> subprocess.CompletedProcess[str]:
+ try:
+ return subprocess.run(
+ [*self._base_command(), *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ input=input_text,
+ env=_git_environment(),
+ timeout=timeout,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise ShowGitError(f"failed to execute Git checkpoint command: {exc}") from exc
+
+ def _run(
+ self,
+ args: list[str],
+ *,
+ check: bool,
+ timeout: int = GIT_COMMAND_TIMEOUT_SECONDS,
+ input_text: str | None = None,
+ ) -> subprocess.CompletedProcess[str]:
+ result = self._run_raw(
+ [f"--git-dir={self.gitdir}", f"--work-tree={self.workspace}", *args],
+ timeout=timeout,
+ input_text=input_text,
+ )
+ if check and result.returncode != 0:
+ detail = result.stderr.strip() or result.stdout.strip() or f"git {' '.join(args)} failed"
+ raise ShowGitError(detail)
+ return result
+
+ def _run_checked(
+ self,
+ args: list[str],
+ *,
+ timeout: int = GIT_COMMAND_TIMEOUT_SECONDS,
+ input_text: str | None = None,
+ ) -> subprocess.CompletedProcess[str]:
+ return self._run(args, check=True, timeout=timeout, input_text=input_text)
+
+
+_UNSET = object()
+
+
+class ShowGitCheckpointService:
+ """Synchronous turn-boundary subscriber owned by the Controller process."""
+
+ def __init__(self, git: ResolvedGit | None | object = _UNSET) -> None:
+ self.git = resolve_git() if git is _UNSET else git
+ self._bus: Any = None
+ self._subscription_id: int | None = None
+ self._active_turns: dict[str, _ActiveTurnCheckpoint] = {}
+
+ @property
+ def enabled(self) -> bool:
+ return isinstance(self.git, ResolvedGit)
+
+ def start(self, event_bus: Any = None) -> None:
+ if self._subscription_id is not None:
+ return
+ _record_checkpoint_service_state(False)
+ if not self.enabled:
+ return
+ if event_bus is None:
+ from core.inbox_events import bus as event_bus
+
+ self._bus = event_bus
+ self._subscription_id = event_bus.subscribe_callback(self._handle_event)
+ _record_checkpoint_service_state(True)
+
+ def stop(self) -> None:
+ global _checkpoint_service_active
+
+ if self._bus is not None and self._subscription_id is not None:
+ self._bus.unsubscribe(self._subscription_id)
+ self._bus = None
+ self._subscription_id = None
+ self._active_turns.clear()
+ _record_checkpoint_service_state(False)
+ _checkpoint_service_active = None
+
+ @staticmethod
+ def _im_turn_state(context: Any) -> dict[str, Any] | None:
+ state = (getattr(context, "platform_specific", None) or {}).get(_IM_TURN_STATE_KEY)
+ return state if isinstance(state, dict) else None
+
+ def mark_im_turn(self, context: Any) -> None:
+ if not self.enabled:
+ return
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ payload[_IM_TURN_STATE_KEY] = {"start_published": False, "ended": False}
+ context.platform_specific = payload
+
+ @staticmethod
+ def _existing_im_session_id(controller: Any, context: Any) -> str | None:
+ session_id = controller._session_id_from_context(context)
+ if session_id:
+ return session_id
+ payload = getattr(context, "platform_specific", None) or {}
+ base_session_id = str(payload.get("turn_base_session_id") or "").strip()
+ finder = getattr(getattr(controller, "sessions", None), "find_session_for_anchor", None)
+ if not base_session_id or not callable(finder):
+ return None
+ try:
+ row = finder(controller._get_session_key(context), base_session_id)
+ except Exception:
+ logger.debug("IM Show checkpoint session lookup failed", exc_info=True)
+ return None
+ session_id = str(row.get("id") or "").strip() if row else ""
+ if not session_id:
+ return None
+ updated = dict(payload)
+ updated["agent_session_id"] = session_id
+ context.platform_specific = updated
+ return session_id
+
+ @staticmethod
+ def _link_im_message(context: Any, session_id: str) -> bool:
+ platform = str(getattr(context, "platform", None) or "").strip()
+ message_id = str(getattr(context, "message_id", None) or "").strip()
+ if not platform or platform == "avibe" or not message_id:
+ return False
+ try:
+ from core.message_mirror import link_inbound_message_session
+
+ link_inbound_message_session(
+ platform=platform,
+ native_message_id=message_id,
+ session_id=session_id,
+ )
+ return True
+ except Exception:
+ logger.debug("IM Show checkpoint message link failed", exc_info=True)
+ return False
+
+ def begin_im_turn(self, controller: Any, context: Any) -> None:
+ state = self._im_turn_state(context)
+ if self._bus is None or state is None or state.get("start_published"):
+ return
+ session_id = self._existing_im_session_id(controller, context)
+ if not session_id:
+ # A first-ever IM turn has no Show workspace yet. Its terminal event
+ # lazily adopts the workspace if the turn creates one.
+ return
+ state = {
+ **state,
+ "start_published": True,
+ "start_session_id": session_id,
+ "message_linked": self._link_im_message(context, session_id),
+ }
+ payload = dict(context.platform_specific or {})
+ payload[_IM_TURN_STATE_KEY] = state
+ context.platform_specific = payload
+ self._bus.publish("turn.start", {"session_id": session_id})
+
+ def should_end_im_turn(
+ self,
+ controller: Any,
+ context: Any,
+ message_type: str,
+ *,
+ output: MessageOutput | None = None,
+ ) -> bool:
+ state = self._im_turn_state(context)
+ if self._bus is None or message_type != "result" or state is None or state.get("ended"):
+ return False
+ if output is not None and (not output.completes_turn or output.detached):
+ return False
+ matches = getattr(getattr(controller, "agent_service", None), "emit_matches_runtime_turn", None)
+ if not callable(matches):
+ return True
+ try:
+ return bool(matches(context))
+ except Exception:
+ logger.debug("IM Show checkpoint active-turn check failed", exc_info=True)
+ return True
+
+ def end_im_turn(self, context: Any) -> None:
+ state = self._im_turn_state(context)
+ if self._bus is None or state is None or state.get("ended"):
+ return
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ session_id = str(payload.get("agent_session_id") or state.get("start_session_id") or "").strip()
+ message_linked = bool(state.get("message_linked"))
+ if session_id and not message_linked:
+ message_linked = self._link_im_message(context, session_id)
+ payload[_IM_TURN_STATE_KEY] = {**state, "ended": True, "message_linked": message_linked}
+ context.platform_specific = payload
+ if session_id:
+ self._bus.publish("turn.end", {"session_id": session_id})
+
+ def _handle_event(self, event_type: str, data: Any) -> None:
+ if event_type not in {"turn.start", "turn.end"} or not isinstance(data, dict):
+ return
+ session_id = str(data.get("session_id") or "").strip()
+ if not _SESSION_ID_PATTERN.fullmatch(session_id):
+ return
+ if not paths.get_show_page_dir(session_id).is_dir():
+ if event_type == "turn.end":
+ self._active_turns.pop(session_id, None)
+ return
+ try:
+ if event_type == "turn.start":
+ started_at = datetime.now(timezone.utc).isoformat()
+ context = load_turn_checkpoint_context(session_id)
+ self._active_turns[session_id] = _ActiveTurnCheckpoint(context=context, started_at=started_at)
+ self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
+ return
+
+ active = self._active_turns.pop(session_id, None)
+ if active is None:
+ context = load_turn_checkpoint_context(session_id)
+ start_context = TurnCheckpointContext()
+ else:
+ start_context = active.context
+ context = (
+ TurnCheckpointContext()
+ if start_context.message_id is not None
+ else load_turn_checkpoint_context(session_id, after=active.started_at)
+ )
+ run_id = start_context.run_id or context.run_id
+ self._repository(session_id).checkpoint(
+ POST_TURN,
+ message=start_context.message if start_context.message_id is not None else context.message,
+ run_id=run_id,
+ )
+ except Exception:
+ logger.exception("Show Page checkpoint failed at %s for session=%s", event_type, session_id)
+
+ def _repository(self, session_id: str) -> ShowGitRepository:
+ if not isinstance(self.git, ResolvedGit):
+ raise ShowGitError("Git is unavailable")
+ return ShowGitRepository(session_id, self.git)
diff --git a/core/show_pages.py b/core/show_pages.py
index 3ed83546f..01761a683 100644
--- a/core/show_pages.py
+++ b/core/show_pages.py
@@ -16,6 +16,7 @@ from sqlalchemy.exc import IntegrityError
from config import paths
from config.v2_config import V2Config
from core.avibe_cloud import avibe_cloud_connect_guidance, base_public_url
+from core.show_git import format_agent_contract
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.models import agent_sessions, show_pages
@@ -580,7 +581,9 @@ def show_page_runtime_recovery_html(session_id: str) -> str:
"with a polished React page. Use the shadcn-style components from @/components/ui and "
"@avibe/show-ui. Do not edit index.html unless it is required. If the browser shows "
"Ready to visualize, check src/App.tsx, src/main.tsx, src/styles.css, and the Vite/browser "
- "console for compile or runtime errors. Make the page responsive and verify it renders."
+ "console for compile or runtime errors. Make the page responsive and verify it renders.\n\n"
+ "Show Page history contract:\n"
+ f"{format_agent_contract(numbered=True, session_id=session_id)}"
)
escaped_prompt = _escape_html(prompt)
return f"""<!doctype html>
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 6e6360a78..74ce62bd2 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -13,6 +13,7 @@ from typing import Any, Iterable, Optional
from config import paths
from core.avibe_cloud import AVIBE_CLOUD_CONNECT_GUIDANCE
from core.message_context import resolve_context_platform
+from core.show_git import format_agent_contract
from modules.im import MessageContext
logger = logging.getLogger(__name__)
@@ -88,6 +89,9 @@ Change visibility:
For more usage details, run `vibe show --help` or a subcommand help such as `vibe show update --help`.
$avibe_cloud_guidance_section
+History contract:
+$show_git_agent_contract
+
Guidance:
- New Show Page workspaces are managed React/Vite apps. Edit `src/App.tsx`, `src/styles.css`, and optional `api/*.ts` handler files. Do not replace `index.html` or `src/main.tsx` unless you are repairing the app shell.
- The standard structure is `index.html`, `src/main.tsx`, `src/App.tsx`, `src/styles.css`, and optional `api/*.ts`; treat `index.html` and `src/main.tsx` as the runtime-owned app shell.
@@ -456,6 +460,7 @@ def _build_show_pages_prompt(context: MessageContext, *, avibe_cloud_guidance: s
return Template(_SHOW_PAGES_PROMPT).substitute(
default_session_id=default_session_id,
avibe_cloud_guidance_section=f"\n{avibe_cloud_guidance}\n" if avibe_cloud_guidance else "\n",
+ show_git_agent_contract=format_agent_contract(numbered=True, session_id=default_session_id),
)
diff --git a/docs/plans/show-page-durability.md b/docs/plans/show-page-durability.md
new file mode 100644
index 000000000..dfdbd17a2
--- /dev/null
+++ b/docs/plans/show-page-durability.md
@@ -0,0 +1,35 @@
+# Show Page Git Checkpoints
+
+Issue: [#669](https://github.com/avibe-bot/avibe/issues/669)
+
+## Goal
+
+Make Show Page workspaces durable without relying on agent behavior. Avibe owns a
+native Git repository outside the served workspace and converges its `main`
+branch to the existing worktree at each session turn boundary.
+
+## Design
+
+- Resolve the checkpoint Git binary through one seam: vendored first, then a
+ macOS-CLT-aware system lookup, otherwise degrade without blocking Show Pages.
+- Lazily adopt only existing workspaces into external gitdirs under
+ `~/.avibe/show-git/`; write the workspace `.git` pointer only when Avibe owns
+ it, and use shadow checkpoints beside user-managed repositories.
+- Subscribe in the controller to `turn.start` and `turn.end`; normalize the
+ legacy streaming Show dispatch and direct IM turns onto that bus without
+ touching the shared turn manager, and never create Show Page workspaces from
+ checkpoint paths.
+- Isolate every platform Git invocation from ambient Git environment, global
+ configuration, signing, hooks, and automatic GC.
+- Self-heal only provably Avibe-owned or dangling state, bound retained history,
+ keep static dot-path denial strict while preserving Vite dependency assets on
+ the hardened runtime proxy, and publish ownership-gated Git guidance from the
+ running checkpoint service's startup-latched capability state.
+
+## Validation
+
+- Focused unit coverage for resolution, adoption/ownership, checkpoint
+ semantics, repair, pruning, event wiring, and Git environment isolation.
+- Route coverage for private/public runtime proxy and static fallback boundaries.
+- Incus edit/overwrite/restore/forward-commit verification remains an
+ integration-pass check after the coordinated milestone lands.
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index c22d0174c..e0c7ba72e 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -9,6 +9,11 @@ from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.controller import Controller
+from core.git_binary import ResolvedGit
+from core.inbox_events import InboxEventBus
+from core.message_output import MessageOutput
+from core.show_git import ShowGitCheckpointService
+from modules.im import MessageContext
def test_dispatch_to_controller_loop_runs_callback_on_controller_loop():
@@ -227,3 +232,144 @@ def test_cleanup_sync_stops_watch_service_on_stopped_loop() -> None:
assert stopped["tasks"] is True
assert stopped["watch"] is True
assert stopped["runtime"] is True
+
+
+def test_im_show_checkpoint_lifecycle_spans_real_start_to_terminal_result(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ controller = Controller.__new__(Controller)
+ updated_threads = []
+ emitted_messages = []
+ linked_messages = []
+
+ class _Dispatcher:
+ def update_thread_message_id(self, context) -> None:
+ updated_threads.append(context)
+
+ async def emit_agent_message(self, **kwargs):
+ emitted_messages.append(kwargs)
+ return "result-1"
+
+ controller.message_dispatcher = _Dispatcher()
+ controller.sessions = SimpleNamespace(
+ find_session_for_anchor=lambda session_key, anchor: {"id": "ses_im"}
+ if (session_key, anchor) == ("slack:C", "anchor")
+ else None
+ )
+ controller.agent_service = SimpleNamespace(emit_matches_runtime_turn=lambda _context: True)
+ controller._get_session_key = lambda context: f"{context.platform}:{context.channel_id}"
+ checkpoint_service = ShowGitCheckpointService(ResolvedGit(path=Path("/usr/bin/git"), source="system"))
+ checkpoint_bus = InboxEventBus()
+ checkpoint_service.start(checkpoint_bus)
+ controller.show_git_checkpoint_service = checkpoint_service
+ monkeypatch.setattr(
+ "core.message_mirror.link_inbound_message_session",
+ lambda **kwargs: linked_messages.append(kwargs),
+ )
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="slack",
+ message_id="msg-1",
+ platform_specific={},
+ )
+ checkpoint_service.mark_im_turn(context)
+ context.platform_specific["turn_base_session_id"] = "anchor"
+ lifecycle = []
+ subscription_id = checkpoint_bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+ try:
+ controller.update_thread_message_id(context)
+ detached_result = asyncio.run(
+ controller.emit_agent_message(
+ context,
+ "result",
+ "activity finished",
+ output=MessageOutput(completes_turn=False, detached=True),
+ )
+ )
+ assert lifecycle == [("turn.start", {"session_id": "ses_im"})]
+ first_result = asyncio.run(controller.emit_agent_message(context, "result", "done"))
+ second_result = asyncio.run(controller.emit_agent_message(context, "result", "duplicate"))
+ finally:
+ checkpoint_bus.unsubscribe(subscription_id)
+ checkpoint_service.stop()
+
+ assert detached_result == "result-1"
+ assert first_result == "result-1"
+ assert second_result == "result-1"
+ assert updated_threads == [context]
+ assert len(emitted_messages) == 3
+ assert emitted_messages[0]["output"] == MessageOutput(completes_turn=False, detached=True)
+ assert context.platform_specific["agent_session_id"] == "ses_im"
+ assert linked_messages == [
+ {
+ "platform": "slack",
+ "native_message_id": "msg-1",
+ "session_id": "ses_im",
+ }
+ ]
+ assert lifecycle == [
+ ("turn.start", {"session_id": "ses_im"}),
+ ("turn.end", {"session_id": "ses_im"}),
+ ]
+
+
+def test_first_im_show_turn_adopts_on_terminal_after_backend_binds_session(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ controller = Controller.__new__(Controller)
+ linked_messages = []
+
+ class _Dispatcher:
+ def update_thread_message_id(self, _context) -> None:
+ return None
+
+ async def emit_agent_message(self, **_kwargs):
+ return "result-1"
+
+ controller.message_dispatcher = _Dispatcher()
+ controller.sessions = SimpleNamespace(find_session_for_anchor=lambda _session_key, _anchor: None)
+ controller.agent_service = SimpleNamespace(emit_matches_runtime_turn=lambda _context: True)
+ controller._get_session_key = lambda context: f"{context.platform}:{context.channel_id}"
+ checkpoint_service = ShowGitCheckpointService(ResolvedGit(path=Path("/usr/bin/git"), source="system"))
+ checkpoint_bus = InboxEventBus()
+ checkpoint_service.start(checkpoint_bus)
+ controller.show_git_checkpoint_service = checkpoint_service
+ monkeypatch.setattr(
+ "core.message_mirror.link_inbound_message_session",
+ lambda **kwargs: linked_messages.append(kwargs),
+ )
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="slack",
+ message_id="msg-new",
+ platform_specific={},
+ )
+ checkpoint_service.mark_im_turn(context)
+ context.platform_specific["turn_base_session_id"] = "new-anchor"
+ lifecycle = []
+ subscription_id = checkpoint_bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+ try:
+ controller.update_thread_message_id(context)
+ assert lifecycle == []
+ context.platform_specific["agent_session_id"] = "ses_new_im"
+ asyncio.run(controller.emit_agent_message(context, "result", "done"))
+ finally:
+ checkpoint_bus.unsubscribe(subscription_id)
+ checkpoint_service.stop()
+
+ assert lifecycle == [("turn.end", {"session_id": "ses_new_im"})]
+ assert linked_messages == [
+ {
+ "platform": "slack",
+ "native_message_id": "msg-new",
+ "session_id": "ses_new_im",
+ }
+ ]
diff --git a/tests/test_controller_platform_reconcile.py b/tests/test_controller_platform_reconcile.py
index a16ff660e..919cf52b4 100644
--- a/tests/test_controller_platform_reconcile.py
+++ b/tests/test_controller_platform_reconcile.py
@@ -189,6 +189,29 @@ def test_reconcile_adds_platform_with_callbacks_before_start(monkeypatch):
assert controller.im_client.clients["discord"].settings_manager.platform == "discord"
+def test_im_message_callback_marks_checkpoint_turn_before_dispatch(monkeypatch):
+ controller = _controller(_config(["slack"]))
+ marked = []
+ dispatched = []
+ controller.show_git_checkpoint_service = SimpleNamespace(mark_im_turn=lambda context: marked.append(context))
+
+ async def _dispatch(_controller, context, text):
+ dispatched.append((context, text))
+
+ monkeypatch.setattr("core.services.dispatch.dispatch_turn", _dispatch)
+ controller._setup_callbacks()
+ context = MessageContext(user_id="U", channel_id="C", platform="slack")
+
+ async def _run_callback():
+ await controller.im_client.clients["slack"].on_message_callback(context, "hello")
+ await asyncio.sleep(0)
+
+ asyncio.run(_run_callback())
+
+ assert marked == [context]
+ assert dispatched == [(context, "hello")]
+
+
def test_reconcile_removes_platform_and_keeps_workbench_delivery(monkeypatch):
monkeypatch.setattr("core.controller.get_platform_descriptor", lambda platform: _Descriptor(platform))
controller = _controller(_config(["slack", "discord"]))
diff --git a/tests/test_git_binary.py b/tests/test_git_binary.py
new file mode 100644
index 000000000..6dd27c7b7
--- /dev/null
+++ b/tests/test_git_binary.py
@@ -0,0 +1,59 @@
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from core import git_binary
+from core.git_binary import ResolvedGit
+
+
+def test_resolve_git_prefers_vendored(monkeypatch):
+ vendored = ResolvedGit(path=Path("/managed/git"), source="vendored")
+ monkeypatch.setattr(git_binary, "_resolve_vendored", lambda: vendored)
+ monkeypatch.setattr(git_binary.shutil, "which", lambda _name: (_ for _ in ()).throw(AssertionError()))
+
+ assert git_binary.resolve_git() == vendored
+
+
+def test_resolve_git_uses_system_git_after_vendored(monkeypatch):
+ monkeypatch.setattr(git_binary, "_resolve_vendored", lambda: None)
+ monkeypatch.setattr(git_binary.shutil, "which", lambda name: "/opt/bin/git" if name == "git" else None)
+ monkeypatch.setattr(git_binary.sys, "platform", "linux")
+
+ assert git_binary.resolve_git() == ResolvedGit(path=Path("/opt/bin/git"), source="system")
+
+
+def test_resolve_git_rejects_macos_shim_without_command_line_tools(monkeypatch):
+ calls = []
+ monkeypatch.setattr(git_binary, "_resolve_vendored", lambda: None)
+ monkeypatch.setattr(git_binary.shutil, "which", lambda name: "/usr/bin/git" if name == "git" else None)
+ monkeypatch.setattr(git_binary.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ git_binary.subprocess,
+ "run",
+ lambda command, **kwargs: calls.append((command, kwargs))
+ or SimpleNamespace(returncode=1, stdout="", stderr="missing"),
+ )
+
+ assert git_binary.resolve_git() is None
+ assert calls[0][0] == ["/usr/bin/xcode-select", "-p"]
+
+
+def test_resolve_git_accepts_non_shim_macos_git_without_clt_probe(monkeypatch):
+ monkeypatch.setattr(git_binary, "_resolve_vendored", lambda: None)
+ monkeypatch.setattr(git_binary.shutil, "which", lambda name: "/opt/homebrew/bin/git" if name == "git" else None)
+ monkeypatch.setattr(git_binary.sys, "platform", "darwin")
+ monkeypatch.setattr(
+ git_binary.subprocess,
+ "run",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("CLT probe must not run")),
+ )
+
+ assert git_binary.resolve_git() == ResolvedGit(path=Path("/opt/homebrew/bin/git"), source="system")
+
+
+def test_resolve_git_degrades_when_no_binary_exists(monkeypatch):
+ monkeypatch.setattr(git_binary, "_resolve_vendored", lambda: None)
+ monkeypatch.setattr(git_binary.shutil, "which", lambda _name: None)
+
+ assert git_binary.resolve_git() is None
diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.py
index c2efe4029..37ede020b 100644
--- a/tests/test_inbox_events.py
+++ b/tests/test_inbox_events.py
@@ -73,6 +73,39 @@ def test_publish_without_subscribers_is_noop():
InboxEventBus().publish("inbox.session.updated", {"x": 1})
+def test_synchronous_callback_runs_before_queue_fanout_and_is_unsubscribed():
+ async def scenario():
+ bus = InboxEventBus()
+ order = []
+ callback_id = bus.subscribe_callback(lambda event_type, data: order.append((event_type, data)))
+ _, queue = bus.subscribe()
+ bus.publish("turn.start", {"session_id": "s1"})
+ assert order == [("turn.start", {"session_id": "s1"})]
+ queued = await asyncio.wait_for(queue.get(), timeout=1.0)
+ bus.unsubscribe(callback_id)
+ bus.publish("turn.end", {"session_id": "s1"})
+ return order, queued
+
+ order, queued = asyncio.run(scenario())
+ assert order == [("turn.start", {"session_id": "s1"})]
+ assert queued == ("turn.start", {"session_id": "s1"})
+
+
+def test_synchronous_callback_failure_does_not_break_queue_delivery():
+ async def scenario():
+ bus = InboxEventBus()
+
+ def fail(_event_type, _data):
+ raise RuntimeError("checkpoint failed")
+
+ bus.subscribe_callback(fail)
+ _, queue = bus.subscribe()
+ bus.publish("turn.end", {"session_id": "s1"})
+ return await asyncio.wait_for(queue.get(), timeout=1.0)
+
+ assert asyncio.run(scenario()) == ("turn.end", {"session_id": "s1"})
+
+
def test_sqlite_background_store_publishes_run_updates(tmp_path):
async def scenario():
from core import inbox_events
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 1af1be30d..7a05d0fc2 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -164,6 +164,50 @@ def test_create_app_exposes_minimal_endpoints():
assert ("/internal/events", ("POST",)) in routes
+def test_streaming_dispatch_publishes_single_bus_lifecycle(monkeypatch):
+ """The Show-page stream owns one bus lifecycle because it bypasses the FSM."""
+ from core import inbox_events
+
+ context = MessageContext(user_id="workbench", channel_id="ses_show", platform="avibe")
+
+ async def _build_payload(_payload):
+ return "edit the show page", context
+
+ async def _dispatch_turn(_controller, _context, _text, *, on_chunk=None):
+ assert on_chunk is not None
+ await on_chunk({"kind": "result", "text": "done"})
+
+ monkeypatch.setattr(internal_server, "_build_dispatch_payload", _build_payload)
+ monkeypatch.setattr(internal_server, "dispatch_turn", _dispatch_turn)
+ controller = _build_controller_double()
+ app = internal_server.create_app(controller)
+ transport = httpx.ASGITransport(app=app)
+ lifecycle = []
+
+ async def _go():
+ subscription_id = inbox_events.bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+ try:
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post(
+ "/internal/dispatch",
+ json={"session_id": "ses_show", "text": "edit the show page"},
+ )
+ finally:
+ inbox_events.bus.unsubscribe(subscription_id)
+
+ response = asyncio.run(_go())
+
+ assert response.status_code == 200
+ assert lifecycle == [
+ ("turn.start", {"session_id": "ses_show"}),
+ ("turn.end", {"session_id": "ses_show"}),
+ ]
+
+
# ---------------------------------------------------------------------
# ASGI round-trips
# ---------------------------------------------------------------------
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 8c269e0fc..ff721721d 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -357,7 +357,10 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
),
]
- with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
+ with (
+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
+ patch("core.show_git.show_git_checkpointing_active", return_value=True),
+ ):
prompt = build_system_prompt_injection(
include_quick_replies=True,
context=context,
@@ -369,6 +372,11 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("`vibe show path`", prompt)
self.assertIn("`vibe show status`", prompt)
self.assertIn("`vibe show update --visibility private`", prompt)
+ self.assertIn("History is saved automatically around each turn", prompt)
+ self.assertIn("`git -C <workspace> status / log / diff / show`", prompt)
+ self.assertIn("Restore only via `git restore --source=<ref> -- <path>`", prompt)
+ self.assertIn("Never move HEAD, switch branches, rewrite history, or run gc", prompt)
+ self.assertIn("Never add remotes, push, or publish the workspace anywhere", prompt)
self.assertNotIn("`vibe show path --session-id sesk8m4q2p7x`", prompt)
self.assertIn("Make the page work reasonably on mobile", prompt)
self.assertIn("managed React/Vite apps", prompt)
@@ -468,6 +476,55 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Keep entries short, deduplicated, and free of secrets unless the user explicitly asks.", prompt)
self.assertIn("use `vibe data query` to recover Sessions and Messages by keyword, time, scope, Agent, or run history", prompt)
+ def test_show_pages_prompt_reports_history_unavailable_without_git(self):
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"agent_session_id": "sesk8m4q2p7x"},
+ )
+
+ with (
+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
+ patch("core.show_git.show_git_checkpointing_active", return_value=False),
+ ):
+ prompt = build_system_prompt_injection(include_quick_replies=True, context=context)
+
+ self.assertIn("Automatic Show Page history is unavailable", prompt)
+ self.assertNotIn("History is saved automatically around each turn", prompt)
+ self.assertNotIn("git restore --source", prompt)
+
+ def test_show_pages_prompt_rechecks_mid_session_ownership_flip(self):
+ session_id = "sesk8m4q2p7x"
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"agent_session_id": session_id},
+ )
+ workspace = paths.get_show_page_dir(session_id)
+ workspace.mkdir(parents=True)
+
+ with (
+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
+ patch("core.show_git.show_git_checkpointing_active", return_value=True),
+ ):
+ managed_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)
+ (workspace / ".git").mkdir()
+ self_managed_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)
+ (workspace / ".git").rmdir()
+ managed_again_prompt = build_system_prompt_injection(include_quick_replies=True, context=context)
+
+ self.assertIn("History is saved automatically around each turn", managed_prompt)
+ self.assertNotIn("shadow history continues automatically", managed_prompt)
+ self.assertIn("Avibe's shadow history continues automatically", self_managed_prompt)
+ self.assertIn("addresses the **user's repo**, not Avibe history", self_managed_prompt)
+ self.assertIn("Only if the user explicitly asks to recover from Avibe history", self_managed_prompt)
+ self.assertNotIn("Read freely: `git -C <workspace>", self_managed_prompt)
+ self.assertNotIn("Restore only via `git restore", self_managed_prompt)
+ self.assertIn("History is saved automatically around each turn", managed_again_prompt)
+ self.assertNotIn("shadow history continues automatically", managed_again_prompt)
+
def test_prompt_does_not_render_empty_agents_as_invokable_table_row(self):
context = MessageContext(
user_id="U1",
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
new file mode 100644
index 000000000..320b828b3
--- /dev/null
+++ b/tests/test_show_git.py
@@ -0,0 +1,714 @@
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import time
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from core import show_git
+from core.git_binary import ResolvedGit
+from core.inbox_events import InboxEventBus
+from core.show_git import (
+ POST_TURN,
+ PRE_TURN,
+ ShowGitCheckpointService,
+ ShowGitRepository,
+ TurnCheckpointContext,
+ format_agent_contract,
+ sanitize_checkpoint_subject,
+)
+
+
+def resolved_git() -> ResolvedGit:
+ candidate = shutil.which("git")
+ if candidate is None:
+ pytest.skip("system Git is required for Show checkpoint tests")
+ return ResolvedGit(path=Path(candidate), source="system")
+
+
+def _workspace(session_id: str = "ses_show_git") -> Path:
+ workspace = paths.get_show_page_dir(session_id)
+ workspace.mkdir(parents=True, exist_ok=True)
+ return workspace
+
+
+def _repo(session_id: str, resolved_git: ResolvedGit) -> ShowGitRepository:
+ return ShowGitRepository(session_id, resolved_git)
+
+
+def _platform_git(repo: ShowGitRepository, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ env = {key: os.environ[key] for key in ("PATH", "HOME", "TMPDIR", "LANG", "LC_ALL") if key in os.environ}
+ for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY"):
+ env.pop(key, None)
+ env.update(
+ {
+ "GIT_CONFIG_GLOBAL": os.devnull,
+ "GIT_CONFIG_SYSTEM": os.devnull,
+ }
+ )
+ return subprocess.run(
+ [
+ str(repo.git.path),
+ f"--git-dir={repo.gitdir}",
+ f"--work-tree={repo.workspace}",
+ *args,
+ ],
+ check=check,
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+
+
+def _native_git(workspace: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ env = {key: os.environ[key] for key in ("PATH", "HOME", "TMPDIR", "LANG", "LC_ALL") if key in os.environ}
+ env.update(
+ {
+ "GIT_CONFIG_GLOBAL": os.devnull,
+ "GIT_CONFIG_SYSTEM": os.devnull,
+ }
+ )
+ return subprocess.run(
+ [shutil.which("git") or "git", "-C", str(workspace), *args],
+ check=check,
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+
+
+def _commit_count(repo: ShowGitRepository) -> int:
+ return int(_platform_git(repo, "rev-list", "--count", "refs/heads/main").stdout.strip())
+
+
+def _head_message(repo: ShowGitRepository) -> str:
+ return _platform_git(repo, "log", "-1", "--format=%B").stdout.rstrip()
+
+
+def test_missing_workspace_never_creates_checkpoint_paths(resolved_git):
+ repo = _repo("ses_missing", resolved_git)
+
+ assert repo.checkpoint(PRE_TURN) is False
+ assert not repo.workspace.exists()
+ assert not repo.gitdir.exists()
+ assert not repo.gitdir.parent.exists()
+
+
+def test_agent_contract_ownership_probe_never_creates_workspace():
+ session_id = "ses_guidance_missing"
+ workspace = paths.get_show_page_dir(session_id)
+ gitdir = paths.get_show_git_dir(session_id)
+
+ contract = format_agent_contract(checkpointing_available=True, session_id=session_id)
+
+ assert "History is saved automatically around each turn" in contract
+ assert not workspace.exists()
+ assert not gitdir.exists()
+ assert not gitdir.parent.exists()
+
+
+def test_lazy_adoption_is_idempotent_and_native_git_works(resolved_git):
+ session_id = "ses_adopt"
+ workspace = _workspace(session_id)
+ (workspace / "src").mkdir()
+ (workspace / "src" / "App.tsx").write_text("export default 1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+
+ assert repo.checkpoint(PRE_TURN, run_id="run-adopt") is True
+ pointer = workspace / ".git"
+ original_pointer = pointer.read_text(encoding="utf-8")
+ original_pointer_mtime = pointer.stat().st_mtime_ns
+
+ assert repo.checkpoint(PRE_TURN, run_id="run-adopt") is False
+ assert pointer.read_text(encoding="utf-8") == original_pointer
+ assert pointer.stat().st_mtime_ns == original_pointer_mtime
+ assert _commit_count(repo) == 1
+ assert _native_git(workspace, "status", "--porcelain").stdout == ""
+ assert _native_git(workspace, "log", "-1", "--format=%s").stdout.strip() == "adopt existing workspace"
+ assert "Avibe-Run: run-adopt" in _head_message(repo)
+ assert "Avibe-Checkpoint: adopt" in _head_message(repo)
+ exclude = (repo.gitdir / "info" / "exclude").read_text(encoding="utf-8")
+ assert all(pattern in exclude.splitlines() for pattern in ("node_modules/", "dist/", ".vite/"))
+
+
+def test_lazy_adoption_does_not_require_initial_branch_option(resolved_git, monkeypatch):
+ session_id = "ses_adopt_old_git"
+ workspace = _workspace(session_id)
+ (workspace / "page.txt").write_text("content\n", encoding="utf-8")
+ commands = []
+ real_run = subprocess.run
+
+ def reject_new_init_option(command, **kwargs):
+ commands.append(command)
+ if any(str(part).startswith("--initial-branch") for part in command):
+ return subprocess.CompletedProcess(command, 129, "", "unknown option: initial-branch")
+ return real_run(command, **kwargs)
+
+ monkeypatch.setattr(show_git.subprocess, "run", reject_new_init_option)
+ repo = _repo(session_id, resolved_git)
+
+ assert repo.checkpoint(PRE_TURN) is True
+ assert _platform_git(repo, "symbolic-ref", "HEAD").stdout.strip() == "refs/heads/main"
+ init_command = next(command for command in commands if "init" in command)
+ assert "--bare" in init_command
+ assert not any(str(part).startswith("--initial-branch") for part in init_command)
+
+
+def test_user_git_directory_is_untouched_while_shadow_checkpoints_continue(resolved_git):
+ session_id = "ses_shadow"
+ workspace = _workspace(session_id)
+ (workspace / "app.txt").write_text("user v1\n", encoding="utf-8")
+ _native_git(workspace, "init", "--initial-branch=trunk")
+ _native_git(workspace, "add", "app.txt")
+ _native_git(
+ workspace,
+ "-c",
+ "user.name=user-owner",
+ "-c",
+ "commit",
+ "-m",
+ "user baseline",
+ )
+ user_git = workspace / ".git"
+ before = {
+ "HEAD": (user_git / "HEAD").read_bytes(),
+ "config": (user_git / "config").read_bytes(),
+ "index": (user_git / "index").read_bytes(),
+ "ref": (user_git / "refs" / "heads" / "trunk").read_bytes(),
+ }
+ repo = _repo(session_id, resolved_git)
+
+ assert repo.checkpoint(PRE_TURN) is True
+ (workspace / "app.txt").write_text("user v2\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message="shadow update") is True
+
+ assert user_git.is_dir()
+ assert before == {
+ "HEAD": (user_git / "HEAD").read_bytes(),
+ "config": (user_git / "config").read_bytes(),
+ "index": (user_git / "index").read_bytes(),
+ "ref": (user_git / "refs" / "heads" / "trunk").read_bytes(),
+ }
+ assert _native_git(workspace, "status", "--porcelain").stdout.strip() == "M app.txt"
+ assert _commit_count(repo) == 2
+
+ shutil.rmtree(user_git)
+ (workspace / "app.txt").write_text("user v3\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message="return to managed") is True
+ assert (workspace / ".git").is_file()
+ assert _native_git(workspace, "log", "-1", "--format=%s").stdout.strip() == "return to managed"
+
+
+def test_user_git_pointer_is_never_overwritten(resolved_git, tmp_path):
+ session_id = "ses_user_pointer"
+ workspace = _workspace(session_id)
+ (workspace / "app.txt").write_text("content\n", encoding="utf-8")
+ user_gitdir = tmp_path / "owner-repository.git"
+ subprocess.run(
+ [str(resolved_git.path), "init", "--bare", str(user_gitdir)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ pointer = workspace / ".git"
+ pointer.write_text(f"gitdir: {user_gitdir}\n", encoding="utf-8")
+ before = pointer.read_bytes()
+
+ assert _repo(session_id, resolved_git).checkpoint(PRE_TURN) is True
+ assert pointer.read_bytes() == before
+
+
+def test_existing_user_git_pointer_with_managed_path_shape_is_never_overwritten(resolved_git, tmp_path):
+ session_id = "ses_user_shaped_pointer"
+ workspace = _workspace(session_id)
+ (workspace / "app.txt").write_text("content\n", encoding="utf-8")
+ user_gitdir = tmp_path / "show-git" / f"{session_id}.git"
+ user_gitdir.parent.mkdir()
+ subprocess.run(
+ [str(resolved_git.path), "init", "--bare", str(user_gitdir)],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ pointer = workspace / ".git"
+ pointer.write_text(f"gitdir: {user_gitdir}\n", encoding="utf-8")
+ before = pointer.read_bytes()
+
+ repo = _repo(session_id, resolved_git)
+ assert repo.checkpoint(PRE_TURN) is True
+
+ assert pointer.read_bytes() == before
+ assert repo.gitdir != user_gitdir
+ assert _commit_count(repo) == 1
+ contract = format_agent_contract(checkpointing_available=True, session_id=session_id)
+ assert "addresses the **user's repo**, not Avibe history" in contract
+
+
+def test_pre_and_post_turn_commit_only_when_dirty_with_frozen_messages(resolved_git):
+ session_id = "ses_turns"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+
+ target.write_text("manual\n", encoding="utf-8")
+ assert repo.checkpoint(PRE_TURN, run_id="run-pre") is True
+ assert _head_message(repo).startswith("out-of-band changes\n\n")
+ assert "Avibe-Run: run-pre" in _head_message(repo)
+ assert "Avibe-Checkpoint: pre-turn" in _head_message(repo)
+ count = _commit_count(repo)
+ assert repo.checkpoint(POST_TURN, message="unchanged") is False
+ assert _commit_count(repo) == count
+
+ driving_message = " Build\n\tthe\x1b new page " + ("x" * 100)
+ target.write_text("agent\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message=driving_message, run_id="run-post") is True
+ assert _platform_git(repo, "log", "-1", "--format=%s").stdout.strip() == sanitize_checkpoint_subject(
+ driving_message
+ )
+ assert "Avibe-Run: run-post" in _head_message(repo)
+ assert "Avibe-Checkpoint: post-turn" in _head_message(repo)
+
+ target.write_text("fallback\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message="\n\t") is True
+ assert _platform_git(repo, "log", "-1", "--format=%s").stdout.strip() == "checkpoint"
+
+
+def test_native_restore_is_recorded_as_a_forward_post_turn_commit(resolved_git):
+ session_id = "ses_restore"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+ target.write_text("v2\n", encoding="utf-8")
+ repo.checkpoint(POST_TURN, message="write v2")
+ v2_head = _platform_git(repo, "rev-parse", "HEAD").stdout.strip()
+
+ _native_git(workspace, "restore", "--source=HEAD~1", "--", "page.txt")
+ assert repo.checkpoint(POST_TURN, message="restore v1") is True
+
+ assert target.read_text(encoding="utf-8") == "v1\n"
+ assert _platform_git(repo, "rev-parse", "HEAD^").stdout.strip() == v2_head
+ assert _platform_git(repo, "log", "-1", "--format=%s").stdout.strip() == "restore v1"
+
+
+def test_main_rewind_is_converted_to_a_forward_commit(resolved_git):
+ session_id = "ses_rewind"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+ target.write_text("v2\n", encoding="utf-8")
+ repo.checkpoint(POST_TURN, message="write v2")
+ v2_head = _platform_git(repo, "rev-parse", "HEAD").stdout.strip()
+
+ _native_git(workspace, "reset", "--hard", "HEAD~1")
+ assert _native_git(workspace, "rev-parse", "HEAD").stdout.strip() != v2_head
+ assert repo.checkpoint(POST_TURN, message="recover after reset") is True
+
+ assert target.read_text(encoding="utf-8") == "v1\n"
+ assert _platform_git(repo, "rev-parse", "HEAD^").stdout.strip() == v2_head
+ assert _platform_git(repo, "rev-parse", "refs/avibe/checkpoint-main").stdout.strip() == _platform_git(
+ repo, "rev-parse", "HEAD"
+ ).stdout.strip()
+
+
+def test_detached_head_and_stale_index_lock_self_heal(resolved_git):
+ session_id = "ses_heal"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+ _native_git(workspace, "checkout", "--detach", "HEAD")
+ lock = repo.gitdir / "index.lock"
+ lock.write_text("stale", encoding="utf-8")
+ old = time.time() - show_git.STALE_INDEX_LOCK_SECONDS - 5
+ os.utime(lock, (old, old))
+ target.write_text("v2\n", encoding="utf-8")
+
+ assert repo.checkpoint(POST_TURN, message="heal history") is True
+ assert not lock.exists()
+ assert _platform_git(repo, "symbolic-ref", "HEAD").stdout.strip() == "refs/heads/main"
+ assert _platform_git(repo, "show", "HEAD:page.txt").stdout == "v2\n"
+
+
+def test_dangling_managed_pointer_reinitializes_and_adopts(resolved_git, tmp_path):
+ session_id = "ses_dangling"
+ workspace = _workspace(session_id)
+ (workspace / "page.txt").write_text("recovered\n", encoding="utf-8")
+ stale = tmp_path / "old-home" / "show-git" / f"{session_id}.git"
+ pointer = workspace / ".git"
+ pointer.write_text(f"gitdir: {stale}\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+
+ assert repo.checkpoint(PRE_TURN) is True
+ assert pointer.read_text(encoding="utf-8") == f"gitdir: {repo.gitdir.resolve()}\n"
+ assert repo.gitdir.is_dir()
+ assert _platform_git(repo, "show", "HEAD:page.txt").stdout == "recovered\n"
+ assert _platform_git(repo, "log", "-1", "--format=%s").stdout.strip() == "adopt existing workspace"
+
+
+def test_prune_squashes_to_current_baseline_without_remote(resolved_git, monkeypatch):
+ monkeypatch.setattr(show_git, "MAX_COMMITS", 2)
+ session_id = "ses_prune"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+
+ target.write_text("v2\n", encoding="utf-8")
+ repo.checkpoint(POST_TURN, message="second")
+ target.write_text("v3\n", encoding="utf-8")
+ repo.checkpoint(POST_TURN, message="third", run_id="run-prune")
+
+ assert _commit_count(repo) == 1
+ assert _platform_git(repo, "show", "HEAD:page.txt").stdout == "v3\n"
+ assert _platform_git(repo, "log", "-1", "--format=%s").stdout.strip() == "third"
+ assert "Avibe-Run: run-prune" in _head_message(repo)
+
+
+def test_remote_freezes_history_rewrite_but_allows_gc(resolved_git, monkeypatch):
+ monkeypatch.setattr(show_git, "MAX_COMMITS", 1)
+ session_id = "ses_remote_freeze"
+ workspace = _workspace(session_id)
+ target = workspace / "page.txt"
+ target.write_text("v1\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+ _platform_git(repo, "remote", "add", "backup", "https://example.invalid/show.git")
+
+ target.write_text("v2\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message="preserve published ancestry") is True
+ assert _commit_count(repo) == 2
+ assert _platform_git(repo, "remote").stdout.strip() == "backup"
+
+
+def test_gitdir_size_limit_triggers_baseline_even_without_new_changes(resolved_git, monkeypatch):
+ session_id = "ses_size_prune"
+ workspace = _workspace(session_id)
+ (workspace / "page.txt").write_text("stable\n", encoding="utf-8")
+ repo = _repo(session_id, resolved_git)
+ repo.checkpoint(PRE_TURN)
+ (workspace / "page.txt").write_text("stable v2\n", encoding="utf-8")
+ repo.checkpoint(POST_TURN, message="second")
+ old_head = _platform_git(repo, "rev-parse", "HEAD").stdout.strip()
+ old_tree = _platform_git(repo, "rev-parse", "HEAD^{tree}").stdout.strip()
+ monkeypatch.setattr(show_git, "MAX_GITDIR_BYTES", 1)
+
+ assert repo.checkpoint(POST_TURN, message="unchanged") is False
+
+ new_head = _platform_git(repo, "rev-parse", "HEAD").stdout.strip()
+ assert new_head != old_head
+ assert _platform_git(repo, "rev-parse", "HEAD^{tree}").stdout.strip() == old_tree
+ assert _commit_count(repo) == 1
+
+
+def test_platform_git_scrubs_environment_and_ignores_global_hooks(resolved_git, monkeypatch, tmp_path):
+ session_id = "ses_isolated_git"
+ workspace = _workspace(session_id)
+ (workspace / "page.txt").write_text("isolated\n", encoding="utf-8")
+ malicious_hooks = tmp_path / "hooks"
+ malicious_hooks.mkdir()
+ marker = tmp_path / "hook-ran"
+ hook = malicious_hooks / "pre-commit"
+ hook.write_text(f"#!/bin/sh\ntouch '{marker}'\n", encoding="utf-8")
+ hook.chmod(0o755)
+ malicious_config = tmp_path / "gitconfig"
+ malicious_config.write_text(
+ "[user]\n\tname = ambient-user\n\temail = [email protected]\n"
+ f"[core]\n\thooksPath = {malicious_hooks}\n"
+ "[commit]\n\tgpgsign = true\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("GIT_DIR", str(tmp_path / "poison.git"))
+ monkeypatch.setenv("GIT_WORK_TREE", str(tmp_path / "poison-worktree"))
+ monkeypatch.setenv("GIT_INDEX_FILE", str(tmp_path / "poison-index"))
+ monkeypatch.setenv("GIT_OBJECT_DIRECTORY", str(tmp_path / "poison-objects"))
+ monkeypatch.setenv("GIT_CONFIG_GLOBAL", str(malicious_config))
+ captured = []
+ real_run = subprocess.run
+
+ def recording_run(command, **kwargs):
+ env = dict(kwargs.get("env") or {})
+ captured.append(
+ (
+ command,
+ {
+ "GIT_CONFIG_GLOBAL": env.get("GIT_CONFIG_GLOBAL"),
+ "GIT_CONFIG_SYSTEM": env.get("GIT_CONFIG_SYSTEM"),
+ **{key: key in env for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY")},
+ },
+ )
+ )
+ return real_run(command, **kwargs)
+
+ monkeypatch.setattr(show_git.subprocess, "run", recording_run)
+ repo = _repo(session_id, resolved_git)
+
+ assert repo.checkpoint(PRE_TURN) is True
+ platform_calls = list(captured)
+ monkeypatch.setattr(show_git.subprocess, "run", real_run)
+ assert not marker.exists()
+ _platform_git(repo, "config", "core.hooksPath", str(malicious_hooks))
+ (workspace / "page.txt").write_text("isolated v2\n", encoding="utf-8")
+ assert repo.checkpoint(POST_TURN, message="local hooks stay disabled") is True
+ assert not marker.exists()
+ identity = _platform_git(repo, "log", "-1", "--format=%an|%ae").stdout.strip()
+ assert identity == "avibe-checkpoint|[email protected]"
+ assert platform_calls
+ for command, env in platform_calls:
+ assert env["GIT_CONFIG_GLOBAL"] == os.devnull
+ assert env["GIT_CONFIG_SYSTEM"] == os.devnull
+ assert all(not env[key] for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY"))
+ assert "user.name=avibe-checkpoint" in command
+ assert "[email protected]" in command
+ assert "commit.gpgsign=false" in command
+ assert "gc.auto=0" in command
+ assert any(str(part).startswith("core.hooksPath=") for part in command)
+
+
+def test_turn_event_subscriber_uses_storage_context_without_payload_changes(resolved_git, monkeypatch):
+ session_id = "ses_bus"
+ _workspace(session_id)
+ calls = []
+
+ class FakeRepository:
+ def checkpoint(self, checkpoint, **kwargs):
+ calls.append((checkpoint, kwargs))
+ return True
+
+ contexts = iter(
+ (
+ TurnCheckpointContext(message="", run_id="run-event"),
+ TurnCheckpointContext(message="driving user message", run_id=None),
+ )
+ )
+ lookups = []
+
+ def load_context(loaded_session_id, **kwargs):
+ lookups.append((loaded_session_id, kwargs))
+ return next(contexts)
+
+ monkeypatch.setattr(show_git, "load_turn_checkpoint_context", load_context)
+ service = ShowGitCheckpointService(resolved_git)
+ monkeypatch.setattr(service, "_repository", lambda _session_id: FakeRepository())
+ bus = InboxEventBus()
+ service.start(bus)
+
+ bus.publish("turn.start", {"session_id": session_id})
+ bus.publish("turn.end", {"session_id": session_id})
+ service.stop()
+ bus.publish("turn.end", {"session_id": session_id})
+
+ assert calls == [
+ (PRE_TURN, {"run_id": "run-event"}),
+ (POST_TURN, {"message": "driving user message", "run_id": "run-event"}),
+ ]
+ assert lookups[0] == (session_id, {})
+ assert lookups[1][0] == session_id
+ assert set(lookups[1][1]) == {"after"}
+
+
+def test_turn_event_subscriber_keeps_start_message_when_next_pending_can_arrive(resolved_git, monkeypatch):
+ session_id = "ses_bus_cached"
+ _workspace(session_id)
+ calls = []
+
+ class FakeRepository:
+ def checkpoint(self, checkpoint, **kwargs):
+ calls.append((checkpoint, kwargs))
+ return True
+
+ lookups = []
+
+ def load_context(_session_id, **kwargs):
+ lookups.append(kwargs)
+ if kwargs:
+ raise AssertionError("turn.end must not select a later pending message")
+ return TurnCheckpointContext(message="current driving message", message_id="msg-current")
+
+ monkeypatch.setattr(show_git, "load_turn_checkpoint_context", load_context)
+ service = ShowGitCheckpointService(resolved_git)
+ monkeypatch.setattr(service, "_repository", lambda _session_id: FakeRepository())
+ bus = InboxEventBus()
+ service.start(bus)
+
+ bus.publish("turn.start", {"session_id": session_id})
+ bus.publish("turn.end", {"session_id": session_id})
+ service.stop()
+
+ assert lookups == [{}]
+ assert calls == [
+ (PRE_TURN, {"run_id": None}),
+ (POST_TURN, {"message": "current driving message", "run_id": None}),
+ ]
+
+
+def test_duplicate_turn_events_do_not_create_duplicate_checkpoint_commits(resolved_git, monkeypatch):
+ session_id = "ses_bus_duplicate"
+ workspace = _workspace(session_id)
+ (workspace / "page.txt").write_text("before\n", encoding="utf-8")
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda _session_id, **_kwargs: TurnCheckpointContext(message="edit page"),
+ )
+ service = ShowGitCheckpointService(resolved_git)
+ bus = InboxEventBus()
+ service.start(bus)
+
+ bus.publish("turn.start", {"session_id": session_id})
+ bus.publish("turn.start", {"session_id": session_id})
+ (workspace / "page.txt").write_text("after\n", encoding="utf-8")
+ bus.publish("turn.end", {"session_id": session_id})
+ bus.publish("turn.end", {"session_id": session_id})
+ service.stop()
+
+ repo = _repo(session_id, resolved_git)
+ assert _platform_git(repo, "rev-list", "--count", "main").stdout.strip() == "2"
+ assert _platform_git(repo, "log", "--format=%s").stdout.splitlines() == [
+ "edit page",
+ "adopt existing workspace",
+ ]
+
+
+def test_agent_contract_uses_startup_latched_checkpoint_service_state(resolved_git, monkeypatch):
+ bus = InboxEventBus()
+ unavailable_service = ShowGitCheckpointService(None)
+ unavailable_service.start(bus)
+ monkeypatch.setattr(show_git, "resolve_git", lambda: resolved_git)
+
+ unavailable = format_agent_contract(session_id="ses_latched_unavailable")
+ unavailable_status = json.loads(paths.get_show_git_runtime_status_path().read_text(encoding="utf-8"))
+ unavailable_service.stop()
+
+ active_service = ShowGitCheckpointService(resolved_git)
+ active_service.start(bus)
+ monkeypatch.setattr(show_git, "resolve_git", lambda: None)
+ available = format_agent_contract(session_id="ses_latched_available")
+ active_status = json.loads(paths.get_show_git_runtime_status_path().read_text(encoding="utf-8"))
+ active_service.stop()
+
+ assert "Automatic Show Page history is unavailable" in unavailable
+ assert unavailable_status["active"] is False
+ assert "History is saved automatically around each turn" in available
+ assert active_status["active"] is True
+ assert active_status["service_pid"] == os.getpid()
+
+
+def test_cross_process_checkpoint_status_requires_current_service_owner(monkeypatch):
+ status_path = paths.get_show_git_runtime_status_path()
+ status_path.parent.mkdir(parents=True)
+ status_path.write_text(
+ json.dumps(
+ {
+ "version": show_git._CHECKPOINT_STATUS_VERSION,
+ "active": True,
+ "service_pid": 1234,
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(show_git, "_checkpoint_service_active", None)
+ monkeypatch.setattr("vibe.runtime.resolve_service_owner_pid", lambda **_kwargs: 5678)
+
+ assert show_git.show_git_checkpointing_active() is False
+
+ monkeypatch.setattr("vibe.runtime.resolve_service_owner_pid", lambda **_kwargs: 1234)
+ assert show_git.show_git_checkpointing_active() is True
+
+
+def test_storage_lookup_uses_turn_boundary_instead_of_later_pending_message():
+ from sqlalchemy import update
+
+ from storage import messages_service
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import agent_sessions, messages
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state(primary_platform="avibe")
+ session_id = "ses_storage_boundary"
+ with get_cached_sqlite_engine().begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_storage_boundary",
+ now="2026-07-11T00:00:00+00:00",
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor=session_id,
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at="2026-07-11T00:00:00+00:00",
+ updated_at="2026-07-11T00:00:00+00:00",
+ last_active_at="2026-07-11T00:00:00+00:00",
+ )
+ )
+ prior = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="prior user message",
+ )
+ result = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="prior result",
+ )
+ conn.execute(update(messages).where(messages.c.id == prior["id"]).values(created_at="2098-01-01T00:00:00+00:00"))
+ conn.execute(update(messages).where(messages.c.id == result["id"]).values(created_at="2098-01-01T00:00:01+00:00"))
+
+ assert show_git.load_turn_checkpoint_context(session_id) == TurnCheckpointContext()
+
+ with get_cached_sqlite_engine().begin() as conn:
+ current = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="current driving message",
+ )
+ later = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ message_type="pending",
+ text="later pending message",
+ )
+ conn.execute(update(messages).where(messages.c.id == current["id"]).values(created_at="2099-01-01T00:00:01+00:00"))
+ conn.execute(update(messages).where(messages.c.id == later["id"]).values(created_at="2099-01-01T00:00:02+00:00"))
+
+ context = show_git.load_turn_checkpoint_context(session_id, after="2099-01-01T00:00:00+00:00")
+ assert context.message == "current driving message"
+ assert context.message_id == current["id"]
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 2e00856f7..0a9a2d3e5 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -551,6 +551,7 @@ def test_public_show_page_does_not_inject_write_runtime_config(monkeypatch, tmp_
def test_private_show_page_falls_back_to_static_when_runtime_unavailable(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: True)
_save_config(tmp_path)
_create_show_page("ses123", "private")
set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))
@@ -563,9 +564,201 @@ def test_private_show_page_falls_back_to_static_when_runtime_unavailable(monkeyp
assert b"Loading Show Page" in response.content
assert b"Ready to visualize" in response.content
assert b"Copy prompt" in response.content
+ assert b"History is saved automatically around each turn" in response.content
+ assert b"Never add remotes, push, or publish" in response.content
assert b'src="./src/main.tsx"' not in response.content
+def test_private_show_page_recovery_reports_history_unavailable_without_git(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: False)
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))
+ try:
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert b"Automatic Show Page history is unavailable" in response.content
+ assert b"History is saved automatically around each turn" not in response.content
+ assert b"git restore --source" not in response.content
+
+
+def test_private_show_page_recovery_uses_self_managed_history_contract(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: True)
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ (paths.get_show_pages_dir() / "ses123" / ".git").mkdir()
+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))
+ try:
+ response = app.test_client().get("/show/ses123/", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert b"shadow history continues automatically" in response.content
+ assert b"not Avibe history" in response.content
+ assert b"Only if the user explicitly asks to recover from Avibe history" in response.content
+ assert b"History is saved automatically around each turn" not in response.content
+ assert b"Restore only via" not in response.content
+
+
+def test_private_show_page_static_fallback_denies_dot_leading_segments(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ page_dir = paths.get_show_pages_dir() / "ses123"
+ (page_dir / ".git").mkdir()
+ (page_dir / ".git" / "HEAD").write_text("private history", encoding="utf-8")
+ (page_dir / "assets" / ".draft").mkdir(parents=True)
+ (page_dir / "assets" / ".draft" / "secret.txt").write_text("private draft", encoding="utf-8")
+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))
+ try:
+ client = app.test_client()
+ git_response = client.get("/show/ses123/.git/HEAD", base_url="http://127.0.0.1:5123")
+ nested_response = client.get(
+ "/show/ses123/assets/.draft/secret.txt",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert git_response.status_code == 404
+ assert nested_response.status_code == 404
+ assert b"private history" not in git_response.content
+ assert b"private draft" not in nested_response.content
+
+
+def test_private_show_page_denies_dot_path_before_runtime_proxy(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ (paths.get_show_pages_dir() / "ses123" / ".git").write_text(
+ "gitdir: /tmp/show-git/ses123.git\n",
+ encoding="utf-8",
+ )
+ manager = _FakeShowRuntimeManager(body=b"leaked pointer")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get("/show/ses123/.git", base_url="http://127.0.0.1:5123")
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert b"show-git" not in response.content
+ assert manager.calls == []
+
+
+def test_private_show_page_proxies_vite_dependency_dot_path(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(
+ body=b"export const react = true",
+ extra_headers={"content-type": "text/javascript"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/node_modules/.vite/deps/react.js",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const react = true"
+ assert manager.calls[0][1] == "/sessions/ses123/app/node_modules/.vite/deps/react.js"
+
+
+def test_private_show_page_proxies_root_vite_dependency_dot_path(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(
+ body=b"export const react = true",
+ extra_headers={"content-type": "text/javascript"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/.vite/deps/react.js",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const react = true"
+ assert manager.calls[0][1] == "/sessions/ses123/app/.vite/deps/react.js"
+
+
+def test_private_show_page_denies_sensitive_file_before_runtime_proxy(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(body=b"private key")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ "/show/ses123/config/server.key",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert manager.calls == []
+
+
+def test_private_show_page_proxies_workspace_at_fs_path_below_dot_home(monkeypatch, tmp_path):
+ avibe_home = tmp_path / ".avibe"
+ monkeypatch.setenv("AVIBE_HOME", str(avibe_home))
+ _save_config(avibe_home)
+ _create_show_page("ses123", "private")
+ source_path = paths.get_show_page_dir("ses123") / "src" / "App.tsx"
+ manager = _FakeShowRuntimeManager(
+ body=b"export default function App() {}",
+ extra_headers={"content-type": "text/javascript"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/show/ses123/@fs/{source_path.as_posix()}",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export default function App() {}"
+ assert manager.calls
+ assert manager.calls[0][1].endswith(f"/@fs/{source_path.as_posix()}")
+
+
+def test_private_show_page_denies_workspace_dot_path_through_at_fs(monkeypatch, tmp_path):
+ avibe_home = tmp_path / ".avibe"
+ monkeypatch.setenv("AVIBE_HOME", str(avibe_home))
+ _save_config(avibe_home)
+ _create_show_page("ses123", "private")
+ hidden_path = paths.get_show_page_dir("ses123") / ".draft" / "secret.ts"
+ manager = _FakeShowRuntimeManager(body=b"export const secret = true")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/show/ses123/@fs/{hidden_path.as_posix()}",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert manager.calls == []
+
+
def test_show_page_recovery_loading_holds_before_ready(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -2842,6 +3035,100 @@ def test_public_show_page_api_does_not_fall_back_to_static(monkeypatch, tmp_path
assert b"secret" not in response.content
+def test_public_show_page_static_fallback_denies_dot_leading_segments(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ page_dir = paths.get_show_pages_dir() / "ses123"
+ (page_dir / ".git").mkdir()
+ (page_dir / ".git" / "config").write_text("public history", encoding="utf-8")
+ set_show_runtime_manager_for_tests(_FakeShowRuntimeManager(fail=True))
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/.git/config",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert b"public history" not in response.content
+
+
+def test_public_show_page_denies_dot_path_before_runtime_proxy(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ (paths.get_show_pages_dir() / "ses123" / ".git").write_text(
+ "gitdir: /tmp/show-git/ses123.git\n",
+ encoding="utf-8",
+ )
+ manager = _FakeShowRuntimeManager(body=b"leaked pointer")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/.git",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 404
+ assert b"show-git" not in response.content
+ assert manager.calls == []
+
+
+def test_public_show_page_proxies_vite_dependency_dot_path(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(
+ body=b"export const react = true",
+ extra_headers={"content-type": "text/javascript"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/node_modules/.vite/deps/react.js",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const react = true"
+ assert manager.calls[0][1] == "/sessions/ses123/app/node_modules/.vite/deps/react.js"
+
+
+def test_public_show_page_proxies_relocated_vite_cache_at_fs_path(monkeypatch, tmp_path):
+ avibe_home = tmp_path / ".avibe"
+ monkeypatch.setenv("AVIBE_HOME", str(avibe_home))
+ _save_config(avibe_home)
+ share_id = _create_show_page("ses123", "public")
+ dependency_path = paths.get_runtime_dir() / "show-runtime" / ".vite-cache" / "deps" / "react.js"
+ manager = _FakeShowRuntimeManager(
+ body=b"export const react = true",
+ extra_headers={"content-type": "text/javascript"},
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/@fs/{dependency_path.as_posix()}",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.content == b"export const react = true"
+ assert manager.calls
+ assert manager.calls[0][1].endswith(f"/@fs/{dependency_path.as_posix()}")
+
+
def test_public_show_page_redirects_without_trailing_slash(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 060b4969e..2b95f1e40 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -207,6 +207,37 @@ def test_render_status_includes_restart_status(tmp_path, monkeypatch):
assert payload["restart"]["error"] == "start command timed out after 30 seconds"
+def test_render_status_reports_degraded_show_checkpoints_without_git(monkeypatch):
+ monkeypatch.setattr("core.git_binary.resolve_git", lambda: None)
+
+ payload = json.loads(runtime.render_status(detect_extra_processes=False))
+
+ assert payload["show_git_checkpoints"] == "degraded: Git checkpoint service unavailable"
+
+
+def test_doctor_reports_degraded_show_checkpoints_without_git(monkeypatch):
+ monkeypatch.setattr("core.git_binary.resolve_git", lambda: None)
+
+ assert cli._show_git_checkpoint_items() == [
+ {
+ "status": "warn",
+ "message": "Show Page checkpointing is degraded because Git is unavailable",
+ "code": "runtime.show_git_unavailable",
+ }
+ ]
+
+
+def test_status_and_doctor_use_running_checkpoint_service_state(monkeypatch):
+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: 1234)
+ monkeypatch.setattr("core.show_git.show_git_checkpointing_active", lambda: False)
+ monkeypatch.setattr("core.git_binary.resolve_git", lambda: object())
+
+ payload = json.loads(runtime.render_status(detect_extra_processes=False))
+
+ assert payload["show_git_checkpoints"] == "degraded: Git checkpoint service unavailable"
+ assert cli._show_git_checkpoint_items()[0]["code"] == "runtime.show_git_unavailable"
+
+
def test_stop_process_handles_missing_pid(tmp_path, monkeypatch):
monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")
runtime.ensure_dirs()
diff --git a/vibe/cli.py b/vibe/cli.py
index 6c4a195ee..9c70bdf8a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -792,6 +792,29 @@ def _service_lifecycle_items(*, detect_extra_processes: bool = True) -> list[dic
return items
+def _show_git_checkpoint_items() -> list[dict]:
+ try:
+ if runtime.resolve_service_owner_pid(include_starting=False):
+ from core.show_git import show_git_checkpointing_active
+
+ available = show_git_checkpointing_active()
+ else:
+ from core.git_binary import resolve_git
+
+ available = resolve_git() is not None
+ except Exception:
+ available = False
+ if available:
+ return []
+ return [
+ {
+ "status": "warn",
+ "message": "Show Page checkpointing is degraded because Git is unavailable",
+ "code": "runtime.show_git_unavailable",
+ }
+ ]
+
+
def _remote_examples_text() -> str:
return dedent(
"""\
@@ -8224,6 +8247,7 @@ def _doctor(*, deep: bool = False):
*_service_install_family_items(detect_extra_processes=deep),
*_restart_state_items(),
*_runtime_architecture_items(),
+ *_show_git_checkpoint_items(),
]:
runtime_items.append(item)
status = item.get("status")
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 9774b4030..654adadb8 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -1097,6 +1097,21 @@ def render_status(*, detect_extra_processes: bool = True):
restart_status = read_json(get_restart_status_path())
if restart_status:
status["restart"] = restart_status
+ try:
+ if owner_pid:
+ from core.show_git import show_git_checkpointing_active
+
+ checkpointing_available = show_git_checkpointing_active()
+ else:
+ from core.git_binary import resolve_git
+
+ checkpointing_available = resolve_git() is not None
+ if checkpointing_available:
+ status.pop("show_git_checkpoints", None)
+ else:
+ status["show_git_checkpoints"] = "degraded: Git checkpoint service unavailable"
+ except Exception:
+ status["show_git_checkpoints"] = "degraded: Git checkpoint status failed"
return json.dumps(status, indent=2)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 66a36faf8..bc4879829 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -7736,6 +7736,12 @@ def _show_page_not_found_response():
return jsonify({"error": "not_found"}), 404
+def _show_page_file_not_found_response():
+ response = jsonify({"error": "not_found"})
+ response.status_code = 404
+ return response
+
+
def _show_page_runtime_unavailable_response():
return jsonify({"error": "show_runtime_unavailable"}), 503
@@ -7750,6 +7756,71 @@ def _is_show_page_entry_asset(asset_path: str) -> bool:
return relative in {"", "index.html"}
+def _decode_show_page_asset_path(asset_path: str) -> str:
+ decoded = (asset_path or "").strip("/")
+ for _ in range(3):
+ updated = unquote(decoded)
+ if updated == decoded:
+ break
+ decoded = updated
+ return decoded.replace("\\", "/")
+
+
+def _is_show_page_dot_path(asset_path: str) -> bool:
+ decoded = _decode_show_page_asset_path(asset_path)
+ return any(segment.startswith(".") for segment in decoded.split("/") if segment)
+
+
+def _is_show_runtime_sensitive_file_segment(segment: str) -> bool:
+ lowered = segment.lower()
+ return (
+ lowered == ".git"
+ or lowered == ".env"
+ or lowered.startswith(".env.")
+ or lowered.endswith((".pem", ".crt", ".key"))
+ )
+
+
+def _is_show_page_runtime_denied_path(asset_path: str, *, session_id: str) -> bool:
+ decoded = _decode_show_page_asset_path(asset_path)
+ segments = [segment for segment in decoded.split("/") if segment]
+ if any(_is_show_runtime_sensitive_file_segment(segment) for segment in segments):
+ return True
+ dot_segments = [index for index, segment in enumerate(segments) if segment.startswith(".")]
+ if not dot_segments:
+ return False
+ if any(segment in {".", ".."} for segment in segments):
+ return True
+
+ vite_dependency = (
+ (len(segments) >= 4 and segments[:3] == ["node_modules", ".vite", "deps"] and dot_segments == [1])
+ or (len(segments) >= 3 and segments[:2] == [".vite", "deps"] and dot_segments == [0])
+ )
+ if vite_dependency:
+ return False
+
+ if not decoded.startswith("@fs/"):
+ return True
+
+ raw_fs_path = decoded.removeprefix("@fs/")
+ fs_path = Path(raw_fs_path)
+ if fs_path.is_absolute():
+ target = fs_path.resolve(strict=False)
+ workspace = paths.get_show_page_dir(session_id).resolve(strict=False)
+ try:
+ workspace_relative = target.relative_to(workspace)
+ except ValueError:
+ # Runtime dependency roots can legitimately live below dot directories
+ # such as ~/.avibe. The Show Runtime owns their allowlist and still denies
+ # sensitive filenames; only workspace-relative dot paths are all private.
+ return False
+ return any(part.startswith(".") for part in workspace_relative.parts)
+
+ # A Vite @fs path is normally absolute. Retain the synthetic relative cache
+ # form used by prewarming/tests, but do not generally relax relative dot paths.
+ return not _is_relocated_vite_dep_path(decoded)
+
+
def _show_page_recovery_response(session_id: str):
from core.show_pages import show_page_runtime_recovery_html
@@ -7760,12 +7831,18 @@ def _show_page_file_response(root: Path, asset_path: str):
relative = (asset_path or "").strip("/")
if not relative:
relative = "index.html"
- candidate = (root / unquote(relative)).resolve()
+ decoded = _decode_show_page_asset_path(relative)
+ segments = [segment for segment in decoded.split("/") if segment]
+ if _is_show_page_dot_path(decoded) or any(
+ _is_show_runtime_sensitive_file_segment(segment) for segment in segments
+ ):
+ return _show_page_file_not_found_response()
+ candidate = (root / decoded).resolve()
root_resolved = root.resolve()
if candidate != root_resolved and root_resolved not in candidate.parents:
- return jsonify({"error": "not_found"}), 404
+ return _show_page_file_not_found_response()
if not candidate.exists() or not candidate.is_file():
- return _show_page_not_found_response()
+ return _show_page_file_not_found_response()
mime_type, _ = mimetypes.guess_type(str(candidate))
response = send_file(candidate, mimetype=mime_type or "application/octet-stream")
response.headers["X-Content-Type-Options"] = "nosniff"
@@ -8711,6 +8788,8 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_offline_response()
if page.visibility != "private":
return _show_page_not_found_response()
+ if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):
+ return _show_page_file_not_found_response()
if asset_path.strip("/") in {"__show/events", "__events"}:
return await _show_events_response(page.session_id)
page_dir = ensure_show_page_dir(page.session_id)
@@ -8780,6 +8859,8 @@ async def serve_public_show_page(share_id, asset_path):
return _show_page_offline_response()
if page.visibility != "public":
return _show_page_not_found_response()
+ if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):
+ return _show_page_file_not_found_response()
if asset_path.strip("/") in {"__show/events", "__events"}:
if request.method != "GET":
return jsonify({"ok": False, "code": "public_show_events_read_only"}), 403