feat(срез 2.2): инструмент verify_estimate_file (проверь смету) + агентный путь; bump 2026-07-17e
smeta_mcp.tool_verify_estimate_file: parse .gge → estimate_verify + verify_gge_summary (ФОТ=ЗПраб+ЗПмаш, точное тождество Summary). Калибровка показала: реконструкция итога из позиций .gge невозможна (материалы отдельно) — честно проверяем коды+самосогласов.+дубли. claude_bridge: +verify_estimate_file и +find_expertise_remarks в allowedTools, mount estimate_verify.py+code_validator.py в Docker. Фикстура broken_totals.gge, 3 passed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -193,6 +193,8 @@ async def stream_claude(
|
|||||||
smeta_gge_tools_path = APP_DIR / "gge_tools.py"
|
smeta_gge_tools_path = APP_DIR / "gge_tools.py"
|
||||||
smeta_gge_deep_path = APP_DIR / "gge_deep.py"
|
smeta_gge_deep_path = APP_DIR / "gge_deep.py"
|
||||||
smeta_corpus_path = APP_DIR / "real_corpus.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_corpus_data = APP_DIR / "data" / "real_corpus"
|
||||||
smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json"
|
smeta_mcp_config = APP_DIR / "sandbox" / "mcp_config.json"
|
||||||
mcp_available = (smeta_mcp_path.exists() and smeta_complaints_path.exists()
|
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__apply_pukts_to_registry,"
|
||||||
"mcp__smeta__parse_gge_archive,"
|
"mcp__smeta__parse_gge_archive,"
|
||||||
"mcp__smeta__parse_gge_file,"
|
"mcp__smeta__parse_gge_file,"
|
||||||
|
"mcp__smeta__verify_estimate_file,"
|
||||||
"mcp__smeta__update_xlsx_cells,"
|
"mcp__smeta__update_xlsx_cells,"
|
||||||
"mcp__smeta__find_in_real_estimates,"
|
"mcp__smeta__find_in_real_estimates,"
|
||||||
"mcp__smeta__find_ka_price,"
|
"mcp__smeta__find_ka_price,"
|
||||||
|
"mcp__smeta__find_expertise_remarks,"
|
||||||
"mcp__smeta__find_in_vor"),
|
"mcp__smeta__find_in_vor"),
|
||||||
]
|
]
|
||||||
if mcp_available:
|
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_mcp_path.resolve()}:/app/smeta_mcp.py:ro",
|
||||||
"-v", f"{smeta_complaints_path.resolve()}:/app/complaints.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_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",
|
"-v", f"{smeta_mcp_config.resolve()}:/app/mcp_config.json:ro",
|
||||||
])
|
])
|
||||||
if corpus_available:
|
if corpus_available:
|
||||||
|
|||||||
@@ -142,6 +142,24 @@ def verify(est: dict, tol: float = _TOL) -> dict:
|
|||||||
return {"ok": not errors, "errors": errors, "warnings": warnings, "checked": checked}
|
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:
|
def from_gge_parsed(parsed: dict) -> dict:
|
||||||
"""Маппинг выхода gge_tools.parse_gge_file → нормализованная схема verify.
|
"""Маппинг выхода gge_tools.parse_gge_file → нормализованная схема verify.
|
||||||
ВНИМАНИЕ: parse_gge_file часто НЕ даёт стоимость позиции (деньги в Totals/Current,
|
ВНИМАНИЕ: parse_gge_file часто НЕ даёт стоимость позиции (деньги в Totals/Current,
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ MAX_MESSAGE_LEN = 10_000
|
|||||||
|
|
||||||
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
# ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква).
|
||||||
# Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version).
|
# Фронт берёт её через 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: path → action name mapping
|
||||||
_AUDIT_MAP = [
|
_AUDIT_MAP = [
|
||||||
|
|||||||
@@ -310,6 +310,39 @@ def tool_parse_gge_file(*, filename: str, max_positions: int = 30) -> dict:
|
|||||||
return data
|
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:
|
def tool_parse_gsfx_file(*, filename: str, max_positions: int = 30) -> dict:
|
||||||
"""Распарсить одну .gsfx смету (ГРАНД-Смета, новый формат). filename —
|
"""Распарсить одну .gsfx смету (ГРАНД-Смета, новый формат). filename —
|
||||||
относительный путь в work_dir или внутри распакованной папки.
|
относительный путь в work_dir или внутри распакованной папки.
|
||||||
@@ -581,6 +614,21 @@ TOOLS: dict[str, dict] = {
|
|||||||
"required": ["filename"],
|
"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": {
|
"parse_gsfx_file": {
|
||||||
"fn": tool_parse_gsfx_file,
|
"fn": tool_parse_gsfx_file,
|
||||||
"description": (
|
"description": (
|
||||||
|
|||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="LocalEstimate.xsd">
|
||||||
|
<Estimate>
|
||||||
|
<Num>ЛСР-99-01</Num>
|
||||||
|
<Name>Тестовая смета (битый итог + несуществующий код)</Name>
|
||||||
|
<EstimatePrice>
|
||||||
|
<Summary>
|
||||||
|
<Salary>100.00</Salary>
|
||||||
|
<WorkersSalary>60.00</WorkersSalary>
|
||||||
|
<MachinistSalary>30.00</MachinistSalary>
|
||||||
|
<Total>1000.00</Total>
|
||||||
|
</Summary>
|
||||||
|
</EstimatePrice>
|
||||||
|
<Item>
|
||||||
|
<Cost>
|
||||||
|
<Code>99-01-001-01</Code>
|
||||||
|
<Name>Несуществующая расценка</Name>
|
||||||
|
<Quantity>2</Quantity>
|
||||||
|
<Unit>м3</Unit>
|
||||||
|
<PriceTotalCur>500</PriceTotalCur>
|
||||||
|
</Cost>
|
||||||
|
</Item>
|
||||||
|
</Estimate>
|
||||||
|
</Construction>
|
||||||
@@ -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()
|
||||||
Reference in New Issue
Block a user