File size: 13,479 Bytes
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
 
 
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
 
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Grade the 15 given events (data/events.json) against the docx test cases TC1-TC6.

    python tests/run_given.py                  # both readers
    python tests/run_given.py --reader rules   # deterministic reader only

Expected answers are in tests/given_cases.json. They were written by reading each
message by hand and looking ids up in the CSVs; the tower never reads that file.
Effects are graded by tests/run_cases.py's grader, which works from the CSVs, not
from tower/graph.py. On top of that, this script checks the evidence the docx asks
for per test case (graph path shape, reasons, three kinds of action).

Output: runs/given/<reader>/ and runs/given/REPORT.md
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from collections import Counter

HERE = os.path.dirname(os.path.abspath(__file__))
HITACHI = os.path.dirname(HERE)
sys.path.insert(0, HERE)
sys.path.insert(0, HITACHI)

import run_cases as rc  # noqa: E402
from tower.graph import WorldGraph  # noqa: E402

OUT = os.path.join(rc.RUNS, "given")
# TOWER_TEST_IDS=E-01,E-02,... grades only those events (the online demo's short set).
ONLY = {e.strip() for e in os.environ.get("TOWER_TEST_IDS", "").split(",") if e.strip()}
REAL = {"supplier_delay", "plant_outage", "quality_hold"}

# What each docx test case is about, and the graph-path evidence it requires.
TC = {
    "TC1": ("Supplier Delay", "Shipment β†’ Part β†’ Model (BOM) β†’ ProductionOrder β†’ CustomerOrder β†’ Dealer / Customer"),
    "TC2": ("Plant Outage", "Plant β†’ ProductionOrder β†’ CustomerOrder β†’ Dealer / Customer"),
    "TC3": ("Quality Hold", "Lot β†’ ProductionOrder β†’ Vehicle β†’ Dealer / Customer"),
    "TC4": ("Noise", "the reason the event was judged not relevant"),
    "TC5": ("Compound Incident", "one graph path per incident"),
    "TC6": ("Unconfirmed Report", "the reason the report was not actionable"),
}


def load_cases():
    events = {e["event_id"]: e for e in json.load(open(os.path.join(rc.DATA, "events.json")))}
    data = json.load(open(os.path.join(HERE, "given_cases.json")))
    cases = data["cases"] if isinstance(data, dict) else data
    if ONLY:
        cases = [c for c in cases if c["id"] in ONLY]
    for case in cases:
        case["text"] = events[case["id"]]["text"]
        case["source"] = events[case["id"]]["source"]
    return cases


def _paths(trace):
    return [p for r in trace.get("results", []) for p in r.get("graph_paths", [])]


def _starts(paths, word):
    return [p for p in paths if p and p[0].startswith(word)]


def _chain(path, *words):
    """True when the path's elements start with these words, in this order."""
    it = iter(path)
    return all(any(step.startswith(w) for step in it) for w in words)


def evidence_checks(case, trace, rows):
    """The docx's 'Evidence Required' and completeness rules for one event. Returns (ok, note) pairs."""
    tc = case["tc"]
    paths = _paths(trace)
    writes = [r for r in rows if r["ok"] and r["tool"] in rc.WRITE_TOOLS]
    kinds = {r["tool"] for r in writes}
    checks = [("summary and reason recorded", bool(trace.get("summary")))]
    checks.append(("no failed tool calls", all(r["ok"] for r in rows)))
    if tc == "TC1":
        full = [p for p in paths if _chain(p, "Shipment", "Part", "Model", "ProductionOrder", "CustomerOrder", "Dealer")]
        checks.append(("graph path starts at the Shipment", bool(full)))
        if not full:
            part = [p for p in paths if _chain(p, "Part", "Model", "ProductionOrder", "CustomerOrder", "Dealer")]
            checks.append(("fallback path Part β†’ … β†’ Dealer / Customer", bool(part)))
    if tc in ("TC2", "TC5"):
        checks.append(("outage path Plant β†’ PO β†’ CO β†’ Dealer / Customer",
                       any(_chain(p, "Plant", "ProductionOrder", "CustomerOrder", "Dealer") for p in paths)))
    if tc == "TC5":
        checks.append(("delay path for the second incident",
                       any(_chain(p, "ProductionOrder", "CustomerOrder", "Dealer") and p[0].split()[0] in ("Shipment", "Part")
                           for p in paths)))
    if tc == "TC3":
        checks.append(("lot path Lot β†’ PO β†’ Vehicle β†’ Dealer / Customer",
                       any(_chain(p, "Lot", "ProductionOrder", "Vehicle", "Dealer") for p in paths)))
    if tc in ("TC1", "TC2", "TC3", "TC5"):
        checks.append((f"β‰₯3 kinds of action (rule 9): {len(kinds)}", len(kinds) >= 3))
    if tc == "TC4":
        checks.append(("no calls at all", not rows))
    if tc == "TC6":
        tools = [r["tool"] for r in rows]
        reason = next((r["args"].get("reason") for r in rows if r["tool"] == "escalate"), "")
        checks.append(("escalate only, no writes", tools == ["escalate"]))
        checks.append(("escalation gives a reason", bool(reason)))
    return checks


