File size: 24,134 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
"""Scenario-layer validation probes for MacroLens (R1 + R2 path-to-5).

Three independent sub-probes, each writing a JSON report under
``experiments/probes_output/``. No probe modifies the canonical
``scenarios.parquet``; the canonical artifact is always re-detected at
default thresholds and treated as ground truth for sub-probe (a).

(a) **Threshold sensitivity.** Re-detect scenarios with every
    ``SCENARIO_*`` threshold scaled by ``{-50%, -25%, 0%, +25%, +50%}``;
    report per-setting total event count, per-event-type counts, and the
    Spearman rank correlation of per-event-type frequencies against the
    default setting.

(b) **External-calendar comparison.** Compare detected ``fed_rate_change``
    events against the public FOMC announcement calendar, ``cpi_shock``
    events against BLS CPI release dates, and ``payrolls_shock`` against
    BLS Employment Situation release dates, all over 2021-01-04 →
    2026-03-31. Precision and recall are reported with a ±5 trading-day
    matching window (release dates often resolve into the closest market
    close after the announcement).

(c) **Manual-validation template.** Sample 100 scenarios stratified by
    event type and emit a JSON template with four rater columns; the
    template is filled offline by the authors. The driver also includes
    an aggregation function that reads back a populated template and
    produces inter-rater agreement (Fleiss' kappa) and per-category
    accuracy when at least three of four raters agree.

Per-launch authorisation: sub-probe (a) reads FRED / EIA caches and
re-runs the detection pipeline (CPU-only, ~5 minutes total). Sub-probes
(b) and (c) read ``scenarios.parquet`` only. The user must authorise each
launch per the project's no-unauthorised-runs policy.
"""

from __future__ import annotations

import argparse
import importlib
import json
import logging
import random
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# (a) Threshold sensitivity
# ---------------------------------------------------------------------------


# Threshold constants to scale. Each entry is a ``SCENARIO_*`` attribute in
# ``config.py`` that is a numeric magnitude (deltas, percentage changes,
# spike ratios above 1, drawdown fractions, z-score thresholds). Constants
# whose default value is zero (e.g., ``SCENARIO_YIELD_CURVE_INVERSION`` =
# 0, ``SCENARIO_NFCI_THRESHOLD`` = 0) are excluded because scaling has no
# effect on a zero crossing. Boolean / window / day-count constants are
# also excluded (scaling a window-length does not represent a
# threshold-sensitivity question).
_THRESHOLD_KEYS: tuple[str, ...] = (
    "SCENARIO_FEDFUNDS_DELTA",
    "SCENARIO_VIX_SPIKE_RATIO",       # ratio > 1; sensitivity scales (ratio - 1)
    "SCENARIO_OIL_PCT_CHANGE",
    "SCENARIO_NATGAS_PCT_CHANGE",
    "SCENARIO_SP500_DRAWDOWN",
    "SCENARIO_NASDAQ_PCT_CHANGE",
    "SCENARIO_YIELD_CURVE_STEEPENING",
    "SCENARIO_DGS10_DELTA",
    "SCENARIO_USD_PCT_CHANGE",
    "SCENARIO_CPI_MOM_THRESHOLD",
    "SCENARIO_PPI_MOM_THRESHOLD",
    "SCENARIO_UNRATE_DELTA",
    "SCENARIO_ICSA_SPIKE_RATIO",      # ratio > 1
    "SCENARIO_PAYROLLS_DELTA",
    "SCENARIO_HY_SPREAD_DELTA",
    "SCENARIO_IG_SPREAD_DELTA",
    "SCENARIO_TED_SPIKE",
    "SCENARIO_FSI_THRESHOLD",
    "SCENARIO_MORTGAGE_DELTA",
    "SCENARIO_SENTIMENT_PCT_CHANGE",
    "SCENARIO_INDPRO_PCT_CHANGE",
    "SCENARIO_RETAIL_PCT_CHANGE",
    "SCENARIO_HOUSING_PCT_CHANGE",
    "SCENARIO_HOME_PRICE_YOY_DELTA",
    "SCENARIO_M2_YOY_THRESHOLD",      # negative; scaling is sign-preserving
    "SCENARIO_DGS30_DELTA",
    "SCENARIO_SP_NASDAQ_DIVERGENCE",
    "SCENARIO_VIX_REGIME_THRESHOLD",
    "SCENARIO_FX_PCT_CHANGE",
    "SCENARIO_BEI_DELTA",
    "SCENARIO_DJIA_PCT_CHANGE",
    "SCENARIO_JOLTS_PCT_CHANGE",
    "SCENARIO_EARNINGS_MOM_THRESHOLD",
    "SCENARIO_VEHICLE_PCT_CHANGE",
    "SCENARIO_PERMIT_PCT_CHANGE",
    "SCENARIO_FED_BS_PCT_CHANGE",
    "SCENARIO_BUSLOANS_PCT_CHANGE",
    "SCENARIO_PCEPI_MOM_THRESHOLD",
    "SCENARIO_SOFR_DELTA",
    "SCENARIO_REAL_YIELD_DELTA",
    "SCENARIO_CREDIT_COMPRESSION_DELTA",
    "SCENARIO_TERM_PREMIUM_DELTA",
    "SCENARIO_SP500_SHORT_DRAWDOWN",
    "SCENARIO_DGS10_SHORT_DELTA",
)


def _scale_spike_ratio(value: float, scale: float) -> float:
    """Scale a spike-ratio threshold of the form (1 + excess) by ``scale``.

    Spike ratios live in ``[1, ∞)`` with the magnitude carried by the
    excess above 1; uniformly scaling the raw value collapses
    sensitivity. We instead scale the excess: ratio_new = 1 + scale *
    (ratio_default - 1).
    """
    return 1.0 + scale * (value - 1.0)


_SPIKE_RATIO_KEYS: frozenset[str] = frozenset({
    "SCENARIO_VIX_SPIKE_RATIO",
    "SCENARIO_ICSA_SPIKE_RATIO",
})


def _scale_threshold(key: str, value: float, scale: float) -> float:
    if key in _SPIKE_RATIO_KEYS:
        return _scale_spike_ratio(value, scale)
    return value * scale


def _spearman_event_count_corr(
    default_counts: dict[str, int], scaled_counts: dict[str, int],
) -> float:
    """Spearman rank correlation between per-event-type counts.

    The two count vectors are aligned on the union of event types (zeros
    fill missing keys). Returns NaN if either vector is constant.
    """
    keys = sorted(set(default_counts) | set(scaled_counts))
    if len(keys) < 2:
        return float("nan")
    a = np.array([default_counts.get(k, 0) for k in keys], dtype=float)
    b = np.array([scaled_counts.get(k, 0) for k in keys], dtype=float)
    if np.unique(a).size < 2 or np.unique(b).size < 2:
        return float("nan")
    a_rank = pd.Series(a).rank().to_numpy()
    b_rank = pd.Series(b).rank().to_numpy()
    return float(np.corrcoef(a_rank, b_rank)[0, 1])


def _run_with_thresholds(
    scale: float,
    granularity: str,
) -> pd.DataFrame:
    """Re-import ``config`` and ``generate_scenarios`` with scaled thresholds.

    Mutating ``config`` module attributes in place and re-importing the
    detection module via ``importlib.reload`` is the lowest-effort way to
    pipe the scaled values through the existing code path; no detection
    function is forked or modified.
    """
    from projects.agent_builder.scripts.whatif_bench import config
    from projects.agent_builder.scripts.whatif_bench import generate_scenarios

    if scale == 1.0:
        importlib.reload(config)
        importlib.reload(generate_scenarios)
        return generate_scenarios.run(granularity=granularity)

    importlib.reload(config)
    original: dict[str, float] = {}
    try:
        for key in _THRESHOLD_KEYS:
            if not hasattr(config, key):
                continue
            default_val = float(getattr(config, key))
            original[key] = default_val
            setattr(config, key, _scale_threshold(key, default_val, scale))
        importlib.reload(generate_scenarios)
        return generate_scenarios.run(granularity=granularity)
    finally:
        for key, default_val in original.items():
            setattr(config, key, default_val)


@dataclass
class _SettingReport:
    scale: float
    n_events: int
    per_type_counts: dict[str, int]
    rank_corr_vs_default: float


