The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Port from superagent-ai/grok-cli: verify subsystem (run-recipe detection + environment manifest + hermes verify smoke runner)
Teknium47a35d63c0ee
diff --git a/agent/verify/__init__.py b/agent/verify/__init__.pynew file mode 100644index 00000000000..e9e1a89e636--- /dev/null+++ b/agent/verify/__init__.py@@ -0,0 +1,38 @@+"""Project verification subsystem.++Ported from superagent-ai/grok-cli's verify subsystem (scoped):+static run-recipe detection, a persisted environment manifest, and a+smoke-test runner used by the ``hermes verify`` CLI command.++Sources:+- https://github.com/superagent-ai/grok-cli/blob/main/src/verify/recipes.ts+- https://github.com/superagent-ai/grok-cli/blob/main/src/verify/environment.ts+"""++from agent.verify.environment import (+ load_manifest,+ load_or_detect,+ manifest_path,+ save_manifest,+)+from agent.verify.recipes import Recipe, detect_package_manager, detect_recipe+from agent.verify.runner import (+ PhaseResult,+ ReadinessResult,+ VerifyResult,+ run_verify,+)++__all__ = [+ "Recipe",+ "detect_recipe",+ "detect_package_manager",+ "load_manifest",+ "save_manifest",+ "load_or_detect",+ "manifest_path",+ "run_verify",+ "PhaseResult",+ "ReadinessResult",+ "VerifyResult",+]diff --git a/agent/verify/environment.py b/agent/verify/environment.pynew file mode 100644index 00000000000..dc902fb6c1a--- /dev/null+++ b/agent/verify/environment.py@@ -0,0 +1,75 @@+"""Environment manifest for project verification.++Ported from superagent-ai/grok-cli ``src/verify/environment.ts``.+The manifest lives at ``<project>/.hermes/environment.json`` and is the+user-editable source of truth: when present and valid it wins over fresh+static detection.+"""++from __future__ import annotations++import json+from datetime import datetime, timezone+from pathlib import Path++from agent.verify.recipes import Recipe, detect_recipe++MANIFEST_VERSION = 1+_MANIFEST_RELPATH = Path(".hermes") / "environment.json"+++def manifest_path(root: Path) -> Path:+ """Path of the verify manifest for the project at ``root``."""+ return Path(root) / _MANIFEST_RELPATH+++def load_manifest(root: Path) -> Recipe | None:+ """Load the saved recipe from the manifest, tolerating malformed files.++ Mirrors grok's ``loadVerifyEnvironment``: any read/parse/shape problem+ returns ``None`` rather than raising, so a corrupt manifest degrades to+ fresh detection instead of breaking ``hermes verify``.+ """+ path = manifest_path(root)+ try:+ raw = path.read_text(encoding="utf-8")+ except OSError:+ return None+ try:+ manifest = json.loads(raw)+ except (json.JSONDecodeError, ValueError):+ return None+ if not isinstance(manifest, dict):+ return None+ # Accept both the wrapped {version, recipe} shape and a bare recipe.+ recipe_raw = manifest.get("recipe", manifest)+ return Recipe.from_dict(recipe_raw)+++def save_manifest(root: Path, recipe: Recipe) -> Path:+ """Persist ``recipe`` as the project's verify manifest.++ Writes the versioned wrapper shape (grok's ``saveVerifyEnvironment``+ equivalent) and returns the manifest path.+ """+ path = manifest_path(root)+ path.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "version": MANIFEST_VERSION,+ "recipe": recipe.to_dict(),+ "updatedAt": datetime.now(timezone.utc).isoformat(),+ }+ path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")+ return path+++def load_or_detect(root: Path) -> tuple[Recipe | None, str]:+ """Return (recipe, source) where source is 'manifest' or 'detected'.++ A saved manifest wins over fresh detection, matching grok-cli's+ behavior where ``.grok/environment.json`` is the source of truth.+ """+ saved = load_manifest(root)+ if saved is not None:+ return saved, "manifest"+ return detect_recipe(root), "detected"diff --git a/agent/verify/recipes.py b/agent/verify/recipes.pynew file mode 100644index 00000000000..a500742073b--- /dev/null+++ b/agent/verify/recipes.py@@ -0,0 +1,462 @@+"""Static run-recipe detection for project verification.++Ported nearly 1:1 from superagent-ai/grok-cli ``src/verify/recipes.ts``.+Mirrors grok's detection order and command choices: Node (lockfile-based+package-manager choice + framework detection), Python (Django / FastAPI /+generic, with uv/poetry/pipenv awareness), Go, Rust, Java (Maven/Gradle),+Makefile fallback, plus a docker-compose recipe.+"""++from __future__ import annotations++import json+import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any+++@dataclass+class Recipe:+ """A runnable verification recipe for a project.++ Mirrors grok-cli's ``VerifyRecipe`` with a scoped field set:+ ``name`` is the human label (grok's ``appLabel``), ``kind`` the+ detector id (grok's ``appKind``), and command lists are shell strings+ executed in the project root.+ """++ name: str+ kind: str = "unknown"+ bootstrap: list[str] = field(default_factory=list)+ build: list[str] = field(default_factory=list)+ test: list[str] = field(default_factory=list)+ start: str | None = None+ port: int | None = None+ readiness_path: str = "/"+ evidence: list[str] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "name": self.name,+ "kind": self.kind,+ "bootstrap": list(self.bootstrap),+ "build": list(self.build),+ "test": list(self.test),+ "start": self.start,+ "port": self.port,+ "readinessPath": self.readiness_path,+ "evidence": list(self.evidence),+ }++ @classmethod+ def from_dict(cls, raw: Any) -> "Recipe | None":+ """Tolerant loader mirroring grok's ``normalizeVerifyRecipe``."""+ if not isinstance(raw, dict):+ return None+ name = raw.get("name") or raw.get("appLabel")+ if not isinstance(name, str) or not name.strip():+ return None+ kind = raw.get("kind") or raw.get("appKind") or "unknown"+ if not isinstance(kind, str) or not kind.strip():+ kind = "unknown"++ def as_strings(value: Any) -> list[str]:+ if isinstance(value, str) and value.strip():+ return [value.strip()]+ if not isinstance(value, list):+ return []+ return [v.strip() for v in value if isinstance(v, str) and v.strip()]++ start = raw.get("start") or raw.get("startCommand")+ if not (isinstance(start, str) and start.strip()):+ start = None+ else:+ start = start.strip()++ port_raw = raw.get("port") or raw.get("startPort")+ port: int | None = None+ if isinstance(port_raw, int) and 0 < port_raw < 65536:+ port = port_raw+ elif isinstance(port_raw, str) and port_raw.strip().isdigit():+ candidate = int(port_raw.strip())+ if 0 < candidate < 65536:+ port = candidate++ readiness = raw.get("readinessPath") or raw.get("readiness_path") or "/"+ if not (isinstance(readiness, str) and readiness.startswith("/")):+ readiness = "/"++ return cls(+ name=name.strip(),+ kind=kind.strip(),+ bootstrap=as_strings(raw.get("bootstrap") or raw.get("installCommands")),+ build=as_strings(raw.get("build") or raw.get("buildCommands")),+ test=as_strings(raw.get("test") or raw.get("testCommands")),+ start=start,+ port=port,+ readiness_path=readiness,+ evidence=as_strings(raw.get("evidence")),+ )+++# ---------------------------------------------------------------------------+# helpers+# ---------------------------------------------------------------------------++def _read_text(root: Path, name: str) -> str | None:+ try:+ return (root / name).read_text(encoding="utf-8")+ except OSError:+ return None+++def _read_package_json(root: Path) -> dict[str, Any] | None:+ raw = _read_text(root, "package.json")+ if raw is None:+ return None+ try:+ parsed = json.loads(raw)+ except (json.JSONDecodeError, ValueError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def detect_package_manager(root: Path) -> str | None:+ """Lockfile-based package-manager detection (grok's detectPackageManager)."""+ candidates = [+ ("pnpm-lock.yaml", "pnpm"),+ ("bun.lock", "bun"),+ ("bun.lockb", "bun"),+ ("yarn.lock", "yarn"),+ ("package-lock.json", "npm"),+ ("uv.lock", "uv"),+ ("poetry.lock", "poetry"),+ ("Pipfile.lock", "pipenv"),+ ]+ for filename, manager in candidates:+ if (root / filename).exists():+ return manager+ return None+++def _infer_port_from_command(command: str | None) -> int | None:+ """Port inference from a start command (grok's inferPortFromCommand)."""+ if not command:+ return None+ flag = re.search(r"(?:--port|-p)\s+(\d{2,5})", command)+ if flag:+ return int(flag.group(1))+ env = re.search(r"\bPORT=(\d{2,5})\b", command)+ if env:+ return int(env.group(1))+ return None+++def _dedupe(values: list[str | None]) -> list[str]:+ seen: dict[str, None] = {}+ for value in values:+ if value and value.strip():+ seen.setdefault(value.strip(), None)+ return list(seen)+++# ---------------------------------------------------------------------------+# Node+# ---------------------------------------------------------------------------++def _script_runner(package_manager: str | None, entry: str) -> str:+ if package_manager == "pnpm":+ return f"pnpm {entry}"+ if package_manager == "bun":+ return f"bun run {entry}"+ if package_manager == "yarn":+ return f"yarn {entry}"+ return f"npm run {entry}"+++def _detect_node_recipe(root: Path, pkg: dict[str, Any]) -> Recipe:+ raw_scripts = pkg.get("scripts")+ scripts: dict[str, str] = raw_scripts if isinstance(raw_scripts, dict) else {}+ deps: dict[str, Any] = {}+ for key in ("dependencies", "devDependencies"):+ section = pkg.get(key)+ if isinstance(section, dict):+ deps.update(section)++ package_manager = detect_package_manager(root)++ kind, label, default_port = "node", "Node.js app", None+ if "next" in deps:+ kind, label, default_port = "nextjs", "Next.js", 3000+ elif "@sveltejs/kit" in deps:+ kind, label, default_port = "sveltekit", "SvelteKit", 5173+ elif "astro" in deps:+ kind, label, default_port = "astro", "Astro", 4321+ elif "@remix-run/dev" in deps or "@remix-run/react" in deps:+ kind, label, default_port = "remix", "Remix", 3000+ elif "react-scripts" in deps:+ kind, label, default_port = "cra", "Create React App", 3000+ elif "vite" in deps:+ kind, label, default_port = "vite", "Vite", 5173++ install = {+ "pnpm": "pnpm install",+ "bun": "bun install",+ "yarn": "yarn install",+ "npm": "npm install",+ }.get(package_manager or "npm", "npm install")++ start_script = "dev" if scripts.get("dev") else ("start" if scripts.get("start") else None)+ start_body = scripts.get(start_script) if start_script else None+ start = _script_runner(package_manager, start_script) if start_script else None+ port = _infer_port_from_command(start_body) or default_port if start else None++ build = _dedupe(+ [_script_runner(package_manager, s) for s in ("build", "typecheck") if scripts.get(s)]+ )+ test = _dedupe(+ [_script_runner(package_manager, s) for s in ("test", "check", "lint") if scripts.get(s)]+ )++ return Recipe(+ name=label,+ kind=kind,+ bootstrap=[install],+ build=build,+ test=test,+ start=start,+ port=port,+ evidence=_dedupe(+ [+ "Detected package.json",+ f"Package manager: {package_manager}" if package_manager else None,+ f"Scripts: {', '.join(scripts) or '(none)'}",+ ]+ ),+ )+++# ---------------------------------------------------------------------------+# Python+# ---------------------------------------------------------------------------++def _detect_python_recipe(root: Path) -> Recipe | None:+ pyproject = _read_text(root, "pyproject.toml")+ requirements = _read_text(root, "requirements.txt")+ manage_py = (root / "manage.py").exists()+ if not (pyproject or requirements or manage_py or (root / "setup.py").exists()):+ return None++ lower = f"{pyproject or ''}\n{requirements or ''}".lower()+ package_manager = detect_package_manager(root)+ is_django = manage_py or "django" in lower+ is_fastapi = "fastapi" in lower or "uvicorn" in lower+ is_flask = "flask" in lower++ install = "pip install -r requirements.txt"+ if package_manager == "uv":+ install = "uv sync"+ elif package_manager == "poetry":+ install = "poetry install"+ elif package_manager == "pipenv":+ install = "pipenv install"+ elif pyproject and not requirements:+ install = "pip install -e ."++ has_tests = (root / "tests").exists()++ if is_django:+ return Recipe(+ name="Django app",+ kind="django",+ bootstrap=[install],+ test=["python manage.py test"],+ start="python manage.py runserver 0.0.0.0:8000",+ port=8000,+ evidence=_dedupe(+ [+ "Detected manage.py" if manage_py else "Detected Django dependency",+ "Detected pyproject.toml" if pyproject else None,+ ]+ ),+ )++ if is_fastapi:+ if (root / "main.py").exists():+ app_module = "main:app"+ elif (root / "app.py").exists():+ app_module = "app:app"+ else:+ app_module = "main:app"+ return Recipe(+ name="FastAPI app",+ kind="fastapi",+ bootstrap=[install],+ test=["pytest"] if has_tests else [],+ start=f"uvicorn {app_module} --host 0.0.0.0 --port 8000",+ port=8000,+ evidence=["Detected Python project", "Detected FastAPI/Uvicorn dependency"],+ )++ if is_flask:+ if (root / "app.py").exists():+ app_module = "app.py"+ elif (root / "main.py").exists():+ app_module = "main.py"+ else:+ app_module = "app.py"+ return Recipe(+ name="Flask app",+ kind="flask",+ bootstrap=[install],+ test=["pytest"] if has_tests else [],+ start=f"flask --app {app_module} run --host 0.0.0.0 --port 5000",+ port=5000,+ evidence=["Detected Python project", "Detected Flask dependency"],+ )++ return Recipe(+ name="Python project",+ kind="python",+ bootstrap=[install],+ test=["pytest"] if has_tests else ["python -m unittest discover"],+ evidence=["Detected Python project"],+ )+++# ---------------------------------------------------------------------------+# Go / Rust / Java / Make / docker-compose+# ---------------------------------------------------------------------------++def _detect_go_recipe(root: Path) -> Recipe | None:+ if not (root / "go.mod").exists():+ return None+ return Recipe(+ name="Go project",+ kind="go",+ build=["go build ./..."],+ test=["go test ./..."],+ start="go run ." if (root / "main.go").exists() else None,+ evidence=["Detected go.mod"],+ )+++def _detect_rust_recipe(root: Path) -> Recipe | None:+ if not (root / "Cargo.toml").exists():+ return None+ return Recipe(+ name="Rust project",+ kind="rust",+ build=["cargo build"],+ test=["cargo test"],+ start="cargo run" if (root / "src" / "main.rs").exists() else None,+ evidence=["Detected Cargo.toml"],+ )+++def _detect_java_recipe(root: Path) -> Recipe | None:+ if (root / "pom.xml").exists():+ return Recipe(+ name="Maven project",+ kind="maven",+ build=["mvn package"],+ test=["mvn test"],+ evidence=["Detected pom.xml"],+ )+ if (root / "build.gradle").exists() or (root / "build.gradle.kts").exists():+ gradle = "./gradlew" if (root / "gradlew").exists() else "gradle"+ return Recipe(+ name="Gradle project",+ kind="gradle",+ build=[f"{gradle} build"],+ test=[f"{gradle} test"],+ evidence=["Detected Gradle build file"],+ )+ return None+++_MAKE_TARGET_RE = re.compile(r"^([A-Za-z0-9_.-]+):(?:\s|$)")+++def _parse_make_targets(raw: str) -> list[str]:+ targets = []+ for line in raw.splitlines():+ match = _MAKE_TARGET_RE.match(line)+ if match:+ targets.append(match.group(1))+ return targets+++def _detect_make_recipe(root: Path) -> Recipe | None:+ makefile = _read_text(root, "Makefile")+ if makefile is None:+ return None+ targets = _parse_make_targets(makefile)++ def pick(names: list[str]) -> str | None:+ for name in names:+ if name in targets:+ return name+ return None++ install = pick(["install", "setup", "bootstrap"])+ build = pick(["build", "compile"])+ test = pick(["test", "check"])+ run = pick(["run", "start", "serve", "dev"])++ return Recipe(+ name="Makefile-driven project",+ kind="make",+ bootstrap=[f"make {install}"] if install else [],+ build=[f"make {build}"] if build else [],+ test=[f"make {test}"] if test else [],+ start=f"make {run}" if run else None,+ evidence=["Detected Makefile", f"Targets: {', '.join(targets) or '(none)'}"],+ )+++_COMPOSE_FILES = (+ "docker-compose.yml",+ "docker-compose.yaml",+ "compose.yml",+ "compose.yaml",+)+++def _detect_compose_recipe(root: Path) -> Recipe | None:+ compose_file = next((f for f in _COMPOSE_FILES if (root / f).exists()), None)+ if compose_file is None:+ return None+ return Recipe(+ name="docker-compose project",+ kind="compose",+ build=["docker compose build"],+ start="docker compose up",+ evidence=[f"Detected {compose_file}"],+ )+++# ---------------------------------------------------------------------------+# entry point+# ---------------------------------------------------------------------------++def detect_recipe(root: Path) -> Recipe | None:+ """Detect a verification recipe for the project at ``root``.++ Detection order mirrors grok-cli's ``inferFallbackRecipe``: package.json+ wins, then Python, Go, Rust, Java, then Makefile / docker-compose+ fallbacks. Returns ``None`` when nothing recognizable is found.+ """+ root = Path(root)+ pkg = _read_package_json(root)+ if pkg is not None:+ return _detect_node_recipe(root, pkg)+ return (+ _detect_python_recipe(root)+ or _detect_go_recipe(root)+ or _detect_rust_recipe(root)+ or _detect_java_recipe(root)+ or _detect_make_recipe(root)+ or _detect_compose_recipe(root)+ )diff --git a/agent/verify/runner.py b/agent/verify/runner.pynew file mode 100644index 00000000000..5eba4a1eeed--- /dev/null+++ b/agent/verify/runner.py@@ -0,0 +1,270 @@+"""Verification runner: execute a Recipe's phases and smoke-test the app.++Scoped port of the execution flow grok-cli's verify sub-agent performs+(install/bootstrap -> build -> test -> start in background -> curl-style+readiness loop -> teardown), reimplemented as a plain subprocess runner.++Commands come from the project's own recipe (its package.json scripts,+Makefile targets, etc.) and are executed with ``shell=True`` on purpose:+this is a developer tool running the project's own build commands in the+project's own checkout — the same trust level as the terminal tool.+"""++from __future__ import annotations++import os+import signal+import subprocess+import time+import urllib.error+import urllib.request+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable++from agent.verify.recipes import Recipe++DEFAULT_PHASE_TIMEOUT = 600.0+DEFAULT_READY_TIMEOUT = 60.0+_TAIL_CHARS = 2000+PHASE_ORDER = ("bootstrap", "build", "test")+++@dataclass+class PhaseResult:+ phase: str+ command: str+ exit_code: int | None+ duration: float+ output_tail: str+ timed_out: bool = False++ @property+ def ok(self) -> bool:+ return self.exit_code == 0 and not self.timed_out++ def to_dict(self) -> dict[str, Any]:+ return {+ "phase": self.phase,+ "command": self.command,+ "exitCode": self.exit_code,+ "duration": round(self.duration, 3),+ "ok": self.ok,+ "timedOut": self.timed_out,+ "outputTail": self.output_tail,+ }+++@dataclass+class ReadinessResult:+ url: str+ ready: bool+ status_code: int | None+ duration: float+ error: str | None = None+ output_tail: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "url": self.url,+ "ready": self.ready,+ "statusCode": self.status_code,+ "duration": round(self.duration, 3),+ "error": self.error,+ "outputTail": self.output_tail,+ }+++@dataclass+class VerifyResult:+ recipe_name: str+ phases: list[PhaseResult] = field(default_factory=list)+ readiness: ReadinessResult | None = None++ @property+ def ok(self) -> bool:+ phases_ok = all(p.ok for p in self.phases)+ readiness_ok = self.readiness.ready if self.readiness is not None else True+ return phases_ok and readiness_ok++ def to_dict(self) -> dict[str, Any]:+ return {+ "recipe": self.recipe_name,+ "ok": self.ok,+ "phases": [p.to_dict() for p in self.phases],+ "readiness": self.readiness.to_dict() if self.readiness else None,+ }+++def _tail(text: str, limit: int = _TAIL_CHARS) -> str:+ return text[-limit:] if len(text) > limit else text+++def _run_phase_command(+ phase: str,+ command: str,+ root: Path,+ timeout: float,+ on_output: Callable[[str], None] | None = None,+) -> PhaseResult:+ started = time.monotonic()+ try:+ proc = subprocess.run(+ command,+ shell=True, # project-authored commands; see module docstring+ cwd=str(root),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=timeout,+ text=True,+ errors="replace",+ )+ output = proc.stdout or ""+ exit_code: int | None = proc.returncode+ timed_out = False+ except subprocess.TimeoutExpired as exc:+ raw = exc.output+ if isinstance(raw, bytes):+ output = raw.decode("utf-8", errors="replace")+ else:+ output = raw or ""+ exit_code = None+ timed_out = True+ duration = time.monotonic() - started+ if on_output and output:+ on_output(output)+ return PhaseResult(+ phase=phase,+ command=command,+ exit_code=exit_code,+ duration=duration,+ output_tail=_tail(output),+ timed_out=timed_out,+ )+++def _poll_readiness(url: str, timeout: float, interval: float = 1.0) -> tuple[bool, int | None, str | None]:+ deadline = time.monotonic() + timeout+ last_error: str | None = None+ while time.monotonic() < deadline:+ try:+ with urllib.request.urlopen(url, timeout=5) as resp:+ return True, resp.status, None+ except urllib.error.HTTPError as exc:+ # The server answered — it is up, even if it returned 4xx/5xx.+ return True, exc.code, None+ except (urllib.error.URLError, OSError, TimeoutError) as exc:+ last_error = str(exc)+ time.sleep(interval)+ return False, None, last_error+++def _terminate_process_group(proc: subprocess.Popen) -> None:+ """Terminate the started app and its whole process group cleanly."""+ if proc.poll() is not None:+ return+ try:+ pgid = os.getpgid(proc.pid)+ except (ProcessLookupError, PermissionError):+ pgid = None+ try:+ if pgid is not None:+ os.killpg(pgid, signal.SIGTERM)+ else:+ proc.terminate()+ except (ProcessLookupError, PermissionError):+ return+ try:+ proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ try:+ if pgid is not None:+ os.killpg(pgid, signal.SIGKILL)+ else:+ proc.kill()+ except (ProcessLookupError, PermissionError):+ pass+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ pass+++def _run_start_phase(+ recipe: Recipe,+ root: Path,+ ready_timeout: float,+ port_override: int | None = None,+) -> ReadinessResult:+ assert recipe.start is not None+ port = port_override or recipe.port or 8000+ url = f"http://127.0.0.1:{port}{recipe.readiness_path}"+ started = time.monotonic()+ proc = subprocess.Popen(+ recipe.start,+ shell=True, # project-authored command; see module docstring+ cwd=str(root),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ start_new_session=True, # own process group for clean teardown+ text=True,+ errors="replace",+ )+ output = ""+ try:+ ready, status, error = _poll_readiness(url, ready_timeout)+ finally:+ _terminate_process_group(proc)+ try:+ if proc.stdout is not None:+ output = proc.stdout.read() or ""+ except (OSError, ValueError):+ output = ""+ return ReadinessResult(+ url=url,+ ready=ready,+ status_code=status,+ duration=time.monotonic() - started,+ error=error,+ output_tail=_tail(output),+ )+++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,+ skip_start: bool = False,+ port_override: int | None = None,+ stop_on_failure: bool = True,+ on_output: Callable[[str], None] | None = None,+) -> VerifyResult:+ """Run a verify pass for ``recipe`` at project ``root``.++ Executes the selected command phases sequentially, then (unless+ ``skip_start`` or a phase failed) launches ``recipe.start`` in the+ background, polls the readiness URL, and tears the process group down.+ """+ root = Path(root)+ selected = tuple(phases) if phases else PHASE_ORDER + ("start",)+ result = VerifyResult(recipe_name=recipe.name)++ failed = False+ for phase in PHASE_ORDER:+ if phase not in selected:+ continue+ for command in getattr(recipe, phase):+ phase_result = _run_phase_command(phase, command, root, phase_timeout, on_output)+ result.phases.append(phase_result)+ if not phase_result.ok:+ failed = True+ if stop_on_failure:+ return result++ if skip_start or "start" not in selected or failed or not recipe.start:+ return result++ result.readiness = _run_start_phase(recipe, root, ready_timeout, port_override)+ return resultdiff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex d71a4f2216c..a6237bbd512 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -455,6 +455,7 @@ from hermes_cli.subcommands.pause import build_pause_parserfrom hermes_cli.subcommands.webhook import build_webhook_parserfrom hermes_cli.subcommands.hooks import build_hooks_parserfrom hermes_cli.subcommands.doctor import build_doctor_parser+from hermes_cli.subcommands.verify import build_verify_parserfrom hermes_cli.subcommands.security import build_security_parserfrom hermes_cli.subcommands.approvals import build_approvals_parserfrom hermes_cli.subcommands.dump import build_dump_parser@@ -4850,6 +4851,13 @@ def cmd_doctor(args):run_doctor(args)+def cmd_verify(args):+ """Detect a project's run recipe and smoke-test it."""+ from hermes_cli.verify_cmd import run_verify_command++ sys.exit(run_verify_command(args))++def cmd_security(args):"""Dispatch `hermes security <subcmd>`."""sub = getattr(args, "security_command", None)@@ -10617,6 +10625,7 @@ _BUILTIN_SUBCOMMANDS = frozenset("send", "sessions", "setup","skin", "skills", "slack", "status", "sync", "tools", "uninstall", "update","version", "webhook", "whatsapp", "whatsapp-cloud", "chat", "secrets", "security",+ "verify",# Help-ish invocations — plugin commands not being listed in# top-level --help is an acceptable trade-off for skipping an# expensive eager import of every bundled plugin module.@@ -11532,6 +11541,11 @@ def main():# =========================================================================build_doctor_parser(subparsers, cmd_doctor=cmd_doctor)+ # =========================================================================+ # verify command (parser built in hermes_cli/subcommands/verify.py)+ # =========================================================================+ build_verify_parser(subparsers, cmd_verify=cmd_verify)+# =========================================================================# security command — on-demand supply-chain audit# =========================================================================diff --git a/hermes_cli/subcommands/verify.py b/hermes_cli/subcommands/verify.pynew file mode 100644index 00000000000..9f99b6593d5--- /dev/null+++ b/hermes_cli/subcommands/verify.py@@ -0,0 +1,80 @@+"""``hermes verify`` subcommand parser.++Follows the pattern of ``hermes_cli/subcommands/doctor.py``: parser built+here, handler injected to avoid importing ``main``.+"""++from __future__ import annotations++from typing import Callable++# Keep in sync with agent/verify/runner.py defaults; not imported here to+# avoid paying an extra module import on every `hermes` invocation.+DEFAULT_PHASE_TIMEOUT = 600.0+DEFAULT_READY_TIMEOUT = 60.0+++def build_verify_parser(subparsers, *, cmd_verify: Callable) -> None:+ """Attach the ``verify`` subcommand to ``subparsers``."""+ verify_parser = subparsers.add_parser(+ "verify",+ help="Detect a project's run recipe and smoke-test it",+ description=(+ "Detect how the current project is built, tested, and started "+ "(or load the saved manifest at .hermes/environment.json), then "+ "run a verification pass: bootstrap -> build -> test -> start in "+ "background -> poll readiness -> teardown."+ ),+ )+ verify_parser.add_argument(+ "path",+ nargs="?",+ default=None,+ help="Project root to verify (default: current directory)",+ )+ verify_parser.add_argument(+ "--detect-only",+ action="store_true",+ help="Only detect and print the recipe as JSON; run nothing",+ )+ verify_parser.add_argument(+ "--save",+ action="store_true",+ help="Save the recipe as .hermes/environment.json in the project",+ )+ verify_parser.add_argument(+ "--skip-start",+ action="store_true",+ help="Run command phases but skip starting the app / readiness poll",+ )+ verify_parser.add_argument(+ "--phase",+ action="append",+ choices=["bootstrap", "build", "test", "start"],+ default=None,+ help="Run only the given phase(s); repeatable",+ )+ verify_parser.add_argument(+ "--port",+ type=int,+ default=None,+ help="Override the port used for the readiness poll",+ )+ verify_parser.add_argument(+ "--timeout",+ type=float,+ default=DEFAULT_PHASE_TIMEOUT,+ help=f"Per-phase timeout in seconds (default: {DEFAULT_PHASE_TIMEOUT:.0f})",+ )+ verify_parser.add_argument(+ "--ready-timeout",+ type=float,+ default=DEFAULT_READY_TIMEOUT,+ help=f"Readiness poll timeout in seconds (default: {DEFAULT_READY_TIMEOUT:.0f})",+ )+ verify_parser.add_argument(+ "--json",+ action="store_true",+ help="Emit a machine-readable JSON result",+ )+ verify_parser.set_defaults(func=cmd_verify)diff --git a/hermes_cli/verify_cmd.py b/hermes_cli/verify_cmd.pynew file mode 100644index 00000000000..612e1a01054--- /dev/null+++ b/hermes_cli/verify_cmd.py@@ -0,0 +1,105 @@+"""``hermes verify`` — detect a project's run recipe and smoke-test it.++Scoped port of superagent-ai/grok-cli's verify subsystem entrypoint.+Statically detects the project kind (or loads the saved manifest at+``.hermes/environment.json``), then runs bootstrap/build/test phases and an+optional background start + readiness poll, printing an evidence summary.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path+++def run_verify_command(args) -> int:+ from agent.verify import (+ load_or_detect,+ manifest_path,+ run_verify,+ save_manifest,+ )++ root = Path(getattr(args, "path", None) or ".").resolve()+ if not root.is_dir():+ print(f"error: not a directory: {root}", file=sys.stderr)+ return 2++ recipe, source = load_or_detect(root)+ if recipe is None:+ message = (+ f"No recognizable project found at {root}.\n"+ f"Create {manifest_path(root)} to define a recipe manually."+ )+ if args.json:+ print(json.dumps({"ok": False, "error": "no-recipe", "root": str(root)}))+ else:+ print(message, file=sys.stderr)+ return 1++ if args.port:+ recipe.port = args.port++ if args.save:+ path = save_manifest(root, recipe)+ if not args.json:+ print(f"Saved manifest: {path}")++ if args.detect_only:+ payload = {"source": source, "recipe": recipe.to_dict()}+ print(json.dumps(payload, indent=None if args.json else 2))+ return 0++ phases = None+ if args.phase:+ phases = tuple(args.phase)++ result = run_verify(+ root,+ recipe,+ phases=phases,+ phase_timeout=args.timeout,+ ready_timeout=args.ready_timeout,+ skip_start=args.skip_start,+ port_override=args.port,+ )++ if args.json:+ payload = result.to_dict()+ payload["source"] = source+ print(json.dumps(payload))+ return 0 if result.ok else 1++ _print_human_report(recipe, source, result)+ return 0 if result.ok else 1+++def _print_human_report(recipe, source, result) -> None:+ print(f"Recipe: {recipe.name} ({recipe.kind}) — source: {source}")+ print()+ if result.phases:+ width = max(len(p.phase) for p in result.phases)+ for p in result.phases:+ status = "PASS" if p.ok else ("TIMEOUT" if p.timed_out else "FAIL")+ print(f" {p.phase.ljust(width)} {status:<7} {p.duration:6.1f}s {p.command}")+ else:+ print(" (no phases executed)")++ if result.readiness is not None:+ r = result.readiness+ status = f"ready (HTTP {r.status_code})" if r.ready else f"not ready ({r.error or 'timeout'})"+ print(f" {'start'.ljust(max(5, max((len(p.phase) for p in result.phases), default=5)))} "+ f"{'PASS' if r.ready else 'FAIL':<7} {r.duration:6.1f}s {recipe.start}")+ print()+ print(f"Readiness: {r.url} -> {status}")++ failed = [p for p in result.phases if not p.ok]+ print()+ print(f"Result: {'OK' if result.ok else 'FAILED'}")+ for p in failed:+ print(f"\n--- output tail: {p.phase} ({p.command}) ---")+ print(p.output_tail.rstrip())+ if result.readiness is not None and not result.readiness.ready and result.readiness.output_tail:+ print("\n--- output tail: start ---")+ print(result.readiness.output_tail.rstrip())diff --git a/tests/verify/test_environment_and_runner.py b/tests/verify/test_environment_and_runner.pynew file mode 100644index 00000000000..4c1d8885623--- /dev/null+++ b/tests/verify/test_environment_and_runner.py@@ -0,0 +1,189 @@+"""Tests for the verify environment manifest and the smoke runner."""++import http.server+import json+import threading+import time++from agent.verify.environment import (+ load_manifest,+ load_or_detect,+ manifest_path,+ save_manifest,+)+from agent.verify.recipes import Recipe+from agent.verify.runner import run_verify+++class TestManifest:+ def test_roundtrip(self, tmp_path):+ recipe = Recipe(+ name="Next.js",+ kind="nextjs",+ bootstrap=["npm install"],+ build=["npm run build"],+ test=["npm test"],+ start="npm run dev",+ port=3000,+ readiness_path="/health",+ )+ path = save_manifest(tmp_path, recipe)+ assert path == manifest_path(tmp_path)+ payload = json.loads(path.read_text())+ assert payload["version"] == 1+ assert "updatedAt" in payload+ assert load_manifest(tmp_path) == recipe++ def test_missing_file(self, tmp_path):+ assert load_manifest(tmp_path) is None++ def test_malformed_json_tolerated(self, tmp_path):+ path = manifest_path(tmp_path)+ path.parent.mkdir(parents=True)+ path.write_text("{oops", encoding="utf-8")+ assert load_manifest(tmp_path) is None++ def test_non_dict_tolerated(self, tmp_path):+ path = manifest_path(tmp_path)+ path.parent.mkdir(parents=True)+ path.write_text("[1, 2, 3]", encoding="utf-8")+ assert load_manifest(tmp_path) is None++ def test_bare_recipe_shape_accepted(self, tmp_path):+ path = manifest_path(tmp_path)+ path.parent.mkdir(parents=True)+ path.write_text(json.dumps({"name": "Custom", "test": ["true"]}), encoding="utf-8")+ recipe = load_manifest(tmp_path)+ assert recipe.name == "Custom"+ assert recipe.test == ["true"]++ def test_manifest_wins_over_detection(self, tmp_path):+ (tmp_path / "go.mod").write_text("module x\n", encoding="utf-8")+ save_manifest(tmp_path, Recipe(name="Custom", kind="custom", test=["true"]))+ recipe, source = load_or_detect(tmp_path)+ assert source == "manifest"+ assert recipe.name == "Custom"++ def test_detection_fallback(self, tmp_path):+ (tmp_path / "go.mod").write_text("module x\n", encoding="utf-8")+ recipe, source = load_or_detect(tmp_path)+ assert source == "detected"+ assert recipe.kind == "go"+++class TestRunner:+ def test_all_phases_pass(self, tmp_path):+ recipe = Recipe(name="x", bootstrap=["true"], build=["true"], test=["true"])+ result = run_verify(tmp_path, recipe, skip_start=True)+ assert result.ok+ assert [p.phase for p in result.phases] == ["bootstrap", "build", "test"]+ assert all(p.exit_code == 0 for p in result.phases)+ assert all(p.duration >= 0 for p in result.phases)++ def test_failure_stops_pipeline(self, tmp_path):+ recipe = Recipe(name="x", build=["false"], test=["true"])+ result = run_verify(tmp_path, recipe, skip_start=True)+ assert not result.ok+ assert len(result.phases) == 1+ assert result.phases[0].exit_code == 1++ def test_output_captured(self, tmp_path):+ recipe = Recipe(name="x", test=["echo hello-verify"])+ result = run_verify(tmp_path, recipe, skip_start=True)+ assert "hello-verify" in result.phases[0].output_tail++ def test_phase_selection(self, tmp_path):+ recipe = Recipe(name="x", bootstrap=["true"], build=["true"], test=["true"])+ result = run_verify(tmp_path, recipe, phases=("test",))+ assert [p.phase for p in result.phases] == ["test"]++ def test_phase_timeout(self, tmp_path):+ recipe = Recipe(name="x", test=["sleep 5"])+ result = run_verify(tmp_path, recipe, phase_timeout=0.3, skip_start=True)+ assert not result.ok+ assert result.phases[0].timed_out+ assert result.phases[0].exit_code is None++ def test_commands_run_in_project_root(self, tmp_path):+ (tmp_path / "marker.txt").write_text("here", encoding="utf-8")+ recipe = Recipe(name="x", test=["cat marker.txt"])+ result = run_verify(tmp_path, recipe, skip_start=True)+ assert result.ok++ 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()+ assert payload["ok"] is True+ assert payload["recipe"] == "x"+ assert payload["phases"][0]["command"] == "true"+ assert payload["readiness"] is None+++def _free_port() -> int:+ import socket++ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++class TestReadiness:+ def test_readiness_against_live_server(self, tmp_path):+ port = _free_port()+ recipe = Recipe(+ name="x",+ start=f"python3 -m http.server {port} --bind 127.0.0.1",+ port=port,+ )+ result = run_verify(tmp_path, recipe, phases=("start",), ready_timeout=15)+ assert result.readiness is not None+ assert result.readiness.ready+ assert result.readiness.status_code == 200+ assert result.readiness.url == f"http://127.0.0.1:{port}/"+ assert result.ok++ def test_readiness_timeout_when_nothing_listens(self, tmp_path):+ port = _free_port()+ recipe = Recipe(name="x", start="sleep 30", port=port)+ result = run_verify(tmp_path, recipe, phases=("start",), ready_timeout=1.5)+ assert result.readiness is not None+ assert not result.readiness.ready+ assert not result.ok++ def test_skip_start(self, tmp_path):+ recipe = Recipe(name="x", test=["true"], start="sleep 30", port=1)+ result = run_verify(tmp_path, recipe, skip_start=True)+ assert result.readiness is None+ assert result.ok++ def test_start_skipped_after_phase_failure(self, tmp_path):+ recipe = Recipe(name="x", test=["false"], start="sleep 30", port=1)+ result = run_verify(tmp_path, recipe, stop_on_failure=False)+ assert result.readiness is None+ assert not result.ok++ def test_port_override(self, tmp_path):+ port = _free_port()++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ self.send_response(204)+ self.end_headers()++ def log_message(self, *a):+ pass++ server = http.server.HTTPServer(("127.0.0.1", port), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ time.sleep(0.05)+ try:+ recipe = Recipe(name="x", start="sleep 30", port=1)+ result = run_verify(+ tmp_path, recipe, phases=("start",), ready_timeout=10, port_override=port+ )+ assert result.readiness.ready+ assert result.readiness.status_code == 204+ finally:+ server.shutdown()+ thread.join(timeout=5)diff --git a/tests/verify/test_recipes.py b/tests/verify/test_recipes.pynew file mode 100644index 00000000000..aa93bbb46eb--- /dev/null+++ b/tests/verify/test_recipes.py@@ -0,0 +1,250 @@+"""Tests for agent/verify/recipes.py — static run-recipe detection."""++import json++import pytest++from agent.verify.recipes import Recipe, detect_package_manager, detect_recipe+++def write_pkg(root, data):+ (root / "package.json").write_text(json.dumps(data), encoding="utf-8")+++class TestPackageManagerDetection:+ def test_pnpm_lock_wins(self, tmp_path):+ (tmp_path / "pnpm-lock.yaml").touch()+ (tmp_path / "yarn.lock").touch()+ assert detect_package_manager(tmp_path) == "pnpm"++ @pytest.mark.parametrize(+ "lockfile,manager",+ [+ ("bun.lock", "bun"),+ ("bun.lockb", "bun"),+ ("yarn.lock", "yarn"),+ ("package-lock.json", "npm"),+ ("uv.lock", "uv"),+ ("poetry.lock", "poetry"),+ ("Pipfile.lock", "pipenv"),+ ],+ )+ def test_single_lockfile(self, tmp_path, lockfile, manager):+ (tmp_path / lockfile).touch()+ assert detect_package_manager(tmp_path) == manager++ def test_no_lockfile(self, tmp_path):+ assert detect_package_manager(tmp_path) is None+++class TestNodeDetection:+ def test_nextjs_with_pnpm(self, tmp_path):+ write_pkg(+ tmp_path,+ {+ "dependencies": {"next": "14.0.0"},+ "scripts": {"dev": "next dev", "build": "next build", "test": "jest"},+ },+ )+ (tmp_path / "pnpm-lock.yaml").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "nextjs"+ assert recipe.bootstrap == ["pnpm install"]+ assert recipe.build == ["pnpm build"]+ assert recipe.test == ["pnpm test"]+ assert recipe.start == "pnpm dev"+ assert recipe.port == 3000++ def test_vite_with_yarn(self, tmp_path):+ write_pkg(+ tmp_path,+ {+ "devDependencies": {"vite": "5.0.0"},+ "scripts": {"dev": "vite", "build": "vite build"},+ },+ )+ (tmp_path / "yarn.lock").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "vite"+ assert recipe.bootstrap == ["yarn install"]+ assert recipe.start == "yarn dev"+ assert recipe.port == 5173++ def test_bun_runner(self, tmp_path):+ write_pkg(tmp_path, {"scripts": {"start": "node server.js", "build": "tsc"}})+ (tmp_path / "bun.lockb").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "node"+ assert recipe.bootstrap == ["bun install"]+ assert recipe.start == "bun run start"++ def test_generic_node_defaults_to_npm(self, tmp_path):+ write_pkg(tmp_path, {"scripts": {"test": "mocha"}})+ recipe = detect_recipe(tmp_path)+ assert recipe.bootstrap == ["npm install"]+ assert recipe.test == ["npm run test"]+ assert recipe.start is None+ assert recipe.port is None++ def test_port_inferred_from_start_command(self, tmp_path):+ write_pkg(tmp_path, {"scripts": {"dev": "node server.js --port 4111"}})+ recipe = detect_recipe(tmp_path)+ assert recipe.port == 4111++ def test_cra(self, tmp_path):+ write_pkg(+ tmp_path,+ {"dependencies": {"react-scripts": "5.0"}, "scripts": {"start": "react-scripts start"}},+ )+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "cra"+ assert recipe.port == 3000++ def test_malformed_package_json_falls_through(self, tmp_path):+ (tmp_path / "package.json").write_text("{not json", encoding="utf-8")+ (tmp_path / "go.mod").write_text("module x\n", encoding="utf-8")+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "go"+++class TestPythonDetection:+ def test_django_via_manage_py(self, tmp_path):+ (tmp_path / "manage.py").touch()+ (tmp_path / "requirements.txt").write_text("django\n", encoding="utf-8")+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "django"+ assert recipe.test == ["python manage.py test"]+ assert recipe.port == 8000+ assert "runserver" in recipe.start++ def test_fastapi_uvicorn(self, tmp_path):+ (tmp_path / "requirements.txt").write_text("fastapi\nuvicorn\n", encoding="utf-8")+ (tmp_path / "main.py").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "fastapi"+ assert recipe.start.startswith("uvicorn main:app")+ assert recipe.port == 8000++ def test_flask(self, tmp_path):+ (tmp_path / "requirements.txt").write_text("flask\n", encoding="utf-8")+ (tmp_path / "app.py").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "flask"+ assert recipe.port == 5000++ def test_generic_python_uv(self, tmp_path):+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")+ (tmp_path / "uv.lock").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "python"+ assert recipe.bootstrap == ["uv sync"]++ def test_generic_python_pyproject_editable_install(self, tmp_path):+ (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8")+ recipe = detect_recipe(tmp_path)+ assert recipe.bootstrap == ["pip install -e ."]+ assert recipe.test == ["python -m unittest discover"]++ def test_pytest_when_tests_dir(self, tmp_path):+ (tmp_path / "requirements.txt").write_text("requests\n", encoding="utf-8")+ (tmp_path / "tests").mkdir()+ recipe = detect_recipe(tmp_path)+ assert recipe.test == ["pytest"]+++class TestOtherEcosystems:+ def test_go(self, tmp_path):+ (tmp_path / "go.mod").write_text("module example.com/x\n", encoding="utf-8")+ (tmp_path / "main.go").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "go"+ assert recipe.build == ["go build ./..."]+ assert recipe.start == "go run ."++ def test_rust(self, tmp_path):+ (tmp_path / "Cargo.toml").write_text("[package]\nname='x'\n", encoding="utf-8")+ (tmp_path / "src").mkdir()+ (tmp_path / "src" / "main.rs").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "rust"+ assert recipe.start == "cargo run"++ def test_rust_library_has_no_start(self, tmp_path):+ (tmp_path / "Cargo.toml").write_text("[package]\nname='x'\n", encoding="utf-8")+ recipe = detect_recipe(tmp_path)+ assert recipe.start is None++ def test_maven(self, tmp_path):+ (tmp_path / "pom.xml").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "maven"+ assert recipe.build == ["mvn package"]++ def test_gradle_wrapper(self, tmp_path):+ (tmp_path / "build.gradle").touch()+ (tmp_path / "gradlew").touch()+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "gradle"+ assert recipe.build == ["./gradlew build"]++ def test_makefile(self, tmp_path):+ (tmp_path / "Makefile").write_text(+ "install:\n\tpip install .\nbuild:\n\tmake -C src\ntest:\n\tpytest\nrun:\n\t./app\n",+ encoding="utf-8",+ )+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "make"+ assert recipe.bootstrap == ["make install"]+ assert recipe.build == ["make build"]+ assert recipe.test == ["make test"]+ assert recipe.start == "make run"++ def test_docker_compose(self, tmp_path):+ (tmp_path / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8")+ recipe = detect_recipe(tmp_path)+ assert recipe.kind == "compose"+ assert recipe.start == "docker compose up"++ def test_empty_dir_returns_none(self, tmp_path):+ assert detect_recipe(tmp_path) is None+++class TestRecipeFromDict:+ def test_roundtrip(self):+ recipe = Recipe(name="X", kind="node", bootstrap=["npm install"], port=3000, start="npm run dev")+ restored = Recipe.from_dict(recipe.to_dict())+ assert restored == recipe++ def test_tolerates_garbage(self):+ assert Recipe.from_dict(None) is None+ assert Recipe.from_dict([]) is None+ assert Recipe.from_dict({"kind": "x"}) is None # no name+ assert Recipe.from_dict({"name": " "}) is None++ def test_grok_style_keys(self):+ recipe = Recipe.from_dict(+ {+ "appLabel": "Next.js",+ "appKind": "nextjs",+ "installCommands": ["npm install"],+ "buildCommands": ["npm run build"],+ "testCommands": ["npm test"],+ "startCommand": "npm run dev",+ "startPort": "3000",+ }+ )+ assert recipe.name == "Next.js"+ assert recipe.port == 3000+ assert recipe.bootstrap == ["npm install"]++ def test_invalid_port_dropped(self):+ recipe = Recipe.from_dict({"name": "x", "port": "not-a-port"})+ assert recipe.port is None+ recipe = Recipe.from_dict({"name": "x", "port": 99999999})+ assert recipe.port is None++ def test_bad_readiness_path_normalized(self):+ recipe = Recipe.from_dict({"name": "x", "readinessPath": "health"})+ assert recipe.readiness_path == "/"+ recipe = Recipe.from_dict({"name": "x", "readinessPath": "/health"})+ assert recipe.readiness_path == "/health"diff --git a/tests/verify/test_verify_cmd.py b/tests/verify/test_verify_cmd.pynew file mode 100644index 00000000000..cebf2b49c94--- /dev/null+++ b/tests/verify/test_verify_cmd.py@@ -0,0 +1,97 @@+"""Tests for the ``hermes verify`` CLI command implementation."""++import argparse+import json++from hermes_cli.verify_cmd import run_verify_command+++def make_args(path, **overrides):+ defaults = dict(+ path=str(path),+ detect_only=False,+ save=False,+ skip_start=False,+ phase=None,+ port=None,+ timeout=60.0,+ ready_timeout=5.0,+ json=False,+ )+ defaults.update(overrides)+ return argparse.Namespace(**defaults)+++def test_detect_only_json(tmp_path, capsys):+ (tmp_path / "go.mod").write_text("module x\n", encoding="utf-8")+ code = run_verify_command(make_args(tmp_path, detect_only=True, json=True))+ assert code == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["source"] == "detected"+ assert payload["recipe"]["kind"] == "go"+ assert payload["recipe"]["build"] == ["go build ./..."]+++def test_no_recipe_found(tmp_path, capsys):+ code = run_verify_command(make_args(tmp_path, detect_only=True))+ assert code == 1+ assert "No recognizable project" in capsys.readouterr().err+++def test_save_writes_manifest(tmp_path):+ (tmp_path / "go.mod").write_text("module x\n", encoding="utf-8")+ code = run_verify_command(make_args(tmp_path, detect_only=True, save=True, json=True))+ assert code == 0+ manifest = tmp_path / ".hermes" / "environment.json"+ assert manifest.exists()+ payload = json.loads(manifest.read_text())+ assert payload["version"] == 1+ assert payload["recipe"]["kind"] == "go"+++def test_run_phases_json(tmp_path, capsys):+ manifest = tmp_path / ".hermes"+ manifest.mkdir()+ (manifest / "environment.json").write_text(+ json.dumps({"recipe": {"name": "Fake", "test": ["echo ok"]}}),+ encoding="utf-8",+ )+ code = run_verify_command(make_args(tmp_path, json=True, skip_start=True))+ assert code == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["ok"] is True+ assert payload["source"] == "manifest"+ assert payload["phases"][0]["command"] == "echo ok"+++def test_failing_phase_exit_code(tmp_path, capsys):+ manifest = tmp_path / ".hermes"+ manifest.mkdir()+ (manifest / "environment.json").write_text(+ json.dumps({"recipe": {"name": "Fake", "test": ["false"]}}),+ encoding="utf-8",+ )+ code = run_verify_command(make_args(tmp_path, json=True))+ assert code == 1+ payload = json.loads(capsys.readouterr().out)+ assert payload["ok"] is False+++def test_human_report(tmp_path, capsys):+ manifest = tmp_path / ".hermes"+ manifest.mkdir()+ (manifest / "environment.json").write_text(+ json.dumps({"recipe": {"name": "Fake", "test": ["echo ok"]}}),+ encoding="utf-8",+ )+ code = run_verify_command(make_args(tmp_path, skip_start=True))+ out = capsys.readouterr().out+ assert code == 0+ assert "Recipe: Fake" in out+ assert "PASS" in out+ assert "Result: OK" in out+++def test_bad_path(tmp_path, capsys):+ code = run_verify_command(make_args(tmp_path / "nope"))+ assert code == 2