File size: 37,155 Bytes
41d37a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b70ac59
 
 
 
41d37a5
 
 
 
 
220d842
 
 
 
 
41d37a5
 
 
 
c00f2e8
41d37a5
 
c7de244
 
 
 
 
 
0b8b912
c7de244
 
41d37a5
 
53f8053
 
 
 
 
41d37a5
 
b70ac59
53f8053
 
41d37a5
eb175d2
41d37a5
 
 
 
 
 
 
53f8053
41d37a5
 
 
 
 
ee336e8
 
 
 
41d37a5
 
 
 
 
 
 
 
 
 
 
 
 
 
c00f2e8
 
 
 
 
41d37a5
 
c7de244
 
 
 
 
 
21cf25d
c7de244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c020d0e
 
 
 
 
 
555a518
 
 
 
 
 
 
c020d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7de244
 
 
 
 
 
 
 
 
 
 
 
41d37a5
 
 
 
 
 
 
 
53f8053
eb175d2
41d37a5
53f8053
41d37a5
 
 
c00f2e8
41d37a5
 
9d2e631
 
 
 
 
41d37a5
 
 
 
 
 
 
 
 
 
 
 
0d9133a
 
eb175d2
0d9133a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d2e631
 
 
 
 
 
0d9133a
 
 
 
 
41d37a5
 
 
 
 
 
 
 
 
 
 
 
 
 
0d9133a
 
b70ac59
41d37a5
 
 
b70ac59
 
 
 
 
 
0d9133a
b70ac59
 
0d9133a
 
 
 
b70ac59
41d37a5
 
ee336e8
 
 
 
41d37a5
b70ac59
41d37a5
b70ac59
41d37a5
 
 
 
 
 
 
c00f2e8
 
41d37a5
 
 
 
 
 
220d842
 
 
 
c7de244
 
41d37a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220d842
c7de244
 
220d842
41d37a5
 
220d842
41d37a5
 
 
 
 
 
220d842
f1fd6d0
 
 
 
220d842
f1fd6d0
c7de244
 
 
41d37a5
 
 
c00f2e8
41d37a5
 
 
 
220d842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41d37a5
 
 
b70ac59
41d37a5
b70ac59
 
41d37a5
220d842
c00f2e8
 
220d842
 
 
 
 
 
 
 
b70ac59
220d842
b70ac59
220d842
 
 
 
 
 
41d37a5
 
 
 
 
 
 
 
 
0b8b912
 
41d37a5
 
c00f2e8
 
 
 
41d37a5
c00f2e8
 
 
 
41d37a5
 
 
 
53f8053
41d37a5
 
 
 
 
220d842
 
41d37a5
220d842
 
 
 
41d37a5
 
 
 
53f8053
c7de244
 
 
 
 
0b8b912
41d37a5
 
 
 
220d842
c7de244
41d37a5
0b8b912
 
 
41d37a5
 
 
 
 
c00f2e8
 
41d37a5
c7de244
41d37a5
 
c7de244
 
 
 
 
 
c020d0e
 
c300290
 
 
 
c020d0e
 
 
0b8b912
 
41d37a5
 
 
 
 
 
 
 
 
 
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
"""
simulate_customers.py — ลูกค้าจำลองด้วย LLM คุยกับบอทจริง แล้ววัดว่าคุยจนได้รุ่นที่ถูกไหม (ผู้ใช้เลือก 25 ต.ค. · ข้อ 3)

ที่มา: Davidson et al. 2023 "User Simulation with Large Language Models for Evaluating Task-Oriented Dialogue"
(arXiv 2309.13233) — ให้ LLM เล่นเป็นผู้ใช้ตามเป้าหมาย แทนการเขียนบททดสอบเอง (test_conversation_leaks.py
จับได้แค่แบบที่ผู้เขียนนึกออก)

แบ่งหน้าที่
    LLM ลูกค้าจำลอง   เขียนข้อความของลูกค้าตาม persona + ข้อเท็จจริง (training/sim_goals.json) · ไม่รู้ชื่อรุ่น
    บอท               chat_interaction() ตัวจริง (assistant.py · Gemini · Jina · Qdrant ครบ)
    ผู้ตัดสิน          โค้ด ไม่ใช่ LLM — ชุดรุ่นที่ถูกคำนวณจากแคตตาล็อก (match_application/industry → filter_by_need)

ตัวชี้วัดต่อบทสนทนา
    reached      บอทเอ่ยรหัสรุ่นอย่างน้อยหนึ่งรุ่น
    hit          รุ่นที่เอ่ยอยู่ในชุดรุ่นที่ถูก (หรือ ชุดว่าง + บอทบอกว่าไม่มี)
    violations   รุ่นที่บอทแนะนำแต่ผิดเงื่อนไขแข็ง (พิทช์ / อุณหภูมิ) — นี่คือ "ตอบผิด"
                 นับเฉพาะรุ่นที่แนะนำจริง (eval_mentions.py · ผู้ใช้สั่งแก้ 26 ต.ค.) — บรรทัดที่บอกว่ารุ่นนั้น
                 ไม่ถึง/ไม่ผ่าน/ถูกตัดออก เป็นการเตือนที่ถูกต้อง ไม่นับ · รุ่นที่เอ่ยแต่ไม่นับอยู่ใน explained_not_recommended
    final_violations  เฉพาะคำแนะนำสุดท้าย (เทิร์นล่าสุดที่บอทแนะนำรุ่น) — รายการภาพรวมช่วงแรกไม่นับ
    offtopic     บอทปฏิเสธว่านอกเรื่องกลางบท
    repeats      บอทพูดข้อความเดิมซ้ำติดกัน (วนถาม)
    ended        done (ลูกค้าพอใจ) · giveup · max_turns · error
    turns        จำนวนเทิร์นของลูกค้า

เวลา (ผู้ใช้ขอ 25 ต.ค.: ข้อ 1 ทำให้ตอบช้าลงไหม) — วัดเฉพาะฝั่งบอท ไม่นับเวลาที่ลูกค้าจำลองคิด
    ทุกเทิร์นของบอท: sec · ตีความ (LLM / กฎ / -) · interp_ms (เวลาเรียกตัวตีความในเทิร์นนั้น)
    สรุป: เฉลี่ย · มัธยฐาน · p90 ทั้งหมด และแยก "เทิร์นที่ลูกค้าตอบคำถามค้าง" กับ "เทิร์นอื่น"
    เทียบสองรอบ: python simulate_customers.py --compare sim_rules.json sim_llm.json

รัน (ต้องมี .env แบบเดียวกับบอท · ใช้ Gemini ทั้งสองฝั่ง)
    python simulate_customers.py -o sim_r1.json                       # ทุกเป้าหมาย 1 รอบ
    python simulate_customers.py --repeats 3 -o sim_r1.json            # เป้าหมายละ 3 บท (ลูกค้าพูดต่างกันทุกรอบ)
    python simulate_customers.py --only G01,G05 -o probe.json
    python simulate_customers.py --goals training/redteam_goals.json --repeats 2 -o redteam.json   # ลูกค้าแบบจับผิด
    $env:ANSWER_INTERPRETER="rules"; python simulate_customers.py -o sim_rules.json   # เทียบกับกฎ regex
ได้ไฟล์ .json (ผลเต็ม) และ .txt (บทสนทนาแบบแชท ลูกค้า/บอท)

ลูกค้าแยกจากระบบที่ถูกวัด (branch sim-fair · 4 พ.ย. 2026) — ไม่ตั้ง env = แบบเดิมทุกตัวอักษร
    SIM_CUSTOMER_MODEL     ว่าง = ลูกค้าใช้ bot.llm_client ตัวเดียวกับบอท (แบบเดิม)
                           ตั้งชื่อรุ่น = สร้าง client ของลูกค้าเอง (google-genai) · โทเคนลูกค้าไม่ปนกับระบบ
                           · บันทึกโทเคนของระบบต่อเทิร์น (usage ในเทิร์นของบอท) · จำเป็นสำหรับ --module agent_assistant
    SIM_CUSTOMER_THINKING  thinking ของลูกค้า (ค่าแบบ GEMINI_THINKING) · ไม่กระทบ GEMINI_THINKING ของระบบ
    SIM_TACTIC_LABEL=1     ใส่ tactic ไว้หัวบทใน .txt · ใส่ tactic + tactic_checked: null ใน json ให้คนอ่านกรอก
    $env:SIM_CUSTOMER_MODEL="gemini-3.8-flash"; $env:SIM_CUSTOMER_THINKING="low"
    python simulate_customers.py --module agent_assistant --goals training/redteam_goals_v2_truth.json --repeats 2 -o x.json
"""
from __future__ import annotations
import os as _os, sys as _sys  # รากของ repo: import แพ็กเกจได้ และพาธข้อมูลนับจากราก
_ROOT = _os.path.dirname(_os.path.dirname(_os.path.abspath(__file__)))
if _ROOT not in _sys.path:
    _sys.path.insert(0, _ROOT)
_os.chdir(_ROOT)

import argparse

from eval import eval_mentions as EM
from eval import leak_detectors as LD
import importlib
from engine.core.entrypoints import import_bot
import json
import os
import re
import sys
import time
from collections import Counter

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

DONE, GIVEUP = "[จบ]", "[ยอมแพ้]"
OFFTOPIC_TH = "ผมตอบได้เฉพาะเรื่องสินค้า"
NONE_WORDS = re.compile(r"ไม่มีรุ่นที่|ไม่มีสายพาน.*ที่ตรง|ไม่พบรุ่น|ไม่มีรุ่นใด")
# ชุด blind (goal มี accept_codes): รวมสำนวนอื่นที่แปลว่า "ไม่มีรุ่นเข้าเงื่อนไข" — NONE_WORDS เดิมมาจากถ้อยคำของบอท
# ใช้เฉพาะเส้นทาง goal เพื่อให้ผลชุดเดิมเทียบกับรอบก่อนได้
NONE_WORDS_NEUTRAL = re.compile(NONE_WORDS.pattern + r"|ไม่มีรุ่นไหน|ไม่มีตัวไหน|ยังไม่มีรุ่น|ไม่มีสายพานรุ่นไหน"
                                r"|ไม่มี(?:สายพาน)?รุ่น\S{0,20}(?:ผ่าน|เหมาะ|ตรง|รองรับ|ทน)|ไม่มีในแคตตาล็อก")

SIM_SYSTEM = """คุณเล่นเป็นลูกค้าที่กำลังแชทกับบอทขายสายพาน/โซ่ลำเลียง เขียนเฉพาะข้อความของลูกค้าหนึ่งข้อความ
ลักษณะลูกค้า: {persona}
งานของลูกค้า: {application}
ข้อเท็จจริงที่ลูกค้ารู้ (บอกเมื่อบอทถาม หรือเมื่อเป็นธรรมชาติ ไม่ต้องบอกหมดในครั้งเดียว ยกเว้นลักษณะลูกค้าบอกให้ทำ):
{facts}
กฎ:
- พิมพ์แบบแชทจริง สั้น ภาษาพูด ไม่ต้องสุภาพเกิน ไม่ใช้ markdown
- ห้ามคิดชื่อรุ่นหรือรหัสสินค้าเอง พูดถึงรุ่นได้เฉพาะที่บอทเอ่ยมาก่อน
- ถ้าบอทเสนอค่าที่ตรงกับข้อเท็จจริงของคุณ ให้ยืนยัน · ถ้าไม่ตรง ให้บอกค่าที่ถูก
- ถ้าไม่รู้คำตอบ ให้บอกว่าไม่รู้
- เมื่อบอทแนะนำรุ่นแล้วและคุณพอใจ (หรือบอทบอกชัดว่าไม่มีรุ่นที่ตรง) ให้ถามต่อตามลักษณะลูกค้าถ้ามี แล้วจบด้วยข้อความที่มี {done}
- ถ้าบอทวนถามซ้ำ ตอบไม่ตรง หรือไม่เข้าใจคุณ 3 ครั้ง ให้จบด้วย {giveup}
"""
# ลูกค้าแบบจับผิด (training/redteam_goals.json · 26 ต.ค.) — มี tactic = ต่อท้ายกฎนี้ · ไม่มี = prompt เดิมทุกตัวอักษร
SIM_TACTIC = """แผนของคุณในบทนี้ (ทำให้ครบระหว่างบท อย่าบอกบอทว่ากำลังทดสอบ):
{tactic}
- ห้ามจบบทด้วย {done} ก่อนทำตามแผนครบ
"""


NO_CLIENT_MSG = ("❌ module {module} ไม่มี llm_client ให้ลูกค้าจำลองใช้ — ตั้ง SIM_CUSTOMER_MODEL เป็นชื่อรุ่นของลูกค้า "
                 "(เช่น $env:SIM_CUSTOMER_MODEL=\"gemini-3.8-flash\") แล้วรันใหม่ · สคริปต์ไม่เลือกรุ่นแทนให้")


def build_customer_client(model: str, thinking_raw: str):
    """client ของลูกค้าจำลอง แยกจากระบบที่ถูกวัด — ใช้ google-genai (มีทั้ง venv บอทและ venv agent)"""
    from engine.core.llm import GenAIClient, parse_thinking
    try:
        from google import genai as genai_new
    except ImportError as e:
        sys.exit(f"❌ SIM_CUSTOMER_MODEL ต้องใช้แพ็กเกจ google-genai แต่ import ไม่ได้ ({e})")
    key = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
    if not key:
        sys.exit("❌ SIM_CUSTOMER_MODEL ต้องมี GEMINI_API_KEY (หรือ GOOGLE_API_KEY)")
    return GenAIClient(genai_new, model, key, parse_thinking(thinking_raw) or {})


def customer_llm(bot, module: str):
    """(complete ของลูกค้า, client แยก หรือ None, meta ที่ต้องเพิ่ม)
    ไม่ตั้ง SIM_CUSTOMER_MODEL = bot.llm_client.complete และ meta ไม่มีคีย์ใหม่ (ผลเท่าเดิมทุกตัวอักษร)"""
    model = (os.getenv("SIM_CUSTOMER_MODEL") or "").strip()
    if not model:
        client = getattr(bot, "llm_client", None)
        if client is None or not hasattr(client, "complete"):
            sys.exit(NO_CLIENT_MSG.format(module=module))
        return client.complete, None, {}
    thinking = (os.getenv("SIM_CUSTOMER_THINKING") or "").strip()
    client = build_customer_client(model, thinking)
    return client.complete, client, {"customer_model": model, "customer_thinking": thinking or "ไม่ตั้ง",
                                     "customer_source": "separate"}


