Step 0.3: add the CLI entrypoint and base command tree

This commit is contained in:
Ilgiz Kalmetyev 2026-04-15 09:44:19 +05:00
parent e02e98ced7
commit df8306376a
4 changed files with 328 additions and 2 deletions

View File

@ -19,3 +19,5 @@ package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[project.scripts]
agent = "agent.cli:main"

View File

@ -1,2 +1,91 @@
"""Application bootstrap placeholders."""
"""Application bootstrap helpers."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping
from .settings import Settings, load_settings
@dataclass(slots=True, frozen=True)
class AgentApplication:
"""Loaded runtime state used by the CLI entrypoint."""
settings: Settings
@property
def config_path(self) -> Path:
return self.settings.config_path
def status(self) -> dict[str, Any]:
runtime = self.settings.runtime
config = self.settings.config
collectors = config.get("collectors", {})
tasks = config.get("tasks", {})
return {
"agent_env": runtime.agent_env,
"log_level": runtime.log_level,
"config_path": str(self.settings.config_path),
"env_file": str(runtime.env_file) if runtime.env_file else None,
"host_id": runtime.host_id,
"site_id": runtime.site_id,
"agent_name": self.settings.agent.get("name"),
"config_sections": len(config) if isinstance(config, dict) else 0,
"collector_count": _count_sections(collectors),
"task_count": _count_tasks(tasks),
}
def stats(self) -> dict[str, int]:
return {
"config_loaded_total": 1,
"events_received_total": 0,
"events_prefilter_dropped_total": 0,
"events_validation_failed_total": 0,
"events_normalized_total": 0,
"events_marked_total": 0,
"events_cached_total": 0,
"events_outbox_enqueued_total": 0,
"cache_overwrite_total": 0,
"derived_events_total": 0,
"commands_received_total": 0,
"commands_rejected_total": 0,
"commands_executed_total": 0,
"webhook_sent_total": 0,
"webhook_send_failed_total": 0,
}
def load_application(
*,
env_file: str | Path | None = None,
config_path: str | Path | None = None,
env: Mapping[str, str] | None = None,
load_env_file: bool = True,
) -> AgentApplication:
"""Load settings and return a ready-to-inspect application object."""
settings = load_settings(
env_file=env_file,
config_path=config_path,
env=env,
load_env_file=load_env_file,
)
return AgentApplication(settings=settings)
def _count_sections(value: Any) -> int:
if isinstance(value, dict):
return len(value)
if isinstance(value, list):
return len(value)
return 0
def _count_tasks(value: Any) -> int:
if isinstance(value, dict):
jobs = value.get("jobs")
return len(jobs) if isinstance(jobs, list) else 0
return 0

View File

@ -1,2 +1,132 @@
"""CLI entrypoint placeholders."""
"""CLI entrypoint and base command tree."""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from typing import Sequence
from .app import AgentApplication, load_application
PROGRAM_NAME = "agent"
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog=PROGRAM_NAME,
description="wf-agent2 command-line interface",
)
_add_bootstrap_options(parser)
subparsers = parser.add_subparsers(dest="command", required=True)
run_parser = subparsers.add_parser("run", help="bootstrap the agent runtime")
run_parser.set_defaults(handler=_handle_run)
config_parser = subparsers.add_parser("config", help="configuration operations")
config_subparsers = config_parser.add_subparsers(dest="config_command", required=True)
config_check_parser = config_subparsers.add_parser("check", help="validate configuration loading")
config_check_parser.set_defaults(handler=_handle_config_check)
status_parser = subparsers.add_parser("status", help="show bootstrap status")
status_parser.set_defaults(handler=_handle_status)
stats_parser = subparsers.add_parser("stats", help="show bootstrap statistics")
stats_parser.set_defaults(handler=_handle_stats)
return parser
def main(argv: Sequence[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(list(argv) if argv is not None else None)
handler = getattr(args, "handler", None)
if handler is None:
parser.print_help(sys.stderr)
return 2
return handler(args)
def _add_bootstrap_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--config", dest="config_path", type=Path, help="TOML config file path")
parser.add_argument("--env-file", dest="env_file", type=Path, help="dotenv file path")
parser.add_argument(
"--no-env-file",
action="store_true",
help="skip loading a dotenv file before reading config",
)
def _load_application_from_args(args: argparse.Namespace) -> AgentApplication:
return load_application(
env_file=getattr(args, "env_file", None),
config_path=getattr(args, "config_path", None),
load_env_file=not getattr(args, "no_env_file", False),
)
def _handle_run(args: argparse.Namespace) -> int:
try:
app = _load_application_from_args(args)
except Exception as exc: # pragma: no cover - exercised indirectly via config check
print(f"run: error: {exc}", file=sys.stderr)
return 1
status = app.status()
print("agent run: bootstrap ok")
print(f"config_path={status['config_path']}")
print(f"agent_env={status['agent_env']}")
print(f"log_level={status['log_level']}")
return 0
def _handle_config_check(args: argparse.Namespace) -> int:
try:
app = _load_application_from_args(args)
except Exception as exc:
print(f"config check: error: {exc}", file=sys.stderr)
return 1
status = app.status()
print("config: ok")
print(f"config_path={status['config_path']}")
if status["env_file"]:
print(f"env_file={status['env_file']}")
if status["agent_name"]:
print(f"agent_name={status['agent_name']}")
return 0
def _handle_status(args: argparse.Namespace) -> int:
try:
app = _load_application_from_args(args)
except Exception as exc:
print(f"status: error: {exc}", file=sys.stderr)
return 1
status = app.status()
print("agent status")
print(f"config_path={status['config_path']}")
print(f"agent_env={status['agent_env']}")
print(f"log_level={status['log_level']}")
print(f"collector_count={status['collector_count']}")
print(f"task_count={status['task_count']}")
return 0
def _handle_stats(args: argparse.Namespace) -> int:
try:
app = _load_application_from_args(args)
except Exception as exc:
print(f"stats: error: {exc}", file=sys.stderr)
return 1
print("agent stats")
for key, value in app.stats().items():
print(f"{key}={value}")
return 0
if __name__ == "__main__": # pragma: no cover - module entrypoint
raise SystemExit(main())

105
tests/unit/test_cli.py Normal file
View File

@ -0,0 +1,105 @@
from __future__ import annotations
import io
import tempfile
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from agent.cli import main
ROOT = Path(__file__).resolve().parents[2]
TEMP_ROOT = ROOT / ".tmp-tests"
TEMP_ROOT.mkdir(exist_ok=True)
def _run_cli(argv: list[str]) -> tuple[int, str, str]:
stdout = io.StringIO()
stderr = io.StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
code = main(argv)
return code, stdout.getvalue(), stderr.getvalue()
def test_config_check_reports_success() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
temp_dir = Path(tmp_dir)
config_file = temp_dir / "agent.toml"
config_file.write_text(
"""
[agent]
name = "wifi-event-agent"
""".strip(),
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "config", "check"])
assert code == 0
assert stderr == ""
assert "config: ok" in stdout
assert f"config_path={config_file}" in stdout
assert "agent_name=wifi-event-agent" in stdout
def test_status_reports_bootstrap_summary() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
temp_dir = Path(tmp_dir)
config_file = temp_dir / "agent.toml"
config_file.write_text(
"""
[agent]
name = "wifi-event-agent"
""".strip(),
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "status"])
assert code == 0
assert stderr == ""
assert "agent status" in stdout
assert f"config_path={config_file}" in stdout
assert "collector_count=0" in stdout
assert "task_count=0" in stdout
def test_stats_reports_zero_counters() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
temp_dir = Path(tmp_dir)
config_file = temp_dir / "agent.toml"
config_file.write_text(
"""
[agent]
name = "wifi-event-agent"
""".strip(),
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "stats"])
assert code == 0
assert stderr == ""
assert "agent stats" in stdout
assert "config_loaded_total=1" in stdout
assert "events_received_total=0" in stdout
def test_run_reports_bootstrap_ok() -> None:
with tempfile.TemporaryDirectory(dir=TEMP_ROOT) as tmp_dir:
temp_dir = Path(tmp_dir)
config_file = temp_dir / "agent.toml"
config_file.write_text(
"""
[agent]
name = "wifi-event-agent"
""".strip(),
encoding="utf-8",
)
code, stdout, stderr = _run_cli(["--config", str(config_file), "--no-env-file", "run"])
assert code == 0
assert stderr == ""
assert "agent run: bootstrap ok" in stdout
assert f"config_path={config_file}" in stdout