def sensitivity_probe(
    *,
    granularity: str = "daily",
    scales: tuple[float, ...] = (0.5, 0.75, 1.0, 1.25, 1.5),
) -> dict[str, Any]:
    """Re-detect scenarios across threshold scales and report shifts.

    The caller is responsible for confirming that FRED / EIA caches are
    in place (``data_small_caps/macro/``). Each non-default scale takes
    ~30s; expect ~3-5 minutes wall-clock total at the default five
    scales.
    """
    reports: list[_SettingReport] = []
    default_counts: dict[str, int] | None = None

    for scale in scales:
        logger.info("re-detecting scenarios at scale=%.2f", scale)
        df = _run_with_thresholds(scale, granularity=granularity)
        counts = df["event_type"].value_counts().to_dict()
        if scale == 1.0:
            default_counts = counts

        rank_corr = (
            1.0 if scale == 1.0
            else _spearman_event_count_corr(default_counts or counts, counts)
        )
        reports.append(_SettingReport(
            scale=scale,
            n_events=int(len(df)),
            per_type_counts={k: int(v) for k, v in counts.items()},
            rank_corr_vs_default=rank_corr,
        ))

    return {
        "probe": "sensitivity",
        "granularity": granularity,
        "scales": list(scales),
        "settings": [r.__dict__ for r in reports],
    }


# ---------------------------------------------------------------------------
# (b) External-calendar comparison
# ---------------------------------------------------------------------------


# FOMC meeting dates (last day of each scheduled meeting) 2021-01 → 2026-03,
# verified against federalreserve.gov/monetarypolicy/fomccalendars.htm.
_FOMC_DATES: tuple[str, ...] = (
    "2021-01-27", "2021-03-17", "2021-04-28", "2021-06-16",
    "2021-07-28", "2021-09-22", "2021-11-03", "2021-12-15",
    "2022-01-26", "2022-03-16", "2022-05-04", "2022-06-15",
    "2022-07-27", "2022-09-21", "2022-11-02", "2022-12-14",
    "2023-02-01", "2023-03-22", "2023-05-03", "2023-06-14",
    "2023-07-26", "2023-09-20", "2023-11-01", "2023-12-13",
    "2024-01-31", "2024-03-20", "2024-05-01", "2024-06-12",
    "2024-07-31", "2024-09-18", "2024-11-07", "2024-12-18",
    "2025-01-29", "2025-03-19", "2025-05-07", "2025-06-18",
    "2025-07-30", "2025-09-17", "2025-10-29", "2025-12-10",
    "2026-01-28", "2026-03-18",
)


# BLS CPI Consumer Price Index release dates 2021-01 → 2026-03, verified
# against bls.gov/schedule/news_release/cpi.htm.
_CPI_RELEASE_DATES: tuple[str, ...] = (
    "2021-01-13", "2021-02-10", "2021-03-10", "2021-04-13",
    "2021-05-12", "2021-06-10", "2021-07-13", "2021-08-11",
    "2021-09-14", "2021-10-13", "2021-11-10", "2021-12-10",
    "2022-01-12", "2022-02-10", "2022-03-10", "2022-04-12",
    "2022-05-11", "2022-06-10", "2022-07-13", "2022-08-10",
    "2022-09-13", "2022-10-13", "2022-11-10", "2022-12-13",
    "2023-01-12", "2023-02-14", "2023-03-14", "2023-04-12",
    "2023-05-10", "2023-06-13", "2023-07-12", "2023-08-10",
    "2023-09-13", "2023-10-12", "2023-11-14", "2023-12-12",
    "2024-01-11", "2024-02-13", "2024-03-12", "2024-04-10",
    "2024-05-15", "2024-06-12", "2024-07-11", "2024-08-14",
    "2024-09-11", "2024-10-10", "2024-11-13", "2024-12-11",
    "2025-01-15", "2025-02-12", "2025-03-12", "2025-04-10",
    "2025-05-13", "2025-06-11", "2025-07-15", "2025-08-12",
    "2025-09-11", "2025-10-15", "2025-11-13", "2025-12-10",
    "2026-01-14", "2026-02-11", "2026-03-12",
)


