Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(regression): stabilize web ui restart + clarify local incus workflow (#541)
Call White76ee4444aae7
diff --git a/AGENTS.md b/AGENTS.mdindex 45fda498e..17d2366e5 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-- Incus-based unified regression environment for real cross-platform verification+- local Incus-based unified regression environment for real cross-platform verificationDefault mindset:@@ -95,17 +95,41 @@ Hard rule:When the user says `回归测试`, treat it as:-- update the latest code into the existing Incus-based regression environment+- update the latest code into the existing **local** 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 Incus system container with all four IM platforms enabled simultaneously.+The regression environment is local developer infrastructure only. It must be+created, inspected, updated, and destroyed through the local Incus runner in this+repo. Remote Incus hosts, remote tenant instances, demo instances, and+customer/user environments are not regression environments and must not be used+as fallbacks for development testing.++The local master regression environment runs a single unified Incus system+container with all four IM platforms enabled simultaneously.Standard path:- default command: `./scripts/run_regression.sh`- direct runner: `python3 scripts/incus_regression.py up --target master`+Connection standard (the one supported way to connect — all platforms, all agents):++- The runner reaches Incus through the `INCUS_CMD` knob only: it builds every+ command as `${INCUS_CMD:-incus}`. This is the single supported connection+ mechanism for development regression on every platform.+ - Linux (native daemon): leave `INCUS_CMD` unset (defaults to `incus`), or set+ `INCUS_CMD="sudo incus"` when the user is not in the `incus-admin` group.+ - macOS (Lima): `INCUS_CMD="limactl shell avibe-incus-regression -- sudo incus"`+ (see the macOS note below).+- `--remote` is a *different axis* — it selects **which** Incus daemon to target,+ not **how** to connect — and is **not** a development-regression connection+ method. It is only a rare escape hatch for operating on a genuinely remote+ Incus host; never use it to reach the local regression environment. Do not+ enable a TLS listener / client cert / named remote on the regression VM to+ "connect that way": the daemon is unix-socket-only by design and `INCUS_CMD`+ is the standard.+Connecting to Incus on macOS (Lima):- macOS has no native Incus daemon. The regression environment runs inside the@@ -130,6 +154,14 @@ Connecting to Incus on macOS (Lima):Rules:+- use local Incus only; do not pass `--remote`, switch Incus remotes, SSH to a+ remote host, or inspect remote tenant projects for development regression+ unless the user explicitly asks for remote operations outside the development+ workflow+- `master` is the long-running local regression environment; keep it online and+ preserve its product state across code updates+- a normal master update should sync source and restart the Avibe service inside+ the existing local Incus instance, not recreate the environment or reseed data- 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 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@@ -149,7 +181,11 @@ Worktree behavior:- 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+- non-master worktrees use temporary isolated local Incus project/instances+- after a worktree is merged, abandoned, or no longer needed, delete its+ regression environment with `python3 scripts/incus_regression.py delete+ --target worktree --yes`; use `cleanup-stale --yes` to remove environments for+ worktree paths that no longer exist- worktree mappings live in `.runtime/incus-regression/worktrees.json`## 4. Configuration and Routing Modeldiff --git a/docs/plans/agents-md-restructure.md b/docs/plans/agents-md-restructure.mdindex a84ede0ff..5d37e65a4 100644--- a/docs/plans/agents-md-restructure.md+++ b/docs/plans/agents-md-restructure.md@@ -20,7 +20,7 @@ Rewrite `AGENTS.md` so it becomes a practical operating manual for coding agents1. the project's purpose and current operating model,2. the architecture and design philosophy,3. the expected development and review workflow,-4. the difference between local runtime and three-end regression,+4. the difference between local runtime and local Incus regression,5. and the key safety constraints that must not be violated.## Solutiondiff --git a/docs/plans/backend-lifecycle-chip.md b/docs/plans/backend-lifecycle-chip.mdindex ffef025fb..5a288d711 100644--- a/docs/plans/backend-lifecycle-chip.md+++ b/docs/plans/backend-lifecycle-chip.md@@ -120,4 +120,4 @@ All probes use a 5s timeout and short-circuit to `latest_version=None` on any er- Unit: add focused pytest for version-string parsing + `restart_backend` Claude-path no-op.- Contract: `psutil` lookup is best-effort; no scenario catalog entry needed.-- Manual: in regression Docker, open Settings → Backends, verify each chip renders the right state for installed / missing / disabled and that Upgrade + Restart succeed.+- Manual: in local Incus regression, open Settings → Backends, verify each chip renders the right state for installed / missing / disabled and that Upgrade + Restart succeed.diff --git a/docs/plans/backend-provider-config.md b/docs/plans/backend-provider-config.mdindex ef223dea8..d38e5deb8 100644--- a/docs/plans/backend-provider-config.md+++ b/docs/plans/backend-provider-config.md@@ -355,6 +355,6 @@ the next refresh without a vibe-remote release.provider-API-key writer (existing path, reuse).- Contract: tests scenario for "configure API key in UI → cli sees iton next launch" for each backend.-- Manual: regression Docker — open Settings → Backends → {Claude,+- Manual: local Incus regression — open Settings → Backends → {Claude,Codex, OpenCode}, configure each path, verify backend actually usesthe saved values.diff --git a/docs/plans/claude-reasoning-effort-settings.md b/docs/plans/claude-reasoning-effort-settings.mdindex 23613c70d..7c56a067e 100644--- a/docs/plans/claude-reasoning-effort-settings.md+++ b/docs/plans/claude-reasoning-effort-settings.md@@ -19,7 +19,7 @@3. Pass the selected Claude effort into `ClaudeAgentOptions(effort=...)`.4. Expose Claude reasoning effort in Slack, Discord, Feishu Agent Settings.5. Expose Claude reasoning effort in the Web UI channel/user settings.-6. Validate with targeted Python/UI checks and update the three-end regression environment.+6. Validate with targeted Python/UI checks and update the local Incus regression environment.## Todo@@ -27,4 +27,4 @@- [x] Add shared Claude reasoning option builder and backend wiring.- [x] Add Claude reasoning selectors to Slack/Discord/Feishu Agent Settings.- [x] Add Claude reasoning selectors to Web UI channel/user settings.-- [x] Validate changes and sync them to the three-end regression environment.+- [x] Validate changes and sync them to the local Incus regression environment.diff --git a/docs/plans/fastapi-migration.md b/docs/plans/fastapi-migration.mdindex c2c116ffe..eb4f3cf38 100644--- a/docs/plans/fastapi-migration.md+++ b/docs/plans/fastapi-migration.md@@ -24,7 +24,7 @@ Replace the Flask + `asyncio.run`-per-request model with **FastAPI + uvicorn** (4. The OpenCodeServerManager `_process_loop` / `_lock_loop` / `_http_session_loop` guards stay (defense in depth), but they should not trip in normal operation any more — verify via regression.5. The test suite (currently ~112 hits across tests using `flask.Flask.test_client`-style APIs) is migrated to `fastapi.testclient.TestClient`. Tests stay green.6. A WebSocket-capable route exists end-to-end (one trivial echo route is enough; chat itself is out of scope for this PR) — proves the substrate is ready.-7. Local install via `uv tool install` still works. The regression Docker container starts cleanly and serves the UI at the same host/port.+7. Local install via `uv tool install` still works. The local Incus regression environment starts cleanly and serves the UI at the same host/port.Out of scope for this PR:- Implementing chat. Just prove the WebSocket pipe is wired.diff --git a/docs/plans/feishu-claude-mobile-discord-fixes.md b/docs/plans/feishu-claude-mobile-discord-fixes.mdindex 897ef087d..c77a49a81 100644--- a/docs/plans/feishu-claude-mobile-discord-fixes.md+++ b/docs/plans/feishu-claude-mobile-discord-fixes.md@@ -2,14 +2,14 @@## Background-- In the three-end regression environment, the Feishu instance (`15133`) fails when Claude is selected as the backend.+- In the local Incus regression environment, the Feishu path fails when Claude is selected as the backend.- The observed runtime error is `Command failed with exit code 1`, with stderr indicating `--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons`.- The mobile Web UI currently allows the fixed bottom tab bar to cover the last visible portion of page content.- On Discord, successful menu submissions leave the original interactive message behind as `submitted`, even though a fresh success message is already sent.## Goal-- Make Claude work in the containerized three-end regression environment without resetting user state.+- Make Claude work in the local Incus regression environment without resetting user state.- Prevent the mobile bottom navigation from obscuring page content.- Dismiss successful Discord operation menus instead of replacing them with a `submitted` placeholder.diff --git a/docs/plans/feishu-dm-thread-session-and-dm-thread-research.md b/docs/plans/feishu-dm-thread-session-and-dm-thread-research.mdindex 5db6e6159..7bbe6db25 100644--- a/docs/plans/feishu-dm-thread-session-and-dm-thread-research.md+++ b/docs/plans/feishu-dm-thread-session-and-dm-thread-research.md@@ -36,4 +36,4 @@- [x] Update session base-id logic to respect platform DM thread capability.- [x] Add regression tests for Slack/Discord/Feishu DM session behavior.- [x] Research Slack and Discord DM thread support and summarize the findings.-- [x] Validate changes and sync them to the three-end regression environment.+- [x] Validate changes and sync them to the local Incus regression environment.diff --git a/docs/plans/incus-regression-migration.md b/docs/plans/incus-regression-migration.mddeleted file mode 100644index 25d8836ff..000000000--- a/docs/plans/incus-regression-migration.md+++ /dev/null@@ -1,395 +0,0 @@-# 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/legacy-regression-plan.md b/docs/plans/legacy-regression-plan.mddeleted file mode 100644index c511fea45..000000000--- a/docs/plans/legacy-regression-plan.md+++ /dev/null@@ -1,40 +0,0 @@-# Legacy Regression Plan--> 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. 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 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,-- exposes three separate local UI ports,-- preconfigures each container with its platform, channel, and backend agent routing,-- keeps local secrets out of git,-- and preserves the current automated E2E entrypoints.--## 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 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 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 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.mdindex 8b1cfe24c..c3c811f56 100644--- a/docs/plans/rebrand-avibe.md+++ b/docs/plans/rebrand-avibe.md@@ -135,7 +135,7 @@ symlink `~/.vibe_remote → ~/.avibe`. Hardening so it never strands anyone:raw URLs; update SKILL.md link + `pyproject.toml` URLs.## 6. Codex collaboration (division of labor)-- **Claude (lead execution)**: edits across repos, build the resolver/shims/migration, run ruff + focused pytest + Docker regression + `npm run build`, open the PR, verify (incl. old-user simulation + the API-redirect test).+- **Claude (lead execution)**: edits across repos, build the resolver/shims/migration, run ruff + focused pytest + local Incus regression + `npm run build`, open the PR, verify (incl. old-user simulation + the API-redirect test).- **Codex (thoroughness / adversarial)**:- C1 — independent exhaustive reference sweep across all three repos; reconcile against §3.- C2 — adversarial review of §5a resolver/migration (state paths, first-run races, run-before-live, Windows, regression shared-state) and §5c sequencing.@@ -147,7 +147,7 @@ symlink `~/.vibe_remote → ~/.avibe`. Hardening so it never strands anyone:## 7. Testing / validation- ruff on changed Python before push (AGENTS.md §5).- focused pytest on the home/env resolver (`test_upgrade_flow.py` already exists — extend it).-- Docker regression for user-facing flows; do NOT reset state; confirm old-home users load cleanly.+- local Incus regression for user-facing flows; do NOT reset state; confirm old-home users load cleanly.- `npm run build` for UI copy changes.- live test: updater follows GitHub API 301 after a simulated rename.diff --git a/docs/plans/unified-channel-inventory.md b/docs/plans/unified-channel-inventory.mdindex fe4896720..951bab208 100644--- a/docs/plans/unified-channel-inventory.md+++ b/docs/plans/unified-channel-inventory.md@@ -289,8 +289,8 @@ Validation:- Focused pytest for storage/service/API paths.- `ruff check` on changed Python files.- `npm run build` for UI changes.-- Docker regression only after core behavior is stable, preserving the selected- regression worktree state.+- local Incus regression only after core behavior is stable, preserving the+ selected regression worktree state.## Implementation Order@@ -307,4 +307,3 @@ Validation:8. Expand endpoint and refresh tests.9. Run focused backend tests, lint, and UI build.10. Review the final diff for cross-platform consistency before PR.-diff --git a/docs/plans/web-ui-redesign.md b/docs/plans/web-ui-redesign.mdindex bdc80ddc7..d43bac78e 100644--- a/docs/plans/web-ui-redesign.md+++ b/docs/plans/web-ui-redesign.md@@ -261,7 +261,7 @@ ui/src/- `npm run build` in `ui/`- targeted manual preview of new routes-- Docker regression when user-facing behavior needs end-to-end confirmation+- local Incus regression when user-facing behavior needs end-to-end confirmation- ensure built assets still package correctly through the existing Python flow## Architectural Rules During Implementationdiff --git a/docs/plans/workbench-chat-media-io.md b/docs/plans/workbench-chat-media-io.mdindex 822a8e28c..88abb6d14 100644--- a/docs/plans/workbench-chat-media-io.md+++ b/docs/plans/workbench-chat-media-io.md@@ -195,7 +195,7 @@ extraction primitive stays shared with the IM enhancer.- ✅ `markdown.tsx` img/a overrides + `file-card.tsx`.- ✅ unit tests (`tests/test_workbench_media.py`, 3 pass), `ruff` clean, UI build clean.- ⏳ residual: end-to-end check in the running workbench (real agent reply with a- saved image/file) — best done in the Docker regression env.+ saved image/file) — best done in the local Incus regression environment.### Frontend rendering (`ui/src/components/ui/markdown.tsx`)- `img` override: if `src` matches the proxy route (relative `^/api/sessions/diff --git a/docs/regression/README.md b/docs/regression/README.mdindex c3ffc2a85..47f993333 100644--- a/docs/regression/README.md+++ b/docs/regression/README.md@@ -30,7 +30,7 @@ For deterministic scenario metadata, read:## Runtime Model-The regression runner manages two Incus environment types:+The regression runner manages two **local Incus** environment types:- `master`: a long-running persistent regression environment.- `worktree`: a temporary isolated environment for the current git worktree.@@ -49,12 +49,13 @@ mapping is recorded under `.runtime/incus-regression/worktrees.json` in theprimary 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.+the operator/client. Development regression is local Incus only; do not use+remote Incus hosts, remote tenant instances, demos, or customer/user+environments for project testing.## Setup-1. Configure an Incus host or remote.+1. Configure the local Incus host.```bashpython3 scripts/incus_regression.py doctor@@ -126,9 +127,12 @@ python3 scripts/incus_regression.py delete --target worktree --yespython3 scripts/incus_regression.py cleanup-stale --yes```+Delete worktree environments promptly after the worktree is merged, abandoned,+or removed. The persistent `master` environment should stay running and preserve+its product state across normal source updates.+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.diff --git a/scripts/incus_regression.py b/scripts/incus_regression.pyindex 234ed99ea..6b8cc0d93 100644--- a/scripts/incus_regression.py+++ b/scripts/incus_regression.py@@ -61,9 +61,7 @@ DEFAULT_MASTER_HOST_PORT = 15130DEFAULT_WORKTREE_PORT_START = 15200DEFAULT_WORKTREE_PORT_END = 15399ENV_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]$")@@ -148,8 +146,6 @@ def validate_slug(slug: str) -> None: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 = defaultreturn value.strip()@@ -159,7 +155,6 @@ 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)@@ -247,8 +242,6 @@ def load_env_file(repo_root: Path, env_file: Path | None) -> Path | None: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:@@ -848,11 +841,6 @@ def runtime_env_payload(repo_root: Path | None = None) -> bytes:continueif 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")@@ -870,12 +858,7 @@ def required_platform_seed_envs() -> tuple[str, ...]: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 ""+ return value.strip()def require_runtime_seed_env() -> None:@@ -1517,6 +1500,10 @@ def cmd_cleanup_stale(args: argparse.Namespace) -> int:def add_common(parser: argparse.ArgumentParser) -> None:parser.add_argument("--dry-run", action="store_true", help="Print commands without changing Incus.")+ # Keep --remote as an explicit escape hatch for the rare remote-ops case the+ # docs call out. Local dev defaults to None (no remote); the remote_ref /+ # preflight-skip machinery still keys off it, so deleting the flag would force+ # args.remote=None always and run the host-port preflight on the wrong host.parser.add_argument("--remote", help="Optional Incus remote name.")diff --git a/scripts/incus_regression_supervisor.py b/scripts/incus_regression_supervisor.pyindex 7555a9372..e5c833b44 100644--- a/scripts/incus_regression_supervisor.py+++ b/scripts/incus_regression_supervisor.py@@ -3,15 +3,62 @@from __future__ import annotations+import osimport signalimport sysimport time+from pathlib import Pathfrom config import pathsfrom config.v2_config import V2Configfrom vibe import runtime+def _read_pid_file(pid_path: Path) -> int | None:+ try:+ pid = int(pid_path.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ return None+ return pid if pid > 0 else None+++def _reap_child(pid: int | None) -> None:+ if not isinstance(pid, int) or pid <= 0 or os.name == "nt":+ return+ try:+ os.waitpid(pid, os.WNOHANG)+ except ChildProcessError:+ return+ except OSError:+ return+++def _restart_in_progress() -> bool:+ status = runtime.read_json(runtime.get_restart_status_path()) or {}+ # Only the active stop/start phase ("running") should suppress the supervisor's+ # own recovery. A "scheduled" (delayed) restart is just sleeping and hasn't+ # touched the service yet, so a crash during the delay must still be recovered+ # immediately rather than waiting for the job to wake.+ if status.get("ok") is not None or status.get("state") != "running":+ return False+ # And only while the job process is still alive: a stale status left by a+ # killed restart job or a reboot would otherwise keep this true forever, so the+ # supervisor would loop writing "restarting" instead of exiting nonzero to let+ # systemd recover the service.+ restart_pid = status.get("supervisor_pid")+ if not (isinstance(restart_pid, int) and restart_pid > 0 and runtime.pid_alive(restart_pid)):+ return False+ # Defend against pid reuse (notably across a reboot): confirm the live pid is+ # still the same process the restart job recorded, by start time. Only treat a+ # mismatch as stale; if either start time is unavailable, fall back to the+ # liveness check above.+ recorded_started_at = status.get("supervisor_started_at")+ current_started_at = runtime.process_create_time(restart_pid)+ if isinstance(recorded_started_at, (int, float)) and current_started_at is not None:+ return abs(current_started_at - recorded_started_at) < 1.0+ return True++def _config() -> V2Config:runtime.ensure_dirs()return runtime.ensure_config()@@ -43,18 +90,49 @@ def main() -> int:return 1while 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+ # _restart_in_progress() is read fresh at each decision below rather than+ # snapshotted here: a managed restart can begin mid-iteration, and a stale+ # snapshot would let the supervisor kill a healthy restart.+ current_service_pid = _read_pid_file(paths.get_runtime_pid_path())+ # Only track a *ready* service pid (recorded and holding the service lock).+ # Adopting a pid just because the file changed would let a hung restart+ # that never becomes ready masquerade as healthy and block recovery.+ if (+ current_service_pid+ and current_service_pid != service_pid+ and runtime.service_pid_recorded(current_service_pid)+ ):+ _reap_child(service_pid)+ service_pid = current_service_pid++ current_ui_pid = _read_pid_file(paths.get_runtime_ui_pid_path()) or ui_pidif 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)+ _reap_child(current_ui_pid)+ if not _restart_in_progress():+ 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)+ elif current_ui_pid != ui_pid:+ ui_pid = current_ui_pid+if not runtime.pid_alive(service_pid):+ _reap_child(service_pid)+ current_service_pid = _read_pid_file(paths.get_runtime_pid_path())+ if (+ current_service_pid+ and current_service_pid != service_pid+ and runtime.service_pid_recorded(current_service_pid)+ ):+ service_pid = current_service_pid+ time.sleep(1)+ continue+ # Re-read right before the recovery exit: a managed restart may have+ # begun after the dead-service check above, and exiting for systemd+ # would interrupt a healthy restart.+ if _restart_in_progress():+ runtime.write_status("restarting", "incus regression restart in progress", service_pid, ui_pid)+ time.sleep(1)+ continueruntime.write_status("error", "service exited in incus regression", service_pid, ui_pid)runtime.stop_ui()return 1diff --git a/scripts/prepare_regression.py b/scripts/prepare_regression.pyindex d9d84f7b2..185463ed0 100755--- a/scripts/prepare_regression.py+++ b/scripts/prepare_regression.py@@ -56,21 +56,10 @@ 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 = defaultreturn value.strip()diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.pydeleted file mode 100755index 7ba2aba2c..000000000--- a/scripts/prepare_three_regression.py+++ /dev/null@@ -1,8 +0,0 @@-#!/usr/bin/env python3-"""Compatibility entrypoint for the renamed regression state preparer."""--from prepare_regression import main---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/run_regression.sh b/scripts/run_regression.shindex 085c2ed78..7725e61de 100755--- a/scripts/run_regression.sh+++ b/scripts/run_regression.sh@@ -11,7 +11,7 @@ if ! command -v "$PYTHON_BIN" >/dev/null 2>&1; thenfimode="up"-target="${REGRESSION_TARGET:-${THREE_REGRESSION_TARGET:-master}}"+target="${REGRESSION_TARGET:-master}"incus_args=()passthrough=()@@ -71,7 +71,7 @@ while [ $# -gt 0 ]; do;;--remote|--incus-remote)if [ $# -lt 2 ]; then- echo "--incus-remote requires a remote name" >&2+ echo "--remote requires a remote name" >&2exit 1fiincus_args+=(--remote "$2")diff --git a/scripts/run_three_regression.sh b/scripts/run_three_regression.shdeleted file mode 100755index ace987215..000000000--- a/scripts/run_three_regression.sh+++ /dev/null@@ -1,7 +0,0 @@-#!/bin/bash--set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"--exec "$SCRIPT_DIR/run_regression.sh" "$@"diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.pyindex 5aaccd50b..4606b6e15 100644--- a/tests/test_incus_regression.py+++ b/tests/test_incus_regression.py@@ -23,7 +23,6 @@ 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",@@ -63,7 +62,7 @@ def test_master_target_uses_env_host_port(monkeypatch: pytest.MonkeyPatch) -> Noassert target.host_port == 15131-def test_master_target_accepts_legacy_env_host_port(monkeypatch: pytest.MonkeyPatch) -> None:+def test_master_target_ignores_legacy_env_host_port(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.delenv("REGRESSION_PORT", raising=False)monkeypatch.setenv("THREE_REGRESSION_PORT", "15132")@@ -81,7 +80,7 @@ def test_master_target_accepts_legacy_env_host_port(monkeypatch: pytest.MonkeyPadry_run=True,)- assert target.host_port == 15132+ assert target.host_port == 15130def test_master_target_uses_env_bind_host_after_env_load(monkeypatch: pytest.MonkeyPatch) -> None:@@ -515,7 +514,7 @@ def test_runtime_env_payload_maps_show_runtime_and_llm_env(monkeypatch: pytest.Massert "OPENAI_API_KEY=sk-test" in payload-def test_runtime_env_payload_normalizes_legacy_regression_env(monkeypatch: pytest.MonkeyPatch) -> None:+def test_runtime_env_payload_ignores_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")@@ -523,8 +522,8 @@ def test_runtime_env_payload_normalizes_legacy_regression_env(monkeypatch: pytespayload = incus_regression.runtime_env_payload().decode()- assert "VIBE_SHOW_RUNTIME_GITHUB_REF=legacy-ref" in payload- assert "REGRESSION_SLACK_CHANNEL=CLEGACY" in payload+ assert "VIBE_SHOW_RUNTIME_GITHUB_REF=main" in payload+ assert "REGRESSION_SLACK_CHANNEL=CLEGACY" not in payloadassert "THREE_REGRESSION_SLACK_CHANNEL" not in payload@@ -550,7 +549,7 @@ def test_load_env_file_accepts_export_prefix(tmp_path: Path, monkeypatch: pytestassert 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:+def test_load_env_file_ignores_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)@@ -558,8 +557,8 @@ def test_load_env_file_falls_back_to_legacy_file(tmp_path: Path, monkeypatch: pyloaded = incus_regression.load_env_file(tmp_path, None)- assert loaded == env_file- assert incus_regression.os.environ["THREE_REGRESSION_SLACK_CHANNEL"] == "C123"+ assert loaded is None+ assert "THREE_REGRESSION_SLACK_CHANNEL" not in incus_regression.os.environdef test_require_runtime_seed_env_fails_fast_for_blank_values(monkeypatch: pytest.MonkeyPatch) -> None:@@ -592,15 +591,18 @@ def test_require_runtime_seed_env_checks_platform_credentials(monkeypatch: pytesassert "REGRESSION_FEISHU_APP_SECRET" in str(excinfo.value)-def test_require_runtime_seed_env_accepts_legacy_platform_credentials(monkeypatch: pytest.MonkeyPatch) -> None:+def test_require_runtime_seed_env_rejects_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):]+ legacy_key = "THREE_" + keymonkeypatch.setenv(legacy_key, "legacy")- incus_regression.require_runtime_seed_env()+ with pytest.raises(SystemExit) as excinfo:+ incus_regression.require_runtime_seed_env()++ assert "REGRESSION_SLACK_BOT_TOKEN" in str(excinfo.value)def test_prepare_state_skips_existing_state_without_reset() -> None:@@ -1147,7 +1149,7 @@ def test_up_defers_master_port_preflight_until_after_instance_exists(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:+def test_up_checks_host_port_preflight_for_new_local_instance(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:class NewRemoteRunner:def __init__(self, *, dry_run=False):self.dry_run = dry_run@@ -1162,7 +1164,8 @@ def test_up_skips_host_port_preflight_for_remote_new_instance(tmp_path: Path, momonkeypatch.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")))+ preflight_calls = []+ monkeypatch.setattr(incus_regression, "ensure_host_port_available", lambda host, port: preflight_calls.append((host, port)))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)@@ -1195,7 +1198,7 @@ def test_up_skips_host_port_preflight_for_remote_new_instance(tmp_path: Path, momemory="4GiB",disk="20GiB",processes="4096",- remote="lab",+ remote=None,clean=False,force_deps=False,no_build_ui=True,@@ -1203,6 +1206,7 @@ def test_up_skips_host_port_preflight_for_remote_new_instance(tmp_path: Path, mo)assert incus_regression.cmd_up(args) == 0+ assert preflight_calls == [("127.0.0.1", 15130)]def test_up_checks_seed_env_before_target_mutation(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:diff --git a/tests/test_incus_regression_supervisor.py b/tests/test_incus_regression_supervisor.pynew file mode 100644index 000000000..490f7d6fc--- /dev/null+++ b/tests/test_incus_regression_supervisor.py@@ -0,0 +1,157 @@+from __future__ import annotations++import importlib.util+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++from config import paths+from vibe import runtime++# The supervisor lives in scripts/ (not an installed package); load it the same+# way test_incus_regression.py loads its sibling script.+SCRIPT_PATH = Path(__file__).resolve().parents[1] / "scripts" / "incus_regression_supervisor.py"+SPEC = importlib.util.spec_from_file_location("incus_regression_supervisor", SCRIPT_PATH)+supervisor = importlib.util.module_from_spec(SPEC)+assert SPEC and SPEC.loader+sys.modules[SPEC.name] = supervisor+SPEC.loader.exec_module(supervisor)+++def _write_restart_status(status: dict) -> None:+ path = runtime.get_restart_status_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(path, status)+++def test_restart_in_progress_true_while_job_pid_alive(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_started_at": 1000.0})+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4242)+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 1000.0)++ assert supervisor._restart_in_progress() is True+++def test_restart_in_progress_false_when_pid_reused(monkeypatch, tmp_path):+ # Pid is alive but its start time no longer matches what the job recorded —+ # the pid was reused (e.g. after a reboot) by an unrelated process, so the+ # restart is not actually in progress and recovery must proceed.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242, "supervisor_started_at": 1000.0})+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 4242)+ monkeypatch.setattr(runtime, "process_create_time", lambda pid: 9999.0)++ assert supervisor._restart_in_progress() is False+++def test_restart_in_progress_false_when_job_pid_dead(monkeypatch, tmp_path):+ # The P2: a killed restart job or a reboot leaves ok=None + state=running with+ # a now-dead pid. The supervisor must treat it as stale, not in progress, so+ # it can exit nonzero and let systemd recover instead of looping "restarting".+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": None, "state": "running", "supervisor_pid": 4242})+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)++ assert supervisor._restart_in_progress() is False+++def test_restart_in_progress_false_without_recorded_pid(monkeypatch, tmp_path):+ # An older "running" status with no job pid can't be confirmed alive → stale.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": None, "state": "running"})++ assert supervisor._restart_in_progress() is False+++def test_restart_in_progress_false_for_scheduled_restart(monkeypatch, tmp_path):+ # A delayed restart is only sleeping ("scheduled") and hasn't stopped the+ # service yet, so a crash during the delay must still be recovered — even+ # though the job process is alive.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": None, "state": "scheduled", "supervisor_pid": 4242})+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)++ assert supervisor._restart_in_progress() is False+++def test_restart_in_progress_false_when_completed(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ _write_restart_status({"ok": True, "state": "succeeded", "supervisor_pid": 4242})+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)++ assert supervisor._restart_in_progress() is False+++def test_main_recovers_when_restart_leaves_unready_service(monkeypatch, tmp_path):+ # Codex P2: after a restart writes a new service pid that hangs (alive but+ # never acquires the lock) and the restart job then fails, the supervisor must+ # not adopt the unready pid and loop forever — it must exit nonzero so systemd+ # recovers the service. Old ready pid 100 is dead; the file now points at the+ # hung pid 200 (alive, not recorded); the UI (333) is alive; no restart active.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_pid_path().write_text("200", encoding="utf-8")+ paths.get_runtime_ui_pid_path().write_text("333", encoding="utf-8")++ monkeypatch.setattr(supervisor, "_config", lambda: SimpleNamespace(ui=SimpleNamespace(setup_port=8080)))+ monkeypatch.setattr(supervisor, "_reap_child", lambda pid: None)+ monkeypatch.setattr(supervisor, "_restart_in_progress", lambda: False)+ monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True: 100)+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")+ monkeypatch.setattr(runtime, "start_ui", lambda host, port: 333)+ # 100 was ready at startup; the hung 200 never records (no lock).+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 100)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in {200, 333})+ monkeypatch.setattr(runtime, "stop_ui", lambda *args, **kwargs: None)+ monkeypatch.setattr(runtime, "stop_service", lambda *args, **kwargs: None)+ monkeypatch.setattr(supervisor.time, "sleep", lambda _seconds: None)++ rc = supervisor.main()++ assert rc == 1+ assert runtime.read_status()["state"] == "error"+++def test_main_backs_off_during_active_restart(monkeypatch, tmp_path):+ # Service is gone but a managed restart is in progress → the supervisor must+ # write "restarting" and keep waiting, never exit for systemd. Guards the+ # TOCTOU where the restart begins after the loop-top: the recovery branch+ # re-reads _restart_in_progress() before exiting.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_ui_pid_path().write_text("333", encoding="utf-8")++ monkeypatch.setattr(supervisor, "_config", lambda: SimpleNamespace(ui=SimpleNamespace(setup_port=8080)))+ monkeypatch.setattr(supervisor, "_reap_child", lambda pid: None)+ monkeypatch.setattr(supervisor, "_restart_in_progress", lambda: True)+ monkeypatch.setattr(runtime, "start_service", lambda wait_for_ready=True: 100)+ monkeypatch.setattr(runtime, "effective_ui_bind_host", lambda config: "127.0.0.1")+ monkeypatch.setattr(runtime, "start_ui", lambda host, port: 333)+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 100)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 333) # service 100 dead, ui alive++ statuses: list[str] = []+ monkeypatch.setattr(runtime, "write_status", lambda state, *a, **k: statuses.append(state))++ class _Stop(Exception):+ pass++ def stop_on_sleep(_seconds):+ raise _Stop()++ monkeypatch.setattr(supervisor.time, "sleep", stop_on_sleep)++ with pytest.raises(_Stop):+ supervisor.main()++ assert "restarting" in statuses+ assert "error" not in statusesdiff --git a/tests/test_prepare_regression.py b/tests/test_prepare_regression.pyindex b792b075e..6f74bfbd1 100644--- a/tests/test_prepare_regression.py+++ b/tests/test_prepare_regression.py@@ -153,18 +153,16 @@ def test_prepare_derives_openai_relay_base_from_anthropic_base(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):+def test_prepare_ignores_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"+ assert settings["scopes"]["channel"]["slack"] == {}def test_prepare_preserves_existing_state_without_reset(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):@@ -434,10 +432,6 @@ def test_prepare_allows_missing_channel_ids(tmp_path: Path, monkeypatch: pytest.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)- monkeypatch.delenv("THREE_REGRESSION_WECHAT_CHANNEL", raising=False)module.prepare(tmp_path, reset_mode="config")diff --git a/tests/test_regression_script.py b/tests/test_regression_script.pyindex bbe7c65e7..fa0a1dff5 100644--- a/tests/test_regression_script.py+++ b/tests/test_regression_script.py@@ -13,11 +13,6 @@ def test_regression_script_has_valid_shell_syntax() -> None: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:@@ -40,10 +35,9 @@ def test_regression_script_maps_legacy_flags_to_incus() -> None: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_legacy_three_regression_wrapper_was_removed() -> None:+ assert not (REPO_ROOT / "scripts" / "run_three_regression.sh").exists()+ assert not (REPO_ROOT / "scripts" / "prepare_three_regression.py").exists()def test_regression_maintenance_commands_accept_env_file(tmp_path: Path) -> None:@@ -52,7 +46,7 @@ def test_regression_maintenance_commands_accept_env_file(tmp_path: Path) -> Nonesubprocess.run([- str(REPO_ROOT / "scripts" / "run_three_regression.sh"),+ str(REPO_ROOT / "scripts" / "run_regression.sh"),"--status","--env-file",str(env_file),@@ -82,22 +76,14 @@ def test_regression_wrapper_forwards_worktree_port_range() -> None:)-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,- )+def test_regression_wrapper_forwards_remote_flag() -> None:+ # --remote is the documented escape hatch for explicit remote ops; the wrapper+ # must forward it to incus_regression.py (which still registers it), not reject+ # it. Asserted statically (running the wrapper would reach the Incus daemon).+ script = (REPO_ROOT / "scripts" / "run_regression.sh").read_text(encoding="utf-8")- assert "lab:avibe-master" in result.stdout+ assert "--remote|--incus-remote)" in script+ assert 'incus_args+=(--remote "$2")' in scriptdef test_regression_wrapper_accepts_paired_master_reset_override() -> None:diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex 6649ccaed..3b9ed9b5a 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -1,8 +1,11 @@from __future__ import annotations+import osimport threadingfrom types import SimpleNamespace+import pytest+from config import pathsfrom vibe import restart_supervisorfrom vibe import runtime@@ -86,6 +89,32 @@ def test_schedule_restart_can_prepare_show_runtime_after_restart(monkeypatch, tmassert "--prepare-show-runtime" in calls["command"]+def test_schedule_restart_marks_status_failed_when_spawn_fails(monkeypatch, tmp_path):+ # The "scheduled" status is seeded before spawning; if the spawn fails, no+ # child will overwrite it, so schedule_restart must mark it failed (otherwise+ # `vibe status` shows a permanently pending restart that never ran).+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)++ def boom(*args, **kwargs):+ raise OSError("no such executable")++ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", boom)++ with pytest.raises(OSError):+ restart_supervisor.schedule_restart(delay_seconds=0, vibe_path="/bin/vibe", trigger="agent")++ status = runtime.read_json(runtime.get_restart_status_path())+ assert status["ok"] is False+ assert status["state"] == "failed"+ assert "failed to spawn" in status["error"]++def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()@@ -94,6 +123,7 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)@@ -106,11 +136,16 @@ def test_restart_job_stops_and_starts_service(monkeypatch, tmp_path):assert status["state"] == "succeeded"assert status["old_pid"] == 111assert status["new_pid"] == 222+ # The job records its own pid + start time so a watcher can validate the+ # restart is live and not a reused pid.+ assert status["supervisor_pid"] == os.getpid()+ assert isinstance(status["supervisor_started_at"], (int, float))assert status["stage_durations"]["stop_remote_access_seconds"] == 0.01assert status["stage_durations"]["stop_remote_access_skipped"] is Trueassert "stop_ui_total_seconds" in status["stage_durations"]assert "stop_service_seconds" in status["stage_durations"]assert "stop_runtime_seconds" in status["stage_durations"]+ assert "wait_service_lock_release_seconds" in status["stage_durations"]assert "start_runtime_seconds" in status["stage_durations"]assert "restart_total_seconds" in status["stage_durations"]@@ -123,6 +158,7 @@ def test_restart_job_prepares_show_runtime_after_service_start(monkeypatch, tmp_monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "get_restart_command", lambda vibe_path=None: ["/bin/vibe"])monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)@@ -164,6 +200,7 @@ def test_restart_job_aborts_when_stop_fails(monkeypatch, tmp_path):lambda: _fake_stop_runtime(calls, service_stopped=False),)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 111)+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor.subprocess, "run", lambda *args, **kwargs: calls.append("run"))rc = restart_supervisor._run_restart_job(job_id="jobdef", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")@@ -188,6 +225,7 @@ def test_restart_job_continues_when_old_pid_already_exited(monkeypatch, tmp_pathlambda: _fake_stop_runtime(calls, service_stopped=False),)monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)@@ -205,6 +243,7 @@ def test_restart_job_adopts_slow_starting_service_pid(monkeypatch, tmp_path):calls = []monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)def slow_start_runtime():calls.append("start_runtime")runtime.write_status("starting", "service process is still starting", 222, 333)@@ -238,6 +277,7 @@ def test_restart_job_marks_start_runtime_failed(monkeypatch, tmp_path):paths.get_runtime_pid_path().write_text("111", encoding="utf-8")monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime([]))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: True)monkeypatch.setattr(restart_supervisor,"_start_runtime_processes",@@ -254,6 +294,57 @@ def test_restart_job_marks_start_runtime_failed(monkeypatch, tmp_path):assert "restart_total_seconds" in status["stage_durations"]+def test_restart_job_waits_for_service_lock_release_before_start(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_pid_path().write_text("111", encoding="utf-8")+ calls = []++ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_start_runtime_processes", lambda: _fake_start_runtime(calls))++ lock_checks = iter([(False, 111), (True, None)])++ def service_instance_lock_available():+ calls.append("lock_available")+ return next(lock_checks)++ monkeypatch.setattr(runtime, "service_instance_lock_available", service_instance_lock_available)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 222)+ monkeypatch.setattr(runtime, "service_pid_recorded", lambda pid: pid == 222)+ monkeypatch.setattr(restart_supervisor.time, "sleep", lambda _seconds: None)++ rc = restart_supervisor._run_restart_job(job_id="joblock", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")++ assert rc == 0+ assert calls == ["stop_runtime", "lock_available", "lock_available", "start_runtime"]+ assert runtime.read_json(runtime.get_restart_status_path())["state"] == "succeeded"+++def test_restart_job_fails_when_service_lock_does_not_release(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ paths.get_runtime_pid_path().write_text("111", encoding="utf-8")+ calls = []++ monkeypatch.setattr(restart_supervisor, "_stop_runtime_for_restart", lambda: _fake_stop_runtime(calls))+ monkeypatch.setattr(restart_supervisor, "_wait_for_service_lock_release", lambda: False)+ monkeypatch.setattr(+ restart_supervisor,+ "_start_runtime_processes",+ lambda: (_ for _ in ()).throw(AssertionError("start should wait for lock release")),+ )+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: False)++ rc = restart_supervisor._run_restart_job(job_id="joblockfail", delay_seconds=0, vibe_path="/bin/vibe", trigger="test")++ assert rc == 2+ assert calls == ["stop_runtime"]+ status = runtime.read_json(runtime.get_restart_status_path())+ assert status["state"] == "failed"+ assert "service lock did not release" in status["error"]++def test_start_runtime_processes_starts_service_and_ui(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))calls = []diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex e82692a66..0faa01d77 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -5,6 +5,7 @@ import signalimport shleximport sqlite3import sys+import threadingfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import patch@@ -222,6 +223,50 @@ def test_pid_alive_returns_true_on_permission_error(monkeypatch):assert runtime.pid_alive(12345) is True+def test_pid_alive_returns_false_for_zombie_process(monkeypatch):+ monkeypatch.setattr(runtime.os, "name", "posix", raising=False)+ monkeypatch.setattr(runtime.os, "kill", lambda _pid, _sig: None)++ class ZombieProcess:+ def __init__(self, pid):+ self.pid = pid++ def status(self):+ return runtime.psutil.STATUS_ZOMBIE++ monkeypatch.setattr(runtime.psutil, "Process", ZombieProcess)++ assert runtime.pid_alive(12345) is False+++def test_write_json_is_atomic_and_concurrency_safe(tmp_path):+ # write_json must use a unique temp per call so concurrent in-process writers+ # (e.g. overlapping threadpool-dispatched control requests) never collide on a+ # shared temp file, and must never leave the target half-written or temps behind.+ target = tmp_path / "status.json"+ errors: list[Exception] = []++ def hammer(worker: int) -> None:+ try:+ for i in range(50):+ runtime.write_json(target, {"worker": worker, "i": i})+ except Exception as exc: # noqa: BLE001 - surface any write race to the assert+ errors.append(exc)++ threads = [threading.Thread(target=hammer, args=(w,)) for w in range(4)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert not errors+ # Target is always a complete JSON document, never a partial write.+ assert isinstance(json.loads(target.read_text(encoding="utf-8")), dict)+ # No leftover temp files in the directory.+ assert list(tmp_path.glob(".status.json.*.tmp")) == []+ assert [p for p in tmp_path.iterdir() if p.name != "status.json"] == []++def test_pid_alive_delegates_to_windows_probe(monkeypatch):monkeypatch.setattr(runtime.os, "name", "nt", raising=False)monkeypatch.setattr(runtime, "_pid_alive_windows", lambda pid: pid == 4321)diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 3c9723dd2..68a92c1ad 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -17,6 +17,7 @@ from vibe.upgrade import get_restart_command, get_restart_environment, get_restalogger = logging.getLogger(__name__)_RESTART_LOG_RETENTION = 10+_SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS = 30.0def _now_iso() -> str:@@ -156,6 +157,17 @@ def _stop_runtime_for_restart() -> tuple[bool, dict[str, float | bool], float, ireturn ui_stopped, ui_timings, stop_ui_seconds, ui_pid, service_stopped, stop_service_seconds+def _wait_for_service_lock_release(timeout: float = _SERVICE_LOCK_RELEASE_TIMEOUT_SECONDS) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ available, _holder_pid = runtime.service_instance_lock_available()+ if available:+ return True+ time.sleep(0.2)+ available, _holder_pid = runtime.service_instance_lock_available()+ return available++def _run_restart_job(*,job_id: str,@@ -189,6 +201,13 @@ def _run_restart_job(payload = {"ok": None,"job_id": job_id,+ # Record this restart job's own pid (and start time) so a watcher+ # (e.g. the incus regression supervisor) can tell a live restart from a+ # stale status left by a killed job or a reboot, and from an unrelated+ # process that later reused the pid. Matches the key schedule_restart+ # seeds with the spawned subprocess pid (this process is that pid).+ "supervisor_pid": os.getpid(),+ "supervisor_started_at": runtime.process_create_time(os.getpid()),"state": "scheduled" if delay_seconds > 0 else "running","trigger": trigger,"delay_seconds": delay_seconds,@@ -227,6 +246,12 @@ def _run_restart_job(if old_pid and stopped is False and runtime.pid_alive(old_pid):return _fail(payload, f"service pid {old_pid} did not stop", log, 2, started_at=restart_started_at)+ wait_lock_release_started_at = time.monotonic()+ if not _wait_for_service_lock_release():+ mark_duration("wait_service_lock_release_seconds", wait_lock_release_started_at)+ return _fail(payload, "service lock did not release after stopping runtime", log, 2, started_at=restart_started_at)+ mark_duration("wait_service_lock_release_seconds", wait_lock_release_started_at)+write("starting service")start_runtime_started_at = time.monotonic()try:@@ -318,25 +343,19 @@ def schedule_restart(env = get_restart_environment(vibe_path=vibe_path)log_path = _restart_log_path(job_id)log_path.parent.mkdir(parents=True, exist_ok=True)- with log_path.open("a", encoding="utf-8") as log:- log.write(f"{_now_iso()} spawning restart supervisor job_id={job_id} delay_seconds={delay_seconds!r}\n")- log.flush()- process = subprocess.Popen(- command,- stdout=log,- stderr=subprocess.STDOUT,- start_new_session=True,- close_fds=True,- cwd=get_safe_cwd(),- env=env,- )+ # Seed the status BEFORE spawning the job so the child's own writes (which set+ # state="running" plus its pid and start time) always land afterwards and are+ # never clobbered. A zero-delay restart could otherwise race the parent's+ # "scheduled" write on top of the child's "running" write, hiding the active+ # restart from the supervisor and making it treat the stopped service as a+ # crash. The job records its real supervisor_pid once it starts.payload = {"ok": None,"job_id": job_id,"state": "scheduled","trigger": trigger,"delay_seconds": delay_seconds,- "supervisor_pid": process.pid,+ "supervisor_pid": None,"old_pid": _read_recorded_pid(),"new_pid": None,"log_path": str(log_path),@@ -344,6 +363,31 @@ def schedule_restart("created_at": _now_iso(),}_write_status(payload)+ try:+ with log_path.open("a", encoding="utf-8") as log:+ log.write(f"{_now_iso()} spawning restart supervisor job_id={job_id} delay_seconds={delay_seconds!r}\n")+ log.flush()+ process = subprocess.Popen(+ command,+ stdout=log,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ close_fds=True,+ cwd=get_safe_cwd(),+ env=env,+ )+ except OSError as exc:+ # The seed status above is now "scheduled"; if the job can't be spawned+ # (bad cached vibe path, missing executable, permission/log-open error) no+ # child will ever overwrite it, leaving a permanently pending restart in+ # `vibe status`. Mark it failed before propagating.+ payload.update(ok=False, state="failed", error=f"failed to spawn restart supervisor: {exc}")+ _write_status(payload)+ _prune_restart_logs()+ raise+ # Surface the spawned pid to the caller without rewriting the status (that+ # would reintroduce the race); the job writes its own pid on disk when it runs.+ payload["supervisor_pid"] = process.pid_prune_restart_logs()return payloaddiff --git a/vibe/runtime.py b/vibe/runtime.pyindex 0adebef60..10cae5762 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -6,12 +6,15 @@ import shleximport socketimport subprocessimport sys+import tempfileimport threadingimport timeimport urllib.errorimport urllib.requestfrom pathlib import Path+import psutil+from config import pathsfrom config.v2_config import (AgentsConfig,@@ -137,7 +140,24 @@ def ensure_config():def write_json(path, payload):- path.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ # Write atomically (unique temp file in the same dir + os.replace) so a+ # concurrent reader never sees a half-written file. The regression supervisor+ # polls status files (e.g. restart_status.json) while restart jobs rewrite+ # them, and a partial read would otherwise surface as None and be misread as+ # "no restart in progress". The temp name must be unique *per call* — several+ # threads in this process can write the same status path at once (e.g.+ # overlapping FastAPI control requests dispatched through a threadpool), and a+ # shared temp name would let one writer's os.replace yank the file from under+ # another.+ fd, tmp_name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")+ tmp = Path(tmp_name)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(json.dumps(payload, indent=2))+ os.replace(tmp, path)+ except OSError:+ tmp.unlink(missing_ok=True)+ raisedef read_json(path):@@ -463,13 +483,38 @@ def pid_alive(pid):try:os.kill(pid, 0)- return Trueexcept ProcessLookupError:return Falseexcept PermissionError:return Trueexcept (OSError, ValueError, SystemError):return False+ try:+ status = psutil.Process(pid).status()+ except psutil.NoSuchProcess:+ return False+ except psutil.AccessDenied:+ return True+ except psutil.Error:+ return True+ dead_statuses = {psutil.STATUS_ZOMBIE}+ status_dead = getattr(psutil, "STATUS_DEAD", None)+ if status_dead is not None:+ dead_statuses.add(status_dead)+ return status not in dead_statuses+++def process_create_time(pid: int) -> float | None:+ """Wall-clock start time of a process, or ``None`` if it can't be read.++ Used to tell a recorded pid apart from an unrelated process that later reused+ the same pid (notably across a reboot): a reused pid has a different start+ time, so ``(pid, create_time)`` identifies the original process.+ """+ try:+ return float(psutil.Process(pid).create_time())+ except (psutil.Error, ValueError, TypeError):+ return Nonedef stop_pid(pid: int, timeout: float = 5) -> bool: