File size: 25,998 Bytes
a6f4696
9e87f14
a6f4696
 
9e87f14
 
 
 
 
 
a6f4696
9e87f14
 
a6f4696
9e87f14
a6f4696
 
 
 
 
 
 
 
9e87f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a009989
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e87f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a009989
 
 
 
 
 
9e87f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d5e588
 
 
 
 
 
 
 
9e87f14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6f4696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d5e588
 
 
a6f4696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
"""Tests for agents/eligibility.py.

Wave 3: _evaluate_deterministic, _resolve_patient_value, _compute_overall (pure).
Wave 4: _parse_criteria, _assess_llm, run_eligibility_check, bulk_parse_and_strip (LLM-mocked).
"""
from __future__ import annotations

import pytest

from agents.eligibility import (
    _assess_llm,
    _compute_overall,
    _evaluate_deterministic,
    _parse_criteria,
    _resolve_patient_value,
    bulk_parse_and_strip,
    run_eligibility_check,
)
from tests.conftest import (
    FakeStream,
    make_message,
    make_text_block,
    make_tool_use_block,
)
from models import (
    CriterionAssessment,
    CriterionVerdict,
    EligibilityCriterion,
    ParsedConstraint,
    PatientProfile,
)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def make_criterion(
    key: str = "age_years",
    operator: str = ">=",
    value=18,
    unit: str | None = None,
    ctype: str = "inclusion",
    description: str = "Test criterion",
    raw_criteria: str = "Raw criterion text",
) -> EligibilityCriterion:
    return EligibilityCriterion(
        key=key,
        type=ctype,
        description=description,
        raw_criteria=raw_criteria,
        constraint=ParsedConstraint(key=key, operator=operator, value=value, unit=unit),
    )


def make_assessment(verdict: CriterionVerdict) -> CriterionAssessment:
    c = make_criterion()
    return CriterionAssessment(
        criterion=c,
        verdict=verdict,
        reason="test",
        patient_value="42",
        confidence="high",
    )


# ---------------------------------------------------------------------------
# _evaluate_deterministic β€” every operator Γ— pass/fail
# ---------------------------------------------------------------------------

class TestEvaluateDeterministic:
    # --- >= ---
    def test_gte_passes_when_equal(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 18)
        assert a.verdict == CriterionVerdict.PASS

    def test_gte_passes_when_above(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 52)
        assert a.verdict == CriterionVerdict.PASS

    def test_gte_fails_when_below(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 16)
        assert a.verdict == CriterionVerdict.FAIL

    # --- <= ---
    def test_lte_passes_when_equal(self):
        a = _evaluate_deterministic(make_criterion(operator="<=", value=75), 75)
        assert a.verdict == CriterionVerdict.PASS

    def test_lte_passes_when_below(self):
        a = _evaluate_deterministic(make_criterion(operator="<=", value=75), 52)
        assert a.verdict == CriterionVerdict.PASS

    def test_lte_fails_when_above(self):
        a = _evaluate_deterministic(make_criterion(operator="<=", value=75), 80)
        assert a.verdict == CriterionVerdict.FAIL

    # --- == ---
    def test_eq_passes(self):
        a = _evaluate_deterministic(make_criterion(operator="==", value=0), 0)
        assert a.verdict == CriterionVerdict.PASS

    def test_eq_fails(self):
        a = _evaluate_deterministic(make_criterion(operator="==", value=0), 1)
        assert a.verdict == CriterionVerdict.FAIL

    # --- != ---
    def test_ne_passes(self):
        a = _evaluate_deterministic(make_criterion(operator="!=", value=0), 1)
        assert a.verdict == CriterionVerdict.PASS

    def test_ne_fails(self):
        a = _evaluate_deterministic(make_criterion(operator="!=", value=0), 0)
        assert a.verdict == CriterionVerdict.FAIL

    # --- in ---
    def test_in_passes(self):
        a = _evaluate_deterministic(make_criterion(operator="in", value=[0, 1]), 1)
        assert a.verdict == CriterionVerdict.PASS

    def test_in_fails(self):
        a = _evaluate_deterministic(make_criterion(operator="in", value=[0, 1]), 2)
        assert a.verdict == CriterionVerdict.FAIL

    # --- not_in ---
    def test_not_in_passes(self):
        a = _evaluate_deterministic(make_criterion(operator="not_in", value=[2, 3]), 1)
        assert a.verdict == CriterionVerdict.PASS

    def test_not_in_fails(self):
        a = _evaluate_deterministic(make_criterion(operator="not_in", value=[2, 3]), 2)
        assert a.verdict == CriterionVerdict.FAIL

    # --- between ---
    def test_between_passes_at_lower_bound(self):
        a = _evaluate_deterministic(make_criterion(operator="between", value=[18, 75]), 18)
        assert a.verdict == CriterionVerdict.PASS

    def test_between_passes_at_upper_bound(self):
        a = _evaluate_deterministic(make_criterion(operator="between", value=[18, 75]), 75)
        assert a.verdict == CriterionVerdict.PASS

    def test_between_passes_mid(self):
        a = _evaluate_deterministic(make_criterion(operator="between", value=[18, 75]), 52)
        assert a.verdict == CriterionVerdict.PASS

    def test_between_fails_below(self):
        a = _evaluate_deterministic(make_criterion(operator="between", value=[18, 75]), 17)
        assert a.verdict == CriterionVerdict.FAIL

    def test_between_fails_above(self):
        a = _evaluate_deterministic(make_criterion(operator="between", value=[18, 75]), 76)
        assert a.verdict == CriterionVerdict.FAIL

    # --- output shape ---
    def test_confidence_is_high(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 52)
        assert a.confidence == "high"

    def test_patient_value_stringified(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 52)
        assert a.patient_value == "52"

    def test_reason_contains_operator_and_value(self):
        a = _evaluate_deterministic(make_criterion(operator=">=", value=18), 52)
        assert ">=" in a.reason
        assert "18" in a.reason

    def test_reason_includes_unit_when_present(self):
        c = make_criterion(operator=">=", value=60, unit="mL/min")
        a = _evaluate_deterministic(c, 65)
        assert "mL/min" in a.reason

    def test_type_error_in_comparison_yields_fail(self):
        # Comparing int to a list value that can't be compared numerically
        c = make_criterion(operator=">=", value="not-a-number")
        a = _evaluate_deterministic(c, 52)
        assert a.verdict == CriterionVerdict.FAIL

    # --- unit normalization: years β†’ months ---

    def test_onset_years_converted_to_months_fails_correctly(self):
        # Trial says "onset >= 18 years"; patient has 20 months β€” should FAIL (20 < 216)
        c = make_criterion(key="symptom_onset_months", operator=">=", value=18, unit="years")
        a = _evaluate_deterministic(c, 20)
        assert a.verdict == CriterionVerdict.FAIL
        assert "216" in a.reason
        assert "months" in a.reason

    def test_onset_months_unit_unchanged(self):
        # Trial says "onset >= 18 months"; patient has 20 months β€” should PASS, value stays 18
        c = make_criterion(key="symptom_onset_months", operator=">=", value=18, unit="months")
        a = _evaluate_deterministic(c, 20)
        assert a.verdict == CriterionVerdict.PASS
        assert "18 months" in a.reason

    def test_diagnosis_years_converted_to_months(self):
        # Trial says "diagnosis >= 2 years"; patient has 18 months β€” should FAIL (18 < 24)
        c = make_criterion(key="diagnosis_months", operator=">=", value=2, unit="years")
        a = _evaluate_deterministic(c, 18)
        assert a.verdict == CriterionVerdict.FAIL
        assert "24" in a.reason

    def test_between_years_normalized_to_months(self):
        # Trial says "onset between 1 and 2 years" β†’ [12, 24] months; patient 20 months β†’ PASS
        c = make_criterion(key="symptom_onset_months", operator="between", value=[1, 2], unit="years")
        a = _evaluate_deterministic(c, 20)
        assert a.verdict == CriterionVerdict.PASS
        assert "12" in a.reason and "24" in a.reason


# ---------------------------------------------------------------------------
# _resolve_patient_value
# ---------------------------------------------------------------------------