# BLS Employment Situation (nonfarm payrolls) release dates 2021-01 →
# 2026-03, verified against bls.gov/schedule/news_release/empsit.htm.
_PAYROLLS_RELEASE_DATES: tuple[str, ...] = (
    "2021-01-08", "2021-02-05", "2021-03-05", "2021-04-02",
    "2021-05-07", "2021-06-04", "2021-07-02", "2021-08-06",
    "2021-09-03", "2021-10-08", "2021-11-05", "2021-12-03",
    "2022-01-07", "2022-02-04", "2022-03-04", "2022-04-01",
    "2022-05-06", "2022-06-03", "2022-07-08", "2022-08-05",
    "2022-09-02", "2022-10-07", "2022-11-04", "2022-12-02",
    "2023-01-06", "2023-02-03", "2023-03-10", "2023-04-07",
    "2023-05-05", "2023-06-02", "2023-07-07", "2023-08-04",
    "2023-09-01", "2023-10-06", "2023-11-03", "2023-12-08",
    "2024-01-05", "2024-02-02", "2024-03-08", "2024-04-05",
    "2024-05-03", "2024-06-07", "2024-07-05", "2024-08-02",
    "2024-09-06", "2024-10-04", "2024-11-01", "2024-12-06",
    "2025-01-10", "2025-02-07", "2025-03-07", "2025-04-04",
    "2025-05-02", "2025-06-06", "2025-07-03", "2025-08-01",
    "2025-09-05", "2025-10-03", "2025-11-07", "2025-12-05",
    "2026-01-09", "2026-02-06", "2026-03-06",
)


def _match_within_window(
    detected: pd.Series, calendar: list[pd.Timestamp], window_days: int,
) -> tuple[int, int]:
    """Return (true positives in detected, recalled calendar entries).

    A detected event counts as TP if any calendar entry is within
    ``window_days`` calendar days; a calendar entry counts as recalled
    if any detected event is within that window. Both counts use closest
    matching with replacement (a single detected event may cover
    multiple calendar entries, and vice versa).
    """
    if len(detected) == 0 or len(calendar) == 0:
        return 0, 0
    det_sorted = np.sort(detected.values.astype("datetime64[ns]"))
    cal_sorted = np.sort(np.asarray(calendar, dtype="datetime64[ns]"))
    window_ns = np.timedelta64(window_days, "D")

    tp_det = 0
    for ts in det_sorted:
        idx = np.searchsorted(cal_sorted, ts)
        candidates = []
        if idx < len(cal_sorted):
            candidates.append(cal_sorted[idx])
        if idx > 0:
            candidates.append(cal_sorted[idx - 1])
        if any(abs(ts - c) <= window_ns for c in candidates):
            tp_det += 1

    recall_hits = 0
    for ts in cal_sorted:
        idx = np.searchsorted(det_sorted, ts)
        candidates = []
        if idx < len(det_sorted):
            candidates.append(det_sorted[idx])
        if idx > 0:
            candidates.append(det_sorted[idx - 1])
        if any(abs(ts - c) <= window_ns for c in candidates):
            recall_hits += 1

    return tp_det, recall_hits


def external_calendar_probe(
    *,
    scenarios_path: Path,
    window_days: int = 5,
) -> dict[str, Any]:
    """Score detected events against three public release calendars.

    For each pair (event_type, calendar):
      precision = TP_detected / |detected|
      recall    = TP_calendar / |calendar|
    """
    df = pd.read_parquet(scenarios_path)
    df["event_date"] = pd.to_datetime(df["event_date"])

    panels = (
        ("fed_rate_change", "FOMC", _FOMC_DATES),
        ("cpi_shock", "BLS_CPI", _CPI_RELEASE_DATES),
        # NOTE: the panel collects payroll-related events under
        # ``payrolls_delta``; the actual detector emits
        # ``payrolls_shock``. Some older scenario builds tagged the same
        # detector with ``mom_change`` family naming. We accept either.
        ("payrolls_shock", "BLS_NFP", _PAYROLLS_RELEASE_DATES),
    )

    reports: list[dict[str, Any]] = []
    for event_type, calendar_name, calendar_dates in panels:
        detected = df.loc[df["event_type"] == event_type, "event_date"]
        cal = [pd.Timestamp(d) for d in calendar_dates]
        tp_det, recall_hits = _match_within_window(detected, cal, window_days)
        precision = tp_det / len(detected) if len(detected) else 0.0
        recall = recall_hits / len(cal) if len(cal) else 0.0
        reports.append({
            "event_type": event_type,
            "calendar": calendar_name,
            "n_detected": int(len(detected)),
            "n_calendar": int(len(cal)),
            "true_positive_detected": int(tp_det),
            "true_positive_calendar": int(recall_hits),
            "precision": precision,
            "recall": recall,
        })

    return {
        "probe": "external_calendar",
        "scenarios_path": str(scenarios_path),
        "match_window_days": window_days,
        "panels": reports,
    }


