feat: универсальные MCP-tools для .gge архивов + clarification-first алгоритм

Перенос алгоритма обработки смет из чат-сессии в dev-чат smeta-web:
агент сам уточняет задачу у пользователя и собирает решение из
универсальных tools, без специальных скриптов под конкретный сценарий.

- gge_tools.py: парсер архивов .gge (extract_archive с cp866-decoding и
  path-traversal guard, parse_gge_file для XML смет ГГЭ, index_gge_directory
  с записью полного индекса в JSON, update_xlsx_cells для массовой записи).
- smeta_mcp.py: 3 новых tool — parse_gge_archive, parse_gge_file,
  update_xlsx_cells. Универсальные, не привязаны к конкретной задаче
  (ИГИ/ТС, сводная таблица и т.д.).
- claude_project_instructions.md: явный алгоритм «понимание → уточнения
  → подтверждение → выполнение → проверка» вместо одной строки
  «уточняй». Описание новых tools для агента.
- claude_bridge.py: монтирование gge_tools.py в /app, новые tools в
  --allowedTools.

Тест: JSON-RPC stdio + прямой вызов tool-функций на 1989 .gge
(1750 уникальных кодов, 1082 с «разработка грунта», 821 с
EstimatePrice/Summary/Transport > 0). Эталон ЛСР-04-01-0-00-01:
has_excavation=True, has_transport_summary=True. update_xlsx_cells
записал E=ИГИ, F=ТС в первую строку кода. Regression: read_xlsx_sheet
не сломан.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-05-06 21:01:37 +10:00
co-authored by Claude Opus 4.7
parent f763d22263
commit 855e2f2eef
4 changed files with 459 additions and 2 deletions
+258
View File
@@ -0,0 +1,258 @@
"""gge_tools — работа с архивами .gge (XML смет ГГЭ) и xlsx-реестрами.
Универсальный, без привязки к конкретной задаче (ИГИ/ТС). Чат-агент
сам комбинирует tools для нужного сценария.
Зависимости: openpyxl + stdlib (zipfile, xml.etree, json). Без plotly,
sentence-transformers и т.п. — работает в sandbox-контейнере.
"""
from __future__ import annotations
import json
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path
def _decode_zip_name(info: zipfile.ZipInfo) -> str:
"""Python 3 zipfile авто-декодирует cp437 если флаг UTF-8 (0x800) не задан.
Для имён от Windows-архиваторов нужно re-encode→re-decode как cp866."""
if info.flag_bits & 0x800:
return info.filename
try:
return info.filename.encode('cp437').decode('cp866')
except UnicodeError:
return info.filename
def extract_archive(zip_path: Path, target_dir: Path) -> dict:
"""Распаковать zip с .gge файлами в target_dir. Сохраняет древовидную
структуру внутри архива. Корректно декодирует cp866-имена.
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
"""
import os
target_dir.mkdir(parents=True, exist_ok=True)
target_resolved = target_dir.resolve()
total = gge = skipped = 0
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
if info.is_dir():
continue
total += 1
name = _decode_zip_name(info).replace('\\', '/')
# path traversal guard
out = (target_dir / name).resolve()
try:
out.relative_to(target_resolved)
except ValueError:
skipped += 1
continue
out.parent.mkdir(parents=True, exist_ok=True)
try:
with z.open(info) as src, open(out, 'wb') as dst:
while chunk := src.read(64 * 1024):
dst.write(chunk)
if name.lower().endswith('.gge'):
gge += 1
except Exception:
skipped += 1
return {
'target': str(target_dir),
'total_files': total,
'gge_files': gge,
'skipped': skipped,
}
def parse_gge_file(path: Path) -> dict:
"""Извлечь данные одной сметы из .gge XML.
Возвращает: code, name, schema_kind ('local' | 'object' | 'unknown'),
has_excavation, has_transport_summary, totals (всё что есть в
EstimatePrice/Summary), positions (список dict с name/code/quantity/
unit/price_total из <Cost>; для перевозочных позиций <Transport>
тоже включаем).
"""
try:
tree = ET.parse(str(path))
except (ET.ParseError, OSError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
root = tree.getroot()
schema_loc = root.attrib.get(
'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation', '')
if 'LocalEstimate' in schema_loc:
schema_kind = 'local'
elif 'ObjectEstimate' in schema_loc:
schema_kind = 'object'
else:
schema_kind = 'unknown'
code = (root.findtext('.//Estimate/Num') or '').strip()
name = (root.findtext('.//Estimate/Name') or '').strip()
# Totals: EstimatePrice/Summary
totals: dict[str, float] = {}
summary = root.find('.//EstimatePrice/Summary')
if summary is not None:
for child in summary:
if len(list(child)) > 0:
# Materials/Total etc.
for sub in child:
if sub.text:
try:
totals[f'{child.tag}.{sub.tag}'] = float(sub.text.strip())
except ValueError:
pass
elif child.text:
try:
totals[child.tag] = float(child.text.strip())
except ValueError:
pass
# Positions: Item/Cost (work) + Item/Transport (carrier line)
positions: list[dict] = []
has_excavation = False
for it in root.iter('Item'):
for kind_tag in ('Cost', 'Transport'):
node = it.find(kind_tag)
if node is None:
continue
pname = (node.findtext('Name') or '').strip()
if not pname:
continue
pcode = (node.findtext('Code') or '').strip()
qty = node.findtext('Quantity') or ''
unit = (node.findtext('Unit') or '').strip()
ptcur = node.findtext('PriceTotalCur') or ''
direct = node.findtext('.//Totals/Current/Direct') or ''
try: qty_f = float(qty) if qty else 0.0
except ValueError: qty_f = 0.0
try: pt_f = float(ptcur) if ptcur else 0.0
except ValueError: pt_f = 0.0
try: dir_f = float(direct) if direct else 0.0
except ValueError: dir_f = 0.0
positions.append({
'kind': kind_tag.lower(), # 'cost' | 'transport'
'name': pname,
'code': pcode,
'quantity': qty_f,
'unit': unit,
'price_total_cur': pt_f,
'direct': dir_f,
})
if 'разработка грунта' in pname.lower():
has_excavation = True
has_transport_summary = (totals.get('Transport', 0.0) > 0)
return {
'path': str(path),
'code': code,
'name': name,
'schema_kind': schema_kind,
'has_excavation': has_excavation,
'has_transport_summary': has_transport_summary,
'totals': totals,
'positions': positions,
}
def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict:
"""Пройти все .gge в dir_path рекурсивно, распарсить.
Returns: {by_code: {code: {has_excavation, has_transport_summary,
name, total_rub, schema_kind, path}}, summary: {...}, parse_errors: N}.
Если save_index_to задан — пишет полный индекс (с positions) в JSON.
Возврат компактнее (без positions), чтобы влез в MCP-ответ.
"""
files = sorted(p for p in dir_path.rglob('*.gge'))
by_code: dict[str, dict] = {}
full_index: dict[str, dict] = {}
parse_errors = 0
schemas: dict[str, int] = {}
excav = transp = 0
rub_sum = 0.0
for f in files:
data = parse_gge_file(f)
if 'error' in data:
parse_errors += 1
continue
code = data['code']
if not code:
continue
# Сводный (компактный) вид без positions для MCP-ответа.
compact = {
'name': data['name'],
'schema_kind': data['schema_kind'],
'has_excavation': data['has_excavation'],
'has_transport_summary': data['has_transport_summary'],
'total_rub': data['totals'].get('Total') or data['totals'].get('Price') or 0.0,
'transport_rub': data['totals'].get('Transport', 0.0),
'path': data['path'],
}
prev = by_code.get(code)
if prev is None or compact['total_rub'] > prev['total_rub']:
by_code[code] = compact
full_index[code] = data
schemas[data['schema_kind']] = schemas.get(data['schema_kind'], 0) + 1
if data['has_excavation']:
excav += 1
if data['has_transport_summary']:
transp += 1
rub_sum += compact['total_rub']
summary = {
'files_total': len(files),
'parse_errors': parse_errors,
'unique_codes': len(by_code),
'schemas': schemas,
'with_excavation': excav,
'with_transport_summary': transp,
'sum_total_rub': rub_sum,
}
if save_index_to is not None:
save_index_to.write_text(
json.dumps({'by_code': full_index, 'summary': summary},
ensure_ascii=False),
encoding='utf-8',
)
return {'by_code': by_code, 'summary': summary}
def update_xlsx_cells(src_path: Path, out_path: Path, sheet: str,
updates: list[dict]) -> dict:
"""Записать список ячеек в xlsx.
updates: [{"row": 5, "col": "E" | 5, "value": "ИГИ"}, ...]
Сохраняет копию в out_path. Не трогает остальной контент книги.
"""
import openpyxl
wb = openpyxl.load_workbook(str(src_path))
if sheet not in wb.sheetnames:
return {'error': f'Лист «{sheet}» не найден',
'available_sheets': wb.sheetnames}
ws = wb[sheet]
written = 0
skipped = 0
for u in updates:
try:
row = int(u['row'])
col = u['col']
if isinstance(col, str):
col_idx = openpyxl.utils.column_index_from_string(col)
else:
col_idx = int(col)
ws.cell(row, col_idx).value = u.get('value')
written += 1
except (KeyError, ValueError, TypeError):
skipped += 1
wb.save(str(out_path))
return {
'output_path': str(out_path),
'sheet': sheet,
'cells_written': written,
'cells_skipped': skipped,
}