test_triage.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. """Tests for the triage analyzer (todos 3, 9, 10, 11). Pure, hardware-free."""
  2. import json
  3. import logging
  4. from pathlib import Path
  5. from types import SimpleNamespace
  6. import pytest
  7. from stt_daemon import events
  8. from stt_daemon.assistant import triage
  9. from stt_daemon.assistant.service import AssistantService
  10. from stt_daemon.assistant.triage import FactLedger, TriageAnalyzer, load_questions
  11. from stt_daemon.config import Config
  12. from stt_daemon.tui.state import ViewState
  13. EXAMPLE_PATH = str(Path(__file__).resolve().parent.parent / "questions.example.json")
  14. def _cfg(path=EXAMPLE_PATH, **overrides):
  15. base = {
  16. "questions_file": path,
  17. "state_char_budget": 1200,
  18. "confidence_field": "answer_confidence",
  19. "escalate_threshold": 0.6,
  20. "choice_min_confidence": 0.85,
  21. }
  22. base.update(overrides)
  23. return SimpleNamespace(**base)
  24. def _write_questions(tmp_path, questions):
  25. path = tmp_path / "questions.json"
  26. path.write_text(json.dumps(questions), encoding="utf-8")
  27. return str(path)
  28. def _analyzer(tmp_path, questions=None, **overrides):
  29. if questions is None:
  30. return TriageAnalyzer(_cfg(**overrides))
  31. return TriageAnalyzer(_cfg(_write_questions(tmp_path, questions), **overrides))
  32. # --- todo 3: load_questions -------------------------------------------------
  33. def test_load_example_order_preserved():
  34. raw = json.loads(Path(EXAMPLE_PATH).read_text(encoding="utf-8"))
  35. questions = load_questions(EXAMPLE_PATH)
  36. assert questions is not None
  37. assert questions
  38. assert list(questions.keys()) == list(raw.keys())
  39. for definition in questions.values():
  40. assert definition["type"] in {"choice", "score", "noul"}
  41. assert isinstance(definition["instructions"], str)
  42. assert definition["instructions"].strip()
  43. def test_example_questions_match_design():
  44. questions = load_questions(EXAMPLE_PATH)
  45. assert questions is not None
  46. assert list(questions.keys()) == [
  47. "substantive_update",
  48. "opportunity",
  49. "blocker",
  50. "decision_status",
  51. "action_item",
  52. "responsibility_clarity",
  53. "deadline",
  54. "open_question",
  55. ]
  56. for qid, definition in questions.items():
  57. assert isinstance(definition["instructions"], str)
  58. assert definition["instructions"].strip()
  59. if definition["type"] == "choice":
  60. criteria = definition["criteria"]
  61. options = list(criteria.keys()) if isinstance(criteria, dict) else list(criteria)
  62. assert "other" in options
  63. assert len(options) <= 7
  64. if definition["type"] == "noul":
  65. assert isinstance(definition.get("instructions"), str)
  66. assert definition["instructions"].strip()
  67. def test_load_missing_file_returns_none_with_warning(caplog):
  68. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  69. assert load_questions("/nonexistent/questions.json") is None
  70. assert caplog.records, "expected a warning for the missing file"
  71. def test_load_bad_json_returns_none_with_warning(tmp_path, caplog):
  72. path = tmp_path / "questions.json"
  73. path.write_text("{not valid json", encoding="utf-8")
  74. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  75. assert load_questions(str(path)) is None
  76. assert caplog.records
  77. @pytest.mark.parametrize(
  78. "bad_entry",
  79. [
  80. {"type": "mystery", "instructions": "do something"}, # unknown type
  81. {"type": "score", "instructions": "rate it", "criteria": {"0": "low"}}, # score dict
  82. { # noul criteria with a bad key
  83. "type": "noul",
  84. "instructions": "holds?",
  85. "criteria": {"true": "yes", "maybe": "hmm"},
  86. },
  87. "just a string", # non-object entry
  88. {"type": "choice", "instructions": "pick one", "criteria": []}, # empty choice
  89. {"type": "choice", "instructions": "pick one", "criteria": {}}, # empty choice dict
  90. {"type": "choice", "criteria": ["a", "b"]}, # missing instructions
  91. {"type": "score", "instructions": "rate it", "criteria": ["a", None]}, # None level
  92. {"type": "noul", "instructions": "holds?", "criteria": ["true"]}, # noul list
  93. ],
  94. )
  95. def test_load_malformed_returns_none_with_warning(tmp_path, caplog, bad_entry):
  96. path = _write_questions(
  97. tmp_path, {"good": {"type": "noul", "instructions": "ok?"}, "bad": bad_entry}
  98. )
  99. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  100. assert load_questions(str(path)) is None
  101. assert caplog.records
  102. # --- todo 9: normalize ------------------------------------------------------
  103. def _score_questions():
  104. return {
  105. "severity": {
  106. "type": "score",
  107. "instructions": "How severe is the issue?",
  108. "criteria": ["none", "low", "high", "critical"],
  109. },
  110. "category": {
  111. "type": "choice",
  112. "instructions": "What is this about?",
  113. "criteria": {"support": "help needed", "sales": "buying"},
  114. },
  115. "churn_risk": {"type": "noul", "instructions": "User may leave."},
  116. }
  117. def test_normalize_choice_exact(tmp_path):
  118. analyzer = _analyzer(tmp_path, _score_questions())
  119. payload = {
  120. "model": "multilingual",
  121. "answers": {
  122. "category": {
  123. "type": "choice",
  124. "choice": "support",
  125. "confidence": 0.7,
  126. "answer_confidence": 0.4,
  127. }
  128. },
  129. "usage": {"input_tokens": 123, "output_tokens": 0},
  130. }
  131. result = analyzer.normalize(payload)
  132. assert result["order"] == ["category"]
  133. assert result["items"]["category"] == {
  134. "kind": "choice",
  135. "choice": "support",
  136. "confidence": 0.7,
  137. "answer_confidence": 0.4,
  138. "gate": 0.4,
  139. "flagged": True,
  140. }
  141. assert result["input_tokens"] == 123
  142. assert result["escalated"] is True
  143. def test_normalize_score_with_legend(tmp_path):
  144. analyzer = _analyzer(tmp_path, _score_questions())
  145. payload = {
  146. "answers": {
  147. "severity": {
  148. "type": "score",
  149. "score": 2.6,
  150. "legend": {"0": "none", "1": "low", "2": "high", "3": "critical"},
  151. "confidence": 0.5,
  152. "answer_confidence": 0.6,
  153. }
  154. },
  155. "usage": {"input_tokens": 7, "output_tokens": 0},
  156. }
  157. item = analyzer.normalize(payload)["items"]["severity"]
  158. assert item["kind"] == "score"
  159. assert item["expected"] == 2.6
  160. assert item["level"] == 3
  161. assert item["label"] == "critical"
  162. assert item["confidence"] == 0.5
  163. assert item["answer_confidence"] == 0.6
  164. assert item["gate"] == 0.6
  165. assert item["flagged"] is True
  166. def test_normalize_score_legend_fallback(tmp_path):
  167. analyzer = _analyzer(tmp_path, _score_questions())
  168. payload = {
  169. "answers": {
  170. "severity": {"type": "score", "score": 1.2, "confidence": 0.9, "answer_confidence": 0.9}
  171. }
  172. }
  173. item = analyzer.normalize(payload)["items"]["severity"]
  174. assert item["level"] == 1
  175. assert item["label"] == "low" # falls back to criteria[level]
  176. assert item["flagged"] is False # 1.2 < (4 - 1) * 0.5
  177. def test_normalize_noul_and_bare_payload(tmp_path):
  178. analyzer = _analyzer(tmp_path, _score_questions())
  179. bare = {
  180. "churn_risk": {"type": "noul", "noul": 0.9, "confidence": 0.9, "answer_confidence": 0.85}
  181. }
  182. result = analyzer.normalize(bare)
  183. assert result["order"] == ["churn_risk"]
  184. assert result["items"]["churn_risk"] == {
  185. "kind": "noul",
  186. "p": 0.9,
  187. "confidence": 0.9,
  188. "answer_confidence": 0.85,
  189. "gate": 0.85,
  190. "flagged": True,
  191. }
  192. assert result["input_tokens"] == 0
  193. def test_normalize_skips_unknown_qid_and_malformed(tmp_path):
  194. analyzer = _analyzer(tmp_path, _score_questions())
  195. payload = {
  196. "answers": {
  197. "ghost": {"type": "noul", "noul": 0.99, "confidence": 0.9, "answer_confidence": 0.9},
  198. "category": {"type": "choice", "choice": 42}, # malformed: no confidences
  199. "churn_risk": "nonsense", # malformed: not a dict
  200. },
  201. "usage": {"input_tokens": 3, "output_tokens": 0},
  202. }
  203. result = analyzer.normalize(payload)
  204. assert result["order"] == []
  205. assert result["items"] == {}
  206. assert result["escalated"] is False
  207. def test_normalize_ignores_side_channel_fields(tmp_path):
  208. analyzer = _analyzer(tmp_path, _score_questions())
  209. payload = {
  210. "answers": {
  211. "category": {
  212. "type": "choice",
  213. "choice": "sales",
  214. "confidence": 0.95,
  215. "answer_confidence": 0.9,
  216. "action": {"act" + "_probability": 0.99},
  217. }
  218. },
  219. "usage": {"input_tokens": 1, "output_tokens": 0},
  220. }
  221. result = analyzer.normalize(payload)
  222. assert result["items"]["category"]["flagged"] is False
  223. assert "act" + "_probability" not in json.dumps(result)
  224. source = Path(triage.__file__).read_text(encoding="utf-8")
  225. assert "act" + "_probability" not in source
  226. def test_normalize_gating_field_selectable(tmp_path):
  227. analyzer = _analyzer(tmp_path, _score_questions(), confidence_field="confidence")
  228. payload = {
  229. "answers": {
  230. "category": {
  231. "type": "choice",
  232. "choice": "sales",
  233. "confidence": 0.5,
  234. "answer_confidence": 0.99,
  235. }
  236. }
  237. }
  238. item = analyzer.normalize(payload)["items"]["category"]
  239. assert item["gate"] == 0.5 # gates on confidence, keeps both
  240. assert item["answer_confidence"] == 0.99
  241. assert item["flagged"] is True
  242. # --- todo 9: condensation ---------------------------------------------------
  243. def test_condense_keeps_newest_chronological_no_numerals(tmp_path):
  244. analyzer = _analyzer(tmp_path, _score_questions(), state_char_budget=40)
  245. window = ["alpha first", "beta second", "gamma third newest here"]
  246. state = analyzer.build_state(window)
  247. assert "gamma third newest here" in state
  248. assert "alpha first" not in state # oldest dropped under the budget
  249. lines = state.splitlines()
  250. assert all(line.startswith("- ") for line in lines)
  251. assert not any(ch.isdigit() for ch in state) # no numerals injected
  252. # chronological restore: kept lines stay in original order
  253. kept = [u for u in window if u in state]
  254. assert [line[2:] for line in lines] == kept
  255. def test_condense_empty_window(tmp_path):
  256. analyzer = _analyzer(tmp_path, _score_questions())
  257. assert analyzer.build_state([]) == ""
  258. # --- todo 10: escalation + extraction ---------------------------------------
  259. def _signals(choice_gate=0.9, noul_p=0.1, score_expected=0.2):
  260. return {
  261. "order": ["category", "churn_risk", "severity"],
  262. "items": {
  263. "category": {
  264. "kind": "choice",
  265. "choice": "sales",
  266. "confidence": choice_gate,
  267. "answer_confidence": choice_gate,
  268. "gate": choice_gate,
  269. "flagged": choice_gate < 0.85,
  270. },
  271. "churn_risk": {
  272. "kind": "noul",
  273. "p": noul_p,
  274. "confidence": noul_p,
  275. "answer_confidence": noul_p,
  276. "gate": noul_p,
  277. "flagged": noul_p >= 0.6,
  278. },
  279. "severity": {
  280. "kind": "score",
  281. "expected": score_expected,
  282. "level": 0,
  283. "label": "none",
  284. "confidence": 0.9,
  285. "answer_confidence": 0.9,
  286. "gate": 0.9,
  287. "flagged": score_expected >= 1.5,
  288. },
  289. },
  290. "escalated": False,
  291. "input_tokens": 0,
  292. }
  293. def test_escalation_arms_fire_independently(tmp_path):
  294. analyzer = _analyzer(tmp_path, _score_questions())
  295. assert analyzer.should_escalate(_signals(choice_gate=0.5)) is True # choice arm
  296. assert analyzer.should_escalate(_signals(noul_p=0.8)) is True # noul arm
  297. assert analyzer.should_escalate(_signals(score_expected=2.0)) is True # score arm
  298. assert analyzer.should_escalate(_signals()) is False
  299. def test_normalize_escalated_matches_should_escalate(tmp_path):
  300. analyzer = _analyzer(tmp_path, _score_questions())
  301. payload = {
  302. "answers": {
  303. "category": {
  304. "type": "choice",
  305. "choice": "sales",
  306. "confidence": 0.9,
  307. "answer_confidence": 0.9,
  308. },
  309. "churn_risk": {
  310. "type": "noul",
  311. "noul": 0.1,
  312. "confidence": 0.9,
  313. "answer_confidence": 0.9,
  314. },
  315. "severity": {
  316. "type": "score",
  317. "score": 0.1,
  318. "confidence": 0.9,
  319. "answer_confidence": 0.9,
  320. },
  321. }
  322. }
  323. result = analyzer.normalize(payload)
  324. assert result["escalated"] == analyzer.should_escalate(result) is False
  325. # --- todo 5: brief prompt / parse / gate / finalize --------------------------
  326. def test_build_brief_prompt_order_and_focus(tmp_path):
  327. analyzer = _analyzer(tmp_path, _score_questions())
  328. prompt = analyzer.build_brief_prompt(
  329. ["Alice: let's ship Friday", "Bob: agreed"], _signals(noul_p=0.8)
  330. )
  331. assert prompt.startswith("New utterances:\n- Alice: let's ship Friday\n- Bob: agreed")
  332. assert "Focus:" in prompt
  333. assert "churn_risk" in prompt # signal named in words
  334. assert prompt.index("New utterances:") < prompt.index("Focus:")
  335. assert prompt.index("Focus:") < prompt.index("Return only the updated brief")
  336. # no JSON extraction keys or raw dict shapes leak into the brief prompt
  337. for key in ("summary", "opportunities", "action_items", "risks", "doubts"):
  338. assert key not in prompt
  339. assert "{" not in prompt and "}" not in prompt
  340. def test_build_brief_prompt_no_focus_without_signals(tmp_path):
  341. analyzer = _analyzer(tmp_path, _score_questions())
  342. for signals in (None, {}, {"order": [], "items": {}}):
  343. prompt = analyzer.build_brief_prompt(["solo utterance"], signals)
  344. assert "solo utterance" in prompt
  345. assert "Focus:" not in prompt
  346. assert prompt.endswith("Return only the updated brief as plain text.")
  347. def test_build_ledger_prompt_inlines_ledger_narrative_and_deltas(tmp_path):
  348. analyzer = _analyzer(tmp_path, _score_questions())
  349. prompt = analyzer.build_ledger_prompt(
  350. "Summary: shipped\n\nOpportunities: expand",
  351. ["fact one", "fact two"],
  352. ["Alice: let's ship Friday"],
  353. _signals(noul_p=0.8),
  354. )
  355. assert "- fact one" in prompt and "- fact two" in prompt
  356. assert "CURRENT LEDGER" in prompt
  357. assert "Summary: shipped" in prompt
  358. assert "NEW UTTERANCES:\n- Alice: let's ship Friday" in prompt
  359. assert prompt.index("CURRENT LEDGER") < prompt.index("CURRENT BRIEF:")
  360. assert prompt.index("CURRENT BRIEF:") < prompt.index("NEW UTTERANCES:")
  361. assert prompt.index("NEW UTTERANCES:") < prompt.index("Focus:")
  362. assert "churn_risk" in prompt
  363. assert "NEW FACTS:" in prompt and "BRIEF:" in prompt
  364. def test_build_ledger_prompt_empty_ledger_and_narrative(tmp_path):
  365. analyzer = _analyzer(tmp_path, _score_questions())
  366. prompt = analyzer.build_ledger_prompt("", [], ["solo"], None)
  367. assert "CURRENT LEDGER" in prompt and "(none yet)" in prompt
  368. assert "CURRENT BRIEF:\n(none yet)" in prompt
  369. assert "NEW UTTERANCES:\n- solo" in prompt
  370. assert "Focus:" not in prompt
  371. def test_extract_bullets_strips_new_marker_and_normalizes(tmp_path):
  372. analyzer = _analyzer(tmp_path, _score_questions())
  373. brief = (
  374. "Summary: things\n"
  375. "- top level bullet\n"
  376. " - indented child\n"
  377. "- **New:** tagged fact\n"
  378. "not a bullet\n"
  379. "\n"
  380. )
  381. assert analyzer.extract_bullets(brief) == [
  382. "top level bullet",
  383. "indented child",
  384. "tagged fact",
  385. ]
  386. def test_restore_missing_bullets_reappends_dropped_fact(tmp_path):
  387. analyzer = _analyzer(tmp_path, _score_questions())
  388. prior = (
  389. "Summary: old\n\nPrior Details:\n"
  390. "- The budget was $305 million.\n"
  391. "- Sense could find prey.\n"
  392. )
  393. new = "Summary: newer\n\nPrior Details:\n- Sense could find prey.\n"
  394. restored = analyzer.restore_missing_bullets(new, prior)
  395. assert "- Sense could find prey." in restored
  396. assert "- The budget was $305 million." in restored
  397. assert restored.count("- Sense could find prey.") == 1
  398. def test_restore_missing_bullets_matches_reworded_bullet(tmp_path):
  399. analyzer = _analyzer(tmp_path, _score_questions())
  400. prior = "Prior Details:\n- **New:** Sense could find prey.\n"
  401. new = "Prior Details:\n- Sense could find prey.\n"
  402. restored = analyzer.restore_missing_bullets(new, prior)
  403. assert restored == new
  404. def test_restore_missing_bullets_restores_reworded_as_new_fact(tmp_path):
  405. analyzer = _analyzer(tmp_path, _score_questions())
  406. prior = "Prior Details:\n- The budget was $305 million.\n"
  407. new = "Prior Details:\n- Budget: $305 million (nearly Spider-Man 2).\n"
  408. restored = analyzer.restore_missing_bullets(new, prior)
  409. assert restored.count("$305 million") == 2
  410. assert restored.rstrip().endswith("- The budget was $305 million.")
  411. def test_restore_missing_bullets_noop_without_prior_or_new(tmp_path):
  412. analyzer = _analyzer(tmp_path, _score_questions())
  413. new = "Summary: only\nPrior Details:\n- keep me\n"
  414. assert analyzer.restore_missing_bullets(new, "") == new
  415. assert analyzer.restore_missing_bullets(new, None) == new
  416. assert analyzer.restore_missing_bullets("", new) == ""
  417. assert analyzer.restore_missing_bullets(None, new) is None
  418. def test_restore_missing_bullets_appends_section_when_absent(tmp_path):
  419. analyzer = _analyzer(tmp_path, _score_questions())
  420. prior = "- orphan fact\n"
  421. new = "Summary: no prior details header\n"
  422. restored = analyzer.restore_missing_bullets(new, prior)
  423. assert "- orphan fact" in restored
  424. assert "Prior Details:" in restored
  425. def test_parse_brief_strips_fences_and_rejects_empty(tmp_path):
  426. analyzer = _analyzer(tmp_path, _score_questions())
  427. assert analyzer.parse_brief("```\nhello brief\n```") == "hello brief"
  428. assert analyzer.parse_brief("```markdown\nhello brief\n```") == "hello brief"
  429. assert analyzer.parse_brief("plain brief") == "plain brief"
  430. assert analyzer.parse_brief(" padded ") == "padded"
  431. assert analyzer.parse_brief("") is None
  432. assert analyzer.parse_brief(" ") is None
  433. assert analyzer.parse_brief(None) is None
  434. assert analyzer.parse_brief(42) is None
  435. assert analyzer.parse_brief("```") is None
  436. def test_parse_brief_unescapes_literal_backslash_n(tmp_path):
  437. analyzer = _analyzer(tmp_path, _score_questions())
  438. assert analyzer.parse_brief("## Title\\n\\nBody line") == "## Title\n\nBody line"
  439. assert analyzer.parse_brief("a\\tb") == "a\tb"
  440. assert analyzer.parse_brief("line1\nline2\\nline3") == "line1\nline2\\nline3"
  441. def test_parse_brief_truncates_not_rejects(tmp_path):
  442. analyzer = _analyzer(tmp_path, _score_questions())
  443. parsed = analyzer.parse_brief("x" * 5000)
  444. assert parsed is not None
  445. assert parsed == "x" * 4000
  446. assert len(parsed) == 4000
  447. wrapped = "[update_brief(updated_brief='" + "x" * 5000 + "')]"
  448. assert analyzer.parse_brief(wrapped) == "x" * 4000
  449. def test_parse_brief_honors_configured_cap(tmp_path):
  450. analyzer = _analyzer(tmp_path, _score_questions(), brief_max_chars=10)
  451. assert analyzer.parse_brief("x" * 50) == "x" * 10
  452. def test_parse_brief_unwraps_single_quoted_tool_call_with_apostrophes(tmp_path):
  453. analyzer = _analyzer(tmp_path, _score_questions())
  454. observed = "<|tool_call_start|>[update_brief(updated_brief='the company's game failed')]"
  455. assert analyzer.parse_brief(observed) == "the company's game failed"
  456. def test_parse_brief_unwraps_double_quoted_tool_call(tmp_path):
  457. analyzer = _analyzer(tmp_path, _score_questions())
  458. wrapped = '[update_brief(updated_brief="the company\'s plan")]'
  459. assert analyzer.parse_brief(wrapped) == "the company's plan"
  460. def test_parse_brief_unwraps_trailing_end_marker(tmp_path):
  461. analyzer = _analyzer(tmp_path, _score_questions())
  462. wrapped = "[update_brief(updated_brief='ship friday')]<|tool_call_end|>"
  463. assert analyzer.parse_brief(wrapped) == "ship friday"
  464. def test_parse_brief_unwraps_fenced_and_wrapped(tmp_path):
  465. analyzer = _analyzer(tmp_path, _score_questions())
  466. wrapped = "```\n<|tool_call_start|>[update_brief(updated_brief='fenced payload')]\n```"
  467. assert analyzer.parse_brief(wrapped) == "fenced payload"
  468. def test_parse_brief_does_not_mangle_clean_markdown(tmp_path):
  469. analyzer = _analyzer(tmp_path, _score_questions())
  470. clean = "Here's the [brief]: it's the company's plan - don't mangle [it]."
  471. assert analyzer.parse_brief(clean) == clean
  472. prose = "We should update_brief the notes, here's [why]."
  473. assert analyzer.parse_brief(prose) == prose
  474. def test_parse_brief_empty_tool_call_payload_is_none(tmp_path):
  475. analyzer = _analyzer(tmp_path, _score_questions())
  476. assert analyzer.parse_brief("[update_brief(updated_brief='')]") is None
  477. def test_parse_brief_unwraps_multi_arg_tool_call(tmp_path):
  478. analyzer = _analyzer(tmp_path, _score_questions())
  479. wrapped = (
  480. "[update_brief(updated_brief='## Opportunities\n- ship Friday', "
  481. "previous_brief='## old\n- y', mode='read')]"
  482. )
  483. assert analyzer.parse_brief(wrapped) == "## Opportunities\n- ship Friday"
  484. def test_parse_brief_unwraps_multi_arg_with_markers(tmp_path):
  485. analyzer = _analyzer(tmp_path, _score_questions())
  486. wrapped = (
  487. "<|tool_call_start|>[update_brief(updated_brief='## Opportunities\n- ship Friday', "
  488. "previous_brief='## old\n- y', mode='read')]<|tool_call_end|>"
  489. )
  490. assert analyzer.parse_brief(wrapped) == "## Opportunities\n- ship Friday"
  491. def test_parse_brief_unwraps_multi_arg_apostrophes_preserved(tmp_path):
  492. analyzer = _analyzer(tmp_path, _score_questions())
  493. wrapped = (
  494. "[update_brief(updated_brief='the company's game failed', "
  495. "previous_brief='## old', mode='read')]"
  496. )
  497. assert analyzer.parse_brief(wrapped) == "the company's game failed"
  498. def test_parse_brief_unwraps_positional_tool_call(tmp_path):
  499. analyzer = _analyzer(tmp_path, _score_questions())
  500. assert analyzer.parse_brief("[update_brief('payload here', mode='read')]") == "payload here"
  501. def test_parse_brief_rejects_polluted_tool_call(tmp_path):
  502. analyzer = _analyzer(tmp_path, _score_questions())
  503. polluted = "[update_brief(updated_brief='oops, previous_brief=', mode='read')]"
  504. assert analyzer.parse_brief(polluted) is None
  505. no_arg = "<|tool_call_start|>[update_brief(previous_brief=old, mode=read)]"
  506. assert analyzer.parse_brief(no_arg) is None
  507. def test_parse_brief_clean_mode_text_not_mangled(tmp_path):
  508. analyzer = _analyzer(tmp_path, _score_questions())
  509. clean = "Set mode=read, then read [the brief] - it's fine (really)."
  510. assert analyzer.parse_brief(clean) == clean
  511. def test_parse_brief_rejects_marker_with_artifacts_but_no_call(tmp_path):
  512. analyzer = _analyzer(tmp_path, _score_questions())
  513. assert analyzer.parse_brief("<|tool_call_start|>previous_brief='x', mode='read'") is None
  514. assert analyzer.parse_brief("<|tool_call_start|>mode='read'") is None
  515. def _brief_signals(p=None):
  516. item = {"kind": "noul"}
  517. if p is not None:
  518. item["p"] = p
  519. return {"order": ["substantive_update"], "items": {"substantive_update": item}}
  520. def test_should_update_brief_gate(tmp_path):
  521. analyzer = _analyzer(tmp_path, _score_questions())
  522. assert analyzer.should_update_brief(_brief_signals(0.9)) is True
  523. assert analyzer.should_update_brief(_brief_signals(0.5)) is True # boundary
  524. assert analyzer.should_update_brief(_brief_signals(0.2)) is False
  525. # absent update / no numeric p / not a dict -> fail open
  526. assert analyzer.should_update_brief({"order": [], "items": {}}) is True
  527. assert analyzer.should_update_brief(_brief_signals(None)) is True
  528. assert analyzer.should_update_brief(None) is True
  529. assert analyzer.should_update_brief({"items": {"substantive_update": "nope"}}) is True
  530. def test_should_update_brief_threshold_configured(tmp_path):
  531. analyzer = _analyzer(tmp_path, _score_questions(), brief_gate_threshold=0.8)
  532. assert analyzer.should_update_brief(_brief_signals(0.6)) is False
  533. assert analyzer.should_update_brief(_brief_signals(0.8)) is True
  534. def test_finalize_brief_length_truncates_not_rejects(tmp_path, caplog):
  535. analyzer = _analyzer(tmp_path, _score_questions())
  536. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  537. result = analyzer.finalize_brief("y" * 5000, "length")
  538. assert result is not None
  539. assert result == "y" * 4000
  540. assert caplog.records # warned about the length cutoff but still accepted
  541. def test_finalize_brief_stop_and_empty(tmp_path):
  542. analyzer = _analyzer(tmp_path, _score_questions())
  543. assert analyzer.finalize_brief("a brief", "stop") == "a brief"
  544. assert analyzer.finalize_brief("", "stop") is None
  545. assert analyzer.finalize_brief("```\nfenced\n```", "stop") == "fenced"
  546. assert analyzer.finalize_brief(None, "length") is None
  547. # --- todo 11: cached state() ------------------------------------------------
  548. def test_state_initial_loading_with_good_questions(tmp_path):
  549. analyzer = _analyzer(tmp_path, _score_questions())
  550. assert analyzer.state() == ("loading", "")
  551. def test_state_initial_no_questions_with_bad_path(tmp_path):
  552. missing = str(tmp_path / "missing.json")
  553. analyzer = TriageAnalyzer(_cfg(missing))
  554. state, reason = analyzer.state()
  555. assert state == "no_questions"
  556. assert missing in reason
  557. def test_state_vocabulary_has_no_extra_member():
  558. assert set(triage.TRIAGE_REASONS) == {
  559. "ok",
  560. "no_questions",
  561. "loading",
  562. "laya_missing",
  563. "disabled",
  564. "error",
  565. }
  566. assert "service" + "_down" not in triage.TRIAGE_REASONS
  567. def test_refresh_transitions(tmp_path):
  568. analyzer = _analyzer(tmp_path, _score_questions())
  569. analyzer.refresh("ok")
  570. assert analyzer.state() == ("ok", "")
  571. analyzer.refresh("laya_missing", "run: uv sync --extra triage")
  572. assert analyzer.state() == ("laya_missing", "run: uv sync --extra triage")
  573. analyzer.refresh("error", "boom")
  574. assert analyzer.state() == ("error", "boom")
  575. def test_refresh_unknown_state_ignored(tmp_path, caplog):
  576. analyzer = _analyzer(tmp_path, _score_questions())
  577. analyzer.refresh("ok")
  578. with caplog.at_level(logging.WARNING, logger="stt_daemon.assistant.triage"):
  579. analyzer.refresh("bogus_state")
  580. assert analyzer.state() == ("ok", "")
  581. assert caplog.records
  582. def test_no_questions_state_cannot_be_overridden(tmp_path):
  583. analyzer = TriageAnalyzer(_cfg(str(tmp_path / "missing.json")))
  584. assert analyzer.state()[0] == "no_questions"
  585. analyzer.refresh("ok")
  586. analyzer.refresh("error", "boom")
  587. assert analyzer.state()[0] == "no_questions"
  588. def test_state_does_not_touch_lane(tmp_path):
  589. analyzer = _analyzer(tmp_path, _score_questions())
  590. class StrictLane:
  591. def __init__(self):
  592. self.calls = []
  593. def __getattr__(self, name):
  594. def record(*args, **kwargs):
  595. self.calls.append(name)
  596. return record
  597. lane = StrictLane()
  598. for _ in range(3):
  599. analyzer.state()
  600. analyzer.refresh("ok")
  601. analyzer.state()
  602. assert lane.calls == []
  603. # --- F3: end-to-end triage flow on fakes ------------------------------------
  604. EXTRACT_JSON = (
  605. '{"summary":"s","opportunities":[],"doubts":[],"action_items":[],"risks":[]}'
  606. )
  607. class _Clock:
  608. """Injected clock: no sleeps, fully deterministic."""
  609. def __init__(self, start=1000.0):
  610. self.t = float(start)
  611. def __call__(self):
  612. return self.t
  613. def advance(self, dt):
  614. self.t += float(dt)
  615. class _FakeSubscriber:
  616. def events(self):
  617. return iter(())
  618. def close(self):
  619. pass
  620. class _FakeLane:
  621. """Duck-typed LayaLane: canned-ready, records submits, counts drops."""
  622. def __init__(self):
  623. self.submits: list[tuple] = []
  624. self.drops = 0
  625. def ready(self) -> bool:
  626. return True
  627. def state(self):
  628. return ("ok", "")
  629. def submit(self, state, questions, lang, generation):
  630. self.submits.append((state, questions, lang, generation))
  631. return True
  632. def drop_pending(self):
  633. self.drops += 1
  634. return 1
  635. def _answers(noul_p=0.1):
  636. """A full laya-shaped answers payload for the example questions.
  637. `noul_p` drives every noul arm, including the `substantive_update` gate:
  638. below `brief_gate_threshold` (0.5) the turn is gated OUT (no brief job),
  639. at or above it the turn gates IN.
  640. """
  641. answers = {
  642. "decision_status": {
  643. "type": "choice",
  644. "choice": "made",
  645. "confidence": 0.9,
  646. "answer_confidence": 0.9,
  647. },
  648. "responsibility_clarity": {
  649. "type": "choice",
  650. "choice": "explicit",
  651. "confidence": 0.9,
  652. "answer_confidence": 0.9,
  653. },
  654. }
  655. for qid in (
  656. "substantive_update",
  657. "opportunity",
  658. "blocker",
  659. "action_item",
  660. "deadline",
  661. "open_question",
  662. ):
  663. answers[qid] = {
  664. "type": "noul",
  665. "noul": noul_p,
  666. "confidence": 0.9,
  667. "answer_confidence": 0.9,
  668. }
  669. return {"model": "multilingual", "answers": answers, "usage": {"input_tokens": 42}}
  670. def test_end_to_end_triage_flow():
  671. """signals -> content -> cleared across service, analyzer, lane, and ViewState.
  672. The lane result is wired by calling `service._on_triage_result(gen, payload)`
  673. directly (the runner does exactly this in production); the brief job is
  674. drained with `job.run()` so no worker thread is started. The
  675. single-outstanding guard plus the shared `_pending_brief` collapse settled
  676. turns into ONE job consuming every buffered delta, and the
  677. `substantive_update` gate can reduce that to ZERO jobs.
  678. """
  679. cfg = Config()
  680. cfg.assistant.turn_gap_s = 0.5
  681. cfg.triage.enabled = True
  682. cfg.triage.questions_file = EXAMPLE_PATH
  683. clock = _Clock(1000.0)
  684. lane = _FakeLane()
  685. emitted: list[dict] = []
  686. prompts: list[str] = []
  687. def emit(type_, **fields):
  688. emitted.append({"type": type_, **fields})
  689. analyzer = TriageAnalyzer(cfg.triage)
  690. def brief_fn(prompt, on_io=None, finalize=None):
  691. prompts.append(prompt)
  692. return "NEW FACTS:\nnone\n\nBRIEF:\nSummary: brief\n"
  693. service = AssistantService(
  694. cfg,
  695. _FakeSubscriber(),
  696. emit=emit,
  697. time_fn=clock,
  698. chat_fn=lambda text: "reply",
  699. triage=analyzer,
  700. laya_lane=lane,
  701. brief_fn=brief_fn,
  702. )
  703. def triage_events():
  704. return [e for e in emitted if e["type"] == "triage"]
  705. def brief_jobs():
  706. return [j for j in service._inference._queue if j.name == "brief-update"]
  707. # 1. settled turn -> exactly one lane submit, lang + generation recorded
  708. assert service.toggle_chat() is True
  709. service.handle_event(
  710. {"type": events.TRANSCRIPT, "text": "hola, necesito ayuda", "lang": "es"}
  711. )
  712. clock.advance(1.0)
  713. service.tick()
  714. assert len(lane.submits) == 1
  715. state_text, questions, lang, gen1 = lane.submits[0]
  716. assert "hola, necesito ayuda" in state_text
  717. assert questions is analyzer.questions
  718. assert lang == "es"
  719. assert gen1 == 0
  720. # 2. low-p turn -> signals only: the gate (p=0.1 < 0.5) dispatches ZERO jobs
  721. service._on_triage_result(gen1, _answers(noul_p=0.1))
  722. assert [e["stage"] for e in triage_events()] == ["signals"]
  723. assert triage_events()[0]["triage"]["escalated"] is False
  724. assert service.last_triage is not None
  725. assert service.last_triage["escalated"] is False
  726. assert brief_jobs() == []
  727. assert prompts == []
  728. # 3. high-p turn -> second submit, then ONE brief job (the only one outstanding)
  729. service.handle_event(
  730. {"type": events.TRANSCRIPT, "text": "quiero cancelar mi suscripcion", "lang": "es"}
  731. )
  732. clock.advance(1.0)
  733. service.tick()
  734. assert len(lane.submits) == 2
  735. gen2 = lane.submits[1][3]
  736. service._on_triage_result(gen2, _answers(noul_p=0.9))
  737. assert [e["stage"] for e in triage_events()] == ["signals", "signals"]
  738. assert triage_events()[1]["triage"]["escalated"] is True
  739. jobs = brief_jobs()
  740. assert len(jobs) == 1
  741. # 4. run the brief job directly (deterministic, no worker thread): it consumes
  742. # both buffered deltas and emits ONE content with the brief merged over signals
  743. jobs[0].run()
  744. assert len(prompts) == 1
  745. assert "hola, necesito ayuda" in prompts[0]
  746. assert "quiero cancelar mi suscripcion" in prompts[0]
  747. content_events = [e for e in triage_events() if e["stage"] == "content"]
  748. assert len(content_events) == 1
  749. merged = content_events[0]["triage"]
  750. assert merged["brief"] == "Summary: brief"
  751. assert merged["escalated"] is True # signals preserved under the brief
  752. assert merged["order"] == triage_events()[1]["triage"]["order"]
  753. # 5. drive the emitted stream through a fresh ViewState
  754. view = ViewState()
  755. for event in emitted:
  756. view.ingest(event)
  757. analyzer.refresh("ok") # the lane callback does this in production
  758. view.ingest({"type": "status", **service.status()})
  759. assert view.triage is not None
  760. assert view.triage["brief"] == "Summary: brief"
  761. lines = view.triage_lines()
  762. assert lines
  763. # 6. clear -> cleared event empties the panel and bumps the epoch
  764. baseline_epoch = view.triage_epoch
  765. already = len(emitted)
  766. service.clear()
  767. for event in emitted[already:]:
  768. view.ingest(event)
  769. assert view.triage is None
  770. assert view.triage_epoch > baseline_epoch
  771. # a stale result after clear must not re-populate the panel
  772. service._on_triage_result(gen2, _answers(noul_p=0.9))
  773. assert [e["stage"] for e in triage_events()] == [
  774. "signals",
  775. "signals",
  776. "content",
  777. "cleared",
  778. ]
  779. assert view.triage is None
  780. assert lane.drops == 1
  781. # 7. disabled control: no triage/lane -> status disabled, clear emits nothing
  782. cfg2 = Config()
  783. clock2 = _Clock(2000.0)
  784. emitted2: list[dict] = []
  785. def emit2(type_, **fields):
  786. emitted2.append({"type": type_, **fields})
  787. plain = AssistantService(cfg2, _FakeSubscriber(), emit=emit2, time_fn=clock2)
  788. assert plain.status()["triage_state"] == "disabled"
  789. assert plain.clear() is True
  790. assert [e for e in emitted2 if e["type"] == "triage"] == []
  791. def test_ledger_merge_dedupes_exact_and_punctuation_variants():
  792. ledger = FactLedger()
  793. assert ledger.merge(["The budget was $305 million.", "Sense could find prey."]) == 2
  794. assert ledger.merge(["sense could find prey", "The budget was $305 million"]) == 0
  795. assert ledger.facts() == [
  796. "The budget was $305 million.",
  797. "Sense could find prey.",
  798. ]
  799. def test_ledger_merge_keeps_near_match_with_different_number():
  800. ledger = FactLedger()
  801. ledger.merge(["Sold 1.9 million units."])
  802. assert ledger.merge(["Sold 10 million units."]) == 1
  803. assert len(ledger) == 2
  804. def test_ledger_merge_keeps_near_match_with_different_entity():
  805. ledger = FactLedger()
  806. ledger.merge(["Marcus Smith directed the game."])
  807. assert ledger.merge(["Mike Daly directed the game."]) == 1
  808. assert len(ledger) == 2
  809. def test_ledger_merge_ignores_empty_and_non_string():
  810. ledger = FactLedger()
  811. assert ledger.merge(["", " ", None, 123]) == 0
  812. assert ledger.render() == ""
  813. def test_ledger_render_has_prior_details_section():
  814. ledger = FactLedger()
  815. ledger.merge(["fact one", "fact two"])
  816. assert ledger.render() == "Prior Details:\n- fact one\n- fact two"
  817. def test_ledger_evicts_oldest_over_cap_and_never_new():
  818. ledger = FactLedger(max_facts=2)
  819. ledger.merge(["alpha", "beta"])
  820. ledger.merge(["gamma"])
  821. assert ledger.facts() == ["beta", "gamma"]
  822. def test_ledger_truncates_overlong_fact():
  823. ledger = FactLedger(fact_max_chars=10)
  824. ledger.merge(["x" * 50])
  825. assert ledger.facts() == ["x" * 10]
  826. def test_ledger_clear_empties():
  827. ledger = FactLedger()
  828. ledger.merge(["fact"])
  829. ledger.clear()
  830. assert ledger.facts() == []
  831. assert ledger.render() == ""
  832. def test_ledger_from_brief_harvests_bullets():
  833. ledger = FactLedger.from_brief("Summary: s\n\nPrior Details:\n- one\n- two\n")
  834. assert ledger.facts() == ["one", "two"]
  835. def test_parse_ledger_reply_splits_narrative_and_facts(tmp_path):
  836. analyzer = _analyzer(tmp_path, _score_questions())
  837. narrative, facts = analyzer.parse_ledger_reply(
  838. "NEW FACTS:\n- budget is $305m\n- sense finds prey\n\nBRIEF:\nSummary: ok"
  839. )
  840. assert facts == ["budget is $305m", "sense finds prey"]
  841. assert narrative == "Summary: ok"
  842. def test_parse_ledger_reply_drops_trailing_fact_when_truncated(tmp_path):
  843. analyzer = _analyzer(tmp_path, _score_questions())
  844. _, facts = analyzer.parse_ledger_reply(
  845. "NEW FACTS:\n- complete fact\n- half a fac", truncated=True
  846. )
  847. assert facts == ["complete fact"]
  848. def test_parse_ledger_reply_missing_facts_block(tmp_path):
  849. analyzer = _analyzer(tmp_path, _score_questions())
  850. narrative, facts = analyzer.parse_ledger_reply("BRIEF:\nSummary: only narrative")
  851. assert facts == []
  852. assert narrative == "Summary: only narrative"
  853. def test_parse_ledger_reply_strips_model_prior_details(tmp_path):
  854. analyzer = _analyzer(tmp_path, _score_questions())
  855. narrative, _ = analyzer.parse_ledger_reply(
  856. "NEW FACTS:\nnone\n\nBRIEF:\nSummary: s\n\nPrior Details:\n- model echo\n"
  857. )
  858. assert "model echo" not in narrative
  859. assert "Summary: s" in narrative
  860. def test_parse_ledger_reply_none_on_unusable(tmp_path):
  861. analyzer = _analyzer(tmp_path, _score_questions())
  862. assert analyzer.parse_ledger_reply("") is None
  863. assert analyzer.parse_ledger_reply("just some prose with no sections") is None
  864. def test_parse_facts_ignores_prose_and_handles_markers(tmp_path):
  865. analyzer = _analyzer(tmp_path, _score_questions())
  866. block = "- bullet fact\n* star fact\n• dot fact\n1. numbered fact\nplain prose\nnone"
  867. assert analyzer.parse_facts(block) == [
  868. "bullet fact",
  869. "star fact",
  870. "dot fact",
  871. "numbered fact",
  872. ]
  873. def _rich_questions():
  874. return {
  875. "substantive_update": {
  876. "type": "noul",
  877. "instructions": "This recent conversation segment adds something a running brief "
  878. "should record.",
  879. },
  880. "blocker": {
  881. "type": "noul",
  882. "instructions": "An obstacle, dependency, objection, or risk that could block "
  883. "or delay the work was raised.",
  884. },
  885. "churn_risk": {"type": "noul", "instructions": "User may leave."},
  886. "category": {
  887. "type": "choice",
  888. "instructions": "What is this about?",
  889. "criteria": {"support": "help needed", "sales": "buying"},
  890. },
  891. "severity": {
  892. "type": "score",
  893. "instructions": "How severe is the issue?",
  894. "criteria": ["none", "low", "high", "critical"],
  895. },
  896. }
  897. def _rich_signals(**overrides):
  898. items = {
  899. "blocker": {
  900. "kind": "noul",
  901. "p": 0.91,
  902. "confidence": 0.9,
  903. "answer_confidence": 0.9,
  904. "gate": 0.9,
  905. "flagged": True,
  906. },
  907. "churn_risk": {
  908. "kind": "noul",
  909. "p": 0.10,
  910. "confidence": 0.9,
  911. "answer_confidence": 0.9,
  912. "gate": 0.9,
  913. "flagged": False,
  914. },
  915. "substantive_update": {
  916. "kind": "noul",
  917. "p": 0.10,
  918. "confidence": 0.9,
  919. "answer_confidence": 0.9,
  920. "gate": 0.9,
  921. "flagged": False,
  922. },
  923. "category": {
  924. "kind": "choice",
  925. "choice": "support",
  926. "confidence": 0.4,
  927. "answer_confidence": 0.4,
  928. "gate": 0.4,
  929. "flagged": True,
  930. },
  931. "severity": {
  932. "kind": "score",
  933. "expected": 2.6,
  934. "level": 3,
  935. "label": "critical",
  936. "confidence": 0.9,
  937. "answer_confidence": 0.9,
  938. "gate": 0.9,
  939. "flagged": True,
  940. },
  941. }
  942. items.update(overrides.get("items", {}))
  943. order = overrides.get(
  944. "order", ["blocker", "churn_risk", "substantive_update", "category", "severity"])
  945. return {"order": order, "items": items, "escalated": overrides.get("escalated", False),
  946. "input_tokens": 0}
  947. def test_signal_lines_filters_low_noul_but_keeps_gate_qid(tmp_path):
  948. analyzer = _analyzer(tmp_path, _rich_questions())
  949. lines = analyzer._signal_lines(_rich_signals())
  950. text = "\n".join(lines)
  951. assert not any("churn_risk" in line for line in lines) # p=0.10 filtered
  952. assert any("substantive_update" in line for line in lines) # gate qid kept
  953. assert any("blocker" in line for line in lines) # high-signal kept
  954. assert "p=0.91" in text and "flagged" in text
  955. assert "could block or delay" in text # instructions carried
  956. assert all(line.startswith("- ") for line in lines)
  957. # original order preserved among kept lines
  958. kept = [line for line in lines]
  959. assert [i for i, line in enumerate(kept) if "blocker" in line][0] < [
  960. i for i, line in enumerate(kept) if "category" in line][0]
  961. def test_signal_lines_choice_carries_instructions_and_flag(tmp_path):
  962. analyzer = _analyzer(tmp_path, _rich_questions())
  963. lines = analyzer._signal_lines(_rich_signals(order=["category"], escalated=False))
  964. assert len(lines) == 1
  965. assert "category (choice): selected support (conf 0.40, flagged as uncertain)" in lines[0]
  966. assert "What is this about?" in lines[0]
  967. assert "help needed" in lines[0] # criteria[selected] definition
  968. def test_signal_lines_escalated_marker_only_on_flagged(tmp_path):
  969. analyzer = _analyzer(tmp_path, _rich_questions())
  970. lines = analyzer._signal_lines(_rich_signals(
  971. order=["blocker", "substantive_update"], escalated=True))
  972. by_qid = {line.split(" ")[1]: line for line in lines}
  973. assert by_qid["blocker"].endswith(" [escalated]")
  974. assert not by_qid["substantive_update"].endswith(" [escalated]")
  975. plain = analyzer._signal_lines(_rich_signals(
  976. order=["blocker", "substantive_update"], escalated=False))
  977. assert not any("[escalated]" in line for line in plain)
  978. def test_signal_lines_score_format_and_instruction_cap(tmp_path):
  979. questions = _rich_questions()
  980. questions["severity"]["instructions"] = "x " * 200 # force long instructions
  981. analyzer = _analyzer(tmp_path, questions)
  982. lines = analyzer._signal_lines(_rich_signals(order=["severity"]))
  983. assert len(lines) == 1
  984. assert "severity (score): expected 2.60, level 3 (critical), flagged" in lines[0]
  985. assert len(lines[0]) <= len("- severity (score): expected 2.60, level 3 "
  986. "(critical), flagged — ") + 160 + len(" [escalated]")
  987. assert lines[0].rstrip().endswith("…")
  988. def test_signal_lines_never_raises_on_malformed(tmp_path):
  989. analyzer = _analyzer(tmp_path, _rich_questions())
  990. assert analyzer._signal_lines(None) == [] # type: ignore[arg-type]
  991. assert analyzer._signal_lines({}) == [] # type: ignore[dict-item]
  992. assert analyzer._signal_lines({"order": "nope", "items": "nope"}) == [] # type: ignore[dict-item]
  993. assert analyzer._signal_lines({"order": ["ghost"], "items": {}}) == []