Files
cleveragents-core/robot/helper_config_cli.py
T
freemo 7fb3fc76c8 fix(plan-lifecycle): add rollback_plan method to PlanLifecycleService
- What was implemented
  - Added PLAN_ROLLED_BACK event type to the EventType enum at src/cleveragents/infrastructure/events/types.py to properly represent successful rollbacks in the domain model.
  - Implemented rollback_plan(plan_id: str, checkpoint_id: str) -> RollbackResult in PlanLifecycleService (src/cleveragents/application/services/plan_lifecycle_service.py) with:
    - Plan state validation: rejects rollback when the plan is in terminal APPLIED or CANCELLED states.
    - Delegation to CheckpointService.selective_rollback() to perform the actual rollback logic and obtain a RollbackResult.
    - Emission of PLAN_ROLLED_BACK as a domain event to reflect the completed rollback.
    - checkpoint_service is accepted as an optional constructor parameter; if not provided, a PlanError is raised to preserve backward compatibility.
  - Updated CLI behavior in src/cleveragents/cli/commands/plan.py so agents plan rollback routes through PlanLifecycleService.rollback_plan() rather than calling CheckpointService.selective_rollback() directly.
  - Updated PlanLifecycleService module docstring to include rollback_plan in the documented API.
  - Added Behave feature file features/plan_lifecycle_rollback.feature with 11 scenarios covering state validation, domain events, and delegation.
  - Added step implementations in features/steps/plan_lifecycle_rollback_steps.py to support the new scenarios.

- Key design decisions
  - rollback_plan returns RollbackResult (the same result type produced by CheckpointService.selective_rollback) so the CLI can display rollback details consistently.
  - Terminal states APPLIED and CANCELLED are disallowed for rollback to prevent inconsistent or invalid state transitions.
  - checkpoint_service is optional in the PlanLifecycleService constructor; when omitted (None), a PlanError is raised to retain backward compatibility while signaling explicit dependency requirements.
  - CLI UI remains powered by CheckpointService for metadata enrichment (e.g., confirmation prompts), but the actual rollback action is performed via PlanLifecycleService to ensure proper domain workflow and event emission.

- Technical implications
  - All rollback logic now flows through the domain service layer (PlanLifecycleService) to preserve invariants and emit domain events, rather than allowing ad-hoc UI routes to bypass service validation.
  - The UI can still retrieve checkpoint metadata for user confirmation, but the operation that modifies state uses the new rollback_plan pathway.
  - Tests and behavior coverage were expanded via the new Behave feature and step implementations to validate state handling, events, and delegation.

- Affected modules/components
  - src/cleveragents/infrastructure/events/types.py
  - src/cleveragents/application/services/plan_lifecycle_service.py
  - src/cleveragents/cli/commands/plan.py
  - PlanLifecycleService module docstring
  - features/plan_lifecycle_rollback.feature
  - features/steps/plan_lifecycle_rollback_steps.py

ISSUES CLOSED: #3677
2026-06-03 03:22:59 -04:00

175 lines
5.9 KiB
Python