def system_meter(bot):
    """ตัวนับโทเคนของระบบที่ถูกวัด — แบบเดียวกับ run_answer_eval (engine.llm) · สำรอง llm_client"""
    return getattr(getattr(bot, "engine", None), "llm", None) or getattr(bot, "llm_client", None)


def system_info_of(bot, module: str, meter) -> dict:
    """ค่าตั้งของระบบที่ถูกวัด (คีย์แบบ run_answer_eval.system_info → eval_mlflow อ่านได้)"""
    info = {"system": "agent" if module.startswith("agent") else "bot",
            "gemini_model": getattr(meter, "model_name", "") or os.getenv("GEMINI_MODEL", ""),
            "gemini_thinking": os.getenv("GEMINI_THINKING", ""),
            "token_scope": getattr(meter, "usage_scope", "")}
    if info["system"] == "agent":
        # 10 พ.ย.: บันทึกฐาน Modutech ที่ agent ใช้จริง (r4 ต้องคู่กับ v31) · บันทึกอย่างเดียว ไม่เปลี่ยนพฤติกรรม
        try:
            from agent.tools_impl import CATALOGUE_PATH
            info["modutech_json"] = os.path.relpath(CATALOGUE_PATH, ROOT).replace("\\", "/")
        except Exception as e:                       # noqa: BLE001 — คนละไดรฟ์บน Windows ฯลฯ
            info["modutech_json"] = os.getenv("AGENT_MODUTECH_JSON") or f"? ({type(e).__name__})"
    if info["system"] == "bot":
        info["front_interpreter"] = (os.getenv("FRONT_INTERPRETER") or "rules").strip().lower()
    try:
        import subprocess
        info["commit"] = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
                                        text=True, timeout=10).stdout.strip()
    except Exception:                                # noqa: BLE001 — ไม่มี git ก็รันต่อได้
        info["commit"] = ""
    if hasattr(bot, "system_info"):
        try:
            info.update(bot.system_info())
        except Exception as e:                       # noqa: BLE001
            info["system_info_error"] = f"{type(e).__name__}: {e}"
    return info


_USAGE_SUM_KEYS = ("llm_calls", "prompt_token_count", "candidates_token_count", "thoughts_token_count",
                   "total_token_count")


def usage_total(usages) -> dict | None:
    """รวมโทเคนจากหลาย usage · ไม่มีข้อมูลเลย = None (ไม่ใช่ 0)"""
    got = [u for u in usages if isinstance(u, dict)]
    if not got:
        return None
    return {k: sum(u.get(k, 0) for u in got) for k in _USAGE_SUM_KEYS if any(k in u for u in got)}


def load_goals(path: str) -> list[dict]:
    return json.load(open(path, encoding="utf-8"))["goals"]


class Judge:
    """ชุดรุ่นที่ถูก — คำนวณจากแคตตาล็อกด้วยโค้ดชุดเดียวกับบอท (need_flow.filter_by_need)"""

    def __init__(self, root: str = ROOT):
        from bot import dialogue_state as DS
        from engine.brands.modutech import need_flow as NF
        self.NF = NF
        self.cat = DS.Catalogue(os.path.join(root, "data/modutech_v30_3.json"))
        mgr = DS.DialogueManager({}, self.cat)
        self.search = mgr.modutech_plugin.search
        self.detector = mgr.modutech_plugin.detector
        self.need_in = mgr.modutech_plugin._need_in

    def acceptable(self, g: dict) -> dict:
        # 2 พ.ย. (ผู้ใช้ตกลง ชุด blind): goal ที่ให้ accept_codes/hard_ok_codes มาเอง = คำตอบที่ถูกคำนวณแยกจากโค้ดบอท
        # (blind/compute_truth.py) → ใช้ตามนั้น ไม่ผ่าน need_flow ของบอท เพื่อไม่ให้บอทเป็นผู้ตัดสินตัวเอง
        if "accept_codes" in g:
            ok = list(g["accept_codes"])
            return dict(ok=ok, hard_ok=list(g.get("hard_ok_codes", ok)), source="goal", n_candidates=len(ok))
        t = g.get("application", "")
        am = self.search.match_application(t)
        if am is not None:
            cands, src = list(am.belt_codes), "application"
        else:
            im = self.search.match_industry(t)
            cands, src = (list(im[1]), "industry") if im else ([p["belt_code"] for p in self.cat.products], "all")
        f = self.NF.filter_by_need(self.cat, cands, g.get("pitch_mm"), g.get("temp_c"), g.get("wet_or_dry"))
        hard = self.NF.filter_by_need(self.cat, [p["belt_code"] for p in self.cat.products],
                                      g.get("pitch_mm"), g.get("temp_c"), g.get("wet_or_dry"))
        return dict(ok=f["kept"], hard_ok=hard["kept"], source=src, n_candidates=len(cands))

    def stated_before(self, transcript: list[dict], bot_index: int) -> set:
        """เงื่อนไขที่ลูกค้าพิมพ์ออกมาแล้ว ก่อนข้อความที่ bot_index ของบอท (pitch · temp · wet)"""
        from engine.brands.modutech.plugin import extract_modutech_slots
        seen, b = set(), -1
        for t in transcript:
            if t["role"] == "bot":
                b += 1
                if b >= bot_index:
                    break
                continue
            txt = t.get("text") or ""
            if self.NF.parse_pitch(txt) is not None or self.NF.stated_pitch(txt) is not None:
                seen.add("pitch")
            if self.NF.parse_temp(txt) is not None:
                seen.add("temp")
            if extract_modutech_slots(txt, ()).get("wet_or_dry"):
                seen.add("wet")
        return seen

    def hard_ok_stated(self, g: dict, stated: set) -> list[str]:
        if "accept_codes" in g:
            # goal ที่เป็นกลาง: ใช้ชุดตามเงื่อนไขที่ลูกค้าพูดแล้ว ถ้า goal ให้มา (key = "pitch+temp+wet" เรียงตามนี้)
            # ไม่ให้มา → ใช้ hard_ok_codes ของเงื่อนไขครบ (เข้มกว่าเดิม — รายงานในผลว่า source=goal)
            key = "+".join(k for k in ("pitch", "temp", "wet") if k in stated)
            by = g.get("hard_ok_by_stated") or {}
            return list(by.get(key, g.get("hard_ok_codes", g["accept_codes"])))
        return self.NF.filter_by_need(self.cat, [p["belt_code"] for p in self.cat.products],
                                      g.get("pitch_mm") if "pitch" in stated else None,
                                      g.get("temp_c") if "temp" in stated else None,
                                      g.get("wet_or_dry") if "wet" in stated else None)["kept"]

    def codes_in(self, text: str) -> list[str]:
        return list(self.detector.detect(text or "").parsed.belt_codes)


