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(regression): add incus regression runner (#522)

Call White9b6a3f179b2d
diff --git a/.env.regression.example b/.env.regression.example
new file mode 100644
index 000000000..ff1100dcd
--- /dev/null
+++ b/.env.regression.example
@@ -0,0 +1,119 @@
+# Copy to .env.regression and fill in local-only secrets.
+# This file stays local and must never be committed.
+
+# -----------------------------------------------------------------------------
+# Shared agent credentials
+# -----------------------------------------------------------------------------
+ANTHROPIC_API_KEY=
+ANTHROPIC_BASE_URL=
+OPENAI_API_KEY=
+OPENAI_BASE_URL=
+OPENAI_API_BASE=
+
+# -----------------------------------------------------------------------------
+# Shared agent home config bootstrap
+# -----------------------------------------------------------------------------
+REGRESSION_CLAUDE_BASE_URL=
+REGRESSION_CLAUDE_AUTH_TOKEN=
+REGRESSION_CLAUDE_ATTRIBUTION_HEADER=0
+
+REGRESSION_CODEX_MODEL_PROVIDER=OpenAI
+REGRESSION_CODEX_MODEL=gpt-5.4
+REGRESSION_CODEX_REVIEW_MODEL=gpt-5.4
+REGRESSION_CODEX_REASONING_EFFORT=xhigh
+REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE=true
+REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2=false
+REGRESSION_CODEX_CONTEXT_WINDOW=1000000
+REGRESSION_CODEX_AUTO_COMPACT_TOKEN_LIMIT=900000
+REGRESSION_CODEX_BASE_URL=
+REGRESSION_CODEX_OPENAI_API_KEY=
+REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING=true
+
+REGRESSION_OPENCODE_OPENAI_BASE_URL=
+REGRESSION_OPENCODE_OPENAI_API_KEY=
+REGRESSION_OPENCODE_ANTHROPIC_BASE_URL=
+REGRESSION_OPENCODE_ANTHROPIC_API_KEY=
+
+# -----------------------------------------------------------------------------
+# Shared regression defaults
+# -----------------------------------------------------------------------------
+REGRESSION_UI_HOST=127.0.0.1
+REGRESSION_PORT=15130
+REGRESSION_DEFAULT_CWD=/home/avibe/.avibe/workdir
+REGRESSION_DEFAULT_BACKEND=opencode
+REGRESSION_LOG_LEVEL=INFO
+REGRESSION_LANGUAGE=en
+
+# Master/worktree regression does not necessarily carry a packaged release
+# manifest, so the regression script prepares Show Runtime from source by
+# default. Release/pre-release installs should use the packaged manifest path.
+REGRESSION_SHOW_RUNTIME_SOURCE=github-source
+REGRESSION_SHOW_RUNTIME_GITHUB_REPO=https://github.com/avibe-bot/vibe-show-runtime.git
+REGRESSION_SHOW_RUNTIME_GITHUB_REF=main
+
+# -----------------------------------------------------------------------------
+# Slack
+# -----------------------------------------------------------------------------
+REGRESSION_SLACK_BOT_TOKEN=
+REGRESSION_SLACK_APP_TOKEN=
+REGRESSION_SLACK_CHANNEL=
+REGRESSION_SLACK_BACKEND=opencode
+REGRESSION_SLACK_REQUIRE_MENTION=false
+REGRESSION_SLACK_OPENCODE_AGENT=
+REGRESSION_SLACK_OPENCODE_MODEL=
+REGRESSION_SLACK_OPENCODE_REASONING_EFFORT=
+REGRESSION_SLACK_CLAUDE_AGENT=
+REGRESSION_SLACK_CLAUDE_MODEL=
+REGRESSION_SLACK_CODEX_MODEL=
+REGRESSION_SLACK_CODEX_REASONING_EFFORT=
+
+# -----------------------------------------------------------------------------
+# Discord
+# -----------------------------------------------------------------------------
+REGRESSION_DISCORD_BOT_TOKEN=
+REGRESSION_DISCORD_CHANNEL=
+REGRESSION_DISCORD_GUILD_ALLOWLIST=
+REGRESSION_DISCORD_GUILD_DENYLIST=
+REGRESSION_DISCORD_BACKEND=codex
+REGRESSION_DISCORD_REQUIRE_MENTION=false
+REGRESSION_DISCORD_OPENCODE_AGENT=
+REGRESSION_DISCORD_OPENCODE_MODEL=
+REGRESSION_DISCORD_OPENCODE_REASONING_EFFORT=
+REGRESSION_DISCORD_CLAUDE_AGENT=
+REGRESSION_DISCORD_CLAUDE_MODEL=
+REGRESSION_DISCORD_CODEX_MODEL=
+REGRESSION_DISCORD_CODEX_REASONING_EFFORT=
+
+# -----------------------------------------------------------------------------
+# Feishu
+# -----------------------------------------------------------------------------
+REGRESSION_FEISHU_APP_ID=
+REGRESSION_FEISHU_APP_SECRET=
+REGRESSION_FEISHU_CHAT_ID=
+REGRESSION_FEISHU_BACKEND=claude
+REGRESSION_FEISHU_REQUIRE_MENTION=false
+REGRESSION_FEISHU_DOMAIN=feishu
+REGRESSION_FEISHU_OPENCODE_AGENT=
+REGRESSION_FEISHU_OPENCODE_MODEL=
+REGRESSION_FEISHU_OPENCODE_REASONING_EFFORT=
+REGRESSION_FEISHU_CLAUDE_AGENT=
+REGRESSION_FEISHU_CLAUDE_MODEL=
+REGRESSION_FEISHU_CODEX_MODEL=
+REGRESSION_FEISHU_CODEX_REASONING_EFFORT=
+
+# -----------------------------------------------------------------------------
+# WeChat
+# -----------------------------------------------------------------------------
+REGRESSION_WECHAT_BOT_TOKEN=
+REGRESSION_WECHAT_BASE_URL=https://ilinkai.weixin.qq.com
+REGRESSION_WECHAT_CDN_BASE_URL=https://novac2c.cdn.weixin.qq.com/c2c
+REGRESSION_WECHAT_CHANNEL=
+REGRESSION_WECHAT_BACKEND=opencode
+REGRESSION_WECHAT_REQUIRE_MENTION=false
+REGRESSION_WECHAT_OPENCODE_AGENT=
+REGRESSION_WECHAT_OPENCODE_MODEL=
+REGRESSION_WECHAT_OPENCODE_REASONING_EFFORT=
+REGRESSION_WECHAT_CLAUDE_AGENT=
+REGRESSION_WECHAT_CLAUDE_MODEL=
+REGRESSION_WECHAT_CODEX_MODEL=
+REGRESSION_WECHAT_CODEX_REASONING_EFFORT=
diff --git a/.env.three-regression.example b/.env.three-regression.example
deleted file mode 100644
index 573363a77..000000000
--- a/.env.three-regression.example
+++ /dev/null
@@ -1,123 +0,0 @@
-# Copy to .env.three-regression and fill in local-only secrets.
-# This file stays local and must never be committed.
-
-# -----------------------------------------------------------------------------
-# Shared agent credentials
-# -----------------------------------------------------------------------------
-ANTHROPIC_API_KEY=
-ANTHROPIC_BASE_URL=
-OPENAI_API_KEY=
-OPENAI_BASE_URL=
-OPENAI_API_BASE=
-
-# -----------------------------------------------------------------------------
-# Shared agent home config bootstrap
-# -----------------------------------------------------------------------------
-THREE_REGRESSION_CLAUDE_BASE_URL=
-THREE_REGRESSION_CLAUDE_AUTH_TOKEN=
-THREE_REGRESSION_CLAUDE_ATTRIBUTION_HEADER=0
-
-THREE_REGRESSION_CODEX_MODEL_PROVIDER=OpenAI
-THREE_REGRESSION_CODEX_MODEL=gpt-5.4
-THREE_REGRESSION_CODEX_REVIEW_MODEL=gpt-5.4
-THREE_REGRESSION_CODEX_REASONING_EFFORT=xhigh
-THREE_REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE=true
-THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2=false
-THREE_REGRESSION_CODEX_CONTEXT_WINDOW=1000000
-THREE_REGRESSION_CODEX_AUTO_COMPACT_TOKEN_LIMIT=900000
-THREE_REGRESSION_CODEX_BASE_URL=
-THREE_REGRESSION_CODEX_OPENAI_API_KEY=
-THREE_REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING=true
-
-THREE_REGRESSION_OPENCODE_OPENAI_BASE_URL=
-THREE_REGRESSION_OPENCODE_OPENAI_API_KEY=
-THREE_REGRESSION_OPENCODE_ANTHROPIC_BASE_URL=
-THREE_REGRESSION_OPENCODE_ANTHROPIC_API_KEY=
-
-# -----------------------------------------------------------------------------
-# Shared regression defaults
-# -----------------------------------------------------------------------------
-# Keep empty to use the canonical repo-level runtime state root:
-# `.runtime/three-regression` under the primary checkout. Set this only when
-# intentionally running an isolated regression state.
-THREE_REGRESSION_STATE_ROOT=
-THREE_REGRESSION_UI_HOST=127.0.0.1
-THREE_REGRESSION_PORT=15130
-THREE_REGRESSION_DEFAULT_CWD=/home/avibe/.avibe/workdir
-THREE_REGRESSION_DEFAULT_BACKEND=opencode
-THREE_REGRESSION_LOG_LEVEL=INFO
-THREE_REGRESSION_LANGUAGE=en
-
-# Master/worktree regression does not necessarily carry a packaged release
-# manifest, so the regression script prepares Show Runtime from source by
-# default. Release/pre-release installs should use the packaged manifest path.
-THREE_REGRESSION_SHOW_RUNTIME_SOURCE=github-source
-THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REPO=https://github.com/avibe-bot/vibe-show-runtime.git
-THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REF=main
-
-# -----------------------------------------------------------------------------
-# Slack
-# -----------------------------------------------------------------------------
-THREE_REGRESSION_SLACK_BOT_TOKEN=
-THREE_REGRESSION_SLACK_APP_TOKEN=
-THREE_REGRESSION_SLACK_CHANNEL=
-THREE_REGRESSION_SLACK_BACKEND=opencode
-THREE_REGRESSION_SLACK_REQUIRE_MENTION=false
-THREE_REGRESSION_SLACK_OPENCODE_AGENT=
-THREE_REGRESSION_SLACK_OPENCODE_MODEL=
-THREE_REGRESSION_SLACK_OPENCODE_REASONING_EFFORT=
-THREE_REGRESSION_SLACK_CLAUDE_AGENT=
-THREE_REGRESSION_SLACK_CLAUDE_MODEL=
-THREE_REGRESSION_SLACK_CODEX_MODEL=
-THREE_REGRESSION_SLACK_CODEX_REASONING_EFFORT=
-
-# -----------------------------------------------------------------------------
-# Discord
-# -----------------------------------------------------------------------------
-THREE_REGRESSION_DISCORD_BOT_TOKEN=
-THREE_REGRESSION_DISCORD_CHANNEL=
-THREE_REGRESSION_DISCORD_GUILD_ALLOWLIST=
-THREE_REGRESSION_DISCORD_GUILD_DENYLIST=
-THREE_REGRESSION_DISCORD_BACKEND=codex
-THREE_REGRESSION_DISCORD_REQUIRE_MENTION=false
-THREE_REGRESSION_DISCORD_OPENCODE_AGENT=
-THREE_REGRESSION_DISCORD_OPENCODE_MODEL=
-THREE_REGRESSION_DISCORD_OPENCODE_REASONING_EFFORT=
-THREE_REGRESSION_DISCORD_CLAUDE_AGENT=
-THREE_REGRESSION_DISCORD_CLAUDE_MODEL=
-THREE_REGRESSION_DISCORD_CODEX_MODEL=
-THREE_REGRESSION_DISCORD_CODEX_REASONING_EFFORT=
-
-# -----------------------------------------------------------------------------
-# Feishu
-# -----------------------------------------------------------------------------
-THREE_REGRESSION_FEISHU_APP_ID=
-THREE_REGRESSION_FEISHU_APP_SECRET=
-THREE_REGRESSION_FEISHU_CHAT_ID=
-THREE_REGRESSION_FEISHU_BACKEND=claude
-THREE_REGRESSION_FEISHU_REQUIRE_MENTION=false
-THREE_REGRESSION_FEISHU_DOMAIN=feishu
-THREE_REGRESSION_FEISHU_OPENCODE_AGENT=
-THREE_REGRESSION_FEISHU_OPENCODE_MODEL=
-THREE_REGRESSION_FEISHU_OPENCODE_REASONING_EFFORT=
-THREE_REGRESSION_FEISHU_CLAUDE_AGENT=
-THREE_REGRESSION_FEISHU_CLAUDE_MODEL=
-THREE_REGRESSION_FEISHU_CODEX_MODEL=
-THREE_REGRESSION_FEISHU_CODEX_REASONING_EFFORT=
-
-# -----------------------------------------------------------------------------
-# WeChat
-# -----------------------------------------------------------------------------
-THREE_REGRESSION_WECHAT_BOT_TOKEN=
-THREE_REGRESSION_WECHAT_BASE_URL=https://ilinkai.weixin.qq.com
-THREE_REGRESSION_WECHAT_CDN_BASE_URL=https://novac2c.cdn.weixin.qq.com/c2c
-THREE_REGRESSION_WECHAT_CHANNEL=
-THREE_REGRESSION_WECHAT_BACKEND=opencode
-THREE_REGRESSION_WECHAT_REQUIRE_MENTION=false
-THREE_REGRESSION_WECHAT_OPENCODE_AGENT=
-THREE_REGRESSION_WECHAT_OPENCODE_MODEL=
-THREE_REGRESSION_WECHAT_OPENCODE_REASONING_EFFORT=
-THREE_REGRESSION_WECHAT_CLAUDE_AGENT=
-THREE_REGRESSION_WECHAT_CLAUDE_MODEL=
-THREE_REGRESSION_WECHAT_CODEX_MODEL=
-THREE_REGRESSION_WECHAT_CODEX_REASONING_EFFORT=
diff --git a/.gitignore b/.gitignore
index 96c0b7340..32424b8f4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -105,6 +105,7 @@ celerybeat.pid
# Environments
.env
.env.e2e
+.env.regression
.env.three-regression
.env.*.local
.venv
diff --git a/AGENTS.md b/AGENTS.md
index eca948337..9cff7b7d5 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -13,7 +13,7 @@ Current product shape:
- V2 config-driven service with a Web UI setup wizard and settings pages
- multi-platform message transport with shared core orchestration
- multi-backend agent routing across OpenCode, Claude Code, and Codex
-- Docker-based unified regression container for real cross-platform verification
+- Incus-based unified regression environment for real cross-platform verification
Default mindset:
@@ -59,7 +59,7 @@ Decision checklist before writing code:
- logs: `~/.avibe/logs/vibe_remote.log`
- persisted state: `~/.avibe/state/`
- default agent working directory: `_tmp/`
-- generated regression data: `.runtime/three-regression/` in the primary checkout
+- generated regression metadata: `.runtime/incus-regression/` in the primary checkout
## 3. Runtime Environments
@@ -87,47 +87,48 @@ Hard rule:
agent detection/install tests against `~/.avibe`, legacy `~/.vibe_remote`, the user's shell
environment, or the running local service unless the user explicitly asks for
that exact local operation. Use an isolated `VIBE_REMOTE_HOME`, a temporary
- fixture directory, the Docker regression container, or the existing regression
+ fixture directory, the Incus regression environment, or the existing regression
environment instead.
-- Unless the user explicitly asks otherwise, use the Docker regression environment for user-facing verification.
+- Unless the user explicitly asks otherwise, use the Incus regression environment for user-facing verification.
-### Regression Testing (Docker)
+### Regression Testing (Incus)
When the user says `回归测试`, treat it as:
-- update the latest code into the existing Docker-based regression environment
+- update the latest code into the existing Incus-based regression environment
- let the user verify behavior on Slack, Discord, Feishu/Lark, and WeChat
- preserve previously accumulated regression config/state unless the user explicitly asks for a reset
-The regression environment runs a single unified container with all four IM platforms enabled simultaneously.
+The regression environment runs a single unified Incus system container with all four IM platforms enabled simultaneously.
Standard path:
-- default command: `./scripts/run_three_regression.sh`
+- default command: `./scripts/run_regression.sh`
+- direct runner: `python3 scripts/incus_regression.py up --target master`
Rules:
- do **not** use `--reset-config` or `--reset-all` unless the user explicitly requests reset behavior
- do **not** disable or overwrite preserved `remote_access` / Avibe Cloud pairing state just to make local probes pass; the regression environment is also used to test remote access, so preserve and fix the host/binding path instead
-- when Avibe Cloud remote access is enabled in regression, prefer binding the Docker UI port to loopback for local maintenance access (`THREE_REGRESSION_PORT_BIND_HOST=127.0.0.1`) while keeping the remote public URL active for product testing
-- do **not** use `--no-build` when code changes must take effect; it is only for restarting with the existing image
+- when Avibe Cloud remote access is enabled in regression, prefer binding the Incus UI proxy to loopback for local maintenance access (`REGRESSION_PORT_BIND_HOST=127.0.0.1`) while keeping the remote public URL active for product testing
+- use `--target master` for the long-running master regression environment
+- use `--target worktree` for isolated temporary worktree regression environments
- after running the script, verify the service is healthy before handing back to the user
-- prefer Docker regression over local `vibe` whenever validating cross-platform behavior, setup wizard behavior, or user-facing IM flows
-- always use `./scripts/run_three_regression.sh`; do not run `docker compose -f docker-compose.three-regression.yml ...` directly because the script owns the canonical state root and runtime readiness checks
-- the script stores persistent regression state under the primary checkout's `.runtime/three-regression/` by default, even when invoked from a task worktree
-- the script reads `.env.three-regression` from the current worktree first, then falls back to the primary checkout
-- override `THREE_REGRESSION_STATE_ROOT` only when intentionally creating an isolated regression state
-- the regression container uses `/home/avibe` as a persistent real home; product state should live under `/home/avibe/.avibe`, with `/home/avibe/.vibe_remote` as the compatibility symlink after migration
+- prefer Incus regression over local `vibe` whenever validating cross-platform behavior, setup wizard behavior, or user-facing IM flows
+- always use `./scripts/run_regression.sh` or `python3 scripts/incus_regression.py`; do not run raw Incus commands directly because the runner owns naming, state preparation, source sync, runtime readiness checks, and worktree cleanup metadata
+- the script stores worktree regression metadata under the primary checkout's `.runtime/incus-regression/` by default, even when invoked from a task worktree
+- the script reads `.env.regression` from the current worktree first, then falls back to the primary checkout
+- temporary worktree environments should be deleted with `python3 scripts/incus_regression.py delete --target worktree --yes` or cleaned with `cleanup-stale --yes`
+- the regression container uses `/home/avibe` as a persistent real home; product state should live under `/home/avibe/.avibe`, with `/home/avibe/.vibe_remote` as the compatibility symlink
- the script must prepare and verify Show Runtime before reporting success; if Show Runtime cannot be installed or executed, treat the regression update as failed
-- for branch/master regression, `THREE_REGRESSION_SHOW_RUNTIME_SOURCE` defaults to `github-source` because source checkouts do not necessarily include a packaged release manifest; release/pre-release installs should use the packaged manifest path
-- the script serializes `up` and `down` operations with `.runtime/three-regression/.run.lock`; do not remove the lock unless the recorded PID is gone and the run is clearly stale
+- for branch/master regression, `REGRESSION_SHOW_RUNTIME_SOURCE` defaults to `github-source` because source checkouts do not necessarily include a packaged release manifest; release/pre-release installs should use the packaged manifest path
Worktree behavior:
-- code is built from the worktree where the script is invoked
-- runtime state is shared from the primary checkout's `.runtime/three-regression/`
-- this keeps pairing (`remote_access` config), agent CLI homes, sessions, Show Page workspaces, and Show Runtime cache stable while still allowing any worktree to update the regression image
-- the regression runner treats `.runtime/three-regression/home/.avibe/` as the normal 3.0 state; it does not import older harness layouts automatically
+- code is synced from the worktree where the script is invoked
+- `master` uses the long-running Incus project/instance and preserves product state
+- non-master worktrees should use temporary isolated Incus project/instances
+- worktree mappings live in `.runtime/incus-regression/worktrees.json`
## 4. Configuration and Routing Model
@@ -268,7 +269,7 @@ Testing guidance:
- when a scenario catalog exists, make the scenario ID visible in the automated test and in the PR description
- for multi-step auth/setup flows, update `tests/scenarios/auth_setup/catalog.yaml` and add or update a closed-loop scenario harness case under `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`; keep provider-specific parsing and heuristics in focused unit tests
- for UI changes, run `npm run build` in `ui/`
-- for cross-platform or user-facing verification, use the Docker regression workflow
+- for cross-platform or user-facing verification, use the Incus regression workflow
- until CI fully covers a flow, do a manual sanity check for the affected workflow when practical
## 8. Git, Security, and Operational Safety
@@ -283,7 +284,7 @@ Testing guidance:
- keep `AGENT_DEFAULT_CWD` scoped to `_tmp/` or another sanitized directory
- logs may contain sensitive context; scrub before sharing them back
-- be careful with persisted state under `~/.avibe/`, legacy `~/.vibe_remote/`, and `.runtime/three-regression/`
+- be careful with persisted state under `~/.avibe/`, legacy `~/.vibe_remote/`, and `.runtime/incus-regression/`
- do not reset or wipe regression data unless the user explicitly asks for it
## 9. Release Notes
diff --git a/config/v2_compat.py b/config/v2_compat.py
index eef0d4772..009e049fb 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -53,6 +53,8 @@ class OpenCodeCompatConfig:
binary: str
port: int
request_timeout_seconds: int
+ default_model: Optional[str] = None
+ default_reasoning_effort: Optional[str] = None
error_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT # Max retries on LLM stream errors (0 = no retry)
# User's saved default provider from Settings → Backends → OpenCode.
# Used as the ``providerID`` when a routed model string has no ``provider/``
@@ -128,6 +130,8 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
binary=v2.agents.opencode.cli_path,
port=4096,
request_timeout_seconds=60,
+ default_model=v2.agents.opencode.default_model,
+ default_reasoning_effort=v2.agents.opencode.default_reasoning_effort,
error_retry_limit=v2.agents.opencode.error_retry_limit,
# Surface the user's saved provider choice so the OpenCode agent
# adapter can prepend it as ``providerID`` for bare-model strings.
diff --git a/core/show_runtime.py b/core/show_runtime.py
index 520067246..6dde4e5a4 100644
--- a/core/show_runtime.py
+++ b/core/show_runtime.py
@@ -42,6 +42,9 @@ _RUNTIME_SOURCE_GITHUB = "github"
_RUNTIME_SOURCE_NPM = "npm"
_RUNTIME_MANIFEST_RESOURCE = "show_runtime_manifest.json"
_FALSE_VALUES = {"0", "false", "no", "off"}
+_PREWARM_IMPORT_RE = re.compile(r"""(?P<quote>["'])(?P<path>[^"']+)(?P=quote)""")
+_PREWARM_MAX_ASSETS = 64
+_PREWARM_MAX_DEPTH = 4
@dataclass(frozen=True)
@@ -198,13 +201,63 @@ class ShowRuntimeManager:
response = await self.request("GET", runtime_path, headers=headers)
if response.status_code >= 500:
return ShowRuntimeResult(False, reason=f"session_prewarm_failed:{response.status_code}")
- module_response = await self.request("GET", f"{runtime_path}src/main.tsx", headers=headers)
- if module_response.status_code >= 500:
- return ShowRuntimeResult(False, reason=f"session_prewarm_module_failed:{module_response.status_code}")
+ result = await self._prewarm_session_module_graph(
+ session_id,
+ runtime_path=runtime_path,
+ headers=headers,
+ seed_responses=[(runtime_path, response)],
+ base_path=base_path,
+ )
+ if not result.available:
+ return result
return ShowRuntimeResult(True, self._base_url)
except Exception as exc:
return ShowRuntimeResult(False, reason=f"session_prewarm_failed:{exc}")
+ async def _prewarm_session_module_graph(
+ self,
+ session_id: str,
+ *,
+ runtime_path: str,
+ headers: dict[str, str] | None,
+ seed_responses: list[tuple[str, httpx.Response]],
+ base_path: str | None,
+ ) -> ShowRuntimeResult:
+ pending: list[tuple[str, int]] = [(f"{runtime_path}src/main.tsx", 0)]
+ visited: set[str] = {path for path, _response in seed_responses}
+ for path, response in seed_responses:
+ pending.extend(
+ (import_path, 1)
+ for import_path in _show_runtime_prewarm_import_paths(
+ response,
+ session_id=session_id,
+ runtime_path=runtime_path,
+ base_path=base_path,
+ )
+ )
+
+ while pending and len(visited) < _PREWARM_MAX_ASSETS:
+ path, depth = pending.pop(0)
+ if path in visited or depth > _PREWARM_MAX_DEPTH:
+ continue
+ visited.add(path)
+ response = await self.request("GET", path, headers=headers)
+ if response.status_code >= 500:
+ return ShowRuntimeResult(False, reason=f"session_prewarm_module_failed:{response.status_code}:{path}")
+ if response.status_code >= 400:
+ continue
+ if depth >= _PREWARM_MAX_DEPTH:
+ continue
+ for import_path in _show_runtime_prewarm_import_paths(
+ response,
+ session_id=session_id,
+ runtime_path=runtime_path,
+ base_path=base_path,
+ ):
+ if import_path not in visited:
+ pending.append((import_path, depth + 1))
+ return ShowRuntimeResult(True, self._base_url)
+
async def websocket_url(self, path: str) -> str:
ready = await self.ensure()
if not ready.available or not ready.base_url:
@@ -969,6 +1022,85 @@ def set_show_runtime_manager_for_tests(manager: ShowRuntimeManager | None) -> No
_manager = manager
+def _show_runtime_prewarm_import_paths(
+ response: httpx.Response,
+ *,
+ session_id: str,
+ runtime_path: str,
+ base_path: str | None,
+) -> list[str]:
+ content_type = response.headers.get("content-type", "")
+ if "javascript" not in content_type and "html" not in content_type and "css" not in content_type:
+ return []
+ try:
+ text = response.text
+ except UnicodeDecodeError:
+ return []
+ paths: list[str] = []
+ seen: set[str] = set()
+ for match in _PREWARM_IMPORT_RE.finditer(text):
+ value = match.group("path")
+ path = _show_runtime_prewarm_runtime_path(
+ value,
+ session_id=session_id,
+ runtime_path=runtime_path,
+ base_path=base_path,
+ )
+ if path and path not in seen:
+ seen.add(path)
+ paths.append(path)
+ return paths
+
+
+def _show_runtime_prewarm_runtime_path(
+ value: str,
+ *,
+ session_id: str,
+ runtime_path: str,
+ base_path: str | None,
+) -> str | None:
+ if not value or value.startswith(("http://", "https://", "data:", "blob:", "#")):
+ return None
+ raw_path, separator, query = value.partition("?")
+ if not _show_runtime_prewarm_asset_path_allowed(raw_path):
+ return None
+ session_prefixes = [f"/show/{session_id}/", f"/p/{session_id}/"]
+ if base_path:
+ session_prefixes.insert(0, base_path.rstrip("/") + "/")
+ for prefix in session_prefixes:
+ if raw_path.startswith(prefix):
+ asset_path = raw_path[len(prefix):]
+ return _join_show_runtime_prewarm_path(runtime_path, asset_path, separator, query)
+ if raw_path.startswith("/_show-runtime/deps/"):
+ asset_path = raw_path.lstrip("/")
+ return _join_show_runtime_prewarm_path(runtime_path, asset_path, separator, query)
+ if raw_path.startswith("/src/") or raw_path.startswith("/@") or raw_path.startswith("/node_modules/"):
+ return _join_show_runtime_prewarm_path(runtime_path, raw_path.lstrip("/"), separator, query)
+ if raw_path.startswith("./"):
+ return _join_show_runtime_prewarm_path(runtime_path, raw_path[2:], separator, query)
+ if raw_path.startswith(("src/", "@", "node_modules/")):
+ return _join_show_runtime_prewarm_path(runtime_path, raw_path, separator, query)
+ return None
+
+
+def _show_runtime_prewarm_asset_path_allowed(path: str) -> bool:
+ if not path:
+ return False
+ if path.startswith(("/home/", "/Users/", "/tmp/", "/var/", "/private/")):
+ return False
+ return path.endswith((".js", ".mjs", ".ts", ".tsx", ".css")) or path in {
+ "/@vite/client",
+ "/@react-refresh",
+ }
+
+
+def _join_show_runtime_prewarm_path(runtime_path: str, asset_path: str, separator: str, query: str) -> str:
+ path = f"{runtime_path}{urllib.parse.quote(asset_path.lstrip('/'), safe='/@:-._~')}"
+ if separator:
+ path = f"{path}?{query}"
+ return path
+
+
def _auto_install_enabled() -> bool:
value = os.environ.get("VIBE_SHOW_RUNTIME_AUTO_INSTALL")
return value is None or value.strip().lower() not in _FALSE_VALUES
diff --git a/docker-compose.three-regression.yml b/docker-compose.three-regression.yml
deleted file mode 100644
index d8258da24..000000000
--- a/docker-compose.three-regression.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-services:
- vibe:
- image: vibe-remote-three-regression:latest
- build:
- context: .
- dockerfile: Dockerfile
- target: integration
- command: ["full"]
- environment:
- HOME: /home/avibe
- VIBE_REMOTE_HOME: ""
- VIBE_DEPLOYMENT_ENV: regression
- VIBE_INTERNAL_DISPATCH_SOCKET: /tmp/vibe_remote/dispatch.sock
- VIBE_UI_PORT: 5123
- VIBE_REMOTE_ALLOW_DOCKER_LOOPBACK_PEERS: "1"
- VIBE_REMOTE_DOCKER_LOOPBACK_BIND_HOST: "${THREE_REGRESSION_PORT_BIND_HOST:-127.0.0.1}"
- VIBE_REMOTE_DOCKER_LOOPBACK_PEER_IPS: "${THREE_REGRESSION_DOCKER_LOOPBACK_PEER_IPS:-}"
- VIBE_SHOW_RUNTIME_SOURCE: "${THREE_REGRESSION_SHOW_RUNTIME_SOURCE:-github-source}"
- VIBE_SHOW_RUNTIME_GITHUB_REPO: "${THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REPO:-https://github.com/avibe-bot/vibe-show-runtime.git}"
- VIBE_SHOW_RUNTIME_GITHUB_REF: "${THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REF:-main}"
- PYTHONUNBUFFERED: "1"
- ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
- ANTHROPIC_BASE_URL: ${ANTHROPIC_BASE_URL:-}
- ANTHROPIC_AUTH_TOKEN: ${THREE_REGRESSION_CLAUDE_AUTH_TOKEN:-}
- CLAUDE_CODE_ATTRIBUTION_HEADER: ${THREE_REGRESSION_CLAUDE_ATTRIBUTION_HEADER:-0}
- OPENAI_API_KEY: ${OPENAI_API_KEY:-}
- healthcheck:
- test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5123/health', timeout=3)"]
- interval: 3s
- timeout: 5s
- retries: 20
- start_period: 30s
- ports:
- - "${THREE_REGRESSION_PORT_BIND_HOST:-127.0.0.1}:${THREE_REGRESSION_PORT:-15130}:5123"
- volumes:
- - ${THREE_REGRESSION_STATE_ROOT:?set by scripts/run_three_regression.sh}/home:/home/avibe
diff --git a/docs/plans/agents-md-restructure.md b/docs/plans/agents-md-restructure.md
index 6535e6bb2..a84ede0ff 100644
--- a/docs/plans/agents-md-restructure.md
+++ b/docs/plans/agents-md-restructure.md
@@ -9,7 +9,7 @@
- reusable workflow rules and project-specific rules are split in ways that force agents to jump around,
- architecture, structure, and workflow guidance overlap,
- some operational guidance is outdated or underspecified,
-- and the distinction between local `vibe` and the Docker-based three-end regression environment is not explicit enough.
+- and the distinction between local `vibe` and the Incus regression environment is not explicit enough.
This causes avoidable mistakes, especially around environment selection, UI verification, and where changes should be made in a multi-platform codebase.
@@ -27,8 +27,8 @@ Rewrite `AGENTS.md` so it becomes a practical operating manual for coding agents
1. Reorganize the document around how agents actually make decisions: context → architecture → environments → workflow → coding/testing → safety.
2. Merge overlapping sections such as architecture and structure into a single codebase map.
-3. Add an explicit environment model that distinguishes local `vibe` from Docker three-end regression.
-4. Add a hard rule: do not restart the local `vibe` service for verification; use the regression Docker environment unless the user explicitly asks otherwise.
+3. Add an explicit environment model that distinguishes local `vibe` from Incus regression.
+4. Add a hard rule: do not restart the local `vibe` service for verification; use the Incus regression environment unless the user explicitly asks otherwise.
5. Update configuration and routing guidance so it reflects the current V2 config model rather than legacy assumptions.
6. Keep low-frequency release notes brief and move them to the end.
diff --git a/docs/plans/fastapi-migration.md b/docs/plans/fastapi-migration.md
index 9c4452f2d..c2c116ffe 100644
--- a/docs/plans/fastapi-migration.md
+++ b/docs/plans/fastapi-migration.md
@@ -295,7 +295,7 @@ Each phase ends with a green test run + a manual smoke. Commit between phases.
1. **Bootstrap.** Add fastapi/uvicorn/python-multipart/httpx to `pyproject.toml`. Create `vibe/ui_routers/` directory with empty `__init__.py`. Create the new `app = FastAPI(lifespan=lifespan)` in `vibe/ui_server.py` ALONGSIDE the existing Flask `app` (rename Flask app temporarily, e.g. `_legacy_flask_app`). Wire `run_ui_server` to dispatch to whichever app a `VIBE_UI_FRAMEWORK=fastapi` env var selects. Implement `/health` on FastAPI as the canary route.
2. **Middleware.** Port CSRF / remote_access auth / setup wizard gate / CSRF cookie / remote_access cookie hooks as FastAPI middleware. Carry the existing `tests/test_ui_remote_access_auth.py` through; it must stay green.
-3. **Static + Setup.** Port the SPA catch-all, `/setup/*`, `/auth/callback`, asset routes. The setup wizard is high-traffic; smoke through `./scripts/run_three_regression.sh` end-to-end after this phase.
+3. **Static + Setup.** Port the SPA catch-all, `/setup/*`, `/auth/callback`, asset routes. The setup wizard is high-traffic; smoke through `./scripts/run_regression.sh` end-to-end after this phase.
4. **Backends + agent CLI lifecycle.** Port `/backend/*`, `/agent/*`, `/cli/detect`. Drop `asyncio.run` from the corresponding `vibe/api.py` helpers as you go.
5. **Backend OAuth + per-provider.** Port `/backend/<b>/auth/oauth/*` and `/backend/opencode/provider/*`. Delete `vibe-oauth-loop` thread; `_submit_oauth_coro` callers become `await`. This phase **fixes the cross-loop bug at the root**.
6. **IM platform credentials.** Slack / Discord / Telegram / Feishu / WeChat routes. WeChat QR login long-poll is a candidate for `StreamingResponse` (or stays as poll — keep behavior identical).
@@ -314,7 +314,7 @@ Codex review after each phase keeps the surface area manageable.
- [x] `asyncio.run` does not appear in `vibe/api.py`.
- [x] A trivial WebSocket echo route proves the ASGI substrate end-to-end.
- [ ] All 74 existing routes return identical responses for golden inputs. UI in `ui/` is byte-identical and works against the new server.
-- [ ] `./scripts/run_three_regression.sh` brings up a healthy container; `/health` returns ok; the React UI loads; setup wizard works; OpenCode provider OAuth flow works without cross-loop errors.
+- [ ] `./scripts/run_regression.sh` brings up a healthy container; `/health` returns ok; the React UI loads; setup wizard works; OpenCode provider OAuth flow works without cross-loop errors.
- [ ] `pytest tests/` passes.
- [ ] `vibe restart && vibe status` works locally.
- [x] Repo guidance is updated to mention FastAPI / uvicorn and prefer native FastAPI patterns for new UI routes.
diff --git a/docs/plans/incus-regression-migration.md b/docs/plans/incus-regression-migration.md
new file mode 100644
index 000000000..25d8836ff
--- /dev/null
+++ b/docs/plans/incus-regression-migration.md
@@ -0,0 +1,395 @@
+# Incus regression migration
+
+## Background
+
+The current regression workflow is Docker-based. It rebuilds an
+application image and force-recreates the regression container for normal code
+updates. That shape is useful for reproducible application-container testing,
+but it is a poor fit for Avibe's product reality:
+
+- Avibe behaves like a long-running local OS service, not a single application
+ process.
+- Regression state is valuable and should survive code updates.
+- Worktree testing should be cheap enough to use during normal PR work.
+- Full image rebuilds make routine regression updates slow and make Show Runtime
+ cold-start issues harder to separate from container rebuild churn.
+
+Incus is a better runtime model for this because it manages full Linux system
+containers and VMs. A system container gives us a real init/systemd environment,
+a real home directory, long-lived state, service restarts, and lower overhead
+than rebuilding Docker application images for every code change.
+
+This migration should replace the Docker regression runner with an
+Incus-backed regression runner. The existing `scripts/incus_tenant.py` tenant
+scaffold is useful prior art, but regression needs a different lifecycle model:
+one persistent master environment plus temporary worktree environments.
+
+## Goals
+
+1. Run manual regression in Incus instead of Docker.
+2. Keep the `master` regression environment long-lived.
+3. Allow any git worktree to create an isolated temporary regression
+ environment.
+4. Update code by syncing source into the instance and restarting Avibe, not by
+ rebuilding an image.
+5. Keep regression state, agent CLI homes, remote access pairing, sessions, and
+ Show Page workspaces stable for the persistent master environment.
+6. Prepare and verify Show Runtime as part of every successful regression
+ update.
+7. Make cleanup deterministic for temporary worktree environments.
+8. Remove Docker regression artifacts after the Incus runner owns the workflow.
+
+## Non-goals
+
+- Do not redesign the product's tenant hosting model in this migration.
+- Do not require every developer machine to run an Incus daemon locally. On
+ macOS, the local machine can be an Incus client, but the daemon should run on a
+ Linux host or Linux VM.
+- Do not turn regression environments into untrusted multi-tenant production
+ isolation. Use resource limits and restricted projects, but treat this as
+ developer/operator regression infrastructure.
+- Do not reset existing regression config/state unless explicitly requested.
+
+## Runtime model
+
+### Host
+
+Use a Linux Incus host as the regression runtime. For this workstation, macOS is
+only the operator/client environment. The runner should support:
+
+- local Linux host with `incus` available,
+- remote Incus daemon configured through the standard Incus CLI remote,
+- dry-run planning when Incus is unavailable.
+
+The runner should fail early with a clear message if no usable Incus CLI/remote
+is configured.
+
+### Base image
+
+Create one reusable Avibe regression base image that contains slow-changing
+dependencies, not Avibe source code:
+
+- Ubuntu base image,
+- Python, `uv`, build essentials, git,
+- Node.js and npm,
+- agent CLIs: Claude Code, Codex, OpenCode,
+- systemd service template and helper scripts,
+- optional browser/runtime packages needed by Show Runtime.
+
+The image should be rebuilt only when base dependencies change. Normal Avibe
+code updates must not rebuild this image.
+
+Proposed image alias:
+
+- `avibe-regression-base-<date-or-dependency-hash>`
+- `avibe-regression-base-current`
+
+### Instance layout
+
+Inside every regression instance:
+
+- service user: `avibe`
+- source checkout: `/opt/avibe/source`
+- app venv: `/opt/avibe/venv`
+- UI dist: `/opt/avibe/source/ui/dist`
+- Avibe home: `/home/avibe/.avibe`
+- compatibility home: `/home/avibe/.vibe_remote -> /home/avibe/.avibe`
+- operator metadata: `/var/lib/avibe-regression/metadata.json`
+
+The Avibe service should run through systemd:
+
+- service name: `avibe-regression.service`
+- environment: `VIBE_DEPLOYMENT_ENV=regression`
+- environment: `HOME=/home/avibe`
+- environment: `VIBE_REMOTE_HOME=` so default-home behavior is exercised
+- UI bind: `0.0.0.0:5123`
+
+## Environment types
+
+### Persistent master environment
+
+The master regression environment is long-lived:
+
+- project: `avr-master`
+- instance: `avibe-master`
+- host port: default `15130`
+- state: persistent under the instance root disk and optional named volume
+- lifecycle: create once, then update source and restart service
+
+Normal update flow:
+
+1. Ensure local `master` is current.
+2. Sync source into `/opt/avibe/source`.
+3. Build UI if UI inputs changed or `--build-ui` is requested.
+4. Refresh editable Python install if dependency metadata changed.
+5. Restart `avibe-regression.service`.
+6. Run health checks.
+7. Run `vibe runtime prepare --strict`.
+8. Verify Show Runtime status.
+9. Print the public/local URL and routing summary.
+
+This environment preserves:
+
+- platform credentials,
+- remote access pairing,
+- agent CLI homes,
+- Harness/session state,
+- Show Page workspaces,
+- Show Runtime cache where safe.
+
+### Temporary worktree environments
+
+Temporary environments are tied to a worktree identity:
+
+- project: `avr-wt-<slug>`
+- instance: `avibe-wt-<slug>`
+- host port: allocated from a regression port range, for example `15200-15399`
+- state: isolated per worktree
+- lifecycle: create/update/delete with the worktree
+
+The slug should be deterministic and collision-resistant:
+
+- prefer branch name when valid,
+- include a short hash of the absolute worktree path,
+- store the mapping in `.runtime/incus-regression/worktrees.json`.
+
+Temporary environments should support:
+
+- `up`: create or update from the current worktree,
+- `status`: show instance, branch, commit, URL, health,
+- `logs`: follow Avibe service logs,
+- `shell`: enter the instance as the `avibe` user,
+- `down`: stop the instance,
+- `delete`: delete project, instance, and all temporary state.
+
+By default, deleting a git worktree should not automatically delete Incus state
+behind the user's back. Instead, provide a cleanup command that detects missing
+worktree paths and offers deletion with `--yes`.
+
+## CLI design
+
+Add a new runner:
+
+```bash
+python3 scripts/incus_regression.py doctor
+python3 scripts/incus_regression.py init-host
+python3 scripts/incus_regression.py build-base
+python3 scripts/incus_regression.py up --target master
+python3 scripts/incus_regression.py up --target worktree
+python3 scripts/incus_regression.py status --target master
+python3 scripts/incus_regression.py logs --target master
+python3 scripts/incus_regression.py shell --target worktree
+python3 scripts/incus_regression.py down --target worktree
+python3 scripts/incus_regression.py delete --target worktree --yes
+python3 scripts/incus_regression.py cleanup-stale --yes
+```
+
+Keep the existing entry point as a thin Incus wrapper:
+
+```bash
+./scripts/run_regression.sh
+```
+
+The wrapper should not contain Docker fallback logic. Docker-specific flags
+should fail as unknown arguments.
+
+## Source sync strategy
+
+Use a host-side sync step rather than git clone inside the instance.
+
+Requirements:
+
+- sync the exact current worktree, including uncommitted files when requested,
+- exclude `.git`, `.runtime`, `node_modules`, caches, and generated state,
+- preserve `ui/dist` policy explicitly,
+- write sync metadata with branch, commit, dirty state, source path, and time.
+
+Implementation options:
+
+1. Preferred: `rsync` to `/opt/avibe/source`.
+2. Fallback: tar stream through `incus exec`.
+
+Default behavior:
+
+- include committed and uncommitted source files because manual regression often
+ happens before committing,
+- mark metadata as dirty when the local worktree is dirty,
+- allow `--clean` to remove files in the instance that no longer exist locally.
+
+## Dependency update strategy
+
+Do not reinstall everything on every update. Track fingerprints:
+
+- Python dependencies: `pyproject.toml`, `uv.lock`,
+- UI dependencies: `ui/package.json`, `ui/package-lock.json`,
+- base image dependencies: runner-owned base image manifest,
+- Show Runtime source provider/ref.
+
+Actions:
+
+- If Python metadata changed, run `uv pip install -e /opt/avibe/source` in the
+ persistent venv.
+- If UI dependency metadata changed, run `npm ci` in `/opt/avibe/source/ui`.
+- If UI source changed, run `npm run build`.
+- If only Python source changed, skip UI and dependency install.
+- If only docs/tests changed, allow `--restart=false`.
+- Always run Show Runtime prepare after a service update unless explicitly
+ skipped for debugging.
+
+## State preparation
+
+Reuse the existing `prepare_regression.py` logic, but decouple it from
+Docker paths.
+
+Needed changes:
+
+- allow target home path `/home/avibe/.avibe`,
+- allow host state generation for master and worktree targets,
+- keep reset modes: `none`, `config`, `all`,
+- preserve current env-file behavior,
+- keep platform routing preseed behavior,
+- keep agent home import/export behavior for master where relevant.
+
+For master, preparation should only seed missing config by default.
+
+For temporary worktrees, preparation can create a fresh isolated state unless
+`--state-root` is provided.
+
+## Networking
+
+Expose the Web UI through an Incus proxy device:
+
+- master: `127.0.0.1:15130 -> instance 127.0.0.1:5123`,
+- worktrees: allocated host port -> instance `127.0.0.1:5123`.
+
+Keep remote access behavior intact. If Avibe Cloud is paired in the master
+environment, do not overwrite that config during updates.
+
+## Show Runtime handling
+
+Every successful `up` should verify Show Runtime:
+
+```bash
+vibe runtime prepare --strict
+vibe runtime status --json
+```
+
+The runner should fail the update if:
+
+- runtime command is missing,
+- runtime provider install fails,
+- installed runtime does not match requested provider/ref,
+- a smoke endpoint cannot load a basic public Show Page asset.
+
+For worktree environments, support overriding:
+
+- `REGRESSION_SHOW_RUNTIME_SOURCE`
+- `REGRESSION_SHOW_RUNTIME_GITHUB_REPO`
+- `REGRESSION_SHOW_RUNTIME_GITHUB_REF`
+
+## Migration phases
+
+### Phase 0: Design lock
+
+- Land this plan.
+- Confirm Linux Incus host choice for regression.
+- Recreate master state from `.env.regression`; old Docker regression
+ state roots are not part of the Incus cutover.
+
+### Phase 1: Incus runner scaffold
+
+- Add `scripts/incus_regression.py`.
+- Add doctor/status/dry-run tests.
+- Reuse naming and project helpers from `incus_tenant.py` where possible.
+- Add docs for host setup and command usage.
+
+### Phase 2: Base image and service bootstrap
+
+- Add base image build command.
+- Add cloud-init or provisioning script for `avibe` user, venv, Node, agent
+ CLIs, systemd unit, and helper commands.
+- Add tests for rendered provisioning config.
+
+### Phase 3: Persistent master environment
+
+- Implement `up/status/logs/shell` for `--target master`.
+- Implement source sync, dependency fingerprints, UI build, service restart,
+ health check, and Show Runtime prepare.
+- Validate on the real regression host.
+
+### Phase 4: Temporary worktree environments
+
+- Implement deterministic worktree slugging.
+- Implement port allocation and mapping file.
+- Implement create/update/delete/cleanup-stale.
+- Validate two concurrent worktree environments can run without sharing state.
+
+### Phase 5: Replace Docker path
+
+- Change `run_regression.sh` to call the Incus runner.
+- Update `AGENTS.md` and `docs/regression/README.md`.
+- Remove Docker fallback from the wrapper.
+
+### Phase 6: Remove Docker regression artifacts
+
+- Remove `docker-compose.regression.yml`.
+- Remove Docker-only tests or rewrite them for Incus.
+- Update all developer docs and examples.
+
+## Validation
+
+Focused automated checks:
+
+- runner CLI parsing,
+- project/instance naming,
+- port allocation,
+- dry-run command rendering,
+- source sync exclude list,
+- dependency fingerprint decisions,
+- reset-mode state preparation,
+- Show Runtime status parsing.
+
+Manual/live checks:
+
+- master update from clean `master`,
+- master update from dirty local source,
+- temporary worktree creation/update/delete,
+- two worktree instances at once,
+- preserved master remote access pairing,
+- Slack/Discord/Feishu/WeChat routing still present,
+- public Show Page loads without private runtime paths,
+- Show Runtime cold and warm starts can be measured separately from service
+ update time.
+
+## Risks and mitigations
+
+- **Mac host mismatch**: Incus system containers require a Linux host. Mitigate
+ by treating macOS as a client and making the runner support remote Incus.
+- **State migration mistakes**: master state is valuable. Mitigate with an
+ explicit snapshot/export command before first Incus cutover.
+- **Source sync drift**: stale files can survive in the instance. Mitigate with
+ default clean sync after the first implementation is stable.
+- **Dependency fingerprint bugs**: skipped installs can cause confusing runtime
+ failures. Mitigate by recording fingerprints and exposing `--force-deps`.
+- **Port collisions**: worktree ports must be deterministic but conflict-free.
+ Mitigate with a lock file and live socket/Incus device checks.
+- **Security boundary overconfidence**: system containers share the host kernel.
+ Mitigate with restricted projects, resource limits, and VM mode for stronger
+ isolation if needed.
+
+## Open decisions
+
+1. Which Linux host should own the long-running master regression instance?
+2. Should temporary worktree environments include real IM credentials by
+ default, or start with Web/UI-only validation unless explicitly enabled?
+3. Should base image rebuilds happen manually, or via a separate CI-published
+ Incus image artifact?
+
+## Recommendation
+
+Proceed with the Incus migration, but do it as a runtime-model replacement, not
+a direct Docker command translation. The key architectural move is to make the
+base environment long-lived and dependency-prepared, while source code becomes a
+cheap synced input. That gives Avibe a regression setup that behaves much closer
+to a real installed machine and supports both persistent master verification and
+isolated worktree verification.
diff --git a/docs/plans/three-end-regression.md b/docs/plans/legacy-regression-plan.md
similarity index 63%
rename from docs/plans/three-end-regression.md
rename to docs/plans/legacy-regression-plan.md
index 3097a9084..c511fea45 100644
--- a/docs/plans/three-end-regression.md
+++ b/docs/plans/legacy-regression-plan.md
@@ -1,14 +1,14 @@
-# Three-End Regression Plan
+# Legacy Regression Plan
-> Status: Completed
+> Status: Superseded by the Incus regression runner.
## Background
-The repository already has automated Docker-based E2E coverage for API and platform-driver flows, but full product validation still requires a human to trigger real workflows from Slack, Discord, and Feishu. We need a repeatable way to bring up three isolated test environments in parallel without replacing the existing automated E2E suite.
+The repository already has automated Docker-based E2E coverage for API and platform-driver flows, but full product validation still requires a human to trigger real workflows from Slack, Discord, and Feishu. This historical plan captured the old Docker Compose regression workflow. Manual regression now uses the Incus runner documented in `docs/regression/README.md`.
## Goal
-Add a named workflow called `三端回归测试` that:
+Add a named workflow for the old multi-platform regression environment that:
- builds the latest branch code into Docker images,
- starts three independent containers for Slack, Discord, and Feishu,
@@ -17,19 +17,24 @@ Add a named workflow called `三端回归测试` that:
- keeps local secrets out of git,
- and preserves the current automated E2E entrypoints.
-## Solution
+## Historical Solution
1. Add a dedicated three-service Docker Compose file for Slack / Discord / Feishu regression environments.
2. Add a local-only env template for secrets and per-service mappings (ports, tokens, channels, backend routing).
-3. Add a preparation script that materializes per-service `config.json` and `settings.json` into generated `_tmp/three-regression/` state directories before the containers start.
+3. Add a preparation script that materializes per-service `config.json` and `settings.json` into generated local state directories before the containers start.
4. Add a one-command runner script that loads the local env file, rebuilds the services, recreates the containers, waits for health, and prints the three local URLs plus platform/channel/backend mapping.
-5. Document the difference between `E2E 测试` and `三端回归测试` in a dedicated docs folder.
+5. Document the difference between `E2E 测试` and manual product regression in a dedicated docs folder.
## Todo
- [x] Add local-secret-safe env template and ignore rules.
-- [x] Add generated-config bootstrap for the three regression services.
+- [x] Add generated-config bootstrap for the old platform-specific regression services.
- [x] Add three-service Docker Compose orchestration with separate ports and volumes.
- [x] Add a runner script for build/up/down/status/log workflows.
- [x] Add docs that explain setup, usage, and the difference from automated E2E.
- [x] Validate the new workflow with targeted checks.
+
+## Current Replacement
+
+Use `./scripts/run_regression.sh` or `python3 scripts/incus_regression.py`.
+The Docker Compose regression artifacts from this plan have been removed.
diff --git a/docs/plans/rebrand-avibe.md b/docs/plans/rebrand-avibe.md
index ca0c3357c..8b1cfe24c 100644
--- a/docs/plans/rebrand-avibe.md
+++ b/docs/plans/rebrand-avibe.md
@@ -337,7 +337,7 @@ runtime compatibility surfaces.
models. Keep it or add an alias path; do not bulk-rename and orphan existing
OpenCode configs.
- Regression/container data paths such as `/data/vibe_remote` and existing
- three-regression state roots must be preserved unless an isolated migration is
+ regression state roots must be preserved unless an isolated migration is
explicitly tested. Do not reset regression state.
- `use-avibe` skill name, raw URL, and tests need compatibility handling.
Update public prose/URLs, but keep an alias or old lookup path until callers
diff --git a/docs/plans/telegram-im.md b/docs/plans/telegram-im.md
index 2337e5686..6869939f7 100644
--- a/docs/plans/telegram-im.md
+++ b/docs/plans/telegram-im.md
@@ -414,13 +414,13 @@ Minimum cases:
### Regression environment
-Do not try to fold Telegram into the existing Docker three-regression flow immediately.
+Do not try to fold Telegram into the existing Incus regression flow immediately.
Recommended rollout:
1. ship adapter + unit coverage first
2. add manual Telegram smoke validation
-3. then design whether the unified regression container should evolve into a four-platform container
+3. then design whether the unified regression environment should evolve into a four-platform environment
## Implementation Phases
diff --git a/docs/plans/three-regression-followup-fixes.md b/docs/plans/three-regression-followup-fixes.md
deleted file mode 100644
index 06bf77ae0..000000000
--- a/docs/plans/three-regression-followup-fixes.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# Three Regression Follow-up Fixes
-
-> Status: In Progress
-
-## Background
-
-The three-end regression workflow is running, but two UX issues remain:
-
-1. The Discord container is configured for Codex, yet some Web UI surfaces still show OpenCode, creating inconsistent routing feedback.
-2. The Web UI health/status polling appears overly chatty, and likely uses multiple endpoints more often than needed.
-
-## Goal
-
-Make backend display consistent across the Web UI and reduce polling overhead by simplifying the runtime status checks.
-
-## Solution
-
-1. Trace the backend shown in dashboard/pages to determine whether it is reading global defaults, stale local state, or per-channel routing.
-2. Fix the UI/API contract so the effective backend shown for the current platform reflects the actual runtime routing the service will use.
-3. Inspect the status polling implementation, collapse redundant endpoint polling where possible, and reduce the polling interval without breaking responsiveness.
-4. Validate in the running three-end regression environment and cover the behavior with tests where practical.
-
-## Todo
-
-- [ ] Find the source of the incorrect OpenCode display in the Discord Web UI.
-- [ ] Fix effective backend display so it matches the actual Discord runtime backend.
-- [ ] Simplify and reduce status polling.
-- [ ] Validate via tests/build and live container checks.
diff --git a/docs/regression/README.md b/docs/regression/README.md
index 9b25fca26..c3ffc2a85 100644
--- a/docs/regression/README.md
+++ b/docs/regression/README.md
@@ -1,20 +1,25 @@
# Regression Testing
-`回归测试` is the manual regression workflow for this repository. It starts a single unified container with all four IM platforms (Slack, Discord, Feishu, WeChat) running simultaneously, each with per-channel backend routing pre-configured.
+`回归测试` is the manual regression workflow for this repository. It runs Avibe
+inside Incus so the environment behaves like a real long-running Linux machine:
+systemd service, real home directory, persistent state, source sync, service
+restart, and Show Runtime preparation.
-The container state is persistent by default. Changes you make through the UI or inside the running service, such as channel routing and other saved settings, stay under `.runtime/three-regression/` in the primary checkout across normal restarts.
-
-It complements the existing automated `E2E` flow instead of replacing it:
+It complements automated `E2E` tests instead of replacing them:
- `E2E testing` keeps using scripts and pytest for automatable scenarios.
-- capability scenario metadata now lives under `tests/scenarios/`
-- multi-step auth/setup journeys should add or update `tests/scenarios/auth_setup/catalog.yaml` and `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`
-- `docs/regression/` is now a human-facing entry layer, not the canonical source of truth for scenario metadata
+- capability scenario metadata lives under `tests/scenarios/`
+- multi-step auth/setup journeys should add or update
+ `tests/scenarios/auth_setup/catalog.yaml` and
+ `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`
+- `docs/regression/` is a human-facing entry layer, not the canonical source of
+ truth for scenario metadata
- `Regression testing` is for human-triggered checks on real IM platforms.
## Scenario Metadata Navigation
-Start here only if you are doing manual regression or need the human-readable index.
+Start here only if you are doing manual regression or need the human-readable
+index.
For deterministic scenario metadata, read:
@@ -23,122 +28,179 @@ For deterministic scenario metadata, read:
3. `tests/scenarios/<capability>/observations.yaml`
4. `tests/scenarios/<capability>/test_*.py`
+## Runtime Model
+
+The regression runner manages two Incus environment types:
+
+- `master`: a long-running persistent regression environment.
+- `worktree`: a temporary isolated environment for the current git worktree.
+
+The master environment keeps product state across normal updates:
+
+- platform credentials,
+- Avibe Cloud remote-access pairing,
+- agent CLI homes,
+- Harness/session state,
+- Show Page workspaces,
+- Show Runtime cache where safe.
+
+Worktree environments get their own Incus project/instance and host port. Their
+mapping is recorded under `.runtime/incus-regression/worktrees.json` in the
+primary checkout.
+
+On macOS, run the Incus daemon in a local Linux VM and use the local machine as
+the operator/client. A separately configured Incus remote is supported, but the
+default regression setup should stay local to the workstation.
+
## Setup
-1. Copy the local template:
+1. Configure an Incus host or remote.
+
+ ```bash
+ python3 scripts/incus_regression.py doctor
+ ```
+
+ If you are initializing a fresh Linux host directly:
+
+ ```bash
+ python3 scripts/incus_regression.py init-host --minimal
+ ```
+
+2. Build or provide the reusable base image.
```bash
- cp .env.three-regression.example .env.three-regression
+ python3 scripts/incus_regression.py build-base
```
-2. Fill in `.env.three-regression` with:
+ The base image contains slow-changing dependencies such as Python, Node,
+ build tools, and agent CLIs. Normal code updates do not rebuild this image.
+
+3. Copy the local env template:
+
+ ```bash
+ cp .env.regression.example .env.regression
+ ```
+
+4. Fill in `.env.regression` with:
- shared LLM credentials: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`
- optional API base URLs: `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`, `OPENAI_API_BASE`
-- optional UI host override: `THREE_REGRESSION_UI_HOST` (useful when exposing the UI on a LAN host)
+- optional UI proxy bind host: `REGRESSION_PORT_BIND_HOST`
- platform-specific bot credentials for Slack, Discord, Feishu, and WeChat
-- the target regression channel for each platform, if you want channel routing preseeded at startup
+- the target regression channel for each platform, if you want channel routing
+ preseeded at startup
- the backend that each platform's channel should pin to by default
-Channel IDs are optional. If you leave them empty, the container still starts and you can configure channels later from the Web UI.
+Channel IDs are optional. If you leave them empty, the environment still starts
+and you can configure channels later from the Web UI.
-3. Keep these local-only files out of git:
+5. Keep these local-only files out of git:
-- `.env.three-regression`
-- `.runtime/three-regression/`
+- `.env.regression`
+- `.runtime/incus-regression/`
## Usage
-The default command rebuilds the image, preserves your current regression state, and recreates the container:
+The compatibility entry point now uses Incus by default:
```bash
-./scripts/run_three_regression.sh
+./scripts/run_regression.sh
```
-Common commands:
+Direct runner commands:
```bash
-./scripts/run_three_regression.sh --no-build
-./scripts/run_three_regression.sh --reset-config
-./scripts/run_three_regression.sh --reset-all
-./scripts/run_three_regression.sh --status
-./scripts/run_three_regression.sh --logs
-./scripts/run_three_regression.sh --down
+python3 scripts/incus_regression.py up --target master
+python3 scripts/incus_regression.py status --target master
+python3 scripts/incus_regression.py logs --target master
+python3 scripts/incus_regression.py shell --target master
+python3 scripts/incus_regression.py down --target master
```
-If you run the script over SSH on macOS and `docker` is not in the non-interactive `PATH`, the script now auto-detects common Docker CLI locations such as `/usr/local/bin/docker` and `/opt/homebrew/bin/docker`. You can also override it explicitly:
+Temporary worktree environment:
```bash
-DOCKER_BIN=/usr/local/bin/docker ./scripts/run_three_regression.sh
+python3 scripts/incus_regression.py up --target worktree
+python3 scripts/incus_regression.py status --target worktree
+python3 scripts/incus_regression.py delete --target worktree --yes
+python3 scripts/incus_regression.py cleanup-stale --yes
```
-Reset modes:
+Useful flags:
+
+- `--remote <name>`: use an Incus remote configured in the Incus CLI.
+- `--host-port <port>`: set the host-side Web UI proxy port.
+- `--slug <slug>`: set the worktree environment slug.
+- `--reset-mode config`: re-seed config/state/runtime.
+- `--reset-mode all`: wipe and re-seed the environment state.
+- `--clean`: compatibility flag; normal syncs already remove stale source files.
+- `--force-deps`: force Python dependency refresh.
+- `--no-build-ui`: skip UI asset build.
+- `--dry-run`: print the planned Incus commands without changing the host.
-- `--reset-config`: re-seed `config/`, `state/`, and `runtime/` from `.env.three-regression`, while preserving `workdir/`, `attachments/`, and `logs/`
-- `--reset-all`: wipe the full state directory, including `workdir/`, then re-seed from `.env.three-regression`
+The wrapper maps common legacy flags:
-`--reset-state` remains available as a backward-compatible alias for `--reset-all`.
+```bash
+./scripts/run_regression.sh --status
+./scripts/run_regression.sh --logs
+./scripts/run_regression.sh --worktree
+./scripts/run_regression.sh --reset-config
+./scripts/run_regression.sh --dry-run
+```
## What You Get
-On success, the script prints one local UI URL together with the configured per-platform channel/backend mapping:
+On success, the runner prints one local UI URL:
```text
-Unified regression environment is ready:
+Incus regression environment is ready:
URL: http://127.0.0.1:15130
- Default backend: opencode
-
- Platform routing:
- - Slack: channel=C123SLACK backend=opencode
- - Discord: channel=1234567890 backend=codex
- - Feishu: channel=oc_xxx backend=claude
- - WeChat: channel=(QR login) backend=opencode
+ Target: master
+ Project: avr-master
+ Instance: avibe-master
+ Show Runtime source: github-source
```
-If you set `THREE_REGRESSION_UI_HOST=192.168.2.3`, the printed URL and generated UI config will use that host instead.
-
-On first startup, or when you run with `--reset-config` / `--reset-all`, the runner seeds these files under `.runtime/three-regression/home/.avibe/` in the primary checkout:
-
-- `config/config.json`
-- `state/settings.json`
-- `state/sessions.json`
-
-The generated state lives under `.runtime/three-regression/`, which keeps the regression environment isolated while preserving your later modifications by default. Task worktrees share this primary-checkout state root unless `THREE_REGRESSION_STATE_ROOT` is explicitly set for an isolated run.
+Default names:
-The container uses a real persistent home directory mounted at `/home/avibe`.
-That means Avibe's default-home behavior is exercised in regression:
-`/home/avibe/.avibe` is the active runtime home, and a legacy
-`/home/avibe/.vibe_remote` path is left as the product-managed compatibility
-symlink after product startup. The runner now treats `home/.avibe/` as the
-normal 3.0 state and does not import older harness layouts automatically.
-
-Persistence rules:
-
-- `./scripts/run_three_regression.sh` preserves UI changes, sessions, and files under `home/.avibe/workdir/`
-- `--reset-config` preserves `workdir/` files but resets service config/state
-- `--reset-all` clears everything under the regression home
+- master project: `avr-master`
+- master instance: `avibe-master`
+- master URL: `http://127.0.0.1:15130`
+- worktree project: `avr-wt-<slug>`
+- worktree instance: `avibe-wt-<slug>`
+- worktree ports: allocated from `15200-15399` unless overridden
## Architecture
-The unified container leverages the multi-platform IM support to run all four platforms in one process:
+The Incus runner separates slow-changing dependencies from fast-changing source:
+
+- **Base image**: Ubuntu plus Python, Node, build tools, systemd unit helpers,
+ and agent CLI prerequisites.
+- **Source sync**: current worktree source is streamed into
+ `/opt/avibe/source`, excluding `.git`, `.runtime`, dependency directories, and
+ generated assets.
+- **Service**: Avibe runs under `avibe-regression.service` as user `avibe`.
+- **Home**: `/home/avibe/.avibe` is the active product state home;
+ `/home/avibe/.vibe_remote` is a compatibility symlink.
+- **Show Runtime**: every successful update runs `vibe runtime prepare --strict`
+ and then verifies `vibe runtime status --json`.
-- **Config**: A single `config.json` with `platforms.enabled: ["slack", "discord", "lark", "wechat"]` and all four platform credential blocks populated.
-- **Routing**: Per-channel backend routing via `settings.json` scoped by platform, so each platform's test channel resolves to its designated backend.
-- **Agents**: All three backend agents (OpenCode, Claude, Codex) are enabled and installed in the container image.
-- **State**: A single `.runtime/three-regression/home/.avibe/` directory holds config, state, logs, and the agent workdir.
-- **Agent home configs**: Generated under `.runtime/three-regression/home/` and mounted as the container's real `$HOME`.
+The runner fingerprints dependency inputs:
-## Configuration Rules
+- Python dependencies: `pyproject.toml`, `uv.lock`
+- UI dependencies: `ui/package.json`, `ui/package-lock.json`
+- UI source: `ui/src`, `ui/public`, `ui/index.html`, Vite config, and TypeScript config
+- Show Runtime provider/ref
-- All four IM platforms (Slack, Discord, Feishu, WeChat) run in a single container process.
-- The `platforms.primary` is set to `slack` by default (controls fallback behavior).
-- `THREE_REGRESSION_DEFAULT_BACKEND` sets the global default backend (default: `opencode`).
-- Per-platform backend vars (`THREE_REGRESSION_SLACK_BACKEND`, etc.) control per-channel routing in `settings.json`.
-- All three agent CLIs receive shared credentials via `.runtime/three-regression/home/`.
-- The default working directory is `/home/avibe/.avibe/workdir`, a writable sandbox under the generated state.
+If fingerprints are unchanged, the runner skips unnecessary Python dependency
+installation. Source syncs replace the source tree, so UI dependencies and UI
+assets are rebuilt for each update to avoid serving stale or missing `ui/dist`
+content.
## Secret Safety
-- Never commit `.env.three-regression`.
-- Never commit generated files under `.runtime/three-regression/`.
-- Share `.env.three-regression.example` if you only need to show the structure.
+- Never commit `.env.regression`.
+- Never commit generated files under `.runtime/`.
+- Runtime secrets are written into the Incus instance through stdin to
+ `/etc/avibe-regression.env`; they should not appear in command-line logs.
+- Share `.env.regression.example` if you only need to show the structure.
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 4cf891c8e..66a601200 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -26,6 +26,17 @@ from .session import OpenCodeResumeUnavailableError, OpenCodeSessionManager
logger = logging.getLogger(__name__)
+def resolve_opencode_model_dict(model_str: str | None, default_provider: str | None) -> dict[str, str] | None:
+ if not model_str:
+ return None
+ parts = model_str.split("/", 1)
+ if len(parts) == 2:
+ return {"providerID": parts[0], "modelID": parts[1]}
+ if isinstance(default_provider, str) and default_provider.strip():
+ return {"providerID": default_provider.strip(), "modelID": model_str}
+ return None
+
+
class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"""OpenCode Server API integration via HTTP."""
@@ -248,26 +259,21 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
model_str = override_model
if not model_str:
model_str = server.get_agent_model_from_config(agent_to_use)
- if model_str:
- parts = model_str.split("/", 1)
- if len(parts) == 2:
- model_dict = {"providerID": parts[0], "modelID": parts[1]}
- else:
- # Bare model id (no ``provider/`` prefix): only inject
- # ``providerID`` when the user has explicitly chosen a
- # default provider in Settings → Backends → OpenCode.
- # Otherwise leave ``model_dict`` unset so OpenCode keeps
- # using its own routing — silently forcing every legacy
- # install onto Anthropic on upgrade breaks Ollama/OpenAI
- # users who never visited the new settings page.
- opencode_cfg = getattr(self.controller.config, "opencode", None)
- default_provider = getattr(opencode_cfg, "default_provider", None)
- if isinstance(default_provider, str) and default_provider.strip():
- model_dict = {"providerID": default_provider.strip(), "modelID": model_str}
+ opencode_cfg = getattr(self.controller.config, "opencode", None)
+ if not model_str:
+ model_str = getattr(opencode_cfg, "default_model", None)
+ # Bare model id (no ``provider/`` prefix): only inject ``providerID``
+ # when the user has explicitly chosen a default provider in Settings.
+ # Otherwise leave ``model_dict`` unset so OpenCode keeps using its own
+ # routing for legacy installs.
+ default_provider = getattr(opencode_cfg, "default_provider", None)
+ model_dict = resolve_opencode_model_dict(model_str, default_provider)
reasoning_effort = override_reasoning
if not reasoning_effort:
reasoning_effort = server.get_agent_reasoning_effort_from_config(agent_to_use)
+ if not reasoning_effort:
+ reasoning_effort = getattr(opencode_cfg, "default_reasoning_effort", None)
baseline_message_ids: set[str] = set()
try:
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
new file mode 100644
index 000000000..887ede044
--- /dev/null
+++ b/scripts/incus_regression.py
@@ -0,0 +1,1471 @@
+#!/usr/bin/env python3
+"""Manage Incus-backed Avibe regression environments.
+
+The runner uses Incus as a long-lived system environment, not as a Docker-like
+image rebuild wrapper. Slow-moving dependencies live in a reusable base image;
+Avibe source is synced into the instance and the service is restarted.
+"""
+
+from __future__ import annotations
+
+import argparse
+import errno
+import hashlib
+import json
+import os
+import re
+import shlex
+import shutil
+import socket
+import subprocess
+import sys
+import tarfile
+import tempfile
+import textwrap
+from contextlib import contextmanager
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Sequence
+
+try:
+ import fcntl
+except ImportError: # pragma: no cover - Incus runner is not used on Windows.
+ fcntl = None
+
+
+PROJECT_PREFIX = "avr-"
+WORKTREE_PROJECT_PREFIX = "avr-wt-"
+INSTANCE_PREFIX = "avibe-"
+WORKTREE_INSTANCE_PREFIX = "avibe-wt-"
+MASTER_TARGET = "master"
+WORKTREE_TARGET = "worktree"
+TARGETS = {MASTER_TARGET, WORKTREE_TARGET}
+SERVICE_USER = "avibe"
+SERVICE_HOME = f"/home/{SERVICE_USER}"
+AVIBE_HOME = f"{SERVICE_HOME}/.avibe"
+LEGACY_HOME = f"{SERVICE_HOME}/.vibe_remote"
+SOURCE_DIR = "/opt/avibe/source"
+VENV_DIR = "/opt/avibe/venv"
+METADATA_DIR = "/var/lib/avibe-regression"
+METADATA_PATH = f"{METADATA_DIR}/metadata.json"
+FINGERPRINT_PATH = f"{METADATA_DIR}/fingerprints.json"
+SERVICE_NAME = "avibe-regression.service"
+DEFAULT_IMAGE = "avibe-regression-base-current"
+DEFAULT_BASE_SOURCE_IMAGE = "images:ubuntu/24.04/cloud"
+DEFAULT_NETWORK = "incusbr0"
+DEFAULT_STORAGE_POOL = "default"
+DEFAULT_UI_PORT = 5123
+CONTAINER_UI_HOST = "127.0.0.1"
+DEFAULT_MASTER_HOST_PORT = 15130
+DEFAULT_WORKTREE_PORT_START = 15200
+DEFAULT_WORKTREE_PORT_END = 15399
+ENV_FILE_NAME = ".env.regression"
+LEGACY_ENV_FILE_NAME = ".env.three-regression"
+ENV_PREFIX = "REGRESSION_"
+LEGACY_ENV_PREFIX = "THREE_REGRESSION_"
+SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{1,38}[a-z0-9]$")
+
+
+class RegressionError(RuntimeError):
+ """A user-correctable regression runner error."""
+
+
+@dataclass(frozen=True)
+class RegressionTarget:
+ target: str
+ slug: str
+ project: str
+ instance: str
+ host_port: int
+ ui_host: str
+ ui_port: int
+
+
+class Runner:
+ def __init__(self, *, dry_run: bool = False) -> None:
+ self.dry_run = dry_run
+
+ def run(
+ self,
+ command: Sequence[str],
+ *,
+ input_bytes: bytes | None = None,
+ input_text: str | None = None,
+ check: bool = True,
+ capture: bool = False,
+ ) -> subprocess.CompletedProcess[str]:
+ print("+ " + shlex.join(command))
+ if self.dry_run:
+ return subprocess.CompletedProcess(list(command), 0, "", "")
+ kwargs: dict = {
+ "check": check,
+ "text": input_bytes is None,
+ "capture_output": capture,
+ }
+ if input_bytes is not None:
+ kwargs["input"] = input_bytes
+ elif input_text is not None:
+ kwargs["input"] = input_text
+ return subprocess.run(list(command), **kwargs)
+
+ def exists(self, command: Sequence[str]) -> bool:
+ if self.dry_run:
+ return False
+ result = subprocess.run(list(command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ return result.returncode == 0
+
+
+def incus(*args: str, project: str | None = None) -> list[str]:
+ command = shlex.split(os.environ.get("INCUS_CMD", "incus"))
+ if project:
+ command.extend(["--project", project])
+ command.extend(args)
+ return command
+
+
+def remote_ref(remote: str | None, name: str = "") -> str:
+ if not remote:
+ return name
+ return f"{remote}:{name}"
+
+
+def optional_remote_ref(remote: str | None) -> list[str]:
+ return [remote_ref(remote)] if remote else []
+
+
+def require_incus() -> None:
+ command = shlex.split(os.environ.get("INCUS_CMD", "incus"))
+ executable = command[0] if command else "incus"
+ if shutil.which(executable) is None:
+ raise RegressionError(f"The Incus CLI executable was not found: {executable}")
+
+
+def validate_slug(slug: str) -> None:
+ if not SLUG_RE.match(slug):
+ raise RegressionError("Slug must be 3-40 chars, lowercase, and contain only letters, numbers, and hyphens.")
+
+
+def regression_env(suffix: str, default: str = "") -> str:
+ value = os.environ.get(f"{ENV_PREFIX}{suffix}")
+ if value is None:
+ value = os.environ.get(f"{LEGACY_ENV_PREFIX}{suffix}")
+ if value is None:
+ value = default
+ return value.strip()
+
+
+def host_bind_env(default: str = "127.0.0.1") -> str:
+ return (
+ regression_env("PORT_BIND_HOST")
+ or os.environ.get("REGRESSION_UI_HOST", "").strip()
+ or os.environ.get("THREE_REGRESSION_UI_HOST", "").strip()
+ or default
+ )
+
+
+def env_int(name: str) -> int | None:
+ if name.startswith(ENV_PREFIX):
+ value = regression_env(name[len(ENV_PREFIX):])
+ else:
+ value = os.environ.get(name, "").strip()
+ if not value:
+ return None
+ try:
+ return int(value)
+ except ValueError as exc:
+ raise RegressionError(f"{name} must be an integer.") from exc
+
+
+def current_repo_root() -> Path:
+ result = subprocess.run(
+ ["git", "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ return Path.cwd().resolve()
+ return Path(result.stdout.strip()).resolve()
+
+
+def git_common_root(repo_root: Path) -> Path:
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "rev-parse", "--git-common-dir"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if result.returncode != 0:
+ return repo_root
+ common = Path(result.stdout.strip())
+ if not common.is_absolute():
+ common = repo_root / common
+ return common.resolve().parent
+
+
+def runtime_root(repo_root: Path) -> Path:
+ return git_common_root(repo_root) / ".runtime" / "incus-regression"
+
+
+@contextmanager
+def target_update_lock(repo_root: Path, target: RegressionTarget, *, dry_run: bool):
+ if dry_run or fcntl is None:
+ yield
+ return
+ lock_dir = runtime_root(repo_root) / "locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ lock_path = lock_dir / f"{target.project}.lock"
+ with lock_path.open("w", encoding="utf-8") as fh:
+ print(f"Acquiring regression update lock: {lock_path}")
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
+
+
+@contextmanager
+def worktree_mapping_lock(repo_root: Path, *, dry_run: bool):
+ if dry_run or fcntl is None:
+ yield
+ return
+ lock_dir = runtime_root(repo_root) / "locks"
+ lock_dir.mkdir(parents=True, exist_ok=True)
+ lock_path = lock_dir / "worktrees.lock"
+ with lock_path.open("w", encoding="utf-8") as fh:
+ print(f"Acquiring regression worktree mapping lock: {lock_path}")
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
+
+
+def load_env_file(repo_root: Path, env_file: Path | None) -> Path | None:
+ common_root = git_common_root(repo_root)
+ candidates = [env_file] if env_file else [
+ repo_root / ENV_FILE_NAME,
+ common_root / ENV_FILE_NAME,
+ repo_root / LEGACY_ENV_FILE_NAME,
+ common_root / LEGACY_ENV_FILE_NAME,
+ ]
+ for candidate in candidates:
+ if not candidate:
+ continue
+ path = candidate.resolve()
+ if not path.is_file():
+ continue
+ for raw_line in path.read_text(encoding="utf-8").splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#") or "=" not in line:
+ continue
+ if line.startswith("export "):
+ line = line.removeprefix("export ").strip()
+ key, value = line.split("=", 1)
+ key = key.strip()
+ value = value.strip().strip("'\"")
+ os.environ.setdefault(key, value)
+ return path
+ return None
+
+
+def branch_name(repo_root: Path) -> str:
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "branch", "--show-current"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def commit_sha(repo_root: Path) -> str:
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return result.stdout.strip() if result.returncode == 0 else ""
+
+
+def is_dirty(repo_root: Path) -> bool:
+ result = subprocess.run(
+ ["git", "-C", str(repo_root), "status", "--porcelain"],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return bool(result.stdout.strip())
+
+
+def slugify(value: str) -> str:
+ slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
+ slug = re.sub(r"-+", "-", slug)
+ if not slug or not slug[0].isalpha():
+ slug = f"wt-{slug}" if slug else "wt"
+ return slug[:32].strip("-")
+
+
+def worktree_slug(repo_root: Path, explicit: str | None = None) -> str:
+ if explicit:
+ slug = slugify(explicit)
+ else:
+ source = branch_name(repo_root) or repo_root.name
+ digest = hashlib.sha1(str(repo_root).encode("utf-8")).hexdigest()[:8]
+ slug = f"{slugify(source)[:24]}-{digest}"
+ validate_slug(slug)
+ return slug
+
+
+def project_name_for(target: str, slug: str) -> str:
+ if target == MASTER_TARGET:
+ return f"{PROJECT_PREFIX}master"
+ validate_slug(slug)
+ return f"{WORKTREE_PROJECT_PREFIX}{slug}"
+
+
+def instance_name_for(target: str, slug: str) -> str:
+ if target == MASTER_TARGET:
+ return f"{INSTANCE_PREFIX}master"
+ validate_slug(slug)
+ return f"{WORKTREE_INSTANCE_PREFIX}{slug}"
+
+
+def unbracket_host(host: str) -> str:
+ if host.startswith("[") and host.endswith("]"):
+ return host[1:-1]
+ return host
+
+
+def is_ipv6_host(host: str) -> bool:
+ try:
+ return ":" in unbracket_host(host)
+ except ValueError:
+ return False
+
+
+def tcp_endpoint(host: str, port: int) -> str:
+ return f"tcp:[{unbracket_host(host)}]:{port}" if is_ipv6_host(host) else f"tcp:{host}:{port}"
+
+
+def ensure_host_port_available(host: str, port: int) -> None:
+ family = socket.AF_INET6 if is_ipv6_host(host) else socket.AF_INET
+ with socket.socket(family, socket.SOCK_STREAM) as sock:
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ sock.bind((unbracket_host(host), port))
+ except OSError as exc:
+ if exc.errno in {errno.EACCES, errno.EPERM}:
+ print(f"Warning: cannot preflight privileged host port {host}:{port}; continuing.", file=sys.stderr)
+ return
+ raise RegressionError(f"Host port {host}:{port} is not available: {exc}") from exc
+
+
+def mapping_path(repo_root: Path) -> Path:
+ return runtime_root(repo_root) / "worktrees.json"
+
+
+def load_worktree_mapping(repo_root: Path) -> dict:
+ path = mapping_path(repo_root)
+ if not path.is_file():
+ return {"schema_version": 1, "worktrees": {}}
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ return {"schema_version": 1, "worktrees": {}}
+ if not isinstance(payload, dict):
+ return {"schema_version": 1, "worktrees": {}}
+ payload.setdefault("schema_version", 1)
+ payload.setdefault("worktrees", {})
+ return payload
+
+
+def save_worktree_mapping(repo_root: Path, payload: dict) -> None:
+ path = mapping_path(repo_root)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+
+
+def allocated_worktree_ports(repo_root: Path) -> set[int]:
+ payload = load_worktree_mapping(repo_root)
+ ports: set[int] = set()
+ for item in (payload.get("worktrees") or {}).values():
+ if isinstance(item, dict) and isinstance(item.get("host_port"), int):
+ ports.add(item["host_port"])
+ return ports
+
+
+def allocate_worktree_port(repo_root: Path, ui_host: str, start: int, end: int, *, dry_run: bool, preflight: bool) -> int:
+ used = allocated_worktree_ports(repo_root)
+ for port in range(start, end + 1):
+ if port in used:
+ continue
+ if not dry_run and preflight:
+ try:
+ ensure_host_port_available(ui_host, port)
+ except RegressionError:
+ continue
+ return port
+ raise RegressionError(f"No available worktree regression port in range {start}-{end}.")
+
+
+def mapped_worktree_port(repo_root: Path, slug: str) -> int | None:
+ item = (load_worktree_mapping(repo_root).get("worktrees") or {}).get(slug)
+ if isinstance(item, dict) and isinstance(item.get("host_port"), int):
+ return item["host_port"]
+ return None
+
+
+def resolve_target(
+ args: argparse.Namespace,
+ repo_root: Path,
+ *,
+ dry_run: bool,
+ preflight_ports: bool = True,
+ allocate_port: bool = True,
+) -> RegressionTarget:
+ if args.target not in TARGETS:
+ raise RegressionError(f"target must be one of: {', '.join(sorted(TARGETS))}")
+ ui_host = args.ui_host or host_bind_env()
+ ui_port = args.ui_port
+ if args.target == MASTER_TARGET:
+ slug = "master"
+ host_port = args.host_port or env_int("REGRESSION_PORT") or DEFAULT_MASTER_HOST_PORT
+ else:
+ slug = worktree_slug(repo_root, args.slug)
+ host_port = args.host_port or mapped_worktree_port(repo_root, slug)
+ if host_port is None and allocate_port:
+ host_port = allocate_worktree_port(
+ repo_root,
+ ui_host,
+ args.worktree_port_start,
+ args.worktree_port_end,
+ dry_run=dry_run,
+ preflight=preflight_ports,
+ )
+ if host_port is None:
+ host_port = 0
+ return RegressionTarget(
+ target=args.target,
+ slug=slug,
+ project=project_name_for(args.target, slug),
+ instance=instance_name_for(args.target, slug),
+ host_port=host_port,
+ ui_host=ui_host,
+ ui_port=ui_port,
+ )
+
+
+def project_create_config(target: RegressionTarget) -> list[str]:
+ return [
+ "features.images=false",
+ "features.profiles=true",
+ "features.storage.volumes=true",
+ "restricted=true",
+ "restricted.devices.proxy=allow",
+ "limits.instances=1",
+ "limits.containers=1",
+ f"user.avibe_regression.target={target.target}",
+ f"user.avibe_regression.slug={target.slug}",
+ f"user.avibe_regression.instance={target.instance}",
+ f"user.avibe_regression.host_port={target.host_port}",
+ ]
+
+
+def profile_yaml(storage_pool: str, network: str, cpus: str, memory: str, disk: str, processes: str) -> str:
+ return textwrap.dedent(
+ f"""\
+ config:
+ limits.cpu: "{cpus}"
+ limits.memory: "{memory}"
+ limits.processes: "{processes}"
+ description: Avibe regression profile
+ devices:
+ eth0:
+ name: eth0
+ network: {network}
+ type: nic
+ root:
+ path: /
+ pool: {storage_pool}
+ size: {disk}
+ type: disk
+ name: default
+ """
+ )
+
+
+def cloud_init_user_data() -> str:
+ service = textwrap.dedent(
+ f"""\
+ [Unit]
+ Description=Avibe regression service
+ Wants=network-online.target
+ After=network-online.target
+
+ [Service]
+ Type=simple
+ User={SERVICE_USER}
+ Group={SERVICE_USER}
+ WorkingDirectory={SOURCE_DIR}
+ Environment=HOME={SERVICE_HOME}
+ Environment=VIBE_REMOTE_HOME=
+ Environment=VIBE_DEPLOYMENT_ENV=regression
+ Environment=VIBE_INTERNAL_DISPATCH_SOCKET=/tmp/vibe_remote/dispatch.sock
+ Environment=PYTHONUNBUFFERED=1
+ Environment=PATH={VENV_DIR}/bin:{SERVICE_HOME}/.local/bin:/usr/local/bin:/usr/bin:/bin
+ EnvironmentFile=-/etc/avibe-regression.env
+ ExecStart={VENV_DIR}/bin/python scripts/incus_regression_supervisor.py
+ Restart=on-failure
+ RestartSec=2
+ TimeoutStopSec=60
+
+ [Install]
+ WantedBy=multi-user.target
+ """
+ ).rstrip()
+ helper = textwrap.dedent(
+ f"""\
+ #!/usr/bin/env bash
+ set -euo pipefail
+ echo "service={SERVICE_NAME}"
+ echo "source={SOURCE_DIR}"
+ echo "home={AVIBE_HOME}"
+ echo "metadata={METADATA_PATH}"
+ """
+ ).rstrip()
+ lines = [
+ "#cloud-config",
+ "package_update: true",
+ "packages:",
+ " - bash",
+ " - ca-certificates",
+ " - curl",
+ " - git",
+ " - build-essential",
+ " - python3",
+ " - python3-pip",
+ " - python3-venv",
+ " - rsync",
+ " - sudo",
+ "users:",
+ f" - name: {SERVICE_USER}",
+ " groups: sudo",
+ " shell: /bin/bash",
+ " sudo: ALL=(ALL) NOPASSWD:ALL",
+ " lock_passwd: true",
+ "write_files:",
+ f" - path: /etc/systemd/system/{SERVICE_NAME}",
+ " owner: root:root",
+ " permissions: '0644'",
+ " content: |",
+ yaml_block(service),
+ " - path: /usr/local/bin/avibe-regression-info",
+ " owner: root:root",
+ " permissions: '0755'",
+ " content: |",
+ yaml_block(helper),
+ "runcmd:",
+ f" - [mkdir, -p, {SOURCE_DIR}, {VENV_DIR}, {METADATA_DIR}, {AVIBE_HOME}]",
+ f" - [chown, -R, {SERVICE_USER}:{SERVICE_USER}, {SERVICE_HOME}, /opt/avibe, {METADATA_DIR}]",
+ f" - [ln, -sfn, {AVIBE_HOME}, {LEGACY_HOME}]",
+ " - [systemctl, daemon-reload]",
+ f'final_message: "Avibe regression base is ready."',
+ ]
+ return "\n".join(lines)
+
+
+def yaml_block(value: str, indent: int = 6) -> str:
+ prefix = " " * indent
+ return "\n".join(prefix + line if line else prefix for line in value.splitlines())
+
+
+def proxy_device_args(target: RegressionTarget, *, remote: str | None = None) -> list[str]:
+ return [
+ "config",
+ "device",
+ "add",
+ remote_ref(remote, target.instance),
+ "ui",
+ "proxy",
+ f"listen={tcp_endpoint(target.ui_host, target.host_port)}",
+ f"connect=tcp:127.0.0.1:{target.ui_port}",
+ ]
+
+
+def ensure_proxy_device(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ instance_ref = remote_ref(remote, target.instance)
+ runner.run(incus("config", "device", "remove", instance_ref, "ui", project=target.project), check=False)
+ runner.run(incus(*proxy_device_args(target, remote=remote), project=target.project))
+
+
+def ensure_project_and_instance(
+ runner: Runner,
+ target: RegressionTarget,
+ *,
+ image: str,
+ storage_pool: str,
+ network: str,
+ cpus: str,
+ memory: str,
+ disk: str,
+ processes: str,
+ remote: str | None,
+) -> None:
+ if not runner.exists(incus("project", "show", remote_ref(remote, target.project))):
+ command = incus("project", "create", remote_ref(remote, target.project))
+ for item in project_create_config(target):
+ command.extend(["--config", item])
+ runner.run(command)
+ runner.run(
+ incus("profile", "edit", remote_ref(remote, "default"), project=target.project),
+ input_text=profile_yaml(storage_pool, network, cpus, memory, disk, processes),
+ )
+ if not runner.exists(incus("info", remote_ref(remote, target.instance), project=target.project)):
+ runner.run(
+ incus(
+ "init",
+ remote_ref(remote, image) if remote and ":" not in image else image,
+ remote_ref(remote, target.instance),
+ "--profile",
+ "default",
+ "--config",
+ f"cloud-init.user-data={cloud_init_user_data()}",
+ project=target.project,
+ )
+ )
+ ensure_proxy_device(runner, target, remote=remote)
+ runner.run(incus("start", remote_ref(remote, target.instance), project=target.project), check=False)
+ runner.run(
+ root_exec(
+ target,
+ (
+ "if command -v cloud-init >/dev/null 2>&1; then cloud-init status --wait || true; fi; "
+ f"mkdir -p {SOURCE_DIR} {VENV_DIR} {METADATA_DIR} {AVIBE_HOME}; "
+ f"chown -R {SERVICE_USER}:{SERVICE_USER} {SERVICE_HOME} /opt/avibe {METADATA_DIR}; "
+ f"ln -sfn {AVIBE_HOME} {LEGACY_HOME}; "
+ "systemctl daemon-reload"
+ ),
+ remote=remote,
+ )
+ )
+
+
+def tenant_exec(target: RegressionTarget, command: str, *args: str, remote: str | None = None) -> list[str]:
+ bash_command = (
+ "set -a; [ ! -f /etc/avibe-regression.env ] || . /etc/avibe-regression.env; "
+ f"set +a; cd {shlex.quote(SOURCE_DIR)} && {command}"
+ )
+ return incus(
+ "exec",
+ remote_ref(remote, target.instance),
+ "--",
+ "sudo",
+ "-H",
+ "-u",
+ SERVICE_USER,
+ "--",
+ "bash",
+ "-lc",
+ bash_command,
+ "bash",
+ *args,
+ project=target.project,
+ )
+
+
+def root_exec(target: RegressionTarget, command: str, *, remote: str | None = None) -> list[str]:
+ return incus("exec", remote_ref(remote, target.instance), "--", "bash", "-lc", command, project=target.project)
+
+
+def source_excludes(*, include_ui_dist: bool = False) -> tuple[str, ...]:
+ excludes = [
+ ".git",
+ ".runtime",
+ ".worktrees",
+ "__pycache__",
+ ".pytest_cache",
+ ".mypy_cache",
+ ".ruff_cache",
+ ".venv",
+ "node_modules",
+ "ui/node_modules",
+ "ui/.vite",
+ "_tmp",
+ "tmp",
+ "logs",
+ ]
+ if not include_ui_dist:
+ excludes.append("ui/dist")
+ return tuple(excludes)
+
+
+def is_env_file(relative: str) -> bool:
+ return any(part == ".env" or part.startswith(".env.") for part in relative.split("/"))
+
+
+def should_exclude(relative: str, *, include_ui_dist: bool = False) -> bool:
+ if is_env_file(relative):
+ return True
+ parts = relative.split("/")
+ for pattern in source_excludes(include_ui_dist=include_ui_dist):
+ pattern_parts = pattern.split("/")
+ if relative == pattern or relative.startswith(pattern + "/"):
+ return True
+ if len(pattern_parts) == 1 and pattern in parts:
+ return True
+ return False
+
+
+def build_source_tar(repo_root: Path, *, include_ui_dist: bool = False) -> bytes:
+ with tempfile.TemporaryFile() as fh:
+ with tarfile.open(fileobj=fh, mode="w") as tar:
+ for path in sorted(repo_root.rglob("*")):
+ relative = path.relative_to(repo_root).as_posix()
+ if should_exclude(relative, include_ui_dist=include_ui_dist):
+ continue
+ tar.add(path, arcname=relative, recursive=False)
+ fh.seek(0)
+ return fh.read()
+
+
+def sync_source(
+ runner: Runner,
+ target: RegressionTarget,
+ repo_root: Path,
+ *,
+ remote: str | None,
+ clean: bool,
+ include_ui_dist: bool = False,
+) -> None:
+ runner.run(root_exec(target, f"mkdir -p {shlex.quote(SOURCE_DIR)} && find {shlex.quote(SOURCE_DIR)} -mindepth 1 -maxdepth 1 -exec rm -rf {{}} +", remote=remote))
+ runner.run(root_exec(target, f"mkdir -p {shlex.quote(SOURCE_DIR)} && chown -R {SERVICE_USER}:{SERVICE_USER} /opt/avibe", remote=remote))
+ tar_bytes = b"" if runner.dry_run else build_source_tar(repo_root, include_ui_dist=include_ui_dist)
+ runner.run(
+ incus("exec", remote_ref(remote, target.instance), "--", "tar", "-C", SOURCE_DIR, "-xf", "-", project=target.project),
+ input_bytes=tar_bytes,
+ )
+ runner.run(root_exec(target, f"chown -R {SERVICE_USER}:{SERVICE_USER} {shlex.quote(SOURCE_DIR)}", remote=remote))
+
+
+def stop_service_for_update(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ runner.run(root_exec(target, f"systemctl stop {SERVICE_NAME} || true", remote=remote), check=False)
+
+
+def file_hash(repo_root: Path, relative_paths: Sequence[str]) -> str:
+ digest = hashlib.sha256()
+ for relative in relative_paths:
+ path = repo_root / relative
+ digest.update(relative.encode("utf-8"))
+ if path.is_file():
+ digest.update(path.read_bytes())
+ else:
+ digest.update(b"<missing>")
+ return digest.hexdigest()
+
+
+def compute_fingerprints(repo_root: Path) -> dict:
+ ui_source_parts = [
+ tree_hash(repo_root / "ui" / "src"),
+ tree_hash(repo_root / "ui" / "public"),
+ file_hash(
+ repo_root,
+ [
+ "ui/index.html",
+ "ui/vite.config.ts",
+ "ui/tsconfig.json",
+ "ui/tsconfig.app.json",
+ "ui/tsconfig.node.json",
+ ],
+ ),
+ ]
+ return {
+ "python": file_hash(repo_root, ["pyproject.toml", "uv.lock"]),
+ "ui_deps": file_hash(repo_root, ["ui/package.json", "ui/package-lock.json"]),
+ "ui_source": "|".join(ui_source_parts),
+ "show_runtime": "|".join(
+ [
+ regression_env("SHOW_RUNTIME_SOURCE", "github-source"),
+ regression_env("SHOW_RUNTIME_GITHUB_REPO", "https://github.com/avibe-bot/vibe-show-runtime.git"),
+ regression_env("SHOW_RUNTIME_GITHUB_REF", "main"),
+ ]
+ ),
+ }
+
+
+def tree_hash(root: Path) -> str:
+ digest = hashlib.sha256()
+ if not root.exists():
+ return "<missing>"
+ for path in sorted(p for p in root.rglob("*") if p.is_file()):
+ digest.update(path.relative_to(root).as_posix().encode("utf-8"))
+ digest.update(path.read_bytes())
+ return digest.hexdigest()
+
+
+def write_metadata(runner: Runner, target: RegressionTarget, repo_root: Path, fingerprints: dict, *, remote: str | None) -> None:
+ payload = {
+ "schema_version": 1,
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ "target": target.target,
+ "slug": target.slug,
+ "project": target.project,
+ "instance": target.instance,
+ "repo_root": str(repo_root),
+ "branch": branch_name(repo_root),
+ "commit": commit_sha(repo_root),
+ "dirty": is_dirty(repo_root),
+ "fingerprints": fingerprints,
+ }
+ encoded = json.dumps(payload, indent=2)
+ command = f"mkdir -p {METADATA_DIR} && cat > {METADATA_PATH} <<'EOF'\n{encoded}\nEOF\ncat > {FINGERPRINT_PATH} <<'EOF'\n{json.dumps(fingerprints, indent=2)}\nEOF"
+ runner.run(root_exec(target, command, remote=remote))
+
+
+def runtime_env_payload(repo_root: Path | None = None) -> bytes:
+ scm_version = "0.0.0.dev0"
+ if repo_root is not None:
+ sha = commit_sha(repo_root)
+ if sha:
+ scm_version = f"0.0.0.dev0+{sha[:12]}"
+ mappings = {
+ "SETUPTOOLS_SCM_PRETEND_VERSION": scm_version,
+ "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS": scm_version,
+ "REGRESSION_UI_HOST": CONTAINER_UI_HOST,
+ "VIBE_SHOW_RUNTIME_SOURCE": regression_env("SHOW_RUNTIME_SOURCE", "github-source"),
+ "VIBE_SHOW_RUNTIME_GITHUB_REPO": regression_env("SHOW_RUNTIME_GITHUB_REPO", "https://github.com/avibe-bot/vibe-show-runtime.git"),
+ "VIBE_SHOW_RUNTIME_GITHUB_REF": regression_env("SHOW_RUNTIME_GITHUB_REF", "main"),
+ "ANTHROPIC_API_KEY": os.environ.get("ANTHROPIC_API_KEY", ""),
+ "ANTHROPIC_BASE_URL": os.environ.get("ANTHROPIC_BASE_URL", ""),
+ "OPENAI_API_KEY": os.environ.get("OPENAI_API_KEY", ""),
+ "OPENAI_BASE_URL": os.environ.get("OPENAI_BASE_URL", ""),
+ "OPENAI_API_BASE": os.environ.get("OPENAI_API_BASE", ""),
+ }
+ for key, value in os.environ.items():
+ if key == "REGRESSION_UI_HOST":
+ continue
+ if key.startswith(ENV_PREFIX):
+ mappings[key] = value
+ elif key.startswith(LEGACY_ENV_PREFIX):
+ canonical_key = ENV_PREFIX + key[len(LEGACY_ENV_PREFIX):]
+ if canonical_key == "REGRESSION_UI_HOST":
+ continue
+ mappings.setdefault(canonical_key, value)
+ lines = [f"{key}={shlex.quote(value)}" for key, value in mappings.items() if value]
+ return ("\n".join(lines) + "\n").encode("utf-8")
+
+
+def required_platform_seed_envs() -> tuple[str, ...]:
+ required = [
+ "REGRESSION_SLACK_BOT_TOKEN",
+ "REGRESSION_SLACK_APP_TOKEN",
+ "REGRESSION_DISCORD_BOT_TOKEN",
+ "REGRESSION_FEISHU_APP_ID",
+ "REGRESSION_FEISHU_APP_SECRET",
+ ]
+ return tuple(required)
+
+
+def env_value(key: str) -> str:
+ value = os.environ.get(key, "")
+ if value:
+ return value.strip()
+ if key.startswith(ENV_PREFIX):
+ legacy_key = LEGACY_ENV_PREFIX + key[len(ENV_PREFIX):]
+ return os.environ.get(legacy_key, "").strip()
+ return ""
+
+
+def require_runtime_seed_env() -> None:
+ required = ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", *required_platform_seed_envs())
+ missing = [key for key in required if not env_value(key)]
+ if missing:
+ joined = ", ".join(missing)
+ raise SystemExit(f"Missing required regression seed environment variables: {joined}")
+
+
+def write_runtime_env(runner: Runner, target: RegressionTarget, *, repo_root: Path | None = None, remote: str | None) -> None:
+ runner.run(
+ incus(
+ "exec",
+ remote_ref(remote, target.instance),
+ "--",
+ "bash",
+ "-lc",
+ f"cat > /etc/avibe-regression.env && chown root:{SERVICE_USER} /etc/avibe-regression.env && chmod 0640 /etc/avibe-regression.env",
+ project=target.project,
+ ),
+ input_bytes=b"" if runner.dry_run else runtime_env_payload(repo_root),
+ )
+
+
+def read_existing_fingerprints(runner: Runner, target: RegressionTarget, *, remote: str | None) -> dict:
+ if runner.dry_run:
+ return {}
+ result = runner.run(
+ root_exec(target, f"test -f {FINGERPRINT_PATH} && cat {FINGERPRINT_PATH} || true", remote=remote),
+ capture=True,
+ check=False,
+ )
+ try:
+ payload = json.loads(result.stdout or "{}")
+ except json.JSONDecodeError:
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def should_seed_state(runner: Runner, target: RegressionTarget, *, reset_mode: str, remote: str | None) -> bool:
+ if runner.dry_run or reset_mode != "none":
+ return True
+ result = runner.run(
+ root_exec(target, f"test -f {AVIBE_HOME}/config/config.json", remote=remote),
+ check=False,
+ )
+ return result.returncode != 0
+
+
+def run_prepare_state(runner: Runner, target: RegressionTarget, *, reset_mode: str, remote: str | None) -> None:
+ if not should_seed_state(runner, target, reset_mode=reset_mode, remote=remote):
+ print("Existing Avibe state found; skipping regression state seed.")
+ return
+ runner.run(root_exec(target, f"rm -rf /home/{SERVICE_USER}/.regression-seed", remote=remote))
+ runner.run(
+ tenant_exec(
+ target,
+ f"{VENV_DIR}/bin/python scripts/prepare_regression.py --output-root /home/{SERVICE_USER}/.regression-seed --reset-mode {shlex.quote(reset_mode)}",
+ remote=remote,
+ )
+ )
+ if reset_mode == "config":
+ runner.run(
+ root_exec(
+ target,
+ f"rm -rf {AVIBE_HOME}/config {AVIBE_HOME}/state {AVIBE_HOME}/runtime",
+ remote=remote,
+ )
+ )
+ elif reset_mode == "all":
+ runner.run(
+ root_exec(
+ target,
+ "rm -rf "
+ f"{AVIBE_HOME} {LEGACY_HOME} "
+ f"{SERVICE_HOME}/.claude {SERVICE_HOME}/.claude.json {SERVICE_HOME}/.codex "
+ f"{SERVICE_HOME}/.config/opencode {SERVICE_HOME}/.local/share/opencode",
+ remote=remote,
+ )
+ )
+ runner.run(
+ root_exec(
+ target,
+ f"mkdir -p {AVIBE_HOME} && "
+ f"cp -a /home/{SERVICE_USER}/.regression-seed/home/. {SERVICE_HOME}/ && "
+ f"chown -R {SERVICE_USER}:{SERVICE_USER} {SERVICE_HOME} && "
+ f"ln -sfn {AVIBE_HOME} {LEGACY_HOME} && chown -h {SERVICE_USER}:{SERVICE_USER} {LEGACY_HOME}",
+ remote=remote,
+ )
+ )
+
+
+def instance_ui_dist_exists(runner: Runner, target: RegressionTarget, *, remote: str | None) -> bool:
+ result = runner.run(
+ tenant_exec(target, "test -d ui/dist && test -f ui/dist/index.html", remote=remote),
+ check=False,
+ )
+ return result.returncode == 0
+
+
+def normalize_runtime_config(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ script = textwrap.dedent(f"""
+ import json
+ from pathlib import Path
+
+ path = Path({str(AVIBE_HOME + "/config/config.json")!r})
+ if not path.exists():
+ raise SystemExit(0)
+ payload = json.loads(path.read_text())
+ ui = payload.setdefault("ui", {{}})
+ changed = False
+ if ui.get("setup_host") != {CONTAINER_UI_HOST!r}:
+ ui["setup_host"] = {CONTAINER_UI_HOST!r}
+ changed = True
+ if ui.get("setup_port") != {target.ui_port!r}:
+ ui["setup_port"] = {target.ui_port!r}
+ changed = True
+ if not changed:
+ raise SystemExit(0)
+ path.write_text(json.dumps(payload, indent=2))
+ """).strip()
+ runner.run(
+ root_exec(
+ target,
+ f"python3 - <<'PY'\n{script}\nPY\nchown {SERVICE_USER}:{SERVICE_USER} {AVIBE_HOME}/config/config.json",
+ remote=remote,
+ )
+ )
+
+
+def update_dependencies_and_build(
+ runner: Runner,
+ target: RegressionTarget,
+ *,
+ previous_fingerprints: dict,
+ next_fingerprints: dict,
+ force_deps: bool,
+ build_ui: bool,
+ force_ui: bool,
+ remote: str | None,
+) -> None:
+ runner.run(root_exec(target, f"python3 -m venv {shlex.quote(VENV_DIR)} || true", remote=remote))
+ runner.run(root_exec(target, f"chown -R {SERVICE_USER}:{SERVICE_USER} {shlex.quote(VENV_DIR)}", remote=remote))
+ python_changed = (
+ force_deps
+ or previous_fingerprints.get("python") != next_fingerprints.get("python")
+ or not previous_fingerprints
+ )
+ if python_changed:
+ runner.run(tenant_exec(target, f"{VENV_DIR}/bin/python -m pip install -U pip wheel", remote=remote))
+ else:
+ print("Python dependency fingerprint unchanged; skipping pip install.")
+ needs_ui_dist = not instance_ui_dist_exists(runner, target, remote=remote)
+ should_build_ui = build_ui or needs_ui_dist
+ if needs_ui_dist and not build_ui:
+ print("UI dist missing in synced source; building UI before editable install.")
+ if should_build_ui:
+ ui_deps_changed = force_ui or previous_fingerprints.get("ui_deps") != next_fingerprints.get("ui_deps") or not previous_fingerprints
+ if ui_deps_changed:
+ runner.run(tenant_exec(target, "cd ui && npm ci", remote=remote))
+ else:
+ print("UI dependency fingerprint unchanged; skipping npm ci.")
+ if (
+ force_ui
+ or needs_ui_dist
+ or ui_deps_changed
+ or previous_fingerprints.get("ui_source") != next_fingerprints.get("ui_source")
+ ):
+ runner.run(tenant_exec(target, "cd ui && npm run build", remote=remote))
+ else:
+ print("UI source fingerprint unchanged; skipping npm run build.")
+ if python_changed:
+ runner.run(tenant_exec(target, f"{VENV_DIR}/bin/pip install -e .", remote=remote))
+
+
+def restart_and_verify(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ runner.run(root_exec(target, "systemctl daemon-reload", remote=remote))
+ runner.run(root_exec(target, f"systemctl enable --now {SERVICE_NAME}", remote=remote))
+ runner.run(root_exec(target, f"systemctl restart {SERVICE_NAME}", remote=remote))
+ runner.run(
+ root_exec(
+ target,
+ (
+ "for i in $(seq 1 60); do "
+ f"systemctl is-active --quiet {SERVICE_NAME} && "
+ f"curl -fsS http://127.0.0.1:{target.ui_port}/health >/dev/null && "
+ f"curl -fsS http://127.0.0.1:{target.ui_port}/status | grep -q '\"state\":\"running\"' && "
+ "exit 0; "
+ "sleep 2; "
+ f"done; journalctl -u {SERVICE_NAME} --no-pager -n 120; exit 1"
+ ),
+ remote=remote,
+ )
+ )
+
+
+def prepare_show_runtime(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ result = runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime prepare --strict", remote=remote), check=False)
+ if result.returncode != 0:
+ runner.run(tenant_exec(target, "rm -rf ~/.avibe/runtime/show-runtime/source ~/.npm/_cacache", remote=remote))
+ runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime prepare --strict", remote=remote))
+ runner.run(tenant_exec(target, f"{VENV_DIR}/bin/vibe runtime status --json", remote=remote))
+
+
+def update_worktree_mapping(repo_root: Path, target: RegressionTarget) -> None:
+ if target.target != WORKTREE_TARGET:
+ return
+ payload = load_worktree_mapping(repo_root)
+ payload.setdefault("worktrees", {})[target.slug] = {
+ "path": str(repo_root),
+ "project": target.project,
+ "instance": target.instance,
+ "host_port": target.host_port,
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ "branch": branch_name(repo_root),
+ "commit": commit_sha(repo_root),
+ }
+ save_worktree_mapping(repo_root, payload)
+
+
+def reserve_worktree_mapping(repo_root: Path, target: RegressionTarget) -> None:
+ if target.target != WORKTREE_TARGET:
+ return
+ payload = load_worktree_mapping(repo_root)
+ payload.setdefault("worktrees", {}).setdefault(target.slug, {})
+ payload["worktrees"][target.slug].update(
+ {
+ "path": str(repo_root),
+ "project": target.project,
+ "instance": target.instance,
+ "host_port": target.host_port,
+ "reserved_at": datetime.now(timezone.utc).isoformat(),
+ "branch": branch_name(repo_root),
+ }
+ )
+ save_worktree_mapping(repo_root, payload)
+
+
+def cmd_doctor(args: argparse.Namespace) -> int:
+ if not args.dry_run:
+ require_incus()
+ runner = Runner(dry_run=args.dry_run)
+ checks = [
+ ("version", incus("version")),
+ ("daemon info", incus("info", *optional_remote_ref(args.remote))),
+ ("projects", incus("project", "list", *optional_remote_ref(args.remote))),
+ ("storage", incus("storage", "list", *optional_remote_ref(args.remote))),
+ ("network", incus("network", "list", *optional_remote_ref(args.remote))),
+ ]
+ failed: list[str] = []
+ for name, command in checks:
+ result = runner.run(command, check=False)
+ if result.returncode != 0:
+ failed.append(name)
+ if failed:
+ print("Failed checks: " + ", ".join(failed), file=sys.stderr)
+ return 1
+ return 0
+
+
+def cmd_init_host(args: argparse.Namespace) -> int:
+ if not args.dry_run:
+ require_incus()
+ runner = Runner(dry_run=args.dry_run)
+ if args.minimal:
+ if args.remote:
+ raise RegressionError("init-host --minimal must run on the Incus host itself, not through a remote.")
+ runner.run(incus("admin", "init", "--minimal"))
+ return cmd_doctor(args)
+
+
+def cmd_build_base(args: argparse.Namespace) -> int:
+ if not args.dry_run:
+ require_incus()
+ runner = Runner(dry_run=args.dry_run)
+ runner.run(incus("delete", remote_ref(args.remote, args.temp_instance), "--force"), check=False)
+ runner.run(
+ incus(
+ "launch",
+ remote_ref(args.remote, args.source_image) if args.remote and ":" not in args.source_image else args.source_image,
+ remote_ref(args.remote, args.temp_instance),
+ "--storage",
+ args.storage_pool,
+ "--network",
+ args.network,
+ )
+ )
+ runner.run(
+ incus(
+ "exec",
+ remote_ref(args.remote, args.temp_instance),
+ "--",
+ "bash",
+ "-lc",
+ textwrap.dedent(
+ """\
+ set -euo pipefail
+ apt-get update
+ apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo
+ curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
+ apt-get install -y nodejs
+ npm install -g @anthropic-ai/claude-code @openai/codex
+ curl -fsSL https://askill.sh | sh -s -- -b /usr/local/bin
+ HOME=/usr/local curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path
+ install -o root -g root -m 0755 /usr/local/.opencode/bin/opencode /usr/local/bin/opencode
+ askill --version
+ opencode --version
+ node --version
+ npm --version
+ """
+ ),
+ )
+ )
+ runner.run(
+ incus(
+ "exec",
+ remote_ref(args.remote, args.temp_instance),
+ "--",
+ "bash",
+ "-lc",
+ "cloud-init clean --logs || true",
+ )
+ )
+ runner.run(incus("stop", remote_ref(args.remote, args.temp_instance), "--force"), check=False)
+ runner.run(incus("image", "delete", remote_ref(args.remote, args.image)), check=False)
+ publish_command = incus("publish", remote_ref(args.remote, args.temp_instance))
+ if args.remote:
+ publish_command.append(remote_ref(args.remote))
+ publish_command.extend(["--alias", args.image])
+ runner.run(publish_command)
+ runner.run(incus("delete", remote_ref(args.remote, args.temp_instance), "--force"))
+ return 0
+
+
+def cmd_up(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ loaded_env_file = load_env_file(repo_root, args.env_file)
+ if not args.dry_run:
+ require_incus()
+ preflight_during_target_resolution = args.remote is None and args.target != MASTER_TARGET
+ with worktree_mapping_lock(repo_root, dry_run=args.dry_run):
+ target = resolve_target(
+ args,
+ repo_root,
+ dry_run=args.dry_run,
+ preflight_ports=preflight_during_target_resolution,
+ )
+ if not args.dry_run:
+ reserve_worktree_mapping(repo_root, target)
+ with target_update_lock(repo_root, target, dry_run=args.dry_run):
+ runner = Runner(dry_run=args.dry_run)
+ target_exists = runner.exists(incus("info", remote_ref(args.remote, target.instance), project=target.project))
+ if not args.dry_run and not target_exists and args.remote is None:
+ ensure_host_port_available(target.ui_host, target.host_port)
+ seed_requires_env = not args.dry_run and (args.reset_mode != "none" or not target_exists)
+ if seed_requires_env:
+ require_runtime_seed_env()
+ ensure_project_and_instance(
+ runner,
+ target,
+ image=args.image,
+ storage_pool=args.storage_pool,
+ network=args.network,
+ cpus=args.cpus,
+ memory=args.memory,
+ disk=args.disk,
+ processes=args.processes,
+ remote=args.remote,
+ )
+ if not args.dry_run and not seed_requires_env and should_seed_state(runner, target, reset_mode=args.reset_mode, remote=args.remote):
+ require_runtime_seed_env()
+ stop_service_for_update(runner, target, remote=args.remote)
+ if seed_requires_env or loaded_env_file is not None or args.dry_run:
+ write_runtime_env(runner, target, repo_root=repo_root, remote=args.remote)
+ else:
+ print("No regression env file loaded; preserving existing runtime env file.")
+ sync_source(runner, target, repo_root, remote=args.remote, clean=args.clean, include_ui_dist=args.no_build_ui)
+ fingerprints = compute_fingerprints(repo_root)
+ previous_fingerprints = read_existing_fingerprints(runner, target, remote=args.remote)
+ update_dependencies_and_build(
+ runner,
+ target,
+ previous_fingerprints=previous_fingerprints,
+ next_fingerprints=fingerprints,
+ force_deps=args.force_deps,
+ build_ui=not args.no_build_ui,
+ force_ui=True,
+ remote=args.remote,
+ )
+ run_prepare_state(runner, target, reset_mode=args.reset_mode, remote=args.remote)
+ normalize_runtime_config(runner, target, remote=args.remote)
+ write_metadata(runner, target, repo_root, fingerprints, remote=args.remote)
+ restart_and_verify(runner, target, remote=args.remote)
+ prepare_show_runtime(runner, target, remote=args.remote)
+ if not args.dry_run:
+ update_worktree_mapping(repo_root, target)
+ print_summary(target)
+ return 0
+
+
+def print_summary(target: RegressionTarget) -> None:
+ print("")
+ print("Incus regression environment is ready:")
+ print(f" URL: http://{target.ui_host}:{target.host_port}")
+ print(f" Target: {target.target}")
+ print(f" Project: {target.project}")
+ print(f" Instance: {target.instance}")
+ print(f" Show Runtime source: {regression_env('SHOW_RUNTIME_SOURCE', 'github-source')}")
+
+
+def cmd_status(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ load_env_file(repo_root, args.env_file)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ if not args.dry_run:
+ require_incus()
+ runner = Runner(dry_run=args.dry_run)
+ failed = 0
+ for command in (
+ incus("list", *optional_remote_ref(args.remote), project=target.project),
+ root_exec(target, "avibe-regression-info && systemctl status avibe-regression --no-pager", remote=args.remote),
+ tenant_exec(target, f"{VENV_DIR}/bin/vibe status", remote=args.remote),
+ ):
+ result = runner.run(command, check=False)
+ failed += 1 if result.returncode != 0 else 0
+ return 1 if failed else 0
+
+
+def cmd_logs(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ load_env_file(repo_root, args.env_file)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ if not args.dry_run:
+ require_incus()
+ Runner(dry_run=args.dry_run).run(
+ root_exec(target, f"journalctl -u {SERVICE_NAME} -f --no-pager", remote=args.remote),
+ check=False,
+ )
+ return 0
+
+
+def cmd_shell(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ load_env_file(repo_root, args.env_file)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ if not args.dry_run:
+ require_incus()
+ Runner(dry_run=args.dry_run).run(tenant_exec(target, "exec bash -l", remote=args.remote))
+ return 0
+
+
+def cmd_down(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ load_env_file(repo_root, args.env_file)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ if not args.dry_run:
+ require_incus()
+ Runner(dry_run=args.dry_run).run(incus("stop", remote_ref(args.remote, target.instance), project=target.project), check=False)
+ return 0
+
+
+def cmd_delete(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ load_env_file(repo_root, args.env_file)
+ target = resolve_target(args, repo_root, dry_run=args.dry_run, allocate_port=False, preflight_ports=False)
+ if target.target == MASTER_TARGET and not args.yes:
+ raise RegressionError("Deleting the master regression environment requires --yes.")
+ if not args.dry_run:
+ require_incus()
+ runner = Runner(dry_run=args.dry_run)
+ runner.run(incus("delete", remote_ref(args.remote, target.instance), "--force", project=target.project), check=False)
+ runner.run(incus("project", "delete", remote_ref(args.remote, target.project)), check=False)
+ if target.target == WORKTREE_TARGET and not args.dry_run:
+ payload = load_worktree_mapping(repo_root)
+ (payload.get("worktrees") or {}).pop(target.slug, None)
+ save_worktree_mapping(repo_root, payload)
+ return 0
+
+
+def cmd_cleanup_stale(args: argparse.Namespace) -> int:
+ repo_root = current_repo_root()
+ payload = load_worktree_mapping(repo_root)
+ stale = []
+ for slug, item in (payload.get("worktrees") or {}).items():
+ path = Path(str(item.get("path", "")))
+ if not path.exists():
+ stale.append((slug, item))
+ if not stale:
+ print("No stale worktree regression environments found.")
+ return 0
+ if not args.yes and not args.dry_run:
+ raise RegressionError("Stale worktree cleanup requires --yes.")
+ runner = Runner(dry_run=args.dry_run)
+ for slug, item in stale:
+ project = str(item.get("project") or project_name_for(WORKTREE_TARGET, slug))
+ instance = str(item.get("instance") or instance_name_for(WORKTREE_TARGET, slug))
+ runner.run(incus("delete", remote_ref(args.remote, instance), "--force", project=project), check=False)
+ runner.run(incus("project", "delete", remote_ref(args.remote, project)), check=False)
+ if not args.dry_run:
+ payload["worktrees"].pop(slug, None)
+ if not args.dry_run:
+ save_worktree_mapping(repo_root, payload)
+ return 0
+
+
+def add_common(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--dry-run", action="store_true", help="Print commands without changing Incus.")
+ parser.add_argument("--remote", help="Optional Incus remote name.")
+
+
+def add_target_args(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--target", choices=sorted(TARGETS), default=MASTER_TARGET)
+ parser.add_argument("--slug", help="Explicit worktree slug for --target worktree.")
+ parser.add_argument("--env-file", type=Path)
+ parser.add_argument("--host-port", type=int, help="Host port for the Web UI proxy.")
+ parser.add_argument("--ui-host", help="Host/interface for the Incus UI proxy. Defaults to REGRESSION_PORT_BIND_HOST or 127.0.0.1 after env loading.")
+ parser.add_argument("--ui-port", type=int, default=DEFAULT_UI_PORT)
+ parser.add_argument("--worktree-port-start", type=int, default=DEFAULT_WORKTREE_PORT_START)
+ parser.add_argument("--worktree-port-end", type=int, default=DEFAULT_WORKTREE_PORT_END)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ doctor = subparsers.add_parser("doctor", help="Check Incus readiness.")
+ add_common(doctor)
+ doctor.set_defaults(func=cmd_doctor)
+
+ init_host = subparsers.add_parser("init-host", help="Optionally initialize Incus and check readiness.")
+ init_host.add_argument("--minimal", action="store_true")
+ add_common(init_host)
+ init_host.set_defaults(func=cmd_init_host)
+
+ build_base = subparsers.add_parser("build-base", help="Build/publish the reusable regression base image.")
+ build_base.add_argument("--image", default=DEFAULT_IMAGE)
+ build_base.add_argument("--source-image", default=DEFAULT_BASE_SOURCE_IMAGE)
+ build_base.add_argument("--temp-instance", default="avibe-regression-base-build")
+ build_base.add_argument("--storage-pool", default=DEFAULT_STORAGE_POOL)
+ build_base.add_argument("--network", default=DEFAULT_NETWORK)
+ add_common(build_base)
+ build_base.set_defaults(func=cmd_build_base)
+
+ up = subparsers.add_parser("up", help="Create/update a regression environment.")
+ add_common(up)
+ add_target_args(up)
+ up.add_argument("--image", default=DEFAULT_IMAGE)
+ up.add_argument("--storage-pool", default=DEFAULT_STORAGE_POOL)
+ up.add_argument("--network", default=DEFAULT_NETWORK)
+ up.add_argument("--cpus", default="4")
+ up.add_argument("--memory", default="8GiB")
+ up.add_argument("--disk", default="80GiB")
+ up.add_argument("--processes", default="8192")
+ up.add_argument("--reset-mode", choices=["none", "config", "all"], default="none")
+ up.add_argument("--clean", action="store_true", help="Remove stale files before source sync.")
+ up.add_argument("--force-deps", action="store_true", help="Force Python dependency refresh.")
+ up.add_argument("--no-build-ui", action="store_true", help="Skip npm ci/build for UI assets.")
+ up.set_defaults(func=cmd_up)
+
+ for name, func in (
+ ("status", cmd_status),
+ ("logs", cmd_logs),
+ ("shell", cmd_shell),
+ ("down", cmd_down),
+ ("delete", cmd_delete),
+ ):
+ sub = subparsers.add_parser(name)
+ add_common(sub)
+ add_target_args(sub)
+ if name == "delete":
+ sub.add_argument("--yes", action="store_true")
+ sub.set_defaults(func=func)
+
+ cleanup = subparsers.add_parser("cleanup-stale", help="Delete environments for missing worktree paths.")
+ add_common(cleanup)
+ cleanup.add_argument("--yes", action="store_true")
+ cleanup.set_defaults(func=cmd_cleanup_stale)
+ return parser
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ try:
+ return args.func(args)
+ except RegressionError as exc:
+ print(str(exc), file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.py
new file mode 100644
index 000000000..7555a9372
--- /dev/null
+++ b/scripts/incus_regression_supervisor.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Run Avibe service + Web UI inside the Incus regression systemd service."""
+
+from __future__ import annotations
+
+import signal
+import sys
+import time
+
+from config import paths
+from config.v2_config import V2Config
+from vibe import runtime
+
+
+def _config() -> V2Config:
+ runtime.ensure_dirs()
+ return runtime.ensure_config()
+
+
+def main() -> int:
+ stopping = False
+
+ def request_stop(signum, frame): # noqa: ANN001
+ nonlocal stopping
+ stopping = True
+
+ signal.signal(signal.SIGTERM, request_stop)
+ signal.signal(signal.SIGINT, request_stop)
+
+ config = _config()
+ service_pid = runtime.start_service(wait_for_ready=False)
+ bind_host = runtime.effective_ui_bind_host(config)
+ ui_pid = runtime.start_ui(bind_host, config.ui.setup_port)
+
+ if runtime.service_pid_recorded(service_pid):
+ runtime.write_status("running", "incus regression started", service_pid, ui_pid)
+ elif runtime.wait_for_service_pid(service_pid, timeout=runtime.SERVICE_SLOW_START_TIMEOUT_SECONDS):
+ runtime.write_status("running", "incus regression started", service_pid, ui_pid)
+ else:
+ runtime.write_status("error", "service did not become ready", service_pid, ui_pid)
+ runtime.stop_ui()
+ runtime.stop_service()
+ return 1
+
+ while not stopping:
+ current_ui_pid = ui_pid
+ ui_pid_path = paths.get_runtime_ui_pid_path()
+ if ui_pid_path.exists():
+ try:
+ current_ui_pid = int(ui_pid_path.read_text(encoding="utf-8").strip())
+ except (OSError, ValueError):
+ current_ui_pid = 0
+ if not current_ui_pid or not runtime.pid_alive(current_ui_pid):
+ config = _config()
+ ui_pid = runtime.start_ui(runtime.effective_ui_bind_host(config), config.ui.setup_port)
+ runtime.write_status("running", "ui restarted in incus regression", service_pid, ui_pid)
+ if not runtime.pid_alive(service_pid):
+ runtime.write_status("error", "service exited in incus regression", service_pid, ui_pid)
+ runtime.stop_ui()
+ return 1
+ time.sleep(1)
+
+ runtime.stop_ui()
+ runtime.stop_service()
+ runtime.write_status("stopped", "incus regression stopped")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.py
new file mode 100755
index 000000000..d9d84f7b2
--- /dev/null
+++ b/scripts/prepare_regression.py
@@ -0,0 +1,750 @@
+#!/usr/bin/env python3
+"""Prepare generated config/state for the unified Incus regression environment.
+
+Generates a single config.json with all four IM platforms enabled and all
+three agent backends configured, plus per-channel routing in settings.json.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import sqlite3
+import sys
+from pathlib import Path
+
+
+PLATFORM_DEFS = {
+ "slack": {
+ "platform": "slack",
+ "channel_env": "REGRESSION_SLACK_CHANNEL",
+ "backend_env": "REGRESSION_SLACK_BACKEND",
+ "required_envs": (
+ "REGRESSION_SLACK_BOT_TOKEN",
+ "REGRESSION_SLACK_APP_TOKEN",
+ ),
+ },
+ "discord": {
+ "platform": "discord",
+ "channel_env": "REGRESSION_DISCORD_CHANNEL",
+ "backend_env": "REGRESSION_DISCORD_BACKEND",
+ "required_envs": ("REGRESSION_DISCORD_BOT_TOKEN",),
+ },
+ "feishu": {
+ "platform": "lark",
+ "channel_env": "REGRESSION_FEISHU_CHAT_ID",
+ "backend_env": "REGRESSION_FEISHU_BACKEND",
+ "required_envs": (
+ "REGRESSION_FEISHU_APP_ID",
+ "REGRESSION_FEISHU_APP_SECRET",
+ ),
+ },
+ "wechat": {
+ "platform": "wechat",
+ "channel_env": "REGRESSION_WECHAT_CHANNEL",
+ "backend_env": "REGRESSION_WECHAT_BACKEND",
+ "required_envs": (), # bot_token obtained via QR login, not env
+ },
+}
+
+SUPPORTED_BACKENDS = {"opencode", "claude", "codex"}
+RESET_MODES = {"none", "config", "all"}
+CONTAINER_HOME = Path("/home/avibe")
+CONTAINER_AVIBE_HOME = CONTAINER_HOME / ".avibe"
+DEFAULT_CWD = str(CONTAINER_AVIBE_HOME / "workdir")
+CONTAINER_OPENCODE_CLI = "/usr/local/bin/opencode"
+ENV_PREFIX = "REGRESSION_"
+LEGACY_ENV_PREFIX = "THREE_REGRESSION_"
+
+
+def _legacy_key(key: str) -> str | None:
+ if not key.startswith(ENV_PREFIX):
+ return None
+ return LEGACY_ENV_PREFIX + key[len(ENV_PREFIX):]
+
+
+def _env(key: str, default: str = "") -> str:
+ value = os.environ.get(key)
+ if value is None:
+ legacy_key = _legacy_key(key)
+ if legacy_key:
+ value = os.environ.get(legacy_key)
+ if value is None:
+ value = default
+ return value.strip()
+
+
+def _optional(key: str) -> str | None:
+ value = _env(key)
+ return value or None
+
+
+def _parse_bool(value: str | None, default: bool = False) -> bool:
+ if value is None or value == "":
+ return default
+ return value.strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _parse_csv(value: str | None) -> list[str] | None:
+ if value is None:
+ return None
+ items = [item.strip() for item in value.split(",") if item.strip()]
+ return items or None
+
+
+def _require_envs(keys: tuple[str, ...]) -> None:
+ missing = [key for key in keys if not _env(key)]
+ if missing:
+ joined = ", ".join(missing)
+ raise SystemExit(f"Missing required environment variables: {joined}")
+
+
+def _platform_prefix(name: str) -> str:
+ return f"REGRESSION_{name.upper()}"
+
+
+def _build_routing(name: str) -> dict:
+ prefix = _platform_prefix(name)
+ backend = _env(f"{prefix}_BACKEND")
+ if backend and backend not in SUPPORTED_BACKENDS:
+ allowed = ", ".join(sorted(SUPPORTED_BACKENDS))
+ raise SystemExit(f"{prefix}_BACKEND must be one of: {allowed}")
+
+ return {
+ "agent_backend": backend or None,
+ "opencode_agent": _optional(f"{prefix}_OPENCODE_AGENT"),
+ "opencode_model": _optional(f"{prefix}_OPENCODE_MODEL"),
+ "opencode_reasoning_effort": _optional(f"{prefix}_OPENCODE_REASONING_EFFORT"),
+ "claude_agent": _optional(f"{prefix}_CLAUDE_AGENT"),
+ "claude_model": _optional(f"{prefix}_CLAUDE_MODEL"),
+ "codex_agent": _optional(f"{prefix}_CODEX_AGENT"),
+ "codex_model": _optional(f"{prefix}_CODEX_MODEL"),
+ "codex_reasoning_effort": _optional(f"{prefix}_CODEX_REASONING_EFFORT"),
+ }
+
+
+def _default_cwd() -> str:
+ return _normalize_stale_container_path(_env("REGRESSION_DEFAULT_CWD", DEFAULT_CWD))
+
+
+def _ui_host() -> str:
+ return _env("REGRESSION_UI_HOST", "127.0.0.1")
+
+
+def _build_slack_payload() -> dict:
+ prefix = _platform_prefix("slack")
+ require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
+ return {
+ "bot_token": _env("REGRESSION_SLACK_BOT_TOKEN"),
+ "app_token": _env("REGRESSION_SLACK_APP_TOKEN") or None,
+ "signing_secret": None,
+ "team_id": None,
+ "team_name": None,
+ "app_id": None,
+ "require_mention": require_mention,
+ }
+
+
+def _build_discord_payload() -> dict:
+ prefix = _platform_prefix("discord")
+ require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
+ return {
+ "bot_token": _env("REGRESSION_DISCORD_BOT_TOKEN"),
+ "application_id": None,
+ "require_mention": require_mention,
+ }
+
+
+def _build_lark_payload() -> dict:
+ prefix = _platform_prefix("feishu")
+ require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
+ return {
+ "app_id": _env("REGRESSION_FEISHU_APP_ID"),
+ "app_secret": _env("REGRESSION_FEISHU_APP_SECRET"),
+ "require_mention": require_mention,
+ "domain": _env("REGRESSION_FEISHU_DOMAIN", "feishu"),
+ }
+
+
+def _build_wechat_payload() -> dict:
+ prefix = _platform_prefix("wechat")
+ require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
+ return {
+ "bot_token": _env("REGRESSION_WECHAT_BOT_TOKEN"),
+ "base_url": _env("REGRESSION_WECHAT_BASE_URL", "https://ilinkai.weixin.qq.com"),
+ "cdn_base_url": _env("REGRESSION_WECHAT_CDN_BASE_URL", "https://novac2c.cdn.weixin.qq.com/c2c"),
+ "require_mention": require_mention,
+ }
+
+
+def _default_backend() -> str:
+ backend = _env("REGRESSION_DEFAULT_BACKEND", "opencode")
+ if backend not in SUPPORTED_BACKENDS:
+ allowed = ", ".join(sorted(SUPPORTED_BACKENDS))
+ raise SystemExit(f"REGRESSION_DEFAULT_BACKEND must be one of: {allowed}")
+ return backend
+
+
+def _build_config_payload() -> dict:
+ """Build a unified config.json with all four platforms and all three backends."""
+ return {
+ "platforms": {
+ "enabled": ["slack", "discord", "lark", "wechat"],
+ "primary": "slack",
+ },
+ "platform": "slack",
+ "mode": "self_host",
+ "version": "v2",
+ "slack": _build_slack_payload(),
+ "discord": _build_discord_payload(),
+ "lark": _build_lark_payload(),
+ "wechat": _build_wechat_payload(),
+ "runtime": {
+ "default_cwd": _default_cwd(),
+ "log_level": _env("REGRESSION_LOG_LEVEL", "INFO"),
+ },
+ "agents": {
+ "default_backend": _default_backend(),
+ "opencode": {
+ "enabled": True,
+ "cli_path": CONTAINER_OPENCODE_CLI,
+ "default_agent": _optional("REGRESSION_OPENCODE_AGENT"),
+ "default_model": _optional("REGRESSION_OPENCODE_MODEL") or "gpt-5.4",
+ "default_reasoning_effort": _optional("REGRESSION_OPENCODE_REASONING_EFFORT"),
+ "error_retry_limit": 1,
+ "default_provider": _optional("REGRESSION_OPENCODE_DEFAULT_PROVIDER") or "openai",
+ },
+ "claude": {
+ "enabled": True,
+ "cli_path": "claude",
+ "default_model": _optional("REGRESSION_CLAUDE_MODEL"),
+ },
+ "codex": {
+ "enabled": True,
+ "cli_path": "codex",
+ "default_model": _optional("REGRESSION_CODEX_MODEL"),
+ },
+ },
+ "gateway": None,
+ "ui": {
+ "setup_host": _ui_host(),
+ "setup_port": 5123,
+ "open_browser": False,
+ },
+ "update": {
+ "auto_update": False,
+ "check_interval_minutes": 0,
+ "idle_minutes": 30,
+ "notify_admins": False,
+ },
+ "ack_mode": "reaction",
+ "show_duration": True,
+ "include_time_info": True,
+ "include_user_info": True,
+ "reply_enhancements": True,
+ "language": _env("REGRESSION_LANGUAGE", "en"),
+ }
+
+
+def _build_settings_payload() -> dict:
+ """Build a unified settings.json with per-channel routing for every platform."""
+ channel_scopes: dict[str, dict] = {}
+ guild_scopes: dict[str, dict] = {}
+ guild_policy_scopes: dict[str, dict] = {}
+
+ for name, pdef in PLATFORM_DEFS.items():
+ platform_key = pdef["platform"]
+ channel_id = _env(pdef["channel_env"])
+ routing = _build_routing(name)
+ scope: dict = {}
+
+ if channel_id and routing["agent_backend"]:
+ prefix = _platform_prefix(name)
+ scope[channel_id] = {
+ "enabled": True,
+ "show_message_types": ["assistant"],
+ "custom_cwd": _default_cwd(),
+ "routing": routing,
+ "require_mention": _parse_bool(
+ _env(f"{prefix}_REQUIRE_MENTION"),
+ default=False,
+ ),
+ }
+
+ channel_scopes[platform_key] = scope
+
+ discord_allowlist = _parse_csv(_optional("REGRESSION_DISCORD_GUILD_ALLOWLIST")) or []
+ discord_denylist = _parse_csv(_optional("REGRESSION_DISCORD_GUILD_DENYLIST")) or []
+ if discord_allowlist or discord_denylist:
+ guild_scopes["discord"] = {
+ guild_id: {"enabled": True}
+ for guild_id in discord_allowlist
+ }
+ for guild_id in discord_denylist:
+ guild_scopes["discord"][guild_id] = {"enabled": False}
+ guild_policy_scopes["discord"] = {
+ "default_enabled": not bool(discord_allowlist),
+ }
+
+ return {
+ "schema_version": 5,
+ "scopes": {
+ "channel": channel_scopes,
+ "guild": guild_scopes,
+ "guild_policy": guild_policy_scopes,
+ "user": {},
+ },
+ "bind_codes": [],
+ }
+
+
+def _write_json(path: Path, payload: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+
+
+def _write_text(path: Path, content: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content, encoding="utf-8")
+
+
+def _ensure_file_path(path: Path, default_content: str) -> None:
+ """Ensure a bind-mounted file path did not get created as a directory."""
+ if path.exists() and path.is_dir():
+ shutil.rmtree(path)
+ if not path.exists():
+ _write_text(path, default_content)
+
+
+def _home_root(output_root: Path) -> Path:
+ return output_root / "home"
+
+
+def _avibe_home(output_root: Path) -> Path:
+ return _home_root(output_root) / ".avibe"
+
+
+def _active_vibe_dir(output_root: Path) -> Path:
+ return _avibe_home(output_root)
+
+
+def _agent_home(output_root: Path) -> Path:
+ return _home_root(output_root)
+
+
+def _normalize_stale_container_path(value: str | None) -> str:
+ if not value:
+ return value or ""
+ prefix_replacements = (
+ ("/data/vibe_remote", str(CONTAINER_AVIBE_HOME)),
+ ("/root/.avibe", str(CONTAINER_AVIBE_HOME)),
+ ("/root/.vibe_remote", str(CONTAINER_AVIBE_HOME)),
+ ("/root", str(CONTAINER_HOME)),
+ )
+ normalized = value
+ for old, new in prefix_replacements:
+ if normalized == old:
+ return new
+ if normalized.startswith(old + "/"):
+ return new + normalized[len(old):]
+ for old, new in prefix_replacements[:-1]:
+ normalized = normalized.replace(old + "/", new + "/")
+ return normalized
+
+
+def _rewrite_json_stale_container_paths(value):
+ if isinstance(value, dict):
+ return {
+ _normalize_stale_container_path(key) if isinstance(key, str) else key: _rewrite_json_stale_container_paths(
+ item
+ )
+ for key, item in value.items()
+ }
+ if isinstance(value, list):
+ return [_rewrite_json_stale_container_paths(item) for item in value]
+ if isinstance(value, str):
+ return _normalize_stale_container_path(value)
+ return value
+
+
+def _rewrite_json_file_stale_container_paths(path: Path) -> None:
+ if not path.exists() or not path.is_file():
+ return
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ return
+ _write_json(path, _rewrite_json_stale_container_paths(payload))
+
+
+def _rewrite_sqlite_stale_container_paths(db_path: Path) -> None:
+ if not db_path.exists() or not db_path.is_file():
+ return
+ with sqlite3.connect(str(db_path)) as conn:
+ table_columns = {
+ "agent_sessions": ("workdir",),
+ "scope_settings": ("workdir", "settings_json"),
+ "runtime_records": ("workdir", "payload_json"),
+ "run_definitions": ("cwd", "command_json", "metadata_json"),
+ "agent_runs": ("message_payload_json", "result_payload_json", "metadata_json"),
+ "media_objects": ("local_path",),
+ }
+ for table, columns in table_columns.items():
+ existing = {
+ row[1]
+ for row in conn.execute(f'pragma table_info("{table}")').fetchall()
+ }
+ for column in columns:
+ if column not in existing:
+ continue
+ rows = conn.execute(
+ f'select rowid, "{column}" from "{table}" where "{column}" is not null'
+ ).fetchall()
+ for rowid, value in rows:
+ if not isinstance(value, str):
+ continue
+ next_value = _normalize_stale_container_path(value)
+ if column.endswith("_json"):
+ try:
+ next_value = json.dumps(
+ _rewrite_json_stale_container_paths(json.loads(value)),
+ separators=(",", ":"),
+ )
+ except json.JSONDecodeError:
+ next_value = _normalize_stale_container_path(value)
+ if next_value != value:
+ conn.execute(
+ f'update "{table}" set "{column}" = ? where rowid = ?',
+ (next_value, rowid),
+ )
+ conn.commit()
+
+
+def _ensure_shared_home(output_root: Path, reset_mode: str = "none") -> Path:
+ if reset_mode == "all":
+ home_root = _home_root(output_root)
+ for relative in (
+ ".claude",
+ ".claude.json",
+ ".codex",
+ ".config/opencode",
+ ".local/share/opencode",
+ ):
+ target = home_root / relative
+ if target.exists() or target.is_symlink():
+ if target.is_dir() and not target.is_symlink():
+ shutil.rmtree(target)
+ else:
+ target.unlink()
+
+ shared_root = _agent_home(output_root)
+ for subdir in (
+ ".claude",
+ ".codex",
+ ".config/opencode",
+ ".local/share/opencode",
+ ):
+ (shared_root / subdir).mkdir(parents=True, exist_ok=True)
+ return shared_root
+
+
+def _validate_reset_mode(reset_mode: str) -> None:
+ if reset_mode not in RESET_MODES:
+ allowed = ", ".join(sorted(RESET_MODES))
+ raise SystemExit(f"reset_mode must be one of: {allowed}")
+
+
+def _ensure_vibe_dir(vibe_dir: Path, reset_mode: str = "none") -> None:
+ _validate_reset_mode(reset_mode)
+
+ if reset_mode == "all" and vibe_dir.exists():
+ shutil.rmtree(vibe_dir)
+ elif reset_mode == "config" and vibe_dir.exists():
+ for subdir in ("config", "state", "runtime"):
+ target = vibe_dir / subdir
+ if target.exists():
+ shutil.rmtree(target)
+
+ for subdir in ("config", "state", "logs", "runtime", "attachments", "workdir"):
+ (vibe_dir / subdir).mkdir(parents=True, exist_ok=True)
+
+
+def _build_claude_settings_payload() -> dict:
+ auth_token = _optional("REGRESSION_CLAUDE_AUTH_TOKEN") or _env("ANTHROPIC_API_KEY")
+ payload = {
+ "env": {
+ "ANTHROPIC_BASE_URL": _optional("REGRESSION_CLAUDE_BASE_URL")
+ or _optional("ANTHROPIC_BASE_URL")
+ or "",
+ "ANTHROPIC_AUTH_TOKEN": auth_token,
+ "CLAUDE_CODE_ATTRIBUTION_HEADER": _env("REGRESSION_CLAUDE_ATTRIBUTION_HEADER", "0"),
+ }
+ }
+ return payload
+
+
+def _relay_openai_base_from_anthropic_base() -> str | None:
+ anthropic_base = _optional("ANTHROPIC_BASE_URL")
+ if not anthropic_base:
+ return None
+ return anthropic_base.rstrip("/") + "/v1"
+
+
+def _openai_base_url(*extra_keys: str) -> str | None:
+ for key in (*extra_keys, "OPENAI_API_BASE", "OPENAI_BASE_URL"):
+ value = _optional(key)
+ if value:
+ return value
+ return _relay_openai_base_from_anthropic_base()
+
+
+def _build_codex_config_toml() -> str:
+ model_provider = _env("REGRESSION_CODEX_MODEL_PROVIDER", "OpenAI")
+ model = _env("REGRESSION_CODEX_MODEL", "gpt-5.4")
+ review_model = _env("REGRESSION_CODEX_REVIEW_MODEL", model)
+ reasoning_effort = _env("REGRESSION_CODEX_REASONING_EFFORT", "xhigh")
+ base_url = _openai_base_url("REGRESSION_CODEX_BASE_URL")
+ disable_storage = str(
+ _parse_bool(_optional("REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE"), default=True)
+ ).lower()
+ responses_websockets_v2 = str(
+ _parse_bool(_optional("REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2"), default=False)
+ ).lower()
+ suppress_unstable_warning = str(
+ _parse_bool(_optional("REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING"), default=True)
+ ).lower()
+ provider_lines = [
+ "[model_providers.OpenAI]",
+ 'name = "OpenAI"',
+ ]
+ if base_url:
+ provider_lines.append(f'base_url = "{base_url}"')
+ provider_lines.extend(
+ [
+ 'wire_api = "responses"',
+ f"supports_websockets = {str(not bool(base_url)).lower()}",
+ "requires_openai_auth = true",
+ ]
+ )
+
+ return (
+ f'model_provider = "{model_provider}"\n'
+ f'model = "{model}"\n'
+ f'review_model = "{review_model}"\n'
+ f'model_reasoning_effort = "{reasoning_effort}"\n'
+ f"disable_response_storage = {disable_storage}\n"
+ f"suppress_unstable_features_warning = {suppress_unstable_warning}\n"
+ 'network_access = "enabled"\n'
+ "windows_wsl_setup_acknowledged = true\n"
+ f"model_context_window = {_env('REGRESSION_CODEX_CONTEXT_WINDOW', '1000000')}\n"
+ f"model_auto_compact_token_limit = {_env('REGRESSION_CODEX_AUTO_COMPACT_TOKEN_LIMIT', '900000')}\n\n"
+ + "\n".join(provider_lines)
+ + "\n\n"
+ "[features]\n"
+ f"responses_websockets_v2 = {responses_websockets_v2}\n"
+ )
+
+
+def _build_codex_auth_payload() -> dict:
+ return {
+ "OPENAI_API_KEY": _optional("REGRESSION_CODEX_OPENAI_API_KEY") or _env("OPENAI_API_KEY"),
+ }
+
+
+def _build_opencode_payload() -> dict:
+ openai_base = _openai_base_url("REGRESSION_OPENCODE_OPENAI_BASE_URL")
+ anthropic_base = _optional("REGRESSION_OPENCODE_ANTHROPIC_BASE_URL")
+ if not anthropic_base:
+ anthropic_base = _optional("ANTHROPIC_BASE_URL")
+ openai_key = _optional("REGRESSION_OPENCODE_OPENAI_API_KEY") or _env("OPENAI_API_KEY")
+ anthropic_key = _optional("REGRESSION_OPENCODE_ANTHROPIC_API_KEY") or _env("ANTHROPIC_API_KEY")
+ openai_options = {"apiKey": openai_key}
+ if openai_base:
+ openai_options["baseURL"] = openai_base
+ anthropic_options = {"apiKey": anthropic_key}
+ if anthropic_base:
+ anthropic_options["baseURL"] = anthropic_base
+
+ return {
+ "permission": "allow",
+ "provider": {
+ "openai": {
+ "options": openai_options,
+ "models": {
+ "gpt-5.4": {
+ "name": "GPT-5.4",
+ "options": {"store": False},
+ "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
+ },
+ "gpt-5.3-codex-spark": {
+ "name": "GPT-5.3 Codex Spark",
+ "options": {"store": False},
+ "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
+ },
+ "gpt-5.3-codex": {
+ "name": "GPT-5.3 Codex",
+ "options": {"store": False},
+ "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
+ },
+ },
+ },
+ "anthropic": {
+ "options": anthropic_options,
+ "npm": "@ai-sdk/anthropic",
+ },
+ },
+ "agent": {
+ "build": {"options": {"store": False}},
+ "plan": {"options": {"store": False}},
+ },
+ "$schema": "https://opencode.ai/config.json",
+ }
+
+
+def _shared_agent_config_paths(output_root: Path) -> tuple[Path, ...]:
+ shared_root = _agent_home(output_root)
+ return (
+ shared_root / ".claude" / "settings.json",
+ shared_root / ".claude.json",
+ shared_root / ".codex" / "config.toml",
+ shared_root / ".codex" / "auth.json",
+ shared_root / ".config" / "opencode" / "opencode.json",
+ )
+
+
+def _should_write_shared_agent_configs(output_root: Path, *, reset_mode: str) -> bool:
+ return reset_mode in {"config", "all"} or any(
+ not path.is_file() for path in _shared_agent_config_paths(output_root)
+ )
+
+
+def _repair_shared_agent_state_files(output_root: Path, *, reset_mode: str) -> None:
+ shared_root = _ensure_shared_home(output_root, reset_mode=reset_mode)
+ _ensure_file_path(shared_root / ".claude.json", "{}\n")
+
+
+def _write_shared_agent_configs(output_root: Path, *, reset_mode: str) -> None:
+ shared_root = _ensure_shared_home(output_root, reset_mode=reset_mode)
+ _write_json(shared_root / ".claude" / "settings.json", _build_claude_settings_payload())
+ claude_state_path = shared_root / ".claude.json"
+ _ensure_file_path(claude_state_path, "{}\n")
+ _write_text(shared_root / ".codex" / "config.toml", _build_codex_config_toml())
+ _write_json(shared_root / ".codex" / "auth.json", _build_codex_auth_payload())
+ _write_json(shared_root / ".config" / "opencode" / "opencode.json", _build_opencode_payload())
+
+
+def _normalize_config_payload(path: Path) -> None:
+ if not path.is_file():
+ return
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return
+ if not isinstance(payload, dict):
+ return
+
+ agents = payload.get("agents")
+ if not isinstance(agents, dict):
+ return
+ opencode = agents.get("opencode")
+ if not isinstance(opencode, dict):
+ return
+ cli_path = str(opencode.get("cli_path") or "")
+ legacy_home_cli = str(CONTAINER_HOME / ".opencode" / "bin" / "opencode")
+ if cli_path not in {"", "opencode", legacy_home_cli}:
+ return
+
+ opencode["cli_path"] = CONTAINER_OPENCODE_CLI
+ _write_json(path, payload)
+
+
+def _normalize_existing_state(vibe_dir: Path) -> None:
+ config_path = vibe_dir / "config" / "config.json"
+ _rewrite_json_file_stale_container_paths(config_path)
+ _normalize_config_payload(config_path)
+ _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "settings.json")
+ _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "sessions.json")
+ _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "scheduled_tasks.json")
+ _rewrite_sqlite_stale_container_paths(vibe_dir / "state" / "vibe.sqlite")
+
+
+def prepare(output_root: Path, reset_mode: str = "none") -> None:
+ _validate_reset_mode(reset_mode)
+ home_root = _home_root(output_root)
+ if reset_mode == "all" and (home_root.exists() or home_root.is_symlink()):
+ if home_root.is_dir() and not home_root.is_symlink():
+ shutil.rmtree(home_root)
+ else:
+ home_root.unlink()
+ home_root.mkdir(parents=True, exist_ok=True)
+
+ vibe_dir = _active_vibe_dir(output_root)
+ config_path = vibe_dir / "config" / "config.json"
+ settings_path = vibe_dir / "state" / "settings.json"
+ sessions_path = vibe_dir / "state" / "sessions.json"
+ needs_config = reset_mode in {"config", "all"} or not config_path.exists()
+ needs_settings = reset_mode in {"config", "all"} or not settings_path.exists()
+ needs_sessions = reset_mode in {"config", "all"} or not sessions_path.exists()
+ _repair_shared_agent_state_files(output_root, reset_mode=reset_mode)
+ needs_shared_agent_configs = _should_write_shared_agent_configs(output_root, reset_mode=reset_mode)
+
+ if needs_shared_agent_configs:
+ _require_envs(("ANTHROPIC_API_KEY", "OPENAI_API_KEY"))
+
+ if needs_config or needs_settings:
+ for pdef in PLATFORM_DEFS.values():
+ _require_envs(pdef["required_envs"])
+
+ if needs_shared_agent_configs:
+ _write_shared_agent_configs(output_root, reset_mode=reset_mode)
+
+ _ensure_vibe_dir(vibe_dir, reset_mode=reset_mode)
+
+ if needs_config:
+ _write_json(config_path, _build_config_payload())
+ if needs_settings:
+ _write_json(settings_path, _build_settings_payload())
+ if needs_sessions:
+ _write_json(sessions_path, {})
+ if not needs_config or not needs_settings:
+ _normalize_existing_state(vibe_dir)
+
+ summary_lines: list[str] = []
+ for name, pdef in PLATFORM_DEFS.items():
+ channel = _env(pdef["channel_env"]) or "(configure later in UI)"
+ backend = _env(pdef["backend_env"]) or _default_backend()
+ summary_lines.append(f" {name}: platform={pdef['platform']} channel={channel} backend={backend}")
+
+ print(f"Prepared unified regression state under {vibe_dir}")
+ print("Platform routing:")
+ print("\n".join(summary_lines))
+ print(f"State: {reset_mode if reset_mode != 'none' else 'preserved'}")
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--output-root",
+ default=str(Path(".runtime") / "incus-regression" / "seed"),
+ help="Directory that will hold generated state",
+ )
+ parser.add_argument(
+ "--reset-mode",
+ choices=sorted(RESET_MODES),
+ default="none",
+ help="Reset scope before generating files: none, config, or all",
+ )
+ args = parser.parse_args()
+
+ try:
+ prepare(Path(args.output_root).resolve(), reset_mode=args.reset_mode)
+ except SystemExit as exc:
+ print(str(exc), file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.py
index ea9e1cb52..7ba2aba2c 100755
--- a/scripts/prepare_three_regression.py
+++ b/scripts/prepare_three_regression.py
@@ -1,710 +1,7 @@
#!/usr/bin/env python3
-"""Prepare generated config/state for the unified regression container.
+"""Compatibility entrypoint for the renamed regression state preparer."""
-Generates a single config.json with all four IM platforms enabled and all
-three agent backends configured, plus per-channel routing in settings.json.
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import os
-import shutil
-import sqlite3
-import sys
-from pathlib import Path
-
-
-PLATFORM_DEFS = {
- "slack": {
- "platform": "slack",
- "channel_env": "THREE_REGRESSION_SLACK_CHANNEL",
- "backend_env": "THREE_REGRESSION_SLACK_BACKEND",
- "required_envs": (
- "THREE_REGRESSION_SLACK_BOT_TOKEN",
- "THREE_REGRESSION_SLACK_APP_TOKEN",
- ),
- },
- "discord": {
- "platform": "discord",
- "channel_env": "THREE_REGRESSION_DISCORD_CHANNEL",
- "backend_env": "THREE_REGRESSION_DISCORD_BACKEND",
- "required_envs": ("THREE_REGRESSION_DISCORD_BOT_TOKEN",),
- },
- "feishu": {
- "platform": "lark",
- "channel_env": "THREE_REGRESSION_FEISHU_CHAT_ID",
- "backend_env": "THREE_REGRESSION_FEISHU_BACKEND",
- "required_envs": (
- "THREE_REGRESSION_FEISHU_APP_ID",
- "THREE_REGRESSION_FEISHU_APP_SECRET",
- ),
- },
- "wechat": {
- "platform": "wechat",
- "channel_env": "THREE_REGRESSION_WECHAT_CHANNEL",
- "backend_env": "THREE_REGRESSION_WECHAT_BACKEND",
- "required_envs": (), # bot_token obtained via QR login, not env
- },
-}
-
-SUPPORTED_BACKENDS = {"opencode", "claude", "codex"}
-RESET_MODES = {"none", "config", "all"}
-CONTAINER_HOME = Path("/home/avibe")
-CONTAINER_AVIBE_HOME = CONTAINER_HOME / ".avibe"
-DEFAULT_CWD = str(CONTAINER_AVIBE_HOME / "workdir")
-CONTAINER_OPENCODE_CLI = "/usr/local/bin/opencode"
-
-
-def _env(key: str, default: str = "") -> str:
- return os.environ.get(key, default).strip()
-
-
-def _optional(key: str) -> str | None:
- value = _env(key)
- return value or None
-
-
-def _parse_bool(value: str | None, default: bool = False) -> bool:
- if value is None or value == "":
- return default
- return value.strip().lower() in {"1", "true", "yes", "on"}
-
-
-def _parse_csv(value: str | None) -> list[str] | None:
- if value is None:
- return None
- items = [item.strip() for item in value.split(",") if item.strip()]
- return items or None
-
-
-def _require_envs(keys: tuple[str, ...]) -> None:
- missing = [key for key in keys if not _env(key)]
- if missing:
- joined = ", ".join(missing)
- raise SystemExit(f"Missing required environment variables: {joined}")
-
-
-def _platform_prefix(name: str) -> str:
- return f"THREE_REGRESSION_{name.upper()}"
-
-
-def _build_routing(name: str) -> dict:
- prefix = _platform_prefix(name)
- backend = _env(f"{prefix}_BACKEND")
- if backend and backend not in SUPPORTED_BACKENDS:
- allowed = ", ".join(sorted(SUPPORTED_BACKENDS))
- raise SystemExit(f"{prefix}_BACKEND must be one of: {allowed}")
-
- return {
- "agent_backend": backend or None,
- "opencode_agent": _optional(f"{prefix}_OPENCODE_AGENT"),
- "opencode_model": _optional(f"{prefix}_OPENCODE_MODEL"),
- "opencode_reasoning_effort": _optional(f"{prefix}_OPENCODE_REASONING_EFFORT"),
- "claude_agent": _optional(f"{prefix}_CLAUDE_AGENT"),
- "claude_model": _optional(f"{prefix}_CLAUDE_MODEL"),
- "codex_agent": _optional(f"{prefix}_CODEX_AGENT"),
- "codex_model": _optional(f"{prefix}_CODEX_MODEL"),
- "codex_reasoning_effort": _optional(f"{prefix}_CODEX_REASONING_EFFORT"),
- }
-
-
-def _default_cwd() -> str:
- return _normalize_stale_container_path(_env("THREE_REGRESSION_DEFAULT_CWD", DEFAULT_CWD))
-
-
-def _ui_host() -> str:
- return _env("THREE_REGRESSION_UI_HOST", "127.0.0.1")
-
-
-def _build_slack_payload() -> dict:
- prefix = _platform_prefix("slack")
- require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
- return {
- "bot_token": _env("THREE_REGRESSION_SLACK_BOT_TOKEN"),
- "app_token": _env("THREE_REGRESSION_SLACK_APP_TOKEN") or None,
- "signing_secret": None,
- "team_id": None,
- "team_name": None,
- "app_id": None,
- "require_mention": require_mention,
- }
-
-
-def _build_discord_payload() -> dict:
- prefix = _platform_prefix("discord")
- require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
- return {
- "bot_token": _env("THREE_REGRESSION_DISCORD_BOT_TOKEN"),
- "application_id": None,
- "require_mention": require_mention,
- }
-
-
-def _build_lark_payload() -> dict:
- prefix = _platform_prefix("feishu")
- require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
- return {
- "app_id": _env("THREE_REGRESSION_FEISHU_APP_ID"),
- "app_secret": _env("THREE_REGRESSION_FEISHU_APP_SECRET"),
- "require_mention": require_mention,
- "domain": _env("THREE_REGRESSION_FEISHU_DOMAIN", "feishu"),
- }
-
-
-def _build_wechat_payload() -> dict:
- prefix = _platform_prefix("wechat")
- require_mention = _parse_bool(_env(f"{prefix}_REQUIRE_MENTION"), default=False)
- return {
- "bot_token": _env("THREE_REGRESSION_WECHAT_BOT_TOKEN"),
- "base_url": _env("THREE_REGRESSION_WECHAT_BASE_URL", "https://ilinkai.weixin.qq.com"),
- "cdn_base_url": _env("THREE_REGRESSION_WECHAT_CDN_BASE_URL", "https://novac2c.cdn.weixin.qq.com/c2c"),
- "require_mention": require_mention,
- }
-
-
-def _default_backend() -> str:
- backend = _env("THREE_REGRESSION_DEFAULT_BACKEND", "opencode")
- if backend not in SUPPORTED_BACKENDS:
- allowed = ", ".join(sorted(SUPPORTED_BACKENDS))
- raise SystemExit(f"THREE_REGRESSION_DEFAULT_BACKEND must be one of: {allowed}")
- return backend
-
-
-def _build_config_payload() -> dict:
- """Build a unified config.json with all four platforms and all three backends."""
- return {
- "platforms": {
- "enabled": ["slack", "discord", "lark", "wechat"],
- "primary": "slack",
- },
- "platform": "slack",
- "mode": "self_host",
- "version": "v2",
- "slack": _build_slack_payload(),
- "discord": _build_discord_payload(),
- "lark": _build_lark_payload(),
- "wechat": _build_wechat_payload(),
- "runtime": {
- "default_cwd": _default_cwd(),
- "log_level": _env("THREE_REGRESSION_LOG_LEVEL", "INFO"),
- },
- "agents": {
- "default_backend": _default_backend(),
- "opencode": {
- "enabled": True,
- "cli_path": CONTAINER_OPENCODE_CLI,
- "default_agent": _optional("THREE_REGRESSION_OPENCODE_AGENT"),
- "default_model": _optional("THREE_REGRESSION_OPENCODE_MODEL"),
- "default_reasoning_effort": _optional("THREE_REGRESSION_OPENCODE_REASONING_EFFORT"),
- "error_retry_limit": 1,
- },
- "claude": {
- "enabled": True,
- "cli_path": "claude",
- "default_model": _optional("THREE_REGRESSION_CLAUDE_MODEL"),
- },
- "codex": {
- "enabled": True,
- "cli_path": "codex",
- "default_model": _optional("THREE_REGRESSION_CODEX_MODEL"),
- },
- },
- "gateway": None,
- "ui": {
- "setup_host": _ui_host(),
- "setup_port": 5123,
- "open_browser": False,
- },
- "update": {
- "auto_update": False,
- "check_interval_minutes": 0,
- "idle_minutes": 30,
- "notify_admins": False,
- },
- "ack_mode": "reaction",
- "show_duration": True,
- "include_time_info": True,
- "include_user_info": True,
- "reply_enhancements": True,
- "language": _env("THREE_REGRESSION_LANGUAGE", "en"),
- }
-
-
-def _build_settings_payload() -> dict:
- """Build a unified settings.json with per-channel routing for every platform."""
- channel_scopes: dict[str, dict] = {}
- guild_scopes: dict[str, dict] = {}
- guild_policy_scopes: dict[str, dict] = {}
-
- for name, pdef in PLATFORM_DEFS.items():
- platform_key = pdef["platform"]
- channel_id = _env(pdef["channel_env"])
- routing = _build_routing(name)
- scope: dict = {}
-
- if channel_id and routing["agent_backend"]:
- prefix = _platform_prefix(name)
- scope[channel_id] = {
- "enabled": True,
- "show_message_types": ["assistant"],
- "custom_cwd": _default_cwd(),
- "routing": routing,
- "require_mention": _parse_bool(
- _env(f"{prefix}_REQUIRE_MENTION"),
- default=False,
- ),
- }
-
- channel_scopes[platform_key] = scope
-
- discord_allowlist = _parse_csv(_optional("THREE_REGRESSION_DISCORD_GUILD_ALLOWLIST")) or []
- discord_denylist = _parse_csv(_optional("THREE_REGRESSION_DISCORD_GUILD_DENYLIST")) or []
- if discord_allowlist or discord_denylist:
- guild_scopes["discord"] = {
- guild_id: {"enabled": True}
- for guild_id in discord_allowlist
- }
- for guild_id in discord_denylist:
- guild_scopes["discord"][guild_id] = {"enabled": False}
- guild_policy_scopes["discord"] = {
- "default_enabled": not bool(discord_allowlist),
- }
-
- return {
- "schema_version": 5,
- "scopes": {
- "channel": channel_scopes,
- "guild": guild_scopes,
- "guild_policy": guild_policy_scopes,
- "user": {},
- },
- "bind_codes": [],
- }
-
-
-def _write_json(path: Path, payload: dict) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
-
-
-def _write_text(path: Path, content: str) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(content, encoding="utf-8")
-
-
-def _ensure_file_path(path: Path, default_content: str) -> None:
- """Ensure a bind-mounted file path did not get created as a directory."""
- if path.exists() and path.is_dir():
- shutil.rmtree(path)
- if not path.exists():
- _write_text(path, default_content)
-
-
-def _home_root(output_root: Path) -> Path:
- return output_root / "home"
-
-
-def _avibe_home(output_root: Path) -> Path:
- return _home_root(output_root) / ".avibe"
-
-
-def _active_vibe_dir(output_root: Path) -> Path:
- return _avibe_home(output_root)
-
-
-def _agent_home(output_root: Path) -> Path:
- return _home_root(output_root)
-
-
-def _normalize_stale_container_path(value: str | None) -> str:
- if not value:
- return value or ""
- prefix_replacements = (
- ("/data/vibe_remote", str(CONTAINER_AVIBE_HOME)),
- ("/root/.avibe", str(CONTAINER_AVIBE_HOME)),
- ("/root/.vibe_remote", str(CONTAINER_AVIBE_HOME)),
- ("/root", str(CONTAINER_HOME)),
- )
- normalized = value
- for old, new in prefix_replacements:
- if normalized == old:
- return new
- if normalized.startswith(old + "/"):
- return new + normalized[len(old):]
- for old, new in prefix_replacements[:-1]:
- normalized = normalized.replace(old + "/", new + "/")
- return normalized
-
-
-def _rewrite_json_stale_container_paths(value):
- if isinstance(value, dict):
- return {
- _normalize_stale_container_path(key) if isinstance(key, str) else key: _rewrite_json_stale_container_paths(
- item
- )
- for key, item in value.items()
- }
- if isinstance(value, list):
- return [_rewrite_json_stale_container_paths(item) for item in value]
- if isinstance(value, str):
- return _normalize_stale_container_path(value)
- return value
-
-
-def _rewrite_json_file_stale_container_paths(path: Path) -> None:
- if not path.exists() or not path.is_file():
- return
- try:
- payload = json.loads(path.read_text(encoding="utf-8"))
- except json.JSONDecodeError:
- return
- _write_json(path, _rewrite_json_stale_container_paths(payload))
-
-
-def _rewrite_sqlite_stale_container_paths(db_path: Path) -> None:
- if not db_path.exists() or not db_path.is_file():
- return
- with sqlite3.connect(str(db_path)) as conn:
- table_columns = {
- "agent_sessions": ("workdir",),
- "scope_settings": ("workdir", "settings_json"),
- "runtime_records": ("workdir", "payload_json"),
- "run_definitions": ("cwd", "command_json", "metadata_json"),
- "agent_runs": ("message_payload_json", "result_payload_json", "metadata_json"),
- "media_objects": ("local_path",),
- }
- for table, columns in table_columns.items():
- existing = {
- row[1]
- for row in conn.execute(f'pragma table_info("{table}")').fetchall()
- }
- for column in columns:
- if column not in existing:
- continue
- rows = conn.execute(
- f'select rowid, "{column}" from "{table}" where "{column}" is not null'
- ).fetchall()
- for rowid, value in rows:
- if not isinstance(value, str):
- continue
- next_value = _normalize_stale_container_path(value)
- if column.endswith("_json"):
- try:
- next_value = json.dumps(
- _rewrite_json_stale_container_paths(json.loads(value)),
- separators=(",", ":"),
- )
- except json.JSONDecodeError:
- next_value = _normalize_stale_container_path(value)
- if next_value != value:
- conn.execute(
- f'update "{table}" set "{column}" = ? where rowid = ?',
- (next_value, rowid),
- )
- conn.commit()
-
-
-def _ensure_shared_home(output_root: Path, reset_mode: str = "none") -> Path:
- if reset_mode == "all":
- home_root = _home_root(output_root)
- for relative in (
- ".claude",
- ".claude.json",
- ".codex",
- ".config/opencode",
- ".local/share/opencode",
- ):
- target = home_root / relative
- if target.exists() or target.is_symlink():
- if target.is_dir() and not target.is_symlink():
- shutil.rmtree(target)
- else:
- target.unlink()
-
- shared_root = _agent_home(output_root)
- for subdir in (
- ".claude",
- ".codex",
- ".config/opencode",
- ".local/share/opencode",
- ):
- (shared_root / subdir).mkdir(parents=True, exist_ok=True)
- return shared_root
-
-
-def _validate_reset_mode(reset_mode: str) -> None:
- if reset_mode not in RESET_MODES:
- allowed = ", ".join(sorted(RESET_MODES))
- raise SystemExit(f"reset_mode must be one of: {allowed}")
-
-
-def _ensure_vibe_dir(vibe_dir: Path, reset_mode: str = "none") -> None:
- _validate_reset_mode(reset_mode)
-
- if reset_mode == "all" and vibe_dir.exists():
- shutil.rmtree(vibe_dir)
- elif reset_mode == "config" and vibe_dir.exists():
- for subdir in ("config", "state", "runtime"):
- target = vibe_dir / subdir
- if target.exists():
- shutil.rmtree(target)
-
- for subdir in ("config", "state", "logs", "runtime", "attachments", "workdir"):
- (vibe_dir / subdir).mkdir(parents=True, exist_ok=True)
-
-
-def _build_claude_settings_payload() -> dict:
- auth_token = _optional("THREE_REGRESSION_CLAUDE_AUTH_TOKEN") or _env("ANTHROPIC_API_KEY")
- payload = {
- "env": {
- "ANTHROPIC_BASE_URL": _optional("THREE_REGRESSION_CLAUDE_BASE_URL")
- or _optional("ANTHROPIC_BASE_URL")
- or "",
- "ANTHROPIC_AUTH_TOKEN": auth_token,
- "CLAUDE_CODE_ATTRIBUTION_HEADER": _env("THREE_REGRESSION_CLAUDE_ATTRIBUTION_HEADER", "0"),
- }
- }
- return payload
-
-
-def _build_codex_config_toml() -> str:
- model_provider = _env("THREE_REGRESSION_CODEX_MODEL_PROVIDER", "OpenAI")
- model = _env("THREE_REGRESSION_CODEX_MODEL", "gpt-5.4")
- review_model = _env("THREE_REGRESSION_CODEX_REVIEW_MODEL", model)
- reasoning_effort = _env("THREE_REGRESSION_CODEX_REASONING_EFFORT", "xhigh")
- base_url = _optional("THREE_REGRESSION_CODEX_BASE_URL") or _optional("OPENAI_BASE_URL") or ""
- disable_storage = str(
- _parse_bool(_optional("THREE_REGRESSION_CODEX_DISABLE_RESPONSE_STORAGE"), default=True)
- ).lower()
- responses_websockets_v2 = str(
- _parse_bool(_optional("THREE_REGRESSION_CODEX_RESPONSES_WEBSOCKETS_V2"), default=False)
- ).lower()
- suppress_unstable_warning = str(
- _parse_bool(_optional("THREE_REGRESSION_CODEX_SUPPRESS_UNSTABLE_WARNING"), default=True)
- ).lower()
- return (
- f'model_provider = "{model_provider}"\n'
- f'model = "{model}"\n'
- f'review_model = "{review_model}"\n'
- f'model_reasoning_effort = "{reasoning_effort}"\n'
- f"disable_response_storage = {disable_storage}\n"
- f"suppress_unstable_features_warning = {suppress_unstable_warning}\n"
- 'network_access = "enabled"\n'
- "windows_wsl_setup_acknowledged = true\n"
- f"model_context_window = {_env('THREE_REGRESSION_CODEX_CONTEXT_WINDOW', '1000000')}\n"
- f"model_auto_compact_token_limit = {_env('THREE_REGRESSION_CODEX_AUTO_COMPACT_TOKEN_LIMIT', '900000')}\n\n"
- "[model_providers.OpenAI]\n"
- 'name = "OpenAI"\n'
- f'base_url = "{base_url}"\n'
- 'wire_api = "responses"\n'
- "supports_websockets = true\n"
- "requires_openai_auth = true\n\n"
- "[features]\n"
- f"responses_websockets_v2 = {responses_websockets_v2}\n"
- )
-
-
-def _build_codex_auth_payload() -> dict:
- return {
- "OPENAI_API_KEY": _optional("THREE_REGRESSION_CODEX_OPENAI_API_KEY") or _env("OPENAI_API_KEY"),
- }
-
-
-def _build_opencode_payload() -> dict:
- openai_base = _optional("THREE_REGRESSION_OPENCODE_OPENAI_BASE_URL")
- if not openai_base:
- openai_base = _optional("OPENAI_API_BASE") or _optional("OPENAI_BASE_URL") or ""
- anthropic_base = _optional("THREE_REGRESSION_OPENCODE_ANTHROPIC_BASE_URL")
- if not anthropic_base:
- anthropic_base = _optional("ANTHROPIC_BASE_URL") or ""
- openai_key = _optional("THREE_REGRESSION_OPENCODE_OPENAI_API_KEY") or _env("OPENAI_API_KEY")
- anthropic_key = _optional("THREE_REGRESSION_OPENCODE_ANTHROPIC_API_KEY") or _env("ANTHROPIC_API_KEY")
-
- return {
- "permission": "allow",
- "provider": {
- "openai": {
- "options": {
- "baseURL": openai_base,
- "apiKey": openai_key,
- },
- "models": {
- "gpt-5.4": {
- "name": "GPT-5.4",
- "options": {"store": False},
- "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
- },
- "gpt-5.3-codex-spark": {
- "name": "GPT-5.3 Codex Spark",
- "options": {"store": False},
- "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
- },
- "gpt-5.3-codex": {
- "name": "GPT-5.3 Codex",
- "options": {"store": False},
- "variants": {"low": {}, "medium": {}, "high": {}, "xhigh": {}},
- },
- },
- },
- "anthropic": {
- "options": {
- "baseURL": anthropic_base,
- "apiKey": anthropic_key,
- },
- "npm": "@ai-sdk/anthropic",
- },
- },
- "agent": {
- "build": {"options": {"store": False}},
- "plan": {"options": {"store": False}},
- },
- "$schema": "https://opencode.ai/config.json",
- }
-
-
-def _shared_agent_config_paths(output_root: Path) -> tuple[Path, ...]:
- shared_root = _agent_home(output_root)
- return (
- shared_root / ".claude" / "settings.json",
- shared_root / ".claude.json",
- shared_root / ".codex" / "config.toml",
- shared_root / ".codex" / "auth.json",
- shared_root / ".config" / "opencode" / "opencode.json",
- )
-
-
-def _should_write_shared_agent_configs(output_root: Path, *, reset_mode: str) -> bool:
- return reset_mode in {"config", "all"} or any(
- not path.is_file() for path in _shared_agent_config_paths(output_root)
- )
-
-
-def _repair_shared_agent_state_files(output_root: Path, *, reset_mode: str) -> None:
- shared_root = _ensure_shared_home(output_root, reset_mode=reset_mode)
- _ensure_file_path(shared_root / ".claude.json", "{}\n")
-
-
-def _write_shared_agent_configs(output_root: Path, *, reset_mode: str) -> None:
- shared_root = _ensure_shared_home(output_root, reset_mode=reset_mode)
- _write_json(shared_root / ".claude" / "settings.json", _build_claude_settings_payload())
- claude_state_path = shared_root / ".claude.json"
- _ensure_file_path(claude_state_path, "{}\n")
- _write_text(shared_root / ".codex" / "config.toml", _build_codex_config_toml())
- _write_json(shared_root / ".codex" / "auth.json", _build_codex_auth_payload())
- _write_json(shared_root / ".config" / "opencode" / "opencode.json", _build_opencode_payload())
-
-
-def _normalize_config_payload(path: Path) -> None:
- if not path.is_file():
- return
- try:
- payload = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
- return
- if not isinstance(payload, dict):
- return
-
- agents = payload.get("agents")
- if not isinstance(agents, dict):
- return
- opencode = agents.get("opencode")
- if not isinstance(opencode, dict):
- return
- cli_path = str(opencode.get("cli_path") or "")
- legacy_home_cli = str(CONTAINER_HOME / ".opencode" / "bin" / "opencode")
- if cli_path not in {"", "opencode", legacy_home_cli}:
- return
-
- opencode["cli_path"] = CONTAINER_OPENCODE_CLI
- _write_json(path, payload)
-
-
-def _normalize_existing_state(vibe_dir: Path) -> None:
- config_path = vibe_dir / "config" / "config.json"
- _rewrite_json_file_stale_container_paths(config_path)
- _normalize_config_payload(config_path)
- _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "settings.json")
- _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "sessions.json")
- _rewrite_json_file_stale_container_paths(vibe_dir / "state" / "scheduled_tasks.json")
- _rewrite_sqlite_stale_container_paths(vibe_dir / "state" / "vibe.sqlite")
-
-
-def prepare(output_root: Path, reset_mode: str = "none") -> None:
- _validate_reset_mode(reset_mode)
- home_root = _home_root(output_root)
- if reset_mode == "all" and (home_root.exists() or home_root.is_symlink()):
- if home_root.is_dir() and not home_root.is_symlink():
- shutil.rmtree(home_root)
- else:
- home_root.unlink()
- home_root.mkdir(parents=True, exist_ok=True)
-
- vibe_dir = _active_vibe_dir(output_root)
- config_path = vibe_dir / "config" / "config.json"
- settings_path = vibe_dir / "state" / "settings.json"
- sessions_path = vibe_dir / "state" / "sessions.json"
- needs_config = reset_mode in {"config", "all"} or not config_path.exists()
- needs_settings = reset_mode in {"config", "all"} or not settings_path.exists()
- needs_sessions = reset_mode in {"config", "all"} or not sessions_path.exists()
- _repair_shared_agent_state_files(output_root, reset_mode=reset_mode)
- needs_shared_agent_configs = _should_write_shared_agent_configs(output_root, reset_mode=reset_mode)
-
- if needs_shared_agent_configs:
- _require_envs(("ANTHROPIC_API_KEY", "OPENAI_API_KEY"))
-
- if needs_config or needs_settings:
- for pdef in PLATFORM_DEFS.values():
- _require_envs(pdef["required_envs"])
-
- if needs_shared_agent_configs:
- _write_shared_agent_configs(output_root, reset_mode=reset_mode)
-
- _ensure_vibe_dir(vibe_dir, reset_mode=reset_mode)
-
- if needs_config:
- _write_json(config_path, _build_config_payload())
- if needs_settings:
- _write_json(settings_path, _build_settings_payload())
- if needs_sessions:
- _write_json(sessions_path, {})
- if not needs_config or not needs_settings:
- _normalize_existing_state(vibe_dir)
-
- summary_lines: list[str] = []
- for name, pdef in PLATFORM_DEFS.items():
- channel = _env(pdef["channel_env"]) or "(configure later in UI)"
- backend = _env(pdef["backend_env"]) or _default_backend()
- summary_lines.append(f" {name}: platform={pdef['platform']} channel={channel} backend={backend}")
-
- print(f"Prepared unified regression state under {vibe_dir}")
- print("Platform routing:")
- print("\n".join(summary_lines))
- print(f"State: {reset_mode if reset_mode != 'none' else 'preserved'}")
-
-
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument(
- "--output-root",
- default=str(Path(".runtime") / "three-regression"),
- help="Directory that will hold generated state",
- )
- parser.add_argument(
- "--reset-mode",
- choices=sorted(RESET_MODES),
- default="none",
- help="Reset scope before generating files: none, config, or all",
- )
- args = parser.parse_args()
-
- try:
- prepare(Path(args.output_root).resolve(), reset_mode=args.reset_mode)
- except SystemExit as exc:
- print(str(exc), file=sys.stderr)
- return 1
- return 0
+from prepare_regression import main
if __name__ == "__main__":
diff --git a/scripts/run_regression.sh b/scripts/run_regression.sh
new file mode 100755
index 000000000..6bb5ae988
--- /dev/null
+++ b/scripts/run_regression.sh
@@ -0,0 +1,112 @@
+#!/bin/bash
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+PYTHON_BIN="${PYTHON_BIN:-python3}"
+
+if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
+ PYTHON_BIN="python"
+fi
+
+mode="up"
+target="${REGRESSION_TARGET:-${THREE_REGRESSION_TARGET:-master}}"
+incus_args=()
+passthrough=()
+
+usage() {
+ "$PYTHON_BIN" "$REPO_ROOT/scripts/incus_regression.py" --help
+}
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --master)
+ target="master"
+ shift
+ ;;
+ --worktree)
+ target="worktree"
+ shift
+ ;;
+ --down)
+ mode="down"
+ shift
+ ;;
+ --status)
+ mode="status"
+ shift
+ ;;
+ --logs)
+ mode="logs"
+ shift
+ ;;
+ --shell)
+ mode="shell"
+ shift
+ ;;
+ --delete)
+ mode="delete"
+ shift
+ ;;
+ --reset-config)
+ incus_args+=(--reset-mode config)
+ shift
+ ;;
+ --reset-all|--reset-state)
+ incus_args+=(--reset-mode all)
+ shift
+ ;;
+ --no-build)
+ incus_args+=(--no-build-ui)
+ shift
+ ;;
+ --env-file)
+ if [ $# -lt 2 ]; then
+ echo "--env-file requires a path argument" >&2
+ exit 1
+ fi
+ incus_args+=(--env-file "$2")
+ shift 2
+ ;;
+ --remote|--incus-remote)
+ if [ $# -lt 2 ]; then
+ echo "--incus-remote requires a remote name" >&2
+ exit 1
+ fi
+ incus_args+=(--remote "$2")
+ shift 2
+ ;;
+ --dry-run|--clean|--force-deps|--no-build-ui|--yes)
+ incus_args+=("$1")
+ shift
+ ;;
+ --slug|--host-port|--ui-host|--ui-port|--worktree-port-start|--worktree-port-end|--image|--storage-pool|--network|--cpus|--memory|--disk|--processes)
+ if [ $# -lt 2 ]; then
+ echo "$1 requires an argument" >&2
+ exit 1
+ fi
+ incus_args+=("$1" "$2")
+ shift 2
+ ;;
+ -h|--help)
+ usage
+ exit 0
+ ;;
+ *)
+ passthrough+=("$1")
+ shift
+ ;;
+ esac
+done
+
+if [ ${#passthrough[@]} -gt 0 ]; then
+ echo "Unknown Incus regression argument(s): ${passthrough[*]}" >&2
+ exit 1
+fi
+
+if [ ${#incus_args[@]} -gt 0 ]; then
+ exec "$PYTHON_BIN" "$REPO_ROOT/scripts/incus_regression.py" "$mode" --target "$target" "${incus_args[@]}"
+else
+ exec "$PYTHON_BIN" "$REPO_ROOT/scripts/incus_regression.py" "$mode" --target "$target"
+fi
diff --git a/scripts/run_three_regression.sh b/scripts/run_three_regression.sh
index 426039b88..ace987215 100755
--- a/scripts/run_three_regression.sh
+++ b/scripts/run_three_regression.sh
@@ -3,481 +3,5 @@
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
-COMPOSE_FILE="$REPO_ROOT/docker-compose.three-regression.yml"
-PROJECT_NAME="vibe-three-regression"
-PYTHON_BIN="${PYTHON_BIN:-python3}"
-DOCKER_BIN="${DOCKER_BIN:-}"
-CONTAINER_HOME="/home/avibe"
-CONTAINER_AVIBE_HOME="$CONTAINER_HOME/.avibe"
-resolve_git_common_repo_root() {
- local common_dir
- common_dir="$(git -C "$REPO_ROOT" rev-parse --git-common-dir 2>/dev/null || true)"
- if [ -z "$common_dir" ]; then
- echo "$REPO_ROOT"
- return 0
- fi
- case "$common_dir" in
- /*) ;;
- *) common_dir="$REPO_ROOT/$common_dir" ;;
- esac
- (cd "$common_dir/.." && pwd)
-}
-
-absolute_from_repo_root() {
- local path="$1"
- case "$path" in
- /*) echo "$path" ;;
- *) echo "$REPO_ROOT/$path" ;;
- esac
-}
-
-CANONICAL_REPO_ROOT="$(resolve_git_common_repo_root)"
-DEFAULT_OUTPUT_ROOT="$CANONICAL_REPO_ROOT/.runtime/three-regression"
-OUTPUT_ROOT="${THREE_REGRESSION_STATE_ROOT:-$DEFAULT_OUTPUT_ROOT}"
-if [ -f "$REPO_ROOT/.env.three-regression" ]; then
- ENV_FILE="$REPO_ROOT/.env.three-regression"
-else
- ENV_FILE="$CANONICAL_REPO_ROOT/.env.three-regression"
-fi
-
-if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
- PYTHON_BIN="python"
-fi
-
-resolve_docker_bin() {
- if [ -n "$DOCKER_BIN" ] && [ -x "$DOCKER_BIN" ]; then
- return 0
- fi
-
- if command -v docker >/dev/null 2>&1; then
- DOCKER_BIN="$(command -v docker)"
- return 0
- fi
-
- for candidate in /usr/local/bin/docker /opt/homebrew/bin/docker /Applications/Docker.app/Contents/Resources/bin/docker; do
- if [ -x "$candidate" ]; then
- DOCKER_BIN="$candidate"
- export PATH="$(dirname "$candidate"):$PATH"
- return 0
- fi
- done
-
- echo "Docker CLI not found in PATH or common install locations." >&2
- echo "Set DOCKER_BIN=/absolute/path/to/docker if Docker is installed elsewhere." >&2
- exit 1
-}
-
-resolve_docker_bin
-
-MODE="up"
-BUILD_FLAG="--build"
-RESET_MODE="none"
-
-usage() {
- cat <<'EOF'
-Usage:
- ./scripts/run_three_regression.sh
- ./scripts/run_three_regression.sh --no-build
- ./scripts/run_three_regression.sh --reset-config
- ./scripts/run_three_regression.sh --reset-all
- ./scripts/run_three_regression.sh --down
- ./scripts/run_three_regression.sh --status
- ./scripts/run_three_regression.sh --logs
- ./scripts/run_three_regression.sh --env-file /path/to/.env.three-regression
-
-Environment:
- THREE_REGRESSION_STATE_ROOT Override the persistent state root.
- THREE_REGRESSION_SHOW_RUNTIME_SOURCE
- Show Runtime provider for regression.
- Defaults to github-source.
-EOF
-}
-
-while [ $# -gt 0 ]; do
- case "$1" in
- --env-file)
- if [ $# -lt 2 ]; then
- echo "--env-file requires a path argument" >&2
- usage >&2
- exit 1
- fi
- ENV_FILE="$2"
- shift 2
- ;;
- --down)
- MODE="down"
- shift
- ;;
- --status)
- MODE="status"
- shift
- ;;
- --logs)
- MODE="logs"
- shift
- ;;
- --no-build)
- BUILD_FLAG=""
- shift
- ;;
- --reset-config)
- RESET_MODE="config"
- shift
- ;;
- --reset-all)
- RESET_MODE="all"
- shift
- ;;
- --reset-state)
- RESET_MODE="all"
- shift
- ;;
- -h|--help)
- usage
- exit 0
- ;;
- *)
- echo "Unknown argument: $1" >&2
- usage >&2
- exit 1
- ;;
- esac
-done
-
-load_env_file() {
- if [ ! -f "$ENV_FILE" ]; then
- return 1
- fi
-
- set -a
- . "$ENV_FILE"
- set +a
- return 0
-}
-
-ENV_LOADED=false
-if load_env_file; then
- ENV_LOADED=true
-elif [ "$MODE" = "up" ]; then
- echo "Missing env file: $ENV_FILE" >&2
- echo "Copy .env.three-regression.example to .env.three-regression in either this worktree or the primary checkout first." >&2
- exit 1
-fi
-
-OUTPUT_ROOT="${THREE_REGRESSION_STATE_ROOT:-$DEFAULT_OUTPUT_ROOT}"
-OUTPUT_ROOT="$(absolute_from_repo_root "$OUTPUT_ROOT")"
-export THREE_REGRESSION_STATE_ROOT="$OUTPUT_ROOT"
-export THREE_REGRESSION_SHOW_RUNTIME_SOURCE="${THREE_REGRESSION_SHOW_RUNTIME_SOURCE:-github-source}"
-export THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REPO="${THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REPO:-https://github.com/avibe-bot/vibe-show-runtime.git}"
-export THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REF="${THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REF:-main}"
-
-LOCK_DIR=""
-LOCK_HELD=false
-
-release_run_lock() {
- if [ "$LOCK_HELD" != true ] || [ -z "$LOCK_DIR" ] || [ ! -d "$LOCK_DIR" ]; then
- return 0
- fi
-
- local lock_pid
- lock_pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
- if [ "$lock_pid" = "$$" ]; then
- rm -rf "$LOCK_DIR"
- fi
-}
-
-acquire_run_lock() {
- mkdir -p "$OUTPUT_ROOT"
- LOCK_DIR="$OUTPUT_ROOT/.run.lock"
-
- if mkdir "$LOCK_DIR" 2>/dev/null; then
- LOCK_HELD=true
- else
- local existing_pid=""
- existing_pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
- if [[ "$existing_pid" =~ ^[0-9]+$ ]] && kill -0 "$existing_pid" 2>/dev/null; then
- echo "Another three-regression update is already running." >&2
- echo "Lock: $LOCK_DIR" >&2
- echo "PID: $existing_pid" >&2
- echo "Repo: $(cat "$LOCK_DIR/repo_root" 2>/dev/null || echo unknown)" >&2
- exit 1
- fi
-
- echo "Removing stale three-regression lock: $LOCK_DIR" >&2
- rm -rf "$LOCK_DIR"
- if ! mkdir "$LOCK_DIR" 2>/dev/null; then
- echo "Failed to acquire three-regression lock: $LOCK_DIR" >&2
- exit 1
- fi
- LOCK_HELD=true
- fi
-
- printf '%s\n' "$$" > "$LOCK_DIR/pid"
- printf '%s\n' "$REPO_ROOT" > "$LOCK_DIR/repo_root"
- date -u +"%Y-%m-%dT%H:%M:%SZ" > "$LOCK_DIR/started_at"
- trap 'release_run_lock' EXIT
- trap 'release_run_lock; exit 130' INT
- trap 'release_run_lock; exit 143' TERM
-}
-
-if [ "$MODE" = "up" ] || [ "$MODE" = "down" ]; then
- acquire_run_lock
-fi
-
-print_summary() {
- local port="${THREE_REGRESSION_PORT:-15130}"
- local bind_host="${THREE_REGRESSION_PORT_BIND_HOST:-127.0.0.1}"
- local ui_host="${THREE_REGRESSION_ACCESS_HOST:-${THREE_REGRESSION_UI_HOST:-$bind_host}}"
- local default_backend="${THREE_REGRESSION_DEFAULT_BACKEND:-opencode}"
- local config_path="$OUTPUT_ROOT/home/.avibe/config/config.json"
- local display_root
- display_root="$OUTPUT_ROOT"
- case "$display_root" in
- "$CANONICAL_REPO_ROOT"/*) display_root="${display_root#"$CANONICAL_REPO_ROOT/"}" ;;
- esac
-
- if [ -f "$config_path" ]; then
- default_backend="$("$PYTHON_BIN" - "$config_path" "$default_backend" <<'PY'
-import json
-import sys
-
-path, fallback = sys.argv[1], sys.argv[2]
-try:
- with open(path, encoding="utf-8") as fh:
- payload = json.load(fh)
- print((payload.get("agents") or {}).get("default_backend") or fallback)
-except Exception:
- print(fallback)
-PY
-)"
- fi
-
- local slack_channel="${THREE_REGRESSION_SLACK_CHANNEL:-}"
- local discord_channel="${THREE_REGRESSION_DISCORD_CHANNEL:-}"
- local feishu_channel="${THREE_REGRESSION_FEISHU_CHAT_ID:-}"
- local wechat_channel="${THREE_REGRESSION_WECHAT_CHANNEL:-}"
-
- [ -z "$slack_channel" ] && slack_channel="(configure later in UI)"
- [ -z "$discord_channel" ] && discord_channel="(configure later in UI)"
- [ -z "$feishu_channel" ] && feishu_channel="(configure later in UI)"
- [ -z "$wechat_channel" ] && wechat_channel="(QR login required in UI)"
-
- cat <<EOF
-Unified regression environment is ready:
- URL: http://${ui_host}:${port}
- Default backend: ${default_backend}
- State root: ${display_root}
- Show Runtime source: ${THREE_REGRESSION_SHOW_RUNTIME_SOURCE}
-
- Platform routing:
- - Slack: channel=${slack_channel} backend=${THREE_REGRESSION_SLACK_BACKEND:-${default_backend}}
- - Discord: channel=${discord_channel} backend=${THREE_REGRESSION_DISCORD_BACKEND:-${default_backend}}
- - Feishu: channel=${feishu_channel} backend=${THREE_REGRESSION_FEISHU_BACKEND:-${default_backend}}
- - WeChat: channel=${wechat_channel} backend=${THREE_REGRESSION_WECHAT_BACKEND:-${default_backend}}
-EOF
-}
-
-container_exists() {
- local cid
- cid="$("$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps -q vibe 2>/dev/null || true)"
- [ -n "$cid" ]
-}
-
-snapshot_container_path() {
- local container_path="$1"
- local host_parent="$2"
- local host_name="$3"
-
- if ! "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe sh -lc "test -e '$container_path'" >/dev/null 2>&1; then
- return 0
- fi
-
- mkdir -p "$host_parent"
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe sh -lc \
- "tar --ignore-failed-read --warning=no-file-changed -C \"$(dirname "$container_path")\" -cf - \"$(basename "$container_path")\"" \
- | tar -C "$host_parent" -xf - || true
-}
-
-snapshot_agent_runtime_state() {
- if [ "$RESET_MODE" = "all" ]; then
- return 0
- fi
-
- if ! container_exists; then
- return 0
- fi
-
- local home_root="$OUTPUT_ROOT/home"
- mkdir -p "$home_root"
-
- echo "Snapshotting agent runtime state from existing regression container..."
- snapshot_container_path "$CONTAINER_HOME/.claude" "$home_root" ".claude"
- snapshot_container_path "$CONTAINER_HOME/.claude.json" "$home_root" ".claude.json"
- snapshot_container_path "$CONTAINER_HOME/.codex" "$home_root" ".codex"
- snapshot_container_path "$CONTAINER_HOME/.config/opencode" "$home_root/.config" "opencode"
- snapshot_container_path "$CONTAINER_HOME/.local/share/opencode" "$home_root/.local/share" "opencode"
-}
-
-snapshot_avibe_state() {
- if [ "$RESET_MODE" = "all" ]; then
- return 0
- fi
-
- if ! container_exists; then
- return 0
- fi
-
- local cid
- cid="$("$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps -q vibe 2>/dev/null || true)"
- if [ -z "$cid" ]; then
- return 0
- fi
-
- local avibe_target="$OUTPUT_ROOT/home/.avibe"
- if [ -f "$avibe_target/config/config.json" ]; then
- return 0
- fi
-
- mkdir -p "$OUTPUT_ROOT/home"
- echo "Importing Avibe state from the existing regression container..."
- "$DOCKER_BIN" cp "$cid:$CONTAINER_AVIBE_HOME/." "$avibe_target" >/dev/null 2>&1 || true
-}
-
-write_regression_metadata() {
- mkdir -p "$OUTPUT_ROOT"
- "$PYTHON_BIN" - "$OUTPUT_ROOT" "$REPO_ROOT" "$CANONICAL_REPO_ROOT" <<'PY'
-import json
-import subprocess
-import sys
-from datetime import datetime, timezone
-from pathlib import Path
-
-output_root = Path(sys.argv[1])
-repo_root = Path(sys.argv[2])
-canonical_repo_root = Path(sys.argv[3])
-
-def git_value(*args: str) -> str | None:
- try:
- result = subprocess.run(
- ["git", "-C", str(repo_root), *args],
- capture_output=True,
- text=True,
- timeout=5,
- check=False,
- )
- except Exception:
- return None
- if result.returncode != 0:
- return None
- return result.stdout.strip() or None
-
-payload = {
- "schema_version": 1,
- "updated_at": datetime.now(timezone.utc).isoformat(),
- "state_root": str(output_root),
- "repo_root": str(repo_root),
- "canonical_repo_root": str(canonical_repo_root),
- "branch": git_value("branch", "--show-current"),
- "commit": git_value("rev-parse", "HEAD"),
-}
-(output_root / "metadata.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
-PY
-}
-
-prepare_show_runtime() {
- echo "Preparing Show Runtime inside the regression container..."
- if ! "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe vibe runtime prepare --strict; then
- echo "Show Runtime preparation failed inside the regression container." >&2
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe vibe runtime status --json >&2 || true
- return 1
- fi
-
- local status_json
- status_json="$("$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe vibe runtime status --json)"
- STATUS_JSON="$status_json" "$PYTHON_BIN" - <<'PY'
-import json
-import os
-
-payload = json.loads(os.environ["STATUS_JSON"])
-if not payload.get("command"):
- reason = payload.get("reason") or "runtime_command_missing"
- raise SystemExit(f"Show Runtime is not executable after prepare: {reason}")
-print(
- "Show Runtime ready: "
- f"provider={payload.get('provider')} "
- f"platform={payload.get('platform')} "
- f"installed={payload.get('installed')}"
-)
-PY
-}
-
-wait_for_service() {
- for _ in $(seq 1 60); do
- if "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" exec -T vibe python - <<'PY' >/dev/null 2>&1; then
-import json
-import sys
-import urllib.request
-
-try:
- urllib.request.urlopen("http://127.0.0.1:5123/health", timeout=3).read()
- status = json.loads(urllib.request.urlopen("http://127.0.0.1:5123/status", timeout=3).read())
-except Exception:
- sys.exit(1)
-sys.exit(0 if status.get("running") else 1)
-PY
- return 0
- fi
- sleep 2
- done
-
- echo "Service did not become ready inside the regression container" >&2
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" logs vibe || true
- return 1
-}
-
-case "$MODE" in
- down)
- snapshot_avibe_state
- snapshot_agent_runtime_state
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" down --remove-orphans
- exit 0
- ;;
- status)
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" ps
- if [ "$ENV_LOADED" = true ]; then
- print_summary
- fi
- exit 0
- ;;
- logs)
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" logs -f vibe
- exit 0
- ;;
-esac
-
-snapshot_avibe_state
-snapshot_agent_runtime_state
-
-echo "Stopping previous regression container..."
-"$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" down --remove-orphans >/dev/null 2>&1 || true
-
-echo "Preparing generated config and state..."
-PREPARE_ARGS=(--output-root "$OUTPUT_ROOT")
-PREPARE_ARGS+=(--reset-mode "$RESET_MODE")
-"$PYTHON_BIN" "$REPO_ROOT/scripts/prepare_three_regression.py" "${PREPARE_ARGS[@]}"
-write_regression_metadata
-
-echo "Starting unified regression container..."
-if [ -n "$BUILD_FLAG" ]; then
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" up -d --build --force-recreate --remove-orphans
-else
- "$DOCKER_BIN" compose -p "$PROJECT_NAME" -f "$COMPOSE_FILE" up -d --force-recreate --remove-orphans
-fi
-
-echo "Waiting for service to become healthy..."
-wait_for_service "${THREE_REGRESSION_PORT:-15130}"
-prepare_show_runtime
-
-print_summary
+exec "$SCRIPT_DIR/run_regression.sh" "$@"
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
new file mode 100644
index 000000000..f1a3f2a73
--- /dev/null
+++ b/tests/test_incus_regression.py
@@ -0,0 +1,1699 @@
+from __future__ import annotations
+
+import argparse
+import io
+import importlib.util
+import json
+import subprocess
+import sys
+import tarfile
+from pathlib import Path
+
+import pytest
+
+
+SCRIPT_PATH = Path(__file__).resolve().parents[1] / "scripts" / "incus_regression.py"
+SPEC = importlib.util.spec_from_file_location("incus_regression", SCRIPT_PATH)
+incus_regression = importlib.util.module_from_spec(SPEC)
+assert SPEC.loader is not None
+sys.modules[SPEC.name] = incus_regression
+SPEC.loader.exec_module(incus_regression)
+
+
+def test_master_target_uses_stable_project_instance_and_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("REGRESSION_PORT", raising=False)
+ monkeypatch.delenv("THREE_REGRESSION_PORT", raising=False)
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.project == "avr-master"
+ assert target.instance == "avibe-master"
+ assert target.host_port == 15130
+
+
+def test_master_target_uses_env_host_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("REGRESSION_PORT", "15131")
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.host_port == 15131
+
+
+def test_master_target_accepts_legacy_env_host_port(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("REGRESSION_PORT", raising=False)
+ monkeypatch.setenv("THREE_REGRESSION_PORT", "15132")
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.host_port == 15132
+
+
+def test_master_target_uses_env_bind_host_after_env_load(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("REGRESSION_PORT_BIND_HOST", "0.0.0.0")
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host=None,
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.ui_host == "0.0.0.0"
+
+
+def test_master_target_prefers_port_bind_host_over_container_ui_host(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("REGRESSION_UI_HOST", "127.0.0.1")
+ monkeypatch.setenv("REGRESSION_PORT_BIND_HOST", "0.0.0.0")
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host=None,
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.ui_host == "0.0.0.0"
+
+
+def test_master_target_accepts_legacy_ui_host_as_bind_host(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("REGRESSION_PORT_BIND_HOST", raising=False)
+ monkeypatch.setenv("REGRESSION_UI_HOST", "0.0.0.0")
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host=None,
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo"),
+ dry_run=True,
+ )
+
+ assert target.ui_host == "0.0.0.0"
+
+
+def test_worktree_target_slug_includes_path_hash(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(incus_regression, "branch_name", lambda repo_root: "feature/Show Runtime")
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug=None,
+ host_port=15234,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ Path("/tmp/repo-a"),
+ dry_run=True,
+ )
+
+ assert target.project.startswith("avr-wt-feature-show-runtime-")
+ assert target.instance.startswith("avibe-wt-feature-show-runtime-")
+ assert target.host_port == 15234
+
+
+def test_remote_worktree_target_skips_local_port_preflight(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(incus_regression, "branch_name", lambda repo_root: "feature/demo")
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight remote ports")))
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15200,
+ ),
+ Path("/tmp/repo-a"),
+ dry_run=False,
+ preflight_ports=False,
+ )
+
+ assert target.host_port == 15200
+
+
+def test_worktree_target_reuses_mapped_port_without_allocation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ runtime = tmp_path / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ (runtime / "worktrees.json").write_text(
+ json.dumps({"schema_version": 1, "worktrees": {"demo-branch": {"host_port": 15234}}}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "allocate_worktree_port", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should reuse mapped port")))
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ tmp_path,
+ dry_run=False,
+ )
+
+ assert target.host_port == 15234
+
+
+def test_worktree_maintenance_target_does_not_allocate_port(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(incus_regression, "allocate_worktree_port", lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("should not allocate for maintenance")))
+
+ target = incus_regression.resolve_target(
+ argparse.Namespace(
+ target="worktree",
+ slug="missing-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ ),
+ tmp_path,
+ dry_run=False,
+ allocate_port=False,
+ preflight_ports=False,
+ )
+
+ assert target.host_port == 0
+
+
+def test_cloud_init_configures_systemd_service_without_source_code() -> None:
+ data = incus_regression.cloud_init_user_data()
+
+ assert "#cloud-config" in data
+ assert "name: avibe" in data
+ assert "Description=Avibe regression service" in data
+ assert "Environment=VIBE_DEPLOYMENT_ENV=regression" in data
+ assert "EnvironmentFile=-/etc/avibe-regression.env" in data
+ assert "ExecStart=/opt/avibe/venv/bin/python scripts/incus_regression_supervisor.py" in data
+ assert "/opt/avibe/source" in data
+ assert "/home/avibe/.vibe_remote" in data
+
+
+def test_project_config_marks_regression_target() -> None:
+ target = incus_regression.RegressionTarget(
+ target="worktree",
+ slug="demo-branch",
+ project="avr-wt-demo-branch",
+ instance="avibe-wt-demo-branch",
+ host_port=15200,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ config = incus_regression.project_create_config(target)
+
+ assert "restricted=true" in config
+ assert "restricted.devices.proxy=allow" in config
+ assert "user.avibe_regression.target=worktree" in config
+ assert "user.avibe_regression.host_port=15200" in config
+
+
+def test_remote_ref_prefixes_resource_names_only() -> None:
+ assert incus_regression.remote_ref("lab", "demo") == "lab:demo"
+ assert incus_regression.remote_ref(None, "demo") == "demo"
+ assert incus_regression.remote_ref("lab") == "lab:"
+ assert incus_regression.optional_remote_ref(None) == []
+ assert incus_regression.optional_remote_ref("lab") == ["lab:"]
+
+
+def test_incus_command_can_be_overridden(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("INCUS_CMD", "sudo incus")
+
+ assert incus_regression.incus("info") == ["sudo", "incus", "info"]
+
+
+def test_require_incus_uses_command_override(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("INCUS_CMD", "/custom/incus --debug")
+ monkeypatch.setattr(incus_regression.shutil, "which", lambda executable: executable if executable == "/custom/incus" else None)
+
+ incus_regression.require_incus()
+
+
+def test_require_incus_reports_missing_override(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("INCUS_CMD", "/missing/incus")
+ monkeypatch.setattr(incus_regression.shutil, "which", lambda executable: None)
+
+ with pytest.raises(incus_regression.RegressionError, match="/missing/incus"):
+ incus_regression.require_incus()
+
+
+def test_default_base_image_alias_is_not_remote_syntax() -> None:
+ assert ":" not in incus_regression.DEFAULT_IMAGE
+
+
+def test_proxy_device_uses_remote_instance_ref() -> None:
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ args = incus_regression.proxy_device_args(target, remote="lab")
+
+ assert args[3] == "lab:avibe-master"
+ assert "listen=tcp:127.0.0.1:15130" in args
+ assert "connect=tcp:127.0.0.1:5123" in args
+
+
+def test_existing_instance_proxy_device_is_refreshed() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def exists(self, command):
+ return True
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append((command, check))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15131,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.ensure_project_and_instance(
+ RecordingRunner(),
+ target,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ )
+
+ rendered = [" ".join(command) for command, _ in commands]
+ assert "incus --project avr-master config device remove avibe-master ui" in rendered
+ assert any("incus --project avr-master config device add avibe-master ui proxy listen=tcp:127.0.0.1:15131" in command for command in rendered)
+
+
+def test_build_base_uses_publishable_temp_instance() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ args = argparse.Namespace(
+ dry_run=True,
+ remote=None,
+ source_image="images:ubuntu/24.04/cloud",
+ temp_instance="avibe-regression-base-build",
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ )
+
+ original_runner = incus_regression.Runner
+ try:
+ incus_regression.Runner = RecordingRunner
+ assert incus_regression.cmd_build_base(args) == 0
+ finally:
+ incus_regression.Runner = original_runner
+
+ joined = "\n".join(" ".join(command) for command in commands)
+ assert "--ephemeral" not in joined
+ assert "incus launch images:ubuntu/24.04/cloud avibe-regression-base-build --storage default --network incusbr0" in joined
+ assert "https://deb.nodesource.com/setup_20.x" in joined
+ assert "npm install -g @anthropic-ai/claude-code @openai/codex" in joined
+ assert "https://askill.sh | sh -s -- -b /usr/local/bin" in joined
+ assert "HOME=/usr/local curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path" in joined
+ assert "install -o root -g root -m 0755 /usr/local/.opencode/bin/opencode /usr/local/bin/opencode" in joined
+ assert "cloud-init clean --logs || true" in joined
+ assert "incus publish avibe-regression-base-build --alias avibe-regression-base-current" in joined
+
+
+def test_source_exclude_drops_runtime_and_dependency_dirs() -> None:
+ assert incus_regression.should_exclude(".runtime/state.json")
+ assert incus_regression.should_exclude("ui/node_modules/pkg/index.js")
+ assert incus_regression.should_exclude("ui/dist/assets/app.js")
+ assert not incus_regression.should_exclude("ui/dist/assets/app.js", include_ui_dist=True)
+ assert incus_regression.should_exclude("pkg/__pycache__/x.pyc")
+ assert incus_regression.should_exclude(".env")
+ assert incus_regression.should_exclude(".env.regression")
+ assert incus_regression.should_exclude(".env.three-regression")
+ assert incus_regression.should_exclude(".env.e2e")
+ assert incus_regression.should_exclude("ui/.env.local")
+ assert incus_regression.should_exclude("api/.env.preview.local")
+ assert not incus_regression.should_exclude("vibe/ui_server.py")
+
+
+def test_source_tar_excludes_regression_secret_file(tmp_path: Path) -> None:
+ (tmp_path / ".env.regression").write_text("OPENAI_API_KEY=secret\n", encoding="utf-8")
+ (tmp_path / "vibe").mkdir()
+ (tmp_path / "vibe" / "ui_server.py").write_text("print('ok')\n", encoding="utf-8")
+
+ payload = incus_regression.build_source_tar(tmp_path)
+ with tarfile.open(fileobj=io.BytesIO(payload), mode="r") as archive:
+ names = set(archive.getnames())
+ ui_server = archive.extractfile("vibe/ui_server.py")
+ assert ui_server is not None
+ content = ui_server.read()
+
+ assert ".env.regression" not in names
+ assert b"print('ok')" in content
+
+
+def test_source_tar_excludes_all_local_env_files(tmp_path: Path) -> None:
+ (tmp_path / ".env.e2e").write_text("SECRET=1\n", encoding="utf-8")
+ (tmp_path / ".env.preview.local").write_text("SECRET=2\n", encoding="utf-8")
+ (tmp_path / "ui").mkdir()
+ (tmp_path / "ui" / ".env.local").write_text("SECRET=3\n", encoding="utf-8")
+ (tmp_path / "vibe").mkdir()
+ (tmp_path / "vibe" / "ui_server.py").write_text("print('ok')\n", encoding="utf-8")
+
+ payload = incus_regression.build_source_tar(tmp_path)
+ with tarfile.open(fileobj=io.BytesIO(payload), mode="r") as archive:
+ names = set(archive.getnames())
+
+ assert ".env.e2e" not in names
+ assert ".env.preview.local" not in names
+ assert "ui/.env.local" not in names
+
+
+def test_source_tar_can_include_existing_ui_dist_when_build_is_skipped(tmp_path: Path) -> None:
+ (tmp_path / "ui" / "dist" / "assets").mkdir(parents=True)
+ (tmp_path / "ui" / "dist" / "index.html").write_text("<html></html>\n", encoding="utf-8")
+ (tmp_path / "ui" / "dist" / "assets" / "app.js").write_text("console.log('ok')\n", encoding="utf-8")
+
+ payload = incus_regression.build_source_tar(tmp_path, include_ui_dist=True)
+ with tarfile.open(fileobj=io.BytesIO(payload), mode="r") as archive:
+ names = set(archive.getnames())
+
+ assert "ui/dist/index.html" in names
+ assert "ui/dist/assets/app.js" in names
+
+
+def test_sync_source_clears_stale_files_even_without_clean(tmp_path: Path) -> None:
+ commands = []
+
+ class RecordingRunner:
+ dry_run = True
+
+ def run(self, command, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.sync_source(RecordingRunner(), target, tmp_path, remote=None, clean=False)
+
+ joined = "\n".join(" ".join(command) for command in commands)
+ assert f"find {incus_regression.SOURCE_DIR} -mindepth 1 -maxdepth 1 -exec rm -rf" in joined
+
+
+def test_ui_public_assets_are_part_of_source_fingerprint(tmp_path: Path) -> None:
+ (tmp_path / "ui" / "src").mkdir(parents=True)
+ (tmp_path / "ui" / "public").mkdir(parents=True)
+ (tmp_path / "ui" / "public" / "push-sw.js").write_text("one\n", encoding="utf-8")
+
+ before = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
+ (tmp_path / "ui" / "public" / "push-sw.js").write_text("two\n", encoding="utf-8")
+ after = incus_regression.compute_fingerprints(tmp_path)["ui_source"]
+
+ assert before != after
+
+
+def test_runtime_env_payload_maps_show_runtime_and_llm_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("REGRESSION_SHOW_RUNTIME_GITHUB_REF", "main")
+ monkeypatch.setenv("REGRESSION_SLACK_CHANNEL", "C123")
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
+
+ payload = incus_regression.runtime_env_payload().decode()
+
+ assert "SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0.dev0" in payload
+ assert "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_AVIBE_OS=0.0.0.dev0" in payload
+ assert "VIBE_SHOW_RUNTIME_SOURCE=github-source" in payload
+ assert "VIBE_SHOW_RUNTIME_GITHUB_REF=main" in payload
+ assert "REGRESSION_SLACK_CHANNEL=C123" in payload
+ assert "OPENAI_API_KEY=sk-test" in payload
+
+
+def test_runtime_env_payload_normalizes_legacy_regression_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("REGRESSION_SHOW_RUNTIME_GITHUB_REF", raising=False)
+ monkeypatch.delenv("REGRESSION_SLACK_CHANNEL", raising=False)
+ monkeypatch.setenv("THREE_REGRESSION_SHOW_RUNTIME_GITHUB_REF", "legacy-ref")
+ monkeypatch.setenv("THREE_REGRESSION_SLACK_CHANNEL", "CLEGACY")
+
+ payload = incus_regression.runtime_env_payload().decode()
+
+ assert "VIBE_SHOW_RUNTIME_GITHUB_REF=legacy-ref" in payload
+ assert "REGRESSION_SLACK_CHANNEL=CLEGACY" in payload
+ assert "THREE_REGRESSION_SLACK_CHANNEL" not in payload
+
+
+def test_runtime_env_payload_forces_container_ui_host(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("REGRESSION_UI_HOST", "192.168.2.3")
+ monkeypatch.setenv("THREE_REGRESSION_UI_HOST", "10.1.2.3")
+
+ payload = incus_regression.runtime_env_payload().decode()
+
+ assert "REGRESSION_UI_HOST=127.0.0.1" in payload
+ assert "REGRESSION_UI_HOST=192.168.2.3" not in payload
+ assert "REGRESSION_UI_HOST=10.1.2.3" not in payload
+
+
+def test_load_env_file_accepts_export_prefix(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ env_file = tmp_path / ".env.regression"
+ env_file.write_text("export REGRESSION_SLACK_CHANNEL=C123\n", encoding="utf-8")
+ monkeypatch.delenv("REGRESSION_SLACK_CHANNEL", raising=False)
+
+ loaded = incus_regression.load_env_file(tmp_path, env_file)
+
+ assert loaded == env_file
+ assert incus_regression.os.environ["REGRESSION_SLACK_CHANNEL"] == "C123"
+
+
+def test_load_env_file_falls_back_to_legacy_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ env_file = tmp_path / ".env.three-regression"
+ env_file.write_text("export THREE_REGRESSION_SLACK_CHANNEL=C123\n", encoding="utf-8")
+ monkeypatch.delenv("REGRESSION_SLACK_CHANNEL", raising=False)
+ monkeypatch.delenv("THREE_REGRESSION_SLACK_CHANNEL", raising=False)
+
+ loaded = incus_regression.load_env_file(tmp_path, None)
+
+ assert loaded == env_file
+ assert incus_regression.os.environ["THREE_REGRESSION_SLACK_CHANNEL"] == "C123"
+
+
+def test_require_runtime_seed_env_fails_fast_for_blank_values(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "")
+ monkeypatch.setenv("OPENAI_API_KEY", " ")
+
+ with pytest.raises(SystemExit) as excinfo:
+ incus_regression.require_runtime_seed_env()
+
+ assert "ANTHROPIC_API_KEY" in str(excinfo.value)
+ assert "OPENAI_API_KEY" in str(excinfo.value)
+
+
+def test_require_runtime_seed_env_checks_platform_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+ for key in (
+ "ANTHROPIC_API_KEY",
+ "OPENAI_API_KEY",
+ "REGRESSION_SLACK_BOT_TOKEN",
+ "REGRESSION_SLACK_APP_TOKEN",
+ "REGRESSION_DISCORD_BOT_TOKEN",
+ "REGRESSION_FEISHU_APP_ID",
+ "REGRESSION_FEISHU_APP_SECRET",
+ ):
+ monkeypatch.setenv(key, "set")
+ monkeypatch.setenv("REGRESSION_FEISHU_APP_SECRET", "")
+
+ with pytest.raises(SystemExit) as excinfo:
+ incus_regression.require_runtime_seed_env()
+
+ assert "REGRESSION_FEISHU_APP_SECRET" in str(excinfo.value)
+
+
+def test_require_runtime_seed_env_accepts_legacy_platform_credentials(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "set")
+ monkeypatch.setenv("OPENAI_API_KEY", "set")
+ for key in incus_regression.required_platform_seed_envs():
+ monkeypatch.delenv(key, raising=False)
+ legacy_key = incus_regression.LEGACY_ENV_PREFIX + key[len(incus_regression.ENV_PREFIX):]
+ monkeypatch.setenv(legacy_key, "legacy")
+
+ incus_regression.require_runtime_seed_env()
+
+
+def test_prepare_state_skips_existing_state_without_reset() -> None:
+ commands = []
+
+ class RecordingRunner:
+ dry_run = False
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.run_prepare_state(RecordingRunner(), target, reset_mode="none", remote=None)
+
+ joined = "\n".join(" ".join(command) for command in commands)
+ assert "test -f /home/avibe/.avibe/config/config.json" in joined
+ assert "prepare_regression.py" not in joined
+
+
+def test_prepare_state_reseeds_when_reset_requested(monkeypatch: pytest.MonkeyPatch) -> None:
+ commands = []
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic")
+ monkeypatch.setenv("OPENAI_API_KEY", "openai")
+
+ class RecordingRunner:
+ dry_run = False
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.run_prepare_state(RecordingRunner(), target, reset_mode="config", remote=None)
+
+ joined = "\n".join(" ".join(command) for command in commands)
+ assert "rm -rf /home/avibe/.avibe/config /home/avibe/.avibe/state /home/avibe/.avibe/runtime" in joined
+ assert "rm -rf /home/avibe/.regression-seed" in joined
+ assert "prepare_regression.py" in joined
+
+
+def test_prepare_state_reset_all_deletes_target_home_before_copy(monkeypatch: pytest.MonkeyPatch) -> None:
+ commands = []
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "anthropic")
+ monkeypatch.setenv("OPENAI_API_KEY", "openai")
+
+ class RecordingRunner:
+ dry_run = False
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.run_prepare_state(RecordingRunner(), target, reset_mode="all", remote=None)
+
+ joined = "\n".join(" ".join(command) for command in commands)
+ assert "rm -rf /home/avibe/.avibe /home/avibe/.vibe_remote" in joined
+ assert "/home/avibe/.codex" in joined
+ assert "ln -sfn /home/avibe/.avibe /home/avibe/.vibe_remote" in joined
+
+
+def test_write_runtime_env_uses_stdin_not_command_line() -> None:
+ commands = []
+ inputs = []
+
+ class RecordingRunner:
+ dry_run = False
+
+ def run(self, command, *, input_bytes=None, **kwargs):
+ commands.append(command)
+ inputs.append(input_bytes)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.write_runtime_env(RecordingRunner(), target, remote="lab")
+
+ joined_command = " ".join(commands[0])
+ assert commands[0][:5] == ["incus", "--project", "avr-master", "exec", "lab:avibe-master"]
+ assert "chown root:avibe /etc/avibe-regression.env" in joined_command
+ assert "chmod 0640 /etc/avibe-regression.env" in joined_command
+ assert b"VIBE_SHOW_RUNTIME_SOURCE" in inputs[0]
+ assert "OPENAI_API_KEY" not in joined_command
+
+
+def test_cleanup_stale_deletes_missing_worktree_mapping(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ runtime = repo / ".runtime" / "incus-regression"
+ runtime.mkdir(parents=True)
+ (runtime / "worktrees.json").write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "worktrees": {
+ "old": {
+ "path": str(tmp_path / "missing"),
+ "project": "avr-wt-old",
+ "instance": "avibe-wt-old",
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def run(self, command, *, check=True, **kwargs):
+ commands.append(command)
+ return subprocess.CompletedProcess(command, 0)
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: repo)
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "Runner", RecordingRunner)
+
+ exit_code = incus_regression.cmd_cleanup_stale(argparse.Namespace(yes=True, dry_run=False, remote=None))
+
+ assert exit_code == 0
+ assert ["incus", "--project", "avr-wt-old", "delete", "avibe-wt-old", "--force"] in commands
+ payload = json.loads((runtime / "worktrees.json").read_text(encoding="utf-8"))
+ assert payload["worktrees"] == {}
+
+
+def test_up_skips_host_port_preflight_for_existing_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")
+ (tmp_path / "uv.lock").write_text("", encoding="utf-8")
+ (tmp_path / "ui").mkdir()
+ (tmp_path / "ui" / "package.json").write_text("{}", encoding="utf-8")
+ (tmp_path / "ui" / "package-lock.json").write_text("{}", encoding="utf-8")
+ (tmp_path / "ui" / "src").mkdir()
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return command[:4] == ["incus", "--project", "avr-master", "info"]
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight existing instance")))
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+
+
+def test_up_defers_master_port_preflight_until_after_instance_exists(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def fail_if_resolve_target_preflights(repo_root, ui_host, start, end, *, dry_run, preflight):
+ if preflight:
+ raise AssertionError("master target resolution must not preflight ports")
+ return start
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "allocate_worktree_port", fail_if_resolve_target_preflights)
+ monkeypatch.setattr(
+ incus_regression,
+ "ensure_host_port_available",
+ lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight existing master instance")),
+ )
+ monkeypatch.setattr(incus_regression, "reserve_worktree_mapping", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+
+
+def test_up_skips_host_port_preflight_for_remote_new_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ class NewRemoteRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return False
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", NewRemoteRunner)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: (_ for _ in ()).throw(AssertionError("should not preflight remote ports")))
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", lambda: None)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_runtime_env", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "sync_source", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "run_prepare_state", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "write_metadata", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "restart_and_verify", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", lambda *args, **kwargs: None)
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote="lab",
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+
+
+def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ class NewRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return False
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 1, stdout="")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+ if name == "require_runtime_seed_env":
+ raise SystemExit("missing")
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda *args, **kwargs: None)
+ monkeypatch.setattr(incus_regression, "Runner", NewRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", record("require_runtime_seed_env"))
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ with pytest.raises(SystemExit):
+ incus_regression.cmd_up(args)
+
+ assert calls == ["require_runtime_seed_env"]
+
+
+def test_up_checks_platform_seed_env_before_existing_reset_mutation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+ if name == "require_runtime_seed_env":
+ raise SystemExit("missing platform")
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", record("require_runtime_seed_env"))
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="config",
+ )
+
+ with pytest.raises(SystemExit):
+ incus_regression.cmd_up(args)
+
+ assert calls == ["require_runtime_seed_env"]
+
+
+def test_up_dry_run_does_not_require_seed_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ class DryRunRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return False
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+ if name == "require_runtime_seed_env":
+ raise AssertionError("dry-run should not require seed secrets")
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "Runner", DryRunRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "require_runtime_seed_env", record("require_runtime_seed_env"))
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", record("update_dependencies_and_build"))
+ monkeypatch.setattr(incus_regression, "run_prepare_state", record("run_prepare_state"))
+ monkeypatch.setattr(incus_regression, "normalize_runtime_config", record("normalize_runtime_config"))
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+ monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=True,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+ assert "require_runtime_seed_env" not in calls
+ assert not (tmp_path / ".runtime" / "incus-regression" / "worktrees.json").exists()
+
+
+def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+ env_file = tmp_path / ".env.regression"
+ env_file.write_text("OPENAI_API_KEY=set\n", encoding="utf-8")
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", record("update_dependencies_and_build"))
+ monkeypatch.setattr(incus_regression, "run_prepare_state", record("run_prepare_state"))
+ monkeypatch.setattr(incus_regression, "normalize_runtime_config", record("normalize_runtime_config"))
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+ monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+ assert calls[:3] == ["ensure_project_and_instance", "stop_service_for_update", "write_runtime_env"]
+ assert calls.index("sync_source") < calls.index("update_dependencies_and_build")
+ assert calls.index("normalize_runtime_config") < calls.index("restart_and_verify")
+
+
+def test_up_preserves_runtime_env_when_existing_target_has_no_env_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", record("update_dependencies_and_build"))
+ monkeypatch.setattr(incus_regression, "run_prepare_state", record("run_prepare_state"))
+ monkeypatch.setattr(incus_regression, "normalize_runtime_config", record("normalize_runtime_config"))
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+ monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+ assert "write_runtime_env" not in calls
+ assert calls.index("stop_service_for_update") < calls.index("sync_source")
+
+
+def test_up_rewrites_runtime_env_when_env_file_is_loaded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+ env_file = tmp_path / ".env.regression"
+ env_file.write_text("OPENAI_API_KEY=set\n", encoding="utf-8")
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", record("update_dependencies_and_build"))
+ monkeypatch.setattr(incus_regression, "run_prepare_state", record("run_prepare_state"))
+ monkeypatch.setattr(incus_regression, "normalize_runtime_config", record("normalize_runtime_config"))
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+ monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
+ monkeypatch.setattr(incus_regression, "update_worktree_mapping", record("update_worktree_mapping"))
+
+ args = argparse.Namespace(
+ target="master",
+ slug=None,
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+ assert "write_runtime_env" in calls
+
+
+def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ class ExistingRunner:
+ def __init__(self, *, dry_run=False):
+ self.dry_run = dry_run
+
+ def exists(self, command):
+ return True
+
+ def run(self, command, **kwargs):
+ return subprocess.CompletedProcess(command, 0, stdout="{}")
+
+ def mapping_lock(repo_root, *, dry_run):
+ class Lock:
+ def __enter__(self):
+ calls.append("mapping_lock_enter")
+
+ def __exit__(self, exc_type, exc, tb):
+ calls.append("mapping_lock_exit")
+
+ return Lock()
+
+ def target_lock(repo_root, target, *, dry_run):
+ class Lock:
+ def __enter__(self):
+ calls.append("target_lock_enter")
+
+ def __exit__(self, exc_type, exc, tb):
+ calls.append("target_lock_exit")
+
+ return Lock()
+
+ def record(name):
+ def wrapper(*args, **kwargs):
+ calls.append(name)
+
+ return wrapper
+
+ monkeypatch.setattr(incus_regression, "git_common_root", lambda repo_root: repo_root)
+ monkeypatch.setattr(incus_regression, "current_repo_root", lambda: tmp_path)
+ monkeypatch.setattr(incus_regression, "load_env_file", lambda repo_root, env_file: None)
+ monkeypatch.setattr(incus_regression, "require_incus", lambda: None)
+ monkeypatch.setattr(incus_regression, "Runner", ExistingRunner)
+ monkeypatch.setattr(incus_regression, "worktree_mapping_lock", mapping_lock)
+ original_reserve_worktree_mapping = incus_regression.reserve_worktree_mapping
+
+ def reserve_worktree_mapping(repo_root, target):
+ calls.append("reserve_worktree_mapping")
+ original_reserve_worktree_mapping(repo_root, target)
+
+ monkeypatch.setattr(incus_regression, "target_update_lock", target_lock)
+ monkeypatch.setattr(incus_regression, "reserve_worktree_mapping", reserve_worktree_mapping)
+ monkeypatch.setattr(incus_regression, "ensure_project_and_instance", record("ensure_project_and_instance"))
+ monkeypatch.setattr(incus_regression, "stop_service_for_update", record("stop_service_for_update"))
+ monkeypatch.setattr(incus_regression, "should_seed_state", lambda *args, **kwargs: False)
+ monkeypatch.setattr(incus_regression, "write_runtime_env", record("write_runtime_env"))
+ monkeypatch.setattr(incus_regression, "sync_source", record("sync_source"))
+ monkeypatch.setattr(incus_regression, "compute_fingerprints", lambda repo_root: {})
+ monkeypatch.setattr(incus_regression, "read_existing_fingerprints", lambda *args, **kwargs: {})
+ monkeypatch.setattr(incus_regression, "update_dependencies_and_build", record("update_dependencies_and_build"))
+ monkeypatch.setattr(incus_regression, "run_prepare_state", record("run_prepare_state"))
+ monkeypatch.setattr(incus_regression, "normalize_runtime_config", record("normalize_runtime_config"))
+ monkeypatch.setattr(incus_regression, "write_metadata", record("write_metadata"))
+ monkeypatch.setattr(incus_regression, "restart_and_verify", record("restart_and_verify"))
+ monkeypatch.setattr(incus_regression, "prepare_show_runtime", record("prepare_show_runtime"))
+
+ args = argparse.Namespace(
+ target="worktree",
+ slug="demo-branch",
+ host_port=None,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ worktree_port_start=15200,
+ worktree_port_end=15399,
+ env_file=None,
+ dry_run=False,
+ image="avibe-regression-base-current",
+ storage_pool="default",
+ network="incusbr0",
+ cpus="2",
+ memory="4GiB",
+ disk="20GiB",
+ processes="4096",
+ remote=None,
+ clean=False,
+ force_deps=False,
+ no_build_ui=True,
+ reset_mode="none",
+ )
+
+ assert incus_regression.cmd_up(args) == 0
+
+ assert calls[:4] == ["mapping_lock_enter", "reserve_worktree_mapping", "mapping_lock_exit", "target_lock_enter"]
+ payload = json.loads((tmp_path / ".runtime" / "incus-regression" / "worktrees.json").read_text(encoding="utf-8"))
+ mapping = payload["worktrees"]["demo-branch"]
+ assert mapping["host_port"] == 15200
+ assert mapping["project"] == "avr-wt-demo-branch"
+ assert "updated_at" in mapping
+
+
+def test_normalize_runtime_config_updates_host_and_port() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=6123,
+ )
+
+ incus_regression.normalize_runtime_config(RecordingRunner(), target, remote=None)
+
+ joined = "\n".join(commands)
+ assert "ui.get(\"setup_host\") != '127.0.0.1'" in joined
+ assert 'ui.get("setup_port") != 6123' in joined
+ assert 'ui["setup_port"] = 6123' in joined
+
+
+def test_stop_service_for_update_ignores_missing_service() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, *, check=True, **kwargs):
+ commands.append((command, check))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.stop_service_for_update(RecordingRunner(), target, remote=None)
+
+ joined = " ".join(commands[0][0])
+ assert "systemctl stop avibe-regression.service || true" in joined
+ assert commands[0][1] is False
+
+
+def test_update_builds_ui_before_editable_install() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints={},
+ next_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ force_deps=False,
+ build_ui=True,
+ force_ui=False,
+ remote=None,
+ )
+
+ install_index = next(i for i, command in enumerate(commands) if "pip install -e ." in command)
+ build_index = next(i for i, command in enumerate(commands) if "npm run build" in command)
+ assert build_index < install_index
+
+
+def test_force_ui_rebuilds_even_when_fingerprints_match() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ next_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ force_deps=False,
+ build_ui=True,
+ force_ui=True,
+ remote=None,
+ )
+
+ joined = "\n".join(commands)
+ assert "cd ui && npm ci" in joined
+ assert "cd ui && npm run build" in joined
+ assert "pip install -e ." not in joined
+
+
+def test_missing_ui_dist_overrides_no_build_ui_before_editable_install() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ if "test -d ui/dist" in commands[-1]:
+ return subprocess.CompletedProcess(command, 1)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints={},
+ next_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ force_deps=False,
+ build_ui=False,
+ force_ui=False,
+ remote=None,
+ )
+
+ joined = "\n".join(commands)
+ install_index = next(i for i, command in enumerate(commands) if "pip install -e ." in command)
+ build_index = next(i for i, command in enumerate(commands) if "npm run build" in command)
+ assert "test -d ui/dist && test -f ui/dist/index.html" in joined
+ assert "cd ui && npm ci" in joined
+ assert build_index < install_index
+
+
+def test_missing_ui_dist_rebuilds_even_when_python_is_unchanged() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ if "test -d ui/dist" in commands[-1]:
+ return subprocess.CompletedProcess(command, 1)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(),
+ target,
+ previous_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ next_fingerprints={"python": "p", "ui_deps": "d", "ui_source": "s"},
+ force_deps=False,
+ build_ui=False,
+ force_ui=False,
+ remote=None,
+ )
+
+ joined = "\n".join(commands)
+ assert "test -d ui/dist && test -f ui/dist/index.html" in joined
+ assert "cd ui && npm run build" in joined
+ assert "pip install -e ." not in joined
+
+
+def test_prepare_show_runtime_cleans_partial_source_and_retries_once() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def __init__(self) -> None:
+ self.prepare_attempts = 0
+
+ def run(self, command, **kwargs):
+ joined = " ".join(command)
+ commands.append(joined)
+ if "vibe runtime prepare --strict" in joined:
+ self.prepare_attempts += 1
+ return subprocess.CompletedProcess(command, 1 if self.prepare_attempts == 1 else 0)
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.prepare_show_runtime(RecordingRunner(), target, remote=None)
+
+ joined = "\n".join(commands)
+ assert joined.count("vibe runtime prepare --strict") == 2
+ assert "rm -rf ~/.avibe/runtime/show-runtime/source ~/.npm/_cacache" in joined
+ assert "vibe runtime status --json" in joined
+
+
+def test_restart_waits_for_service_and_status_running() -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ return subprocess.CompletedProcess(command, 0)
+
+ target = incus_regression.RegressionTarget(
+ target="master",
+ slug="master",
+ project="avr-master",
+ instance="avibe-master",
+ host_port=15130,
+ ui_host="127.0.0.1",
+ ui_port=5123,
+ )
+
+ incus_regression.restart_and_verify(RecordingRunner(), target, remote=None)
+
+ joined = "\n".join(commands)
+ assert "systemctl is-active --quiet avibe-regression.service" in joined
+ assert "http://127.0.0.1:5123/status" in joined
+ assert "'\"state\":\"running\"'" in joined
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index df4d7c492..2be2bfc5e 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -310,6 +310,15 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
"show_pages_prompt": True,
"remote_access": None,
"language": "en",
+ "opencode": type(
+ "OpenCodeConfig",
+ (),
+ {
+ "default_model": "gpt-5.4",
+ "default_provider": "openai",
+ "default_reasoning_effort": "high",
+ },
+ )(),
},
)()
self.im_client = _StubClient("slack")
@@ -354,6 +363,8 @@ def test_opencode_prompt_disables_question_tool_for_all_platforms():
assert calls
assert calls[0]["tools"] == {"question": False}
+ assert calls[0]["model"] == {"providerID": "openai", "modelID": "gpt-5.4"}
+ assert calls[0]["reasoning_effort"] == "high"
def test_opencode_normal_text_matching_legacy_question_prefix_is_processed():
diff --git a/tests/test_opencode_default_provider_routing.py b/tests/test_opencode_default_provider_routing.py
index fb0411f3b..8eaf8e80c 100644
--- a/tests/test_opencode_default_provider_routing.py
+++ b/tests/test_opencode_default_provider_routing.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import dataclasses
from config.v2_config import OpenCodeConfig
+from modules.agents.opencode.agent import resolve_opencode_model_dict
def test_opencode_config_default_provider_is_unset_by_default() -> None:
@@ -26,40 +27,25 @@ def test_opencode_config_default_provider_is_unset_by_default() -> None:
assert fields["default_provider"].default is None
-def _resolve_model_dict(model_str: str, default_provider):
- """Replicates the bare-model branch in ``modules/agents/opencode/agent.py``.
-
- Kept verbatim so the test fails loudly if the agent-side guard regresses
- back to ``if default_provider:`` (which truthy-checked an empty string and
- forced bare-model strings onto Anthropic for legacy installs).
- """
- parts = model_str.split("/", 1)
- if len(parts) == 2:
- return {"providerID": parts[0], "modelID": parts[1]}
- if isinstance(default_provider, str) and default_provider.strip():
- return {"providerID": default_provider.strip(), "modelID": model_str}
- return None
-
-
def test_bare_model_with_no_default_provider_returns_none() -> None:
# Pre-upgrade behaviour: OpenCode owns routing for bare model IDs.
- assert _resolve_model_dict("kimi-k2", default_provider=None) is None
+ assert resolve_opencode_model_dict("kimi-k2", default_provider=None) is None
def test_bare_model_with_blank_default_provider_returns_none() -> None:
- assert _resolve_model_dict("kimi-k2", default_provider=" ") is None
- assert _resolve_model_dict("kimi-k2", default_provider="") is None
+ assert resolve_opencode_model_dict("kimi-k2", default_provider=" ") is None
+ assert resolve_opencode_model_dict("kimi-k2", default_provider="") is None
def test_bare_model_with_explicit_default_provider_injects_provider_id() -> None:
- assert _resolve_model_dict("kimi-k2", default_provider="ollama") == {
+ assert resolve_opencode_model_dict("kimi-k2", default_provider="ollama") == {
"providerID": "ollama",
"modelID": "kimi-k2",
}
def test_bare_model_strips_default_provider_whitespace() -> None:
- assert _resolve_model_dict("kimi-k2", default_provider=" ollama ") == {
+ assert resolve_opencode_model_dict("kimi-k2", default_provider=" ollama ") == {
"providerID": "ollama",
"modelID": "kimi-k2",
}
@@ -68,7 +54,7 @@ def test_bare_model_strips_default_provider_whitespace() -> None:
def test_prefixed_model_ignores_default_provider() -> None:
# Explicit ``provider/model`` always wins, even if the user configured a
# different default.
- assert _resolve_model_dict("openai/gpt-5", default_provider="ollama") == {
+ assert resolve_opencode_model_dict("openai/gpt-5", default_provider="ollama") == {
"providerID": "openai",
"modelID": "gpt-5",
}
diff --git a/tests/test_prepare_three_regression.py b/tests/test_prepare_regression.py
similarity index 80%
rename from tests/test_prepare_three_regression.py
rename to tests/test_prepare_regression.py
index 085a3d867..b792b075e 100644
--- a/tests/test_prepare_three_regression.py
+++ b/tests/test_prepare_regression.py
@@ -9,8 +9,8 @@ import pytest
def _load_module():
- script_path = Path(__file__).resolve().parents[1] / "scripts" / "prepare_three_regression.py"
- spec = importlib.util.spec_from_file_location("prepare_three_regression", script_path)
+ script_path = Path(__file__).resolve().parents[1] / "scripts" / "prepare_regression.py"
+ spec = importlib.util.spec_from_file_location("prepare_regression", script_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -24,36 +24,36 @@ def _set_required_env(monkeypatch: pytest.MonkeyPatch) -> None:
"OPENAI_API_KEY": "sk-openai-test",
"OPENAI_BASE_URL": "https://openai.example",
"OPENAI_API_BASE": "https://openai.example/v1",
- "THREE_REGRESSION_UI_HOST": "192.168.2.3",
- "THREE_REGRESSION_DEFAULT_CWD": "/home/avibe/.avibe/workdir",
- "THREE_REGRESSION_DEFAULT_BACKEND": "opencode",
- "THREE_REGRESSION_LOG_LEVEL": "DEBUG",
- "THREE_REGRESSION_LANGUAGE": "en",
- "THREE_REGRESSION_CLAUDE_BASE_URL": "https://ai-relay.example",
- "THREE_REGRESSION_CLAUDE_AUTH_TOKEN": "sk-claude-auth-token",
- "THREE_REGRESSION_CLAUDE_ATTRIBUTION_HEADER": "0",
- "THREE_REGRESSION_CODEX_MODEL": "gpt-5.4",
- "THREE_REGRESSION_CODEX_REVIEW_MODEL": "gpt-5.4",
- "THREE_REGRESSION_CODEX_REASONING_EFFORT": "xhigh",
- "THREE_REGRESSION_CODEX_BASE_URL": "https://ai-relay.example",
- "THREE_REGRESSION_CODEX_OPENAI_API_KEY": "sk-codex-openai",
- "THREE_REGRESSION_OPENCODE_OPENAI_BASE_URL": "https://ai-relay.example/v1",
- "THREE_REGRESSION_OPENCODE_OPENAI_API_KEY": "sk-opencode-openai",
- "THREE_REGRESSION_OPENCODE_ANTHROPIC_BASE_URL": "https://ai-relay.example/v1",
- "THREE_REGRESSION_OPENCODE_ANTHROPIC_API_KEY": "sk-opencode-anthropic",
- "THREE_REGRESSION_SLACK_BOT_TOKEN": "xoxb-test-token",
- "THREE_REGRESSION_SLACK_APP_TOKEN": "xapp-test-token",
- "THREE_REGRESSION_SLACK_CHANNEL": "C123SLACK",
- "THREE_REGRESSION_SLACK_BACKEND": "opencode",
- "THREE_REGRESSION_DISCORD_BOT_TOKEN": "discord-token-1234567890",
- "THREE_REGRESSION_DISCORD_CHANNEL": "123456789012345678",
- "THREE_REGRESSION_DISCORD_GUILD_ALLOWLIST": "754776951587340359",
- "THREE_REGRESSION_DISCORD_BACKEND": "codex",
- "THREE_REGRESSION_FEISHU_APP_ID": "cli_test_app_id",
- "THREE_REGRESSION_FEISHU_APP_SECRET": "test-app-secret",
- "THREE_REGRESSION_FEISHU_CHAT_ID": "oc_test_chat_id",
- "THREE_REGRESSION_FEISHU_BACKEND": "claude",
- "THREE_REGRESSION_WECHAT_BACKEND": "opencode",
+ "REGRESSION_UI_HOST": "192.168.2.3",
+ "REGRESSION_DEFAULT_CWD": "/home/avibe/.avibe/workdir",
+ "REGRESSION_DEFAULT_BACKEND": "opencode",
+ "REGRESSION_LOG_LEVEL": "DEBUG",
+ "REGRESSION_LANGUAGE": "en",
+ "REGRESSION_CLAUDE_BASE_URL": "https://ai-relay.example",
+ "REGRESSION_CLAUDE_AUTH_TOKEN": "sk-claude-auth-token",
+ "REGRESSION_CLAUDE_ATTRIBUTION_HEADER": "0",
+ "REGRESSION_CODEX_MODEL": "gpt-5.4",
+ "REGRESSION_CODEX_REVIEW_MODEL": "gpt-5.4",
+ "REGRESSION_CODEX_REASONING_EFFORT": "xhigh",
+ "REGRESSION_CODEX_BASE_URL": "https://ai-relay.example",
+ "REGRESSION_CODEX_OPENAI_API_KEY": "sk-codex-openai",
+ "REGRESSION_OPENCODE_OPENAI_BASE_URL": "https://ai-relay.example/v1",
+ "REGRESSION_OPENCODE_OPENAI_API_KEY": "sk-opencode-openai",
+ "REGRESSION_OPENCODE_ANTHROPIC_BASE_URL": "https://ai-relay.example/v1",
+ "REGRESSION_OPENCODE_ANTHROPIC_API_KEY": "sk-opencode-anthropic",
+ "REGRESSION_SLACK_BOT_TOKEN": "xoxb-test-token",
+ "REGRESSION_SLACK_APP_TOKEN": "xapp-test-token",
+ "REGRESSION_SLACK_CHANNEL": "C123SLACK",
+ "REGRESSION_SLACK_BACKEND": "opencode",
+ "REGRESSION_DISCORD_BOT_TOKEN": "discord-token-1234567890",
+ "REGRESSION_DISCORD_CHANNEL": "123456789012345678",
+ "REGRESSION_DISCORD_GUILD_ALLOWLIST": "754776951587340359",
+ "REGRESSION_DISCORD_BACKEND": "codex",
+ "REGRESSION_FEISHU_APP_ID": "cli_test_app_id",
+ "REGRESSION_FEISHU_APP_SECRET": "test-app-secret",
+ "REGRESSION_FEISHU_CHAT_ID": "oc_test_chat_id",
+ "REGRESSION_FEISHU_BACKEND": "claude",
+ "REGRESSION_WECHAT_BACKEND": "opencode",
}
for key, value in values.items():
monkeypatch.setenv(key, value)
@@ -85,6 +85,8 @@ def test_prepare_generates_unified_state(tmp_path: Path, monkeypatch: pytest.Mon
assert config["agents"]["codex"]["enabled"] is True
assert config["agents"]["default_backend"] == "opencode"
assert config["agents"]["opencode"]["cli_path"] == "/usr/local/bin/opencode"
+ assert config["agents"]["opencode"]["default_model"] == "gpt-5.4"
+ assert config["agents"]["opencode"]["default_provider"] == "openai"
# UI host propagated
assert config["ui"]["setup_host"] == "192.168.2.3"
@@ -115,6 +117,8 @@ def test_prepare_generates_unified_state(tmp_path: Path, monkeypatch: pytest.Mon
)
codex_config = (tmp_path / "home" / ".codex" / "config.toml").read_text(encoding="utf-8")
assert 'model = "gpt-5.4"' in codex_config
+ assert 'base_url = "https://ai-relay.example"' in codex_config
+ assert "supports_websockets = false" in codex_config
assert "responses_websockets_v2 = false" in codex_config
assert "suppress_unstable_features_warning = true" in codex_config
opencode_config = json.loads(
@@ -124,6 +128,45 @@ def test_prepare_generates_unified_state(tmp_path: Path, monkeypatch: pytest.Mon
assert opencode_config["provider"]["openai"]["options"]["baseURL"] == "https://ai-relay.example/v1"
+def test_prepare_derives_openai_relay_base_from_anthropic_base(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ module = _load_module()
+ _set_required_env(monkeypatch)
+ for key in (
+ "OPENAI_API_BASE",
+ "OPENAI_BASE_URL",
+ "REGRESSION_CODEX_BASE_URL",
+ "REGRESSION_OPENCODE_OPENAI_BASE_URL",
+ ):
+ monkeypatch.delenv(key, raising=False)
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://relay.example")
+
+ module.prepare(tmp_path)
+
+ codex_config = (tmp_path / "home" / ".codex" / "config.toml").read_text(encoding="utf-8")
+ opencode_config = json.loads(
+ (tmp_path / "home" / ".config" / "opencode" / "opencode.json").read_text(encoding="utf-8")
+ )
+ assert 'base_url = "https://relay.example/v1"' in codex_config
+ assert "supports_websockets = false" in codex_config
+ assert opencode_config["provider"]["openai"]["options"]["baseURL"] == "https://relay.example/v1"
+
+
+def test_prepare_accepts_legacy_regression_env_names(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ module = _load_module()
+ _set_required_env(monkeypatch)
+ monkeypatch.delenv("REGRESSION_SLACK_CHANNEL", raising=False)
+ monkeypatch.delenv("REGRESSION_SLACK_BACKEND", raising=False)
+ monkeypatch.setenv("THREE_REGRESSION_SLACK_CHANNEL", "C123LEGACY")
+ monkeypatch.setenv("THREE_REGRESSION_SLACK_BACKEND", "codex")
+
+ module.prepare(tmp_path)
+
+ settings = json.loads((tmp_path / "home" / ".avibe" / "state" / "settings.json").read_text(encoding="utf-8"))
+ assert settings["scopes"]["channel"]["slack"]["C123LEGACY"]["routing"]["agent_backend"] == "codex"
+
+
def test_prepare_preserves_existing_state_without_reset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
module = _load_module()
_set_required_env(monkeypatch)
@@ -147,11 +190,11 @@ def test_prepare_preserves_existing_state_without_reset(tmp_path: Path, monkeypa
for key in (
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
- "THREE_REGRESSION_SLACK_BOT_TOKEN",
- "THREE_REGRESSION_SLACK_APP_TOKEN",
- "THREE_REGRESSION_DISCORD_BOT_TOKEN",
- "THREE_REGRESSION_FEISHU_APP_ID",
- "THREE_REGRESSION_FEISHU_APP_SECRET",
+ "REGRESSION_SLACK_BOT_TOKEN",
+ "REGRESSION_SLACK_APP_TOKEN",
+ "REGRESSION_DISCORD_BOT_TOKEN",
+ "REGRESSION_FEISHU_APP_ID",
+ "REGRESSION_FEISHU_APP_SECRET",
):
monkeypatch.delenv(key, raising=False)
@@ -377,16 +420,20 @@ def test_prepare_without_reset_still_requires_platform_envs_when_config_missing(
(shared_home / ".codex" / "auth.json").write_text("{}", encoding="utf-8")
(shared_home / ".config" / "opencode" / "opencode.json").write_text("{}", encoding="utf-8")
- monkeypatch.delenv("THREE_REGRESSION_SLACK_BOT_TOKEN", raising=False)
- monkeypatch.delenv("THREE_REGRESSION_SLACK_APP_TOKEN", raising=False)
+ monkeypatch.delenv("REGRESSION_SLACK_BOT_TOKEN", raising=False)
+ monkeypatch.delenv("REGRESSION_SLACK_APP_TOKEN", raising=False)
- with pytest.raises(SystemExit, match="THREE_REGRESSION_SLACK_BOT_TOKEN, THREE_REGRESSION_SLACK_APP_TOKEN"):
+ with pytest.raises(SystemExit, match="REGRESSION_SLACK_BOT_TOKEN, REGRESSION_SLACK_APP_TOKEN"):
module.prepare(tmp_path)
def test_prepare_allows_missing_channel_ids(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
module = _load_module()
_set_required_env(monkeypatch)
+ monkeypatch.delenv("REGRESSION_SLACK_CHANNEL", raising=False)
+ monkeypatch.delenv("REGRESSION_DISCORD_CHANNEL", raising=False)
+ monkeypatch.delenv("REGRESSION_FEISHU_CHAT_ID", raising=False)
+ monkeypatch.delenv("REGRESSION_WECHAT_CHANNEL", raising=False)
monkeypatch.delenv("THREE_REGRESSION_SLACK_CHANNEL", raising=False)
monkeypatch.delenv("THREE_REGRESSION_DISCORD_CHANNEL", raising=False)
monkeypatch.delenv("THREE_REGRESSION_FEISHU_CHAT_ID", raising=False)
@@ -404,8 +451,8 @@ def test_prepare_allows_missing_channel_ids(tmp_path: Path, monkeypatch: pytest.
def test_prepare_preserves_discord_denylist_only_guild_policy(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
module = _load_module()
_set_required_env(monkeypatch)
- monkeypatch.delenv("THREE_REGRESSION_DISCORD_GUILD_ALLOWLIST", raising=False)
- monkeypatch.setenv("THREE_REGRESSION_DISCORD_GUILD_DENYLIST", "blocked-guild")
+ monkeypatch.delenv("REGRESSION_DISCORD_GUILD_ALLOWLIST", raising=False)
+ monkeypatch.setenv("REGRESSION_DISCORD_GUILD_DENYLIST", "blocked-guild")
module.prepare(tmp_path, reset_mode="config")
@@ -417,9 +464,9 @@ def test_prepare_preserves_discord_denylist_only_guild_policy(tmp_path: Path, mo
def test_prepare_requires_supported_backend(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
module = _load_module()
_set_required_env(monkeypatch)
- monkeypatch.setenv("THREE_REGRESSION_SLACK_BACKEND", "unknown")
+ monkeypatch.setenv("REGRESSION_SLACK_BACKEND", "unknown")
- with pytest.raises(SystemExit, match="THREE_REGRESSION_SLACK_BACKEND"):
+ with pytest.raises(SystemExit, match="REGRESSION_SLACK_BACKEND"):
module.prepare(tmp_path)
@@ -468,13 +515,13 @@ def test_prepare_reset_config_rewrites_shared_agent_configs(tmp_path: Path, monk
encoding="utf-8",
)
- monkeypatch.setenv("THREE_REGRESSION_CODEX_MODEL", "gpt-5.4")
- monkeypatch.setenv("THREE_REGRESSION_CODEX_OPENAI_API_KEY", "sk-codex-new")
- monkeypatch.setenv("THREE_REGRESSION_OPENCODE_OPENAI_API_KEY", "sk-opencode-new")
- monkeypatch.setenv("THREE_REGRESSION_OPENCODE_ANTHROPIC_API_KEY", "sk-opencode-anthropic-new")
- monkeypatch.setenv("THREE_REGRESSION_OPENCODE_OPENAI_BASE_URL", "https://fresh.example/v1")
- monkeypatch.setenv("THREE_REGRESSION_OPENCODE_ANTHROPIC_BASE_URL", "https://fresh.example/v1")
- monkeypatch.setenv("THREE_REGRESSION_CLAUDE_AUTH_TOKEN", "sk-claude-fresh")
+ monkeypatch.setenv("REGRESSION_CODEX_MODEL", "gpt-5.4")
+ monkeypatch.setenv("REGRESSION_CODEX_OPENAI_API_KEY", "sk-codex-new")
+ monkeypatch.setenv("REGRESSION_OPENCODE_OPENAI_API_KEY", "sk-opencode-new")
+ monkeypatch.setenv("REGRESSION_OPENCODE_ANTHROPIC_API_KEY", "sk-opencode-anthropic-new")
+ monkeypatch.setenv("REGRESSION_OPENCODE_OPENAI_BASE_URL", "https://fresh.example/v1")
+ monkeypatch.setenv("REGRESSION_OPENCODE_ANTHROPIC_BASE_URL", "https://fresh.example/v1")
+ monkeypatch.setenv("REGRESSION_CLAUDE_AUTH_TOKEN", "sk-claude-fresh")
module.prepare(tmp_path, reset_mode="config")
@@ -530,7 +577,7 @@ def test_prepare_reset_all_clears_workdir(tmp_path: Path, monkeypatch: pytest.Mo
def test_prepare_default_backend_from_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
module = _load_module()
_set_required_env(monkeypatch)
- monkeypatch.setenv("THREE_REGRESSION_DEFAULT_BACKEND", "claude")
+ monkeypatch.setenv("REGRESSION_DEFAULT_BACKEND", "claude")
module.prepare(tmp_path, reset_mode="config")
@@ -541,8 +588,8 @@ def test_prepare_default_backend_from_env(tmp_path: Path, monkeypatch: pytest.Mo
def test_prepare_all_platform_channel_routing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
module = _load_module()
_set_required_env(monkeypatch)
- monkeypatch.setenv("THREE_REGRESSION_WECHAT_CHANNEL", "wx_test_room")
- monkeypatch.setenv("THREE_REGRESSION_WECHAT_BACKEND", "codex")
+ monkeypatch.setenv("REGRESSION_WECHAT_CHANNEL", "wx_test_room")
+ monkeypatch.setenv("REGRESSION_WECHAT_BACKEND", "codex")
module.prepare(tmp_path, reset_mode="config")
diff --git a/tests/test_regression_script.py b/tests/test_regression_script.py
new file mode 100644
index 000000000..b860b2983
--- /dev/null
+++ b/tests/test_regression_script.py
@@ -0,0 +1,100 @@
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def test_regression_script_has_valid_shell_syntax() -> None:
+ subprocess.run(
+ ["bash", "-n", str(REPO_ROOT / "scripts" / "run_regression.sh")],
+ check=True,
+ cwd=REPO_ROOT,
+ )
+ subprocess.run(
+ ["bash", "-n", str(REPO_ROOT / "scripts" / "run_three_regression.sh")],
+ check=True,
+ cwd=REPO_ROOT,
+ )
+
+
+def test_regression_script_is_incus_only_wrapper() -> None:
+ script = (REPO_ROOT / "scripts" / "run_regression.sh").read_text(encoding="utf-8")
+
+ assert "scripts/incus_regression.py" in script
+ assert "docker compose" not in script
+ assert "--docker" not in script
+ assert "REGRESSION_STATE_ROOT" not in script
+
+
+def test_regression_script_maps_legacy_flags_to_incus() -> None:
+ script = (REPO_ROOT / "scripts" / "run_regression.sh").read_text(encoding="utf-8")
+
+ assert "--reset-config)" in script
+ assert "incus_args+=(--reset-mode config)" in script
+ assert "--reset-all|--reset-state)" in script
+ assert "incus_args+=(--reset-mode all)" in script
+ assert "--no-build)" in script
+ assert "incus_args+=(--no-build-ui)" in script
+
+
+def test_legacy_three_regression_script_delegates_to_new_wrapper() -> None:
+ script = (REPO_ROOT / "scripts" / "run_three_regression.sh").read_text(encoding="utf-8")
+
+ assert 'exec "$SCRIPT_DIR/run_regression.sh" "$@"' in script
+
+
+def test_regression_maintenance_commands_accept_env_file(tmp_path: Path) -> None:
+ env_file = tmp_path / ".env.regression"
+ env_file.write_text("REGRESSION_PORT=15999\n", encoding="utf-8")
+
+ subprocess.run(
+ [
+ str(REPO_ROOT / "scripts" / "run_three_regression.sh"),
+ "--status",
+ "--env-file",
+ str(env_file),
+ "--dry-run",
+ ],
+ check=True,
+ cwd=REPO_ROOT,
+ )
+
+
+def test_regression_wrapper_forwards_worktree_port_range() -> None:
+ subprocess.run(
+ [
+ str(REPO_ROOT / "scripts" / "run_regression.sh"),
+ "--worktree",
+ "--slug",
+ "demo-branch",
+ "--worktree-port-start",
+ "15240",
+ "--worktree-port-end",
+ "15240",
+ "--dry-run",
+ "--no-build-ui",
+ ],
+ check=True,
+ cwd=REPO_ROOT,
+ )
+
+
+def test_regression_wrapper_accepts_documented_remote_flag() -> None:
+ result = subprocess.run(
+ [
+ str(REPO_ROOT / "scripts" / "run_regression.sh"),
+ "--remote",
+ "lab",
+ "--status",
+ "--dry-run",
+ ],
+ check=True,
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ )
+
+ assert "lab:avibe-master" in result.stdout
diff --git a/tests/test_three_regression_script.py b/tests/test_three_regression_script.py
deleted file mode 100644
index 61823b9c9..000000000
--- a/tests/test_three_regression_script.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from __future__ import annotations
-
-import subprocess
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-
-
-def test_three_regression_script_has_valid_shell_syntax() -> None:
- subprocess.run(
- ["bash", "-n", str(REPO_ROOT / "scripts" / "run_three_regression.sh")],
- check=True,
- cwd=REPO_ROOT,
- )
-
-
-def test_three_regression_compose_uses_canonical_state_root_env() -> None:
- compose = (REPO_ROOT / "docker-compose.three-regression.yml").read_text(encoding="utf-8")
-
- assert "${THREE_REGRESSION_STATE_ROOT:" in compose
- assert "./_tmp/three-regression" not in compose
- assert "VIBE_SHOW_RUNTIME_SOURCE" in compose
- assert "VIBE_INTERNAL_DISPATCH_SOCKET: /tmp/vibe_remote/dispatch.sock" in compose
-
-
-def test_three_regression_script_serializes_state_updates() -> None:
- script = (REPO_ROOT / "scripts" / "run_three_regression.sh").read_text(encoding="utf-8")
-
- assert "$OUTPUT_ROOT/.run.lock" in script
- assert "Another three-regression update is already running." in script
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 24f5f8716..c9935b7ba 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1,11 +1,21 @@
import asyncio
import json
import time
+from dataclasses import dataclass
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
+from config.v2_config import (
+ AgentsConfig,
+ CodexConfig,
+ PlatformsConfig,
+ RuntimeConfig,
+ SlackConfig,
+ UiConfig,
+ V2Config,
+)
from config import paths
from core.vibe_agents import VibeAgentStore
from core import chat_discovery
@@ -2314,6 +2324,42 @@ def test_builtin_default_agent_enabled_state_follows_backend_config(tmp_path, mo
store.close()
+def test_enabled_agent_backends_treat_missing_enabled_field_as_schema_default():
+ @dataclass
+ class LegacyCodexConfig:
+ cli_path: str = "codex"
+
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token="xoxb-test", app_token="xapp-test"),
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ runtime=RuntimeConfig(default_cwd="/tmp/work"),
+ agents=AgentsConfig(codex=LegacyCodexConfig()), # type: ignore[arg-type]
+ ui=UiConfig(),
+ )
+ config.agents.opencode.enabled = False
+ config.agents.claude.enabled = False
+
+ assert api._enabled_agent_backends_from_config(config) == ["codex"]
+
+
+def test_enabled_agent_backends_respect_explicit_disabled_backend():
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(bot_token="xoxb-test", app_token="xapp-test"),
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ runtime=RuntimeConfig(default_cwd="/tmp/work"),
+ agents=AgentsConfig(codex=CodexConfig(enabled=False)),
+ ui=UiConfig(),
+ )
+ config.agents.opencode.enabled = False
+ config.agents.claude.enabled = False
+
+ assert api._enabled_agent_backends_from_config(config) == []
+
+
def test_user_can_disable_builtin_default_agent_without_catalog_reenabling_it(tmp_path, monkeypatch):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
store = VibeAgentStore()
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 2e48f7204..f379793e8 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -37,12 +37,14 @@ class _FakeShowRuntimeManager:
fail: bool = False,
status_code: int = 200,
extra_headers: dict[str, str] | None = None,
+ headers_by_path: dict[str, dict[str, str]] | None = None,
bodies_by_path: dict[str, bytes] | None = None,
):
self.body = body
self.fail = fail
self.status_code = status_code
self.extra_headers = extra_headers or {}
+ self.headers_by_path = headers_by_path or {}
self.bodies_by_path = bodies_by_path or {}
self.calls = []
self.websocket_paths = []
@@ -58,7 +60,7 @@ class _FakeShowRuntimeManager:
"content-type": "text/html; charset=utf-8",
"set-cookie": "__Host-vibe_remote_session=attacker",
"x-runtime-private-header": "secret",
- } | self.extra_headers
+ } | self.extra_headers | self.headers_by_path.get(path, {})
return httpx.Response(self.status_code, content=self.bodies_by_path.get(path, self.body), headers=headers)
async def websocket_url(self, path):
@@ -354,7 +356,7 @@ def test_show_runtime_vendor_deps_are_cacheable(monkeypatch, tmp_path):
set_show_runtime_manager_for_tests(None)
assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r4-d6d38251/react-dom_client.js"
+ assert response.headers["location"] == "/_show-runtime/deps/r8-d6d38251/react-dom_client.js"
assert response.headers["cache-control"] == "no-store"
assert "set-cookie" not in response.headers
@@ -377,7 +379,7 @@ def test_show_runtime_public_dep_proxy_is_cacheable(monkeypatch, tmp_path):
base_url="http://127.0.0.1:5123",
)
response = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -390,6 +392,42 @@ def test_show_runtime_public_dep_proxy_is_cacheable(monkeypatch, tmp_path):
assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/react.js?v=d6d38251"
+def test_show_runtime_public_dep_proxy_compresses_large_javascript(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(
+ body=(b"export const value = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';\n" * 200),
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ "content-length": "12000",
+ "etag": "source-etag",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ app.test_client().get(
+ "/show/ses123/node_modules/.vite/deps/react.js?v=d6d38251",
+ base_url="http://127.0.0.1:5123",
+ )
+ response = app.test_client().get(
+ "/_show-runtime/deps/r8-d6d38251/react.js?v=d6d38251",
+ base_url="http://127.0.0.1:5123",
+ headers={"Accept-Encoding": "gzip"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert response.headers["content-encoding"] == "gzip"
+ assert response.headers["vary"] == "Accept-Encoding"
+ assert response.headers["content-length"] != "12000"
+ assert "etag" not in response.headers
+ assert response.content.startswith(b"export const value")
+ assert "accept-encoding" not in manager.calls[-1][2]
+
+
def test_show_runtime_public_dep_proxy_allows_scoped_package_names(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -408,14 +446,14 @@ def test_show_runtime_public_dep_proxy_allows_scoped_package_names(monkeypatch,
base_url="http://127.0.0.1:5123",
)
response = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/%40avibe_show-ui_theme.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/%40avibe_show-ui_theme.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
finally:
set_show_runtime_manager_for_tests(None)
assert original.status_code == 302
- assert original.headers["location"] == "/_show-runtime/deps/r4-d6d38251/%40avibe_show-ui_theme.js"
+ assert original.headers["location"] == "/_show-runtime/deps/r8-d6d38251/%40avibe_show-ui_theme.js"
assert response.status_code == 200
assert response.headers["cache-control"] == "public, max-age=31536000, immutable"
assert manager.calls[-1][1] == "/sessions/ses123/app/node_modules/.vite/deps/@avibe_show-ui_theme.js?v=d6d38251"
@@ -442,11 +480,11 @@ def test_show_runtime_public_dep_proxy_registers_sibling_chunks(monkeypatch, tmp
base_url="http://127.0.0.1:5123",
)
dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react-dom_client.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
chunk = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/chunk-OUYO74D4.js?v=108951fb",
+ "/_show-runtime/deps/r8-108951fb/chunk-OUYO74D4.js?v=108951fb",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -454,7 +492,7 @@ def test_show_runtime_public_dep_proxy_registers_sibling_chunks(monkeypatch, tmp
assert original.status_code == 302
assert dep.status_code == 200
- assert b'import "/_show-runtime/deps/r4-d6d38251/chunk-OUYO74D4.js?v=108951fb"' in dep.content
+ assert b'import "/_show-runtime/deps/r8-108951fb/chunk-OUYO74D4.js?v=108951fb"' in dep.content
assert dep.headers["cache-control"] == "no-store"
assert chunk.status_code == 200
assert chunk.headers["cache-control"] == "public, max-age=31536000, immutable"
@@ -486,11 +524,11 @@ def test_show_runtime_public_dep_proxy_rewrites_private_chunk_imports(monkeypatc
base_url="http://127.0.0.1:5123",
)
dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react-dom_client.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
chunk = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/chunk-QA663NX4.js?v=108951fb",
+ "/_show-runtime/deps/r8-108951fb/chunk-QA663NX4.js?v=108951fb",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -498,7 +536,7 @@ def test_show_runtime_public_dep_proxy_rewrites_private_chunk_imports(monkeypatc
assert original.status_code == 302
assert dep.status_code == 200
- assert b'import "/_show-runtime/deps/r4-d6d38251/chunk-QA663NX4.js?v=108951fb"' in dep.content
+ assert b'import "/_show-runtime/deps/r8-108951fb/chunk-QA663NX4.js?v=108951fb"' in dep.content
assert b'"/show/ses123/@fs/' not in dep.content
assert dep.headers["cache-control"] == "no-store"
assert chunk.status_code == 200
@@ -530,7 +568,7 @@ def test_show_runtime_public_dep_proxy_refreshes_private_chunk_registry(monkeypa
base_url="http://127.0.0.1:5123",
)
first_dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react-dom_client.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
manager.body = (
@@ -542,11 +580,11 @@ def test_show_runtime_public_dep_proxy_refreshes_private_chunk_registry(monkeypa
base_url="http://127.0.0.1:5123",
)
second_dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react-dom_client.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
chunk = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/chunk-QA663NX4.js?v=new222",
+ "/_show-runtime/deps/r8-new222/chunk-QA663NX4.js?v=new222",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -557,7 +595,7 @@ def test_show_runtime_public_dep_proxy_refreshes_private_chunk_registry(monkeypa
assert first_dep.headers["cache-control"] == "no-store"
assert second_original.status_code == 302
assert second_dep.status_code == 200
- assert b"/_show-runtime/deps/r4-d6d38251/chunk-QA663NX4.js?v=new222" in second_dep.content
+ assert b"/_show-runtime/deps/r8-new222/chunk-QA663NX4.js?v=new222" in second_dep.content
assert second_dep.headers["cache-control"] == "no-store"
assert chunk.status_code == 200
assert manager.calls[-1][1] == (
@@ -584,7 +622,7 @@ def test_show_runtime_public_dep_proxy_derives_chunk_paths_when_registry_is_cold
base_url="http://127.0.0.1:5123",
)
chunk = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/chunk-OUYO74D4.js?v=108951fb",
+ "/_show-runtime/deps/r8-d6d38251/chunk-OUYO74D4.js?v=108951fb",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -638,7 +676,7 @@ def test_show_runtime_public_dep_rejects_unregistered_cache_key_without_cache(mo
_save_config(tmp_path)
response = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react.js",
+ "/_show-runtime/deps/r8-d6d38251/react.js",
base_url="http://127.0.0.1:5123",
)
@@ -667,7 +705,7 @@ def test_show_runtime_relocated_vendor_deps_are_cacheable(monkeypatch, tmp_path)
set_show_runtime_manager_for_tests(None)
assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r4-d6d38251/react-dom_client.js"
+ assert response.headers["location"] == "/_show-runtime/deps/r8-d6d38251/react-dom_client.js"
assert "set-cookie" not in response.headers
@@ -766,14 +804,14 @@ def test_show_runtime_source_rewrites_dep_imports_to_public_paths(monkeypatch, t
base_url="http://127.0.0.1:5123",
)
public_dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
finally:
set_show_runtime_manager_for_tests(None)
assert response.status_code == 200
- assert b'"/_show-runtime/deps/r4-d6d38251/react.js"' in response.content
+ assert b'"/_show-runtime/deps/r8-d6d38251/react.js?v=d6d38251"' in response.content
assert b'"./App.tsx"' in response.content
assert response.headers["cache-control"] == "no-store"
assert "etag" not in response.headers
@@ -803,14 +841,14 @@ def test_show_runtime_source_rewrites_prefixed_fs_vite_cache_dep_imports(monkeyp
base_url="http://127.0.0.1:5123",
)
public_dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react-dom_client.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
finally:
set_show_runtime_manager_for_tests(None)
assert response.status_code == 200
- assert b'"/_show-runtime/deps/r4-d6d38251/react-dom_client.js"' in response.content
+ assert b'"/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251"' in response.content
assert response.headers["cache-control"] == "no-store"
assert "etag" not in response.headers
assert public_dep.status_code == 200
@@ -846,14 +884,337 @@ def test_public_show_runtime_source_rewrites_private_runtime_paths(monkeypatch,
set_show_runtime_manager_for_tests(None)
assert response.status_code == 200
- assert f'"/p/{share_id}/@vite/client"'.encode() in response.content
- assert f'"/p/{share_id}/@react-refresh"'.encode() in response.content
+ assert b'"/_show-runtime/client-shim-r8.js"' in response.content
+ assert b'"/_show-runtime/react-refresh-shim-r8.js"' in response.content
+ assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
+ assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
assert f'"/p/{share_id}/__vite_hmr"'.encode() in response.content
assert b'"/show/ses123/' not in response.content
assert response.headers["cache-control"] == "no-store"
assert "etag" not in response.headers
+def test_public_show_runtime_html_rewrites_private_runtime_client_paths(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(
+ body=(
+ b'<script type="module">import { injectIntoGlobalHook } from "/show/ses123/@react-refresh";</script>'
+ b'<script type="module" src="/show/ses123/@vite/client"></script>'
+ b'<script type="module" src="/show/ses123/src/main.tsx"></script>'
+ ),
+ extra_headers={
+ "content-type": "text/html; charset=utf-8",
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert b'"/_show-runtime/client-shim-r8.js"' in response.content
+ assert b'"/_show-runtime/react-refresh-shim-r8.js"' in response.content
+ assert f'"/p/{share_id}/src/main.tsx"'.encode() in response.content
+ assert b'"/show/ses123/' not in response.content
+ assert f'"/p/{share_id}/@vite/client"'.encode() not in response.content
+ assert f'"/p/{share_id}/@react-refresh"'.encode() not in response.content
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
+
+
+def test_public_show_runtime_html_preloads_entry_direct_imports(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><html><head></head><body><script type="module" src="./src/main.tsx"></script></body></html>',
+ bodies_by_path={
+ "/sessions/ses123/app/": b'<!doctype html><html><head></head><body><script type="module" src="./src/main.tsx"></script></body></html>',
+ "/sessions/ses123/app/src/main.tsx": (
+ b'import "/node_modules/.vite/deps/react-dom_client.js?v=d6d38251";'
+ b'import "./styles.css";'
+ b'import App from "./App.tsx";'
+ ),
+ "/sessions/ses123/app/src/App.tsx": f'import {{ Button }} from "{package_path}";'.encode("utf-8"),
+ f"/sessions/ses123/app{package_path}": (
+ b'import { motion } from "/node_modules/.vite/deps/motion_react.js?v=d8d245fb";'
+ b'import { cn } from "./utils.js";'
+ ),
+ },
+ headers_by_path={
+ "/sessions/ses123/app/": {"content-type": "text/html; charset=utf-8"},
+ "/sessions/ses123/app/src/main.tsx": {"content-type": "text/javascript"},
+ "/sessions/ses123/app/src/App.tsx": {"content-type": "text/javascript"},
+ f"/sessions/ses123/app{package_path}": {"content-type": "text/javascript"},
+ },
+ extra_headers={
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert f'<link rel="modulepreload" href="/p/{share_id}/src/main.tsx">'.encode() in response.content
+ assert b'<link rel="modulepreload" href="/_show-runtime/deps/r8-d6d38251/react-dom_client.js?v=d6d38251">' in response.content
+ assert f'<link rel="modulepreload" href="/p/{share_id}/src/styles.css">'.encode() in response.content
+ assert b'<link rel="modulepreload" href="/_show-runtime/deps/r8-m' in response.content
+ assert b'/button.js">' in response.content
+ assert b'<link rel="modulepreload" href="/_show-runtime/deps/r8-d8d245fb/motion_react.js?v=d8d245fb">' in response.content
+ assert b"/utils.js" in response.content
+ assert response.content.index(b'rel="modulepreload"') < response.content.index(b"</head>")
+ assert package_path.encode() not in response.content
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
+
+
+def test_public_show_runtime_javascript_strips_inline_source_map(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(
+ body=b"export const ok = true;\n//# sourceMappingURL=data:application/json;base64,AAAA",
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ "sourcemap": "app.js.map",
+ "x-sourcemap": "app.js.map",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/src/App.tsx?t=1780732068677",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert b"export const ok = true;" in response.content
+ assert b"sourceMappingURL=data:" not in response.content
+ assert response.headers["cache-control"] == "no-store"
+ assert "etag" not in response.headers
+ assert "sourcemap" not in response.headers
+ assert "x-sourcemap" not in response.headers
+
+
+def test_show_runtime_public_dep_strips_inline_source_map_without_disabling_cache(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(
+ body=b"export const ok = true;\n//# sourceMappingURL=data:application/json;base64,AAAA",
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ "sourcemap": "react-dom_client.js.map",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ source = app.test_client().get(
+ f"/p/{share_id}/node_modules/.vite/deps/react-dom_client.js?v=d6d38251",
+ base_url="http://127.0.0.1:5123",
+ )
+ public_dep = app.test_client().get(
+ "/_show-runtime/deps/r8-d6d38251/react-dom_client.js",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert source.status_code == 302
+ assert public_dep.status_code == 200
+ assert b"sourceMappingURL=data:" not in public_dep.content
+ assert public_dep.headers["cache-control"] == "public, max-age=31536000, immutable"
+ assert "etag" not in public_dep.headers
+ assert "sourcemap" not in public_dep.headers
+
+
+def test_public_show_runtime_rewrites_package_dist_modules_to_public_deps(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
+ manager = _FakeShowRuntimeManager(
+ body=f'import "{package_path}";'.encode("utf-8"),
+ bodies_by_path={
+ f"/sessions/ses123/app{package_path}": b'export { Button } from "./utils.js";',
+ },
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ response = app.test_client().get(
+ f"/p/{share_id}/src/App.tsx?t=1780732068677",
+ base_url="http://127.0.0.1:5123",
+ )
+ public_path = response.content.decode("utf-8").split('"')[1]
+ public_dep = app.test_client().get(
+ public_path,
+ base_url="http://127.0.0.1:5123",
+ )
+ sibling_path = public_dep.content.decode("utf-8").split('"')[1]
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert response.status_code == 200
+ assert public_path.startswith("/_show-runtime/deps/r8-m")
+ assert public_path.endswith("/button.js")
+ assert package_path.encode() not in response.content
+ assert public_dep.status_code == 200
+ assert public_dep.headers["cache-control"] == "no-store"
+ assert sibling_path.startswith(public_path.rsplit("/", 1)[0])
+ assert sibling_path.endswith("/utils.js")
+ assert manager.calls[-1][1] == f"/sessions/ses123/app{package_path}"
+
+
+def test_show_runtime_public_package_dep_rewrites_private_client_imports(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/button.js"
+ manager = _FakeShowRuntimeManager(
+ body=f'import "{package_path}";'.encode("utf-8"),
+ bodies_by_path={
+ f"/sessions/ses123/app{package_path}": (
+ b'import { createHotContext as __vite__createHotContext } from "/show/ses123/@vite/client";'
+ b'import * as RefreshRuntime from "/show/ses123/@react-refresh";'
+ b"export const Button = true;"
+ ),
+ },
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ "etag": "source-etag",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ source = app.test_client().get(
+ f"/p/{share_id}/src/App.tsx?t=1780732068677",
+ base_url="http://127.0.0.1:5123",
+ )
+ public_path = source.content.decode("utf-8").split('"')[1]
+ public_dep = app.test_client().get(
+ public_path,
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert source.status_code == 200
+ assert public_dep.status_code == 200
+ assert b'"/_show-runtime/client-shim-r8.js"' in public_dep.content
+ assert b'"/_show-runtime/react-refresh-shim-r8.js"' in public_dep.content
+ assert b'"/show/ses123/@vite/client"' not in public_dep.content
+ assert b'"/show/ses123/@react-refresh"' not in public_dep.content
+ assert public_dep.headers["cache-control"] == "no-store"
+
+
+def test_show_runtime_public_package_dep_siblings_with_vite_version_use_shared_dep_namespace(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ package_path = "/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/card.js"
+ manager = _FakeShowRuntimeManager(
+ body=f'import "{package_path}";'.encode("utf-8"),
+ bodies_by_path={
+ f"/sessions/ses123/app{package_path}": b'import "./react.js?v=d8d245fb";',
+ "/sessions/ses123/app/@fs/home/avibe/.avibe/runtime/show-runtime/source/github/avibe-bot_vibe-show-runtime/main/packages/ui/dist/react.js": (
+ b"export default {};"
+ ),
+ },
+ extra_headers={
+ "content-type": "text/javascript",
+ "cache-control": "no-cache",
+ },
+ )
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ source = app.test_client().get(
+ f"/p/{share_id}/src/App.tsx?t=1780732068677",
+ base_url="http://127.0.0.1:5123",
+ )
+ package_public_path = source.content.decode("utf-8").split('"')[1]
+ package_dep = app.test_client().get(
+ package_public_path,
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert source.status_code == 200
+ assert package_dep.status_code == 200
+ assert b'"/_show-runtime/deps/r8-d8d245fb/react.js?v=d8d245fb"' in package_dep.content
+ assert b"/_show-runtime/deps/r8-m" not in package_dep.content
+
+
+def test_show_runtime_public_client_shims_are_cacheable():
+ client = app.test_client()
+ vite_client = client.get("/_show-runtime/client-shim-r8.js", base_url="http://127.0.0.1:5123")
+ react_refresh = client.get("/_show-runtime/react-refresh-shim-r8.js", base_url="http://127.0.0.1:5123")
+
+ assert vite_client.status_code == 200
+ assert react_refresh.status_code == 200
+ assert vite_client.headers["cache-control"] == "public, max-age=31536000, immutable"
+ assert react_refresh.headers["cache-control"] == "public, max-age=31536000, immutable"
+ assert b"export function createHotContext" in vite_client.content
+ assert b"export function injectIntoGlobalHook" in react_refresh.content
+ assert b"createSignatureFunctionForTransform" in react_refresh.content
+ assert b"performReactRefresh" in react_refresh.content
+ assert b"__hmr_import" in react_refresh.content
+ assert b"validateRefreshBoundaryAndEnqueueUpdate" in react_refresh.content
+
+
+def test_public_show_runtime_direct_client_paths_return_shims(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ share_id = _create_show_page("ses123", "public")
+ manager = _FakeShowRuntimeManager(body=b"real vite client")
+ set_show_runtime_manager_for_tests(manager)
+ try:
+ vite_client = app.test_client().get(
+ f"/p/{share_id}/@vite/client",
+ base_url="http://127.0.0.1:5123",
+ )
+ react_refresh = app.test_client().get(
+ f"/p/{share_id}/@react-refresh",
+ base_url="http://127.0.0.1:5123",
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert vite_client.status_code == 200
+ assert react_refresh.status_code == 200
+ assert b"export function createHotContext" in vite_client.content
+ assert b"export function injectIntoGlobalHook" in react_refresh.content
+ assert manager.calls == []
+
+
def test_show_runtime_source_preserves_dot_vite_dep_import_paths(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -872,7 +1233,7 @@ def test_show_runtime_source_preserves_dot_vite_dep_import_paths(monkeypatch, tm
base_url="http://127.0.0.1:5123",
)
public_dep = app.test_client().get(
- "/_show-runtime/deps/r4-d6d38251/react.js?v=d6d38251",
+ "/_show-runtime/deps/r8-d6d38251/react.js?v=d6d38251",
base_url="http://127.0.0.1:5123",
)
finally:
@@ -1322,7 +1683,7 @@ def test_public_show_page_immutable_deps_do_not_clear_write_cookie(monkeypatch,
set_show_runtime_manager_for_tests(None)
assert response.status_code == 302
- assert response.headers["location"] == "/_show-runtime/deps/r4-d6d38251/react.js"
+ assert response.headers["location"] == "/_show-runtime/deps/r8-d6d38251/react.js"
assert "set-cookie" not in response.headers
@@ -1847,8 +2208,31 @@ def test_show_runtime_manager_passes_runtime_options(monkeypatch, tmp_path):
def test_show_runtime_manager_prewarm_loads_entry_module(monkeypatch, tmp_path):
responses = {
- "/sessions/ses123/app/": 200,
- "/sessions/ses123/app/src/main.tsx": 200,
+ "/sessions/ses123/app/": (
+ 200,
+ b'<script type="module" src="/show/ses123/src/main.tsx"></script>',
+ {"content-type": "text/html"},
+ ),
+ "/sessions/ses123/app/src/main.tsx": (
+ 200,
+ b'import App from "/show/ses123/src/App.tsx";',
+ {"content-type": "text/javascript"},
+ ),
+ "/sessions/ses123/app/src/App.tsx": (
+ 200,
+ b'import { Button } from "/show/ses123/@fs/runtime/packages/ui/dist/button.js";',
+ {"content-type": "text/javascript"},
+ ),
+ "/sessions/ses123/app/@fs/runtime/packages/ui/dist/button.js": (
+ 200,
+ b'import { jsx } from "/show/ses123/@fs/runtime/vite-cache/deps/react_jsx-runtime.js?v=abc";',
+ {"content-type": "text/javascript"},
+ ),
+ "/sessions/ses123/app/@fs/runtime/vite-cache/deps/react_jsx-runtime.js?v=abc": (
+ 200,
+ b"export const jsx = () => null;",
+ {"content-type": "text/javascript"},
+ ),
}
calls = []
@@ -1856,7 +2240,8 @@ def test_show_runtime_manager_prewarm_loads_entry_module(monkeypatch, tmp_path):
import httpx
calls.append((method, path, headers, body))
- return httpx.Response(responses[path])
+ status, content, headers_out = responses[path]
+ return httpx.Response(status, content=content, headers=headers_out)
manager = ShowRuntimeManager(
command="/bin/echo",
@@ -1871,9 +2256,60 @@ def test_show_runtime_manager_prewarm_loads_entry_module(monkeypatch, tmp_path):
assert calls == [
("GET", "/sessions/ses123/app/", {"x-vibe-show-base": "/show/ses123/"}, None),
("GET", "/sessions/ses123/app/src/main.tsx", {"x-vibe-show-base": "/show/ses123/"}, None),
+ ("GET", "/sessions/ses123/app/src/App.tsx", {"x-vibe-show-base": "/show/ses123/"}, None),
+ (
+ "GET",
+ "/sessions/ses123/app/@fs/runtime/packages/ui/dist/button.js",
+ {"x-vibe-show-base": "/show/ses123/"},
+ None,
+ ),
+ (
+ "GET",
+ "/sessions/ses123/app/@fs/runtime/vite-cache/deps/react_jsx-runtime.js?v=abc",
+ {"x-vibe-show-base": "/show/ses123/"},
+ None,
+ ),
]
+def test_show_runtime_manager_prewarm_reports_nested_module_failures(monkeypatch, tmp_path):
+ responses = {
+ "/sessions/ses123/app/": (
+ 200,
+ b'<script type="module" src="/p/share123/src/main.tsx"></script>',
+ {"content-type": "text/html"},
+ ),
+ "/sessions/ses123/app/src/main.tsx": (
+ 200,
+ b'import App from "/p/share123/src/App.tsx";',
+ {"content-type": "text/javascript"},
+ ),
+ "/sessions/ses123/app/src/App.tsx": (
+ 504,
+ b"timeout",
+ {"content-type": "text/plain"},
+ ),
+ }
+
+ async def fake_request(self, method, path, *, headers=None, body=None):
+ import httpx
+
+ status, content, headers_out = responses[path]
+ return httpx.Response(status, content=content, headers=headers_out)
+
+ manager = ShowRuntimeManager(
+ command="/bin/echo",
+ workspace_root=tmp_path / "show",
+ runtime_dir=tmp_path / "runtime",
+ )
+ monkeypatch.setattr(ShowRuntimeManager, "request", fake_request)
+
+ result = asyncio.run(manager.prewarm_session("ses123", base_path="/p/share123/"))
+
+ assert result.available is False
+ assert result.reason == "session_prewarm_module_failed:504:/sessions/ses123/app/src/App.tsx"
+
+
def test_show_runtime_manager_uses_managed_runtime_bin(tmp_path):
runtime_dir = tmp_path / "runtime with spaces"
bin_path = runtime_dir / "package" / "node_modules" / ".bin" / "avibe-show-runtime"
diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.py
index 560033257..1e075c570 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -120,3 +120,25 @@ def test_to_app_config_uses_shared_agent_defaults() -> None:
assert compat.claude.idle_timeout_seconds == DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
assert compat.opencode is not None
assert compat.opencode.error_retry_limit == DEFAULT_OPENCODE_ERROR_RETRY_LIMIT
+
+
+def test_to_app_config_exposes_opencode_default_model_fields() -> None:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ update=UpdateConfig(),
+ )
+ config.agents.opencode.default_model = "gpt-5.4"
+ config.agents.opencode.default_reasoning_effort = "high"
+ config.agents.opencode.default_provider = "openai"
+
+ compat = to_app_config(config)
+
+ assert compat.opencode is not None
+ assert compat.opencode.default_model == "gpt-5.4"
+ assert compat.opencode.default_reasoning_effort == "high"
+ assert compat.opencode.default_provider == "openai"
diff --git a/vibe/api.py b/vibe/api.py
index ac034b851..33b545272 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -86,7 +86,7 @@ def _enabled_agent_backends_from_config(config: Optional[V2Config] = None) -> li
if agents is not None:
for backend in ("opencode", "claude", "codex"):
backend_cfg = getattr(agents, backend, None)
- if bool(getattr(backend_cfg, "enabled", False)):
+ if backend_cfg is not None and bool(getattr(backend_cfg, "enabled", True)):
result.append(backend)
return result
diff --git a/vibe/sentry_integration.py b/vibe/sentry_integration.py
index e7b4994f4..61b8ce0e4 100644
--- a/vibe/sentry_integration.py
+++ b/vibe/sentry_integration.py
@@ -148,7 +148,7 @@ def detect_sentry_environment() -> str:
return deployment.strip()
vibe_home = os.environ.get("AVIBE_HOME") or os.environ.get("VIBE_REMOTE_HOME", "")
- if "three-regression" in vibe_home:
+ if "incus-regression" in vibe_home or "three-regression" in vibe_home:
return "regression"
if os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3b73ee511..5d7fcd759 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1,6 +1,8 @@
import base64
import asyncio
+import gzip
import hashlib
+import html
import hmac
import ipaddress
import json
@@ -14,11 +16,12 @@ import socket
import subprocess
import threading
import time
+from collections import deque
from contextlib import contextmanager
from datetime import datetime
from pathlib import Path
from typing import Any, Callable
-from urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplit
+from urllib.parse import parse_qsl, quote, unquote, urlencode, urljoin, urlparse, urlsplit, urlunsplit
import psutil
from aiohttp import ClientSession, WSMsgType
@@ -85,15 +88,30 @@ _SHOW_RUNTIME_MODULE_SCRIPT_RE = re.compile(
r"<script\b(?=[^>]*\btype\s*=\s*['\"]module['\"])[^>]*>",
re.IGNORECASE,
)
+_SHOW_RUNTIME_MODULE_SCRIPT_SRC_RE = re.compile(
+ r"<script\b(?=[^>]*\btype\s*=\s*['\"]module['\"])[^>]*\bsrc\s*=\s*(?P<quote>['\"])(?P<src>[^'\"]+)(?P=quote)[^>]*>",
+ re.IGNORECASE,
+)
+_SHOW_RUNTIME_IMPORT_SPECIFIER_RE = re.compile(
+ r"\bimport\s*(?:[^'\"\n;]*?\sfrom\s*)?(?P<quote>['\"])(?P<path>[^'\"]+)(?P=quote)"
+ r"|\bimport\(\s*(?P<dynamic_quote>['\"])(?P<dynamic_path>[^'\"]+)(?P=dynamic_quote)\s*\)"
+)
+_SHOW_RUNTIME_INLINE_SOURCE_MAP_RE = re.compile(rb"\n?//# sourceMappingURL=data:[^\r\n]+")
_SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
_SHOW_RUNTIME_PUBLIC_DEP_RE = re.compile(
r"(?P<quote>['\"])(?P<path>(?:(?:\.?/)?(?:node_modules/)?\.vite/deps/|[^'\"?#]*@fs/[^'\"?#]*/(?:\.vite-cache|vite-cache)/[^'\"?#]*/deps/)[^'\"?#]+)(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
)
+_SHOW_RUNTIME_PUBLIC_MODULE_RE = re.compile(
+ r"(?P<quote>['\"])(?P<path>[^'\"?#]*@fs/[^'\"?#]*/packages/[^'\"?#]*/dist/[^'\"?#]+\.(?:css|js))(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
+)
_SHOW_RUNTIME_PUBLIC_DEP_SIBLING_RE = re.compile(
- r"(?P<quote>['\"])\./(?P<name>[A-Za-z0-9_.-]+\.js)(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
+ r"(?P<quote>['\"])\./(?P<name>[A-Za-z0-9_.-]+\.(?:css|js))(?:\?v=(?P<version>[A-Za-z0-9_-]+))?(?P<rest>[^'\"]*)(?P=quote)"
)
_SHOW_RUNTIME_PUBLIC_DEP_PREFIX = "/_show-runtime/deps"
-_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH = "r4"
+_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH = "r8"
+_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH = "/_show-runtime/client-shim-r8.js"
+_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH = "/_show-runtime/react-refresh-shim-r8.js"
+_SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES = 1024
_SHOW_RUNTIME_PUBLIC_DEP_REGISTRY: dict[tuple[str, str], str] = {}
STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")
@@ -987,6 +1005,7 @@ def _remote_auth_exempt_path() -> bool:
or path == "/api/csrf-token"
or path.startswith("/assets/")
or path.startswith("/_show-runtime/deps/")
+ or path in {_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH, _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH}
or path.startswith("/p/")
or path == "/favicon.ico"
or path in _PWA_PUBLIC_ASSETS
@@ -998,6 +1017,7 @@ def _remote_auth_exempt_before_host_validation() -> bool:
request.path in {"/auth/callback", "/auth/logout", "/api/session", "/api/csrf-token"}
or request.path.startswith("/assets/")
or request.path.startswith("/_show-runtime/deps/")
+ or request.path in {_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH, _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH}
or request.path == "/favicon.ico"
)
@@ -5575,6 +5595,9 @@ async def show_runtime_public_dep(version: str, asset_name: str):
version=version,
runtime_path=runtime_path,
)
+ content = _rewrite_public_show_runtime_dep_client(content, response_headers, runtime_path=runtime_path)
+ content = _strip_public_show_runtime_inline_source_maps(content, response_headers)
+ content = _compress_show_runtime_response(content, response_headers, request._request)
return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)
@@ -5587,6 +5610,99 @@ def _show_runtime_public_dep_not_found_response():
)
[email protected](_SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH, methods=["GET", "HEAD"])
+def show_runtime_public_client_shim():
+ content = b"""
+const styles = new Map();
+
+export function createHotContext() {
+ return {
+ data: {},
+ accept() {},
+ decline() {},
+ dispose() {},
+ invalidate() {},
+ on() {},
+ prune() {},
+ send() {},
+ };
+}
+
+export function updateStyle(id, css) {
+ let style = styles.get(id);
+ if (!style) {
+ style = document.createElement("style");
+ style.setAttribute("type", "text/css");
+ style.setAttribute("data-vite-dev-id", id);
+ document.head.appendChild(style);
+ styles.set(id, style);
+ }
+ style.textContent = css;
+}
+
+export function removeStyle(id) {
+ const style = styles.get(id);
+ if (style) {
+ style.remove();
+ styles.delete(id);
+ }
+}
+"""
+ return FastAPIResponse(
+ content=content.strip(),
+ media_type="text/javascript",
+ headers={
+ "Cache-Control": _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL,
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ },
+ )
+
+
[email protected](_SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH, methods=["GET", "HEAD"])
+def show_runtime_public_react_refresh_shim():
+ content = b"""
+function identity(type) {
+ return type;
+}
+
+function noop() {}
+
+export function injectIntoGlobalHook(target) {
+ const scope = target || globalThis;
+ scope.$RefreshReg$ = scope.$RefreshReg$ || noop;
+ scope.$RefreshSig$ = scope.$RefreshSig$ || (() => identity);
+}
+
+export const register = noop;
+export const performReactRefresh = noop;
+export const createSignatureFunctionForTransform = () => identity;
+export const isLikelyComponentType = () => false;
+export const getFamilyByType = () => undefined;
+export const __hmr_import = () => Promise.resolve({});
+export const registerExportsForReactRefresh = noop;
+export const validateRefreshBoundaryAndEnqueueUpdate = () => undefined;
+"""
+ return FastAPIResponse(
+ content=content.strip(),
+ media_type="text/javascript",
+ headers={
+ "Cache-Control": _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL,
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ },
+ )
+
+
+def _show_runtime_public_client_shim_response(asset_path: str):
+ normalized = (asset_path or "").strip("/")
+ if normalized == "@vite/client":
+ return show_runtime_public_client_shim()
+ if normalized == "@react-refresh":
+ return show_runtime_public_react_refresh_shim()
+ return None
+
+
async def _show_page_runtime_response(
session_id: str,
asset_path: str,
@@ -5655,19 +5771,30 @@ async def _show_page_runtime_response(
_strip_mutated_show_runtime_headers(response_headers)
else:
if proxied.status_code == 200:
- content = _rewrite_show_runtime_public_deps(content, response_headers, session_id=session_id)
content = _rewrite_public_show_runtime_private_paths(
content,
response_headers,
session_id=session_id,
external_prefix=external_prefix,
)
+ content = _rewrite_public_show_runtime_client(content, response_headers, external_prefix=external_prefix)
+ content = _rewrite_show_runtime_public_deps(content, response_headers, session_id=session_id)
+ content = await _inject_public_show_runtime_preloads(
+ content,
+ response_headers,
+ session_id=session_id,
+ asset_path=asset_path,
+ external_prefix=external_prefix,
+ forwarded_headers=forwarded_headers,
+ )
+ content = _strip_public_show_runtime_inline_source_maps(content, response_headers)
_apply_show_runtime_cache_headers(
asset_path,
response_headers,
status_code=proxied.status_code,
query=starlette_request.url.query,
)
+ content = _compress_show_runtime_response(content, response_headers, starlette_request)
return FastAPIResponse(content=content, status_code=proxied.status_code, headers=response_headers)
@@ -5690,6 +5817,51 @@ def _strip_mutated_show_runtime_headers(headers: dict[str, str]) -> None:
headers["Cache-Control"] = "no-store"
+def _compress_show_runtime_response(content: bytes, headers: dict[str, str], starlette_request: FastAPIRequest) -> bytes:
+ if len(content) < _SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES:
+ return content
+ if _response_header(headers, "content-encoding"):
+ return content
+ if "gzip" not in (starlette_request.headers.get("accept-encoding") or "").lower():
+ return content
+ content_type = _response_header(headers, "content-type") or ""
+ if not _show_response_is_compressible(content_type):
+ return content
+ compressed = gzip.compress(content, compresslevel=6)
+ if len(compressed) >= len(content):
+ return content
+ _remove_response_header(headers, "content-length")
+ _remove_response_header(headers, "etag")
+ headers["Content-Encoding"] = "gzip"
+ headers["Vary"] = _append_vary_header(_response_header(headers, "vary"), "Accept-Encoding")
+ return compressed
+
+
+def _append_vary_header(existing: str | None, value: str) -> str:
+ values = [item.strip() for item in (existing or "").split(",") if item.strip()]
+ if not any(item.lower() == value.lower() for item in values):
+ values.append(value)
+ return ", ".join(values)
+
+
+def _show_response_is_compressible(content_type: str | None) -> bool:
+ if not content_type:
+ return False
+ lowered = content_type.lower()
+ return any(
+ marker in lowered
+ for marker in (
+ "javascript",
+ "ecmascript",
+ "text/",
+ "json",
+ "css",
+ "svg",
+ "xml",
+ )
+ )
+
+
def _apply_show_runtime_cache_headers(asset_path: str, headers: dict[str, str], *, status_code: int, query: str | None) -> None:
relative = (asset_path or "").strip("/")
if not relative or relative == "index.html":
@@ -5759,6 +5931,11 @@ def _public_show_runtime_dep_version(vite_version: str) -> str:
return f"{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-{vite_version}"
+def _public_show_runtime_module_version(module_path: str) -> str:
+ digest = hashlib.sha256(module_path.encode("utf-8")).hexdigest()[:12]
+ return f"{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-m{digest}"
+
+
def _show_runtime_dep_version(query: str | None) -> str | None:
if not query:
return None
@@ -5771,6 +5948,263 @@ def _show_runtime_dep_version(query: str | None) -> str | None:
return value
+def _show_response_is_rewritable_show_runtime_source(content_type: str | None) -> bool:
+ return _show_response_is_javascript(content_type) or _show_response_is_html(content_type)
+
+
+def _strip_public_show_runtime_inline_source_maps(content: bytes, headers: dict[str, str]) -> bytes:
+ content_type = _response_header(headers, "content-type") or ""
+ if not _show_response_is_javascript(content_type):
+ return content
+ stripped = _SHOW_RUNTIME_INLINE_SOURCE_MAP_RE.sub(b"", content)
+ if stripped == content:
+ return content
+ for name in ("content-length", "etag", "sourcemap", "x-sourcemap"):
+ _remove_response_header(headers, name)
+ if _response_header(headers, "cache-control") != _SHOW_RUNTIME_IMMUTABLE_CACHE_CONTROL:
+ _remove_response_header(headers, "cache-control")
+ headers["Cache-Control"] = "no-store"
+ return stripped
+
+
+async def _inject_public_show_runtime_preloads(
+ content: bytes,
+ headers: dict[str, str],
+ *,
+ session_id: str,
+ asset_path: str,
+ external_prefix: str | None,
+ forwarded_headers: dict[str, str],
+) -> bytes:
+ if not external_prefix or asset_path.strip("/"):
+ return content
+ content_type = _response_header(headers, "content-type") or ""
+ if not _show_response_is_html(content_type):
+ return content
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return content
+ if 'rel="modulepreload"' in text or "rel='modulepreload'" in text:
+ return content
+ preload_urls = await _public_show_runtime_preload_urls(
+ text,
+ session_id=session_id,
+ external_prefix=external_prefix,
+ forwarded_headers=forwarded_headers,
+ )
+ if not preload_urls:
+ return content
+ tags = "\n".join(_public_show_runtime_preload_tag(url) for url in preload_urls)
+ injection = f"\n{tags}\n"
+ if "</head>" in text:
+ rewritten = text.replace("</head>", f"{injection}</head>", 1)
+ else:
+ rewritten = f"{injection}{text}"
+ _strip_mutated_show_runtime_headers(headers)
+ return rewritten.encode("utf-8")
+
+
+async def _public_show_runtime_preload_urls(
+ html_text: str,
+ *,
+ session_id: str,
+ external_prefix: str,
+ forwarded_headers: dict[str, str],
+) -> list[str]:
+ urls: list[str] = []
+ seen: set[str] = set()
+ import_scan_queue: deque[tuple[str, int]] = deque()
+ scanned_imports: set[str] = set()
+
+ def add_url(url: str) -> None:
+ if url and url not in seen and not url.endswith("/@vite/client") and "/@react-refresh" not in url:
+ seen.add(url)
+ urls.append(url)
+
+ def queue_import_scan(url: str, depth: int) -> None:
+ if depth < 0 or not _should_scan_public_show_runtime_imports(url, external_prefix=external_prefix):
+ return
+ if url not in scanned_imports:
+ import_scan_queue.append((url, depth))
+
+ for match in _SHOW_RUNTIME_MODULE_SCRIPT_SRC_RE.finditer(html_text):
+ src = html.unescape(match.group("src"))
+ normalized = _resolve_public_show_runtime_url(src, base_url=f"{external_prefix.rstrip('/')}/")
+ add_url(normalized)
+ queue_import_scan(normalized, 1)
+ if normalized.endswith("/src/main.tsx"):
+ queue_import_scan(_resolve_public_show_runtime_url("./App.tsx", base_url=normalized), 1)
+ while import_scan_queue and len(urls) < 32:
+ scan_url, depth = import_scan_queue.popleft()
+ if scan_url in scanned_imports:
+ continue
+ scanned_imports.add(scan_url)
+ for imported_url in await _public_show_runtime_direct_import_urls(
+ scan_url,
+ session_id=session_id,
+ external_prefix=external_prefix,
+ forwarded_headers=forwarded_headers,
+ ):
+ add_url(imported_url)
+ if depth > 0:
+ queue_import_scan(imported_url, depth - 1)
+ return urls[:32]
+
+
+async def _public_show_runtime_direct_import_urls(
+ public_url: str,
+ *,
+ session_id: str,
+ external_prefix: str,
+ forwarded_headers: dict[str, str],
+) -> list[str]:
+ asset_path = _public_show_runtime_asset_path(public_url, external_prefix=external_prefix)
+ runtime_path = None
+ if asset_path:
+ runtime_path = f"/sessions/{quote(session_id, safe='')}/app/{quote(asset_path, safe='/@:-._~')}"
+ else:
+ runtime_path = _public_show_runtime_dep_asset_path(public_url)
+ if not runtime_path:
+ return []
+ from core.show_runtime import get_show_runtime_manager
+
+ try:
+ proxied = await get_show_runtime_manager().request(
+ "GET",
+ runtime_path,
+ headers=forwarded_headers,
+ body=None,
+ )
+ except Exception:
+ logger.debug("Failed to inspect Show Runtime preload imports for %s", public_url, exc_info=True)
+ return []
+ if proxied.status_code != 200:
+ return []
+ response_headers = {
+ key: value
+ for key, value in proxied.headers.items()
+ if key.lower() in _SHOW_RUNTIME_RESPONSE_HEADER_ALLOWLIST
+ }
+ import_content = _rewrite_public_show_runtime_private_paths(
+ proxied.content,
+ response_headers,
+ session_id=session_id,
+ external_prefix=external_prefix,
+ )
+ import_content = _rewrite_public_show_runtime_client(import_content, response_headers, external_prefix=external_prefix)
+ import_content = _rewrite_show_runtime_public_deps(import_content, response_headers, session_id=session_id)
+ try:
+ text = import_content.decode("utf-8")
+ except UnicodeDecodeError:
+ return []
+ urls: list[str] = []
+ for match in _SHOW_RUNTIME_IMPORT_SPECIFIER_RE.finditer(text):
+ import_path = match.group("path") or match.group("dynamic_path")
+ if not import_path:
+ continue
+ if import_path.startswith(("http://", "https://")):
+ continue
+ urls.append(_resolve_public_show_runtime_url(import_path, base_url=public_url))
+ return urls
+
+
+def _resolve_public_show_runtime_url(value: str, *, base_url: str) -> str:
+ if value.startswith("/"):
+ return value
+ base = base_url.split("?", 1)[0].split("#", 1)[0]
+ base_dir = base if base.endswith("/") else base.rsplit("/", 1)[0] + "/"
+ return urljoin(base_dir, value)
+
+
+def _is_public_show_runtime_local_source_url(url: str, *, external_prefix: str) -> bool:
+ public_prefix = f"{external_prefix.rstrip('/')}/"
+ return url.startswith(public_prefix) and ("/src/" in url or url.endswith("/src/main.tsx"))
+
+
+def _should_scan_public_show_runtime_imports(url: str, *, external_prefix: str) -> bool:
+ if _is_public_show_runtime_local_source_url(url, external_prefix=external_prefix):
+ return True
+ parsed = urlparse(url)
+ path = parsed.path
+ return path.startswith(f"{_SHOW_RUNTIME_PUBLIC_DEP_PREFIX}/{_SHOW_RUNTIME_PUBLIC_DEP_CACHE_EPOCH}-m")
+
+
+def _public_show_runtime_asset_path(public_url: str, *, external_prefix: str) -> str | None:
+ public_prefix = f"{external_prefix.rstrip('/')}/"
+ normalized = public_url.split("?", 1)[0].split("#", 1)[0]
+ if not normalized.startswith(public_prefix):
+ return None
+ return normalized[len(public_prefix) :]
+
+
+def _public_show_runtime_dep_asset_path(public_url: str) -> str | None:
+ parsed = urlparse(public_url)
+ parts = [unquote(part) for part in parsed.path.strip("/").split("/")]
+ if len(parts) < 4 or parts[0] != "_show-runtime" or parts[1] != "deps":
+ return None
+ version = parts[2]
+ asset_name = "/".join(parts[3:])
+ if not re.fullmatch(r"[A-Za-z0-9_-]+", version or "") or not re.fullmatch(r"[A-Za-z0-9_@./-]+", asset_name or ""):
+ return None
+ return _public_show_runtime_dep_runtime_path(version, asset_name)
+
+
+def _public_show_runtime_preload_tag(url: str) -> str:
+ escaped = html.escape(url, quote=True)
+ return f'<link rel="modulepreload" href="{escaped}">'
+
+
+def _rewrite_public_show_runtime_client(
+ content: bytes,
+ headers: dict[str, str],
+ *,
+ external_prefix: str | None,
+) -> bytes:
+ if not external_prefix:
+ return content
+ content_type = _response_header(headers, "content-type") or ""
+ if not _show_response_is_rewritable_show_runtime_source(content_type):
+ return content
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return content
+ public_prefix = f"{external_prefix.rstrip('/')}/"
+ rewritten = text.replace(f"{public_prefix}@vite/client", _SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH)
+ rewritten = rewritten.replace(f"{public_prefix}@react-refresh", _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH)
+ if rewritten == text:
+ return content
+ _strip_mutated_show_runtime_headers(headers)
+ return rewritten.encode("utf-8")
+
+
+def _rewrite_public_show_runtime_dep_client(
+ content: bytes,
+ headers: dict[str, str],
+ *,
+ runtime_path: str,
+) -> bytes:
+ content_type = _response_header(headers, "content-type") or ""
+ if not _show_response_is_rewritable_show_runtime_source(content_type):
+ return content
+ if "/sessions/" not in runtime_path or "/app/" not in runtime_path:
+ return content
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return content
+ session_part = runtime_path.split("/sessions/", 1)[1].split("/app/", 1)[0]
+ session_id = unquote(session_part)
+ private_prefix = f"/show/{quote(session_id, safe='')}/"
+ rewritten = text.replace(f"{private_prefix}@vite/client", _SHOW_RUNTIME_PUBLIC_CLIENT_SHIM_PATH)
+ rewritten = rewritten.replace(f"{private_prefix}@react-refresh", _SHOW_RUNTIME_PUBLIC_REACT_REFRESH_SHIM_PATH)
+ if rewritten == text:
+ return content
+ _strip_mutated_show_runtime_headers(headers)
+ return rewritten.encode("utf-8")
+
+
def _rewrite_show_runtime_public_deps(content: bytes, headers: dict[str, str], *, session_id: str) -> bytes:
content_type = _response_header(headers, "content-type") or ""
if not _show_response_is_javascript(content_type):
@@ -5780,19 +6214,27 @@ def _rewrite_show_runtime_public_deps(content: bytes, headers: dict[str, str], *
except UnicodeDecodeError:
return content
- def replace(match: re.Match[str]) -> str:
+ mutated = False
+
+ def register_dep(match: re.Match[str], *, allow_unversioned: bool) -> str:
+ nonlocal mutated
vite_version = match.group("version")
- if not vite_version:
+ dep_path = _normalize_show_runtime_dep_import_path(match.group("path"))
+ if vite_version:
+ version = _public_show_runtime_dep_version(vite_version)
+ elif allow_unversioned:
+ version = _public_show_runtime_module_version(dep_path)
+ else:
return match.group(0)
- version = _public_show_runtime_dep_version(vite_version)
name = Path(match.group("path")).name
- public_path = f"{_SHOW_RUNTIME_PUBLIC_DEP_PREFIX}/{quote(version, safe='')}/{quote(name, safe='')}"
- dep_path = _normalize_show_runtime_dep_import_path(match.group("path"))
_SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(version, name)] = f"/sessions/{quote(session_id, safe='')}/app/{quote(dep_path, safe='/@:-._~')}"
+ mutated = True
+ public_path = _public_show_runtime_dep_import_url(version, name, vite_version)
return f"{match.group('quote')}{public_path}{match.group('rest')}{match.group('quote')}"
- rewritten = _SHOW_RUNTIME_PUBLIC_DEP_RE.sub(replace, text)
- if rewritten == text:
+ rewritten = _SHOW_RUNTIME_PUBLIC_DEP_RE.sub(lambda match: register_dep(match, allow_unversioned=False), text)
+ rewritten = _SHOW_RUNTIME_PUBLIC_MODULE_RE.sub(lambda match: register_dep(match, allow_unversioned=True), rewritten)
+ if not mutated:
return content
_strip_mutated_show_runtime_headers(headers)
return rewritten.encode("utf-8")
@@ -5808,7 +6250,7 @@ def _rewrite_public_show_runtime_private_paths(
if not external_prefix:
return content
content_type = _response_header(headers, "content-type") or ""
- if not _show_response_is_javascript(content_type):
+ if not _show_response_is_rewritable_show_runtime_source(content_type):
return content
try:
text = content.decode("utf-8")
@@ -5856,19 +6298,21 @@ def _rewrite_public_show_runtime_dep_siblings(
nonlocal mutated
name = Path(dep_path).name
normalized_dep_path = _normalize_show_runtime_dep_import_path(dep_path)
+ registered_version = _public_show_runtime_dep_version(dep_version) if dep_version else _public_show_runtime_module_version(normalized_dep_path)
registered_runtime_path = f"{runtime_app_prefix}{quote(normalized_dep_path, safe='/@:-._~')}"
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(version, name)] = registered_runtime_path
+ _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(registered_version, name)] = registered_runtime_path
mutated = True
- return _public_show_runtime_dep_import_url(version, name, dep_version)
+ return _public_show_runtime_dep_import_url(registered_version, name, dep_version)
def replace_relative_sibling(match: re.Match[str]) -> str:
nonlocal mutated
sibling_name = match.group("name")
sibling_runtime_path = f"{base_runtime_path}/{quote(sibling_name, safe='')}"
sibling_version = match.group("version")
- _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(version, sibling_name)] = sibling_runtime_path
+ registered_version = _public_show_runtime_dep_version(sibling_version) if sibling_version else version
+ _SHOW_RUNTIME_PUBLIC_DEP_REGISTRY[(registered_version, sibling_name)] = sibling_runtime_path
mutated = True
- public_path = _public_show_runtime_dep_import_url(version, sibling_name, sibling_version)
+ public_path = _public_show_runtime_dep_import_url(registered_version, sibling_name, sibling_version)
return f"{match.group('quote')}{public_path}{match.group('rest')}{match.group('quote')}"
def replace_absolute_dep(match: re.Match[str]) -> str:
@@ -5877,6 +6321,7 @@ def _rewrite_public_show_runtime_dep_siblings(
rewritten = _SHOW_RUNTIME_PUBLIC_DEP_SIBLING_RE.sub(replace_relative_sibling, text)
rewritten = _SHOW_RUNTIME_PUBLIC_DEP_RE.sub(replace_absolute_dep, rewritten)
+ rewritten = _SHOW_RUNTIME_PUBLIC_MODULE_RE.sub(replace_absolute_dep, rewritten)
if not mutated:
return content
_strip_mutated_show_runtime_headers(headers)
@@ -6143,6 +6588,9 @@ async def serve_public_show_page(share_id, asset_path):
if request.method != "GET":
return jsonify({"ok": False, "code": "public_show_events_read_only"}), 403
return await _show_events_response(page.session_id, public=True)
+ if request.method in {"GET", "HEAD"}:
+ if shim_response := _show_runtime_public_client_shim_response(asset_path):
+ return shim_response
response = None
if request.method in {"GET", "HEAD"} or _is_show_api_asset(asset_path):
try: