Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

fix(cli): show why a deployment failed and fix deploy remove and lockfile checks (#8083)

João Moura744bf6036700
diff --git a/docs/edge/ar/concepts/cli.mdx b/docs/edge/ar/concepts/cli.mdx
index 28162a61c..2989ca2a2 100644
--- a/docs/edge/ar/concepts/cli.mdx
+++ b/docs/edge/ar/concepts/cli.mdx
@@ -207,6 +207,7 @@ def crew(self) -> Crew:
```shell Terminal
crewai deploy status
```
+ يجلب هذا أحدث حالة لآخر محاولة نشر (مثل `Building Images for Crew` و`Deploy Enqueued` و`Online`). إذا فشل النشر، يعرض أيضًا الخطأ وإصلاحًا مقترحًا.
- **سجلات النشر**:
```shell Terminal
diff --git a/docs/edge/en/concepts/cli.mdx b/docs/edge/en/concepts/cli.mdx
index 1562c9e0c..5427b57de 100644
--- a/docs/edge/en/concepts/cli.mdx
+++ b/docs/edge/en/concepts/cli.mdx
@@ -346,7 +346,7 @@ crewai org switch <organization_id>
crewai deploy status
```
- This fetches the latest deployment status of your most recent deployment attempt (e.g., `Building Images for Crew`, `Deploy Enqueued`, `Online`).
+ This fetches the latest deployment status of your most recent deployment attempt (e.g., `Building Images for Crew`, `Deploy Enqueued`, `Online`). If the deployment failed, it also prints the error and a suggested fix.
- **Deployment Logs**: You can check the logs of your deployment with:
diff --git a/docs/edge/ko/concepts/cli.mdx b/docs/edge/ko/concepts/cli.mdx
index 7f2a62e99..ae10e987a 100644
--- a/docs/edge/ko/concepts/cli.mdx
+++ b/docs/edge/ko/concepts/cli.mdx
@@ -294,7 +294,7 @@ crewai org switch <organization_id>
crewai deploy status
```
- 이 명령은 가장 최근의 배포 시도에 대한 최신 배포 상태(예: `Building Images for Crew`, `Deploy Enqueued`, `Online`)를 가져옵니다.
+ 이 명령은 가장 최근의 배포 시도에 대한 최신 배포 상태(예: `Building Images for Crew`, `Deploy Enqueued`, `Online`)를 가져옵니다. 배포가 실패한 경우 오류와 권장 해결 방법도 함께 출력합니다.
- **배포 로그**: 배포 로그를 확인하려면 다음을 사용합니다:
diff --git a/docs/edge/pt-BR/concepts/cli.mdx b/docs/edge/pt-BR/concepts/cli.mdx
index 4fe206dc2..ef69d5d04 100644
--- a/docs/edge/pt-BR/concepts/cli.mdx
+++ b/docs/edge/pt-BR/concepts/cli.mdx
@@ -315,7 +315,7 @@ crewai org switch <organization_id>
crewai deploy status
```
- Isso retorna o status mais recente do último deployment iniciado (por exemplo, `Building Images for Crew`, `Deploy Enqueued`, `Online`).
+ Isso retorna o status mais recente do último deployment iniciado (por exemplo, `Building Images for Crew`, `Deploy Enqueued`, `Online`). Se o deployment falhou, também mostra o erro e uma sugestão de correção.
- **Logs do Deployment**: Você pode checar os logs do seu deployment com:
diff --git a/lib/cli/src/crewai_cli/deploy/main.py b/lib/cli/src/crewai_cli/deploy/main.py
index 06dbb45ca..5dfa66529 100644
--- a/lib/cli/src/crewai_cli/deploy/main.py
+++ b/lib/cli/src/crewai_cli/deploy/main.py
@@ -811,6 +811,14 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
"""
console.print(f"Name:\t {status_data['name']}")
console.print(f"Status:\t {status_data['status']}")
+ # AMP sets these only while the deployment is failed. They carry raw git
+ # and build output, so print them without Rich markup.
+ error_message = status_data.get("error_message")
+ if error_message:
+ console.print(f"Error:\t {error_message}", style="red", markup=False)
+ suggested_fix = status_data.get("error_suggested_fix")
+ if suggested_fix:
+ console.print(f"Fix:\t {suggested_fix}", markup=False)
def get_crew_logs(self, uuid: str | None, log_type: str = "deployment") -> None:
"""
@@ -852,11 +860,9 @@ class DeployCommand(BaseCommand, PlusAPIMixin):
self._standard_no_param_error_message()
return
+ crew = uuid or self.project_name
if response.status_code == 204:
- console.print(
- f"Crew '{self.project_name}' removed successfully.", style="green"
- )
+ console.print(f"Crew '{crew}' removed successfully.", style="green")
else:
- console.print(
- f"Failed to remove crew '{self.project_name}'", style="bold red"
- )
+ console.print(f"Failed to remove crew '{crew}'", style="bold red")
+ self._validate_response(response)
diff --git a/lib/cli/src/crewai_cli/deploy/validate.py b/lib/cli/src/crewai_cli/deploy/validate.py
index d13562918..a68d56beb 100644
--- a/lib/cli/src/crewai_cli/deploy/validate.py
+++ b/lib/cli/src/crewai_cli/deploy/validate.py
@@ -46,6 +46,7 @@ from crewai_core.project import (
read_toml,
)
from rich.console import Console
+from rich.markup import escape
from crewai_cli.utils import normalize_package_name
@@ -545,6 +546,13 @@ class DeployValidator:
return
lockfile = uv_lock if uv_lock.exists() else poetry_lock
+ uv_path = shutil.which("uv")
+ if lockfile is uv_lock and uv_path is not None:
+ self._check_uv_lock_current(uv_path)
+ return
+
+ # Without uv, file times are the only signal. They also flag edits that
+ # leave dependencies alone, which `uv lock --check` above does not.
try:
if lockfile.stat().st_mtime < pyproject.stat().st_mtime:
self._add(
@@ -561,6 +569,52 @@ class DeployValidator:
except OSError:
pass
+ def _check_uv_lock_current(self, uv_path: str) -> None:
+ # Offline so validate never contacts an index: a current lock is
+ # confirmed without one, and a change uv cannot resolve from the cache
+ # fails with a different message, reported below as unverified.
+ try:
+ proc = subprocess.run( # noqa: S603 - fixed command, trusted uv path
+ [uv_path, "lock", "--check"],
+ cwd=self.project_root,
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ env={**os.environ, "UV_OFFLINE": "1"},
+ )
+ except subprocess.TimeoutExpired:
+ reason = "`uv lock --check` timed out after 60s."
+ except OSError as exc:
+ reason = f"Could not run `uv lock --check`: {exc}"
+ else:
+ if proc.returncode == 0:
+ return
+ if "needs to be updated" in proc.stderr:
+ self._add(
+ Severity.WARNING,
+ "stale_lockfile",
+ "uv.lock is out of date with pyproject.toml",
+ detail=(
+ "Your lockfile does not reflect recent dependency changes. "
+ "The platform resolves from the lockfile, so deployed "
+ "dependencies may differ from local."
+ ),
+ hint="Run `uv lock` and commit the result.",
+ )
+ return
+ reason = (
+ proc.stderr.strip() or f"`uv lock --check` exited {proc.returncode}."
+ )
+
+ self._add(
+ Severity.WARNING,
+ "unverified_lockfile",
+ "Could not verify that uv.lock is up to date",
+ detail=reason,
+ hint="Run `uv lock` and commit the result if it changes uv.lock.",
+ )
+
def _check_package_dir(self) -> bool:
if self._package_name is None:
return False
@@ -1103,21 +1157,27 @@ def render_report(results: list[ValidationResult]) -> None:
errors = [r for r in results if r.severity is Severity.ERROR]
warnings = [r for r in results if r.severity is Severity.WARNING]
+ # Codes, TOML table names like `[project]`, extras like `crewai[tools]`, and raw
+ # subprocess output all contain brackets that Rich would read as markup.
for result in errors:
- console.print(f"[bold red]ERROR[/bold red] [{result.code}] {result.title}")
+ console.print(
+ f"[bold red]ERROR[/bold red] {escape(f'[{result.code}]')} "
+ f"{escape(result.title)}"
+ )
if result.detail:
- console.print(f" {result.detail}")
+ console.print(f" {escape(result.detail)}")
if result.hint:
- console.print(f" [dim]hint:[/dim] {result.hint}")
+ console.print(f" [dim]hint:[/dim] {escape(result.hint)}")
for result in warnings:
console.print(
- f"[bold yellow]WARNING[/bold yellow] [{result.code}] {result.title}"
+ f"[bold yellow]WARNING[/bold yellow] {escape(f'[{result.code}]')} "
+ f"{escape(result.title)}"
)
if result.detail:
- console.print(f" {result.detail}")
+ console.print(f" {escape(result.detail)}")
if result.hint:
- console.print(f" [dim]hint:[/dim] {result.hint}")
+ console.print(f" [dim]hint:[/dim] {escape(result.hint)}")
summary_parts: list[str] = []
if errors:
diff --git a/lib/cli/tests/deploy/test_deploy_main.py b/lib/cli/tests/deploy/test_deploy_main.py
index 9f777d579..c049f358c 100644
--- a/lib/cli/tests/deploy/test_deploy_main.py
+++ b/lib/cli/tests/deploy/test_deploy_main.py
@@ -1337,6 +1337,93 @@ class TestDeployCommand(unittest.TestCase):
"Crew 'test_project' removed successfully", fake_out.getvalue()
)
+ def test_remove_by_uuid_names_the_removed_deployment_not_the_local_project(self):
+ self.mock_client.delete_crew_by_uuid.return_value = httpx.Response(204)
+
+ with patch("sys.stdout", new=StringIO()) as fake_out:
+ self.deploy_command.remove_crew("other-uuid")
+
+ output = fake_out.getvalue()
+ self.assertIn("Crew 'other-uuid' removed successfully", output)
+ self.assertNotIn("test_project", output)
+
+ def test_failed_remove_by_uuid_shows_the_api_error(self):
+ self.mock_client.delete_crew_by_uuid.return_value = httpx.Response(
+ 403, json={"error": "You do not have permission to delete this crew"}
+ )
+
+ with patch("sys.stdout", new=StringIO()) as fake_out:
+ with self.assertRaises(SystemExit):
+ self.deploy_command.remove_crew("other-uuid")
+
+ output = fake_out.getvalue()
+ self.assertIn("Failed to remove crew 'other-uuid'", output)
+ self.assertIn("You do not have permission to delete this crew", output)
+ self.assertNotIn("test_project", output)
+
+ def test_failed_remove_by_name_shows_the_api_error(self):
+ self.mock_client.delete_crew_by_name.return_value = httpx.Response(
+ 404, json={"error": "Crew not found"}
+ )
+
+ with patch("sys.stdout", new=StringIO()) as fake_out:
+ with self.assertRaises(SystemExit):
+ self.deploy_command.remove_crew(None)
+
+ output = fake_out.getvalue()
+ self.assertIn("Failed to remove crew 'test_project'", output)
+ self.assertIn("Crew not found", output)
+
+ def test_status_of_a_failed_deployment_shows_amp_error_and_fix(self):
+ # The shape AMP's status endpoint returns for a failed git clone.
+ self.mock_client.crew_status_by_uuid.return_value = httpx.Response(
+ 200,
+ json={
+ "name": "lead_qualifier",
+ "status": "Provisioning Failed, try again.",
+ "state": "Failed",
+ "error_message": (
+ "Host key verification failed. [[email protected]:org/repo.git]"
+ ),
+ "error_category": "git_clone_failure",
+ "error_suggested_fix": "Use an HTTPS [origin] URL.",
+ },
+ )
+
+ with patch("sys.stdout", new=StringIO()) as fake_out:
+ self.deploy_command.get_crew_status("test-uuid")
+
+ output = fake_out.getvalue()
+ self.assertIn("Provisioning Failed, try again.", output)
+ # Printed verbatim: square brackets are not swallowed as Rich markup.
+ self.assertRegex(
+ output,
+ r"Error:\s+Host key verification failed\. \[git@github\.com:org/repo\.git\]",
+ )
+ self.assertRegex(output, r"Fix:\s+Use an HTTPS \[origin\] URL\.")
+
+ def test_status_of_a_healthy_deployment_prints_no_error_lines(self):
+ # AMP sends the error fields as null outside a failure.
+ self.mock_client.crew_status_by_uuid.return_value = httpx.Response(
+ 200,
+ json={
+ "name": "lead_qualifier",
+ "status": "Online",
+ "state": "Successful",
+ "error_message": None,
+ "error_category": None,
+ "error_suggested_fix": None,
+ },
+ )
+
+ with patch("sys.stdout", new=StringIO()) as fake_out:
+ self.deploy_command.get_crew_status("test-uuid")
+
+ output = fake_out.getvalue()
+ self.assertRegex(output, r"Status:\s+Online")
+ self.assertNotIn("Error:", output)
+ self.assertNotIn("Fix:", output)
+
@unittest.skipIf(sys.version_info < (3, 11), "Requires Python 3.11+")
def test_parse_toml_python_311_plus(self):
toml_content = """
diff --git a/lib/cli/tests/deploy/test_validate.py b/lib/cli/tests/deploy/test_validate.py
index b79d1e035..2957543c3 100644
--- a/lib/cli/tests/deploy/test_validate.py
+++ b/lib/cli/tests/deploy/test_validate.py
@@ -6,7 +6,10 @@ in the #crewai-deployment-failures Slack channel that motivated this work.
from __future__ import annotations
+import os
from pathlib import Path
+import shutil
+import subprocess
from textwrap import dedent
from typing import Iterable
from unittest.mock import patch
@@ -16,8 +19,10 @@ import pytest
from crewai_cli.deploy.validate import (
DeployValidator,
Severity,
+ ValidationResult,
_JSONProjectEnvironmentError,
normalize_package_name,
+ render_report,
)
@@ -299,20 +304,143 @@ def test_poetry_lock_is_accepted(tmp_path: Path) -> None:
assert "missing_lockfile" not in _codes(v)
-def test_stale_lockfile_warns(tmp_path: Path) -> None:
- _scaffold_standard_crew(tmp_path)
- lock = tmp_path / "uv.lock"
- pyproject = tmp_path / "pyproject.toml"
- old_time = pyproject.stat().st_mtime - 60
- import os
+_DEPENDENCY_FREE_PYPROJECT = dedent(
+ """
+ [project]
+ name = "my_crew"
+ version = "0.1.0"
+ description = "first"
+ requires-python = ">=3.10"
+ dependencies = []
+ """
+)
+
+needs_uv = pytest.mark.skipif(shutil.which("uv") is None, reason="needs uv")
+
+
+def _scaffold_locked_crew(root: Path) -> Path:
+ """A crew with a real uv.lock; uv resolves it offline (no dependencies)."""
+ _scaffold_standard_crew(
+ root, include_lockfile=False, pyproject=_DEPENDENCY_FREE_PYPROJECT
+ )
+ subprocess.run( # noqa: S603 - fixed command in a temp directory
+ ["uv", "lock"], # noqa: S607 - resolved from PATH like the validator
+ cwd=root,
+ capture_output=True,
+ check=True,
+ timeout=60,
+ env={**os.environ, "UV_OFFLINE": "1"},
+ )
+ return root / "pyproject.toml"
+
+
+def _make_older(path: Path, than: Path) -> None:
+ old_time = than.stat().st_mtime - 60
+ os.utime(path, (old_time, old_time))
+
+
+def _finding(validator: DeployValidator, code: str) -> ValidationResult:
+ return next(r for r in validator.results if r.code == code)
+
+
+@needs_uv
+def test_lockfile_is_current_when_only_project_metadata_changed(
+ tmp_path: Path,
+) -> None:
+ pyproject = _scaffold_locked_crew(tmp_path)
+ pyproject.write_text(pyproject.read_text().replace('"first"', '"second"'))
+ # `uv lock` leaves an unchanged lock alone, so its mtime stays older.
+ _make_older(tmp_path / "uv.lock", than=pyproject)
+
+ v = _run_without_import_check(tmp_path)
+
+ assert "stale_lockfile" not in _codes(v)
+ assert "unverified_lockfile" not in _codes(v)
+
+
+@needs_uv
+def test_lockfile_behind_pyproject_warns_stale(tmp_path: Path) -> None:
+ pyproject = _scaffold_locked_crew(tmp_path)
+ pyproject.write_text(pyproject.read_text().replace('"0.1.0"', '"0.2.0"'))
- os.utime(lock, (old_time, old_time))
v = _run_without_import_check(tmp_path)
- assert "stale_lockfile" in _codes(v)
+
+ finding = _finding(v, "stale_lockfile")
+ assert finding.severity is Severity.WARNING
+ assert finding.title == "uv.lock is out of date with pyproject.toml"
+ assert finding.hint == "Run `uv lock` and commit the result."
# Stale is a warning, so the run can still be ok (no errors).
assert v.ok
+def test_lockfile_check_that_cannot_resolve_offline_warns_unverified(
+ tmp_path: Path,
+) -> None:
+ _scaffold_standard_crew(tmp_path)
+ no_solution = (
+ " × No solution found when resolving dependencies:\n"
+ " hint: Packages were unavailable because the network was disabled."
+ )
+ with (
+ patch("crewai_cli.deploy.validate.shutil.which", return_value="/bin/uv"),
+ patch(
+ "crewai_cli.deploy.validate.subprocess.run",
+ return_value=subprocess.CompletedProcess(
+ ["/bin/uv", "lock", "--check"], 1, stdout="", stderr=no_solution
+ ),
+ ) as run,
+ ):
+ v = _run_without_import_check(tmp_path)
+
+ assert run.call_args.kwargs["env"]["UV_OFFLINE"] == "1"
+ assert "stale_lockfile" not in _codes(v)
+ finding = _finding(v, "unverified_lockfile")
+ assert finding.severity is Severity.WARNING
+ assert finding.title == "Could not verify that uv.lock is up to date"
+ assert "network was disabled" in finding.detail
+ assert v.ok
+
+
+def test_lockfile_check_timeout_warns_unverified(tmp_path: Path) -> None:
+ _scaffold_standard_crew(tmp_path)
+ with (
+ patch("crewai_cli.deploy.validate.shutil.which", return_value="/bin/uv"),
+ patch(
+ "crewai_cli.deploy.validate.subprocess.run",
+ side_effect=subprocess.TimeoutExpired(["uv", "lock", "--check"], 60),
+ ),
+ ):
+ v = _run_without_import_check(tmp_path)
+
+ finding = _finding(v, "unverified_lockfile")
+ assert finding.detail == "`uv lock --check` timed out after 60s."
+
+
+def test_stale_uv_lock_without_uv_falls_back_to_file_times(tmp_path: Path) -> None:
+ _scaffold_standard_crew(tmp_path)
+ _make_older(tmp_path / "uv.lock", than=tmp_path / "pyproject.toml")
+
+ with patch("crewai_cli.deploy.validate.shutil.which", return_value=None):
+ v = _run_without_import_check(tmp_path)
+
+ finding = _finding(v, "stale_lockfile")
+ assert finding.title == "uv.lock is older than pyproject.toml"
+ assert v.ok
+
+
+def test_stale_poetry_lock_uses_file_times_even_with_uv(tmp_path: Path) -> None:
+ _scaffold_standard_crew(tmp_path, include_lockfile=False)
+ (tmp_path / "poetry.lock").write_text("# poetry lockfile\n")
+ _make_older(tmp_path / "poetry.lock", than=tmp_path / "pyproject.toml")
+
+ with patch("crewai_cli.deploy.validate.shutil.which", return_value="/bin/uv"):
+ v = _run_without_import_check(tmp_path)
+
+ finding = _finding(v, "stale_lockfile")
+ assert finding.title == "poetry.lock is older than pyproject.toml"
+ assert "unverified_lockfile" not in _codes(v)
+
+
def test_missing_package_dir_errors(tmp_path: Path) -> None:
# pyproject says name=my_crew but we only create src/other_pkg/
(tmp_path / "pyproject.toml").write_text(_make_pyproject(name="my_crew"))
@@ -617,3 +745,23 @@ def test_is_json_crew_false_without_pyproject(tmp_path):
(tmp_path / "crew.jsonc").write_text("{}")
assert DeployValidator(project_root=tmp_path)._is_json_crew is False
+
+
[email protected]("severity", [Severity.ERROR, Severity.WARNING])
+def test_render_report_prints_bracketed_text_verbatim(severity, capsys):
+ render_report(
+ [
+ ValidationResult(
+ severity=severity,
+ code="stale_lockfile",
+ title="uv.lock is out of date with pyproject.toml",
+ detail="error: crewai[tools]==1.0 not found; stray [/red] tag",
+ hint="Add [tool.hatch.build.targets.wheel] under [project].",
+ )
+ ]
+ )
+
+ out = capsys.readouterr().out
+ assert "[stale_lockfile] uv.lock is out of date with pyproject.toml" in out
+ assert "error: crewai[tools]==1.0 not found; stray [/red] tag" in out
+ assert "hint: Add [tool.hatch.build.targets.wheel] under [project]." in out