def score(g: dict, transcript: list[dict], judge: Judge, ended: str) -> dict:
    bot = [t["text"] for t in transcript if t["role"] == "bot"]
    offtopic = sum(OFFTOPIC_TH in b for b in bot[1:])
    repeats = sum(1 for a, b in zip(bot, bot[1:]) if a.strip() and a.strip() == b.strip())
    out = dict(ended=ended, turns=sum(t["role"] == "customer" for t in transcript),
               offtopic=offtopic, repeats=repeats)
    if g.get("brand") == "movex":
        hit = any(any(x in b for x in g.get("expect_any", [])) for b in bot)
        return {**out, "reached": hit, "hit": hit, "violations": [], "mentioned": []}
    acc = judge.acceptable(g)
    mentioned, recommended_codes, final_rec, final_i = [], [], [], -1
    for bi, b in enumerate(bot):
        turn_rec = []
        for c in judge.codes_in(b):
            if c not in mentioned:
                mentioned.append(c)
            if EM.recommended(c, b, contains=lambda t, l: t in judge.codes_in(l), grade_note_excludes=False):
                turn_rec.append(c)
        # 26 ต.ค. (ผู้ใช้สั่งแก้): นับผิดเงื่อนไขเฉพาะรุ่นที่บอทแนะนำจริง — "X ทนแห้งได้แค่ 116 °C จึงไม่ถึง 120"
        # เป็นการเตือนที่ถูกต้อง ไม่ใช่การแนะนำ (eval_mentions.py · sim4 G02)
        recommended_codes += [c for c in turn_rec if c not in recommended_codes]
        if turn_rec:
            final_rec, final_i = turn_rec, bi   # คำแนะนำสุดท้าย = เทิร์นล่าสุดที่บอทแนะนำรุ่น
    violations = [c for c in recommended_codes if c not in acc["hard_ok"]]
    # ตัวเลขสำหรับเล่ม: รายการภาพรวมก่อนลูกค้าบอกพิทช์ (sim4 G06 · G07) ไม่ใช่คำแนะนำสุดท้าย
    # 27 ต.ค. (redteam r3 R13#2): ตัดสินเฉพาะเงื่อนไขที่ลูกค้าพิมพ์ออกมาแล้วก่อนเทิร์นนั้น — ลูกค้าไม่เคยบอกพิทช์
    # บอทเสนอทุกพิทช์ไม่ใช่การผิดเงื่อนไข (ข้อเท็จจริงในเป้าหมายบอทมองไม่เห็น)
    hard_final = judge.hard_ok_stated(g, judge.stated_before(transcript, final_i)) if final_rec else acc["hard_ok"]
    final_violations = [c for c in final_rec if c not in hard_final]
    explained = [c for c in mentioned if c not in acc["hard_ok"] and c not in recommended_codes]
    if acc["ok"]:
        hit = any(c in acc["ok"] for c in mentioned)
    elif acc["source"] == "goal":
        # goal ที่ลูกค้าเปลี่ยนใจกลางทาง (blind B09: 1 นิ้ว → 2 นิ้ว): รุ่นที่แนะนำถูกต้องก่อนเปลี่ยนใจไม่ใช่ความผิด
        # ตัดสินจากจุดยืนสุดท้าย: บอทบอกว่าไม่มีรุ่นที่เข้าเงื่อนไข หลังเทิร์นสุดท้ายที่แนะนำรุ่น (final_i)
        hit = any(NONE_WORDS_NEUTRAL.search(b) for b in bot[final_i + 1:])
    else:
        hit = any(NONE_WORDS.search(b) for b in bot) and not violations
    return {**out, "reached": bool(mentioned), "hit": hit, "violations": violations, "mentioned": mentioned,
            "explained_not_recommended": explained, "final_violations": final_violations,
            "acceptable": acc["ok"], "acceptable_source": acc["source"]}