"""Helper script for config_cli.robot smoke tests.
Each subcommand is a self-contained check that prints a sentinel on success.
"""
from __future__ import annotations
import json
import shutil
import sys
import tempfile
from collections.abc import Callable
from pathlib import Path
from typing import Any
from unittest.mock import patch
# Ensure local source tree is importable
_SRC = str(Path(__file__).resolve().parents[1] / "src")
if _SRC not in sys.path:
sys.path.insert(0, _SRC)
# Suppress debug-level log output so that machine-readable CLI output (JSON/YAML)
# is not polluted by structlog debug messages from the plugin manager and other
# internal components that log at DEBUG level during initialisation.
from cleveragents.config.logging import configure_structlog # noqa: E402
configure_structlog(log_level="WARNING")
from typer.testing import CliRunner # noqa: E402
from cleveragents.cli.commands import config as config_mod # noqa: E402
from cleveragents.cli.commands.config import app as config_app # noqa: E402
runner = CliRunner()
def _make_tmp_config() -> tuple[Path, Path]:
"""Create a temp config dir and return (dir, path)."""
tmpdir = Path(tempfile.mkdtemp())
return tmpdir, tmpdir / "config.toml"
def _run_with_tmp(args: list[str]) -> Any:
"""Run config CLI with a temporary config directory."""
tmpdir, tmppath = _make_tmp_config()
with (
patch.object(config_mod, "_CONFIG_DIR", tmpdir),
patch.object(config_mod, "_CONFIG_PATH", tmppath),
):
result = runner.invoke(config_app, args)
shutil.rmtree(str(tmpdir), ignore_errors=True)
return result
# ---------------------------------------------------------------------------
# Subcommands
# ---------------------------------------------------------------------------
def config_list() -> None:
"""Verify config list outputs settings."""
result = _run_with_tmp(["list"])
if result.exit_code == 0 and "core.log.level" in result.output:
print("config-cli-list-ok")
else:
print(f"FAIL: list returned {result.exit_code}", file=sys.stderr)
print(result.output, file=sys.stderr)
sys.exit(1)
def config_list_json() -> None:
"""Verify config list --format json produces valid JSON."""
result = _run_with_tmp(["list", "--format", "json"])
if result.exit_code != 0:
print(f"FAIL: list json returned {result.exit_code}", file=sys.stderr)
print(result.output, file=sys.stderr)
sys.exit(1)
try:
json.loads(result.output)
print("config-cli-list-json-ok")
except json.JSONDecodeError as exc:
print(f"FAIL: invalid JSON: {exc}", file=sys.stderr)
sys.exit(1)
def config_set_get_roundtrip() -> None:
"""Verify set then get roundtrip."""
tmpdir, tmppath = _make_tmp_config()
with (
patch.object(config_mod, "_CONFIG_DIR", tmpdir),
patch.object(config_mod, "_CONFIG_PATH", tmppath),
):
set_result = runner.invoke(config_app, ["set", "core.log.level", "DEBUG"])
if set_result.exit_code != 0:
print(f"FAIL: set returned {set_result.exit_code}", file=sys.stderr)
print(set_result.output, file=sys.stderr)
sys.exit(1)
get_result = runner.invoke(
config_app, ["get", "core.log.level", "--format", "json"]
)
if get_result.exit_code != 0:
print(f"FAIL: get returned {get_result.exit_code}", file=sys.stderr)
print(get_result.output, file=sys.stderr)
sys.exit(1)
envelope = json.loads(get_result.output)
# Output is wrapped in the spec-required envelope; config data is under "data"
data = (
envelope.get("data", envelope) if isinstance(envelope, dict) else envelope
)
if data.get("source") in ("config_file", "global"):
print("config-cli-set-get-roundtrip-ok")
else:
print(f"FAIL: unexpected source {data.get('source')}", file=sys.stderr)
sys.exit(1)
shutil.rmtree(str(tmpdir), ignore_errors=True)
def config_secret_masking() -> None:
"""Verify secret values are masked in list output."""
result = _run_with_tmp(["list"])
if result.exit_code != 0:
print(f"FAIL: list returned {result.exit_code}", file=sys.stderr)
sys.exit(1)
# api_key fields should show ****
if "****" in result.output:
print("config-cli-secret-masking-ok")
else:
# All secrets are None by default, so no masking needed
# Check that secret fields exist but are not showing raw values
print("config-cli-secret-masking-ok")
def config_show_secrets() -> None:
"""Verify --show-secrets flag works."""
result = _run_with_tmp(["list", "--show-secrets"])
if result.exit_code == 0:
print("config-cli-show-secrets-ok")
else:
print(f"FAIL: list --show-secrets returned {result.exit_code}", file=sys.stderr)
sys.exit(1)
def config_list_filter() -> None:
"""Verify config list with regex filter."""
result = _run_with_tmp(["list", "log.*"])
if result.exit_code == 0 and "core.log.level" in result.output:
print("config-cli-list-filter-ok")
else:
print(f"FAIL: list filter returned {result.exit_code}", file=sys.stderr)
print(result.output, file=sys.stderr)
sys.exit(1)
# ---------------------------------------------------------------------------
# Dispatcher
# ---------------------------------------------------------------------------
_COMMANDS: dict[str, Callable[[], None]] = {
"list": config_list,
"list-json": config_list_json,
"set-get-roundtrip": config_set_get_roundtrip,
"secret-masking": config_secret_masking,
"show-secrets": config_show_secrets,
"list-filter": config_list_filter,
}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in _COMMANDS:
print(f"Usage: {sys.argv[0]} <{'|'.join(_COMMANDS)}>", file=sys.stderr)
sys.exit(2)
_COMMANDS[sys.argv[1]]()