File size: 5,544 Bytes
a46f204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Hard rules applied to every xevyo-01 plan before code acts on it.

The planner proposes; code decides. These rules are the code side of the
safety labelling rules: each one mirrors what the serving application already does after
its own deciders, so the model can never route around them.

    from hard_rules import apply
    plan, changes = apply(plan, example)     # changes: what was overridden (no text), for logs

Safety:
  * possible_crisis or possible_emergency: no picture (generate/edit become none, or
    analyze when an image is attached: the vision path answers), no file, no style.*
    directive, no search ("no search for a crisis"; "emergency questions about what to do
    now are answered, not searched").
  * possible_crisis: no tools and no data tool.
  * medication_risk, possible_emergency, possible_crisis: domain medical, so the turn goes
    to the agent path (needs_tools true; quick depth becomes normal).
Mechanical:
  * visible_text on one line; a standalone_question equal to the message is dropped;
  * directives whose input requirements fail (directives.json `requires`), and
    style.followup next to style.casual, are dropped.

Never: lowering a concern, adding a picture, a file, a tool or a search. The concern
itself is only ever raised by the deterministic screen (code takes the max of the two).
A plan still invalid after these rules is not used: `usable(plan, example)` is False and
the backend falls back to today's pipeline for that turn.
"""
import copy
import sys
from pathlib import Path

_SPEC = Path(__file__).resolve().parents[1] / "spec"
if str(_SPEC) not in sys.path:
    sys.path.insert(0, str(_SPEC))
import render
import validate

SAFETY_TURNS = ("possible_crisis", "possible_emergency")
MEDICAL_CONCERNS = ("medication_risk", "possible_emergency", "possible_crisis")
PICTURE = ("generate", "edit")


def _requirements_met(entry: dict, example: dict) -> bool:
    req = entry.get("requires", {})
    history = [m for m in example.get("history") or [] if m.get("role") in ("user", "assistant")]
    if "history_empty" in req and req["history_empty"] != (not history):
        return False
    return all(bool(example.get(flag)) == req[flag]
               for flag in ("document_attached", "signed_in", "memory_enabled") if flag in req)


def apply(plan: dict, example: dict) -> tuple[dict, list[str]]:
    """Return (plan in canonical form after the hard rules, list of rule names that fired)."""
    if not isinstance(plan, dict):
        return plan, []
    p = render.fill_defaults(copy.deepcopy(plan))
    changes: list[str] = []
    concern = p["safety_concern"]
    image = p["image"] if isinstance(p["image"], dict) else {"action": "none"}

    if concern in SAFETY_TURNS:
        if image.get("action") in PICTURE:
            p["image"] = {"action": "analyze"} if example.get("attached_image") else {"action": "none"}
            changes.append("safety.no_picture")
        if p["request_kind"] != "chat" or p["doc_format"] is not None:
            p["request_kind"], p["doc_format"] = "chat", None
            changes.append("safety.no_file")
        if any(isinstance(d, str) and d.startswith("style.") for d in p["directives"]):
            p["directives"] = [d for d in p["directives"] if not (isinstance(d, str) and d.startswith("style."))]
            changes.append("safety.no_style")
        if p["needs_search"] or p["search_queries"]:
            p["needs_search"], p["search_queries"] = False, []
            changes.append("safety.no_search")
    if concern == "possible_crisis":
        if p["tools"]:
            p["tools"] = []
            changes.append("safety.no_tools")
        if p["data_tool"] != "none":
            p["data_tool"] = "none"
            changes.append("safety.no_data_tool")
    if concern in MEDICAL_CONCERNS and (p["image"] or {}).get("action") not in PICTURE and p["domain"] != "medical":
        p["domain"] = "medical"
        changes.append("safety.medical_domain")
    if (changes and p["domain"] == "medical" and not p["clarify"] and p["request_kind"] == "chat"
            and (p["image"] or {}).get("action") not in PICTURE):
        if not p["needs_tools"]:
            p["needs_tools"] = True
            changes.append("route.agent")
        if p["depth"] == "quick":
            p["depth"] = "normal"
            changes.append("route.not_quick")

    image = p["image"] if isinstance(p["image"], dict) else {}
    vt = image.get("visible_text")
    if isinstance(vt, str) and "\n" in vt:
        image["visible_text"] = " ".join(part.strip() for part in vt.splitlines() if part.strip())
        changes.append("image.one_line")
    sq = p["standalone_question"]
    if isinstance(sq, str) and validate._norm(sq) == validate._norm(example.get("message", "")):
        p["standalone_question"] = None
        changes.append("standalone.same_as_message")
    catalogue = validate._directives()
    kept = [d for d in p["directives"]
            if not (isinstance(d, str) and d in catalogue and not _requirements_met(catalogue[d], example))]
    if "style.casual" in kept and "style.followup" in kept:
        kept.remove("style.followup")
    if kept != p["directives"]:
        p["directives"] = kept
        changes.append("directives.requirements")
    return render.canonicalize(p), changes


def usable(plan: dict, example: dict) -> bool:
    """True when the plan (after apply) passes spec/validate.py; otherwise use today's pipeline."""
    return isinstance(plan, dict) and not validate.validate_plan(plan, example)