def sim_message(complete, g: dict, transcript: list[dict], temperature: float) -> str:
    facts = "\n".join(f"- {k}: {v}" for k, v in (g.get("facts") or {}).items())
    system = SIM_SYSTEM.format(persona=g["persona"], application=g.get("application", ""), facts=facts,
                               done=DONE, giveup=GIVEUP)
    if g.get("tactic"):
        system += SIM_TACTIC.format(tactic=g["tactic"], done=DONE)
    chat = "\n".join(f"{'ลูกค้า' if t['role'] == 'customer' else 'บอท'}: {t['text']}" for t in transcript)
    user = f"บทสนทนาจนถึงตอนนี้:\n{chat}\n\nเขียนข้อความถัดไปของลูกค้า (ข้อความเดียว):"
    text = (complete(system, user, temperature=temperature) or "").strip()
    return re.sub(r"^(ลูกค้า|customer)\s*:\s*", "", text, flags=re.IGNORECASE).strip()


_INTERP_RX = re.compile(r"ตีความ: (LLM|กฎ)")


def run_goal(g: dict, chat_fn, complete, judge: Judge, max_turns: int, temperature: float,
             interpreter=None, meter=None) -> dict:
    """meter (sim-fair): ตัวนับโทเคนของระบบ — ให้มา = บันทึก usage ต่อเทิร์นของบอท (None = ไม่บันทึก แบบเดิม)"""
    transcript: list[dict] = []
    history, last_pids, session_id, vit, graph = [], [], "", None, None
    ended = "max_turns"
    msg = g.get("opening") or ""
    t0 = time.time()
    for turn in range(max_turns):
        if turn > 0:
            try:
                msg = sim_message(complete, g, transcript, temperature)
            except Exception as e:                       # noqa: BLE001
                ended = f"sim_error: {type(e).__name__}: {e}"
                break
        clean = msg.replace(DONE, "").replace(GIVEUP, "").strip()
        if clean:
            transcript.append({"role": "customer", "text": clean})
        if DONE in msg or GIVEUP in msg:
            ended = "done" if DONE in msg else "giveup"
            if not clean:
                break
        if not clean:
            continue
        ms0 = getattr(interpreter, "total_ms", 0.0)
        if meter is not None and hasattr(meter, "last_usage"):
            meter.last_usage = None          # เริ่มเทิร์นใหม่ (แบบ run_answer_eval) — ไม่ปนกับเทิร์นก่อน
        tb = time.perf_counter()
        try:
            out = chat_fn(clean, None, history, last_pids, session_id, vit, graph)
            history, _s, refs, last_pids, session_id, vit, graph = out
            reply = next((m["content"] for m in reversed(history) if m["role"] == "assistant"
                          and not str(m.get("content", "")).startswith("<img")), "")
        except Exception as e:                           # noqa: BLE001
            transcript.append({"role": "bot", "text": f"[ERROR] {type(e).__name__}: {e}"})
            ended = "error"
            break
        m = _INTERP_RX.search(str(refs or ""))
        interp_ms = round(getattr(interpreter, "total_ms", 0.0) - ms0, 1)
        # เรียก LLM แล้วแต่เหตุผลไม่มีป้าย (ตัวตีความบอก "เปลี่ยนเรื่อง" → ทางปกติตัดสินต่อ) ก็นับเป็น LLM
        # (sim_llm 26 ต.ค. · G11: interp_ms 1901 แต่ป้าย "-" → answer_turns ของรอบ LLM ว่าง)
        label = m.group(1) if m else ("LLM" if interp_ms > 0 else "-")
        transcript.append({"role": "bot", "text": reply, "sec": round(time.perf_counter() - tb, 3),
                           "interp": label, "interp_ms": interp_ms})
        if meter is not None:
            u = getattr(meter, "last_usage", None)
            transcript[-1]["usage"] = json.loads(json.dumps(u)) if isinstance(u, dict) else None
        if ended in ("done", "giveup"):
            break
    res = score(g, transcript, judge, ended)
    res["issues"] = LD.detect(g, transcript, res, need_in=judge.need_in, codes_in=judge.codes_in)
    return {"goal": g["id"], "brand": g.get("brand"), "application": g.get("application"),
            "seconds": round(time.time() - t0, 1), **res, "transcript": transcript}