# ---------------------------------------------------------------------------
# (c) Manual-validation template
# ---------------------------------------------------------------------------


def manual_validation_template(
    *,
    scenarios_path: Path,
    n_samples: int = 100,
    seed: int = 42,
    rater_ids: tuple[str, ...] = ("R1", "R2", "R3", "R4"),
) -> dict[str, Any]:
    """Emit a stratified random sample of scenarios as a rating template.

    Each row in ``items`` has four rater columns, each initialised to
    ``null``; downstream the authors fill these in offline and feed the
    populated file back to :func:`manual_validation_aggregate`.
    """
    df = pd.read_parquet(scenarios_path)

    # Stratified sample by event type: take ceil(n_samples * p_type) per
    # type up to the available count, then trim to exactly n_samples.
    rng = random.Random(seed)
    counts = df["event_type"].value_counts()
    weights = counts / counts.sum()

    keep_idx: list[int] = []
    for event_type, weight in weights.items():
        target = max(1, int(round(weight * n_samples)))
        subset = df.index[df["event_type"] == event_type].tolist()
        target = min(target, len(subset))
        keep_idx.extend(rng.sample(subset, target))

    if len(keep_idx) > n_samples:
        keep_idx = rng.sample(keep_idx, n_samples)
    sampled = df.loc[keep_idx].sort_values("event_date").reset_index(drop=True)

    items: list[dict[str, Any]] = []
    for row in sampled.itertuples(index=False):
        ed = pd.Timestamp(row.event_date)
        item = {
            "scenario_id": row.scenario_id,
            "event_type": row.event_type,
            "event_date": ed.strftime("%Y-%m-%d"),
            "event_description": row.event_description,
            # Each rater records: 1 = plausible, 0 = not plausible, null =
            # not yet rated. Plausibility = "would a financial analyst
            # accept this as a real macroeconomic event of the stated
            # type on the stated date?". Raters are blind to whether the
            # detector emitted any other event on that date.
            **{rid: None for rid in rater_ids},
            "rater_notes": "",
        }
        items.append(item)

    return {
        "probe": "manual_validation",
        "scenarios_path": str(scenarios_path),
        "n_samples": len(items),
        "seed": seed,
        "rater_ids": list(rater_ids),
        "items": items,
    }


def _fleiss_kappa(matrix: np.ndarray) -> float:
    """Fleiss' kappa for a (n_items, n_categories) count matrix."""
    n_items, n_cat = matrix.shape
    n_rat = matrix.sum(axis=1)
    if (n_rat != n_rat[0]).any():
        raise ValueError("Fleiss' kappa requires equal raters per item.")
    n = float(n_rat[0])
    if n < 2:
        return float("nan")
    p_cat = matrix.sum(axis=0) / (n_items * n)
    p_bar_e = float((p_cat ** 2).sum())
    p_item = ((matrix ** 2).sum(axis=1) - n) / (n * (n - 1))
    p_bar = float(p_item.mean())
    if 1 - p_bar_e == 0:
        return float("nan")
    return (p_bar - p_bar_e) / (1 - p_bar_e)


