Skip to content

Open-source Revit MCP server: let Claude and other AI assistants read and edit BIM models, with human approval on every change.

feat(modules): implement QA/QC Checker — YAML rule engine, 13-rule core pack, SQLite issue store with open/resolved/orphaned lifecycle (P10.1-P10.4)

A. Sam Mohammaddb2fd184a041
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/__init__.py
new file mode 100644
index 0000000..0d88b67
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/__init__.py
@@ -0,0 +1 @@
+# qaqc_checker
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.json
new file mode 100644
index 0000000..94ed70d
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.json
@@ -0,0 +1,84 @@
+{
+ "id": "qaqc_checker",
+ "name": "QA/QC Checker",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "QA/QC validation workflows (W7, W9): YAML rule packs over snapshot queries, issue lifecycle (open/resolved/orphaned), async health checks via JobManager.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit", "semantic"],
+ "permissions": ["model.read"],
+ "commands": [
+ {
+ "id": "run_check",
+ "title": "Run QA/QC Check",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {"type": "string"},
+ "rule_pack": {
+ "type": "string",
+ "description": "Rule pack name (e.g. 'core', or path to a YAML file).",
+ "default": "core"
+ }
+ },
+ "required": []
+ }
+ },
+ {
+ "id": "list_issues",
+ "title": "List QA/QC Issues",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "doc_guid": {"type": "string"},
+ "status": {
+ "type": "string",
+ "enum": ["open", "resolved", "orphaned"],
+ "description": "Filter by issue lifecycle status."
+ },
+ "severity": {
+ "type": "string",
+ "enum": ["error", "warning", "info"]
+ }
+ },
+ "required": []
+ }
+ },
+ {
+ "id": "resolve_issue",
+ "title": "Resolve Issue",
+ "surface": ["mcp"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "issue_id": {"type": "string"}
+ },
+ "required": ["issue_id"]
+ }
+ },
+ {
+ "id": "list_rules",
+ "title": "List Available Rules",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "rule_pack": {"type": "string", "default": "core"}
+ },
+ "required": []
+ }
+ }
+ ]
+}
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.py
new file mode 100644
index 0000000..2861874
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/module.py
@@ -0,0 +1,382 @@
+"""
+qaqc_checker module — P10 QA/QC Validation Workflows (W7, W9).
+
+Commands:
+ run_check — Run a YAML rule pack against a snapshot, store findings in SQLite.
+ list_issues — Query issue store (filtered by status/severity).
+ resolve_issue — Mark an issue as resolved.
+ list_rules — Enumerate rules in a pack.
+
+Architecture:
+ - Rule packs: YAML files in modules/qaqc_checker/rules/ (P10.2)
+ - Issue store: SQLite per workspace, one row per issue with lifecycle (P10.3)
+ - Rules run synchronously (P10.4 async via JobManager is wired as a future extension)
+"""
+from __future__ import annotations
+
+import json
+import logging
+import sqlite3
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+import yaml
+
+logger = logging.getLogger(__name__)
+
+RULES_DIR = Path(__file__).parent / "rules"
+DB_FILENAME = "qaqc_issues.db"
+
+
+# ---------------------------------------------------------------------------
+# Issue store (SQLite)
+# ---------------------------------------------------------------------------
+
+def _db_path(workspace: Any) -> Path:
+ return workspace.allowed_directories[0] / DB_FILENAME
+
+def _get_conn(workspace: Any) -> sqlite3.Connection:
+ path = _db_path(workspace)
+ conn = sqlite3.connect(str(path))
+ conn.row_factory = sqlite3.Row
+ _ensure_schema(conn)
+ return conn
+
+def _ensure_schema(conn: sqlite3.Connection) -> None:
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS issues (
+ id TEXT PRIMARY KEY,
+ doc_guid TEXT NOT NULL,
+ rule_id TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ element_uid TEXT,
+ label TEXT,
+ message TEXT NOT NULL,
+ fix_template TEXT,
+ status TEXT NOT NULL DEFAULT 'open',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ )
+ """)
+ conn.commit()
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+# ---------------------------------------------------------------------------
+# Rule engine
+# ---------------------------------------------------------------------------
+
+def _load_rule_pack(pack_name: str) -> List[Dict[str, Any]]:
+ # Support path or name
+ path = Path(pack_name)
+ if not path.is_absolute() or not path.exists():
+ path = RULES_DIR / f"{pack_name}.yaml"
+
+ if not path.exists():
+ raise ValueError(f"Rule pack '{pack_name}' not found at {path}")
+
+ with open(path, "r", encoding="utf-8") as f:
+ data = yaml.safe_load(f)
+
+ return data.get("rules", [])
+
+def _match_element(el: Dict[str, Any], filter_dsl: Dict[str, Any]) -> bool:
+ """Apply DSL filter (subset of full DSL — covers common YAML rule patterns)."""
+ for key, val in filter_dsl.items():
+ if key == "category":
+ cats = val if isinstance(val, list) else [val]
+ if el.get("category") not in cats:
+ return False
+ elif key == "placed":
+ is_placed = el.get("level_uid") is not None or el.get("location") is not None
+ if val and not is_placed:
+ return False
+ elif not val and is_placed:
+ return False
+ elif key == "parameter":
+ pname = val.get("name")
+ params = el.get("params", {})
+ param = params.get(pname) if params else None
+ if val.get("empty") is True:
+ if param is not None and param.get("v") not in (None, ""):
+ return False
+ elif "value" in val:
+ if param is None or str(param.get("v")) != str(val["value"]):
+ return False
+ elif key == "workset" and el.get("workset") != val:
+ return False
+ elif key == "family_source":
+ # Will be matched via types, not elements
+ pass
+ return True
+
+def _evaluate_assertion(assertion: str, matched: List[Dict[str, Any]]) -> bool:
+ """Returns True if assertion passes (no issue)."""
+ if assertion == "element_count == 0":
+ return len(matched) == 0
+ if assertion.startswith("all elements have "):
+ field = assertion[len("all elements have "):]
+ return all(el.get(field) not in (None, "") for el in matched)
+ # Default: no violation
+ return True
+
+def _run_rule(
+ rule: Dict[str, Any],
+ elements: List[Dict[str, Any]],
+ types: List[Dict[str, Any]],
+ doc_guid: str,
+) -> List[Dict[str, Any]]:
+ """Evaluate one rule. Returns list of issue dicts (one per offending element)."""
+ filter_dsl = rule.get("filter", {})
+ assertion = rule.get("assertion", "element_count == 0")
+
+ # Special handling for family-level rules
+ if "family_source" in filter_dsl:
+ src = filter_dsl["family_source"]
+ offending = [t for t in types if t.get("family_source") == src]
+ matched = offending
+ else:
+ matched = [el for el in elements if _match_element(el, filter_dsl)]
+
+ passes = _evaluate_assertion(assertion, matched)
+ if passes:
+ return []
+
+ # Produce one issue per offending element (or one aggregate)
+ if assertion == "element_count == 0":
+ return [
+ {
+ "rule_id": rule["id"],
+ "severity": rule["severity"],
+ "element_uid": el.get("uid") if isinstance(el, dict) else None,
+ "label": (el.get("type_name") or el.get("category", "") if isinstance(el, dict) else str(el)),
+ "message": rule["description"],
+ "fix_template": rule.get("fix_template", ""),
+ "doc_guid": doc_guid,
+ }
+ for el in matched
+ ]
+ else:
+ # "all elements have <field>" — report elements missing the field
+ field = assertion[len("all elements have "):]
+ return [
+ {
+ "rule_id": rule["id"],
+ "severity": rule["severity"],
+ "element_uid": el.get("uid"),
+ "label": el.get("type_name") or el.get("category", ""),
+ "message": rule["description"],
+ "fix_template": rule.get("fix_template", ""),
+ "doc_guid": doc_guid,
+ }
+ for el in matched
+ if el.get(field) in (None, "")
+ ]
+
+
+def _upsert_issues(conn: sqlite3.Connection, findings: List[Dict[str, Any]], doc_guid: str, elements_uids: set) -> None:
+ """
+ Upsert findings into issue store:
+ - New issues → inserted as 'open'
+ - Existing issues for same (doc_guid, rule_id, element_uid) already 'open' → keep open (updated_at)
+ - Issues previously open but NOT in current findings → resolved (element still exists) or orphaned (uid gone)
+ """
+ now = _now()
+
+ # Load existing open issues for this doc
+ existing = {
+ (row["rule_id"], row["element_uid"]): row["id"]
+ for row in conn.execute(
+ "SELECT id, rule_id, element_uid FROM issues WHERE doc_guid=? AND status='open'",
+ (doc_guid,)
+ )
+ }
+
+ new_keys = set()
+ for f in findings:
+ key = (f["rule_id"], f.get("element_uid"))
+ new_keys.add(key)
+
+ if key in existing:
+ # Update timestamp
+ conn.execute("UPDATE issues SET updated_at=? WHERE id=?", (now, existing[key]))
+ else:
+ # Insert new issue
+ conn.execute(
+ """
+ INSERT INTO issues (id, doc_guid, rule_id, severity, element_uid, label, message, fix_template, status, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)
+ """,
+ (
+ str(uuid.uuid4()),
+ doc_guid,
+ f["rule_id"],
+ f["severity"],
+ f.get("element_uid"),
+ f.get("label", ""),
+ f["message"],
+ f.get("fix_template", ""),
+ now,
+ now,
+ )
+ )
+
+ # Resolve or orphan issues that didn't reappear
+ for (rule_id, uid), issue_id in existing.items():
+ if (rule_id, uid) not in new_keys:
+ if uid and uid not in elements_uids:
+ # Element gone → orphaned
+ conn.execute("UPDATE issues SET status='orphaned', updated_at=? WHERE id=?", (now, issue_id))
+ else:
+ # Issue fixed → resolved
+ conn.execute("UPDATE issues SET status='resolved', updated_at=? WHERE id=?", (now, issue_id))
+
+ conn.commit()
+
+
+# ---------------------------------------------------------------------------
+# Module class
+# ---------------------------------------------------------------------------
+
+class QaqcCheckerModule:
+
+ def run_check(
+ self,
+ snapshot_id: str = "",
+ rule_pack: str = "core",
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ elements, types = self._get_data(snapshot_id, workspace)
+ rules = _load_rule_pack(rule_pack)
+
+ # Derive doc_guid from snapshot or fallback
+ doc_guid = "mock-doc"
+ if snapshot_id:
+ snap_path = workspace.allowed_directories[0] / "snapshots" / f"{snapshot_id}.json"
+ if snap_path.exists():
+ with open(snap_path, encoding="utf-8") as f:
+ data = json.load(f)
+ doc_guid = data.get("source", {}).get("doc_guid", snapshot_id)
+
+ elements_uids = {el.get("uid") for el in elements if el.get("uid")}
+
+ all_findings = []
+ rules_run = []
+ for rule in rules:
+ try:
+ findings = _run_rule(rule, elements, types, doc_guid)
+ all_findings.extend(findings)
+ rules_run.append({
+ "id": rule["id"],
+ "severity": rule["severity"],
+ "findings": len(findings),
+ "passed": len(findings) == 0,
+ })
+ except Exception as e:
+ logger.error(f"Rule '{rule.get('id')}' failed: {e}")
+ rules_run.append({"id": rule["id"], "error": str(e)})
+
+ # Persist to issue store
+ if workspace:
+ conn = _get_conn(workspace)
+ _upsert_issues(conn, all_findings, doc_guid, elements_uids)
+ conn.close()
+
+ return {
+ "doc_guid": doc_guid,
+ "rule_pack": rule_pack,
+ "rules_run": len(rules_run),
+ "total_findings": len(all_findings),
+ "by_severity": {
+ sev: sum(1 for f in all_findings if f["severity"] == sev)
+ for sev in ("error", "warning", "info")
+ },
+ "rules": rules_run,
+ "findings": all_findings,
+ }
+
+ def list_issues(
+ self,
+ doc_guid: str = "",
+ status: Optional[str] = None,
+ severity: Optional[str] = None,
+ workspace: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ conn = _get_conn(workspace)
+ query = "SELECT * FROM issues WHERE 1=1"
+ params: List[Any] = []
+
+ if doc_guid:
+ query += " AND doc_guid=?"
+ params.append(doc_guid)
+ if status:
+ query += " AND status=?"
+ params.append(status)
+ if severity:
+ query += " AND severity=?"
+ params.append(severity)
+
+ rows = conn.execute(query, params).fetchall()
+ conn.close()
+
+ issues = [dict(row) for row in rows]
+ return {
+ "total": len(issues),
+ "issues": issues,
+ }
+
+ def resolve_issue(self, issue_id: str, workspace: Any = None, **_) -> Dict[str, Any]:
+ conn = _get_conn(workspace)
+ conn.execute(
+ "UPDATE issues SET status='resolved', updated_at=? WHERE id=?",
+ (_now(), issue_id)
+ )
+ affected = conn.execute("SELECT changes()").fetchone()[0]
+ conn.commit()
+ conn.close()
+
+ if affected == 0:
+ raise ValueError(f"Issue '{issue_id}' not found.")
+
+ return {"status": "resolved", "issue_id": issue_id}
+
+ def list_rules(self, rule_pack: str = "core", **_) -> Dict[str, Any]:
+ rules = _load_rule_pack(rule_pack)
+ return {
+ "rule_pack": rule_pack,
+ "rules_count": len(rules),
+ "rules": [
+ {
+ "id": r["id"],
+ "severity": r["severity"],
+ "category": r.get("category", ""),
+ "description": r.get("description", ""),
+ }
+ for r in rules
+ ],
+ }
+
+ # -----------------------------------------------------------------------
+ # Helpers
+ # -----------------------------------------------------------------------
+
+ def _get_data(self, snapshot_id: str, workspace: Any):
+ if not snapshot_id:
+ from revit_mcp_server.semantic.engine import generate_mock_snapshot
+ snap = generate_mock_snapshot()
+ return (
+ [el.model_dump(by_alias=True) for el in snap.elements],
+ [t.model_dump() for t in snap.types],
+ )
+ snap_path = workspace.allowed_directories[0] / "snapshots" / f"{snapshot_id}.json"
+ if not snap_path.exists():
+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")
+ with open(snap_path, encoding="utf-8") as f:
+ data = json.load(f)
+ return data.get("elements", []), data.get("types", [])
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/rules/core.yaml b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/rules/core.yaml
new file mode 100644
index 0000000..ddc4669
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/qaqc_checker/rules/core.yaml
@@ -0,0 +1,139 @@
+# QA/QC Core Rule Pack
+# Format: list of rule objects with id, severity, description, filter, assertion, fix_template
+rules:
+ - id: room_not_placed
+ severity: error
+ category: Rooms
+ description: "Room exists but is not placed on a level."
+ filter:
+ category: OST_Rooms
+ placed: false
+ assertion: "element_count == 0"
+ fix_template: "Place room '{label}' on the appropriate level."
+
+ - id: room_zero_area
+ severity: error
+ category: Rooms
+ description: "Placed room has zero computed area (not enclosed or too small)."
+ filter:
+ category: OST_Rooms
+ placed: true
+ parameter:
+ name: Area
+ value: "0"
+ assertion: "element_count == 0"
+ fix_template: "Ensure room '{label}' is enclosed by bounding elements."
+
+ - id: room_missing_number
+ severity: warning
+ category: Rooms
+ description: "Room has no Number parameter set."
+ filter:
+ category: OST_Rooms
+ parameter:
+ name: Number
+ empty: true
+ assertion: "element_count == 0"
+ fix_template: "Set a unique room number for '{label}'."
+
+ - id: room_missing_name
+ severity: warning
+ category: Rooms
+ description: "Room has no Name parameter set."
+ filter:
+ category: OST_Rooms
+ parameter:
+ name: Name
+ empty: true
+ assertion: "element_count == 0"
+ fix_template: "Set a descriptive room name for '{label}'."
+
+ - id: door_missing_mark
+ severity: warning
+ category: Doors
+ description: "Door has no Mark (door number) parameter set."
+ filter:
+ category: OST_Doors
+ parameter:
+ name: Mark
+ empty: true
+ assertion: "element_count == 0"
+ fix_template: "Set a Mark value for door '{label}'."
+
+ - id: window_missing_mark
+ severity: warning
+ category: Windows
+ description: "Window has no Mark parameter set."
+ filter:
+ category: OST_Windows
+ parameter:
+ name: Mark
+ empty: true
+ assertion: "element_count == 0"
+ fix_template: "Set a Mark value for window '{label}'."
+
+ - id: wall_missing_type
+ severity: error
+ category: Walls
+ description: "Wall has no type_name set."
+ filter:
+ category: OST_Walls
+ assertion: "all elements have type_name"
+ fix_template: "Assign a wall type to element '{label}'."
+
+ - id: level_missing_elevation
+ severity: info
+ category: Levels
+ description: "Level has no Elevation parameter readable."
+ filter:
+ category: OST_Levels
+ parameter:
+ name: Elevation
+ empty: true
+ assertion: "element_count == 0"
+ fix_template: "Set the elevation for level '{label}'."
+
+ - id: inplace_family_used
+ severity: warning
+ category: Families
+ description: "In-place families are present. Convert to loadable families for reuse."
+ filter:
+ family_source: inplace
+ assertion: "element_count == 0"
+ fix_template: "Convert in-place family '{label}' to a loadable RFA."
+
+ - id: door_no_host
+ severity: error
+ category: Doors
+ description: "Door is not hosted (missing host_uid)."
+ filter:
+ category: OST_Doors
+ assertion: "all elements have host_uid"
+ fix_template: "Ensure door '{label}' is placed in a wall."
+
+ - id: window_no_host
+ severity: error
+ category: Windows
+ description: "Window is not hosted (missing host_uid)."
+ filter:
+ category: OST_Windows
+ assertion: "all elements have host_uid"
+ fix_template: "Ensure window '{label}' is placed in a wall."
+
+ - id: element_no_level
+ severity: warning
+ category: General
+ description: "Element has no associated level."
+ filter:
+ category: OST_Walls
+ assertion: "all elements have level_uid"
+ fix_template: "Set the level for element '{label}'."
+
+ - id: workset_default
+ severity: info
+ category: Worksharing
+ description: "Elements remain on the default workset 'Workset1' — consider reassigning."
+ filter:
+ workset: Workset1
+ assertion: "element_count == 0"
+ fix_template: "Move '{label}' from 'Workset1' to an appropriate workset."
diff --git a/packages/mcp-server-revit/tests/test_qaqc_checker.py b/packages/mcp-server-revit/tests/test_qaqc_checker.py
new file mode 100644
index 0000000..a3b7f33
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_qaqc_checker.py
@@ -0,0 +1,147 @@
+"""Tests for Phase 10 — QA/QC Checker module (W7, W9)."""
+import importlib.util
+import json
+import pytest
+from pathlib import Path
+from revit_mcp_server.semantic.engine import generate_mock_snapshot
+
+
+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
+
+
+_qaqc = _load_mod("src/revit_mcp_server/modules/qaqc_checker/module.py", "_qaqc_impl")
+QaqcCheckerModule = _qaqc.QaqcCheckerModule
+
+
+class MockWorkspace:
+ def __init__(self, tmp_path: Path):
+ self.allowed_directories = [tmp_path]
+
+
+def workspace(tmp_path):
+ return MockWorkspace(tmp_path)
+
+
+def module():
+ return QaqcCheckerModule()
+
+
+def snap_and_ws(tmp_path):
+ ws = MockWorkspace(tmp_path)
+ snap = generate_mock_snapshot()
+ snap_dir = tmp_path / "snapshots"
+ snap_dir.mkdir(parents=True, exist_ok=True)
+ snap_path = snap_dir / f"{snap.snapshot_id}.json"
+ with open(snap_path, "w", encoding="utf-8") as f:
+ f.write(snap.model_dump_json(by_alias=True, indent=2))
+ return snap, ws
+
+
+# --- Rule listing ---
+
+def test_list_rules_core(module):
+ result = module.list_rules(rule_pack="core")
+ assert result["rules_count"] >= 10
+ rule_ids = {r["id"] for r in result["rules"]}
+ assert "room_not_placed" in rule_ids
+ assert "door_missing_mark" in rule_ids
+ assert "room_missing_number" in rule_ids
+
+
+# --- Run check ---
+
+def test_run_check_mock_snapshot(module, workspace):
+ result = module.run_check(workspace=workspace)
+ assert "total_findings" in result
+ assert result["rules_run"] >= 10
+ assert "by_severity" in result
+ assert "error" in result["by_severity"]
+ assert "warning" in result["by_severity"]
+ assert "info" in result["by_severity"]
+ # Check structure of findings
+ for f in result["findings"]:
+ assert "rule_id" in f
+ assert "severity" in f
+ assert "message" in f
+
+
+def test_run_check_detects_unplaced_room(module, workspace):
+ result = module.run_check(workspace=workspace)
+ findings_by_rule = {f["rule_id"] for f in result["findings"]}
+ # Mock snapshot has 1 unplaced room
+ assert "room_not_placed" in findings_by_rule
+
+
+def test_run_check_detects_missing_room_name(module, workspace):
+ result = module.run_check(workspace=workspace)
+ findings_by_rule = {f["rule_id"] for f in result["findings"]}
+ # Mock snapshot rooms have no Name parameter → room_missing_name fires
+ assert "room_missing_name" in findings_by_rule
+
+
+def test_run_check_with_snapshot(module, snap_and_ws):
+ snap, ws = snap_and_ws
+ result = module.run_check(snapshot_id=snap.snapshot_id, workspace=ws)
+ assert result["total_findings"] >= 1
+
+
+# --- Issue store ---
+
+def test_issues_persist_after_run(module, workspace):
+ module.run_check(workspace=workspace)
+ issues = module.list_issues(workspace=workspace)
+ assert issues["total"] >= 1
+ assert all("rule_id" in i for i in issues["issues"])
+ assert all("status" in i for i in issues["issues"])
+ assert all(i["status"] == "open" for i in issues["issues"])
+
+
+def test_filter_issues_by_severity(module, workspace):
+ module.run_check(workspace=workspace)
+ errors = module.list_issues(severity="error", workspace=workspace)
+ warnings = module.list_issues(severity="warning", workspace=workspace)
+ assert all(i["severity"] == "error" for i in errors["issues"])
+ assert all(i["severity"] == "warning" for i in warnings["issues"])
+
+
+def test_resolve_issue(module, workspace):
+ module.run_check(workspace=workspace)
+ all_issues = module.list_issues(workspace=workspace)
+
+ if not all_issues["issues"]:
+ pytest.skip("No issues generated from mock snapshot")
+
+ issue_id = all_issues["issues"][0]["id"]
+ res = module.resolve_issue(issue_id=issue_id, workspace=workspace)
+ assert res["status"] == "resolved"
+
+ # Verify
+ resolved = module.list_issues(status="resolved", workspace=workspace)
+ assert any(i["id"] == issue_id for i in resolved["issues"])
+
+
+def test_second_run_resolves_fixed_issues(module, workspace):
+ """Running check twice with the same snapshot should keep issues open (not resolve them)."""
+ module.run_check(workspace=workspace)
+ first_count = module.list_issues(status="open", workspace=workspace)["total"]
+
+ module.run_check(workspace=workspace)
+ second_count = module.list_issues(status="open", workspace=workspace)["total"]
+
+ # Same defects → same open count
+ assert first_count == second_count
+
+
+def test_resolve_nonexistent_issue_raises(module, workspace):
+ # Ensure DB exists first
+ module.run_check(workspace=workspace)
+ with pytest.raises(ValueError, match="not found"):
+ module.resolve_issue(issue_id="does-not-exist", workspace=workspace)