def _stats(xs: list[float]) -> dict:
    if not xs:
        return {"n": 0}
    s = sorted(xs)
    q = lambda p: s[min(len(s) - 1, int(round(p * (len(s) - 1))))]  # noqa: E731
    return {"n": len(s), "mean": round(sum(s) / len(s), 2), "median": round(q(0.5), 2), "p90": round(q(0.9), 2),
            "max": round(s[-1], 2)}


def latency(results: list[dict]) -> dict:
    """เวลาตอบของบอทต่อเทิร์น (วินาที) — แยกเทิร์นที่ลูกค้าตอบคำถามค้าง (มีการตีความ) กับเทิร์นอื่น"""
    bot = [t for r in results for t in r["transcript"] if t["role"] == "bot" and "sec" in t]
    ans = [t for t in bot if t.get("interp") in ("LLM", "กฎ")]
    llm = [t for t in ans if t["interp"] == "LLM"]
    return {"all_turns": _stats([t["sec"] for t in bot]),
            "answer_turns": _stats([t["sec"] for t in ans]),
            "other_turns": _stats([t["sec"] for t in bot if t not in ans]),
            "interpreter_ms": _stats([t["interp_ms"] for t in llm]),
            "answer_turns_by": dict(Counter(t["interp"] for t in ans))}


def summarize(results: list[dict]) -> dict:
    n = len(results)
    c = Counter(r["ended"] for r in results)
    pct = lambda k: round(100 * sum(bool(r.get(k)) for r in results) / n, 1) if n else 0.0  # noqa: E731
    return {"conversations": n, "hit_pct": pct("hit"), "reached_pct": pct("reached"),
            "with_violation_pct": pct("violations"), "final_violation_pct": pct("final_violations"),
            "with_offtopic_pct": pct("offtopic"),
            "with_repeat_pct": pct("repeats"), "ended": dict(c),
            "mean_turns": round(sum(r["turns"] for r in results) / n, 1) if n else 0.0,
            "issues_by_kind": dict(Counter(i["kind"] for r in results for i in r.get("issues", []))),
            "with_issue_pct": pct("issues"),
            "latency_sec": latency(results)}


def compare(a_path: str, b_path: str) -> None:
    """เทียบสองรอบ (เช่น กฎ vs LLM) — คุณภาพและเวลาต่อเทิร์น"""
    A, B = (json.load(open(p, encoding="utf-8")) for p in (a_path, b_path))
    sa, sb = A["summary"], B["summary"]
    print(f"{'':28}{A.get('answer_interpreter', '?'):>14}{B.get('answer_interpreter', '?'):>14}")
    for k in ("conversations", "hit_pct", "reached_pct", "with_violation_pct", "final_violation_pct", "with_offtopic_pct",
              "with_repeat_pct", "mean_turns"):
        print(f"{k:28}{str(sa.get(k)):>14}{str(sb.get(k)):>14}")
    for part in ("all_turns", "answer_turns", "other_turns"):
        for st in ("mean", "median", "p90"):
            va, vb = sa["latency_sec"][part].get(st), sb["latency_sec"][part].get(st)
            d = f"{vb - va:+.2f}" if isinstance(va, (int, float)) and isinstance(vb, (int, float)) else ""
            print(f"{'เวลา ' + part + ' ' + st + ' (วิ)':28}{str(va):>14}{str(vb):>14}  {d}")
    print(f"{'เรียกตัวตีความ (มิลลิวินาที)':28}{'':>14}{str(sb['latency_sec']['interpreter_ms']):>14}")


