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.

fix(regression): migrate legacy backend runtimes (#991)

Call Whitecb5ffdcc57a3
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index 15125e9d5..c68e27d82 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -767,6 +767,69 @@ def stop_service_for_update(runner: Runner, target: RegressionTarget, *, remote:
runner.run(root_exec(target, f"systemctl stop {SERVICE_NAME} || true", remote=remote), check=False)
+def migrate_legacy_backend_runtimes(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ """Move pre-#545 root-global backends into the service user's home.
+
+ Long-lived regression instances keep their original base image when ``up``
+ syncs newer source. Instances created before #545 therefore still resolve
+ root-owned CLIs under ``/usr`` even though current base images install
+ self-updatable copies under ``/home/avibe``. Only migrate a backend when its
+ user-owned entrypoint is absent and the corresponding legacy binary exists.
+ """
+ runner.run(
+ tenant_exec(
+ target,
+ textwrap.dedent(
+ f"""\
+ set -euo pipefail
+ user_bin={shlex.quote(f"{SERVICE_HOME}/.local/bin")}
+ npm_prefix={shlex.quote(f"{SERVICE_HOME}/.npm-global")}
+ mkdir -p "$user_bin"
+
+ npm_packages=()
+ if [ ! -x "$user_bin/claude" ]; then
+ if [ -x "$npm_prefix/bin/claude" ]; then
+ ln -sfn "$npm_prefix/bin/claude" "$user_bin/claude"
+ elif [ -x /usr/bin/claude ] || [ -x /usr/local/bin/claude ]; then
+ npm_packages+=("@anthropic-ai/claude-code")
+ fi
+ fi
+ if [ ! -x "$user_bin/codex" ]; then
+ if [ -x "$npm_prefix/bin/codex" ]; then
+ ln -sfn "$npm_prefix/bin/codex" "$user_bin/codex"
+ elif [ -x /usr/bin/codex ] || [ -x /usr/local/bin/codex ]; then
+ npm_packages+=("@openai/codex")
+ fi
+ fi
+ if [ "${{#npm_packages[@]}}" -gt 0 ]; then
+ echo "Migrating legacy npm-installed agent backends into $npm_prefix"
+ npm config set prefix "$npm_prefix" --location=user
+ npm install --global --prefix "$npm_prefix" "${{npm_packages[@]}}"
+ for backend in claude codex; do
+ if [ -x "$npm_prefix/bin/$backend" ]; then
+ ln -sfn "$npm_prefix/bin/$backend" "$user_bin/$backend"
+ fi
+ done
+ fi
+
+ if [ ! -x "$user_bin/opencode" ]; then
+ if [ -x "{SERVICE_HOME}/.opencode/bin/opencode" ]; then
+ ln -sfn "{SERVICE_HOME}/.opencode/bin/opencode" "$user_bin/opencode"
+ elif [ -x /usr/local/bin/opencode ] || [ -x /usr/bin/opencode ]; then
+ echo "Migrating legacy OpenCode into {SERVICE_HOME}/.opencode"
+ curl -fsSL --retry 3 --retry-delay 2 --retry-all-errors https://opencode.ai/install \
+ | HOME={shlex.quote(SERVICE_HOME)} bash -s -- --no-modify-path
+ test -x "{SERVICE_HOME}/.opencode/bin/opencode"
+ ln -sfn "{SERVICE_HOME}/.opencode/bin/opencode" "$user_bin/opencode"
+ fi
+ fi
+ """
+ ),
+ remote=remote,
+ )
+ )
+
+
def file_hash(repo_root: Path, relative_paths: Sequence[str]) -> str:
digest = hashlib.sha256()
for relative in relative_paths:
@@ -1081,11 +1144,12 @@ def instance_ui_dist_exists(runner: Runner, target: RegressionTarget, *, remote:
def normalize_runtime_config(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
+ config_path = f"{AVIBE_HOME}/config/config.json"
script = textwrap.dedent(f"""
import json
from pathlib import Path
- path = Path({str(AVIBE_HOME + "/config/config.json")!r})
+ path = Path({config_path!r})
if not path.exists():
raise SystemExit(0)
payload = json.loads(path.read_text())
@@ -1102,9 +1166,10 @@ def normalize_runtime_config(runner: Runner, target: RegressionTarget, *, remote
path.write_text(json.dumps(payload, indent=2))
""").strip()
runner.run(
- root_exec(
+ tenant_exec(
target,
- f"python3 - <<'PY'\n{script}\nPY\nchown {SERVICE_USER}:{SERVICE_USER} {AVIBE_HOME}/config/config.json",
+ f"{VENV_DIR}/bin/python scripts/prepare_regression.py --normalize-config {shlex.quote(config_path)} && "
+ f"python3 - <<'PY'\n{script}\nPY",
remote=remote,
)
)
@@ -1405,6 +1470,7 @@ def cmd_up(args: argparse.Namespace) -> int:
write_runtime_env(runner, target, repo_root=repo_root, remote=args.remote)
else:
print("No regression env file loaded; preserving existing runtime env file.")
+ migrate_legacy_backend_runtimes(runner, target, remote=args.remote)
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)
diff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.py
index a7cf35bad..c526780da 100755
--- a/scripts/prepare_regression.py
+++ b/scripts/prepare_regression.py
@@ -54,11 +54,10 @@ RESET_MODES = {"none", "config", "all"}
CONTAINER_HOME = Path("/home/avibe")
CONTAINER_AVIBE_HOME = CONTAINER_HOME / ".avibe"
DEFAULT_CWD = str(CONTAINER_AVIBE_HOME / "workdir")
-# OpenCode is a bare PATH-resolved name (the system default; claude/codex too).
-# The service PATH prefers ~/.local/bin, where build-base installs the user-owned,
-# self-updatable binary; on a not-yet-rebuilt base it still resolves the old
-# /usr/local/bin copy. Bare avoids pinning an absolute path that may be absent on
-# a given instance (the cause of breakage across base-image generations).
+# Backends use bare PATH-resolved names. The service PATH prefers ~/.local/bin,
+# where build-base and the legacy-instance migration install user-owned,
+# self-updatable binaries. Bare names keep preserved config portable across base
+# image generations and install-layout migrations.
CONTAINER_OPENCODE_CLI = "opencode"
ENV_PREFIX = "REGRESSION_"
@@ -633,28 +632,43 @@ def _normalize_config_payload(path: Path) -> None:
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 "")
- # Migrate any recognized opencode install location to the bare PATH-resolved
- # name. Pinning an absolute path breaks across base-image generations: the
- # pre-#545 root-global /usr/local/bin/opencode and the user-owned
- # ~/.local/bin/opencode (or its ~/.opencode source) do not both exist on every
- # instance, so a preserved-state config could point at a path that is absent.
- # A custom user-set path is left untouched.
- known_opencode_paths = {
- "",
- "opencode",
- "/usr/local/bin/opencode",
- str(CONTAINER_HOME / ".opencode" / "bin" / "opencode"),
- str(CONTAINER_HOME / ".local" / "bin" / "opencode"),
+ known_backend_paths = {
+ "opencode": {
+ "",
+ "opencode",
+ "/usr/bin/opencode",
+ "/usr/local/bin/opencode",
+ str(CONTAINER_HOME / ".opencode" / "bin" / "opencode"),
+ str(CONTAINER_HOME / ".local" / "bin" / "opencode"),
+ },
+ "claude": {
+ "",
+ "claude",
+ "/usr/bin/claude",
+ "/usr/local/bin/claude",
+ str(CONTAINER_HOME / ".npm-global" / "bin" / "claude"),
+ str(CONTAINER_HOME / ".local" / "bin" / "claude"),
+ },
+ "codex": {
+ "",
+ "codex",
+ "/usr/bin/codex",
+ "/usr/local/bin/codex",
+ str(CONTAINER_HOME / ".npm-global" / "bin" / "codex"),
+ str(CONTAINER_HOME / ".local" / "bin" / "codex"),
+ },
}
- if cli_path not in known_opencode_paths:
- return
-
- opencode["cli_path"] = CONTAINER_OPENCODE_CLI
- _write_json(path, payload)
+ changed = False
+ for backend, known_paths in known_backend_paths.items():
+ config = agents.get(backend)
+ if not isinstance(config, dict):
+ continue
+ if str(config.get("cli_path") or "") not in known_paths:
+ continue
+ config["cli_path"] = backend
+ changed = True
+ if changed:
+ _write_json(path, payload)
def _normalize_existing_state(vibe_dir: Path) -> None:
@@ -733,10 +747,18 @@ def main() -> int:
default="none",
help="Reset scope before generating files: none, config, or all",
)
+ parser.add_argument(
+ "--normalize-config",
+ type=Path,
+ help="Normalize a preserved regression config in place without preparing state",
+ )
args = parser.parse_args()
try:
- prepare(Path(args.output_root).resolve(), reset_mode=args.reset_mode)
+ if args.normalize_config is not None:
+ _normalize_config_payload(args.normalize_config.resolve())
+ else:
+ prepare(Path(args.output_root).resolve(), reset_mode=args.reset_mode)
except SystemExit as exc:
print(str(exc), file=sys.stderr)
return 1
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
index dca27b295..d3ef17813 100644
--- a/tests/test_incus_regression.py
+++ b/tests/test_incus_regression.py
@@ -1586,6 +1586,7 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
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, "migrate_legacy_backend_runtimes", record("migrate_legacy_backend_runtimes"))
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: {})
@@ -1623,7 +1624,14 @@ def test_up_stops_old_service_before_mutating_runtime(tmp_path: Path, monkeypatc
)
assert incus_regression.cmd_up(args) == 0
- assert calls[:3] == ["ensure_project_and_instance", "stop_service_for_update", "write_runtime_env"]
+ assert calls[:4] == [
+ "ensure_project_and_instance",
+ "stop_service_for_update",
+ "write_runtime_env",
+ "migrate_legacy_backend_runtimes",
+ ]
+ assert calls.index("stop_service_for_update") < calls.index("migrate_legacy_backend_runtimes")
+ assert calls.index("migrate_legacy_backend_runtimes") < calls.index("sync_source")
assert calls.index("sync_source") < calls.index("update_dependencies_and_build")
assert calls.index("normalize_runtime_config") < calls.index("restart_and_verify")
assert calls.index("prepare_show_runtime") < calls.index("restart_and_verify")
@@ -1864,7 +1872,7 @@ def test_up_reserves_worktree_port_under_mapping_lock(tmp_path: Path, monkeypatc
assert "updated_at" in mapping
-def test_normalize_runtime_config_updates_host_and_port() -> None:
+def test_normalize_runtime_config_updates_preserved_backend_paths_host_and_port() -> None:
commands = []
class RecordingRunner:
@@ -1885,6 +1893,11 @@ def test_normalize_runtime_config_updates_host_and_port() -> None:
incus_regression.normalize_runtime_config(RecordingRunner(), target, remote=None)
joined = "\n".join(commands)
+ assert "sudo -H -u avibe" in joined
+ assert (
+ "/opt/avibe/venv/bin/python scripts/prepare_regression.py "
+ "--normalize-config /home/avibe/.avibe/config/config.json"
+ ) in joined
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
@@ -1915,6 +1928,38 @@ def test_stop_service_for_update_ignores_missing_service() -> None:
assert commands[0][1] is False
+def test_migrate_legacy_backend_runtimes_uses_user_owned_layout() -> None:
+ commands = []
+
+ class RecordingRunner:
+ 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.migrate_legacy_backend_runtimes(RecordingRunner(), target, remote=None)
+
+ joined = " ".join(commands[0])
+ assert "sudo -H -u avibe" in joined
+ assert '[ ! -x "$user_bin/claude" ]' in joined
+ assert '[ ! -x "$user_bin/codex" ]' in joined
+ assert '[ ! -x "$user_bin/opencode" ]' in joined
+ assert 'npm config set prefix "$npm_prefix" --location=user' in joined
+ assert 'npm install --global --prefix "$npm_prefix" "${npm_packages[@]}"' in joined
+ assert "HOME=/home/avibe bash -s -- --no-modify-path" in joined
+ assert "/home/avibe/.npm-global/bin/claude" not in joined
+ assert "/home/avibe/.npm-global/bin/codex" not in joined
+
+
def test_update_builds_ui_before_editable_install() -> None:
commands = []
diff --git a/tests/test_prepare_regression.py b/tests/test_prepare_regression.py
index e740b5ae5..6d5349d2c 100644
--- a/tests/test_prepare_regression.py
+++ b/tests/test_prepare_regression.py
@@ -225,9 +225,13 @@ def test_prepare_ignores_legacy_regression_layout(tmp_path: Path, monkeypatch: p
json.dumps(
{
"runtime": {"default_cwd": "/data/vibe_remote/workdir"},
- # Legacy root-global install baked by pre-#545 base images; must be
- # migrated to the user-owned path on a preserved-state update.
- "agents": {"opencode": {"cli_path": "/usr/local/bin/opencode"}},
+ # Legacy root-global installs baked by pre-#545 base images must
+ # resolve through the user-owned PATH after migration.
+ "agents": {
+ "opencode": {"cli_path": "/usr/local/bin/opencode"},
+ "claude": {"cli_path": "/usr/bin/claude"},
+ "codex": {"cli_path": "/usr/bin/codex"},
+ },
}
),
encoding="utf-8",
@@ -265,10 +269,54 @@ def test_prepare_ignores_legacy_regression_layout(tmp_path: Path, monkeypatch: p
settings = json.loads((avibe_home / "state" / "settings.json").read_text(encoding="utf-8"))
assert config["runtime"]["default_cwd"] == "/home/avibe/.avibe/workdir"
assert config["agents"]["opencode"]["cli_path"] == "opencode"
+ assert config["agents"]["claude"]["cli_path"] == "claude"
+ assert config["agents"]["codex"]["cli_path"] == "codex"
assert settings["scopes"]["channel"]["slack"]["C123SLACK"]["custom_cwd"] == "/home/avibe/.avibe/workdir"
assert (tmp_path / "home" / ".claude.json").is_file()
+def test_normalize_config_payload_preserves_custom_backend_paths(tmp_path: Path) -> None:
+ module = _load_module()
+ config_path = tmp_path / "config.json"
+ payload = {
+ "agents": {
+ "opencode": {"cli_path": "/opt/custom/opencode"},
+ "claude": {"cli_path": "/opt/custom/claude"},
+ "codex": {"cli_path": "/opt/custom/codex"},
+ }
+ }
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ module._normalize_config_payload(config_path)
+
+ assert json.loads(config_path.read_text(encoding="utf-8")) == payload
+
+
+def test_main_normalizes_preserved_config_without_preparing_state(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ module = _load_module()
+ config_path = tmp_path / "config.json"
+ config_path.write_text(
+ json.dumps(
+ {
+ "agents": {
+ "opencode": {"cli_path": "/usr/local/bin/opencode"},
+ "claude": {"cli_path": "/usr/bin/claude"},
+ "codex": {"cli_path": "/usr/local/bin/codex"},
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("sys.argv", ["prepare_regression.py", "--normalize-config", str(config_path)])
+
+ assert module.main() == 0
+
+ payload = json.loads(config_path.read_text(encoding="utf-8"))
+ assert payload["agents"]["opencode"]["cli_path"] == "opencode"
+ assert payload["agents"]["claude"]["cli_path"] == "claude"
+ assert payload["agents"]["codex"]["cli_path"] == "codex"
+
+
def test_prepare_keeps_avibe_home_authoritative_when_legacy_layout_exists(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None: