feat(срез 1.1): указатель-источник (source_ref) в корпусных инструментах; bump 2026-07-17c

find_in_real_estimates/find_ka_price отдают source_ref={src_id,index_file,verbatim}:
машинный указатель + дословная копия ключевых полей (число ответа обязано совпасть
с verbatim — контракт под number_gate, срез 1.3). _src_id — позиция в файле-индексе.
Fable-чек поймал 2 бага index_file (extka/mat вели на чужой файл) — починено, покрыто
deref-тестом (грузит index_file, идёт по src_id, сверяет запись). 6 passed, red-green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-17 20:22:50 +10:00
co-authored by Claude Opus 4.8
parent 9b153518ae
commit cf13d21931
3 changed files with 139 additions and 5 deletions
+1 -1
View File
@@ -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-17b"
APP_VERSION = "2026-07-17c"
# Audit: path → action name mapping
_AUDIT_MAP = [
+43 -4
View File
@@ -67,13 +67,24 @@ def _load_estimates() -> dict:
p = _DATA / "estimates_index.json"
_est_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
items = _est_cache["items"]
# _src_id — стабильный указатель на источник (позиция в файле-индексе).
# Через него find_* отдаёт «откуда взято число», а number_gate сверяет
# число в ответе ассистента с дословной ценой источника (срез 1.1).
for i, it in enumerate(items):
it["_src_id"] = f"est:{i}"
# Ext-индекс (новые домены: .gge ДВ / .gsfx / .arp ОСНБЖ) — ОТДЕЛЬНЫЙ файл,
# живой ВСЖМ-индекс не трогаем. Каждая ext-запись несёт norm_base/price_level.
ext_p = _DATA / "estimates_ext_index.json"
if ext_p.exists():
ext = json.loads(ext_p.read_text(encoding="utf-8"))
items.extend(ext.get("items", []))
_est_cache.setdefault("materials", []).extend(ext.get("materials", []))
ext_items = ext.get("items", [])
for i, it in enumerate(ext_items):
it["_src_id"] = f"ext:{i}"
items.extend(ext_items)
ext_mats = ext.get("materials", [])
for i, m in enumerate(ext_mats):
m["_src_id"] = f"extmat:{i}"
_est_cache.setdefault("materials", []).extend(ext_mats)
df: dict[str, int] = {}
for it in items:
it["_terms"] = _terms(it["name"])
@@ -91,7 +102,8 @@ def _load_estimates() -> dict:
_est_cache["_idf"] = {t: math.log(1 + n / c) for t, c in df.items()}
mats = _est_cache.get("materials", [])
mdf: dict[str, int] = {}
for m in mats:
for i, m in enumerate(mats):
m.setdefault("_src_id", f"mat:{i}") # ext-материалы уже с extmat:i
m["_terms"] = _terms(m["name"])
for t in m["_terms"]:
mdf[t] = mdf.get(t, 0) + 1
@@ -115,9 +127,14 @@ def _load_ka() -> dict:
if _ka_cache is None:
p = _DATA / "ka_index.json"
_ka_cache = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {"items": []}
for i, it in enumerate(_ka_cache["items"]):
it["_src_id"] = f"ka:{i}"
ext_p = _DATA / "estimates_ext_index.json"
if ext_p.exists():
_ka_cache["items"].extend(json.loads(ext_p.read_text(encoding="utf-8")).get("ka", []))
ext_ka = json.loads(ext_p.read_text(encoding="utf-8")).get("ka", [])
for i, it in enumerate(ext_ka):
it["_src_id"] = f"extka:{i}"
_ka_cache["items"].extend(ext_ka)
df: dict[str, int] = {}
for it in _ka_cache["items"]:
it["_terms"] = _terms(it["name"])
@@ -177,6 +194,18 @@ def find_in_real_estimates(query: str, top_k: int = 5) -> list[dict]:
for _, _, it in results[:top_k]:
d = {k: it.get(k) for k in keys}
d["fot_unit"] = _fot_per_unit(it) # ФОТ/ед (база для НР/СП), масштабирован к цене/ед
# Указатель на источник + дословная копия ключевых полей. Число в ответе
# ассистента обязано совпасть с verbatim (сверяет number_gate, срез 1.3).
sid = it.get("_src_id") or ""
d["source_ref"] = {
"src_id": sid,
"index_file": "estimates_ext_index.json" if sid.startswith("ext:") else "estimates_index.json",
"verbatim": {
"code": it.get("code"), "name": it.get("name"), "unit": it.get("unit"),
"unit_cost_cur": it.get("unit_cost_cur"),
"norm_base": it.get("norm_base"), "price_level": it.get("price_level"),
},
}
out.append(d)
return out
@@ -211,19 +240,29 @@ def find_ka_price(query: str, top_k: int = 5) -> list[dict]:
common = qset & it["_terms"]
if common:
score = sum(ka_idf.get(t, 0.0) for t in common)
sid = it.get("_src_id") or "" # ka:* из ka_index.json, extka:* из ext-индекса
results.append((score, {
"source": "КА", "name": it.get("name"), "unit": it.get("unit"),
"region": it.get("region"), "period": it.get("period"),
"price": it.get("price"), "offers": it.get("offers"),
"source_ref": {"src_id": sid,
"index_file": "estimates_ext_index.json" if sid.startswith("extka") else "ka_index.json",
"verbatim": {"name": it.get("name"), "unit": it.get("unit"),
"price": it.get("price")}},
}))
for m in est.get("materials", []):
common = qset & m["_terms"]
if common:
score = sum(mat_idf.get(t, 0.0) for t in common)
sid = m.get("_src_id") or "" # mat:* из estimates_index.json, extmat:* из ext-индекса
results.append((score, {
"source": "смета", "name": m.get("name"), "unit": m.get("unit"),
"code": m.get("code"), "price_cur": m.get("price_cur"),
"freq": m.get("freq"), "regions": m.get("regions"),
"source_ref": {"src_id": sid,
"index_file": "estimates_ext_index.json" if sid.startswith("extmat") else "estimates_index.json",
"verbatim": {"name": m.get("name"), "unit": m.get("unit"),
"code": m.get("code"), "price_cur": m.get("price_cur")}},
}))
results.sort(key=lambda x: x[0], reverse=True)
return [r for _, r in results[:top_k]]
+95
View File
@@ -0,0 +1,95 @@
"""Срез 1.1: указатель-источник (source_ref) в корпусных инструментах.
Каждый результат find_in_real_estimates / find_ka_price несёт машинный указатель
на источник + ДОСЛОВНУЮ копию ключевых полей. Число в ответе ассистента обязано
совпадать с verbatim — это контракт, который сверяет number_gate (срез 1.3).
Гоняется по реальному корпусу data/real_corpus/ (индексы в репо).
"""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import real_corpus # noqa: E402
_DATA = Path(__file__).resolve().parent.parent / "data" / "real_corpus"
def _deref(src_id: str, index_file: str) -> dict:
"""Разыменовать указатель: загрузить index_file и достать запись по src_id.
Ловит битый index_file (указатель ведёт на чужую запись)."""
data = json.loads((_DATA / index_file).read_text(encoding="utf-8"))
kind, i = src_id.split(":")
i = int(i)
if kind in ("est", "ext"):
return data["items"][i]
if kind == "ka":
return data["items"][i]
if kind == "extka":
return data["ka"][i]
if kind in ("mat", "extmat"):
return data["materials"][i]
raise AssertionError(f"неизвестный тип src_id: {kind}")
def test_estimate_result_has_source_pointer():
res = real_corpus.find_in_real_estimates("тепловоз маневровый", top_k=3)
assert res, "корпус должен вернуть расценки на тепловоз (якорь 91.09.05-023)"
for r in res:
assert "source_ref" in r, "у каждого результата есть source_ref"
s = r["source_ref"]
assert s["src_id"], "src_id непустой (указатель на источник)"
assert "verbatim" in s and "index_file" in s
# ГЛАВНОЕ: число в ответе == дословная цена источника
assert s["verbatim"]["unit_cost_cur"] == r["unit_cost_cur"]
assert s["verbatim"]["code"] == r["code"]
assert s["verbatim"]["name"] == r["name"]
def test_src_id_deterministic():
a = real_corpus.find_in_real_estimates("щебень балластный", top_k=3)
b = real_corpus.find_in_real_estimates("щебень балластный", top_k=3)
assert a, "должны быть результаты на щебень"
assert [x["source_ref"]["src_id"] for x in a] == [x["source_ref"]["src_id"] for x in b]
def test_src_id_has_known_origin_prefix():
# mutation-check: если убрать назначение _src_id — src_id пуст и этот тест падает
res = real_corpus.find_in_real_estimates("тепловоз", top_k=1)
assert res and res[0]["source_ref"]["src_id"].startswith(("est:", "ext:"))
def test_ka_result_has_source_pointer():
res = real_corpus.find_ka_price("щебень", top_k=3)
if not res:
return # КА-корпус может не содержать щебня — мягкий пропуск, не ложное падение
for r in res:
assert "source_ref" in r
assert r["source_ref"]["src_id"], "src_id непустой"
assert "verbatim" in r["source_ref"]
# существующее поле origin ('КА'/'смета') не затёрто указателем
assert r.get("source") in ("КА", "смета")
def test_estimate_pointer_dereferences_to_same_record():
# указатель (src_id + index_file) ведёт на ТУ ЖЕ запись, что и verbatim
res = real_corpus.find_in_real_estimates("тепловоз маневровый", top_k=3)
assert res
for r in res:
s = r["source_ref"]
rec = _deref(s["src_id"], s["index_file"])
assert rec.get("name") == s["verbatim"]["name"], \
f"указатель {s['src_id']} → {s['index_file']} ведёт на чужую запись"
assert rec.get("unit_cost_cur") == s["verbatim"]["unit_cost_cur"]
def test_ka_pointer_dereferences_to_same_record():
# прямой отлов багов index_file (extka→ext-файл, mat→базовый файл)
res = real_corpus.find_ka_price("щебень", top_k=5)
if not res:
return
for r in res:
s = r["source_ref"]
rec = _deref(s["src_id"], s["index_file"])
assert rec.get("name") == s["verbatim"]["name"], \
f"КА-указатель {s['src_id']} → {s['index_file']} ведёт на чужую запись"