File size: 39,230 Bytes
651b674
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
"""Build a deterministic domain graph from the supplied catalogue and schema.

Schema parsing is deliberately strict: a changed ontology must be reviewed rather
than silently acquiring the semantics of the old schema.  Catalogue values remain
open-ended and category-scoped.  No transcript is read by this module.
"""

from __future__ import annotations

import hashlib
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from .enrichment import ENRICHMENT_VERSION, MANIFEST_SHA256, add_enrichment, answer_sections, normalization_rules

FORMAT_VERSION = "1.1"
BUILDER_VERSION = "1.1"
NODE_KINDS = frozenset(
    {"source", "entity_type", "attribute", "category", "catalog_value", "rule", "example",
     "alias", "template", "concept_group"}
)
CATEGORIES = {
    "services": "Услуги",
    "tariffs": "Тарифы",
    "devices": "Устройства",
    "symptoms": "Симптомы",
    "actions": "Действия",
    "agreements": "Договорённости",
    "statuses": "Статусы заявок",
}
ENTITY_LABELS = {
    "service": "Услуга",
    "device": "Устройство",
    "ticket": "Заявка",
    "client": "Клиент",
}
EXPECTED_ATTRIBUTES = frozenset(
    {"service_state", "tariff", "ticket_status", "action", "agreement"}
)
ATTRIBUTE_CATEGORIES = {
    "service_state": "symptoms", "tariff": "tariffs", "ticket_status": "statuses",
    "action": "actions", "agreement": "agreements",
}
ENTITY_CATEGORIES = {"service": "services", "device": "devices"}
ATTRIBUTE_ENTITY_TYPES = {
    "service_state": ("service", "device"), "tariff": ("client",),
    "ticket_status": ("ticket",), "action": ("client",),
}
BASE_RULE_IDS = frozenset({"open_catalog", "polarity", "speaker", "grounding", "dates", "schema_constraints", "output"})


class GraphValidationError(ValueError):
    """A source or graph violates the explicit, supported format."""


def _require(condition: bool, message: str) -> None:
    if not condition:
        raise GraphValidationError(message)


