diff --git a/.gitignore b/.gitignore
index e30c4ce..4efec83 100644
--- a/.gitignore
+++ b/.gitignore
@@ -18,3 +18,6 @@ smeta-web-data-dev/
# git worktrees агентов — не коммитить
.claude/worktrees/
+
+# Локальные полные PDF ТСН (T0): в git только малые выписки и golden.json
+tests/fixtures/tsn_local/
diff --git a/docs/TSN_SAMPLES_2026-11-18.md b/docs/TSN_SAMPLES_2026-11-18.md
new file mode 100644
index 0000000..5b4e14e
--- /dev/null
+++ b/docs/TSN_SAMPLES_2026-11-18.md
@@ -0,0 +1,38 @@
+# Образцы ТСН-2001 и золотые значения (T0, 18.11.2026)
+
+Основание: `docs/PLAN_2026-11-18_tsn.md`, задача T0. Снято с официального сайта
+ГАУ «НИАЦ». Полные PDF лежат только локально (`tests/fixtures/tsn_local/`, в git
+не попадают); в репозитории — `tests/fixtures/tsn_golden.json` и этот документ.
+
+## Что снято
+
+| Документ | Адрес раздела | Страниц | Размер | SHA-256 (начало) |
+|---|---|---|---|---|
+| ТСН-2001.3-1 «Земляные работы» | niac.mos.ru/standards/tsn-2001/collectors-tsn-2001/tsn-2001-3/ | 62 | 2,4 МБ | см. golden.json |
+| Коэффициенты, выпуск 222 (IV кв. 2026) | niac.mos.ru/standards/tsn-2001/the-values-of-smr-recalculation/ | 381 | 31 МБ | см. golden.json |
+
+Реквизиты выпуска индексов: приказ `МКЭ-ОД/26-76` от 25.09.2026, учтено Дополнение 83.
+
+## Золотые значения
+
+`tests/fixtures/tsn_golden.json`:
+
+- 5 расценок главы 3-1 (страницы 17 и 20): `1-1-1`, `1-1-3`, `1-1-5`, `1-5-1`, `1-5-4`
+ с прямыми затратами, оплатой труда, эксплуатацией машин, материалами, затратами
+ труда и одним ресурсом (`2.1-1-12`/`2.1-1-13`, маш.-ч);
+- 4 коэффициента выпуска 222 (страница 12): `1.1-1-1` = 8,00; `1.1-1-2` = 9,86;
+ `1.1-1-4` = 18,38; `1.1-1-5` = 3,88.
+
+Арифметика всех пяти расценок сверена: ПЗ = ОТ + ЭМ + МАТ (допуск 0,01 ₽).
+
+## Особый случай для парсера
+
+В строке `1-5-1` (страница 20) в PDF стоит `314.84` — с точкой вместо запятой.
+Живая база такое встречает; парсер обязан читать это как 314,84, а не терять строку.
+Это и есть проверка нормализации чисел.
+
+## Чего ещё нет
+
+Значения индексов по видам работ (главы 3–7) не выписаны: таблица начинается
+с цен материалов (глава 1). Их добавим при разборе соответствующих страниц в T4 —
+до этого приёмка индексов не считается полной.
diff --git a/niac_client.py b/niac_client.py
new file mode 100644
index 0000000..fbf2697
--- /dev/null
+++ b/niac_client.py
@@ -0,0 +1,352 @@
+"""niac_client — обход официальных разделов ГАУ «НИАЦ» с ТСН-2001.
+
+Зачем: база ТСН опубликована на niac.mos.ru (исследование
+`docs/RESEARCH_2026-11-18_tsn_open_sources.md`), но у неё нет ни API, ни выгрузки —
+только страницы со ссылками на PDF. Модуль делает две вещи: превращает страницы
+разделов в манифест документов с устойчивыми ключами и скачивает нужный файл,
+проверяя, что это действительно целый PDF.
+
+Правила, которые здесь зафиксированы:
+- **Ключ документа не из URL.** Переезд файла внутри сайта не должен рождать
+ «новый документ»; ключ — раздел, книга, глава и версия. Совпавшие ключи
+ разводятся коротким хэшем адреса, чтобы разные файлы не терялись.
+- **Только свой хост.** Абсолютная ссылка на чужой адрес в манифест не попадает:
+ иначе подсунутая страница уводит загрузчик на произвольный сервер.
+- **Пустой или резко похудевший раздел — аномалия,** а не «нет обновлений».
+- **Неопознанное не скачивается:** без книги, номера дополнения или выпуска
+ документ помечается `unclassified`.
+- **Файл проверяется до подмены.** Скачиваем во временное имя, проверяем сигнатуру
+ и число страниц, и только потом заменяем целевой файл.
+
+Сеть — через `ext_fetch` (ретраи, `.part`, атомарная замена): второго загрузчика
+в проекте быть не должно.
+"""
+from __future__ import annotations
+
+import hashlib
+import os
+import re
+from html.parser import HTMLParser
+from pathlib import Path
+from urllib.parse import unquote, urljoin, urlparse
+
+import ext_fetch
+import ext_sources
+
+BASE = "https://niac.mos.ru/standards/tsn-2001/"
+ALLOWED_HOST = "niac.mos.ru"
+
+# Разделы, которые обходим. min_docs — нижняя граница «раздел жив»; резкое падение
+# против прошлого обхода ловится отдельно (expected_at_least из состояния).
+SECTIONS = (
+ {"name": "collections", "url": BASE + "collectors-tsn-2001/index.php", "min_docs": 5},
+ {"name": "collections_3", "url": BASE + "collectors-tsn-2001/tsn-2001-3/index.php", "min_docs": 10},
+ {"name": "collections_4", "url": BASE + "collectors-tsn-2001/tsn-2001-4/index.php", "min_docs": 5},
+ {"name": "collections_5", "url": BASE + "collectors-tsn-2001/tsn-2001-5/index.php", "min_docs": 3},
+ {"name": "collections_6", "url": BASE + "collectors-tsn-2001/tsn-2001-6/index.php", "min_docs": 5},
+ {"name": "collections_7", "url": BASE + "collectors-tsn-2001/tsn-2001-7/index.php", "min_docs": 2},
+ {"name": "collections_12", "url": BASE + "collectors-tsn-2001/tsn-2001-12/index.php", "min_docs": 1},
+ {"name": "collections_13", "url": BASE + "collectors-tsn-2001/tsn-2001-13/index.php", "min_docs": 1},
+ {"name": "additions", "url": BASE + "collections-of-add-ons/index.php", "min_docs": 10},
+ {"name": "indices", "url": BASE + "the-values-of-smr-recalculation/index.php", "min_docs": 5},
+)
+
+_RATE_BOOKS = {"3", "4", "5", "6", "7"}
+
+
+class SourceEmptyError(ext_fetch.FetchError):
+ """Раздел отдал меньше файлов, чем обязан: похоже, сайт изменил структуру."""
+
+
+class _Anchors(HTMLParser):
+ """Сбор ссылок. Незакрытый не должен терять документ: следующая ссылка
+ закрывает предыдущую неявно, как это делает браузер."""
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.items: list[tuple[str, str]] = []
+ self._href: str | None = None
+ self._text: list[str] = []
+
+ def _flush(self) -> None:
+ if self._href is not None:
+ self.items.append((self._href, " ".join("".join(self._text).split())))
+ self._href = None
+ self._text = []
+
+ def handle_starttag(self, tag, attrs):
+ if tag == "a":
+ self._flush()
+ self._href = dict(attrs).get("href")
+ self._text = []
+
+ def handle_data(self, data):
+ if self._href is not None:
+ self._text.append(data)
+
+ def handle_endtag(self, tag):
+ if tag == "a":
+ self._flush()
+
+ def close(self):
+ self._flush()
+ super().close()
+
+
+_BOOK_RE = re.compile(r"ТСН[\s-]?2001\.(\d+)(?:-(\d+))?", re.IGNORECASE)
+_ISSUE_RE = re.compile(r"Выпуск\s*(\d+)", re.IGNORECASE)
+_ADDENDUM_RE = re.compile(r"дополнени\w*\s*№?\s*(\d+)|доп\.?\s*(\d+)", re.IGNORECASE)
+_QUARTER_RE = re.compile(r"\b(I{1,3}V?|IV)\s*квартал\s*(\d{4})", re.IGNORECASE)
+_DECREE_RE = re.compile(r"МКЭ-ОД/\d+-\d+", re.IGNORECASE)
+_ROMAN = {"I": 1, "II": 2, "III": 3, "IV": 4}
+
+
+def _short_hash(text: str) -> str:
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()[:8]
+
+
+def _slug(text: str) -> str:
+ out = re.sub(r"[^\wа-яё]+", "-", text.lower(), flags=re.IGNORECASE).strip("-")[:60] or "doc"
+ return f"{out}-{_short_hash(text)}"
+
+
+def _is_allowed(url: str) -> bool:
+ """Только официальный сайт: чужой хост в манифест не пускаем."""
+ u = urlparse(url)
+ return u.scheme == "https" and (u.hostname or "").endswith(ALLOWED_HOST)
+
+
+def _is_pdf_link(url: str) -> bool:
+ return urlparse(url).path.lower().endswith(".pdf")
+
+
+def _kind(title: str, url: str, book: str | None, issue_no: str | None,
+ addendum_no: str | None) -> str:
+ low = title.lower()
+ if "коэффициент" in low or "индекс" in low:
+ return "index_release"
+ if addendum_no:
+ return "addendum"
+ if book is None and issue_no:
+ return "index_release"
+ if not book:
+ return "unclassified"
+ number = book.removeprefix("ТСН-2001.").split("-")[0]
+ if number == "1":
+ return "price_book"
+ if number == "2":
+ return "machine_book"
+ if number in _RATE_BOOKS:
+ return "rate_book"
+ if number == "8":
+ return "nr_sp"
+ if number == "9":
+ return "winter"
+ if number == "10":
+ return "temp"
+ if number == "11":
+ return "other_works"
+ if number == "12":
+ return "rule"
+ return "book"
+
+
+def parse_section_html(html: str, base_url: str, section: str = "") -> list[dict]:
+ """Страница раздела → манифест документов. Чистая функция: сети не трогает.
+
+ - не-PDF ссылки и чужие хосты отбрасываются;
+ - при повторе URL остаётся самый информативный заголовок, а не первый;
+ - параметры адреса сохраняются: ссылка `/a.pdf?doc=2` должна качаться с ними;
+ - совпавшие ключи разводятся хэшем адреса, чтобы разные файлы не исчезали.
+ """
+ parser = _Anchors()
+ parser.feed(html)
+ parser.close()
+
+ by_url: dict[str, str] = {}
+ for href, text in parser.items:
+ if not href:
+ continue
+ url = urljoin(base_url, href).split("#")[0]
+ if not _is_pdf_link(url) or not _is_allowed(url):
+ continue
+ title = text.strip() or unquote(os.path.basename(urlparse(url).path))
+ if url not in by_url or len(title) > len(by_url[url]):
+ by_url[url] = title
+
+ docs: list[dict] = []
+ for url, title in by_url.items():
+ book_m = _BOOK_RE.search(title)
+ book = chapter = None
+ if book_m:
+ book = f"ТСН-2001.{book_m.group(1)}"
+ if book_m.group(2):
+ chapter = f"{book_m.group(1)}-{book_m.group(2)}"
+
+ issue_m = _ISSUE_RE.search(title)
+ issue_no = issue_m.group(1) if issue_m else None
+ add_m = _ADDENDUM_RE.search(title)
+ addendum_no = (add_m.group(1) or add_m.group(2)) if add_m else None
+ quarter_m = _QUARTER_RE.search(title)
+ quarter = _ROMAN.get(quarter_m.group(1).upper()) if quarter_m else None
+ year = int(quarter_m.group(2)) if quarter_m else None
+ decree_m = _DECREE_RE.search(title)
+
+ kind = _kind(title, url, book, issue_no, addendum_no)
+ edition_bits = []
+ if addendum_no:
+ edition_bits.append(f"доп.{addendum_no}")
+ if issue_no:
+ edition_bits.append(f"выпуск {issue_no}")
+ edition = ", ".join(edition_bits) or (f"ред. {year}" if year else "")
+
+ if book and chapter and edition:
+ tail = f"{chapter}@{edition}"
+ elif book:
+ tail = chapter or edition or "base"
+ elif edition:
+ tail = edition
+ else:
+ tail = _slug(title)
+
+ docs.append({
+ "key": f"{section}/{book or 'nobook'}/{tail}",
+ "section": section,
+ "kind": kind,
+ "book": book,
+ "chapter": chapter,
+ "title": title,
+ "url": url,
+ "edition": edition,
+ "addendum_no": addendum_no,
+ "issue_no": issue_no,
+ "period_label": f"{quarter_m.group(1).upper()} квартал {year}" if quarter_m else None,
+ "quarter": quarter,
+ "year": year,
+ "decree": decree_m.group(0) if decree_m else None,
+ })
+
+ # Совпал ключ: одинаковые названия — это одна и та же ссылка, попавшая на
+ # страницу дважды (переезд файла) — оставляем одну; разные названия — разные
+ # документы (например, «часть 1» и «часть 2») — разводим хэшем адреса.
+ groups: dict[str, list[dict]] = {}
+ for d in docs:
+ groups.setdefault(d["key"], []).append(d)
+ result: list[dict] = []
+ for items in groups.values():
+ if len(items) == 1:
+ result.append(items[0])
+ continue
+ if len({x["title"] for x in items}) == 1:
+ result.append(items[0])
+ continue
+ for x in items:
+ x["key"] = f"{x['key']}--{_short_hash(x['url'])}"
+ result.append(x)
+ return result
+
+
+def fetch_text(url: str, client=None) -> str: # обёртка: в тестах подменяется
+ return ext_fetch.fetch_text(url, client=client)
+
+
+def discover_section(section: dict, client=None, expected_at_least: int | None = None) -> list[dict]:
+ """Манифест одного раздела. Резкое падение числа файлов — аномалия."""
+ html = fetch_text(section["url"], client=client)
+ docs = parse_section_html(html, section["url"], section=section["name"])
+ floor = section.get("min_docs", 1)
+ if expected_at_least is not None:
+ floor = max(floor, int(expected_at_least * 0.5))
+ if len(docs) < floor:
+ raise SourceEmptyError(
+ f"раздел {section['name']} отдал {len(docs)} файлов, ожидалось не меньше {floor}"
+ + (f" (в прошлый раз было {expected_at_least})" if expected_at_least else "")
+ + " — похоже, структура сайта изменилась")
+ return docs
+
+
+def discover(sections=None, client=None, previous_counts: dict | None = None) -> list[dict]:
+ """Обойти разделы; вернуть общий манифест. Один упавший раздел валит обход."""
+ docs: list[dict] = []
+ seen: set[str] = set()
+ counts = previous_counts or {}
+ for section in (sections or SECTIONS):
+ part = discover_section(section, client=client,
+ expected_at_least=counts.get(section["name"]))
+ for doc in part:
+ if doc["key"] in seen:
+ continue
+ seen.add(doc["key"])
+ docs.append(doc)
+ return docs
+
+
+def ensure_registered() -> ext_sources.Source:
+ """Источник в общем реестре. Регистрация идемпотентна: повтор не падает."""
+ existing = ext_sources.by_name("niac_tsn")
+ if existing is not None:
+ return existing
+ return ext_sources.register(ext_sources.Source(
+ name="niac_tsn", kind="docs", title="ТСН-2001 (НИАЦ, Москва)", freq="daily",
+ check=None,
+ notes="PDF качаются и удаляются после разбора; см. docs/PLAN_2026-11-18_tsn.md"))
+
+
+def _pdf_pages(path: str) -> tuple[int | None, str | None]:
+ """(страницы, причина). «Нет библиотеки» и «файл битый» — разные вещи."""
+ try:
+ import fitz # PyMuPDF
+ except Exception: # noqa: BLE001
+ return None, "no_fitz"
+ try:
+ with fitz.open(path) as doc:
+ return doc.page_count, None
+ except Exception: # noqa: BLE001
+ return None, "corrupt"
+
+
+def download(doc: dict, dest: os.PathLike | str, client=None) -> dict:
+ """Скачать документ. Неопознанный — не качаем. Проверка ДО подмены файла."""
+ if doc.get("kind") == "unclassified":
+ return {"skipped": True, "reason": "документ не опознан (нет книги и версии)"}
+ dest = Path(dest)
+ incoming = dest.with_name(dest.name + ".incoming")
+ if incoming.exists():
+ incoming.unlink()
+ try:
+ got = ext_fetch.fetch_file(doc["url"], incoming, expect_min_size=10_000,
+ expected_content_type="application/pdf", client=client)
+ head = incoming.read_bytes()[:5]
+ if head != b"%PDF-":
+ raise ext_fetch.FetchError(f"не PDF: {doc['url']} начинается с {head!r}")
+ pages, problem = _pdf_pages(str(incoming))
+ if problem == "corrupt":
+ raise ext_fetch.FetchError(f"PDF не открывается: {doc['url']}")
+ os.replace(incoming, dest)
+ return {"skipped": False, "path": str(dest), "size": got["size"],
+ "sha256": got["sha256"], "pages": pages,
+ "note": "страницы не проверены: нет PyMuPDF" if problem == "no_fitz" else ""}
+ finally:
+ if incoming.exists():
+ incoming.unlink()
+
+
+def probe_volatile(doc: dict, client=None) -> dict:
+ """Заголовки ответа без скачивания. Ошибки не глотаем: 405/503 — не «не изменилось»."""
+ c = client or ext_fetch.make_client()
+ try:
+ try:
+ r = c.head(doc["url"])
+ except Exception as e: # noqa: BLE001 — сырой httpx наружу не пускаем
+ raise ext_fetch.FetchError(f"HEAD {doc['url']}: {type(e).__name__}: {e}") from e
+ if r.status_code >= 400:
+ raise ext_fetch.FetchError(f"HEAD {doc['url']}: {r.status_code}")
+ return {
+ "status": r.status_code,
+ "etag": r.headers.get("etag"),
+ "last_modified": r.headers.get("last-modified"),
+ "content_length": r.headers.get("content-length"),
+ }
+ finally:
+ if client is None:
+ c.close()
diff --git a/tests/fixtures/niac_tsn_section3.html b/tests/fixtures/niac_tsn_section3.html
new file mode 100644
index 0000000..6d971c4
--- /dev/null
+++ b/tests/fixtures/niac_tsn_section3.html
@@ -0,0 +1,1073 @@
+
+
+ Сборники норм и расценок на строительные работы. ТСН-2001.3
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Сборники норм и расценок на строительные работы. ТСН-2001.3
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/tests/fixtures/tsn_golden.json b/tests/fixtures/tsn_golden.json
new file mode 100644
index 0000000..0e5c7b4
--- /dev/null
+++ b/tests/fixtures/tsn_golden.json
@@ -0,0 +1,129 @@
+{
+ "built": "2026-11-18",
+ "sources": {
+ "tsn_2001_3_1": {
+ "file": "tests/fixtures/tsn_local/tsn3-1.pdf",
+ "sha256": "68480dc1a04b492161e9c352f0cf210c70c01e44a09332790d943822b0fc359f",
+ "pages": 62,
+ "url": "https://niac.mos.ru/standards/tsn-2001/collectors-tsn-2001/tsn-2001-3/"
+ },
+ "index_222": {
+ "file": "tests/fixtures/tsn_local/index222.pdf",
+ "sha256": "119030bbda8bd401f71b2de4c37f271173189ab73dcd22099912775bc61d130f",
+ "pages": 381,
+ "url": "https://niac.mos.ru/standards/tsn-2001/the-values-of-smr-recalculation/",
+ "issue_no": "222",
+ "period": "IV квартал 2026",
+ "decree": "МКЭ-ОД/26-76",
+ "addendum": "83"
+ }
+ },
+ "rates": [
+ {
+ "code": "1-1-1",
+ "page": 17,
+ "unit": "1000 м3",
+ "pz": 225.21,
+ "ot": 5.46,
+ "em": 219.75,
+ "mat": 0.0,
+ "labor": 0.51,
+ "resource": {
+ "code": "2.1-1-13",
+ "unit": "маш.-ч",
+ "qty": 0.909
+ }
+ },
+ {
+ "code": "1-1-3",
+ "page": 17,
+ "unit": "1000 м3",
+ "pz": 455.63,
+ "ot": 10.81,
+ "em": 444.82,
+ "mat": 0.0,
+ "labor": 1.01,
+ "resource": {
+ "code": "2.1-1-13",
+ "unit": "маш.-ч",
+ "qty": 1.84
+ }
+ },
+ {
+ "code": "1-1-5",
+ "page": 17,
+ "unit": "1000 м3",
+ "pz": 391.01,
+ "ot": 7.6,
+ "em": 383.41,
+ "mat": 0.0,
+ "labor": 0.71,
+ "resource": {
+ "code": "2.1-1-12",
+ "unit": "маш.-ч",
+ "qty": 1.61
+ }
+ },
+ {
+ "code": "1-5-1",
+ "page": 20,
+ "unit": "100 м3",
+ "pz": 320.63,
+ "ot": 5.79,
+ "em": 314.84,
+ "mat": 0.0,
+ "labor": 0.55,
+ "resource": {
+ "code": "2.1-1-13",
+ "unit": "маш.-ч",
+ "qty": 1.1415
+ },
+ "note": "в PDF дефект набора: 314.84 с точкой вместо запятой"
+ },
+ {
+ "code": "1-5-4",
+ "page": 20,
+ "unit": "100 м3",
+ "pz": 346.35,
+ "ot": 5.42,
+ "em": 340.93,
+ "mat": 0.0,
+ "labor": 0.53,
+ "resource": {
+ "code": "2.1-1-12",
+ "unit": "маш.-ч",
+ "qty": 1.26
+ }
+ }
+ ],
+ "indices": [
+ {
+ "issue": "222",
+ "period": "IV квартал 2026",
+ "page": 12,
+ "code": "1.1-1-1",
+ "value": 8.0
+ },
+ {
+ "issue": "222",
+ "period": "IV квартал 2026",
+ "page": 12,
+ "code": "1.1-1-2",
+ "value": 9.86
+ },
+ {
+ "issue": "222",
+ "period": "IV квартал 2026",
+ "page": 12,
+ "code": "1.1-1-4",
+ "value": 18.38
+ },
+ {
+ "issue": "222",
+ "period": "IV квартал 2026",
+ "page": 12,
+ "code": "1.1-1-5",
+ "value": 3.88
+ }
+ ]
+}
\ No newline at end of file
diff --git a/tests/test_niac_client.py b/tests/test_niac_client.py
new file mode 100644
index 0000000..7ac02e2
--- /dev/null
+++ b/tests/test_niac_client.py
@@ -0,0 +1,231 @@
+"""Обход официальных разделов НИАЦ (ТСН-2001): разбор страниц, ключи, аномалии.
+
+Основание: docs/PLAN_2026-11-18_tsn.md, задача T2. Образец — настоящая страница
+раздела «Строительные работы» (сохранена 18.11.2026, 42 файла PDF).
+"""
+
+import os
+import sys
+
+import pytest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if ROOT not in sys.path:
+ sys.path.insert(0, ROOT)
+
+import niac_client # noqa: E402
+
+FIXTURE = os.path.join(ROOT, "tests", "fixtures", "niac_tsn_section3.html")
+BASE = "https://niac.mos.ru/standards/tsn-2001/collectors-tsn-2001/tsn-2001-3/index.php"
+
+
+@pytest.fixture(scope="module")
+def html():
+ assert os.path.exists(FIXTURE), f"нет образца страницы НИАЦ: {FIXTURE}"
+ with open(FIXTURE, encoding="utf-8") as f:
+ return f.read()
+
+
+@pytest.fixture(scope="module")
+def docs(html):
+ return niac_client.parse_section_html(html, BASE, section="collections_3")
+
+
+def test_parse_finds_all_pdf_links(docs):
+ """Со страницы раздела собираются ровно PDF, без дублей и не-PDF ссылок."""
+ assert len(docs) == 42, f"ждали 42 файла, получили {len(docs)}"
+ assert len({d["url"] for d in docs}) == len(docs)
+ for d in docs:
+ assert d["url"].startswith("https://niac.mos.ru/")
+ assert d["url"].lower().endswith(".pdf")
+ assert d["title"]
+
+
+def test_book_and_chapter_recognized(docs):
+ """Из названия извлекаются книга и глава, а не «что-то похожее»."""
+ books = {d["book"] for d in docs}
+ chapters = {d["chapter"] for d in docs if d["chapter"]}
+ assert "ТСН-2001.3" in books
+ assert {"3-1", "3-4", "3-5"} <= chapters
+ assert len(chapters) >= 10
+
+
+def test_keys_stable_when_url_changes(html):
+ """Ключ документа строится из раздела/книги/главы, а не из адреса: тот же
+ документ по новому адресу обязан получить тот же ключ. Мутация «ключ = url»
+ обязана ронять этот тест — поэтому адреса в примере разные."""
+ page = (
+ ''
+ 'ТСН-2001.3-1 Сборник 1. Земляные работы'
+ ''
+ 'ТСН-2001.3-1 Сборник 1. Земляные работы'
+ )
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ # один и тот же документ по двум адресам — одна запись, а не две
+ assert len(docs) == 1
+ assert docs[0]["title"] == "ТСН-2001.3-1 Сборник 1. Земляные работы"
+ # на настоящей странице ключи обязаны быть уникальны
+ real = niac_client.parse_section_html(html, BASE, section="collections_3")
+ assert len({d["key"] for d in real}) == len(real)
+
+
+def test_unclassified_document_not_downloaded(tmp_path):
+ """Ссылка без книги и версии помечается unclassified и не скачивается."""
+ page = ('
Памятка без шифра'
+ 'ТСН-2001.3-1 Сборник 1. Земляные работы')
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ kinds = {d["title"]: d["kind"] for d in docs}
+ assert kinds["Памятка без шифра"] == "unclassified"
+ assert kinds["ТСН-2001.3-1 Сборник 1. Земляные работы"] != "unclassified"
+ unclassified = next(d for d in docs if d["kind"] == "unclassified")
+ target = tmp_path / "should-not-appear.pdf"
+ result = niac_client.download(unclassified, target)
+ assert result["skipped"] is True
+ assert not target.exists()
+
+
+def test_empty_section_is_anomaly(monkeypatch):
+ """Раздел, который раньше отдавал файлы, а теперь пуст, — это problem,
+ а не «обновлений нет»."""
+ monkeypatch.setattr(niac_client, "fetch_text", lambda url, client=None: "пусто")
+ section = {"name": "collections_3", "url": BASE, "min_docs": 10}
+ with pytest.raises(niac_client.SourceEmptyError) as e:
+ niac_client.discover_section(section)
+ assert "0" in str(e.value) and "collections_3" in str(e.value)
+
+
+def test_index_release_recognized():
+ """Выпуск коэффициентов распознаётся с номером, кварталом и приказом."""
+ page = ('Коэффициенты пересчета в текущий '
+ 'уровень цен сметной стоимости строительно-монтажных работ. Выпуск 222, '
+ 'IV квартал 2026, приказ МКЭ-ОД/26-76, с учётом Дополнения 83')
+ docs = niac_client.parse_section_html(page, BASE, section="indices")
+ assert len(docs) == 1
+ d = docs[0]
+ assert d["kind"] == "index_release", "выпуск с упоминанием дополнения — не дополнение"
+ assert d["issue_no"] == "222"
+ assert d["quarter"] == 4 and d["year"] == 2026
+ assert d["decree"] == "МКЭ-ОД/26-76"
+ assert d["addendum_no"] == "83"
+
+
+def test_two_editions_of_one_chapter_have_different_keys():
+ """Две редакции одной главы (базовая и с дополнением) — разные документы.
+ Мутация «ключ без версии» обязана ронять этот тест."""
+ page = (
+ ''
+ 'ТСН-2001.3-1 Сборник 1. Земляные работы'
+ ''
+ 'ТСН-2001.3-1 Сборник 1. Земляные работы (доп. 83)'
+ )
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ assert len(docs) == 2
+ assert docs[0]["chapter"] == docs[1]["chapter"] == "3-1"
+ assert docs[0]["key"] != docs[1]["key"], "редакции одной главы склеились в один ключ"
+
+
+def test_long_titles_without_book_do_not_collide():
+ """У документов без книги ключ строится из названия; длинные названия с общим
+ началом не должны схлопываться в один ключ (иначе один документ потеряется)."""
+ prefix = "Очень длинное название пояснения к сборнику нормативов города Москвы часть "
+ page = (f'{prefix} первая'
+ f'{prefix} вторая')
+ docs = niac_client.parse_section_html(page, BASE, section="collections")
+ assert len({d["key"] for d in docs}) == 2
+
+
+def test_query_parameters_preserved_and_not_deduped():
+ """Ссылки, различающиеся параметром, — разные файлы; параметр нужен серверу."""
+ page = ('ТСН-2001.3-1 Земляные работы'
+ 'ТСН-2001.3-4 Скважины')
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ assert len(docs) == 2
+ assert all("?" in d["url"] for d in docs)
+
+
+def test_foreign_host_rejected():
+ """Ссылка на чужой хост не попадает в манифест ни под каким названием."""
+ page = ('ТСН-2001.3-1 Земляные работы'
+ 'ТСН-2001.3-4 Скважины')
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ assert docs == []
+
+
+def test_unclosed_anchor_is_not_lost():
+ """Незакрытый не должен терять документ: браузер закрывает его сам."""
+ page = 'ТСН-2001.3-1 Земляные работымусор
ТСН-2001.3-4 Скважины'
+ docs = niac_client.parse_section_html(page, BASE, section="collections_3")
+ assert len(docs) == 2
+ assert {d["chapter"] for d in docs} == {"3-1", "3-4"}
+
+
+def test_broken_pdf_does_not_overwrite_existing(monkeypatch, tmp_path):
+ """Битый ответ не подменяет прежний исправный файл и даёт FetchError."""
+ import ext_fetch as ef
+ dest = tmp_path / "doc.pdf"
+ dest.write_bytes(b"%PDF-1.4 good old file")
+
+ def fake_fetch(url, path, **kw):
+ path = str(path)
+ with open(path, "wb") as f:
+ f.write(b"%PDF-1.4 broken body that does not open")
+ return {"path": path, "size": 20, "sha256": "x"}
+
+ monkeypatch.setattr(ef, "fetch_file", fake_fetch)
+ monkeypatch.setattr(niac_client, "_pdf_pages", lambda p: (None, "corrupt"))
+ doc = {"url": "https://niac.mos.ru/a.pdf", "kind": "rate_book"}
+ with pytest.raises(ef.FetchError):
+ niac_client.download(doc, dest)
+ assert dest.read_bytes() == b"%PDF-1.4 good old file", "прежний файл подменён битым"
+
+
+def test_probe_volatile_raises_on_http_error(monkeypatch):
+ """405/503 — это отказ, а не «файл не изменился»."""
+ class R:
+ status_code = 405
+ headers = {}
+ class C:
+ def head(self, url):
+ return R()
+ def close(self):
+ pass
+ with pytest.raises(Exception) as e:
+ niac_client.probe_volatile({"url": "https://niac.mos.ru/a.pdf"}, client=C())
+ assert "405" in str(e.value)
+
+
+def test_source_registered_once():
+ """Источник попадает в общий реестр ровно один раз."""
+ a = niac_client.ensure_registered()
+ b = niac_client.ensure_registered()
+ assert a is b and a.name == "niac_tsn"
+
+
+def test_two_parts_of_one_addendum_are_kept():
+ """«Дополнение 83 часть 1» и «часть 2» — разные файлы с разными ключами."""
+ page = ('Дополнение 83, часть 1'
+ 'Дополнение 83, часть 2')
+ docs = niac_client.parse_section_html(page, BASE, section="additions")
+ assert len(docs) == 2
+ assert len({d["key"] for d in docs}) == 2
+
+
+def test_download_success_leaves_exact_bytes(monkeypatch, tmp_path):
+ """Успешная загрузка кладёт в цель ровно скачанные байты и не оставляет .incoming."""
+ import ext_fetch as ef
+ payload = b"%PDF-1.4 valid body"
+ dest = tmp_path / "doc.pdf"
+
+ def fake_fetch(url, path, **kw):
+ path = str(path)
+ with open(path, "wb") as f:
+ f.write(payload)
+ return {"path": path, "size": len(payload), "sha256": "x"}
+
+ monkeypatch.setattr(ef, "fetch_file", fake_fetch)
+ monkeypatch.setattr(niac_client, "_pdf_pages", lambda p: (1, None))
+ doc = {"url": "https://niac.mos.ru/a.pdf", "kind": "rate_book"}
+ res = niac_client.download(doc, dest)
+ assert res["skipped"] is False and res["pages"] == 1
+ assert dest.read_bytes() == payload
+ assert not (tmp_path / "doc.pdf.incoming").exists()