diff --git a/claude_bridge.py b/claude_bridge.py index cc24a11..90da1e9 100644 --- a/claude_bridge.py +++ b/claude_bridge.py @@ -193,6 +193,8 @@ async def stream_claude( smeta_gge_tools_path = APP_DIR / "gge_tools.py" smeta_gge_deep_path = APP_DIR / "gge_deep.py" smeta_corpus_path = APP_DIR / "real_corpus.py" + smeta_verify_path = APP_DIR / "estimate_verify.py" + smeta_codeval_path = APP_DIR / "code_validator.py" smeta_corpus_data = APP_DIR / "data" / "real_corpus" smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json" mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists() @@ -216,9 +218,11 @@ async def stream_claude( "mcp__smeta__apply_pukts_to_registry," "mcp__smeta__parse_gge_archive," "mcp__smeta__parse_gge_file," + "mcp__smeta__verify_estimate_file," "mcp__smeta__update_xlsx_cells," "mcp__smeta__find_in_real_estimates," "mcp__smeta__find_ka_price," + "mcp__smeta__find_expertise_remarks," "mcp__smeta__find_in_vor"), ] if mcp_available: @@ -248,6 +252,8 @@ async def stream_claude( "-v", f"{smeta_mcp_path.resolve()}:/app/smeta_mcp.py:ro", "-v", f"{smeta_complaints_path.resolve()}:/app/complaints.py:ro", "-v", f"{smeta_gge_tools_path.resolve()}:/app/gge_tools.py:ro", + "-v", f"{smeta_verify_path.resolve()}:/app/estimate_verify.py:ro", + "-v", f"{smeta_codeval_path.resolve()}:/app/code_validator.py:ro", "-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro", ]) if corpus_available: diff --git a/estimate_verify.py b/estimate_verify.py index 5fbde9c..0c8e7ee 100644 --- a/estimate_verify.py +++ b/estimate_verify.py @@ -142,6 +142,24 @@ def verify(est: dict, tol: float = _TOL) -> dict: return {"ok": not errors, "errors": errors, "warnings": warnings, "checked": checked} +def verify_gge_summary(totals: dict, tol: float = _TOL) -> dict: + """Самосогласованность Summary из gge_tools.parse_gge_file — ТОЧНЫЕ тождества, + реально держащиеся на сданных .gge (калибровано: держится до копейки): + ФОТ (Salary) == ЗП рабочих (WorkersSalary) + ЗП машинистов (MachinistSalary). + Реконструкция полного итога из позиций .gge НЕ делается (материалы/лимитированные + живут отдельно — Σпозиций≠Total); полная арифметика — на этапе составления движком.""" + errors: list[dict] = [] + checked = 0 + ktol = round(tol * 100) + s, ws, ms = totals.get("Salary"), totals.get("WorkersSalary"), totals.get("MachinistSalary") + if None not in (s, ws, ms): + checked += 1 + if abs(_k(s) - _k(ws + ms)) > ktol: + errors.append({"rule": "ФОТ ≠ ЗП рабочих + ЗП машинистов", + "expected": _rr(ws + ms), "actual": _rr(s)}) + return {"errors": errors, "checked": checked} + + def from_gge_parsed(parsed: dict) -> dict: """Маппинг выхода gge_tools.parse_gge_file → нормализованная схема verify. ВНИМАНИЕ: parse_gge_file часто НЕ даёт стоимость позиции (деньги в Totals/Current, diff --git a/main.py b/main.py index 80bfcf2..d1eb358 100644 --- a/main.py +++ b/main.py @@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-17d" +APP_VERSION = "2026-07-17e" # Audit: path → action name mapping _AUDIT_MAP = [ diff --git a/smeta_mcp.py b/smeta_mcp.py index 4513247..2745a81 100644 --- a/smeta_mcp.py +++ b/smeta_mcp.py @@ -310,6 +310,39 @@ def tool_parse_gge_file(*, filename: str, max_positions: int = 30) -> dict: return data +def tool_verify_estimate_file(*, filename: str) -> dict: + """Детерминированная проверка загруженной .gge сметы на сходимость (fail-loud): + существование кодов расценок, самосогласованность итогов (ФОТ=ЗПраб+ЗПмаш), + возможные дубли. Возвращает errors/warnings с числами «ожидалось/фактически». + Полную попозиционную арифметику даёт движок при СОСТАВЛЕНИИ сметы (материалы/ + лимитированные в .gge живут отдельно, реконструкции итога из позиций тут нет).""" + user, tab = _user_tab() + work_dir = _work_dir(user, tab) + candidate = work_dir / filename + if not candidate.exists(): + matches = list(work_dir.rglob(Path(filename).name)) + if not matches: + return {"error": f"«{filename}» не найден в {user}/{tab}"} + candidate = matches[0] + if candidate.suffix.lower() != ".gge": + return {"error": f"проверка сметы пока для .gge (получен {candidate.suffix or '?'})"} + from gge_tools import parse_gge_file + import estimate_verify as ev + parsed = parse_gge_file(candidate) + if "error" in parsed: + return parsed + if not parsed.get("positions"): + return {"error": "не распознано как смета с позициями (возможно ВОР/ОСР/другая схема)"} + r = ev.verify(ev.from_gge_parsed(parsed)) + sm = ev.verify_gge_summary(parsed.get("totals") or {}) + r["errors"].extend(sm["errors"]) + r["ok"] = not r["errors"] + r["checked"] += sm["checked"] + r["file"] = candidate.name + r["positions_count"] = len(parsed["positions"]) + return r + + def tool_parse_gsfx_file(*, filename: str, max_positions: int = 30) -> dict: """Распарсить одну .gsfx смету (ГРАНД-Смета, новый формат). filename — относительный путь в work_dir или внутри распакованной папки. @@ -581,6 +614,21 @@ TOOLS: dict[str, dict] = { "required": ["filename"], }, }, + "verify_estimate_file": { + "fn": tool_verify_estimate_file, + "description": ( + "Детерминированная проверка загруженной .gge сметы на сходимость: " + "существование кодов расценок, самосогласованность итогов, дубли. " + "Вызывай при просьбе «проверь смету / сходится ли итог / нет ли ошибок»." + ), + "inputSchema": { + "type": "object", + "properties": { + "filename": {"type": "string", "description": "Имя загруженного .gge файла"}, + }, + "required": ["filename"], + }, + }, "parse_gsfx_file": { "fn": tool_parse_gsfx_file, "description": ( diff --git a/tests/fixtures/broken_totals.gge b/tests/fixtures/broken_totals.gge new file mode 100644 index 0000000..e5e24cf --- /dev/null +++ b/tests/fixtures/broken_totals.gge @@ -0,0 +1,24 @@ + + + + ЛСР-99-01 + Тестовая смета (битый итог + несуществующий код) + + + 100.00 + 60.00 + 30.00 + 1000.00 + + + + + 99-01-001-01 + Несуществующая расценка + 2 + м3 + 500 + + + + diff --git a/tests/test_verify_tool.py b/tests/test_verify_tool.py new file mode 100644 index 0000000..f76f79c --- /dev/null +++ b/tests/test_verify_tool.py @@ -0,0 +1,45 @@ +"""Срез 2.2: инструмент verify_estimate_file (проверка загруженной .gge). + +Гоняет tool_verify_estimate_file на фикстуре с несуществующим кодом (99-…) и +рассогласованным ФОТ (Salary≠ЗПраб+ЗПмаш). SMETA_WORK_DIR указывает на fixtures. +""" +import os +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +_FIX = Path(__file__).resolve().parent / "fixtures" + + +def _tool(): + os.environ["SMETA_WORK_DIR"] = str(_FIX) + import importlib + import smeta_mcp + importlib.reload(smeta_mcp) # чтобы _work_dir увидел SMETA_WORK_DIR + return smeta_mcp + + +def test_broken_gge_reports_errors(): + sm = _tool() + r = sm.tool_verify_estimate_file(filename="broken_totals.gge") + assert "error" not in r, r + assert r["ok"] is False + rules = " ".join(e["rule"] for e in r["errors"]) + assert "не существует" in rules # код 99-01-001-01 + assert "ФОТ ≠" in rules # 100 ≠ 60+30 + fot = [e for e in r["errors"] if "ФОТ ≠" in e["rule"]][0] + assert fot["expected"] == 90.0 and fot["actual"] == 100.0 + + +def test_missing_file(): + sm = _tool() + r = sm.tool_verify_estimate_file(filename="net_takogo.gge") + assert "error" in r + + +def test_non_gge_rejected(): + sm = _tool() + (_FIX / "dummy.txt").write_text("x", encoding="utf-8") + r = sm.tool_verify_estimate_file(filename="dummy.txt") + assert "error" in r and ".gge" in r["error"] + (_FIX / "dummy.txt").unlink()