C++(cad_mcp_plugins):
- 新增 bvh.h:header-only 2D BVH(质心中位分割,叶<=4,SelfPairs 交叉对枚举)
- 新增 find_collisions.cpp:粗筛 AABB 相交实体对,附重叠盒 + 逐轴重叠比 ratio
(= 逐轴重叠长/较短长 之积,退化轴取 1.0),按 ratio 降序 + 分页;
narrow=true 只对返回页跑 intersectWith 细筛(附 exact)
- 容器过滤(关键):图框块/分区边界会与一切相交,用重叠【度】判定
deg >= max(exclude_container_deg=8, exclude_container_frac=0.25 * 其他实体数),
与图幅/缩放无关;被剔除者在 excluded_containers 里如实报告
(初版用面积判据对多图框并排失效:3 框只占并集 27/13/7% 全部漏过,
全模型 163 对噪声;改度判据后图框 deg=35/25/23 vs 其余 deg<=3,分离干净)
- cmakelists.txt + 两个 mcp_config.json 注册(28 工具)
agent 侧(Python):
- cad_tools.READ_ONLY_TOOLS += find_collisions(受控子循环可调用)
- checks.check_collisions + run_deterministic_checks(受 CHECK_COLLISIONS 开关,默认关)
- config += CHECK_COLLISIONS=False / COLLISION_MIN_OVERLAP=0.5
- checklist.py / review_checklist.json += 「干涉/碰撞」类别(high)+ 提示词协议
(先 find_collisions 拿候选 → inspect_region 目视确认;AABB 相交 != 真干涉)
验证:
- verify_collisions.py 17/17 PASS:全模型候选 163→80(全部 ratio=0.000),
min_overlap=0.5 → 0 对;逐图框 0 对;narrow top-5 中 4 条 exact=true;
--inject 注入深重叠矩形报出 ratio=0.902 并清理 2/2
- pytest 355 passed(新增 12 项)
- 端到端:LLM 主动调用 find_collisions{min_overlap:0.2,narrow:true,window:<图框>},未误报
211 lines
7.5 KiB
Python
211 lines
7.5 KiB
Python
"""确定性检查:MCP 工具(find_zero_length / find_duplicate_entities / find_collisions)
|
||
+ 纯 Python 派生。
|
||
|
||
产出的 issue 带 `source="deterministic"`,其 handle 来自工具/数据本身,
|
||
因此被视为**可信**,可直接进入批注链路,不依赖 LLM 回忆。
|
||
|
||
注意:`find_zero_length` / `find_duplicate_entities` 的 `window` 参数在 C++ 侧
|
||
(`parseCommonQuery`)**实际生效**,只是 JSON schema 未声明——Python 侧显式传参即可。
|
||
"""
|
||
|
||
from . import config
|
||
from .mcp_client import McpError, McpToolError, result_json
|
||
|
||
|
||
def make_issue(category, severity, message, *, handle=None, handles=None,
|
||
source="deterministic"):
|
||
"""构造统一 issue(`verified` 由 findings 层补齐)。"""
|
||
issue = {
|
||
"category": category,
|
||
"severity": severity,
|
||
"message": message,
|
||
"source": source,
|
||
}
|
||
if handle:
|
||
issue["handle"] = handle
|
||
if handles:
|
||
issue["handles"] = list(handles)
|
||
return issue
|
||
|
||
|
||
def _iter_items(envelope):
|
||
"""健壮迭代 items(`result_json` 解析失败会返回原始字符串)。"""
|
||
if not isinstance(envelope, dict):
|
||
return []
|
||
items = envelope.get("items")
|
||
if not isinstance(items, list):
|
||
return []
|
||
return [i for i in items if isinstance(i, dict)]
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# MCP 检查
|
||
# ---------------------------------------------------------------------------
|
||
def check_zero_length(ctx, window, *, tolerance, limit, log=print):
|
||
"""find_zero_length(window) → 逐条零长度实体转 issue。"""
|
||
try:
|
||
resp = ctx.tools.call(
|
||
"find_zero_length",
|
||
{"window": window, "tolerance": tolerance, "limit": limit},
|
||
)
|
||
except (McpError, McpToolError) as exc:
|
||
log(f" [确定性] find_zero_length 失败: {exc}")
|
||
return []
|
||
|
||
out = []
|
||
for item in _iter_items(result_json(resp, {})):
|
||
handle = item.get("handle")
|
||
if not handle:
|
||
continue
|
||
out.append(
|
||
make_issue(
|
||
"几何", "medium",
|
||
f"零长度/退化实体(类型 {item.get('type')},长度 {item.get('length')})",
|
||
handle=handle,
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def check_duplicate_entities(ctx, window, *, tolerance, group_limit, log=print):
|
||
"""find_duplicate_entities(window) → 每个重复组一条 issue。
|
||
|
||
`limit` 的语义是「最大重复组数」(非条目数)。一组重复是一个问题,
|
||
故只产出一条 issue,主 handle 取组内首个,全部 handle 放进 `handles`。
|
||
"""
|
||
try:
|
||
resp = ctx.tools.call(
|
||
"find_duplicate_entities",
|
||
{"window": window, "tolerance": tolerance, "limit": group_limit},
|
||
)
|
||
except (McpError, McpToolError) as exc:
|
||
log(f" [确定性] find_duplicate_entities 失败: {exc}")
|
||
return []
|
||
|
||
env = result_json(resp, {})
|
||
groups = env.get("groups") if isinstance(env, dict) else None
|
||
out = []
|
||
for group in groups or []:
|
||
if not isinstance(group, dict):
|
||
continue
|
||
handles = [h for h in (group.get("handles") or []) if h]
|
||
if not handles:
|
||
continue
|
||
out.append(
|
||
make_issue(
|
||
"几何", "low",
|
||
f"重复/重叠实体组(类型 {group.get('type')},共 {len(handles)} 个几何相同)",
|
||
handle=handles[0],
|
||
handles=handles,
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
def check_collisions(ctx, window, *, min_overlap, limit, log=print):
|
||
"""find_collisions(window) → 每条「包围盒干涉候选」转 issue。
|
||
|
||
**候选**语义:AABB 相交不等于真干涉(L 形布局、相邻管段接口、标注引线跨越
|
||
图元都会相交),故严重度取 medium、category 单列「干涉」,由报告层 / 人复核。
|
||
重叠比 `ratio` 写进 message,便于按可疑程度排序与人工筛选。
|
||
"""
|
||
try:
|
||
resp = ctx.tools.call(
|
||
"find_collisions",
|
||
{"window": window, "min_overlap": min_overlap, "limit": limit},
|
||
)
|
||
except (McpError, McpToolError) as exc:
|
||
log(f" [确定性] find_collisions 失败: {exc}")
|
||
return []
|
||
|
||
out = []
|
||
for item in _iter_items(result_json(resp, {})):
|
||
a = item.get("a") if isinstance(item.get("a"), dict) else {}
|
||
b = item.get("b") if isinstance(item.get("b"), dict) else {}
|
||
ha, hb = a.get("handle"), b.get("handle")
|
||
if not ha or not hb:
|
||
continue
|
||
ov = item.get("overlap") if isinstance(item.get("overlap"), dict) else {}
|
||
ratio = ov.get("ratio")
|
||
ratio_txt = f"{ratio:.2f}" if isinstance(ratio, (int, float)) else "?"
|
||
out.append(
|
||
make_issue(
|
||
"干涉", "medium",
|
||
f"包围盒干涉候选({a.get('type')}/{ha} × {b.get('type')}/{hb},"
|
||
f"重叠比 {ratio_txt},同层={item.get('same_layer')})",
|
||
handle=ha,
|
||
handles=[ha, hb],
|
||
)
|
||
)
|
||
return out
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 纯 Python 派生(零额外 MCP 往返)
|
||
# ---------------------------------------------------------------------------
|
||
def _empty_texts(evidence):
|
||
out = []
|
||
for item in _iter_items(evidence.get("texts")):
|
||
content = item.get("content")
|
||
if content is None or str(content).strip() == "":
|
||
out.append(
|
||
make_issue("文字", "medium", "存在空文字或仅含空格的文字",
|
||
handle=item.get("handle"))
|
||
)
|
||
return out
|
||
|
||
|
||
def _unclosed_polylines(evidence):
|
||
out = []
|
||
for item in _iter_items(evidence.get("polylines")):
|
||
if item.get("vertex_count", 0) >= 3 and item.get("closed") is False:
|
||
out.append(
|
||
make_issue("几何", "low",
|
||
"多段线顶点≥3但未闭合,可能是应当闭合的轮廓",
|
||
handle=item.get("handle"))
|
||
)
|
||
return out
|
||
|
||
|
||
def derive_from_evidence(evidence, *, check_unclosed=True):
|
||
"""从已采集证据里做零成本派生检查。"""
|
||
issues = _empty_texts(evidence)
|
||
if check_unclosed:
|
||
issues += _unclosed_polylines(evidence)
|
||
return issues
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 入口
|
||
# ---------------------------------------------------------------------------
|
||
def run_deterministic_checks(ctx, evidence, *, log=print):
|
||
"""对单个图框跑全部确定性检查,返回 issue 列表。
|
||
|
||
任何单项 MCP 失败都只记录并跳过,不抛出(不拖垮该图框)。
|
||
"""
|
||
issues = derive_from_evidence(
|
||
evidence, check_unclosed=config.CHECK_UNCLOSED_POLYLINES
|
||
)
|
||
window = evidence.get("window")
|
||
if window:
|
||
issues += check_zero_length(
|
||
ctx, window,
|
||
tolerance=config.ZERO_LENGTH_TOLERANCE,
|
||
limit=config.FRAME_ENTITY_LIMIT,
|
||
log=log,
|
||
)
|
||
issues += check_duplicate_entities(
|
||
ctx, window,
|
||
tolerance=config.DUP_TOLERANCE,
|
||
group_limit=config.DUP_GROUP_LIMIT,
|
||
log=log,
|
||
)
|
||
if config.CHECK_COLLISIONS:
|
||
issues += check_collisions(
|
||
ctx, window,
|
||
min_overlap=config.COLLISION_MIN_OVERLAP,
|
||
limit=config.FRAME_ENTITY_LIMIT,
|
||
log=log,
|
||
)
|
||
return issues
|