File size: 7,397 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
"""Model-independent dependencies for incremental verification.

These rules schedule inference; they never infer a verdict or edit a fact.
Unknown paraphrases remain a limitation, so full_prefix is retained as a control.
"""
from __future__ import annotations

import re
from functools import lru_cache

SCHEDULING_VERSION = "incremental-1.0"

_CORRECTION = re.compile(
    r"\b(?:ошиб\w*|оговор\w*|перепут\w*|поправ\w*|неверн\w*|"
    r"на самом деле|имел[аи]? в виду|не про|не у меня|не я|это не я|"
    r"(?:у|сделал\w*|делал\w*)\s+(?:сосед\w*|брат\w*|коллег\w*)|"
    r"этого не|не делал\w*|не выполнял\w*)\b", re.I)
_RESPONSE = re.compile(
    r"^\s*(?:да|нет|ага|угу|верно|точно|соглас\w*|подтверж\w*|"
    r"отказыва\w*|сделал\w*|готово|выполн\w*|не надо|не нужно)\b", re.I)
_DENIAL = re.compile(r"\b(?:не|нет|никогда|отказ\w*)\b", re.I)
_TIME = re.compile(
    r"\b(?:вчера|позавчера|сегодня|завтра|послезавтра|через|назад|"
    r"(?:с|со|до|после|к|в|во)\s+(?:понедельник\w*|вторник\w*|сред\w*|"
    r"четверг\w*|пятниц\w*|суббот\w*|воскресень\w*|\d))\b|\d{4}-\d{2}-\d{2}", re.I)
_STOP = frozenset({"клиент", "услуга", "устройство", "объект", "это", "этот", "эта", "меня", "вас", "пожалуйста"})
_ATTRIBUTE_CUES = {
    "tariff": re.compile(r"\bтариф\w*", re.I),
    "ticket_status": re.compile(r"\b(?:заявк\w*|тикет\w*)", re.I),
    "action": re.compile(r"\b(?:сделал\w*|делал\w*|выполн\w*|перезагруз\w*|провер\w*|замен\w*)", re.I),
    "agreement": re.compile(r"\b(?:соглас\w*|договор\w*|выезд\w*|визит\w*|мастер\w*)", re.I),
    "service_state": re.compile(r"\b(?:работ\w*|обрыв\w*|завис\w*|скорост\w*|сигнал\w*)", re.I),
}


@lru_cache(maxsize=512)
def _roots(text: str) -> frozenset[str]:
    # Broad roots are only a conservative relevance signal, never normalization.
    return frozenset(word[:5] for word in re.findall(r"[^\W_]+", text.casefold().replace("ё", "е"))
                     if len(word) >= 3 and word not in _STOP)


def _names(candidate: dict) -> frozenset[str]:
    result = _roots(candidate["object"]["name"])
    for alternative in candidate.get("entity_candidates", []):
        result |= _roots(alternative.get("name", ""))
    return result


def _same_object(left: dict, right: dict) -> bool:
    a, b = left["object"], right["object"]
    if a.get("id") and b.get("id"):
        return a["type"] == b["type"] and a["id"] == b["id"]
    return a["type"] == b["type"] and a["name"].casefold() == b["name"].casefold()


def reverification_reason(candidate: dict, cached_entry: dict | None, turns: list[dict],
                          trigger: dict, candidates: dict[str, dict]) -> str | None:
    """Return a stable reason to call the model, or None to reuse its decision.

    Scheduling depends on candidate/source/context, never on model verdicts or
    model-selected citations. Revisions invalidate the whole dependency graph.
    """
    if cached_entry is None:
        return "new_candidate"
    if candidate != cached_entry["candidate"]:
        return "candidate_changed"
    if trigger["type"] == "turn_revised":
        return "transcript_revised"
    by_idx = {turn["idx"]: turn for turn in turns}
    for old in cached_entry["pack"]["dialogue_evidence"]:
        current = by_idx.get(old["idx"])
        if current is None or any(current.get(k, 0) != old.get(k, 0) for k in ("text", "speaker", "revision")):
            return "context_revised"
    incoming = by_idx[trigger["turn_idx"]]
    position = next(i for i, turn in enumerate(turns) if turn["idx"] == incoming["idx"])
    previous = turns[position - 1] if position else None
    source_idx = candidate["source"]["turn_idx"]
    source = by_idx[source_idx]
    text = incoming["text"]
    roots = _roots(text)
    predicate = _roots(candidate.get("canonical_value") or candidate["raw_value"]) - _names(candidate)
    related_predicate = bool(roots & predicate)
    related_object = bool(roots & _names(candidate))
    mentioned_objects = [other for other in candidates.values() if roots & _names(other)]
    object_matches = not mentioned_objects or related_object
    source_position = next(i for i, turn in enumerate(turns) if turn["idx"] == source_idx)
    first_response = next((t for t in turns[source_position + 1:] if t["speaker"] == "client"), None)
    first_answer = (first_response is not None and first_response["idx"] == incoming["idx"]
                    and cached_entry["pack"]["as_of_turn"] < incoming["idx"])
    question_anchor = (previous is not None and previous["speaker"] == "operator" and "?" in previous["text"]
                       and cached_entry["pack"]["as_of_turn"] == previous["idx"])
    recent = previous is not None and (source_idx == previous["idx"] or question_anchor)
    dependent = (candidate.get("speech_act") in {"question", "proposal"}
                 or candidate["speaker"] == "operator" or "?" in source["text"]
                 or candidate.get("entity_resolution") == "unresolved")

    # A correction without an explicit referent is ambiguous: prefer extra
    # inference to silently retaining an invalidated assertion.
    if _CORRECTION.search(text):
        attributes = {attr for attr, pattern in _ATTRIBUTE_CUES.items() if pattern.search(text)}
        if object_matches and (not attributes or candidate["attribute"] in attributes):
            return "explicit_correction"
    if incoming["speaker"] == "client":
        if dependent and (first_answer or question_anchor):
            return "answer_to_source"
        if recent and (_RESPONSE.search(text) or _TIME.search(text)):
            return "local_response_or_time"
        if object_matches and related_predicate and _DENIAL.search(text):
            return "related_denial"
        if dependent and object_matches and related_predicate and (_RESPONSE.search(text) or _TIME.search(text)):
            return "related_response"
        if candidate.get("entity_resolution") == "unresolved" and first_answer and related_object:
            return "entity_clarification"
    # A new question establishes which old claim a subsequent short answer is
    # about. Its verification boundary becomes an explicit dependency anchor.
    if incoming["speaker"] == "operator" and "?" in text and object_matches and related_predicate:
        return "related_question"
    # Explicit opposite-polarity mentions of the same predicate are evidence
    # about the old claim. Ordinary A -> B state transitions only need reduction.
    for other in candidates.values():
        if (other["source"]["turn_idx"] == incoming["idx"] and other["attribute"] == candidate["attribute"]
                and _same_object(candidate, other) and other["polarity"] != candidate["polarity"]
                and _roots(other.get("canonical_value") or other["raw_value"]) & _roots(candidate.get("canonical_value") or candidate["raw_value"])):
            return "opposite_polarity_mention"
    return None