Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.
Python aecai-agentsautodeskautomationbimclaudeifcmcpmcp-servermodel-context-protocolnavisworksrevitrevit-addinrevit-apirhino
feat(modules): implement Recipe Runner orchestration (P15.1-P15.3)
A. Sam Mohammad7ae2eb59966b
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.pyindex aa9a17b..4820ed5 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/mcp_server.py@@ -59,7 +59,7 @@ registry.register(SemanticProvider(workspace=workspace, registry=registry))# Initialize and register Module registry and Module providermodule_registry = ModuleRegistry(config_obj=config)module_registry.discover_and_load()-registry.register(ModuleProvider(module_registry=module_registry, workspace=workspace))+registry.register(ModuleProvider(module_registry=module_registry, workspace=workspace, tool_registry=registry))# Initialize Job Manager and Job Providerjob_manager = JobManager()diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/__init__.pynew file mode 100644index 0000000..27d8cb3--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/__init__.py@@ -0,0 +1 @@+# recipe_runnerdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.jsonnew file mode 100644index 0000000..f261b71--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.json@@ -0,0 +1,66 @@+{+ "id": "recipe_runner",+ "name": "Recipe Runner",+ "version": "1.0.0",+ "schema_version": 1,+ "min_hub_version": "1.2.0",+ "description": "AI agent orchestration: run multi-step YAML recipes with template substitution, condition evaluation, and run logging. Ships three built-in recipes.",+ "author": "AEC Model Bridge",+ "license": "GPL-3.0-or-later",+ "requires_providers": [],+ "permissions": ["model.read", "files.write"],+ "commands": [+ {+ "id": "run_recipe",+ "title": "Run Recipe",+ "surface": ["mcp"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "recipe_id": {"type": "string", "description": "Recipe name or path."},+ "args": {"type": "object", "description": "Context variables for template substitution."},+ "dry_run": {"type": "boolean", "default": false, "description": "If true, plan steps without executing."}+ },+ "required": ["recipe_id"]+ }+ },+ {+ "id": "list_recipes",+ "title": "List Recipes",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {"type": "object", "properties": {}, "required": []}+ },+ {+ "id": "list_runs",+ "title": "List Recipe Runs",+ "surface": ["mcp"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "recipe_id": {"type": "string", "description": "Filter by recipe ID."}+ },+ "required": []+ }+ },+ {+ "id": "get_run_status",+ "title": "Get Recipe Run Status",+ "surface": ["mcp", "panel"],+ "execution_mode": "sync",+ "is_mutating": false,+ "input_schema": {+ "type": "object",+ "properties": {+ "run_id": {"type": "string", "description": "Recipe run ID."}+ },+ "required": ["run_id"]+ }+ }+ ]+}diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.pynew file mode 100644index 0000000..b1a1c8e--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/module.py@@ -0,0 +1,268 @@+"""+Recipe Runner — P15 AI Agent Orchestration.++Recipe format (YAML):+ id: recipe_id+ name: Human name+ description: ...+ steps:+ - id: step_id+ tool: tool_name # e.g. "model_inspector_summarize_model"+ args: # static args+ snapshot_id: "{{snapshot_id}}"+ capture_as: snap_summary # optional: store result under this key+ - id: step_2+ tool: qaqc_checker_run_check+ args:+ snapshot_id: "{{snapshot_id}}"+ condition: "{{prev.total_findings}} >= 0" # always run+ capture_as: qaqc_result++Template variables: {{key}} → replaced from context dict.+Condition: minimal eval — supports == != >= <= comparisons on {{prev.field}}.+"""+from __future__ import annotations++import json+import logging+import re+import uuid+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional++import yaml++logger = logging.getLogger(__name__)++RECIPES_DIR = Path(__file__).parent / "recipes"+RUN_LOG_FILE = "recipe_runs.json"+ToolExecutor = Callable[[str, Dict[str, Any]], Dict[str, Any]]+++# ---------------------------------------------------------------------------+# Template engine (minimal — no exec, no eval on untrusted input)+# ---------------------------------------------------------------------------++def _render(value: Any, context: Dict[str, Any]) -> Any:+ """Recursively substitute {{key}} and {{obj.field}} placeholders."""+ if isinstance(value, str):+ def _sub(m: re.Match) -> str:+ expr = m.group(1).strip()+ parts = expr.split(".")+ node: Any = context+ for p in parts:+ if isinstance(node, dict):+ node = node.get(p)+ else:+ node = getattr(node, p, None)+ if node is None:+ return ""+ return str(node) if node is not None else ""+ return re.sub(r"\{\{([^}]+)\}\}", _sub, value)+ if isinstance(value, dict):+ return {k: _render(v, context) for k, v in value.items()}+ if isinstance(value, list):+ return [_render(v, context) for v in value]+ return value++def _check_condition(condition: Optional[str], context: Dict[str, Any]) -> bool:+ if not condition:+ return True+ rendered = _render(condition, context)+ # Simple comparison: X >= Y, X == Y, etc.+ m = re.match(r"^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$", rendered.strip())+ if not m:+ return bool(rendered)+ lhs, op, rhs = m.group(1).strip(), m.group(2), m.group(3).strip()+ try:+ lhs_v: Any = float(lhs) if "." in lhs else int(lhs)+ rhs_v: Any = float(rhs) if "." in rhs else int(rhs)+ except (ValueError, TypeError):+ lhs_v, rhs_v = lhs, rhs+ ops = {"==": lhs_v == rhs_v, "!=": lhs_v != rhs_v, ">=": lhs_v >= rhs_v, "<=": lhs_v <= rhs_v, ">": lhs_v > rhs_v, "<": lhs_v < rhs_v}+ return ops.get(op, False)+++# ---------------------------------------------------------------------------+# Recipe loader+# ---------------------------------------------------------------------------++def _workspace_path(path: Path, workspace: Any) -> Path:+ if not workspace or not getattr(workspace, "allowed_directories", None):+ raise ValueError("Workspace is required to load recipe files.")+ roots = [Path(root).resolve() for root in workspace.allowed_directories]+ resolved = path.resolve()+ if not any(resolved.is_relative_to(root) for root in roots):+ raise ValueError(f"Recipe file '{resolved}' is outside the allowed workspace.")+ return resolved++def _load_recipe(recipe_id: str, workspace: Any = None) -> Dict[str, Any]:+ candidate = Path(recipe_id)+ looks_like_path = candidate.is_absolute() or candidate.suffix in {".yaml", ".yml"} or len(candidate.parts) > 1+ if looks_like_path:+ if candidate.is_absolute():+ path = _workspace_path(candidate, workspace)+ else:+ if not workspace or not getattr(workspace, "allowed_directories", None):+ raise ValueError("Workspace is required to load recipe files.")+ path = _workspace_path(Path(workspace.allowed_directories[0]) / candidate, workspace)+ else:+ path = RECIPES_DIR / f"{recipe_id}.yaml"+ if not path.exists():+ raise ValueError(f"Recipe '{recipe_id}' not found at {path}")+ with open(path, "r", encoding="utf-8") as f:+ data = yaml.safe_load(f) or {}+ if not isinstance(data.get("steps", []), list):+ raise ValueError(f"Recipe '{recipe_id}' has invalid steps.")+ return data++def _list_recipes() -> List[Dict[str, Any]]:+ if not RECIPES_DIR.exists():+ return []+ result = []+ for p in sorted(RECIPES_DIR.glob("*.yaml")):+ try:+ data = yaml.safe_load(p.read_text(encoding="utf-8"))+ result.append({"id": data.get("id", p.stem), "name": data.get("name", ""), "description": data.get("description", "")})+ except Exception:+ pass+ return result+++# ---------------------------------------------------------------------------+# Run log+# ---------------------------------------------------------------------------++def _run_log_path(workspace: Any) -> Path:+ if not workspace:+ raise ValueError("Workspace is required for recipe run logs.")+ return workspace.allowed_directories[0] / RUN_LOG_FILE++def _load_runs(workspace: Any) -> List[Dict[str, Any]]:+ if not workspace:+ return []+ p = _run_log_path(workspace)+ if p.exists():+ with open(p, encoding="utf-8") as f:+ return json.load(f)+ return []++def _save_run(run: Dict[str, Any], workspace: Any) -> None:+ runs = _load_runs(workspace)+ runs.append(run)+ with open(_run_log_path(workspace), "w", encoding="utf-8") as f:+ json.dump(runs, f, indent=2, default=str)++def _run_status(step_results: List[Dict[str, Any]], dry_run: bool) -> str:+ if any("error" in step for step in step_results):+ return "failed"+ if dry_run:+ return "dry_run"+ if any(step.get("pending") for step in step_results):+ return "pending"+ return "completed"+++# ---------------------------------------------------------------------------+# Module class+# ---------------------------------------------------------------------------++class RecipeRunnerModule:++ def run_recipe(+ self,+ recipe_id: str,+ args: Dict[str, Any] = None,+ dry_run: bool = False,+ workspace: Any = None,+ tool_executor: Any = None, # Callable[str, dict] → dict (injected by provider)+ **_,+ ) -> Dict[str, Any]:+ recipe = _load_recipe(recipe_id, workspace)+ steps = recipe.get("steps", [])+ context: Dict[str, Any] = dict(args or {})++ run_id = str(uuid.uuid4())+ started_at = datetime.now(timezone.utc).isoformat()++ step_results = []+ prev: Dict[str, Any] = {}++ for step in steps:+ step_id = step.get("id", "?")+ tool_name = step.get("tool", "")+ raw_args = step.get("args", {})+ condition = step.get("condition")+ capture_as = step.get("capture_as")++ # Inject prev+ context["prev"] = prev++ if not _check_condition(condition, context):+ step_results.append({"step": step_id, "skipped": True, "reason": "condition_false"})+ continue++ rendered_args = _render(raw_args, context)++ if dry_run:+ step_results.append({"step": step_id, "tool": tool_name, "args": rendered_args, "dry_run": True})+ continue++ if tool_executor:+ try:+ result = tool_executor(tool_name, rendered_args)+ if result is None:+ result = {}+ prev = result+ if capture_as:+ context[capture_as] = result+ step_results.append({"step": step_id, "tool": tool_name, "result": result})+ except Exception as e:+ step_results.append({"step": step_id, "tool": tool_name, "error": str(e)})+ break+ else:+ # No executor — record pending+ step_results.append({"step": step_id, "tool": tool_name, "args": rendered_args, "pending": True})++ status = _run_status(step_results, dry_run)+ finished_at = datetime.now(timezone.utc).isoformat()+ run = {+ "run_id": run_id,+ "recipe_id": recipe_id,+ "status": status,+ "started_at": started_at,+ "finished_at": finished_at,+ "dry_run": dry_run,+ "steps": step_results,+ }++ if workspace:+ _save_run(run, workspace)++ return {+ "run_id": run_id,+ "recipe_id": recipe_id,+ "status": status,+ "steps_total": len(steps),+ "steps_run": len(step_results),+ "dry_run": dry_run,+ "finished_at": finished_at,+ "steps": step_results,+ }++ def list_recipes(self, **_) -> Dict[str, Any]:+ recipes = _list_recipes()+ return {"count": len(recipes), "recipes": recipes}++ def list_runs(self, recipe_id: str = "", workspace: Any = None, **_) -> Dict[str, Any]:+ runs = _load_runs(workspace)+ if recipe_id:+ runs = [r for r in runs if r.get("recipe_id") == recipe_id]+ return {"count": len(runs), "runs": runs}++ def get_run_status(self, run_id: str, workspace: Any = None, **_) -> Dict[str, Any]:+ for run in _load_runs(workspace):+ if run.get("run_id") == run_id:+ return run+ raise ValueError(f"Recipe run '{run_id}' not found.")diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/export_clash_import.yaml b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/export_clash_import.yamlnew file mode 100644index 0000000..4fcaea6--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/export_clash_import.yaml@@ -0,0 +1,21 @@+id: export_clash_import+name: Export → Clash → Issue Import+description: "Export model snapshot, retrieve clash results from Navisworks mapper, and import as QA/QC issues."+steps:+ - id: take_snapshot+ tool: snapshot_take+ args: {}+ capture_as: snapshot_result++ - id: export_data+ tool: report_generator_export_sqlite_summary+ args:+ snapshot_id: "{{snapshot_result.snapshot_id}}"+ output_filename: "clash_export.db"+ capture_as: export_result++ - id: check_qaqc+ tool: qaqc_checker_run_check+ args:+ snapshot_id: "{{snapshot_result.snapshot_id}}"+ capture_as: qaqc_resultdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/nightly_health_check.yaml b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/nightly_health_check.yamlnew file mode 100644index 0000000..c74356d--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/nightly_health_check.yaml@@ -0,0 +1,22 @@+id: nightly_health_check+name: Nightly Health Check → Excel+description: "Take a model snapshot, run QA/QC checks, and export findings to Excel."+steps:+ - id: take_snapshot+ tool: snapshot_take+ args: {}+ capture_as: snapshot_result++ - id: run_qaqc+ tool: qaqc_checker_run_check+ args:+ snapshot_id: "{{snapshot_result.snapshot_id}}"+ capture_as: qaqc_result++ - id: export_report+ tool: report_generator_export_excel+ args:+ snapshot_id: "{{snapshot_result.snapshot_id}}"+ include_qaqc: true+ output_filename: "nightly_health_{{snapshot_result.taken_at}}.xlsx"+ capture_as: report_resultdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/snapshot_publish.yaml b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/snapshot_publish.yamlnew file mode 100644index 0000000..626a37b--- /dev/null+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/recipe_runner/recipes/snapshot_publish.yaml@@ -0,0 +1,16 @@+id: snapshot_publish+name: Snapshot → Speckle Publish+description: "Take a BIM snapshot and publish it as a Speckle version."+steps:+ - id: take_snapshot+ tool: snapshot_take+ args: {}+ capture_as: snapshot_result++ - id: publish_speckle+ tool: speckle_publish_version+ args:+ snapshot_id: "{{snapshot_result.snapshot_id}}"+ stream_id: "{{stream_id}}"+ message: "Auto-publish from recipe at {{snapshot_result.taken_at}}"+ capture_as: speckle_resultdiff --git a/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py b/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.pyindex b33f7a2..eeab16a 100644--- a/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py+++ b/packages/mcp-server-revit/src/revit_mcp_server/providers/module_provider.py@@ -3,7 +3,6 @@ from __future__ import annotationsimport asyncioimport inspectimport logging-from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optionalfrom revit_mcp_server.errors import BridgeError@@ -60,9 +59,10 @@ def validate_json_schema(data: Any, schema: Dict[str, Any], path: str = "root")raise ValueError(f"Value at {path} must be a boolean")class ModuleProvider(AECProvider):- def __init__(self, module_registry: ModuleRegistry, workspace: WorkspaceMonitor):+ def __init__(self, module_registry: ModuleRegistry, workspace: WorkspaceMonitor, tool_registry: Any = None):self.registry = module_registryself.workspace = workspace+ self.tool_registry = tool_registrydef get_identity(self) -> str:return "module"@@ -209,6 +209,7 @@ class ModuleProvider(AECProvider):return {"modules": module_list}async def _run_callable(self, func: Callable[..., Any], arguments: Dict[str, Any]) -> Any:+ loop = asyncio.get_running_loop()sig = inspect.signature(func)kwargs = {}for param_name, param in sig.parameters.items():@@ -216,6 +217,8 @@ class ModuleProvider(AECProvider):kwargs[param_name] = argumentselif param_name == "workspace":kwargs[param_name] = self.workspace+ elif param_name == "tool_executor" and self.tool_registry:+ kwargs[param_name] = self._sync_tool_executor(loop)elif param_name in arguments:kwargs[param_name] = arguments[param_name]@@ -230,6 +233,36 @@ class ModuleProvider(AECProvider):else:return await asyncio.get_running_loop().run_in_executor(None, lambda: func(**kwargs))+ def _sync_tool_executor(self, loop: asyncio.AbstractEventLoop) -> Callable[[str, Dict[str, Any]], Dict[str, Any]]:+ def execute(tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:+ future = asyncio.run_coroutine_threadsafe(+ self._execute_registered_tool(tool_name, arguments),+ loop,+ )+ return future.result()++ return execute++ async def _execute_registered_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:+ provider = self.tool_registry.lookup_tool_provider(tool_name) if self.tool_registry else None+ tool_def = self.tool_registry.lookup_tool(tool_name) if self.tool_registry else None+ if not provider:+ raise BridgeError(f"Recipe step tool '{tool_name}' not found in registry")++ gate = getattr(self.tool_registry.get_provider("approval"), "gate", None)+ if tool_def and tool_def.is_mutating and gate:+ gate.check_tool_execution(tool_name, arguments)++ result = await provider.execute_tool(tool_name, arguments)++ if tool_def and tool_def.is_mutating and gate and isinstance(arguments, dict) and "plan_id" in arguments:+ try:+ gate.update_plan_state(arguments["plan_id"], "executed")+ except Exception:+ pass++ return result+async def _run_callable_with_timeout(self, func: Callable[..., Any], *args, timeout: float = 2.0) -> Any:try:return await asyncio.wait_for(self._run_callable(func, *args), timeout=timeout)diff --git a/packages/mcp-server-revit/tests/test_recipe_runner.py b/packages/mcp-server-revit/tests/test_recipe_runner.pynew file mode 100644index 0000000..a30b2ec--- /dev/null+++ b/packages/mcp-server-revit/tests/test_recipe_runner.py@@ -0,0 +1,256 @@+"""Tests for Phase 15 — Recipe Runner module (AI orchestration)."""+import importlib.util+import pytest+from pathlib import Path++from revit_mcp_server.config import Config+from revit_mcp_server.providers import AECProvider, ApprovalProvider, ModuleProvider, ProviderRegistry, ProviderTool+from revit_mcp_server.module_registry import ModuleRegistry+from revit_mcp_server.security.workspace import WorkspaceMonitor+++def _load_mod(relpath: str, name: str):+ p = Path(__file__).parent.parent / relpath+ spec = importlib.util.spec_from_file_location(name, p)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++_rr = _load_mod("src/revit_mcp_server/modules/recipe_runner/module.py", "_rr_impl")+RecipeRunnerModule = _rr.RecipeRunnerModule+_render = _rr._render+_check_condition = _rr._check_condition+++class MockWorkspace:+ def __init__(self, tmp_path: Path):+ self.allowed_directories = [tmp_path]+++def workspace(tmp_path):+ return MockWorkspace(tmp_path)+++def module():+ return RecipeRunnerModule()+++class SnapshotProvider(AECProvider):+ def get_identity(self) -> str:+ return "snapshot"++ def get_capabilities(self):+ return [+ ProviderTool(+ name="snapshot_take",+ description="Mock snapshot",+ inputSchema={"type": "object", "properties": {}, "required": []},+ )+ ]++ async def check_health(self):+ return {"status": "ok"}++ async def shutdown(self):+ pass++ async def execute_tool(self, name, arguments):+ return {"snapshot_id": "", "taken_at": "20260101"}+++class MutatingProvider(AECProvider):+ def get_identity(self) -> str:+ return "mutating"++ def get_capabilities(self):+ return [+ ProviderTool(+ name="fake_mutate",+ description="Mock mutating tool",+ inputSchema={"type": "object", "properties": {}, "required": []},+ is_mutating=True,+ )+ ]++ async def check_health(self):+ return {"status": "ok"}++ async def shutdown(self):+ pass++ async def execute_tool(self, name, arguments):+ return {"status": "mutated"}+++def _module_provider(tmp_path: Path, registry: ProviderRegistry) -> ModuleProvider:+ cfg = Config(+ workspace_dir=tmp_path,+ allowed_directories=[tmp_path],+ audit_log=tmp_path / "audit.log",+ enable_user_modules=False,+ )+ module_registry = ModuleRegistry(config_obj=cfg)+ module_registry.discover_and_load()+ return ModuleProvider(+ module_registry=module_registry,+ workspace=WorkspaceMonitor([tmp_path]),+ tool_registry=registry,+ )+++# --- Template engine tests ---++def test_render_simple_key():+ assert _render("{{name}}", {"name": "Antigravity"}) == "Antigravity"++def test_render_nested():+ assert _render("{{snap.snapshot_id}}", {"snap": {"snapshot_id": "abc123"}}) == "abc123"++def test_render_no_match():+ assert _render("{{missing}}", {}) == ""++def test_render_dict():+ rendered = _render({"snapshot_id": "{{snap_id}}"}, {"snap_id": "xyz"})+ assert rendered == {"snapshot_id": "xyz"}+++# --- Condition evaluator ---++def test_condition_true_gte():+ assert _check_condition("{{prev.count}} >= 0", {"prev": {"count": 5}}) is True++def test_condition_false_lt():+ assert _check_condition("{{prev.count}} < 0", {"prev": {"count": 5}}) is False++def test_condition_eq():+ assert _check_condition("{{prev.status}} == ok", {"prev": {"status": "ok"}}) is True++def test_condition_none_is_true():+ assert _check_condition(None, {}) is True+++# --- Recipe listing ---++def test_list_recipes_includes_builtins(module):+ result = module.list_recipes()+ assert result["count"] >= 3+ recipe_ids = {r["id"] for r in result["recipes"]}+ assert "nightly_health_check" in recipe_ids+ assert "snapshot_publish" in recipe_ids+ assert "export_clash_import" in recipe_ids+++# --- Dry run ---++def test_dry_run_plans_steps(module, workspace):+ result = module.run_recipe(+ recipe_id="nightly_health_check",+ args={},+ dry_run=True,+ workspace=workspace,+ )+ assert result["dry_run"] is True+ assert result["steps_total"] == 3+ assert all(s.get("dry_run") is True for s in result["steps"])+++# --- Run with mock executor ---++def test_run_with_mock_executor(module, workspace):+ call_log = []++ def mock_executor(tool_name: str, args: dict) -> dict:+ call_log.append(tool_name)+ if tool_name == "snapshot_take":+ return {"snapshot_id": "snap-001", "taken_at": "2026-01-01T00:00:00Z", "elements_count": 6}+ if tool_name == "qaqc_checker_run_check":+ return {"total_findings": 2, "rules_run": 13}+ if tool_name == "report_generator_export_excel":+ return {"status": "exported", "output_file": "/tmp/report.xlsx"}+ return {}++ result = module.run_recipe(+ recipe_id="nightly_health_check",+ args={},+ dry_run=False,+ workspace=workspace,+ tool_executor=mock_executor,+ )+ assert result["steps_run"] == 3+ assert "snapshot_take" in call_log+ assert "qaqc_checker_run_check" in call_log+++# --- Run log persistence ---++def test_runs_are_logged(module, workspace):+ module.run_recipe(recipe_id="nightly_health_check", dry_run=True, workspace=workspace)+ runs = module.list_runs(workspace=workspace)+ assert runs["count"] == 1+ assert runs["runs"][0]["recipe_id"] == "nightly_health_check"+ assert runs["runs"][0]["status"] == "dry_run"++def test_get_run_status(module, workspace):+ result = module.run_recipe(recipe_id="nightly_health_check", dry_run=True, workspace=workspace)+ status = module.get_run_status(run_id=result["run_id"], workspace=workspace)+ assert status["run_id"] == result["run_id"]+ assert status["status"] == "dry_run"++def test_filter_runs_by_recipe_id(module, workspace):+ module.run_recipe(recipe_id="nightly_health_check", dry_run=True, workspace=workspace)+ module.run_recipe(recipe_id="snapshot_publish", dry_run=True, workspace=workspace)+ runs = module.list_runs(recipe_id="nightly_health_check", workspace=workspace)+ assert runs["count"] == 1++def test_nonexistent_recipe_raises(module, workspace):+ with pytest.raises(ValueError, match="not found"):+ module.run_recipe(recipe_id="does_not_exist", workspace=workspace)+++async def test_provider_executes_recipe_steps(tmp_path):+ registry = ProviderRegistry()+ provider = _module_provider(tmp_path, registry)+ registry.register(provider)+ registry.register(SnapshotProvider())++ result = await provider.execute_tool("recipe_runner_run_recipe", {"recipe_id": "nightly_health_check"})++ assert result["status"] == "completed"+ assert [step["tool"] for step in result["steps"]] == [+ "snapshot_take",+ "qaqc_checker_run_check",+ "report_generator_export_excel",+ ]+ assert (tmp_path / "nightly_health_20260101.xlsx").exists()+++async def test_provider_recipe_steps_respect_approval_gate(tmp_path):+ recipe = tmp_path / "mutating.yaml"+ recipe.write_text(+ """+id: mutating+name: Mutating+steps:+ - id: mutate+ tool: fake_mutate+ args: {}+""".strip(),+ encoding="utf-8",+ )++ registry = ProviderRegistry()+ workspace = WorkspaceMonitor([tmp_path])+ registry.register(ApprovalProvider(workspace=workspace, registry=registry, approval_mode="required"))+ provider = _module_provider(tmp_path, registry)+ registry.register(provider)+ registry.register(MutatingProvider())++ result = await provider.execute_tool("recipe_runner_run_recipe", {"recipe_id": "mutating.yaml"})++ assert result["status"] == "failed"+ assert "requires a valid 'plan_id'" in result["steps"][0]["error"]