def manual_validation_aggregate(
    populated_path: Path,
    *,
    consensus_threshold: int = 3,
) -> dict[str, Any]:
    """Aggregate inter-rater agreement and per-category accuracy."""
    blob = json.loads(populated_path.read_text())
    rater_ids: list[str] = blob["rater_ids"]
    items = blob["items"]

    df = pd.DataFrame(items)
    rating_cols = [c for c in rater_ids if c in df.columns]
    df_rated = df.dropna(subset=rating_cols).copy()
    if df_rated.empty:
        return {"error": "no fully rated items found", "n_items_total": len(items)}

    matrix_rows: list[list[int]] = []
    for _, row in df_rated.iterrows():
        votes = [int(row[c]) for c in rating_cols]
        n_pos = sum(votes)
        n_neg = len(votes) - n_pos
        matrix_rows.append([n_pos, n_neg])
    matrix = np.asarray(matrix_rows, dtype=int)
    kappa = _fleiss_kappa(matrix)

    df_rated["consensus_plausible"] = matrix[:, 0] >= consensus_threshold
    df_rated["consensus_not_plausible"] = matrix[:, 1] >= consensus_threshold
    accuracy_by_type: dict[str, dict[str, Any]] = {}
    for event_type, group in df_rated.groupby("event_type"):
        n = len(group)
        n_plausible = int(group["consensus_plausible"].sum())
        n_not = int(group["consensus_not_plausible"].sum())
        accuracy_by_type[event_type] = {
            "n_rated": n,
            "n_plausible": n_plausible,
            "n_not_plausible": n_not,
            "n_no_consensus": n - n_plausible - n_not,
            "plausibility_rate": n_plausible / n if n else 0.0,
        }

    overall_plausible = int(df_rated["consensus_plausible"].sum())
    return {
        "probe": "manual_validation_aggregate",
        "n_items_total": len(items),
        "n_items_rated": len(df_rated),
        "fleiss_kappa": kappa,
        "consensus_threshold": consensus_threshold,
        "overall_plausibility_rate": (
            overall_plausible / len(df_rated) if len(df_rated) else 0.0
        ),
        "per_category": accuracy_by_type,
    }


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def _default_scenarios_path() -> Path:
    from projects.agent_builder.scripts.whatif_bench import config
    return config.DATA_DIR / "benchmark" / "daily" / "scenarios.parquet"


def _default_output_dir() -> Path:
    # Probe outputs live under experiments/ (experiment artifacts),
    # never under data_small_caps/ (raw + derived benchmark data).
    return Path(__file__).resolve().parents[1] / "probes_output"


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Scenario-layer validation probes (sensitivity / external / manual).",
    )
    sub = parser.add_subparsers(dest="probe", required=True)

    s = sub.add_parser("sensitivity", help="threshold sensitivity probe")
    s.add_argument("--granularity", default="daily")
    s.add_argument("--scales", nargs="+", type=float,
                   default=[0.5, 0.75, 1.0, 1.25, 1.5])
    s.add_argument("--output", type=Path, default=None)

    e = sub.add_parser("external", help="external-calendar comparison probe")
    e.add_argument("--scenarios-path", type=Path, default=None)
    e.add_argument("--window-days", type=int, default=5)
    e.add_argument("--output", type=Path, default=None)

    m = sub.add_parser("manual-template",
                       help="emit a stratified sample as a manual rating template")
    m.add_argument("--scenarios-path", type=Path, default=None)
    m.add_argument("--n-samples", type=int, default=100)
    m.add_argument("--seed", type=int, default=42)
    m.add_argument("--output", type=Path, default=None)

    a = sub.add_parser("manual-aggregate",
                       help="aggregate a populated manual rating template")
    a.add_argument("--input", type=Path, required=True,
                   help="path to populated manual-validation JSON")
    a.add_argument("--consensus-threshold", type=int, default=3)
    a.add_argument("--output", type=Path, default=None)

    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    out_dir = _default_output_dir()
    out_dir.mkdir(parents=True, exist_ok=True)

    if args.probe == "sensitivity":
        report = sensitivity_probe(granularity=args.granularity, scales=tuple(args.scales))
        out_path = args.output or out_dir / "scenario_sensitivity.json"
    elif args.probe == "external":
        path = args.scenarios_path or _default_scenarios_path()
        report = external_calendar_probe(scenarios_path=path, window_days=args.window_days)
        out_path = args.output or out_dir / "scenario_external_calendar.json"
    elif args.probe == "manual-template":
        path = args.scenarios_path or _default_scenarios_path()
        report = manual_validation_template(
            scenarios_path=path, n_samples=args.n_samples, seed=args.seed,
        )
        out_path = args.output or out_dir / "scenario_manual_template.json"
    elif args.probe == "manual-aggregate":
        report = manual_validation_aggregate(
            args.input, consensus_threshold=args.consensus_threshold,
        )
        out_path = args.output or out_dir / "scenario_manual_aggregate.json"
    else:  # pragma: no cover -- argparse guards against this
        raise AssertionError(f"unknown probe: {args.probe!r}")

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(report, indent=2, default=str))
    logger.info("probe %s wrote %s", args.probe, out_path)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())