def write_txt(path: str, results: list[dict]) -> None:
    with open(path, "w", encoding="utf-8") as f:
        for r in results:
            flags = [k for k in ("violations", "offtopic", "repeats") if r.get(k)]
            f.write(f"\n=== {r['goal']}#{r.get('run', 1)} · {r['application']} · "
                    f"{'✓ ได้รุ่นที่ถูก' if r['hit'] else '✗ ไม่ได้รุ่นที่ถูก'} · จบแบบ {r['ended']}"
                    + (f" · ⚠ {', '.join(flags)}" if flags else "") + " ===\n")
            if "tactic_checked" in r:          # SIM_TACTIC_LABEL=1 — ให้คนอ่านเทียบกับบทว่าลูกค้าทำตามแผนไหม
                f.write(f"tactic: {r.get('tactic') or '(ไม่ระบุ)'}\n")
            if r.get("violations"):
                f.write(f"รุ่นที่ผิดเงื่อนไข: {r['violations']}\n")
            for i in r.get("issues", []):
                f.write(f"🚩 {i['kind']}" + (f" (บอทข้อความที่ {i['turn']})" if i.get("turn") else "")
                        + f": {i['detail']}\n")
            k = 0
            for t in r["transcript"]:
                if t["role"] == "bot":
                    k += 1
                flag = " 🚩" if t["role"] == "bot" and any(i.get("turn") == k for i in r.get("issues", [])) else ""
                f.write(f"{'🧑 ลูกค้า' if t['role'] == 'customer' else f'🤖 บอท [{k}]{flag}'}: {t['text']}\n")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--module", default="bot.assistant")
    ap.add_argument("--goals", default=os.path.join(ROOT, "training", "sim_goals.json"))
    ap.add_argument("--only", default="")
    ap.add_argument("--repeats", type=int, default=1)
    ap.add_argument("--max-turns", type=int, default=10)
    ap.add_argument("--temperature", type=float, default=1.0)
    ap.add_argument("-o", "--out", default="")
    ap.add_argument("--compare", nargs=2, metavar=("A.json", "B.json"), help="เทียบสองรอบแล้วจบ")
    a = ap.parse_args()
    if a.compare:
        return compare(*a.compare)
    if not a.out:
        sys.exit("ต้องระบุ -o ไฟล์ผล")

    goals = load_goals(a.goals)
    only = {x.strip() for x in a.only.split(",") if x.strip()}
    goals = [g for g in goals if not only or g["id"] in only]
    bot = import_bot(a.module)
    complete, cust_client, cust_meta = customer_llm(bot, a.module)
    meter = None
    if cust_client is not None:
        # ระบบไม่มีตัวนับ → object เปล่า: บันทึก usage = null ต่อเทิร์น (ไม่ใช่ 0 · ไม่ใช่ไม่มีคีย์)
        meter = system_meter(bot) or object()
    tactic_label = os.getenv("SIM_TACTIC_LABEL", "").strip() == "1"
    judge = Judge()
    results = []
    for g in goals:
        for k in range(a.repeats):
            r = run_goal(g, bot.chat_interaction, complete, judge, a.max_turns, a.temperature,
                         interpreter=getattr(bot, "answer_interpreter", None), meter=meter)
            r["run"] = k + 1
            if tactic_label:
                r["tactic"] = g.get("tactic")
                r["tactic_checked"] = None     # คนอ่าน transcript แล้วกรอก true/false (ไม่ใช้ LLM ตัดสิน)
            results.append(r)
            print(f"  {'✓' if r['hit'] else '✗'} {g['id']}#{k + 1} {g.get('application', '')[:20]:20} "
                  f"{r['ended']:9} เทิร์น {r['turns']:2}"
                  + (f" ⚠ ผิดเงื่อนไข {r['violations']}" if r["violations"] else "")
                  + (f" ⚠ นอกเรื่อง {r['offtopic']}" if r["offtopic"] else "")
                  + (f" ⚠ ซ้ำ {r['repeats']}" if r["repeats"] else "")
                  + (f" 🚩 {sorted({i['kind'] for i in r['issues']})}" if r.get("issues") else ""))
    summary = summarize(results)
    meta = {"module": a.module, "llm": getattr(system_meter(bot), "describe", lambda: "")(),
            "answer_interpreter": getattr(bot, "ANSWER_INTERPRETER", "?"), "repeats": a.repeats,
            "max_turns": a.max_turns, "temperature": a.temperature}
    if cust_client is not None:
        meta.update(cust_meta)
        meta["customer_llm"] = getattr(cust_client, "describe", lambda: "")()
        meta["customer_usage_total"] = usage_total([cust_client.last_usage])
        meta["system_usage_total"] = usage_total(t.get("usage") for r in results for t in r["transcript"]
                                                 if t["role"] == "bot")
        # หลักฐานสำหรับเล่ม/MLflow: ไฟล์เป้าหมายที่ใช้ (ล็อกด้วย sha) + ค่าตั้งของระบบที่ถูกวัด
        import hashlib
        try:
            meta["goals"] = os.path.relpath(os.path.abspath(a.goals), ROOT).replace("\\", "/")
        except ValueError:   # Windows: ไฟล์เป้าหมายอยู่คนละไดรฟ์กับ repo (เช่น temp บน C: · repo บน E:) → เก็บพาธเต็ม
            meta["goals"] = os.path.abspath(a.goals).replace("\\", "/")
        meta["goals_sha"] = hashlib.sha256(open(a.goals, "rb").read()).hexdigest()
        meta["only"] = sorted(only)
        meta["system_info"] = system_info_of(bot, a.module, system_meter(bot))
    if tactic_label:
        meta["tactic_label"] = True
    json.dump({**meta, "summary": summary, "results": results}, open(a.out, "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    txt = os.path.splitext(a.out)[0] + ".txt"
    write_txt(txt, results)
    print(f"\nสรุป: {summary}")
    print(f"เขียนแล้ว: {a.out} · {txt}")


if __name__ == "__main__":
    main()