fix: правки по Fable-ревью (P0 GLM-маскировка + корректность + покрытие)
Финальный Fable-ревью (2 адверсариальных агента) → фиксы: - P0: GLM-путь слал сырую ошибку юзеру и в историю — добавлена сигнатура «ошибка glm api» в error_mask → центральная маскировка ловит оба движка. Тест unit + интеграционный (кейс D). - .doc: catdoc -d utf-8 + guard на сплошные '?' (защита sandbox-Latin-1 от кириллицы-мусора). - _read_work_dir_files: рекурсия (файлы распакованных архивов в подпапках были невидимы) + catch-all для .rar/.7z/.ges (молчаливый пропуск → явное «не читается»). - .arp-ветка: проверка error перед positions (был KeyError). - .xls: общий xls_cell_str (числа 5→'5', даты→dd.mm.yyyy вместо серийника); MCP-tool — ошибка на несуществующий лист вместо молчаливого фолбэка на лист 0. - zip-листинг: единый _decode_zip_name (листинг и распаковка не расходятся на macOS-zip). - extract_archive: лимит 5ГБ/50k файлов (zip-бомба). - upload-ошибка: список форматов из ALLOWED_EXTENSIONS (был устаревший хардкод). - defusedxml в requirements+Dockerfile+хост (XXE-hardening; expat и так защищал). - Тесты: фиктивная .docx-проверка → явная проверка ТАБЛИЦ; .arp-числа заякорены; пер-сигнатурное покрытие error_mask; аудит agent_error проверяется. APP_VERSION→2026-07-15g. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+34
-23
@@ -214,6 +214,7 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
book = xlrd.open_workbook(str(path))
|
||||
except Exception:
|
||||
return None
|
||||
from gge_tools import xls_cell_str
|
||||
out: list[str] = []
|
||||
used = 0
|
||||
for sh in book.sheets():
|
||||
@@ -222,8 +223,8 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
out.append(f"\n### Файл: {path.name}, Лист: {sh.name} "
|
||||
f"(строк: {sh.nrows}, колонок: {sh.ncols})")
|
||||
for r in range(sh.nrows):
|
||||
vals = [str(sh.cell_value(r, c))[:300] for c in range(sh.ncols)
|
||||
if str(sh.cell_value(r, c)).strip()]
|
||||
vals = [v[:300] for c in range(sh.ncols)
|
||||
if (v := xls_cell_str(sh.cell(r, c), book.datemode)).strip()]
|
||||
if not vals:
|
||||
continue
|
||||
line = f"стр{r + 1}: " + " | ".join(vals)
|
||||
@@ -235,18 +236,23 @@ def _read_xls_via_xlrd(path: Path, max_chars: int) -> str | None:
|
||||
|
||||
|
||||
def _read_doc_via_catdoc(path: Path) -> str | None:
|
||||
"""Старый .doc (OLE2) — python-docx не умеет; catdoc → текст. None если нет catdoc."""
|
||||
"""Старый .doc (OLE2) — python-docx не умеет; catdoc → текст. None если нет catdoc.
|
||||
`-d utf-8`: по умолчанию /etc/catdocrc = Latin-1, который НЕ кодирует кириллицу →
|
||||
русский .doc превращается в '?'. Сплошные '?' = битая кодировка → честный None,
|
||||
а не выдавать мусор за содержимое (выдуманное хуже пропуска)."""
|
||||
import shutil
|
||||
import subprocess
|
||||
if not shutil.which("catdoc"):
|
||||
return None
|
||||
try:
|
||||
r = subprocess.run(["catdoc", "-w", str(path)],
|
||||
r = subprocess.run(["catdoc", "-w", "-d", "utf-8", str(path)],
|
||||
capture_output=True, timeout=60)
|
||||
text = r.stdout.decode("utf-8", "replace").strip()
|
||||
return text or None
|
||||
except Exception:
|
||||
return None
|
||||
if not text or text.count("?") > len(text) * 0.3:
|
||||
return None
|
||||
return text
|
||||
|
||||
|
||||
def _read_docx(path: Path, max_chars: int) -> str:
|
||||
@@ -290,9 +296,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
"""Read files from work directory and return text summary for LLM context."""
|
||||
parts = []
|
||||
total = 0
|
||||
for f in sorted(work_dir.iterdir()):
|
||||
if f.name.startswith(".") or not f.is_file():
|
||||
continue
|
||||
# Рекурсивно: файлы распакованных архивов лежат в подпапках (<stem>_extracted/…),
|
||||
# иначе они невидимы модели. Кап на число файлов — защита от огромных распаковок.
|
||||
all_files = [f for f in sorted(work_dir.rglob("*"))
|
||||
if f.is_file() and not f.name.startswith(".")]
|
||||
for f in all_files[:250]:
|
||||
ext = f.suffix.lower()
|
||||
try:
|
||||
if ext in (".xlsx", ".xlsm"):
|
||||
@@ -376,12 +384,15 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
elif ext in (".arp", ".arps"):
|
||||
from gge_tools import parse_arp_file
|
||||
a = parse_arp_file(f)
|
||||
poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['unit']} | {p['total']} руб"
|
||||
for p in a["positions"][:40])
|
||||
chunk = (f"\n### Смета .arp: {f.name}\nШифр: {a['code']} | {a['name']}\n"
|
||||
f"Итог: {a['total']} руб | позиций: {a['positions_count']}\n{poss}")
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
if "error" in a:
|
||||
parts.append(f"\n### Файл: {f.name} (.arp, ошибка: {a['error']})")
|
||||
else:
|
||||
poss = "\n".join(f" {p['code']} | {p['name'][:80]} | {p['unit']} | {p['total']} руб"
|
||||
for p in a["positions"][:40])
|
||||
chunk = (f"\n### Смета .arp: {f.name}\nШифр: {a['code']} | {a['name']}\n"
|
||||
f"Итог: {a['total']} руб | позиций: {a['positions_count']}\n{poss}")
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
elif ext in _UNSUPPORTED_SMETA:
|
||||
parts.append(f"\n### Файл: {f.name} (формат {ext} проприетарный, "
|
||||
f"автоматически не читается — экспортируйте смету в АРПС (.arp) или Excel)")
|
||||
@@ -428,16 +439,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
lines = []
|
||||
MAX_LISTED = 100
|
||||
total_size = 0
|
||||
from gge_tools import _decode_zip_name
|
||||
for info in infos:
|
||||
# Декодирование имён: zipfile отдаёт всё как cp437, если флаг
|
||||
# UTF-8 (0x800) не выставлен. Для архивов из Windows имена
|
||||
# обычно в cp866 — пытаемся восстановить.
|
||||
name = info.filename
|
||||
if not (info.flag_bits & 0x800):
|
||||
try:
|
||||
name = name.encode("cp437").decode("cp866")
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
pass
|
||||
# Единый декодер имён (utf-8→cp866, без replacement) — как при
|
||||
# распаковке, иначе листинг и распаковка расходятся на macOS-zip.
|
||||
name = _decode_zip_name(info)
|
||||
total_size += info.file_size
|
||||
if len(lines) < MAX_LISTED:
|
||||
kind = "/" if info.is_dir() else ""
|
||||
@@ -452,6 +458,11 @@ def _read_work_dir_files(work_dir: Path, max_chars: int = 150000) -> str:
|
||||
chunk = f"{header}\n{body}"
|
||||
parts.append(chunk)
|
||||
total += len(chunk)
|
||||
else:
|
||||
# Нераспознанный формат (.rar/.7z/.ges/.smr/.smt и пр.) — назвать
|
||||
# явно, а не пропустить молча (иначе модель сошлётся на историю).
|
||||
parts.append(f"\n### Файл: {f.name} (формат {ext or '?'} автоматически "
|
||||
f"не читается — открой инструментом или попроси экспорт в Excel/АРПС)")
|
||||
except Exception as e:
|
||||
parts.append(f"\n### Файл: {f.name} (ошибка чтения: {e})")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user