class TestResolvePatientValue:
    def test_patient_age_resolves(self, als_patient):
        val, found = _resolve_patient_value("age_years", als_patient, None)
        assert found is True
        assert val == 52

    def test_patient_onset_months_resolves(self, als_patient):
        val, found = _resolve_patient_value("symptom_onset_months", als_patient, None)
        assert found is True
        assert val == 18

    def test_non_canonical_onset_key_not_found(self, als_patient):
        # "weakness_onset_months" is not in _KEY_MAP β€” confirms the parser must use
        # the canonical "symptom_onset_months" key for deterministic evaluation to work
        _, found = _resolve_patient_value("weakness_onset_months", als_patient, None)
        assert found is False

    def test_patient_diagnosis_months_resolves(self, als_patient):
        val, found = _resolve_patient_value("diagnosis_months", als_patient, None)
        assert found is True
        assert val == 12

    def test_unknown_key_returns_not_found(self, als_patient):
        val, found = _resolve_patient_value("nonexistent_key_xyz", als_patient, None)
        assert found is False
        assert val is None

    def test_platform_key_returns_not_found_without_data(self, als_patient):
        val, found = _resolve_patient_value("ecog_status", als_patient, None)
        assert found is False

    def test_platform_key_resolves_with_data(self, als_patient):
        platform = {"ecog_status": 1}
        val, found = _resolve_patient_value("ecog_status", als_patient, platform)
        assert found is True
        assert val == 1

    def test_platform_key_missing_from_dict_returns_not_found(self, als_patient):
        platform = {"other_field": 99}
        val, found = _resolve_patient_value("ecog_status", als_patient, platform)
        assert found is False

    def test_sex_key_not_found_because_patient_profile_has_no_sex_field(self, als_patient):
        # criterion_keys.json maps "sex" β†’ "patient.sex" but PatientProfile has no
        # sex attribute. This documents the current behavior so a future schema
        # addition is caught immediately.
        val, found = _resolve_patient_value("sex", als_patient, None)
        assert found is False
        assert val is None


# ---------------------------------------------------------------------------
# _compute_overall
# ---------------------------------------------------------------------------

class TestComputeOverall:
    def test_all_pass_returns_pass(self):
        assessments = [make_assessment(CriterionVerdict.PASS)] * 3
        assert _compute_overall(assessments) == CriterionVerdict.PASS

    def test_any_fail_returns_fail(self):
        assessments = [
            make_assessment(CriterionVerdict.PASS),
            make_assessment(CriterionVerdict.FAIL),
            make_assessment(CriterionVerdict.UNKNOWN),
        ]
        assert _compute_overall(assessments) == CriterionVerdict.FAIL

    def test_fail_takes_precedence_over_unknown(self):
        assessments = [
            make_assessment(CriterionVerdict.UNKNOWN),
            make_assessment(CriterionVerdict.FAIL),
        ]
        assert _compute_overall(assessments) == CriterionVerdict.FAIL

    def test_unknown_without_fail_returns_unknown(self):
        assessments = [
            make_assessment(CriterionVerdict.PASS),
            make_assessment(CriterionVerdict.UNKNOWN),
        ]
        assert _compute_overall(assessments) == CriterionVerdict.UNKNOWN

    def test_empty_list_returns_pass(self):
        # No criteria β†’ no objections β†’ eligible
        assert _compute_overall([]) == CriterionVerdict.PASS

    def test_single_fail_returns_fail(self):
        assert _compute_overall([make_assessment(CriterionVerdict.FAIL)]) == CriterionVerdict.FAIL

    def test_single_unknown_returns_unknown(self):
        assert _compute_overall([make_assessment(CriterionVerdict.UNKNOWN)]) == CriterionVerdict.UNKNOWN


# ---------------------------------------------------------------------------
# _parse_criteria β€” LLM tool-forced call
# ---------------------------------------------------------------------------

def _parse_tool_response(criteria: list[dict]):
    """Build a mock response as if parse_criteria tool was called."""
    return make_message(
        content=[make_tool_use_block("parse_criteria", {"criteria": criteria})],
        stop_reason="tool_use",
    )