# The report is read by people: kinds, fields and tools in words, not field names or tool ids.
_TOOL_WORDS = {"mes.reschedule": "reschedule", "mes.transfer": "transfer", "dealer.notify": "dealer notice",
               "dealer.stop_sale": "stop sale", "crm.assign_loaner": "loaner", "crm.notify_customer": "owner notice",
               "quality.hold_lot": "lot hold", "escalate": "escalate"}


def _who(reader) -> str:
    """A reader in words, never a model name."""
    return "Rule reader" if reader in (None, "rules") else "AI model"


def _words(name) -> str:
    """'plant_outage+supplier_delay' -> 'plant outage + supplier delay', 'plant_id' -> 'plant'."""
    text = str(name or "")
    return text.replace("+", " + ").replace("_id", "").replace("_", " ")


def _fields(inc: dict) -> str:
    """An incident's records and dates in words: 'plant P_TX, outage start 2027-03-19'."""
    skip = ("summary", "evidence", "reader", "kind", "model_reason", "question")
    parts = [f"{_words(k)} {', '.join(v) if isinstance(v, list) else v}" for k, v in inc.items() if v and k not in skip]
    return ", ".join(parts) or "no details"


def write_report(all_results, cases, traces_by_reader, rows_by_reader):
    names = list(all_results)
    lines = [
        f"# Given test cases β€” the {len(cases)} given events",
        "",
        "Each event is graded twice:",
        "",
        "1. **Effects**: the action log is compared with hand-written expected answers "
        "by an independent grader that works from the company tables. "
        "It checks the right orders moved and no others, slots after the disruption, transfers only when "
        "the home plant is full, one notice per dealer with exactly its orders, loaners by tier, priority "
        "and pool, the lots held, stop-sale VINs and owners notified.",
        "2. **Evidence**: the graph path, reasons and action kinds the docx asks for per test case.",
        "",
        "## Summary by docx test case",
        "",
        "| Test case | Events | " + " | ".join(f"{_who(n)}: effects" for n in names) + " | Evidence | Required evidence |",
        "|---|---|" + "---|" * len(names) + "---|---|",
    ]
    for tc, (title, needed) in TC.items():
        ids = [c["id"] for c in cases if c["tc"] == tc]
        cells = []
        for n in names:
            res = [r for r in all_results[n] if r["id"] in ids]
            cells.append(f"{sum(r['verdict'] == 'PASS' for r in res)}/{len(res)}")
        ev_ok = all(ok for c in cases if c["tc"] == tc
                    for _, ok in evidence_checks(c, traces_by_reader[names[0]][c["id"]], rows_by_reader[names[0]][c["id"]]))
        lines.append(f"| {tc} {title} | {', '.join(ids)} | " + " | ".join(cells) + f" | {'βœ…' if ev_ok else '⚠'} | {needed} |")
    lines.append("")
    for n in names:
        p = sum(r["verdict"] == "PASS" for r in all_results[n])
        calls = sum(len(v) for v in rows_by_reader[n].values())
        failed = sum(not r["ok"] for v in rows_by_reader[n].values() for r in v)
        lines.append(f"- **{_who(n)}**: {p}/{len(cases)} events pass on effects Β· {calls} tool calls Β· {failed} failed")
    lines.append("")

    for n in names:
        lines += [f"## Details β€” {_who(n)}", ""]
        for case, r in zip(cases, all_results[n]):
            trace = traces_by_reader[n][case["id"]]
            rows = rows_by_reader[n][case["id"]]
            lines.append(f"### {case['id']} β€” {case['tc']} {TC[case['tc']][0]} β€” {r['verdict']}")
            lines.append(f"> {case['text']}")
            lines.append("")
            lines.append(f"- **Read as:** {_words(r['classification'])} (reader: {', '.join(sorted({_who(x) for x in r['readers']}))})")
            for inc in trace.get("incidents", []):
                lines.append(f"  - {_words(inc['kind'])}: {_fields(inc)}")
            want = case["expect"]["incidents"]
            expected = "; ".join(f"{_words(w['kind'])}: {_fields(w)}" for w in want) if want else "no incident"
            lines.append(f"- **Expected:** {expected}; {'escalate to a human' if case['expect']['escalate'] else 'no escalation'}")
            counts = Counter(_TOOL_WORDS.get(row["tool"], _words(row["tool"])) for row in rows)
            lines.append(f"- **Calls:** {', '.join(f'{t} {n}' for t, n in counts.items()) if counts else 'none'}")
            for x in r["fails"]:
                lines.append(f"- ❌ {x}")
            for x in r["warnings"]:
                lines.append(f"- ⚠ {x}")
            for label, ok in evidence_checks(case, trace, rows):
                lines.append(f"- {'βœ…' if ok else '⚠'} {label}")
            paths = _paths(trace)
            if paths:
                lines.append(f"- **Graph path (1 of {len(paths)}):** {' β†’ '.join(paths[0])}")
            lines.append(f"- **Summary:** {trace.get('summary')}")
            lines.append("")
    path = os.path.join(OUT, "REPORT.md")
    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
    return path