def _hash(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()


def _canonical(value: Any) -> str:
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def _graph_id(graph: dict) -> str:
    return "domain-graph:" + _hash(_canonical({k: v for k, v in graph.items() if k != "graph_id"}))


def _value_id(category: str, value: str) -> str:
    return f"value:{category}:{_hash(_canonical([category, value]))[:20]}"


@dataclass(frozen=True)
class _Source:
    id: str
    path: Path
    content: str

    @classmethod
    def read(cls, source_id: str, path: Path) -> _Source:
        # Decode bytes directly so hashes and provenance preserve CRLF exactly.
        return cls(source_id, Path(path), Path(path).read_bytes().decode("utf-8"))

    @property
    def lines(self) -> list[str]:
        return self.content.splitlines(keepends=True)

    def at(self, start: int, end: int, locator: str) -> dict:
        _require(0 <= start < end <= len(self.content), f"Invalid source span in {self.id}")
        return {
            "source_id": self.id,
            "locator": locator,
            "quote": self.content[start:end],
            "line_start": self.content.count("\n", 0, start) + 1,
            "line_end": self.content.count("\n", 0, end - 1) + 1,
        }

    def line_span(self, first: int, last: int, locator: str | None = None) -> dict:
        lines = self.lines
        _require(1 <= first <= last <= len(lines), f"Invalid line range in {self.id}")
        start = sum(map(len, lines[: first - 1]))
        text = "".join(lines[first - 1 : last]).rstrip("\r\n")
        return self.at(start, start + len(text), locator or f"lines:{first}-{last}")

    def as_dict(self) -> dict:
        # Basenames make the graph portable and independent of checkout location.
        return {"id": self.id, "path": self.path.name, "sha256": _hash(self.content), "content": self.content}


def _catalogue(source: _Source) -> tuple[dict[str, list[str]], dict[str, dict]]:
    """Parse JSON and retain exact token locations, including compact JSON files."""
    text = source.content
    decoder = json.JSONDecoder()
    position = 0
    values: dict[str, list[str]] = {}
    locations: dict[str, dict] = {}

    def skip() -> None:
        nonlocal position
        while position < len(text) and text[position].isspace():
            position += 1

    def take(character: str) -> None:
        nonlocal position
        skip()
        _require(position < len(text) and text[position] == character,
                 f"catalog.json: expected {character!r} at character {position}")
        position += 1

    def string(locator: str) -> str:
        nonlocal position
        skip()
        start = position
        try:
            value, position = decoder.raw_decode(text, position)
        except json.JSONDecodeError as exc:
            raise GraphValidationError(f"catalog.json: {exc}") from exc
        _require(isinstance(value, str) and bool(value.strip()),
                 f"catalog.json: expected a nonempty string at {locator}")
        locations[locator] = source.at(start, position, locator)
        return value

    take("{")
    skip()
    while position < len(text) and text[position] != "}":
        category = string("/pending-key")
        _require(category not in values, f"catalog.json: duplicate category {category!r}")
        _require(category in CATEGORIES, f"catalog.json: unknown category {category!r}; review schema mapping")
        locations[f"/{category}"] = {**locations.pop("/pending-key"), "locator": f"/{category}"}
        take(":")
        take("[")
        entries: list[str] = []
        skip()
        while position < len(text) and text[position] != "]":
            entry = string(f"/{category}/{len(entries)}")
            _require(entry not in entries, f"catalog.json: duplicate value {entry!r} in {category}")
            entries.append(entry)
            skip()
            if position < len(text) and text[position] == ",":
                position += 1
                skip()
                _require(position < len(text) and text[position] != "]", "catalog.json: trailing comma")
            else:
                break
        take("]")
        values[category] = entries
        skip()
        if position < len(text) and text[position] == ",":
            position += 1
            skip()
            _require(position < len(text) and text[position] != "}", "catalog.json: trailing comma")
        else:
            break
    take("}")
    skip()
    _require(position == len(text), "catalog.json: unexpected trailing content")
    _require(set(values) == set(CATEGORIES), f"catalog.json: missing categories {sorted(set(CATEGORIES) - set(values))}")
    return values, locations


def _schema(source: _Source) -> dict:
    lines = source.lines
    headings: dict[int, tuple[int, str]] = {}
    for number, line in enumerate(lines, 1):
        match = re.match(r"^## (\d+)\. (.+?)\s*$", line)
        if match:
            section = int(match[1])
            _require(section not in headings, f"schema.md: duplicate section {section}")
            headings[section] = (number, match[2])
    expected = {1: "Формат диалога", 2: "Схема факта", 3: "Онтология", 4: "Ловушки (не факты!)"}
    for section, title in expected.items():
        _require(section in headings and headings[section][1] == title,
                 f"schema.md: missing expected section {section}. {title}")
    _require(set(headings) == {1, 2, 3, 4, 5} and headings[5][1].startswith("Метрики ("),
             "schema.md: unexpected section structure; review schema drift")
    _require([headings[i][0] for i in range(1, 6)] == sorted(headings[i][0] for i in range(1, 6)),
             "schema.md: sections are out of order")

    def find_line(fragment: str, section: int) -> int:
        start = headings[section][0]
        end = headings[section + 1][0] - 1 if section < 5 else len(lines)
        found = [i for i in range(start, end + 1) if fragment in lines[i - 1]]
        _require(len(found) == 1, f"schema.md: expected one {fragment!r} in section {section}")
        return found[0]

    def paragraph(fragment: str, section: int) -> dict:
        first = find_line(fragment, section)
        last = first
        while last < len(lines) and lines[last].strip() and not lines[last].startswith("## "):
            last += 1
        return source.line_span(first, last)

    header_line = find_line("| attribute |", 3)
    header = [cell.strip() for cell in lines[header_line - 1].strip().strip("|").split("|")]
    _require(header == ["attribute", "смысл", "одно-значный?", "примеры значений (по каталогу)"],
             "schema.md: unexpected ontology table columns")
    _require(re.fullmatch(r"\|\s*[-:]+\s*\|\s*[-:]+\s*\|\s*[-:]+\s*\|\s*[-:]+\s*\|", lines[header_line].strip()) is not None,
             "schema.md: missing ontology table separator")
    attributes: dict[str, dict] = {}
    for number in range(header_line + 2, len(lines) + 1):
        line = lines[number - 1].strip()
        if not line.startswith("|"):
            break
        cells = [cell.strip() for cell in line.strip("|").split("|")]
        _require(len(cells) == 4, f"schema.md: malformed ontology row at line {number}")
        match = re.fullmatch(r"`([a-z_]+)`", cells[0])
        _require(match is not None, f"schema.md: invalid attribute at line {number}")
        name = match[1]
        _require(name in EXPECTED_ATTRIBUTES and name not in attributes,
                 f"schema.md: unknown or duplicate attribute {name!r}")
        _require(re.fullmatch(r"да(?: \([^()]+\))?|нет", cells[2]) is not None,
                 f"schema.md: unsupported cardinality {cells[2]!r}")
        _require(bool(cells[1]) and bool(cells[3]), f"schema.md: incomplete ontology row {name}")
        attributes[name] = {
            "description": cells[1], "single_valued": cells[2].startswith("да"),
            "cardinality_note": cells[2], "examples_text": cells[3],
            "provenance": source.line_span(number, number),
        }
    _require(set(attributes) == EXPECTED_ATTRIBUTES, "schema.md: missing ontology attributes")

    types_line = find_line('"type":', 2)
    type_match = re.search(r"//\s*([a-z]+(?:\s*\|\s*[a-z]+)+)\s*$", lines[types_line - 1])
    _require(type_match is not None, "schema.md: missing object type enumeration")
    types = [item.strip() for item in type_match[1].split("|")]
    _require(len(types) == len(set(types)) and set(types) == set(ENTITY_LABELS),
             "schema.md: unsupported entity types; review schema drift")

    polarity_line = find_line('"polarity":', 2)
    _require("1 утверждение | -1 явное отрицание клиентом" in lines[polarity_line - 1],
             "schema.md: polarity semantics changed")
    speaker_line = find_line('"speaker":', 2)
    _require("говорящий реплики-источника" in lines[speaker_line - 1], "schema.md: speaker semantics changed")
    source_line = find_line('"source":', 2)
    _require('"span":' in lines[source_line] and '"quote":' in lines[source_line + 1],
             "schema.md: source grounding fields changed")

    dates = paragraph("**Семантика дат (", 2)
    date_text = " ".join(dates["quote"].split())
    version_match = re.search(r"\*\*Семантика дат \((v[\d.]+)\)\.\*\*", date_text)
    _require(version_match is not None and version_match[1] == "v2", "schema.md: unsupported declared date semantics version")
    for fragment in ("`valid_from` — момент действия/состояния", "Если дата в тексте не названа — возвращайте дату звонка",
                     "`action` темпорально не оценивается", "относительно `started_at`", "время суток присутствует только когда оно явно озвучено"):
        _require(fragment in date_text, f"schema.md: missing date rule {fragment!r}")

    constraints = paragraph("Возможны однодневные звенья", 3)
    for fragment in ("valid_from и valid_to в один день", "`confirmed`", "Имя объекта может быть пустым"):
        _require(fragment in constraints["quote"], f"schema.md: missing constraint {fragment!r}")
    normalization = paragraph("Каталог нормализации значений", 3)
    value_line = find_line('"value":', 2)
    _require("каталог — справочник, не закрытый алфавит" in lines[value_line - 1],
             "schema.md: catalogue open-value semantics changed")

    trap_lines = [(i, lines[i - 1]) for i in range(headings[4][0] + 1, headings[5][0]) if lines[i - 1].startswith("- ")]
    trap_specs = [
        ("unconfirmed_offer", "Неподтверждённое предложение", "предложение оператора"),
        ("rejected_guess", "Отвергнутая догадка", "догадка оператора"),
        ("unrelated_mentions", "Посторонние упоминания", "упоминания посторонних"),
        ("hypotheses_and_questions", "Гипотезы, вопросы и чужие слова", "гипотезы, вопросы"),
    ]
    _require(len(trap_lines) == len(trap_specs), "schema.md: trap list changed")
    traps = []
    for (number, line), (key, label, prefix) in zip(trap_lines, trap_specs):
        _require(line.startswith("- " + prefix), f"schema.md: expected trap {prefix!r}")
        traps.append({"key": key, "label": label, "provenance": source.line_span(number, number)})

    output = paragraph("Формат `pred.jsonl`", 5)
    _require("достаточно полей" in output["quote"] and "(span" in output["quote"], "schema.md: missing output contract")
    required_fields = re.findall(r"`([^`]+)`", output["quote"].split("достаточно полей", 1)[1].split("(span", 1)[0])
    _require(required_fields == ["object.name", "attribute", "value", "polarity", "valid_from", "valid_to", "source.turn_idx"],
             "schema.md: required output fields changed")
    return {
        "attributes": attributes, "types": types, "type_provenance": source.line_span(types_line, types_line),
        "dates": dates, "declared_version": version_match[1], "constraints": constraints,
        "normalization": normalization, "open_values": source.line_span(value_line, value_line),
        "polarity": source.line_span(polarity_line, polarity_line),
        "speaker": source.line_span(speaker_line, speaker_line),
        "grounding": source.line_span(source_line, source_line + 2),
        "traps": traps, "output": output, "required_fields": required_fields,
    }


def _examples(attribute: str, raw: str) -> list[str]:
    if "→" in raw:
        examples = [part.strip() for part in raw.split("→")]
    elif "«" in raw:
        examples = re.findall(r"«([^»]+)»", raw)
    else:
        examples = [part.strip() for part in raw.split(";")]
    _require(bool(examples) and all(examples) and len(examples) == len(set(examples)),
             f"schema.md: invalid or duplicate examples for {attribute}")
    return examples


def build_graph(catalog_path: Path, schema_path: Path, answers_path: Path | None = None) -> dict:
    """Build from catalogue/schema and optional organizer answers, never call data.

    If the third path is omitted, an existing ANSWERS_v2.md beside the schema is
    included. A portable pair of catalogue/schema files without it remains valid.
    """
    catalog_source = _Source.read("catalog", catalog_path)
    schema_source = _Source.read("schema", schema_path)
    if answers_path is None:
        sibling = Path(schema_path).with_name("ANSWERS_v2.md")
        answers_path = sibling if sibling.is_file() else None
    answers_source = _Source.read("answers", answers_path) if answers_path is not None else None
    graph = _assemble_graph(catalog_source, schema_source, answers_source)
    validate_graph(graph)
    return graph


def _assemble_graph(catalog_source: _Source, schema_source: _Source, answers_source: _Source | None = None) -> dict:
    """Pure derivation shared by construction and semantic verification; no I/O."""
    catalog, catalog_locations = _catalogue(catalog_source)
    schema = _schema(schema_source)
    answers = answer_sections(answers_source, _require)
    nodes: list[dict] = []
    edges: list[dict] = []

    def node(node_id: str, display_label: str, kind: str, description: str, provenance: list[dict], **properties: Any) -> None:
        nodes.append({"id": node_id, "label": display_label, "kind": kind, "description": description,
                      "properties": properties, "provenance": provenance})

    def edge(origin: str, target: str, relation: str, label: str, provenance: list[dict],
             *, status: str = "explicit", description: str = "", **properties: Any) -> None:
        edges.append({"id": "edge:" + _hash(_canonical([origin, relation, target]))[:24],
                      "source": origin, "target": target, "relation": relation, "label": label,
                      "description": description, "status": status, "provenance": provenance,
                      "properties": properties})

    source_labels = [(catalog_source, "Каталог значений"), (schema_source, "Схема фактов")]
    if answers_source is not None:
        source_labels.append((answers_source, "Уточнения организаторов v2.1"))
    for source, label in source_labels:
        node(f"source:{source.id}", label, "source", f"Исходный файл {source.path.name}",
             [source.line_span(1, 1)], source_id=source.id, path=source.path.name, sha256=_hash(source.content))

    for category, label in CATEGORIES.items():
        category_id = f"category:{category}"
        provenance = [catalog_locations[f"/{category}"]]
        node(category_id, label, "category", f"Раздел каталога: {len(catalog[category])} значений.",
             provenance + [schema["open_values"]], category=category, entry_count=len(catalog[category]), closed_vocabulary=False)
        edge("source:catalog", category_id, "defines_category", "содержит раздел", provenance)
        for index, value in enumerate(catalog[category]):
            value_provenance = [catalog_locations[f"/{category}/{index}"]]
            value_id = _value_id(category, value)
            node(value_id, value, "catalog_value", f"Запись справочника в разделе «{label}».",
                 value_provenance, category=category, catalog_index=index, value=value)
            edge(category_id, value_id, "contains_value", "содержит значение", value_provenance)

    for entity_type in schema["types"]:
        node_id = f"entity_type:{entity_type}"
        provenance = [schema["type_provenance"]]
        node(node_id, ENTITY_LABELS[entity_type], "entity_type", f"Тип объекта схемы: {entity_type}.", provenance,
             code=entity_type)
        edge("source:schema", node_id, "defines_entity_type", "задаёт тип объекта", provenance)

    for name, attribute in schema["attributes"].items():
        node_id = f"attribute:{name}"
        provenance = [attribute["provenance"]]
        node(node_id, name, "attribute", attribute["description"], provenance, code=name,
             single_valued=attribute["single_valued"], cardinality_note=attribute["cardinality_note"],
             examples_text=attribute["examples_text"])
        edge("source:schema", node_id, "defines_attribute", "задаёт атрибут", provenance)

    # These cross-document associations are a curated interpretation, not quoted
    # constraints or evidence about any customer's service or device.
    for attribute, category in ATTRIBUTE_CATEGORIES.items():
        edge(f"attribute:{attribute}", f"category:{category}", "uses_catalog", "справочник значений",
             [schema["attributes"][attribute]["provenance"], catalog_locations[f"/{category}"]], status="derived",
             description="Кураторское сопоставление атрибута с разделом; не закрытый словарь и не факт о клиенте.",
             mapping_origin="curated", exhaustive=False, hard_constraint=False)
    for entity_type, category in ENTITY_CATEGORIES.items():
        edge(f"entity_type:{entity_type}", f"category:{category}", "uses_catalog", "справочник названий",
             [schema["type_provenance"], catalog_locations[f"/{category}"]], status="derived",
             description="Кураторское сопоставление типа объекта и раздела каталога.",
             mapping_origin="curated", exhaustive=False, hard_constraint=False)
    for attribute, entity_types in ATTRIBUTE_ENTITY_TYPES.items():
        for entity_type in entity_types:
            edge(f"attribute:{attribute}", f"entity_type:{entity_type}", "describes_entity", "описывает объект",
                 [schema["attributes"][attribute]["provenance"], schema["type_provenance"]], status="derived",
                 description="Интерпретация смысла атрибута; не жёсткое ограничение на входные факты.",
                 mapping_origin="curated", hard_constraint=False)

    rules = [
        ("open_catalog", "Каталог — открытый справочник", [schema["open_values"], schema["normalization"]], {"closed_vocabulary": False}),
        ("polarity", "Полярность утверждения", [schema["polarity"]], {"positive": 1, "negative": -1, "negative_requires_explicit_client_denial": True}),
        ("speaker", "Говорящий реплики-источника", [schema["speaker"]], {}),
        ("grounding", "Привязка к исходной реплике", [schema["grounding"]], {}),
        ("dates", "Семантика и нормализация дат", [schema["dates"]], {"anchor": "started_at", "unspecified_date": "call_date", "action_temporally_scored": False}),
        ("schema_constraints", "Дополнительные правила схемы", [schema["constraints"]], {}),
        ("output", "Обязательные поля результата", [schema["output"]], {"required_fields": schema["required_fields"]}),
    ]
    for trap in schema["traps"]:
        rules.append((trap["key"], trap["label"], [trap["provenance"]], {"rule_type": "not_a_fact"}))
    rules.extend([
        ("agreement_deadline", "Срок договорённости", [schema["attributes"]["agreement"]["provenance"], schema["dates"]],
         {"scope": "attribute", "attributes": ["agreement"], "valid_from_role": "deadline", "anchor": "started_at"}),
        ("single_valued_state", "Однозначные атрибуты состояния",
         [schema["attributes"][name]["provenance"] for name in ("service_state", "tariff", "ticket_status")],
         {"scope": "attribute", "attributes": ["service_state", "tariff", "ticket_status"], "single_valued": True}),
    ])
    rules.extend(normalization_rules(answers, schema))
    for name, label, provenance, properties in rules:
        node_id = f"rule:{name}"
        properties = {"scope": "global", **properties}
        node(node_id, label, "rule", "\n\n".join(item["quote"] for item in provenance), provenance, **properties)
        edge(f"source:{provenance[0]['source_id']}", node_id, "defines_rule", "задаёт правило", provenance)
        if properties["scope"] == "attribute":
            for attribute in properties["attributes"]:
                edge(node_id, f"attribute:{attribute}", "applies_to", "область применения",
                     provenance + [schema["attributes"][attribute]["provenance"]], status="derived",
                     mapping_origin="curated", hard_constraint=False,
                     derivation="Область применения определена по смыслу правила и определению атрибута.")

    for attribute, details in schema["attributes"].items():
        raw = details["examples_text"]
        examples = _examples(attribute, raw)
        category = ATTRIBUTE_CATEGORIES[attribute]
        example_ids = []
        for example in examples:
            if example in catalog[category]:
                example_id = _value_id(category, example)
            else:
                example_id = f"example:{attribute}:{_hash(example)[:20]}"
                node(example_id, example, "example", "Пример из схемы; отсутствует как точная запись соответствующего раздела каталога.",
                     [details["provenance"]], attribute=attribute, category=category, is_example=True)
            edge(f"attribute:{attribute}", example_id, "has_example", "пример значения", [details["provenance"]],
                 is_example=True, exhaustive=False)
            example_ids.append(example_id)
        if "→" in raw:
            for previous, following in zip(example_ids, example_ids[1:]):
                edge(previous, following, "example_transition", "пример следующего статуса", [details["provenance"]],
                     description="Порядок в примере таблицы; не полный перечень допустимых переходов.",
                     is_example=True, exhaustive=False, hard_constraint=False)

    add_enrichment(catalog, catalog_locations, schema, answers, node, edge, _value_id)
    nodes.sort(key=lambda item: item["id"])
    edges.sort(key=lambda item: item["id"])
    graph = {
        "format_version": FORMAT_VERSION,
        "metadata": {
            "title": "Граф предметной области CompactFactExtraction",
            "description": "Статическая онтология и каталог. Не содержит реплик, фактов клиентов или результатов LLM.",
            "schema_version": "2.1",
            "schema_declared_date_version": schema["declared_version"],
            "builder_version": BUILDER_VERSION,
            "enrichment_version": ENRICHMENT_VERSION,
            "taxonomy_manifest_sha256": MANIFEST_SHA256,
            "scope": "static_domain",
            "runtime_data_included": False,
            "counts": {"nodes": len(nodes), "edges": len(edges), "catalog_entries": sum(map(len, catalog.values()))},
            "notes": ["Каталог не является закрытым словарём.",
                      "Связи derived — кураторская интерпретация; цитаты показывают её основания.",
                      "Группы — навигационные фасеты по словам названий, не свойства услуг и тарифов.",
                      "Общие варианты упоминания могут соответствовать нескольким значениям; требуется контекст звонка.",
                      "Цепочка статусов — пример из схемы, а не исчерпывающий закон переходов.",
                      "schema_version обозначает поддерживаемую версию пакета v2.1; сам раздел дат помечен v2."],
        },
        "sources": [source.as_dict() for source, _ in source_labels],
        "nodes": nodes,
        "edges": edges,
    }
    graph["graph_id"] = _graph_id(graph)
    return graph


def validate_graph(graph: dict) -> None:
    """Check structure, identities, source hashes, provenance, and catalogue coverage.

    This function never changes its argument.  It raises GraphValidationError on
    inconsistent or tampered artefacts; it does not claim to prove semantic truth.
    """
    _require(isinstance(graph, dict), "Graph must be an object")
    _require(graph.get("format_version") == FORMAT_VERSION, "Unsupported graph format_version")
    _require(isinstance(graph.get("metadata"), dict), "Missing graph metadata")
    for key in ("sources", "nodes", "edges"):
        _require(isinstance(graph.get(key), list), f"Graph {key} must be a list")
    sources: dict[str, dict] = {}
    for source in graph["sources"]:
        _require(isinstance(source, dict), "Source must be an object")
        source_id = source.get("id")
        _require(isinstance(source_id, str) and bool(source_id) and source_id not in sources, "Source ids must be unique nonempty strings")
        _require(isinstance(source.get("path"), str) and bool(source["path"]), f"Source {source_id} is missing its path")
        _require(isinstance(source.get("content"), str) and bool(source["content"]), f"Source {source_id} is empty")
        _require(source.get("sha256") == _hash(source["content"]), f"Source hash mismatch: {source_id}")
        sources[source_id] = source
    _require("catalog" in sources and "schema" in sources, "Both catalog and schema sources are required")
    _require(set(sources) <= {"catalog", "schema", "answers"}, "Unexpected source type; only domain documents are supported")

    def provenance(items: Any, owner: str) -> None:
        _require(isinstance(items, list) and bool(items), f"Missing provenance: {owner}")
        for item in items:
            _require(isinstance(item, dict), f"Invalid provenance: {owner}")
            source_id = item.get("source_id")
            _require(isinstance(source_id, str) and source_id in sources, f"Unknown provenance source: {owner}")
            text = sources[source_id]["content"]
            quote = item.get("quote")
            _require(isinstance(item.get("locator"), str) and bool(item["locator"]), f"Missing source locator: {owner}")
            _require(isinstance(quote, str) and bool(quote) and quote in text, f"Quote not in source: {owner}")
            first, last = item.get("line_start"), item.get("line_end")
            _require((first is None) == (last is None), f"Incomplete provenance line range: {owner}")
            if first is not None:
                lines = text.splitlines(keepends=True)
                _require(type(first) is int and type(last) is int and 1 <= first <= last <= len(lines),
                         f"Invalid provenance line range: {owner}")
                _require(quote in "".join(lines[first - 1 : last]), f"Quote outside provenance line range: {owner}")

    nodes: dict[str, dict] = {}
    for node in graph["nodes"]:
        _require(isinstance(node, dict), "Node must be an object")
        node_id = node.get("id")
        _require(isinstance(node_id, str) and bool(node_id) and node_id not in nodes, "Node ids must be unique nonempty strings")
        _require(isinstance(node.get("kind"), str) and node["kind"] in NODE_KINDS, f"Invalid node kind: {node_id}")
        _require(isinstance(node.get("label"), str) and bool(node["label"]), f"Missing node label: {node_id}")
        _require(isinstance(node.get("description"), str), f"Missing node description: {node_id}")
        _require(isinstance(node.get("properties"), dict), f"Missing node properties: {node_id}")
        provenance(node.get("provenance"), node_id)
        nodes[node_id] = node
    edge_ids = set()
    signatures = set()
    # Kind/status checks prohibit reinterpreting a catalogue edge as a causal or
    # customer fact, even when an altered graph has a freshly recomputed hash.
    relation_specs = {
        "defines_category": ({"source"}, {"category"}, "explicit"),
        "contains_value": ({"category"}, {"catalog_value"}, "explicit"),
        "defines_entity_type": ({"source"}, {"entity_type"}, "explicit"),
        "defines_attribute": ({"source"}, {"attribute"}, "explicit"),
        "defines_rule": ({"source"}, {"rule"}, "explicit"),
        "uses_catalog": ({"attribute", "entity_type"}, {"category"}, "derived"),
        "describes_entity": ({"attribute"}, {"entity_type"}, "derived"),
        "has_example": ({"attribute"}, {"catalog_value", "example"}, "explicit"),
        "example_transition": ({"catalog_value", "example"}, {"catalog_value", "example"}, "explicit"),
        "has_group": ({"category"}, {"concept_group"}, "derived"),
        "groups_value": ({"concept_group"}, {"catalog_value"}, "derived"),
        "alias_of": ({"alias"}, {"catalog_value"}, "derived"),
        "template_for": ({"template"}, {"attribute"}, "derived"),
        "applies_to": ({"rule"}, {"attribute"}, "derived"),
    }
    for edge in graph["edges"]:
        _require(isinstance(edge, dict), "Edge must be an object")
        edge_id = edge.get("id")
        _require(isinstance(edge_id, str) and bool(edge_id) and edge_id not in edge_ids, "Edge ids must be unique nonempty strings")
        edge_ids.add(edge_id)
        _require(isinstance(edge.get("source"), str) and edge["source"] in nodes and
                 isinstance(edge.get("target"), str) and edge["target"] in nodes,
                 f"Edge refers to an unknown node: {edge_id}")
        _require(isinstance(edge.get("status"), str) and edge["status"] in {"explicit", "derived"}, f"Invalid edge status: {edge_id}")
        _require(isinstance(edge.get("relation"), str) and bool(edge["relation"]), f"Missing edge relation: {edge_id}")
        _require(isinstance(edge.get("label"), str) and bool(edge["label"]), f"Missing edge label: {edge_id}")
        _require(edge["relation"] in relation_specs, f"Unsupported edge relation: {edge_id}")
        origin_kinds, target_kinds, required_status = relation_specs[edge["relation"]]
        _require(nodes[edge["source"]]["kind"] in origin_kinds and nodes[edge["target"]]["kind"] in target_kinds,
                 f"Invalid edge endpoint kinds: {edge_id}")
        _require(edge["status"] == required_status, f"Edge semantic status mismatch: {edge_id}")
        signature = (edge["source"], edge["relation"], edge["target"])
        _require(signature not in signatures, f"Duplicate semantic edge: {edge_id}")
        signatures.add(signature)
        _require(edge_id == "edge:" + _hash(_canonical(list(signature)))[:24], f"Edge ID mismatch: {edge_id}")
        properties = edge.get("properties", {})
        _require(isinstance(properties, dict), f"Invalid edge properties: {edge_id}")
        if required_status == "derived":
            _require(properties.get("mapping_origin") == "curated" and properties.get("hard_constraint") is False,
                     f"Derived edge must retain interpretation metadata: {edge_id}")
        if edge["relation"] in {"has_example", "example_transition"}:
            _require(properties.get("is_example") is True and properties.get("exhaustive") is False,
                     f"Example edge must remain non-exhaustive: {edge_id}")
        if edge["relation"] == "example_transition":
            _require(properties.get("hard_constraint") is False, f"Example transition cannot be a hard constraint: {edge_id}")
        provenance(edge.get("provenance"), edge_id)

    catalog_source = sources["catalog"]
    catalog, _ = _catalogue(_Source("catalog", Path(catalog_source["path"]), catalog_source["content"]))
    expected_values = {(category, index, value) for category, values in catalog.items() for index, value in enumerate(values)}
    actual_values = set()
    value_nodes = [node for node in nodes.values() if node["kind"] == "catalog_value"]
    for node in value_nodes:
        props = node["properties"]
        category, index = props.get("category"), props.get("catalog_index")
        _require(isinstance(category, str) and category in CATEGORIES and type(index) is int,
                 f"Invalid catalogue identity: {node['id']}")
        _require(node["id"] == _value_id(category, node["label"]), f"Catalogue value ID mismatch: {node['id']}")
        _require(f"category:{category}" in nodes, f"Catalogue category missing: {category}")
        _require(props.get("value") == node["label"], f"Catalogue value property mismatch: {node['id']}")
        _require(any(item["source_id"] == "catalog" and item["locator"] == f"/{category}/{index}"
                     for item in node["provenance"]), f"Catalogue value locator mismatch: {node['id']}")
        actual_values.add((category, index, node["label"]))
    _require(actual_values == expected_values and len(value_nodes) == len(expected_values), "Catalogue coverage mismatch")

    schema_source = sources["schema"]
    answers_source = sources.get("answers")
    expected = _assemble_graph(
        _Source("catalog", Path(catalog_source["path"]), catalog_source["content"]),
        _Source("schema", Path(schema_source["path"]), schema_source["content"]),
        _Source("answers", Path(answers_source["path"]), answers_source["content"]) if answers_source else None,
    )
    expected_nodes = {node["id"]: node for node in expected["nodes"]}
    expected_edges = {edge["id"]: edge for edge in expected["edges"]}
    for kind in NODE_KINDS:
        actual_ids = {node_id for node_id, node in nodes.items() if node["kind"] == kind}
        expected_ids = {node_id for node_id, node in expected_nodes.items() if node["kind"] == kind}
        _require(actual_ids == expected_ids, f"Schema node coverage mismatch: {kind}")
    for node_id, node in nodes.items():
        expected_node = expected_nodes[node_id]
        if node["kind"] == "rule":
            # A correct checksum does not prove a rule's meaning. Re-derive every
            # semantic property, description and exact source reference.
            _require(node == expected_node, f"Rule semantics mismatch: {node_id}")
        elif node["kind"] == "attribute":
            _require(node == expected_node, f"Attribute semantics mismatch: {node_id}")
        else:
            _require(node == expected_node, f"Node semantics mismatch: {node_id}")
    _require(edge_ids == set(expected_edges),
             f"Required edge structure mismatch: {len(set(expected_edges) - edge_ids)} missing, "
             f"{len(edge_ids - set(expected_edges))} unexpected")
    for edge in graph["edges"]:
        _require(edge == expected_edges[edge["id"]], f"Edge semantics mismatch: {edge['id']}")
    counts = graph["metadata"].get("counts")
    _require(isinstance(counts, dict), "Missing graph counts")
    for key, actual in (("nodes", len(nodes)), ("edges", len(edge_ids)), ("catalog_entries", len(value_nodes))):
        _require(type(counts.get(key)) is int and counts[key] == actual, f"Graph count mismatch: {key}")
    _require(graph.get("graph_id") == _graph_id(graph), "Graph content hash mismatch")
    _require(graph["metadata"] == expected["metadata"], "Graph metadata semantics mismatch")