class TestParseCriteria:
    def test_empty_text_returns_empty(self, mock_client):
        result = _parse_criteria(mock_client, "   ")
        assert result == []
        mock_client.messages.create.assert_not_called()

    def test_single_criterion_parsed(self, mock_client):
        raw = [{
            "key": "age_years",
            "type": "inclusion",
            "description": "Age 18-75",
            "raw_criteria": "Age between 18 and 75 years",
            "constraint": {"key": "age_years", "operator": "between", "value": [18, 75], "unit": None},
        }]
        mock_client.messages.create.return_value = _parse_tool_response(raw)
        result = _parse_criteria(mock_client, "Age between 18 and 75 years")
        assert len(result) == 1
        assert result[0].key == "age_years"
        assert result[0].constraint.operator == "between"
        assert result[0].constraint.value == [18, 75]

    def test_criterion_without_constraint_has_none(self, mock_client):
        raw = [{
            "key": "adequate_hepatic_function",
            "type": "inclusion",
            "description": "Adequate hepatic function",
            "raw_criteria": "Adequate hepatic function per investigator",
            "constraint": None,
        }]
        mock_client.messages.create.return_value = _parse_tool_response(raw)
        result = _parse_criteria(mock_client, "Adequate hepatic function per investigator")
        assert result[0].constraint is None

    def test_missing_tool_call_returns_empty(self, mock_client):
        mock_client.messages.create.return_value = make_message(
            content=[make_text_block("No tool called")],
            stop_reason="end_turn",
        )
        result = _parse_criteria(mock_client, "some eligibility text")
        assert result == []

    def test_exactly_one_api_call(self, mock_client):
        mock_client.messages.create.return_value = _parse_tool_response([])
        _parse_criteria(mock_client, "some text")
        assert mock_client.messages.create.call_count == 1


# ---------------------------------------------------------------------------
# _assess_llm β€” LLM tool-forced call
# ---------------------------------------------------------------------------

def _criterion(key: str = "ecog_status") -> "EligibilityCriterion":
    from models import EligibilityCriterion
    return EligibilityCriterion(
        key=key, type="inclusion",
        description="ECOG 0 or 1",
        raw_criteria="ECOG performance status 0 or 1",
        constraint=None,
    )


def _assess_tool_response(assessments: list[dict]):
    return make_message(
        content=[make_tool_use_block("assess_eligibility", {"assessments": assessments})],
        stop_reason="tool_use",
    )


class TestAssessLlm:
    def test_empty_criteria_returns_empty(self, mock_client, als_patient):
        result = _assess_llm(mock_client, [], als_patient, None)
        assert result == []
        mock_client.messages.create.assert_not_called()

    def test_pass_verdict_mapped(self, mock_client, als_patient):
        criteria = [_criterion("ecog_status")]
        raw = [{"criterion_key": "ecog_status", "verdict": "pass", "reason": "ECOG is 0", "patient_value": "0", "confidence": "medium"}]
        mock_client.messages.create.return_value = _assess_tool_response(raw)
        result = _assess_llm(mock_client, criteria, als_patient, None)
        assert result[0].verdict == CriterionVerdict.PASS
        assert result[0].confidence == "medium"

    def test_fail_verdict_mapped(self, mock_client, als_patient):
        criteria = [_criterion("ecog_status")]
        raw = [{"criterion_key": "ecog_status", "verdict": "fail", "reason": "ECOG is 3", "patient_value": "3", "confidence": "medium"}]
        mock_client.messages.create.return_value = _assess_tool_response(raw)
        result = _assess_llm(mock_client, criteria, als_patient, None)
        assert result[0].verdict == CriterionVerdict.FAIL

    def test_unknown_criterion_key_skipped(self, mock_client, als_patient):
        criteria = [_criterion("ecog_status")]
        raw = [{"criterion_key": "nonexistent_key", "verdict": "pass", "reason": "ok", "patient_value": None, "confidence": "low"}]
        mock_client.messages.create.return_value = _assess_tool_response(raw)
        result = _assess_llm(mock_client, criteria, als_patient, None)
        assert result == []

    def test_missing_tool_call_returns_unknown_for_all(self, mock_client, als_patient):
        criteria = [_criterion("ecog_status"), _criterion("prior_systemic_therapy_lines")]
        mock_client.messages.create.return_value = make_message(
            content=[make_text_block("No tool")], stop_reason="end_turn"
        )
        result = _assess_llm(mock_client, criteria, als_patient, None)
        assert len(result) == 2
        assert all(a.verdict == CriterionVerdict.UNKNOWN for a in result)