def _reader_label(folder_name: str) -> str:
    """'rules' stays; 'llm_qwen2.5_0.5b' becomes 'qwen2.5:0.5b'."""
    if folder_name.startswith("llm_"):
        return folder_name[4:].replace("_", ":", 1)
    return folder_name


def _load_saved(folder_name: str):
    """A reader folder left by an earlier run, or None when it is incomplete."""
    folder = os.path.join(OUT, folder_name)
    results_path = os.path.join(folder, "results.json")
    traces_path = os.path.join(folder, "traces.json")
    log_path = os.path.join(folder, "action_log.jsonl")
    if not (os.path.isfile(results_path) and os.path.isfile(traces_path) and os.path.isfile(log_path)):
        return None
    results = json.load(open(results_path, encoding="utf-8"))
    traces = {t["event_id"]: t for t in json.load(open(traces_path, encoding="utf-8"))}
    rows = {}
    for line in open(log_path, encoding="utf-8"):
        if not line.strip():
            continue
        row = json.loads(line)
        if "event_id" in row:
            rows.setdefault(row["event_id"], []).append(row)
    return results, traces, rows


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--reader", choices=("rules", "llm", "both"), default="both")
    ap.add_argument("--from-run", help="grade the model's saved tower run in this folder (e.g. runs/run1) "
                                       "instead of reading the 15 events again")
    args = ap.parse_args()
    rc.OUT = OUT  # rc.run writes each reader's log, traces and results under runs/given/
    cases = load_cases()
    truth, graph = rc.Truth(), WorldGraph()
    from tower.agents.llm_reader import MODEL

    readers = ["rules", "llm"] if args.reader == "both" else [args.reader]
    all_results, traces_by_reader, rows_by_reader = {}, {}, {}
    fresh = set()
    for reader in readers:
        name = "rules" if reader == "rules" else MODEL
        if reader == "llm" and args.from_run:
            all_results[name] = rc.grade_saved(os.path.join(HITACHI, args.from_run), cases, truth, MODEL)
        else:
            all_results[name] = rc.run(reader, cases, truth, graph)
        folder_name = "rules" if reader == "rules" else "llm_" + MODEL.replace(":", "_")
        fresh.add(folder_name)
        folder = os.path.join(OUT, folder_name)
        traces_by_reader[name] = {t["event_id"]: t for t in json.load(open(os.path.join(folder, "traces.json"), encoding="utf-8"))}
        rows = {c["id"]: [] for c in cases}
        for line in open(os.path.join(folder, "action_log.jsonl"), encoding="utf-8"):
            row = json.loads(line)
            rows[row["event_id"]].append(row)
        rows_by_reader[name] = rows
    # A rules-only run must not drop the model column from the report.
    if os.path.isdir(OUT):
        for folder_name in sorted(os.listdir(OUT)):
            if folder_name in fresh or not os.path.isdir(os.path.join(OUT, folder_name)):
                continue
            loaded = _load_saved(folder_name)
            if not loaded:
                continue
            results, traces, rows = loaded
            by_id = {r["id"]: r for r in results}
            if any(c["id"] not in by_id or c["id"] not in traces for c in cases):
                continue
            label = _reader_label(folder_name)
            all_results[label] = [by_id[c["id"]] for c in cases]
            traces_by_reader[label] = traces
            rows_by_reader[label] = {c["id"]: rows.get(c["id"], []) for c in cases}
    print("report:", write_report(all_results, cases, traces_by_reader, rows_by_reader))


if __name__ == "__main__":
    main()