The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(verify): refuse compose recipes against a project with running containers
ygd585b6defc766be
diff --git a/agent/verify/runner.py b/agent/verify/runner.pyindex eb6f746cfe4..e9aed619348 100644--- a/agent/verify/runner.py+++ b/agent/verify/runner.py@@ -182,6 +182,24 @@ def _run_start_phase(return ReadinessResult(url, ready, status, time.monotonic() - started, error, _tail(output))+def _running_compose_containers(root: Path) -> list[str] | None:+ """Names of currently-running containers for the compose project at *root*,+ via ``docker compose ps`` (read-only; never mutates anything). ``None`` when the+ check itself could not run (docker/compose unavailable, or not a compose+ project here) -- callers must not treat that as "no running containers".+ """+ try:+ result = subprocess.run(+ ["docker", "compose", "ps", "--status", "running", "--format", "{{.Name}}"],+ cwd=root, capture_output=True, text=True, timeout=15, stdin=subprocess.DEVNULL,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None+ if result.returncode != 0:+ return None+ return [line for line in result.stdout.splitlines() if line.strip()]++def run_verify(root: Path, recipe: Recipe, phases: tuple[str, ...] | list[str] | None = None,phase_timeout: float = DEFAULT_PHASE_TIMEOUT, ready_timeout: float = DEFAULT_READY_TIMEOUT,@@ -189,11 +207,34 @@ def run_verify(on_output: Callable[[str], None] | None = None,) -> VerifyResult:"""Run the selected command phases sequentially, then (unless ``skip_start`` or a- phase failed) boot ``recipe.start``, poll readiness, and tear the process group down."""+ phase failed) boot ``recipe.start``, poll readiness, and tear the process group down.++ A ``compose`` recipe refuses outright when the project already has running+ containers: ``docker compose build`` + ``up`` replaces them on an image-hash+ change, destroying any container-local state they carry -- this has caused a+ real state-loss incident (#103567). The check is best-effort and read-only+ (``docker compose ps``); when it cannot run at all, verify proceeds rather than+ blocking on an unrelated environment gap, matching every other recipe kind's+ behavior when its own tooling is unavailable."""root = Path(root)selected = tuple(phases) if phases else PHASE_ORDER + ("start",)result = VerifyResult(recipe_name=recipe.name)+ if recipe.kind == "compose":+ running = _running_compose_containers(root)+ if running:+ result.phases.append(PhaseResult(+ phase="build", command=recipe.build[0] if recipe.build else "docker compose build",+ exit_code=1, duration=0.0, output_tail=(+ "Refusing to run: this compose project already has running "+ f"container(s) ({', '.join(running)}). `docker compose build` + "+ "`up` would replace them on an image-hash change, destroying any "+ "container-local state they carry. If you intend to rebuild this "+ "live deployment, run `docker compose build`/`up` yourself."+ ),+ ))+ return result+for phase in PHASE_ORDER:if phase not in selected:continuediff --git a/tests/verify/test_environment_and_runner.py b/tests/verify/test_environment_and_runner.pyindex 4c1d8885623..31f0cc83070 100644--- a/tests/verify/test_environment_and_runner.py+++ b/tests/verify/test_environment_and_runner.py@@ -4,6 +4,7 @@ import http.serverimport jsonimport threadingimport time+from unittest.mock import MagicMock, patchfrom agent.verify.environment import (load_manifest,@@ -110,6 +111,90 @@ class TestRunner:result = run_verify(tmp_path, recipe, skip_start=True)assert result.ok++class TestComposeGuard:+ """Regression for issue #103567: a compose recipe must refuse to run+ against a project directory that's already a live compose deployment+ with running containers -- ``docker compose build`` + ``up`` replaces+ them on an image-hash change, destroying container-local state (a real+ incident: a kanban worker's state DB was lost this way)."""++ def _compose_recipe(self):+ return Recipe(+ name="docker-compose project", kind="compose",+ build=["docker compose build"], start="docker compose up",+ evidence=["Detected docker-compose.yml"],+ )++ def test_refuses_when_containers_are_running(self, tmp_path, monkeypatch):+ fake_ps = MagicMock(returncode=0, stdout="myproject-db-1\nmyproject-web-1\n")+ monkeypatch.setattr("subprocess.run", MagicMock(return_value=fake_ps))++ result = run_verify(tmp_path, self._compose_recipe(), skip_start=True)++ assert not result.ok+ assert len(result.phases) == 1+ assert "myproject-db-1" in result.phases[0].output_tail+ assert "myproject-web-1" in result.phases[0].output_tail+ assert "Refusing to run" in result.phases[0].output_tail++ def test_does_not_actually_invoke_build_or_start_when_refusing(self, tmp_path, monkeypatch):+ """The refusal must be a synthetic result -- the real build/start+ commands (which would trigger the destructive replace) must never+ actually be spawned."""+ fake_ps = MagicMock(returncode=0, stdout="myproject-db-1\n")+ calls: list[list[str] | str] = []++ def tracking_run(cmd, *args, **kwargs):+ calls.append(cmd)+ return fake_ps++ monkeypatch.setattr("subprocess.run", tracking_run)++ run_verify(tmp_path, self._compose_recipe(), skip_start=False)++ # Only the read-only "docker compose ps" probe ran -- never+ # "docker compose build" or "docker compose up" as an actual subprocess.+ assert len(calls) == 1+ assert calls[0][:3] == ["docker", "compose", "ps"]++ def test_proceeds_normally_with_no_running_containers(self, tmp_path, monkeypatch):+ fake_ps = MagicMock(returncode=0, stdout="")+ monkeypatch.setattr("subprocess.run", MagicMock(return_value=fake_ps))++ with patch("agent.verify.runner._run_phase_command") as mock_phase:+ mock_phase.return_value = MagicMock(ok=True, phase="build")+ result = run_verify(tmp_path, self._compose_recipe(), phases=("build",))++ assert mock_phase.called++ def test_proceeds_when_the_docker_probe_itself_is_unavailable(self, tmp_path, monkeypatch):+ """docker/compose not installed, or this isn't actually a compose+ project's directory from docker's perspective -- must not block+ verify on an unrelated environment gap."""+ monkeypatch.setattr(+ "subprocess.run",+ MagicMock(side_effect=FileNotFoundError("docker not found")),+ )++ with patch("agent.verify.runner._run_phase_command") as mock_phase:+ mock_phase.return_value = MagicMock(ok=True, phase="build")+ result = run_verify(tmp_path, self._compose_recipe(), phases=("build",))++ assert mock_phase.called++ def test_non_compose_recipes_are_unaffected(self, tmp_path, monkeypatch):+ """The guard is scoped to kind == "compose" only -- a Node/Python/etc.+ recipe must never even check for running compose containers."""+ probe = MagicMock()+ monkeypatch.setattr("agent.verify.runner._running_compose_containers", probe)+ recipe = Recipe(name="x", kind="node", build=["true"])++ result = run_verify(tmp_path, recipe, skip_start=True)++ assert result.ok+ probe.assert_not_called()+def test_result_to_dict(self, tmp_path):recipe = Recipe(name="x", test=["true"])payload = run_verify(tmp_path, recipe, skip_start=True).to_dict()