# ---------------------------------------------------------------------------
# run_eligibility_check β€” orchestration
# ---------------------------------------------------------------------------

class TestRunEligibilityCheck:
    def _age_criterion_raw(self):
        return [{
            "key": "age_years",
            "type": "inclusion",
            "description": "Age 18-75",
            "raw_criteria": "Age between 18 and 75",
            "constraint": {"key": "age_years", "operator": "between", "value": [18, 75], "unit": None},
        }]

    def test_deterministic_criterion_resolved_without_llm_assess(self, mock_client, als_patient):
        # age_years=52 satisfies between [18,75] deterministically
        parse_resp = make_message(
            content=[make_tool_use_block("parse_criteria", {"criteria": self._age_criterion_raw()})],
            stop_reason="tool_use",
        )
        assess_resp = make_message(
            content=[make_tool_use_block("assess_eligibility", {"assessments": []})],
            stop_reason="tool_use",
        )
        mock_client.messages.create.side_effect = [parse_resp, assess_resp]

        trial = {"nct_id": "NCT99999999", "eligibility": "Inclusion:\n- Age between 18 and 75"}
        report = run_eligibility_check(mock_client, trial, als_patient)

        assert report.nct_id == "NCT99999999"
        det = [a for a in report.assessments if a.confidence == "high"]
        assert len(det) == 1
        assert det[0].verdict == CriterionVerdict.PASS

    def test_overall_verdict_fail_when_criterion_fails(self, mock_client, als_patient):
        # Age >75 means patient (age 52) passes, but let's use a criterion patient fails
        raw = [{
            "key": "age_years",
            "type": "inclusion",
            "description": "Age <= 40",
            "raw_criteria": "Age 40 or younger",
            "constraint": {"key": "age_years", "operator": "<=", "value": 40, "unit": None},
        }]
        parse_resp = make_message(
            content=[make_tool_use_block("parse_criteria", {"criteria": raw})],
            stop_reason="tool_use",
        )
        assess_resp = make_message(
            content=[make_tool_use_block("assess_eligibility", {"assessments": []})],
            stop_reason="tool_use",
        )
        mock_client.messages.create.side_effect = [parse_resp, assess_resp]
        trial = {"nct_id": "NCT00000001", "eligibility": "Age <= 40"}
        report = run_eligibility_check(mock_client, trial, als_patient)
        assert report.overall_verdict == CriterionVerdict.FAIL

    def test_empty_eligibility_text_returns_pass(self, mock_client, als_patient):
        trial = {"nct_id": "NCT00000002", "eligibility": ""}
        report = run_eligibility_check(mock_client, trial, als_patient)
        assert report.overall_verdict == CriterionVerdict.PASS
        # _parse_criteria short-circuits on empty text; _assess_llm short-circuits
        # on empty criteria list β€” neither should make an API call
        mock_client.messages.create.assert_not_called()

    def test_parse_called_once_assess_called_once(self, mock_client, als_patient):
        # ecog_status is a platform key; without platform_data it goes to needs_llm,
        # so _assess_llm will make a second API call
        platform_criterion = [{
            "key": "ecog_status",
            "type": "inclusion",
            "description": "ECOG 0 or 1",
            "raw_criteria": "ECOG performance status 0 or 1",
            "constraint": {"key": "ecog_status", "operator": "in", "value": [0, 1], "unit": None},
        }]
        parse_resp = make_message(
            content=[make_tool_use_block("parse_criteria", {"criteria": platform_criterion})],
            stop_reason="tool_use",
        )
        assess_resp = make_message(
            content=[make_tool_use_block("assess_eligibility", {"assessments": []})],
            stop_reason="tool_use",
        )
        mock_client.messages.create.side_effect = [parse_resp, assess_resp]
        trial = {"nct_id": "NCT00000003", "eligibility": "some text"}
        run_eligibility_check(mock_client, trial, als_patient)
        assert mock_client.messages.create.call_count == 2


# ---------------------------------------------------------------------------
# bulk_parse_and_strip β€” batch parse + deterministic filter
# ---------------------------------------------------------------------------

