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: links and worksets audit (read-only) (#83)

A. Sam Mohammad60a25be00678
diff --git a/docs/tools-generated.md b/docs/tools-generated.md
index f4afeb0..072d453 100644
--- a/docs/tools-generated.md
+++ b/docs/tools-generated.md
@@ -78,6 +78,7 @@ This catalog lists all tools exposed by the AEC Model Bridge providers.
| `familytype_mapper_audit_families` | Audit the families in a saved snapshot and report problems such as unmapped or inconsistent family types. | No | sync |
| `familytype_mapper_list_type_mappings` | List family-type mappings found in a saved snapshot, optionally for one category. | No | sync |
| `hello_world_say_hello` | Example module command that returns a greeting; use it to confirm the module system works. | No | sync |
+| `links_worksets_audit_audit` | Check linked models and worksets for problems (unloaded or missing links, links not pinned or placed Origin to Origin, empty or default-named worksets, worksets owned by someone else, elements on the wrong workset) and give plain next steps. | No | sync |
| `model_inspector_ask` | Answer a question about a saved snapshot by filtering its element records with the filter DSL. | No | sync |
| `model_inspector_inspect_selection` | Return the snapshot records of the given elements (by UniqueId). | No | sync |
| `model_inspector_list_groups` | List the model groups found in a saved snapshot. | No | sync |
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/__init__.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/__init__.py
new file mode 100644
index 0000000..82aa30c
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/__init__.py
@@ -0,0 +1 @@
+# links_worksets_audit
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.json b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.json
new file mode 100644
index 0000000..7fed7ad
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.json
@@ -0,0 +1,57 @@
+{
+ "id": "links_worksets_audit",
+ "name": "Links and Worksets Audit",
+ "version": "1.0.0",
+ "schema_version": 1,
+ "min_hub_version": "1.2.0",
+ "description": "Read-only audit of linked models and worksets: unloaded or missing links, links that are not pinned, links placed Origin to Origin, empty or default-named worksets, worksets open by another user, and elements on the wrong workset for their category.",
+ "author": "AEC Model Bridge",
+ "license": "GPL-3.0-or-later",
+ "requires_providers": ["revit"],
+ "permissions": ["model.read"],
+ "commands": [
+ {
+ "id": "audit",
+ "title": "Audit Links and Worksets",
+ "surface": ["mcp", "panel"],
+ "execution_mode": "sync",
+ "is_mutating": false,
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "snapshot_id": {
+ "type": "string",
+ "description": "Optional saved snapshot. Used to count elements per workset and to check categories against the workset mapping."
+ },
+ "category_workset_map": {
+ "type": "object",
+ "description": "Optional. Which workset each category belongs on, for example {\"Walls\": \"Shared Architecture\"} (Revit names such as OST_Walls are also accepted). Elements on a different workset are reported.",
+ "additionalProperties": {"type": "string"}
+ },
+ "current_user": {
+ "type": "string",
+ "description": "Your Revit username, so worksets you own are not reported as open by someone else."
+ },
+ "expect_shared_coordinates": {
+ "type": "boolean",
+ "description": "Report links placed 'Auto - Origin to Origin' as a warning. Default true.",
+ "default": true
+ },
+ "links": {
+ "type": ["object", "array"],
+ "description": "Optional. Link data to audit instead of reading it live from Revit (output of revit_get_rvt_links)."
+ },
+ "link_instances": {
+ "type": ["object", "array"],
+ "description": "Optional. Link placement data (output of revit_get_link_instances)."
+ },
+ "worksets": {
+ "type": ["object", "array"],
+ "description": "Optional. Workset data (output of revit_get_worksets)."
+ }
+ },
+ "required": []
+ }
+ }
+ ]
+}
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.py b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.py
new file mode 100644
index 0000000..9dd09c0
--- /dev/null
+++ b/packages/mcp-server-revit/src/revit_mcp_server/modules/links_worksets_audit/module.py
@@ -0,0 +1,317 @@
+"""
+links_worksets_audit module - read-only audit of linked models and worksets.
+
+Command:
+ audit - Check links (unloaded, missing path, not pinned, Origin to Origin
+ placement) and worksets (empty, default name, open by another user,
+ elements on the wrong workset for their category).
+
+Data sources (what the Revit add-in exposes today):
+ revit_get_rvt_links -> name, id, is_loaded, is_nested, path
+ revit_get_link_instances -> name, id, type_id, link_name
+ revit_get_worksets -> is_workshared, worksets[name, id, is_open]
+ snapshot elements -> category, workset (name)
+
+GAPS (UNVERIFIED, not yet returned by the add-in; checks run only when the
+field is present in the data, and the result lists each one under "gaps"):
+ - link pinned state, link placement ("Auto - Origin to Origin" etc.),
+ link kind (IFC / CAD), CAD links entirely
+ - workset owner / default flag
+ - per-workset element count (derived from a snapshot when one is given)
+Nothing here has been run against live Revit.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+from collections import defaultdict
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_WORKSET_RE = re.compile(r"^workset\s*\d*$", re.IGNORECASE)
+ORIGIN_TO_ORIGIN = "origin to origin"
+_UNKNOWN_PATHS = {"", "unknown", "none", "null"}
+_SEVERITY_ORDER = {"error": 0, "warning": 1, "info": 2}
+
+
+def _unwrap(data: Any, key: str) -> List[Dict[str, Any]]:
+ """Accept a raw list or the add-in's {key: [...]} reply (possibly wrapped in 'result')."""
+ if isinstance(data, dict) and key not in data and isinstance(data.get("result"), dict):
+ data = data["result"]
+ if isinstance(data, dict):
+ data = data.get(key, [])
+ return [d for d in (data or []) if isinstance(d, dict)]
+
+
+def _finding(severity: str, area: str, rule: str, item: str, message: str, next_step: str, **extra: Any) -> Dict[str, Any]:
+ out = {"severity": severity, "area": area, "rule": rule, "item": item, "message": message, "next_step": next_step}
+ out.update(extra)
+ return out
+
+
+def _bool_or_none(v: Any) -> Optional[bool]:
+ return v if isinstance(v, bool) else None
+
+
+def check_links(
+ links: List[Dict[str, Any]],
+ instances: List[Dict[str, Any]],
+ expect_shared_coordinates: bool = True,
+ check_local_paths: bool = True,
+) -> List[Dict[str, Any]]:
+ findings: List[Dict[str, Any]] = []
+ by_type: Dict[Any, List[Dict[str, Any]]] = defaultdict(list)
+ for inst in instances:
+ by_type[inst.get("type_id")].append(inst)
+
+ for link in links:
+ name = str(link.get("name", "(unnamed link)"))
+ kind = link.get("kind") or link.get("link_kind") or "Revit"
+ label = f"{kind} link '{name}'"
+
+ if link.get("is_loaded") is False:
+ findings.append(_finding(
+ "warning", "link", "link_unloaded", name,
+ f"{label} is unloaded, so its geometry is not in the model.",
+ "In Manage Links, select the link and click Reload (or Reload From if the file moved).",
+ ))
+
+ path = link.get("path")
+ if not link.get("is_nested") and (path is None or str(path).strip().lower() in _UNKNOWN_PATHS):
+ findings.append(_finding(
+ "error", "link", "link_missing_path", name,
+ f"{label} has no file path, so Revit cannot find the source file.",
+ "In Manage Links, use Reload From to point the link at the current file.",
+ ))
+ elif check_local_paths and path and re.match(r"^([A-Za-z]:[\\/]|\\\\)", str(path)) and not os.path.exists(str(path)):
+ findings.append(_finding(
+ "info", "link", "link_path_not_found_from_here", name,
+ f"{label} points to '{path}', which this tool cannot see from where it runs.",
+ "Open Manage Links in Revit and check the Status column. Ignore this if the tool runs on a different machine than Revit.",
+ ))
+
+ pinned_vals: List[bool] = []
+ positions: List[str] = []
+ for inst in by_type.get(link.get("id"), []) + [link]:
+ p = _bool_or_none(inst.get("pinned"))
+ if p is not None:
+ pinned_vals.append(p)
+ pos = inst.get("positioning") or inst.get("position_type")
+ if pos:
+ positions.append(str(pos))
+
+ if pinned_vals and not all(pinned_vals):
+ findings.append(_finding(
+ "warning", "link", "link_not_pinned", name,
+ f"{label} is not pinned and could be moved by accident.",
+ "Select the link in a view and click Pin on the Modify tab.",
+ ))
+ if expect_shared_coordinates and any(ORIGIN_TO_ORIGIN in p.lower() for p in positions):
+ findings.append(_finding(
+ "warning", "link", "link_origin_to_origin", name,
+ f"{label} is placed 'Auto - Origin to Origin' but this project is expected to use shared coordinates.",
+ "Reload the link with Manage Links > Reload From, place it by Shared Coordinates (Acquire Coordinates if needed) and check it against the survey point.",
+ ))
+ if link.get("shared_coordinates_match") is False:
+ findings.append(_finding(
+ "error", "link", "link_coordinates_mismatch", name,
+ f"{label} does not share coordinates with this model.",
+ "Agree the shared coordinate origin with the link owner, then use Acquire or Publish Coordinates.",
+ ))
+ return findings
+
+
+def check_worksets(
+ data: Any,
+ element_counts: Optional[Dict[str, int]] = None,
+ current_user: str = "",
+) -> List[Dict[str, Any]]:
+ if isinstance(data, dict) and "worksets" not in data and isinstance(data.get("result"), dict):
+ data = data["result"]
+ if isinstance(data, dict) and data.get("is_workshared") is False:
+ return [_finding(
+ "info", "workset", "not_workshared", "(model)",
+ "This model is not workshared, so there are no worksets to check.",
+ "Nothing to do unless the model should be workshared (Collaborate > Collaborate).",
+ )]
+ findings: List[Dict[str, Any]] = []
+ me = current_user.strip().lower()
+
+ for ws in _unwrap(data, "worksets"):
+ name = str(ws.get("name", "(unnamed)"))
+ if ws.get("is_default") is True or DEFAULT_WORKSET_RE.match(name):
+ findings.append(_finding(
+ "warning", "workset", "workset_default_name", name,
+ f"Workset '{name}' still has a default name, so nobody can tell what belongs on it.",
+ "Rename it in Collaborate > Worksets (for example 'Architecture - Walls').",
+ ))
+
+ count = ws.get("element_count")
+ if count is None and element_counts is not None:
+ count = element_counts.get(name, 0)
+ if count == 0:
+ findings.append(_finding(
+ "info", "workset", "workset_empty", name,
+ f"Workset '{name}' has no elements.",
+ "Delete it in Collaborate > Worksets if it is not needed, or keep it for planned content.",
+ ))
+
+ owner = str(ws.get("owner") or "").strip()
+ if owner and owner.lower() != me:
+ findings.append(_finding(
+ "warning", "workset", "workset_open_by_other_user", name,
+ f"Workset '{name}' is checked out by {owner}.",
+ f"Ask {owner} to synchronize and relinquish it before you need to edit it.",
+ owner=owner,
+ ))
+ return findings
+
+
+def _norm_category(name: Any) -> str:
+ """'OST_Walls', 'Walls' and 'walls' all compare equal."""
+ text = str(name or "").strip().lower()
+ if text.startswith("ost_"):
+ text = text[4:]
+ return re.sub(r"[\s_]+", "", text)
+
+
+def check_element_worksets(elements: List[Dict[str, Any]], category_map: Dict[str, str]) -> List[Dict[str, Any]]:
+ norm_map = {_norm_category(k): v for k, v in category_map.items()}
+ wrong: Dict[str, List[Dict[str, Any]]] = defaultdict(list)
+ expected_by_cat: Dict[str, str] = {}
+ for el in elements:
+ cat = el.get("category")
+ expected = norm_map.get(_norm_category(cat)) if cat else None
+ ws_name = el.get("workset")
+ if expected is None or not ws_name:
+ continue # no mapping, or the snapshot has no workset data for this element
+ if ws_name != expected:
+ wrong[cat].append(el)
+ expected_by_cat[cat] = expected
+ findings = []
+ for cat, els in sorted(wrong.items()):
+ expected = expected_by_cat[cat]
+ found_on = sorted({str(e.get("workset") or "(none)") for e in els})
+ findings.append(_finding(
+ "warning", "element_workset", "wrong_workset", cat,
+ f"{len(els)} {cat} element(s) are not on workset '{expected}' (found on: {', '.join(found_on)}).",
+ f"Select the {cat} elements and move them to '{expected}' using the workset drop-down in the status bar.",
+ expected_workset=expected, count=len(els),
+ sample_uids=[e.get("uid") for e in els[:10] if e.get("uid")],
+ ))
+ return findings
+
+
+class LinksWorksetsAuditModule:
+
+ def audit(
+ self,
+ snapshot_id: str = "",
+ category_workset_map: Optional[Dict[str, str]] = None,
+ current_user: str = "",
+ expect_shared_coordinates: bool = True,
+ links: Any = None,
+ link_instances: Any = None,
+ worksets: Any = None,
+ workspace: Any = None,
+ tool_executor: Any = None,
+ **_,
+ ) -> Dict[str, Any]:
+ notes: List[str] = []
+ live = False
+ # Anything not supplied is read live from the Revit tools (read-only).
+ if tool_executor is not None:
+ for arg, tool in (("links", "revit_get_rvt_links"),
+ ("link_instances", "revit_get_link_instances"),
+ ("worksets", "revit_get_worksets")):
+ if locals()[arg] is not None:
+ continue
+ try:
+ value = tool_executor(tool, {})
+ except Exception as exc:
+ notes.append(f"Could not read {tool} from Revit: {exc}")
+ continue
+ live = True
+ if arg == "links":
+ links = value
+ elif arg == "link_instances":
+ link_instances = value
+ else:
+ worksets = value
+
+ elements = self._load_elements(snapshot_id, workspace) if snapshot_id else []
+
+ findings: List[Dict[str, Any]] = []
+ link_list = _unwrap(links, "links") if links is not None else []
+ inst_list = _unwrap(link_instances, "instances") if link_instances is not None else []
+ if links is not None:
+ findings += check_links(link_list, inst_list, expect_shared_coordinates)
+ else:
+ notes.append("No link data available, so links were not checked.")
+
+ counts: Optional[Dict[str, int]] = None
+ has_workset_data = any(el.get("workset") for el in elements)
+ if elements and not has_workset_data:
+ notes.append(
+ "The snapshot has no workset information on its elements, so empty worksets "
+ "and elements on the wrong workset could not be checked."
+ )
+ if has_workset_data:
+ counts = defaultdict(int)
+ for el in elements:
+ if el.get("workset"):
+ counts[str(el["workset"])] += 1
+ ws_list = _unwrap(worksets, "worksets") if worksets is not None else []
+ if worksets is not None:
+ findings += check_worksets(worksets, counts, current_user)
+ else:
+ notes.append("No workset data available, so worksets were not checked.")
+
+ if category_workset_map:
+ if has_workset_data:
+ findings += check_element_worksets(elements, category_workset_map)
+ elif elements:
+ pass # already noted above
+ else:
+ notes.append("A workset mapping was given but no snapshot_id, so element worksets were not checked.")
+
+ findings.sort(key=lambda f: (_SEVERITY_ORDER.get(f["severity"], 9), f["area"], f["item"]))
+ return {
+ "total_findings": len(findings),
+ "by_severity": {s: sum(1 for f in findings if f["severity"] == s) for s in ("error", "warning", "info")},
+ "links_checked": len(link_list),
+ "worksets_checked": len(ws_list),
+ "findings": findings,
+ "notes": notes,
+ "gaps": self._gaps(link_list, inst_list, ws_list, counts is not None),
+ "unverified": "UNVERIFIED: read-only and not yet run against live Revit; fields the add-in does not return are listed under gaps.",
+ "source": "live_revit" if live else "supplied_data",
+ }
+
+ @staticmethod
+ def _gaps(link_list, inst_list, ws_list, have_counts: bool) -> List[str]:
+ gaps = []
+ both = link_list + inst_list
+ if link_list and not any("pinned" in d for d in both):
+ gaps.append("UNVERIFIED: the add-in does not return pinned state for links, so 'not pinned' cannot be checked yet.")
+ if link_list and not any(d.get("positioning") or d.get("position_type") for d in both):
+ gaps.append("UNVERIFIED: the add-in does not return link placement (Origin to Origin vs shared coordinates), so that check cannot run yet.")
+ if link_list and not any(d.get("kind") or d.get("link_kind") for d in link_list):
+ gaps.append("UNVERIFIED: only Revit links are listed; IFC and CAD links are not exposed by the add-in yet.")
+ if ws_list and not any("owner" in w for w in ws_list):
+ gaps.append("UNVERIFIED: the add-in does not return who has a workset checked out, so 'open by another user' cannot be checked yet.")
+ if ws_list and not have_counts and not any("element_count" in w for w in ws_list):
+ gaps.append("The empty-workset check needs a snapshot_id (element counts per workset).")
+ return gaps
+
+ @staticmethod
+ def _load_elements(snapshot_id: str, workspace: Any) -> List[Dict[str, Any]]:
+ path = Path(workspace.allowed_directories[0]) / "snapshots" / f"{snapshot_id}.json"
+ if not path.exists():
+ raise ValueError(f"Snapshot '{snapshot_id}' not found.")
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f).get("elements", [])
diff --git a/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py b/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py
index 039b81c..1637a42 100644
--- a/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py
+++ b/packages/mcp-server-revit/src/revit_mcp_server/tool_metadata.py
@@ -162,6 +162,7 @@ DESCRIPTIONS: dict[str, str] = {
"parameter_manager_plan_set_params": "Create a draft ActionPlan that sets parameter values on the elements of a snapshot matching a filter. Review and approve the plan before it runs.",
"parameter_manager_export_params_csv": "Export parameters of the matching snapshot elements to a CSV file in the workspace. Writes a file; does not change the model.",
"parameter_manager_import_params_csv": "Read parameter values from a CSV file in the workspace and create a draft ActionPlan that applies them. Does not change the model; review and approve the plan before it runs.",
+ "links_worksets_audit_audit": "Check linked models and worksets for problems (unloaded or missing links, links not pinned or placed Origin to Origin, empty or default-named worksets, worksets owned by someone else, elements on the wrong workset) and give plain next steps. Read-only.",
"qaqc_checker_run_check": "Run a QA/QC rule pack against a saved snapshot and record the issues it finds.",
"qaqc_checker_list_issues": "List recorded QA/QC issues for a document, optionally filtered by status and severity. Read-only.",
"qaqc_checker_resolve_issue": "Mark one recorded QA/QC issue as resolved.",
diff --git a/packages/mcp-server-revit/tests/test_links_worksets_audit.py b/packages/mcp-server-revit/tests/test_links_worksets_audit.py
new file mode 100644
index 0000000..c1a05dd
--- /dev/null
+++ b/packages/mcp-server-revit/tests/test_links_worksets_audit.py
@@ -0,0 +1,205 @@
+"""Tests for the links and worksets audit module (read-only; fixtures stand in for Revit)."""
+import importlib.util
+import json
+from pathlib import Path
+
+import pytest
+
+
+def _load_mod():
+ # Import under its package name so coverage (source_pkgs) measures it.
+ return importlib.import_module("revit_mcp_server.modules.links_worksets_audit.module")
+
+
+_mod = _load_mod()
+Audit = _mod.LinksWorksetsAuditModule
+
+
+class WS:
+ def __init__(self, tmp_path):
+ self.allowed_directories = [tmp_path]
+
+
+# Shapes match what BridgeCommandFactory.cs returns today.
+LINKS = {"links": [
+ {"name": "ARC.rvt", "id": 1, "is_loaded": True, "is_nested": False, "path": "RSN://srv/ARC.rvt"},
+ {"name": "STR.rvt", "id": 2, "is_loaded": False, "is_nested": False, "path": "RSN://srv/STR.rvt"},
+ {"name": "MEP.rvt", "id": 3, "is_loaded": True, "is_nested": False, "path": "Unknown"},
+]}
+INSTANCES = {"instances": [{"name": "ARC.rvt : 1", "id": 10, "type_id": 1, "link_name": "ARC.rvt"}]}
+WORKSETS = {"is_workshared": True, "worksets": [
+ {"name": "Shared Levels and Grids", "id": 1, "is_open": True},
+ {"name": "Workset1", "id": 2, "is_open": True},
+ {"name": "Spare", "id": 3, "is_open": False},
+]}
+
+
+def rules(result):
+ return {(f["rule"], f["item"]) for f in result["findings"]}
+
+
+def test_unloaded_and_missing_path_links():
+ r = Audit().audit(links=LINKS, link_instances=INSTANCES, worksets=WORKSETS)
+ assert ("link_unloaded", "STR.rvt") in rules(r)
+ assert ("link_missing_path", "MEP.rvt") in rules(r)
+ assert ("link_unloaded", "ARC.rvt") not in rules(r)
+ missing = next(f for f in r["findings"] if f["rule"] == "link_missing_path")
+ assert missing["severity"] == "error" and missing["next_step"]
+ assert r["by_severity"]["error"] == 1
+
+
+def test_default_workset_name_and_gaps_marked_unverified():
+ r = Audit().audit(links=LINKS, link_instances=INSTANCES, worksets=WORKSETS)
+ assert ("workset_default_name", "Workset1") in rules(r)
+ gaps = " ".join(r["gaps"])
+ assert "UNVERIFIED" in gaps and "pinned" in gaps and "checked out" in gaps
+ assert "UNVERIFIED" in r["unverified"]
+ assert r["source"] == "supplied_data"
+
+
+def test_findings_sorted_errors_first():
+ r = Audit().audit(links=LINKS, worksets=WORKSETS)
+ sev = [f["severity"] for f in r["findings"]]
+ order = {"error": 0, "warning": 1, "info": 2}
+ assert sev == sorted(sev, key=order.get)
+
+
+def test_pinned_and_origin_to_origin_when_addin_supplies_fields():
+ links = {"links": [{"name": "ARC.rvt", "id": 1, "is_loaded": True, "path": "RSN://x"}]}
+ inst = {"instances": [
+ {"type_id": 1, "pinned": True, "positioning": "Auto - Origin to Origin"},
+ {"type_id": 1, "pinned": False, "positioning": "Shared Coordinates"},
+ ]}
+ r = Audit().audit(links=links, link_instances=inst)
+ assert ("link_not_pinned", "ARC.rvt") in rules(r)
+ assert ("link_origin_to_origin", "ARC.rvt") in rules(r)
+ assert not any("pinned state" in g for g in r["gaps"])
+ r2 = Audit().audit(links=links, link_instances=inst, expect_shared_coordinates=False)
+ assert ("link_origin_to_origin", "ARC.rvt") not in rules(r2)
+
+
+def test_coordinates_mismatch_is_error():
+ links = [{"name": "CAD", "id": 1, "path": "RSN://x", "shared_coordinates_match": False}]
+ r = Audit().audit(links=links)
+ f = next(f for f in r["findings"] if f["rule"] == "link_coordinates_mismatch")
+ assert f["severity"] == "error"
+
+
+def test_nested_link_without_path_is_not_missing():
+ r = Audit().audit(links=[{"name": "N", "id": 1, "is_nested": True, "path": "Nested"}])
+ assert not r["findings"]
+
+
+def test_workset_owner_and_empty_from_supplied_fields():
+ ws = [
+ {"name": "Arch", "owner": "alice", "element_count": 5},
+ {"name": "Mine", "owner": "Bob", "element_count": 5},
+ {"name": "Unused", "element_count": 0},
+ ]
+ r = Audit().audit(worksets=ws, current_user="bob")
+ assert ("workset_open_by_other_user", "Arch") in rules(r)
+ assert ("workset_open_by_other_user", "Mine") not in rules(r)
+ assert ("workset_empty", "Unused") in rules(r)
+ assert not any("checked out" in g for g in r["gaps"])
+
+
+def test_not_workshared_model():
+ r = Audit().audit(worksets={"is_workshared": False, "worksets": []})
+ assert [f["rule"] for f in r["findings"]] == ["not_workshared"]
+
+
+def test_snapshot_gives_empty_worksets_and_wrong_workset(tmp_path):
+ snap_dir = tmp_path / "snapshots"
+ snap_dir.mkdir()
+ elements = [
+ {"uid": "w1", "category": "Walls", "workset": "Workset1"},
+ {"uid": "w2", "category": "Walls", "workset": "Shared Levels and Grids"},
+ {"uid": "d1", "category": "Doors", "workset": "Shared Levels and Grids"},
+ ]
+ (snap_dir / "s1.json").write_text(json.dumps({"elements": elements}), encoding="utf-8")
+ r = Audit().audit(
+ snapshot_id="s1", worksets=WORKSETS, workspace=WS(tmp_path),
+ category_workset_map={"Walls": "Architecture", "Doors": "Shared Levels and Grids", "Roofs": "Roof"},
+ )
+ assert ("workset_empty", "Spare") in rules(r)
+ assert ("workset_empty", "Workset1") not in rules(r)
+ wrong = [f for f in r["findings"] if f["rule"] == "wrong_workset"]
+ assert len(wrong) == 1 and wrong[0]["item"] == "Walls" and wrong[0]["count"] == 2
+ assert set(wrong[0]["sample_uids"]) == {"w1", "w2"}
+
+
+def test_mapping_without_snapshot_is_noted():
+ r = Audit().audit(worksets=WORKSETS, category_workset_map={"Walls": "Arch"})
+ assert any("snapshot_id" in n for n in r["notes"])
+
+
+def test_unknown_snapshot_raises(tmp_path):
+ with pytest.raises(ValueError):
+ Audit().audit(snapshot_id="nope", workspace=WS(tmp_path))
+
+
+def test_reads_live_tools_via_executor_and_unwraps_result():
+ calls = []
+
+ def ex(tool, args):
+ calls.append(tool)
+ return {"result": {"rvt_links": 1, **{"revit_get_rvt_links": LINKS,
+ "revit_get_link_instances": INSTANCES,
+ "revit_get_worksets": WORKSETS}[tool]}}
+
+ r = Audit().audit(tool_executor=ex)
+ assert calls == ["revit_get_rvt_links", "revit_get_link_instances", "revit_get_worksets"]
+ assert r["source"] == "live_revit"
+ assert ("link_unloaded", "STR.rvt") in rules(r)
+
+
+def test_executor_failure_is_reported_not_raised():
+ def ex(tool, args):
+ raise RuntimeError("Revit not connected")
+
+ r = Audit().audit(tool_executor=ex)
+ assert r["total_findings"] == 0
+ assert any("Revit not connected" in n for n in r["notes"])
+
+
+def test_manifest_is_read_only():
+ p = Path(__file__).parent.parent / "src/revit_mcp_server/modules/links_worksets_audit/module.json"
+ m = json.loads(p.read_text(encoding="utf-8"))
+ assert m["id"] == "links_worksets_audit"
+ assert all(c["is_mutating"] is False for c in m["commands"])
+ assert m["permissions"] == ["model.read"]
+
+
+def _snap(tmp_path, elements, name="s1"):
+ snap_dir = tmp_path / "snapshots"
+ snap_dir.mkdir(exist_ok=True)
+ (snap_dir / f"{name}.json").write_text(json.dumps({"elements": elements}), encoding="utf-8")
+
+
+def test_snapshot_without_workset_data_infers_nothing(tmp_path):
+ # Live snapshots carry no 'workset' field: no empty-workset or wrong-workset findings.
+ _snap(tmp_path, [{"uid": "w1", "category": "OST_Walls"}, {"uid": "d1", "category": "OST_Doors"}])
+ r = Audit().audit(
+ snapshot_id="s1", worksets=WORKSETS, workspace=WS(tmp_path),
+ category_workset_map={"Walls": "Architecture"},
+ )
+ assert not [f for f in r["findings"] if f["rule"] in ("workset_empty", "wrong_workset")]
+ assert any("workset" in n.lower() and "snapshot" in n.lower() for n in r["notes"])
+
+
+def test_category_map_matches_live_ost_names(tmp_path):
+ _snap(tmp_path, [
+ {"uid": "w1", "category": "OST_Walls", "workset": "Workset1"},
+ {"uid": "w2", "category": "OST_Walls", "workset": "Architecture"},
+ ])
+ r = Audit().audit(
+ snapshot_id="s1", worksets=WORKSETS, workspace=WS(tmp_path),
+ category_workset_map={"Walls": "Architecture"},
+ )
+ wrong = [f for f in r["findings"] if f["rule"] == "wrong_workset"]
+ assert len(wrong) == 1 and wrong[0]["count"] == 1 and wrong[0]["sample_uids"] == ["w1"]
+ r2 = Audit().audit(
+ snapshot_id="s1", worksets=WORKSETS, workspace=WS(tmp_path),
+ category_workset_map={"OST_Walls": "Architecture"},
+ )
+ assert [f for f in r2["findings"] if f["rule"] == "wrong_workset"]