def _bulk_parse_response(trials_payload: list[dict]):
    return make_message(
        content=[make_tool_use_block("parse_criteria_bulk", {"trials": trials_payload})],
        stop_reason="tool_use",
    )


class TestBulkParseAndStrip:
    def _trial(self, nct_id: str, eligibility: str = "Age >= 18") -> dict:
        return {"nct_id": nct_id, "eligibility": eligibility, "title": f"Trial {nct_id}"}

    def test_strips_eligibility_field(self, mock_client, als_patient):
        raw_criteria = [{"nct_id": "NCT00000001", "criteria": []}]
        mock_client.messages.create.return_value = _bulk_parse_response(raw_criteria)
        result = bulk_parse_and_strip(mock_client, [self._trial("NCT00000001")], als_patient)
        assert "eligibility" not in result[0]

    def test_strips_std_ages_and_healthy_volunteers(self, mock_client, als_patient):
        trial = {**self._trial("NCT00000001"), "std_ages": ["ADULT"], "healthy_volunteers": "No"}
        mock_client.messages.create.return_value = _bulk_parse_response(
            [{"nct_id": "NCT00000001", "criteria": []}]
        )
        result = bulk_parse_and_strip(mock_client, [trial], als_patient)
        assert "std_ages" not in result[0]
        assert "healthy_volunteers" not in result[0]

    def test_adds_parsed_criteria_key(self, mock_client, als_patient):
        mock_client.messages.create.return_value = _bulk_parse_response(
            [{"nct_id": "NCT00000001", "criteria": []}]
        )
        result = bulk_parse_and_strip(mock_client, [self._trial("NCT00000001")], als_patient)
        assert "parsed_criteria" in result[0]

    def test_adds_deterministic_verdicts_key(self, mock_client, als_patient):
        mock_client.messages.create.return_value = _bulk_parse_response(
            [{"nct_id": "NCT00000001", "criteria": []}]
        )
        result = bulk_parse_and_strip(mock_client, [self._trial("NCT00000001")], als_patient)
        assert "deterministic_verdicts" in result[0]

    def test_deterministic_verdict_computed_for_known_key(self, mock_client, als_patient):
        # age_years=52, criterion >= 18 β†’ PASS
        age_criterion = {
            "key": "age_years", "type": "inclusion",
            "description": "Age >= 18", "raw_criteria": "Age >= 18",
            "constraint": {"key": "age_years", "operator": ">=", "value": 18, "unit": None},
        }
        mock_client.messages.create.return_value = _bulk_parse_response(
            [{"nct_id": "NCT00000001", "criteria": [age_criterion]}]
        )
        result = bulk_parse_and_strip(mock_client, [self._trial("NCT00000001")], als_patient)
        verdicts = result[0]["deterministic_verdicts"]
        assert len(verdicts) == 1
        assert verdicts[0]["verdict"] == "pass"

    def test_trials_beyond_top_n_passed_through_unmodified(self, mock_client, als_patient):
        trials = [self._trial(f"NCT{i:08d}") for i in range(7)]
        mock_client.messages.create.return_value = _bulk_parse_response(
            [{"nct_id": f"NCT{i:08d}", "criteria": []} for i in range(5)]
        )
        result = bulk_parse_and_strip(mock_client, trials, als_patient, top_n=5)
        assert len(result) == 7
        # Trials beyond top_n still have eligibility field
        assert "eligibility" in result[5]
        assert "eligibility" in result[6]

    def test_empty_trials_skipped(self, mock_client, als_patient):
        trial = self._trial("NCT00000001", eligibility="")
        result = bulk_parse_and_strip(mock_client, [trial], als_patient)
        # No API call β€” trial has no eligibility text
        mock_client.messages.create.assert_not_called()
        assert result == [trial]

    def test_api_failure_returns_trials_without_parsed_criteria(self, mock_client, als_patient):
        mock_client.messages.create.side_effect = Exception("API down")
        trial = self._trial("NCT00000001")
        result = bulk_parse_and_strip(mock_client, [trial], als_patient)
        # Should not raise; deterministic_verdicts should be empty
        assert result[0]["deterministic_verdicts"] == []