Skip to content

Decision Engines Reference

AutoDecisionEngine

Default client for provisioning a decision engine backend (the refactor of the original JevClient).

Decision Engine adapter delegating to the best available backend.

Prefers :class:LayaDecisionEngine on Apple Silicon when laya_mlx is installed; otherwise falls back to :class:TransformersDecisionEngine.

Parameters

checkpoint : str, default "aac6fef/laya-mlx" Model checkpoint identifier (MLX format or Hugging Face repository ID). model_name : str or None, optional Alternative checkpoint identifier for Transformers. provider : str or None, optional Explicit backend selector ('laya', 'mlx', 'transformers', or 'auto'). default_confidence_threshold : float, default 0.85 Empirical accuracy threshold for fast-exit routing. conformal_alpha : float, default 0.05 Significance level for conformal prediction sets. batch_size : int, default 16 Maximum batch size for evaluation. timeout_seconds : float, default 2.0 Per-decision call timeout in seconds. args : Any Additional positional arguments passed to backend. *kwargs : Any Additional keyword arguments forwarded to backend engines.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
class AutoDecisionEngine:
    """Decision Engine adapter delegating to the best available backend.

    Prefers :class:`LayaDecisionEngine` on Apple Silicon when ``laya_mlx`` is
    installed; otherwise falls back to :class:`TransformersDecisionEngine`.

    Parameters
    ----------
    checkpoint : str, default "aac6fef/laya-mlx"
        Model checkpoint identifier (MLX format or Hugging Face repository ID).
    model_name : str or None, optional
        Alternative checkpoint identifier for Transformers.
    provider : str or None, optional
        Explicit backend selector ('laya', 'mlx', 'transformers', or 'auto').
    default_confidence_threshold : float, default 0.85
        Empirical accuracy threshold for fast-exit routing.
    conformal_alpha : float, default 0.05
        Significance level for conformal prediction sets.
    batch_size : int, default 16
        Maximum batch size for evaluation.
    timeout_seconds : float, default 2.0
        Per-decision call timeout in seconds.
    *args : Any
        Additional positional arguments passed to backend.
    **kwargs : Any
        Additional keyword arguments forwarded to backend engines.
    """

    def __init__(
        self,
        checkpoint: str = "aac6fef/laya-mlx",
        model_name: str | None = None,
        provider: str | None = None,
        default_confidence_threshold: float = 0.85,
        conformal_alpha: float = 0.05,
        batch_size: int = 16,
        timeout_seconds: float = 2.0,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        target_checkpoint = model_name if model_name is not None else checkpoint
        self._inner: DecisionEngine = _create_engine_backend(
            provider=provider or "auto",
            checkpoint=target_checkpoint,
            default_confidence_threshold=default_confidence_threshold,
            conformal_alpha=conformal_alpha,
            batch_size=batch_size,
            timeout_seconds=timeout_seconds,
            *args,
            **kwargs,
        )

    @property
    def name(self) -> str:
        """Return the active underlying engine name.

        Returns
        -------
        str
            Engine identifier.
        """
        return self._inner.name

    def fingerprint(self) -> dict[str, Any]:
        """Return a deterministic representation of engine configuration.

        Returns
        -------
        dict of str to Any
            Deterministic dictionary delegating to the underlying engine backend.
        """
        inner_fp = (
            self._inner.fingerprint()
            if hasattr(self._inner, "fingerprint") and callable(self._inner.fingerprint)
            else {"class": self._inner.__class__.__name__}
        )
        return {
            "class": self.__class__.__name__,
            "inner": inner_fp,
        }

    async def evaluate_noul(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
    ) -> DecisionNoulResult:
        """Evaluate a binary yes/no statement.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        question : str
            Proposition or question.

        Returns
        -------
        DecisionNoulResult
            Evaluation outcome.
        """
        return await self._inner.evaluate_noul(state, question)

    async def evaluate_choice(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        options: list[str] | dict[str, str],
        alpha: float | None = None,
    ) -> DecisionScore:
        """Evaluate a categorical choice question.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        question : str
            Categorical decision question.
        options : list of str or dict of str to str
            Candidate choices.
        alpha : float or None, default None
            Miscoverage significance level.

        Returns
        -------
        DecisionScore
            Scored categorical decision.
        """
        return await self._inner.evaluate_choice(state, question, options, alpha)

    async def evaluate_score(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        levels: list[int | str],
    ) -> DecisionScore:
        """Evaluate an ordered scale or rubric score.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        question : str
            Rubric or scoring question.
        levels : list of int or list of str
            Ordered score levels.

        Returns
        -------
        DecisionScore
            Score outcome.
        """
        return await self._inner.evaluate_score(state, question, levels)

    async def evaluate(
        self,
        state: str | dict[str, Any] | list[Any],
        question: DecisionQuestion | dict[str, Any],
    ) -> DecisionScore | DecisionNoulResult:
        """Evaluate a single typed question.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        question : DecisionQuestion or dict
            Proposition or question specification.

        Returns
        -------
        DecisionScore or DecisionNoulResult
            Evaluation outcome.
        """
        return await self._inner.evaluate(state, question)

    async def evaluate_batch(
        self,
        state: str | dict[str, Any] | list[Any],
        questions: dict[str, DecisionQuestion | dict[str, Any]],
    ) -> dict[str, DecisionScore | DecisionNoulResult]:
        """Evaluate multiple questions in batch.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        questions : dict of str to (DecisionQuestion or dict)
            Question specifications.

        Returns
        -------
        dict of str to (DecisionScore or DecisionNoulResult)
            Batch evaluation results.
        """
        return await self._inner.evaluate_batch(state, questions)

name property

Return the active underlying engine name.

Returns

str Engine identifier.

evaluate(state, question) async

Evaluate a single typed question.

Parameters

state : str or dict or list State payload. question : DecisionQuestion or dict Proposition or question specification.

Returns

DecisionScore or DecisionNoulResult Evaluation outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
async def evaluate(
    self,
    state: str | dict[str, Any] | list[Any],
    question: DecisionQuestion | dict[str, Any],
) -> DecisionScore | DecisionNoulResult:
    """Evaluate a single typed question.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    question : DecisionQuestion or dict
        Proposition or question specification.

    Returns
    -------
    DecisionScore or DecisionNoulResult
        Evaluation outcome.
    """
    return await self._inner.evaluate(state, question)

evaluate_batch(state, questions) async

Evaluate multiple questions in batch.

Parameters

state : str or dict or list State payload. questions : dict of str to (DecisionQuestion or dict) Question specifications.

Returns

dict of str to (DecisionScore or DecisionNoulResult) Batch evaluation results.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
async def evaluate_batch(
    self,
    state: str | dict[str, Any] | list[Any],
    questions: dict[str, DecisionQuestion | dict[str, Any]],
) -> dict[str, DecisionScore | DecisionNoulResult]:
    """Evaluate multiple questions in batch.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    questions : dict of str to (DecisionQuestion or dict)
        Question specifications.

    Returns
    -------
    dict of str to (DecisionScore or DecisionNoulResult)
        Batch evaluation results.
    """
    return await self._inner.evaluate_batch(state, questions)

evaluate_choice(state, question, options, alpha=None) async

Evaluate a categorical choice question.

Parameters

state : str or dict or list State payload. question : str Categorical decision question. options : list of str or dict of str to str Candidate choices. alpha : float or None, default None Miscoverage significance level.

Returns

DecisionScore Scored categorical decision.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
async def evaluate_choice(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    options: list[str] | dict[str, str],
    alpha: float | None = None,
) -> DecisionScore:
    """Evaluate a categorical choice question.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    question : str
        Categorical decision question.
    options : list of str or dict of str to str
        Candidate choices.
    alpha : float or None, default None
        Miscoverage significance level.

    Returns
    -------
    DecisionScore
        Scored categorical decision.
    """
    return await self._inner.evaluate_choice(state, question, options, alpha)

evaluate_noul(state, question) async

Evaluate a binary yes/no statement.

Parameters

state : str or dict or list State payload. question : str Proposition or question.

Returns

DecisionNoulResult Evaluation outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
async def evaluate_noul(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
) -> DecisionNoulResult:
    """Evaluate a binary yes/no statement.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    question : str
        Proposition or question.

    Returns
    -------
    DecisionNoulResult
        Evaluation outcome.
    """
    return await self._inner.evaluate_noul(state, question)

evaluate_score(state, question, levels) async

Evaluate an ordered scale or rubric score.

Parameters

state : str or dict or list State payload. question : str Rubric or scoring question. levels : list of int or list of str Ordered score levels.

Returns

DecisionScore Score outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
async def evaluate_score(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    levels: list[int | str],
) -> DecisionScore:
    """Evaluate an ordered scale or rubric score.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    question : str
        Rubric or scoring question.
    levels : list of int or list of str
        Ordered score levels.

    Returns
    -------
    DecisionScore
        Score outcome.
    """
    return await self._inner.evaluate_score(state, question, levels)

fingerprint()

Return a deterministic representation of engine configuration.

Returns

dict of str to Any Deterministic dictionary delegating to the underlying engine backend.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
def fingerprint(self) -> dict[str, Any]:
    """Return a deterministic representation of engine configuration.

    Returns
    -------
    dict of str to Any
        Deterministic dictionary delegating to the underlying engine backend.
    """
    inner_fp = (
        self._inner.fingerprint()
        if hasattr(self._inner, "fingerprint") and callable(self._inner.fingerprint)
        else {"class": self._inner.__class__.__name__}
    )
    return {
        "class": self.__class__.__name__,
        "inner": inner_fp,
    }

LayaDecisionEngine

Apple Silicon (MLX) decision engine backend.

High-performance Apple Silicon MLX decision engine client.

Runs local bidirectional Transformer inference using laya_mlx (ModernBERT / mmBERT backbone) to evaluate typed questions against state blocks with dual confidence metrics and zero output token generation.

Parameters

checkpoint : str, default "aac6fef/laya-mlx" Hugging Face repository ID or local path to pre-converted MLX checkpoint. dtype : str, default "float16" Computation precision ("float16" or "float32"). batch_size : int, default 16 Maximum questions processed per MLX forward pass. timeout_seconds : float, default 2.0 Per-request inference timeout in seconds. default_confidence_threshold : float, default 0.85 Empirical accuracy threshold for fast-exit routing. conformal_alpha : float, default 0.05 Default significance level for conformal prediction sets (guaranteeing 1 - alpha coverage). agent : Any or None, default None Optional pre-loaded laya.Agent instance. If None, loaded lazily. embed_fn : Any or None, default None Optional bi-encoder embedding function for large choice set shortlisting. shortlist_threshold : int, default 5 Option count threshold above which candidate shortlisting is applied. compile : bool, default False Whether to enable MLX graph compilation. cache_prompts : bool, default False Whether to cache prefix tokenizations across repetitive calls.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
 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
class LayaDecisionEngine:
    """High-performance Apple Silicon MLX decision engine client.

    Runs local bidirectional Transformer inference using ``laya_mlx``
    (ModernBERT / mmBERT backbone) to evaluate typed questions against state
    blocks with dual confidence metrics and zero output token generation.

    Parameters
    ----------
    checkpoint : str, default "aac6fef/laya-mlx"
        Hugging Face repository ID or local path to pre-converted MLX checkpoint.
    dtype : str, default "float16"
        Computation precision ("float16" or "float32").
    batch_size : int, default 16
        Maximum questions processed per MLX forward pass.
    timeout_seconds : float, default 2.0
        Per-request inference timeout in seconds.
    default_confidence_threshold : float, default 0.85
        Empirical accuracy threshold for fast-exit routing.
    conformal_alpha : float, default 0.05
        Default significance level for conformal prediction sets (guaranteeing
        1 - alpha coverage).
    agent : Any or None, default None
        Optional pre-loaded ``laya.Agent`` instance. If None, loaded lazily.
    embed_fn : Any or None, default None
        Optional bi-encoder embedding function for large choice set shortlisting.
    shortlist_threshold : int, default 5
        Option count threshold above which candidate shortlisting is applied.
    compile : bool, default False
        Whether to enable MLX graph compilation.
    cache_prompts : bool, default False
        Whether to cache prefix tokenizations across repetitive calls.
    """

    def __init__(
        self,
        checkpoint: str = "aac6fef/laya-mlx",
        dtype: str = "float16",
        batch_size: int = 16,
        timeout_seconds: float = 2.0,
        default_confidence_threshold: float = 0.85,
        conformal_alpha: float = 0.05,
        agent: Any = None,
        embed_fn: Any = None,
        shortlist_threshold: int = 5,
        compile: bool = False,
        cache_prompts: bool = False,
    ) -> None:
        self.checkpoint = checkpoint
        self.dtype = dtype
        self.batch_size = batch_size
        self.timeout_seconds = timeout_seconds
        self.default_confidence_threshold = default_confidence_threshold
        self.conformal_alpha = conformal_alpha
        self.embed_fn = embed_fn
        self.shortlist_threshold = shortlist_threshold
        self.compile = compile
        self.cache_prompts = cache_prompts
        self._agent = agent

    @property
    def name(self) -> str:
        """Return the engine name."""
        return f"LayaDecisionEngine({self.checkpoint})"

    def fingerprint(self) -> dict[str, Any]:
        """Return a deterministic representation of engine configuration.

        Returns
        -------
        dict of str to Any
            Deterministic dictionary containing model checkpoint, precision,
            batch size, inference timeout, calibration thresholds, and flags.
        """
        return {
            "class": self.__class__.__name__,
            "checkpoint": self.checkpoint,
            "dtype": self.dtype,
            "batch_size": self.batch_size,
            "timeout_seconds": self.timeout_seconds,
            "default_confidence_threshold": self.default_confidence_threshold,
            "conformal_alpha": self.conformal_alpha,
            "shortlist_threshold": self.shortlist_threshold,
            "compile": self.compile,
            "cache_prompts": self.cache_prompts,
        }

    def _get_agent(self) -> Any:
        """Lazily load the underlying Laya MLX agent.

        Returns
        -------
        Any
            The loaded ``laya_mlx`` Agent instance.

        Raises
        ------
        DecisionEngineError
            If ``laya_mlx`` is not installed or the checkpoint fails to load.
        """
        if self._agent is not None:
            return self._agent

        try:
            import laya_mlx as laya
        except ImportError as exc:
            raise DecisionEngineError(
                "laya-mlx is not installed or unavailable in this environment. "
                "Install via 'pip install laya-mlx' on Apple Silicon macOS, or use "
                "TransformersDecisionEngine for Linux/CUDA environments.",
                cause=exc,
            ) from exc

        try:
            self._agent = laya.load(
                self.checkpoint,
                dtype=self.dtype,
                batch_size=self.batch_size,
                compile=self.compile,
                cache_prompts=self.cache_prompts,
            )
            return self._agent
        except Exception as exc:
            raise DecisionEngineError(
                f"Failed to load Laya checkpoint {self.checkpoint!r}: {exc}",
                cause=exc,
            ) from exc

    def _run_predict_sync(
        self,
        agent: Any,
        state: Any,
        questions: dict[str, dict[str, Any]],
    ) -> dict[str, Any]:
        """Synchronously execute MLX forward pass with shortlisting support.

        Parameters
        ----------
        agent : Any
            Active Laya Agent instance.
        state : Any
            State payload.
        questions : dict of str to dict
            Typed questions payload conforming to Laya API.

        Returns
        -------
        dict
            Laya prediction output dictionary containing answers and action metadata.
        """
        try:
            # Check if any choice question requires shortlist pruning
            has_large_choices = any(
                q.get("type") == "choice"
                and len(q.get("criteria", [])) > self.shortlist_threshold
                for q in questions.values()
            )

            if has_large_choices and self.embed_fn is not None:
                try:
                    from laya_mlx import predict_shortlist

                    return predict_shortlist(
                        agent,
                        state,
                        questions,
                        self.embed_fn,
                        k=self.shortlist_threshold,
                    )
                except (ImportError, AttributeError):
                    pass

            return agent.predict(state, questions)
        except Exception as exc:
            raise DecisionEngineError(
                f"Laya inference forward pass failed: {exc}",
                cause=exc,
            ) from exc

    async def _predict_async(
        self,
        state: Any,
        questions: dict[str, dict[str, Any]],
    ) -> dict[str, Any]:
        """Run MLX prediction asynchronously in worker thread with timeout guard.

        Parameters
        ----------
        state : Any
            State block.
        questions : dict of str to dict
            Questions dictionary.

        Returns
        -------
        dict
            Prediction result.
        """
        agent = self._get_agent()
        try:
            return await asyncio.wait_for(
                asyncio.to_thread(self._run_predict_sync, agent, state, questions),
                timeout=self.timeout_seconds,
            )
        except TimeoutError as exc:
            raise DecisionEngineError(
                f"Laya inference timed out after {self.timeout_seconds} seconds.",
                cause=exc,
            ) from exc

    async def evaluate_noul(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
    ) -> DecisionNoulResult:
        """Evaluate a binary yes/no statement via Laya Noul head.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Binary proposition or verification question.

        Returns
        -------
        DecisionNoulResult
            Evaluation outcome containing calibrated probability and empirical accuracy.
        """
        questions = {
            "noul_q": {
                "type": "noul",
                "instructions": question,
            }
        }
        res = await self._predict_async(state, questions)

        answer_val = res.get("answers", {}).get("noul_q", 0.0)
        probability = float(answer_val)
        act_p = float(res.get("action", {}).get("act_probability", probability))
        passed = probability >= self.default_confidence_threshold

        return DecisionNoulResult(
            probability=probability,
            empirical_accuracy=act_p,
            passed=passed,
        )

    async def evaluate_choice(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        options: list[str] | dict[str, str],
        alpha: float | None = None,
    ) -> DecisionScore:
        """Evaluate a categorical choice via Laya Choice head.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Categorical decision question.
        options : list of str or dict of str to str
            Candidate labels or rubric mapping label to description.
        alpha : float or None, default None
            Significance level for conformal prediction set (1 - alpha coverage).

        Returns
        -------
        DecisionScore
            Score containing selected option, class probability, empirical accuracy,
            and conformal prediction set.
        """
        criteria = options if isinstance(options, (dict, list)) else list(options)
        questions = {
            "choice_q": {
                "type": "choice",
                "instructions": question,
                "criteria": criteria,
            }
        }
        res = await self._predict_async(state, questions)

        raw_answers = res.get("answers", {}).get("choice_q", {})
        if isinstance(raw_answers, dict):
            probabilities = {str(k): float(v) for k, v in raw_answers.items()}
        elif isinstance(raw_answers, str):
            probabilities = {raw_answers: 1.0}
        else:
            probabilities = {}

        if probabilities:
            selected_option = max(probabilities, key=probabilities.get)
            class_probability = probabilities[selected_option]
        else:
            opt_list = list(options.keys()) if isinstance(options, dict) else list(options)
            selected_option = opt_list[0] if opt_list else "UNKNOWN"
            class_probability = 0.5
            probabilities = {selected_option: class_probability}

        act_p = float(res.get("action", {}).get("act_probability", class_probability))
        effective_alpha = alpha if alpha is not None else self.conformal_alpha
        prediction_set = compute_conformal_prediction_set(
            probabilities, alpha=effective_alpha
        )
        tokens_saved = _estimate_tokens_saved(state, question, options)

        return DecisionScore(
            selected_option=selected_option,
            class_probability=class_probability,
            empirical_accuracy=act_p,
            probabilities=probabilities,
            prediction_set=prediction_set,
            tokens_saved_estimate=tokens_saved,
        )

    async def evaluate_score(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        levels: list[int | str],
    ) -> DecisionScore:
        """Evaluate an ordered scale or score via Laya Score head.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Rubric or scoring question.
        levels : list of int or list of str
            Ordered score levels.

        Returns
        -------
        DecisionScore
            Result indicating expected level and distribution.
        """
        questions = {
            "score_q": {
                "type": "score",
                "instructions": question,
                "criteria": [str(lvl) for lvl in levels],
            }
        }
        res = await self._predict_async(state, questions)

        answer_val = res.get("answers", {}).get("score_q")
        if isinstance(answer_val, dict):
            probabilities = {str(k): float(v) for k, v in answer_val.items()}
            selected_option = max(probabilities, key=probabilities.get)
            class_prob = probabilities[selected_option]
        elif isinstance(answer_val, (int, float)):
            idx = min(round(answer_val), len(levels) - 1)
            selected_option = levels[idx]
            class_prob = 0.80
            probabilities = {
                str(lvl): (class_prob if lvl == selected_option else round(0.20 / max(1, len(levels) - 1), 4))
                for lvl in levels
            }
        else:
            selected_option = levels[0] if levels else 1
            class_prob = 0.70
            probabilities = {str(lvl): round(1.0 / max(1, len(levels)), 4) for lvl in levels}

        act_p = float(res.get("action", {}).get("act_probability", class_prob))
        prediction_set = [str(selected_option)]
        tokens_saved = _estimate_tokens_saved(state, question, levels)

        return DecisionScore(
            selected_option=selected_option,
            class_probability=class_prob,
            empirical_accuracy=act_p,
            probabilities=probabilities,
            prediction_set=prediction_set,
            tokens_saved_estimate=tokens_saved,
        )

    async def evaluate(
        self,
        state: str | dict[str, Any] | list[Any],
        question: DecisionQuestion | dict[str, Any],
    ) -> DecisionScore | DecisionNoulResult:
        """Evaluate a single typed question against a state payload.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : DecisionQuestion or dict
            Typed decision question specification or dictionary.

        Returns
        -------
        DecisionScore or DecisionNoulResult
            Evaluation outcome.
        """
        typed_q = ensure_decision_question(question)
        strategy = get_question_strategy(typed_q.type)
        return await strategy.evaluate_single(self, state, typed_q)

    async def evaluate_batch(
        self,
        state: str | dict[str, Any] | list[Any],
        questions: dict[str, DecisionQuestion | dict[str, Any]],
    ) -> dict[str, DecisionScore | DecisionNoulResult]:
        """Evaluate multiple typed questions in a single forward pass.

        Parameters
        ----------
        state : str or dict or list
            State payload.
        questions : dict of str to (DecisionQuestion or dict)
            Dictionary mapping question identifiers to specifications.

        Returns
        -------
        dict of str to (DecisionScore or DecisionNoulResult)
            Mapped results for all evaluated questions.
        """
        typed_questions = {q_id: ensure_decision_question(q_spec) for q_id, q_spec in questions.items()}
        laya_questions = {
            q_id: get_question_strategy(q_item.type).to_laya_spec(q_item)
            for q_id, q_item in typed_questions.items()
        }

        res = await self._predict_async(state, laya_questions)
        answers = res.get("answers", {})
        action_meta = res.get("action", {})
        default_act_p = float(action_meta.get("act_probability", 0.85))

        return {
            q_id: get_question_strategy(q_item.type).decode_laya_answer(
                question=q_item,
                raw_answer=answers.get(q_id),
                default_act_p=default_act_p,
                state=state,
                default_confidence_threshold=self.default_confidence_threshold,
                conformal_alpha=self.conformal_alpha,
            )
            for q_id, q_item in typed_questions.items()
        }

name property

Return the engine name.

evaluate(state, question) async

Evaluate a single typed question against a state payload.

Parameters

state : str or dict or list Structured state payload. question : DecisionQuestion or dict Typed decision question specification or dictionary.

Returns

DecisionScore or DecisionNoulResult Evaluation outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
async def evaluate(
    self,
    state: str | dict[str, Any] | list[Any],
    question: DecisionQuestion | dict[str, Any],
) -> DecisionScore | DecisionNoulResult:
    """Evaluate a single typed question against a state payload.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : DecisionQuestion or dict
        Typed decision question specification or dictionary.

    Returns
    -------
    DecisionScore or DecisionNoulResult
        Evaluation outcome.
    """
    typed_q = ensure_decision_question(question)
    strategy = get_question_strategy(typed_q.type)
    return await strategy.evaluate_single(self, state, typed_q)

evaluate_batch(state, questions) async

Evaluate multiple typed questions in a single forward pass.

Parameters

state : str or dict or list State payload. questions : dict of str to (DecisionQuestion or dict) Dictionary mapping question identifiers to specifications.

Returns

dict of str to (DecisionScore or DecisionNoulResult) Mapped results for all evaluated questions.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
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
async def evaluate_batch(
    self,
    state: str | dict[str, Any] | list[Any],
    questions: dict[str, DecisionQuestion | dict[str, Any]],
) -> dict[str, DecisionScore | DecisionNoulResult]:
    """Evaluate multiple typed questions in a single forward pass.

    Parameters
    ----------
    state : str or dict or list
        State payload.
    questions : dict of str to (DecisionQuestion or dict)
        Dictionary mapping question identifiers to specifications.

    Returns
    -------
    dict of str to (DecisionScore or DecisionNoulResult)
        Mapped results for all evaluated questions.
    """
    typed_questions = {q_id: ensure_decision_question(q_spec) for q_id, q_spec in questions.items()}
    laya_questions = {
        q_id: get_question_strategy(q_item.type).to_laya_spec(q_item)
        for q_id, q_item in typed_questions.items()
    }

    res = await self._predict_async(state, laya_questions)
    answers = res.get("answers", {})
    action_meta = res.get("action", {})
    default_act_p = float(action_meta.get("act_probability", 0.85))

    return {
        q_id: get_question_strategy(q_item.type).decode_laya_answer(
            question=q_item,
            raw_answer=answers.get(q_id),
            default_act_p=default_act_p,
            state=state,
            default_confidence_threshold=self.default_confidence_threshold,
            conformal_alpha=self.conformal_alpha,
        )
        for q_id, q_item in typed_questions.items()
    }

evaluate_choice(state, question, options, alpha=None) async

Evaluate a categorical choice via Laya Choice head.

Parameters

state : str or dict or list Structured state payload. question : str Categorical decision question. options : list of str or dict of str to str Candidate labels or rubric mapping label to description. alpha : float or None, default None Significance level for conformal prediction set (1 - alpha coverage).

Returns

DecisionScore Score containing selected option, class probability, empirical accuracy, and conformal prediction set.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
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
async def evaluate_choice(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    options: list[str] | dict[str, str],
    alpha: float | None = None,
) -> DecisionScore:
    """Evaluate a categorical choice via Laya Choice head.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Categorical decision question.
    options : list of str or dict of str to str
        Candidate labels or rubric mapping label to description.
    alpha : float or None, default None
        Significance level for conformal prediction set (1 - alpha coverage).

    Returns
    -------
    DecisionScore
        Score containing selected option, class probability, empirical accuracy,
        and conformal prediction set.
    """
    criteria = options if isinstance(options, (dict, list)) else list(options)
    questions = {
        "choice_q": {
            "type": "choice",
            "instructions": question,
            "criteria": criteria,
        }
    }
    res = await self._predict_async(state, questions)

    raw_answers = res.get("answers", {}).get("choice_q", {})
    if isinstance(raw_answers, dict):
        probabilities = {str(k): float(v) for k, v in raw_answers.items()}
    elif isinstance(raw_answers, str):
        probabilities = {raw_answers: 1.0}
    else:
        probabilities = {}

    if probabilities:
        selected_option = max(probabilities, key=probabilities.get)
        class_probability = probabilities[selected_option]
    else:
        opt_list = list(options.keys()) if isinstance(options, dict) else list(options)
        selected_option = opt_list[0] if opt_list else "UNKNOWN"
        class_probability = 0.5
        probabilities = {selected_option: class_probability}

    act_p = float(res.get("action", {}).get("act_probability", class_probability))
    effective_alpha = alpha if alpha is not None else self.conformal_alpha
    prediction_set = compute_conformal_prediction_set(
        probabilities, alpha=effective_alpha
    )
    tokens_saved = _estimate_tokens_saved(state, question, options)

    return DecisionScore(
        selected_option=selected_option,
        class_probability=class_probability,
        empirical_accuracy=act_p,
        probabilities=probabilities,
        prediction_set=prediction_set,
        tokens_saved_estimate=tokens_saved,
    )

evaluate_noul(state, question) async

Evaluate a binary yes/no statement via Laya Noul head.

Parameters

state : str or dict or list Structured state payload. question : str Binary proposition or verification question.

Returns

DecisionNoulResult Evaluation outcome containing calibrated probability and empirical accuracy.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
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
async def evaluate_noul(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
) -> DecisionNoulResult:
    """Evaluate a binary yes/no statement via Laya Noul head.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Binary proposition or verification question.

    Returns
    -------
    DecisionNoulResult
        Evaluation outcome containing calibrated probability and empirical accuracy.
    """
    questions = {
        "noul_q": {
            "type": "noul",
            "instructions": question,
        }
    }
    res = await self._predict_async(state, questions)

    answer_val = res.get("answers", {}).get("noul_q", 0.0)
    probability = float(answer_val)
    act_p = float(res.get("action", {}).get("act_probability", probability))
    passed = probability >= self.default_confidence_threshold

    return DecisionNoulResult(
        probability=probability,
        empirical_accuracy=act_p,
        passed=passed,
    )

evaluate_score(state, question, levels) async

Evaluate an ordered scale or score via Laya Score head.

Parameters

state : str or dict or list Structured state payload. question : str Rubric or scoring question. levels : list of int or list of str Ordered score levels.

Returns

DecisionScore Result indicating expected level and distribution.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
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
async def evaluate_score(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    levels: list[int | str],
) -> DecisionScore:
    """Evaluate an ordered scale or score via Laya Score head.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Rubric or scoring question.
    levels : list of int or list of str
        Ordered score levels.

    Returns
    -------
    DecisionScore
        Result indicating expected level and distribution.
    """
    questions = {
        "score_q": {
            "type": "score",
            "instructions": question,
            "criteria": [str(lvl) for lvl in levels],
        }
    }
    res = await self._predict_async(state, questions)

    answer_val = res.get("answers", {}).get("score_q")
    if isinstance(answer_val, dict):
        probabilities = {str(k): float(v) for k, v in answer_val.items()}
        selected_option = max(probabilities, key=probabilities.get)
        class_prob = probabilities[selected_option]
    elif isinstance(answer_val, (int, float)):
        idx = min(round(answer_val), len(levels) - 1)
        selected_option = levels[idx]
        class_prob = 0.80
        probabilities = {
            str(lvl): (class_prob if lvl == selected_option else round(0.20 / max(1, len(levels) - 1), 4))
            for lvl in levels
        }
    else:
        selected_option = levels[0] if levels else 1
        class_prob = 0.70
        probabilities = {str(lvl): round(1.0 / max(1, len(levels)), 4) for lvl in levels}

    act_p = float(res.get("action", {}).get("act_probability", class_prob))
    prediction_set = [str(selected_option)]
    tokens_saved = _estimate_tokens_saved(state, question, levels)

    return DecisionScore(
        selected_option=selected_option,
        class_probability=class_prob,
        empirical_accuracy=act_p,
        probabilities=probabilities,
        prediction_set=prediction_set,
        tokens_saved_estimate=tokens_saved,
    )

fingerprint()

Return a deterministic representation of engine configuration.

Returns

dict of str to Any Deterministic dictionary containing model checkpoint, precision, batch size, inference timeout, calibration thresholds, and flags.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/jev_client.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def fingerprint(self) -> dict[str, Any]:
    """Return a deterministic representation of engine configuration.

    Returns
    -------
    dict of str to Any
        Deterministic dictionary containing model checkpoint, precision,
        batch size, inference timeout, calibration thresholds, and flags.
    """
    return {
        "class": self.__class__.__name__,
        "checkpoint": self.checkpoint,
        "dtype": self.dtype,
        "batch_size": self.batch_size,
        "timeout_seconds": self.timeout_seconds,
        "default_confidence_threshold": self.default_confidence_threshold,
        "conformal_alpha": self.conformal_alpha,
        "shortlist_threshold": self.shortlist_threshold,
        "compile": self.compile,
        "cache_prompts": self.cache_prompts,
    }

MockJevDecisionEngine

In-memory deterministic decision engine used for testing.

In-memory deterministic mock decision engine.

Enables testing pipeline phases and gating logic by matching state/question patterns against pre-registered fixtures, or returning configurable defaults.

Parameters

default_confidence_threshold : float, default 0.85 Default threshold for binary noul decisions. conformal_alpha : float, default 0.05 Default significance error level for conformal prediction sets. simulated_latency : float, default 0.0 Simulated latency in seconds to replicate System 1 inference time.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
 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
class MockJevDecisionEngine:
    """In-memory deterministic mock decision engine.

    Enables testing pipeline phases and gating logic by matching state/question
    patterns against pre-registered fixtures, or returning configurable defaults.

    Parameters
    ----------
    default_confidence_threshold : float, default 0.85
        Default threshold for binary noul decisions.
    conformal_alpha : float, default 0.05
        Default significance error level for conformal prediction sets.
    simulated_latency : float, default 0.0
        Simulated latency in seconds to replicate System 1 inference time.
    """

    def __init__(
        self,
        default_confidence_threshold: float = 0.85,
        conformal_alpha: float = 0.05,
        simulated_latency: float = 0.0,
    ) -> None:
        self.default_confidence_threshold = default_confidence_threshold
        self.conformal_alpha = conformal_alpha
        self.simulated_latency = simulated_latency
        self.calls: list[dict[str, Any]] = []
        self._noul_rules: list[dict[str, Any]] = []
        self._choice_rules: list[dict[str, Any]] = []
        self._score_rules: list[dict[str, Any]] = []
        self.should_raise: Exception | None = None

    @property
    def name(self) -> str:
        """Return the mock engine name."""
        return "MockJevDecisionEngine"

    def fingerprint(self) -> dict[str, Any]:
        """Return a deterministic representation of mock engine configuration.

        Returns
        -------
        dict of str to Any
            Deterministic dictionary containing thresholds, rule counts, and simulated latency.
        """
        return {
            "class": self.__class__.__name__,
            "default_confidence_threshold": self.default_confidence_threshold,
            "conformal_alpha": self.conformal_alpha,
            "simulated_latency": self.simulated_latency,
            "noul_rules_count": len(self._noul_rules),
            "choice_rules_count": len(self._choice_rules),
            "score_rules_count": len(self._score_rules),
        }

    def register_noul_response(
        self,
        question_pattern: str,
        state_pattern: str | None = None,
        probability: float = 0.95,
        empirical_accuracy: float = 0.92,
        passed: bool | None = None,
    ) -> None:
        """Register a fixture response for binary noul questions.

        Parameters
        ----------
        question_pattern : str
            Substring pattern to match against question text (case-insensitive).
        state_pattern : str or None, default None
            Optional substring pattern to match against input state.
        probability : float, default 0.95
            Calibrated proposition probability P(true).
        empirical_accuracy : float, default 0.92
            Calibrated empirical accuracy frequency.
        passed : bool or None, default None
            Explicit boolean flag. If None, derived from probability >= threshold.
        """
        self._noul_rules.append(
            {
                "question_pattern": question_pattern.lower(),
                "state_pattern": state_pattern.lower() if state_pattern else None,
                "probability": probability,
                "empirical_accuracy": empirical_accuracy,
                "passed": passed
                if passed is not None
                else (probability >= self.default_confidence_threshold),
            }
        )

    def register_choice_response(
        self,
        question_pattern: str,
        state_pattern: str | None = None,
        selected_option: str | int | None = None,
        probabilities: dict[str, float] | None = None,
        class_probability: float | None = None,
        empirical_accuracy: float = 0.90,
        prediction_set: list[str] | None = None,
        tokens_saved_estimate: int = 120,
    ) -> None:
        """Register a fixture response for categorical choice questions.

        Parameters
        ----------
        question_pattern : str
            Substring pattern to match against question text (case-insensitive).
        state_pattern : str or None, default None
            Optional substring pattern to match against input state.
        selected_option : str, int, or None, default None
            The winning option to return.
        probabilities : dict of str to float or None, default None
            Categorical probability distribution.
        class_probability : float or None, default None
            Peak softmax probability. If omitted, derived from max(probabilities).
        empirical_accuracy : float, default 0.90
            Calibrated empirical frequency of being correct.
        prediction_set : list of str or None, default None
            Conformal prediction set.
        tokens_saved_estimate : int, default 120
            Estimated LLM tokens saved.
        """
        self._choice_rules.append(
            {
                "question_pattern": question_pattern.lower(),
                "state_pattern": state_pattern.lower() if state_pattern else None,
                "selected_option": selected_option,
                "probabilities": probabilities,
                "class_probability": class_probability,
                "empirical_accuracy": empirical_accuracy,
                "prediction_set": prediction_set,
                "tokens_saved_estimate": tokens_saved_estimate,
            }
        )

    def register_score_response(
        self,
        question_pattern: str,
        state_pattern: str | None = None,
        selected_option: str | int = 1,
        probabilities: dict[str, float] | None = None,
        class_probability: float = 0.85,
        empirical_accuracy: float = 0.88,
        prediction_set: list[str] | None = None,
        tokens_saved_estimate: int = 80,
    ) -> None:
        """Register a fixture response for ordered score questions.

        Parameters
        ----------
        question_pattern : str
            Substring pattern to match against question text.
        state_pattern : str or None, default None
            Optional substring pattern to match against input state.
        selected_option : str or int, default 1
            Expected or selected score level.
        probabilities : dict of str to float or None, default None
            Distribution over levels.
        class_probability : float, default 0.85
            Confidence in the selected level.
        empirical_accuracy : float, default 0.88
            Empirical accuracy estimate.
        prediction_set : list of str or None, default None
            Conformal prediction set over levels.
        tokens_saved_estimate : int, default 80
            Estimated LLM tokens saved.
        """
        self._score_rules.append(
            {
                "question_pattern": question_pattern.lower(),
                "state_pattern": state_pattern.lower() if state_pattern else None,
                "selected_option": selected_option,
                "probabilities": probabilities or {},
                "class_probability": class_probability,
                "empirical_accuracy": empirical_accuracy,
                "prediction_set": prediction_set,
                "tokens_saved_estimate": tokens_saved_estimate,
            }
        )

    def set_simulated_latency(self, latency: float) -> None:
        """Set simulated execution latency in seconds.

        Parameters
        ----------
        latency : float
            Latency duration in seconds.
        """
        self.simulated_latency = max(0.0, latency)

    def reset(self) -> None:
        """Clear all registered fixture rules and call history."""
        self.calls.clear()
        self._noul_rules.clear()
        self._choice_rules.clear()
        self._score_rules.clear()
        self.should_raise = None

    async def evaluate_noul(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
    ) -> DecisionNoulResult:
        """Evaluate a binary yes/no statement.

        Parameters
        ----------
        state : str or dict or list
            Input state block.
        question : str
            Binary proposition or question.

        Returns
        -------
        DecisionNoulResult
            Evaluation result.

        Raises
        ------
        Exception
            If ``should_raise`` is configured.
        """
        if self.should_raise is not None:
            raise self.should_raise

        if self.simulated_latency > 0.0:
            await asyncio.sleep(self.simulated_latency)

        state_str = str(state).lower()
        q_str = question.lower()

        matched_rule = None
        for rule in reversed(self._noul_rules):
            if rule["question_pattern"] in q_str:
                if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                    matched_rule = rule
                    break

        if matched_rule is not None:
            prob = matched_rule["probability"]
            emp_acc = matched_rule["empirical_accuracy"]
            passed = matched_rule["passed"]
        else:
            prob = 0.90
            emp_acc = 0.88
            passed = prob >= self.default_confidence_threshold

        res = DecisionNoulResult(
            probability=prob,
            empirical_accuracy=emp_acc,
            passed=passed,
        )

        self.calls.append(
            {
                "method": "evaluate_noul",
                "state": state,
                "question": question,
                "result": res,
            }
        )
        return res

    async def evaluate_choice(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        options: list[str] | dict[str, str],
        alpha: float | None = None,
    ) -> DecisionScore:
        """Evaluate a categorical choice over options.

        Parameters
        ----------
        state : str or dict or list
            Input state block.
        question : str
            Categorical decision question.
        options : list of str or dict of str to str
            Available options.
        alpha : float or None, default None
            Significance level for conformal prediction set.

        Returns
        -------
        DecisionScore
            Categorical evaluation score.

        Raises
        ------
        Exception
            If ``should_raise`` is configured.
        """
        if self.should_raise is not None:
            raise self.should_raise

        if self.simulated_latency > 0.0:
            await asyncio.sleep(self.simulated_latency)

        state_str = str(state).lower()
        q_str = question.lower()
        effective_alpha = alpha if alpha is not None else self.conformal_alpha

        opt_list = list(options.keys()) if isinstance(options, dict) else list(options)
        fallback_option = opt_list[0] if opt_list else "UNKNOWN"

        matched_rule = None
        for rule in reversed(self._choice_rules):
            if rule["question_pattern"] in q_str:
                if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                    matched_rule = rule
                    break

        if matched_rule is not None:
            selected = matched_rule["selected_option"] or fallback_option
            probs = matched_rule["probabilities"]
            if probs is None:
                probs = {selected: 0.88}
                for opt in opt_list:
                    if opt != selected:
                        probs[opt] = round(0.12 / max(1, len(opt_list) - 1), 4)

            class_prob = matched_rule["class_probability"] or probs.get(selected, 0.88)
            emp_acc = matched_rule["empirical_accuracy"]
            pred_set = matched_rule["prediction_set"]
            if pred_set is None:
                pred_set = compute_conformal_prediction_set(probs, alpha=effective_alpha)
            tokens_saved = matched_rule["tokens_saved_estimate"]
        else:
            selected = fallback_option
            probs = {selected: 0.85}
            rem = 0.15
            other_opts = [opt for opt in opt_list if opt != selected]
            for opt in other_opts:
                probs[opt] = round(rem / len(other_opts), 4)
            class_prob = 0.85
            emp_acc = 0.88
            pred_set = compute_conformal_prediction_set(probs, alpha=effective_alpha)
            tokens_saved = (len(str(state)) // 4) + (len(question) // 4) + (len(opt_list) * 8) + 50

        res = DecisionScore(
            selected_option=selected,
            class_probability=class_prob,
            empirical_accuracy=emp_acc,
            probabilities=probs,
            prediction_set=pred_set,
            tokens_saved_estimate=tokens_saved,
        )

        self.calls.append(
            {
                "method": "evaluate_choice",
                "state": state,
                "question": question,
                "options": options,
                "alpha": alpha,
                "result": res,
            }
        )
        return res

    async def evaluate_score(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        levels: list[int | str],
    ) -> DecisionScore:
        """Evaluate an ordered scale or score against levels.

        Parameters
        ----------
        state : str or dict or list
            Input state block.
        question : str
            Scoring rubric question.
        levels : list of int or list of str
            Ordered levels.

        Returns
        -------
        DecisionScore
            Evaluation score indicating expected level and probabilities.

        Raises
        ------
        Exception
            If ``should_raise`` is configured.
        """
        if self.should_raise is not None:
            raise self.should_raise

        if self.simulated_latency > 0.0:
            await asyncio.sleep(self.simulated_latency)

        state_str = str(state).lower()
        q_str = question.lower()
        fallback_level = levels[0] if levels else 1

        matched_rule = None
        for rule in reversed(self._score_rules):
            if rule["question_pattern"] in q_str:
                if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                    matched_rule = rule
                    break

        if matched_rule is not None:
            selected = matched_rule["selected_option"]
            probs = matched_rule["probabilities"]
            class_prob = matched_rule["class_probability"]
            emp_acc = matched_rule["empirical_accuracy"]
            pred_set = matched_rule["prediction_set"]
            tokens_saved = matched_rule["tokens_saved_estimate"]
        else:
            selected = fallback_level
            probs = {str(lvl): (0.75 if lvl == selected else round(0.25 / max(1, len(levels) - 1), 4)) for lvl in levels}
            class_prob = 0.75
            emp_acc = 0.80
            pred_set = [str(selected)]
            tokens_saved = (len(str(state)) // 4) + (len(question) // 4) + 40

        res = DecisionScore(
            selected_option=selected,
            class_probability=class_prob,
            empirical_accuracy=emp_acc,
            probabilities=probs,
            prediction_set=pred_set,
            tokens_saved_estimate=tokens_saved,
        )

        self.calls.append(
            {
                "method": "evaluate_score",
                "state": state,
                "question": question,
                "levels": levels,
                "result": res,
            }
        )
        return res

    async def evaluate(
        self,
        state: str | dict[str, Any] | list[Any],
        question: DecisionQuestion | dict[str, Any],
    ) -> DecisionScore | DecisionNoulResult:
        """Evaluate a single typed question against state.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : DecisionQuestion or dict
            Typed decision question specification or dictionary.

        Returns
        -------
        DecisionScore or DecisionNoulResult
            Evaluation outcome.
        """
        typed_q = ensure_decision_question(question)
        strategy = get_question_strategy(typed_q.type)
        return await strategy.evaluate_single(self, state, typed_q)

    async def evaluate_batch(
        self,
        state: str | dict[str, Any] | list[Any],
        questions: dict[str, DecisionQuestion | dict[str, Any]],
    ) -> dict[str, DecisionScore | DecisionNoulResult]:
        """Evaluate a batch of questions against a single state block in parallel.

        Parameters
        ----------
        state : str or dict or list
            Structured state block.
        questions : dict of str to (DecisionQuestion or dict)
            Mapping from key to question definition specification or dictionary.

        Returns
        -------
        dict of str to (DecisionScore or DecisionNoulResult)
            Mapping from question key to corresponding result.
        """
        return await evaluate_questions_sequentially(self, state, questions)

name property

Return the mock engine name.

evaluate(state, question) async

Evaluate a single typed question against state.

Parameters

state : str or dict or list Structured state payload. question : DecisionQuestion or dict Typed decision question specification or dictionary.

Returns

DecisionScore or DecisionNoulResult Evaluation outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
async def evaluate(
    self,
    state: str | dict[str, Any] | list[Any],
    question: DecisionQuestion | dict[str, Any],
) -> DecisionScore | DecisionNoulResult:
    """Evaluate a single typed question against state.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : DecisionQuestion or dict
        Typed decision question specification or dictionary.

    Returns
    -------
    DecisionScore or DecisionNoulResult
        Evaluation outcome.
    """
    typed_q = ensure_decision_question(question)
    strategy = get_question_strategy(typed_q.type)
    return await strategy.evaluate_single(self, state, typed_q)

evaluate_batch(state, questions) async

Evaluate a batch of questions against a single state block in parallel.

Parameters

state : str or dict or list Structured state block. questions : dict of str to (DecisionQuestion or dict) Mapping from key to question definition specification or dictionary.

Returns

dict of str to (DecisionScore or DecisionNoulResult) Mapping from question key to corresponding result.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
async def evaluate_batch(
    self,
    state: str | dict[str, Any] | list[Any],
    questions: dict[str, DecisionQuestion | dict[str, Any]],
) -> dict[str, DecisionScore | DecisionNoulResult]:
    """Evaluate a batch of questions against a single state block in parallel.

    Parameters
    ----------
    state : str or dict or list
        Structured state block.
    questions : dict of str to (DecisionQuestion or dict)
        Mapping from key to question definition specification or dictionary.

    Returns
    -------
    dict of str to (DecisionScore or DecisionNoulResult)
        Mapping from question key to corresponding result.
    """
    return await evaluate_questions_sequentially(self, state, questions)

evaluate_choice(state, question, options, alpha=None) async

Evaluate a categorical choice over options.

Parameters

state : str or dict or list Input state block. question : str Categorical decision question. options : list of str or dict of str to str Available options. alpha : float or None, default None Significance level for conformal prediction set.

Returns

DecisionScore Categorical evaluation score.

Raises

Exception If should_raise is configured.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
async def evaluate_choice(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    options: list[str] | dict[str, str],
    alpha: float | None = None,
) -> DecisionScore:
    """Evaluate a categorical choice over options.

    Parameters
    ----------
    state : str or dict or list
        Input state block.
    question : str
        Categorical decision question.
    options : list of str or dict of str to str
        Available options.
    alpha : float or None, default None
        Significance level for conformal prediction set.

    Returns
    -------
    DecisionScore
        Categorical evaluation score.

    Raises
    ------
    Exception
        If ``should_raise`` is configured.
    """
    if self.should_raise is not None:
        raise self.should_raise

    if self.simulated_latency > 0.0:
        await asyncio.sleep(self.simulated_latency)

    state_str = str(state).lower()
    q_str = question.lower()
    effective_alpha = alpha if alpha is not None else self.conformal_alpha

    opt_list = list(options.keys()) if isinstance(options, dict) else list(options)
    fallback_option = opt_list[0] if opt_list else "UNKNOWN"

    matched_rule = None
    for rule in reversed(self._choice_rules):
        if rule["question_pattern"] in q_str:
            if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                matched_rule = rule
                break

    if matched_rule is not None:
        selected = matched_rule["selected_option"] or fallback_option
        probs = matched_rule["probabilities"]
        if probs is None:
            probs = {selected: 0.88}
            for opt in opt_list:
                if opt != selected:
                    probs[opt] = round(0.12 / max(1, len(opt_list) - 1), 4)

        class_prob = matched_rule["class_probability"] or probs.get(selected, 0.88)
        emp_acc = matched_rule["empirical_accuracy"]
        pred_set = matched_rule["prediction_set"]
        if pred_set is None:
            pred_set = compute_conformal_prediction_set(probs, alpha=effective_alpha)
        tokens_saved = matched_rule["tokens_saved_estimate"]
    else:
        selected = fallback_option
        probs = {selected: 0.85}
        rem = 0.15
        other_opts = [opt for opt in opt_list if opt != selected]
        for opt in other_opts:
            probs[opt] = round(rem / len(other_opts), 4)
        class_prob = 0.85
        emp_acc = 0.88
        pred_set = compute_conformal_prediction_set(probs, alpha=effective_alpha)
        tokens_saved = (len(str(state)) // 4) + (len(question) // 4) + (len(opt_list) * 8) + 50

    res = DecisionScore(
        selected_option=selected,
        class_probability=class_prob,
        empirical_accuracy=emp_acc,
        probabilities=probs,
        prediction_set=pred_set,
        tokens_saved_estimate=tokens_saved,
    )

    self.calls.append(
        {
            "method": "evaluate_choice",
            "state": state,
            "question": question,
            "options": options,
            "alpha": alpha,
            "result": res,
        }
    )
    return res

evaluate_noul(state, question) async

Evaluate a binary yes/no statement.

Parameters

state : str or dict or list Input state block. question : str Binary proposition or question.

Returns

DecisionNoulResult Evaluation result.

Raises

Exception If should_raise is configured.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
async def evaluate_noul(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
) -> DecisionNoulResult:
    """Evaluate a binary yes/no statement.

    Parameters
    ----------
    state : str or dict or list
        Input state block.
    question : str
        Binary proposition or question.

    Returns
    -------
    DecisionNoulResult
        Evaluation result.

    Raises
    ------
    Exception
        If ``should_raise`` is configured.
    """
    if self.should_raise is not None:
        raise self.should_raise

    if self.simulated_latency > 0.0:
        await asyncio.sleep(self.simulated_latency)

    state_str = str(state).lower()
    q_str = question.lower()

    matched_rule = None
    for rule in reversed(self._noul_rules):
        if rule["question_pattern"] in q_str:
            if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                matched_rule = rule
                break

    if matched_rule is not None:
        prob = matched_rule["probability"]
        emp_acc = matched_rule["empirical_accuracy"]
        passed = matched_rule["passed"]
    else:
        prob = 0.90
        emp_acc = 0.88
        passed = prob >= self.default_confidence_threshold

    res = DecisionNoulResult(
        probability=prob,
        empirical_accuracy=emp_acc,
        passed=passed,
    )

    self.calls.append(
        {
            "method": "evaluate_noul",
            "state": state,
            "question": question,
            "result": res,
        }
    )
    return res

evaluate_score(state, question, levels) async

Evaluate an ordered scale or score against levels.

Parameters

state : str or dict or list Input state block. question : str Scoring rubric question. levels : list of int or list of str Ordered levels.

Returns

DecisionScore Evaluation score indicating expected level and probabilities.

Raises

Exception If should_raise is configured.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
async def evaluate_score(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    levels: list[int | str],
) -> DecisionScore:
    """Evaluate an ordered scale or score against levels.

    Parameters
    ----------
    state : str or dict or list
        Input state block.
    question : str
        Scoring rubric question.
    levels : list of int or list of str
        Ordered levels.

    Returns
    -------
    DecisionScore
        Evaluation score indicating expected level and probabilities.

    Raises
    ------
    Exception
        If ``should_raise`` is configured.
    """
    if self.should_raise is not None:
        raise self.should_raise

    if self.simulated_latency > 0.0:
        await asyncio.sleep(self.simulated_latency)

    state_str = str(state).lower()
    q_str = question.lower()
    fallback_level = levels[0] if levels else 1

    matched_rule = None
    for rule in reversed(self._score_rules):
        if rule["question_pattern"] in q_str:
            if rule["state_pattern"] is None or rule["state_pattern"] in state_str:
                matched_rule = rule
                break

    if matched_rule is not None:
        selected = matched_rule["selected_option"]
        probs = matched_rule["probabilities"]
        class_prob = matched_rule["class_probability"]
        emp_acc = matched_rule["empirical_accuracy"]
        pred_set = matched_rule["prediction_set"]
        tokens_saved = matched_rule["tokens_saved_estimate"]
    else:
        selected = fallback_level
        probs = {str(lvl): (0.75 if lvl == selected else round(0.25 / max(1, len(levels) - 1), 4)) for lvl in levels}
        class_prob = 0.75
        emp_acc = 0.80
        pred_set = [str(selected)]
        tokens_saved = (len(str(state)) // 4) + (len(question) // 4) + 40

    res = DecisionScore(
        selected_option=selected,
        class_probability=class_prob,
        empirical_accuracy=emp_acc,
        probabilities=probs,
        prediction_set=pred_set,
        tokens_saved_estimate=tokens_saved,
    )

    self.calls.append(
        {
            "method": "evaluate_score",
            "state": state,
            "question": question,
            "levels": levels,
            "result": res,
        }
    )
    return res

fingerprint()

Return a deterministic representation of mock engine configuration.

Returns

dict of str to Any Deterministic dictionary containing thresholds, rule counts, and simulated latency.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def fingerprint(self) -> dict[str, Any]:
    """Return a deterministic representation of mock engine configuration.

    Returns
    -------
    dict of str to Any
        Deterministic dictionary containing thresholds, rule counts, and simulated latency.
    """
    return {
        "class": self.__class__.__name__,
        "default_confidence_threshold": self.default_confidence_threshold,
        "conformal_alpha": self.conformal_alpha,
        "simulated_latency": self.simulated_latency,
        "noul_rules_count": len(self._noul_rules),
        "choice_rules_count": len(self._choice_rules),
        "score_rules_count": len(self._score_rules),
    }

register_choice_response(question_pattern, state_pattern=None, selected_option=None, probabilities=None, class_probability=None, empirical_accuracy=0.9, prediction_set=None, tokens_saved_estimate=120)

Register a fixture response for categorical choice questions.

Parameters

question_pattern : str Substring pattern to match against question text (case-insensitive). state_pattern : str or None, default None Optional substring pattern to match against input state. selected_option : str, int, or None, default None The winning option to return. probabilities : dict of str to float or None, default None Categorical probability distribution. class_probability : float or None, default None Peak softmax probability. If omitted, derived from max(probabilities). empirical_accuracy : float, default 0.90 Calibrated empirical frequency of being correct. prediction_set : list of str or None, default None Conformal prediction set. tokens_saved_estimate : int, default 120 Estimated LLM tokens saved.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
def register_choice_response(
    self,
    question_pattern: str,
    state_pattern: str | None = None,
    selected_option: str | int | None = None,
    probabilities: dict[str, float] | None = None,
    class_probability: float | None = None,
    empirical_accuracy: float = 0.90,
    prediction_set: list[str] | None = None,
    tokens_saved_estimate: int = 120,
) -> None:
    """Register a fixture response for categorical choice questions.

    Parameters
    ----------
    question_pattern : str
        Substring pattern to match against question text (case-insensitive).
    state_pattern : str or None, default None
        Optional substring pattern to match against input state.
    selected_option : str, int, or None, default None
        The winning option to return.
    probabilities : dict of str to float or None, default None
        Categorical probability distribution.
    class_probability : float or None, default None
        Peak softmax probability. If omitted, derived from max(probabilities).
    empirical_accuracy : float, default 0.90
        Calibrated empirical frequency of being correct.
    prediction_set : list of str or None, default None
        Conformal prediction set.
    tokens_saved_estimate : int, default 120
        Estimated LLM tokens saved.
    """
    self._choice_rules.append(
        {
            "question_pattern": question_pattern.lower(),
            "state_pattern": state_pattern.lower() if state_pattern else None,
            "selected_option": selected_option,
            "probabilities": probabilities,
            "class_probability": class_probability,
            "empirical_accuracy": empirical_accuracy,
            "prediction_set": prediction_set,
            "tokens_saved_estimate": tokens_saved_estimate,
        }
    )

register_noul_response(question_pattern, state_pattern=None, probability=0.95, empirical_accuracy=0.92, passed=None)

Register a fixture response for binary noul questions.

Parameters

question_pattern : str Substring pattern to match against question text (case-insensitive). state_pattern : str or None, default None Optional substring pattern to match against input state. probability : float, default 0.95 Calibrated proposition probability P(true). empirical_accuracy : float, default 0.92 Calibrated empirical accuracy frequency. passed : bool or None, default None Explicit boolean flag. If None, derived from probability >= threshold.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
def register_noul_response(
    self,
    question_pattern: str,
    state_pattern: str | None = None,
    probability: float = 0.95,
    empirical_accuracy: float = 0.92,
    passed: bool | None = None,
) -> None:
    """Register a fixture response for binary noul questions.

    Parameters
    ----------
    question_pattern : str
        Substring pattern to match against question text (case-insensitive).
    state_pattern : str or None, default None
        Optional substring pattern to match against input state.
    probability : float, default 0.95
        Calibrated proposition probability P(true).
    empirical_accuracy : float, default 0.92
        Calibrated empirical accuracy frequency.
    passed : bool or None, default None
        Explicit boolean flag. If None, derived from probability >= threshold.
    """
    self._noul_rules.append(
        {
            "question_pattern": question_pattern.lower(),
            "state_pattern": state_pattern.lower() if state_pattern else None,
            "probability": probability,
            "empirical_accuracy": empirical_accuracy,
            "passed": passed
            if passed is not None
            else (probability >= self.default_confidence_threshold),
        }
    )

register_score_response(question_pattern, state_pattern=None, selected_option=1, probabilities=None, class_probability=0.85, empirical_accuracy=0.88, prediction_set=None, tokens_saved_estimate=80)

Register a fixture response for ordered score questions.

Parameters

question_pattern : str Substring pattern to match against question text. state_pattern : str or None, default None Optional substring pattern to match against input state. selected_option : str or int, default 1 Expected or selected score level. probabilities : dict of str to float or None, default None Distribution over levels. class_probability : float, default 0.85 Confidence in the selected level. empirical_accuracy : float, default 0.88 Empirical accuracy estimate. prediction_set : list of str or None, default None Conformal prediction set over levels. tokens_saved_estimate : int, default 80 Estimated LLM tokens saved.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
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
def register_score_response(
    self,
    question_pattern: str,
    state_pattern: str | None = None,
    selected_option: str | int = 1,
    probabilities: dict[str, float] | None = None,
    class_probability: float = 0.85,
    empirical_accuracy: float = 0.88,
    prediction_set: list[str] | None = None,
    tokens_saved_estimate: int = 80,
) -> None:
    """Register a fixture response for ordered score questions.

    Parameters
    ----------
    question_pattern : str
        Substring pattern to match against question text.
    state_pattern : str or None, default None
        Optional substring pattern to match against input state.
    selected_option : str or int, default 1
        Expected or selected score level.
    probabilities : dict of str to float or None, default None
        Distribution over levels.
    class_probability : float, default 0.85
        Confidence in the selected level.
    empirical_accuracy : float, default 0.88
        Empirical accuracy estimate.
    prediction_set : list of str or None, default None
        Conformal prediction set over levels.
    tokens_saved_estimate : int, default 80
        Estimated LLM tokens saved.
    """
    self._score_rules.append(
        {
            "question_pattern": question_pattern.lower(),
            "state_pattern": state_pattern.lower() if state_pattern else None,
            "selected_option": selected_option,
            "probabilities": probabilities or {},
            "class_probability": class_probability,
            "empirical_accuracy": empirical_accuracy,
            "prediction_set": prediction_set,
            "tokens_saved_estimate": tokens_saved_estimate,
        }
    )

reset()

Clear all registered fixture rules and call history.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
257
258
259
260
261
262
263
def reset(self) -> None:
    """Clear all registered fixture rules and call history."""
    self.calls.clear()
    self._noul_rules.clear()
    self._choice_rules.clear()
    self._score_rules.clear()
    self.should_raise = None

set_simulated_latency(latency)

Set simulated execution latency in seconds.

Parameters

latency : float Latency duration in seconds.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/mock.py
247
248
249
250
251
252
253
254
255
def set_simulated_latency(self, latency: float) -> None:
    """Set simulated execution latency in seconds.

    Parameters
    ----------
    latency : float
        Latency duration in seconds.
    """
    self.simulated_latency = max(0.0, latency)

ObservableDecisionEngine

Decorator adding decision audit/observability on top of an underlying decision engine.

Decorates a :class:~episteme_pipeline.protocols.decision.DecisionEngine to emit domain events.

Parameters

inner : DecisionEngine Underlying decision engine instance to decorate. engine_name : str or None, default None Human-readable name of the decision engine. If omitted, derived from the inner engine's attributes or class name. prompt_bundle : StructuredPromptBundle or None, default None Optional prompt bundle carrying prompt_name, prompt_version, and prompt_label for telemetry prompt binding. stochastic_audit_rate : float, default 0.0 Probability in [0, 1] of randomly marking a fast-exit evaluation for stochastic auditing (System 2 validation).

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
 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
class ObservableDecisionEngine:
    """Decorates a :class:`~episteme_pipeline.protocols.decision.DecisionEngine` to emit domain events.

    Parameters
    ----------
    inner : DecisionEngine
        Underlying decision engine instance to decorate.
    engine_name : str or None, default None
        Human-readable name of the decision engine. If omitted, derived from
        the inner engine's attributes or class name.
    prompt_bundle : StructuredPromptBundle or None, default None
        Optional prompt bundle carrying prompt_name, prompt_version, and
        prompt_label for telemetry prompt binding.
    stochastic_audit_rate : float, default 0.0
        Probability in [0, 1] of randomly marking a fast-exit evaluation for
        stochastic auditing (System 2 validation).
    """

    def __init__(
        self,
        inner: DecisionEngine,
        engine_name: str | None = None,
        prompt_bundle: StructuredPromptBundle | None = None,
        stochastic_audit_rate: float = 0.0,
    ) -> None:
        self.inner = inner
        self.engine_name = engine_name or inner.name
        self.prompt_bundle = prompt_bundle
        self.stochastic_audit_rate = stochastic_audit_rate

    @property
    def name(self) -> str:
        """Return the engine name."""
        return self.engine_name

    def fingerprint(self) -> dict[str, Any]:
        """Return a deterministic representation of the observable wrapper and wrapped engine.

        Returns
        -------
        dict of str to Any
            Deterministic dictionary containing wrapper metadata, audit rate,
            and inner engine fingerprint.
        """
        inner_fp = (
            self.inner.fingerprint()
            if hasattr(self.inner, "fingerprint") and callable(self.inner.fingerprint)
            else {"class": self.inner.__class__.__name__}
        )
        return {
            "class": self.__class__.__name__,
            "engine_name": self.engine_name,
            "stochastic_audit_rate": self.stochastic_audit_rate,
            "inner": inner_fp,
        }

    @staticmethod
    def _compute_state_hash(state: Any) -> tuple[str, int]:
        """Compute stable SHA-256 hash and character count of the input state.

        Parameters
        ----------
        state : Any
            The input state block (string, dict, or list).

        Returns
        -------
        tuple of (str, int)
            Hex-encoded SHA-256 digest and character length.
        """
        state_str = str(state)
        state_hash = hashlib.sha256(state_str.encode("utf-8")).hexdigest()
        return state_hash, len(state_str)

    def _should_audit(self) -> bool:
        """Determine whether the current evaluation should be marked for stochastic audit.

        Returns
        -------
        bool
            True if random sample falls within stochastic_audit_rate.
        """
        if self.stochastic_audit_rate <= 0.0:
            return False
        return random.random() < self.stochastic_audit_rate

    async def evaluate_noul(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
    ) -> DecisionNoulResult:
        """Evaluate a binary yes/no statement with latency and event tracking.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Binary proposition or decision question to evaluate.

        Returns
        -------
        DecisionNoulResult
            Evaluation outcome containing calibrated probability and empirical
            accuracy.
        """
        state_hash, char_count = self._compute_state_hash(state)
        emitter = get_event_emitter()

        try:
            emitter.emit(
                DecisionEvaluationStarted(
                    engine_name=self.engine_name,
                    primitive="noul",
                    question=question,
                    state_hash=state_hash,
                    state_character_count=char_count,
                )
            )
        except Exception:
            pass

        t0 = time.perf_counter()
        result = await self.inner.evaluate_noul(state, question)
        duration = time.perf_counter() - t0

        is_audit = self._should_audit()
        tokens_saved = result.tokens_saved_estimate if isinstance(result, DecisionScore) else 0
        if not tokens_saved:
            tokens_saved = (char_count // 4) + (len(question) // 4) + 30

        try:
            emitter.emit(
                DecisionEvaluationCompleted(
                    engine_name=self.engine_name,
                    primitive="noul",
                    question=question,
                    prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                    prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                    prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                    selected_value=result.passed,
                    class_probability=result.probability,
                    empirical_accuracy=result.empirical_accuracy,
                    probabilities={
                        "true": result.probability,
                        "false": max(0.0, 1.0 - result.probability),
                    },
                    prediction_set=None,
                    is_stochastic_audit=is_audit,
                    duration_seconds=duration,
                    tokens_saved_estimate=tokens_saved,
                )
            )
        except Exception:
            pass

        return result

    async def evaluate_choice(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        options: list[str] | dict[str, str],
        alpha: float | None = None,
    ) -> DecisionScore:
        """Evaluate a categorical choice with latency and event tracking.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Categorical decision question.
        options : list of str or dict of str to str
            Allowed options or dictionary mapping option labels to rubric definitions.
        alpha : float or None, default None
            Optional significance level for conformal prediction set (1 - alpha coverage).

        Returns
        -------
        DecisionScore
            Categorical evaluation score containing selected option, class
            probability, full probability distribution, and conformal prediction set.
        """
        state_hash, char_count = self._compute_state_hash(state)
        emitter = get_event_emitter()

        try:
            emitter.emit(
                DecisionEvaluationStarted(
                    engine_name=self.engine_name,
                    primitive="choice",
                    question=question,
                    state_hash=state_hash,
                    state_character_count=char_count,
                )
            )
        except Exception:
            pass

        t0 = time.perf_counter()
        result = await self.inner.evaluate_choice(state, question, options, alpha=alpha)
        duration = time.perf_counter() - t0

        is_audit = self._should_audit()
        tokens_saved = result.tokens_saved_estimate or (
            (char_count // 4) + (len(question) // 4) + (len(options) * 8) + 50
        )

        try:
            emitter.emit(
                DecisionEvaluationCompleted(
                    engine_name=self.engine_name,
                    primitive="choice",
                    question=question,
                    prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                    prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                    prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                    selected_value=str(result.selected_option),
                    class_probability=result.class_probability,
                    empirical_accuracy=result.empirical_accuracy,
                    probabilities=result.probabilities,
                    prediction_set=result.prediction_set,
                    is_stochastic_audit=is_audit,
                    duration_seconds=duration,
                    tokens_saved_estimate=tokens_saved,
                )
            )
        except Exception:
            pass

        return result

    async def evaluate_score(
        self,
        state: str | dict[str, Any] | list[Any],
        question: str,
        levels: list[int | str],
    ) -> DecisionScore:
        """Evaluate an ordered scale or score with latency and event tracking.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : str
            Scoring question or grading rubric.
        levels : list of int or list of str
            Ordered scale levels.

        Returns
        -------
        DecisionScore
            Evaluation score indicating expected level and level probabilities.
        """
        state_hash, char_count = self._compute_state_hash(state)
        emitter = get_event_emitter()

        try:
            emitter.emit(
                DecisionEvaluationStarted(
                    engine_name=self.engine_name,
                    primitive="score",
                    question=question,
                    state_hash=state_hash,
                    state_character_count=char_count,
                )
            )
        except Exception:
            pass

        t0 = time.perf_counter()
        result = await self.inner.evaluate_score(state, question, levels)
        duration = time.perf_counter() - t0

        is_audit = self._should_audit()
        tokens_saved = result.tokens_saved_estimate or (
            (char_count // 4) + (len(question) // 4) + (len(levels) * 4) + 40
        )

        try:
            emitter.emit(
                DecisionEvaluationCompleted(
                    engine_name=self.engine_name,
                    primitive="score",
                    question=question,
                    prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                    prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                    prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                    selected_value=result.selected_option,
                    class_probability=result.class_probability,
                    empirical_accuracy=result.empirical_accuracy,
                    probabilities=result.probabilities,
                    prediction_set=result.prediction_set,
                    is_stochastic_audit=is_audit,
                    duration_seconds=duration,
                    tokens_saved_estimate=tokens_saved,
                )
            )
        except Exception:
            pass

        return result

    async def evaluate(
        self,
        state: str | dict[str, Any] | list[Any],
        question: DecisionQuestion | dict[str, Any],
    ) -> DecisionScore | DecisionNoulResult:
        """Evaluate a single typed question with telemetry instrumentation.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        question : DecisionQuestion or dict
            Typed decision question specification or dictionary.

        Returns
        -------
        DecisionScore or DecisionNoulResult
            Evaluation outcome.
        """
        typed_q = ensure_decision_question(question)
        strategy = get_question_strategy(typed_q.type)
        return await strategy.evaluate_single(self, state, typed_q)

    async def evaluate_batch(
        self,
        state: str | dict[str, Any] | list[Any],
        questions: dict[str, DecisionQuestion | dict[str, Any]],
    ) -> dict[str, DecisionScore | DecisionNoulResult]:
        """Evaluate multiple questions in batch via the inner decision engine.

        Parameters
        ----------
        state : str or dict or list
            Structured state payload.
        questions : dict of str to (DecisionQuestion or dict)
            Question specifications.

        Returns
        -------
        dict of str to (DecisionScore or DecisionNoulResult)
            Batch evaluation results.
        """
        if hasattr(self.inner, "evaluate_batch"):
            return await self.inner.evaluate_batch(state, questions)
        return await evaluate_questions_sequentially(self, state, questions)

    def __getattr__(self, name: str) -> Any:
        """Delegate unhandled attribute and method lookups to the inner engine."""
        return getattr(self.inner, name)

name property

Return the engine name.

__getattr__(name)

Delegate unhandled attribute and method lookups to the inner engine.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
386
387
388
def __getattr__(self, name: str) -> Any:
    """Delegate unhandled attribute and method lookups to the inner engine."""
    return getattr(self.inner, name)

evaluate(state, question) async

Evaluate a single typed question with telemetry instrumentation.

Parameters

state : str or dict or list Structured state payload. question : DecisionQuestion or dict Typed decision question specification or dictionary.

Returns

DecisionScore or DecisionNoulResult Evaluation outcome.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
async def evaluate(
    self,
    state: str | dict[str, Any] | list[Any],
    question: DecisionQuestion | dict[str, Any],
) -> DecisionScore | DecisionNoulResult:
    """Evaluate a single typed question with telemetry instrumentation.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : DecisionQuestion or dict
        Typed decision question specification or dictionary.

    Returns
    -------
    DecisionScore or DecisionNoulResult
        Evaluation outcome.
    """
    typed_q = ensure_decision_question(question)
    strategy = get_question_strategy(typed_q.type)
    return await strategy.evaluate_single(self, state, typed_q)

evaluate_batch(state, questions) async

Evaluate multiple questions in batch via the inner decision engine.

Parameters

state : str or dict or list Structured state payload. questions : dict of str to (DecisionQuestion or dict) Question specifications.

Returns

dict of str to (DecisionScore or DecisionNoulResult) Batch evaluation results.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
async def evaluate_batch(
    self,
    state: str | dict[str, Any] | list[Any],
    questions: dict[str, DecisionQuestion | dict[str, Any]],
) -> dict[str, DecisionScore | DecisionNoulResult]:
    """Evaluate multiple questions in batch via the inner decision engine.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    questions : dict of str to (DecisionQuestion or dict)
        Question specifications.

    Returns
    -------
    dict of str to (DecisionScore or DecisionNoulResult)
        Batch evaluation results.
    """
    if hasattr(self.inner, "evaluate_batch"):
        return await self.inner.evaluate_batch(state, questions)
    return await evaluate_questions_sequentially(self, state, questions)

evaluate_choice(state, question, options, alpha=None) async

Evaluate a categorical choice with latency and event tracking.

Parameters

state : str or dict or list Structured state payload. question : str Categorical decision question. options : list of str or dict of str to str Allowed options or dictionary mapping option labels to rubric definitions. alpha : float or None, default None Optional significance level for conformal prediction set (1 - alpha coverage).

Returns

DecisionScore Categorical evaluation score containing selected option, class probability, full probability distribution, and conformal prediction set.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
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
async def evaluate_choice(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    options: list[str] | dict[str, str],
    alpha: float | None = None,
) -> DecisionScore:
    """Evaluate a categorical choice with latency and event tracking.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Categorical decision question.
    options : list of str or dict of str to str
        Allowed options or dictionary mapping option labels to rubric definitions.
    alpha : float or None, default None
        Optional significance level for conformal prediction set (1 - alpha coverage).

    Returns
    -------
    DecisionScore
        Categorical evaluation score containing selected option, class
        probability, full probability distribution, and conformal prediction set.
    """
    state_hash, char_count = self._compute_state_hash(state)
    emitter = get_event_emitter()

    try:
        emitter.emit(
            DecisionEvaluationStarted(
                engine_name=self.engine_name,
                primitive="choice",
                question=question,
                state_hash=state_hash,
                state_character_count=char_count,
            )
        )
    except Exception:
        pass

    t0 = time.perf_counter()
    result = await self.inner.evaluate_choice(state, question, options, alpha=alpha)
    duration = time.perf_counter() - t0

    is_audit = self._should_audit()
    tokens_saved = result.tokens_saved_estimate or (
        (char_count // 4) + (len(question) // 4) + (len(options) * 8) + 50
    )

    try:
        emitter.emit(
            DecisionEvaluationCompleted(
                engine_name=self.engine_name,
                primitive="choice",
                question=question,
                prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                selected_value=str(result.selected_option),
                class_probability=result.class_probability,
                empirical_accuracy=result.empirical_accuracy,
                probabilities=result.probabilities,
                prediction_set=result.prediction_set,
                is_stochastic_audit=is_audit,
                duration_seconds=duration,
                tokens_saved_estimate=tokens_saved,
            )
        )
    except Exception:
        pass

    return result

evaluate_noul(state, question) async

Evaluate a binary yes/no statement with latency and event tracking.

Parameters

state : str or dict or list Structured state payload. question : str Binary proposition or decision question to evaluate.

Returns

DecisionNoulResult Evaluation outcome containing calibrated probability and empirical accuracy.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
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
async def evaluate_noul(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
) -> DecisionNoulResult:
    """Evaluate a binary yes/no statement with latency and event tracking.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Binary proposition or decision question to evaluate.

    Returns
    -------
    DecisionNoulResult
        Evaluation outcome containing calibrated probability and empirical
        accuracy.
    """
    state_hash, char_count = self._compute_state_hash(state)
    emitter = get_event_emitter()

    try:
        emitter.emit(
            DecisionEvaluationStarted(
                engine_name=self.engine_name,
                primitive="noul",
                question=question,
                state_hash=state_hash,
                state_character_count=char_count,
            )
        )
    except Exception:
        pass

    t0 = time.perf_counter()
    result = await self.inner.evaluate_noul(state, question)
    duration = time.perf_counter() - t0

    is_audit = self._should_audit()
    tokens_saved = result.tokens_saved_estimate if isinstance(result, DecisionScore) else 0
    if not tokens_saved:
        tokens_saved = (char_count // 4) + (len(question) // 4) + 30

    try:
        emitter.emit(
            DecisionEvaluationCompleted(
                engine_name=self.engine_name,
                primitive="noul",
                question=question,
                prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                selected_value=result.passed,
                class_probability=result.probability,
                empirical_accuracy=result.empirical_accuracy,
                probabilities={
                    "true": result.probability,
                    "false": max(0.0, 1.0 - result.probability),
                },
                prediction_set=None,
                is_stochastic_audit=is_audit,
                duration_seconds=duration,
                tokens_saved_estimate=tokens_saved,
            )
        )
    except Exception:
        pass

    return result

evaluate_score(state, question, levels) async

Evaluate an ordered scale or score with latency and event tracking.

Parameters

state : str or dict or list Structured state payload. question : str Scoring question or grading rubric. levels : list of int or list of str Ordered scale levels.

Returns

DecisionScore Evaluation score indicating expected level and level probabilities.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
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
async def evaluate_score(
    self,
    state: str | dict[str, Any] | list[Any],
    question: str,
    levels: list[int | str],
) -> DecisionScore:
    """Evaluate an ordered scale or score with latency and event tracking.

    Parameters
    ----------
    state : str or dict or list
        Structured state payload.
    question : str
        Scoring question or grading rubric.
    levels : list of int or list of str
        Ordered scale levels.

    Returns
    -------
    DecisionScore
        Evaluation score indicating expected level and level probabilities.
    """
    state_hash, char_count = self._compute_state_hash(state)
    emitter = get_event_emitter()

    try:
        emitter.emit(
            DecisionEvaluationStarted(
                engine_name=self.engine_name,
                primitive="score",
                question=question,
                state_hash=state_hash,
                state_character_count=char_count,
            )
        )
    except Exception:
        pass

    t0 = time.perf_counter()
    result = await self.inner.evaluate_score(state, question, levels)
    duration = time.perf_counter() - t0

    is_audit = self._should_audit()
    tokens_saved = result.tokens_saved_estimate or (
        (char_count // 4) + (len(question) // 4) + (len(levels) * 4) + 40
    )

    try:
        emitter.emit(
            DecisionEvaluationCompleted(
                engine_name=self.engine_name,
                primitive="score",
                question=question,
                prompt_name=self.prompt_bundle.name if self.prompt_bundle else None,
                prompt_version=self.prompt_bundle.version if self.prompt_bundle else None,
                prompt_label=self.prompt_bundle.label if self.prompt_bundle else None,
                selected_value=result.selected_option,
                class_probability=result.class_probability,
                empirical_accuracy=result.empirical_accuracy,
                probabilities=result.probabilities,
                prediction_set=result.prediction_set,
                is_stochastic_audit=is_audit,
                duration_seconds=duration,
                tokens_saved_estimate=tokens_saved,
            )
        )
    except Exception:
        pass

    return result

fingerprint()

Return a deterministic representation of the observable wrapper and wrapped engine.

Returns

dict of str to Any Deterministic dictionary containing wrapper metadata, audit rate, and inner engine fingerprint.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/observable.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def fingerprint(self) -> dict[str, Any]:
    """Return a deterministic representation of the observable wrapper and wrapped engine.

    Returns
    -------
    dict of str to Any
        Deterministic dictionary containing wrapper metadata, audit rate,
        and inner engine fingerprint.
    """
    inner_fp = (
        self.inner.fingerprint()
        if hasattr(self.inner, "fingerprint") and callable(self.inner.fingerprint)
        else {"class": self.inner.__class__.__name__}
    )
    return {
        "class": self.__class__.__name__,
        "engine_name": self.engine_name,
        "stochastic_audit_rate": self.stochastic_audit_rate,
        "inner": inner_fp,
    }

Modal resolvers fuse modality evidence, capturing fusion mode, fusion \(\alpha\), epistemic status priors, and underlying decision engine instances.

StructuralistModalResolver

Symbolic modal strength resolver grounded in Schurz's structuralist philosophy.

Evaluates the authorial propositional modality M(phi) deterministically from structuralist syntax attributes (ScopeType, EpistemicStatus, ComponentType).

Parameters

default_base_score : float, default 0.60 Fallback modal certainty when no structuralist dimensions match.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
 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
class StructuralistModalResolver:
    """Symbolic modal strength resolver grounded in Schurz's structuralist philosophy.

    Evaluates the authorial propositional modality M(phi) deterministically from
    structuralist syntax attributes (ScopeType, EpistemicStatus, ComponentType).

    Parameters
    ----------
    default_base_score : float, default 0.60
        Fallback modal certainty when no structuralist dimensions match.
    """

    def __init__(self, default_base_score: float = 0.60) -> None:
        self.default_base_score = default_base_score

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic structuralist modal resolver configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier and default base score.
        """
        return {
            "class": self.__class__.__name__,
            "default_base_score": self.default_base_score,
        }

    def _classify_component(self, comp: str) -> str:
        """Classify component type string into coarse epistemological category.

        Parameters
        ----------
        comp : str
            Sanitized component type string.

        Returns
        -------
        str
            Category: 'axiomatic', 'empirical', 'theoretical', 'speculative', or 'unknown'.
        """
        if any(k in comp for k in ("AXIOM", "LAW", "DEFINITION")):
            return "axiomatic"
        if any(k in comp for k in ("OBSERVATION", "EMPIRICAL")):
            return "empirical"
        if "THEORETICAL" in comp or "HYPOTHESIS" in comp:
            return "theoretical"
        if any(k in comp for k in ("CONJECTURE", "SPECULATION")):
            return "speculative"
        return "unknown"

    def _extract_syntax(
        self, atom: TheoryAtom
    ) -> tuple[ScopeType | None, str, EpistemicStatus | None]:
        """Extract and normalize structuralist syntax attributes from an atom.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.

        Returns
        -------
        tuple of (ScopeType or None, str, EpistemicStatus or None)
            Canonical scope enum, component category, and epistemic status enum.
        """
        comp_raw = (atom.component_type or "").upper().replace(" ", "_").replace("-", "_")
        return (
            ScopeType.from_str(atom.scope_type),
            self._classify_component(comp_raw),
            EpistemicStatus.from_str(atom.epistemic_status),
        )

    def evaluate_syntax_profile(self, atom: TheoryAtom) -> ModalSyntaxProfile:
        """Derive deterministic modal score and guardrail interval from atom syntax.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.

        Returns
        -------
        ModalSyntaxProfile
            Evaluated score and guardrail interval bounds.
        """
        scope, comp_kind, status = self._extract_syntax(atom)

        # Unified pattern matching switch across ScopeType, ComponentKind, and EpistemicStatus
        match (scope, comp_kind, status):
            # 1. Structuralist ScopeType hierarchy (Schurz 2014)
            case (ScopeType.ESSENTIELLER_ALLSATZ, _, EpistemicStatus.ANALYTISCH):
                return ModalSyntaxProfile(score=1.00, bounds=(0.85, 1.00))
            case (ScopeType.ESSENTIELLER_ALLSATZ, _, _):
                return ModalSyntaxProfile(score=0.90, bounds=(0.75, 1.00))
            case (ScopeType.LOKALISIERTER_ALLSATZ, _, _):
                return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
            case (ScopeType.LOKALISIERTER_EXISTENZSATZ, _, _):
                return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
            case (ScopeType.STATISTISCHER_ALLSATZ, _, _):
                return ModalSyntaxProfile(score=0.75, bounds=(0.55, 0.85))
            case (ScopeType.EXISTENZSATZ, _, _):
                return ModalSyntaxProfile(score=0.55, bounds=(0.35, 0.70))

            # 2. ComponentType and EpistemicStatus fallback
            case (_, "axiomatic", _):
                return ModalSyntaxProfile(score=1.00, bounds=(0.85, 1.00))
            case (_, "empirical", _):
                return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
            case (_, "theoretical", EpistemicStatus.ANALYTISCH):
                return ModalSyntaxProfile(score=0.75, bounds=(0.60, 0.85))
            case (_, "theoretical", _):
                return ModalSyntaxProfile(score=0.60, bounds=(0.40, 0.80))
            case (_, "speculative", _):
                return ModalSyntaxProfile(score=0.35, bounds=(0.10, 0.50))

            # 3. Default fallback
            case _:
                return ModalSyntaxProfile(score=self.default_base_score, bounds=(0.30, 0.85))

    def get_syntax_bounds(self, atom: TheoryAtom) -> tuple[float, float]:
        """Compute admissible modal certainty interval [M_min, M_max] for guardrail clipping.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.

        Returns
        -------
        tuple of (float, float)
            Lower and upper bounds for authorial propositional certainty in [0.0, 1.0].
        """
        return self.evaluate_syntax_profile(atom).bounds

    def resolve_modality_sync(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Synchronously derive deterministic modal certainty from structuralist syntax.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Ignored for purely symbolic syntactic evaluation.

        Returns
        -------
        float
            Propositional modal strength M(phi) in [0.0, 1.0].
        """
        return self.evaluate_syntax_profile(atom).score

    async def resolve_modality(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Asynchronously derive deterministic modal certainty (delegates to sync).

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Ignored for symbolic evaluation.

        Returns
        -------
        float
            Propositional modal strength M(phi) in [0.0, 1.0].
        """
        return self.resolve_modality_sync(atom, context)

evaluate_syntax_profile(atom)

Derive deterministic modal score and guardrail interval from atom syntax.

Parameters

atom : TheoryAtom Target theoretical atom.

Returns

ModalSyntaxProfile Evaluated score and guardrail interval bounds.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
def evaluate_syntax_profile(self, atom: TheoryAtom) -> ModalSyntaxProfile:
    """Derive deterministic modal score and guardrail interval from atom syntax.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.

    Returns
    -------
    ModalSyntaxProfile
        Evaluated score and guardrail interval bounds.
    """
    scope, comp_kind, status = self._extract_syntax(atom)

    # Unified pattern matching switch across ScopeType, ComponentKind, and EpistemicStatus
    match (scope, comp_kind, status):
        # 1. Structuralist ScopeType hierarchy (Schurz 2014)
        case (ScopeType.ESSENTIELLER_ALLSATZ, _, EpistemicStatus.ANALYTISCH):
            return ModalSyntaxProfile(score=1.00, bounds=(0.85, 1.00))
        case (ScopeType.ESSENTIELLER_ALLSATZ, _, _):
            return ModalSyntaxProfile(score=0.90, bounds=(0.75, 1.00))
        case (ScopeType.LOKALISIERTER_ALLSATZ, _, _):
            return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
        case (ScopeType.LOKALISIERTER_EXISTENZSATZ, _, _):
            return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
        case (ScopeType.STATISTISCHER_ALLSATZ, _, _):
            return ModalSyntaxProfile(score=0.75, bounds=(0.55, 0.85))
        case (ScopeType.EXISTENZSATZ, _, _):
            return ModalSyntaxProfile(score=0.55, bounds=(0.35, 0.70))

        # 2. ComponentType and EpistemicStatus fallback
        case (_, "axiomatic", _):
            return ModalSyntaxProfile(score=1.00, bounds=(0.85, 1.00))
        case (_, "empirical", _):
            return ModalSyntaxProfile(score=0.85, bounds=(0.70, 0.95))
        case (_, "theoretical", EpistemicStatus.ANALYTISCH):
            return ModalSyntaxProfile(score=0.75, bounds=(0.60, 0.85))
        case (_, "theoretical", _):
            return ModalSyntaxProfile(score=0.60, bounds=(0.40, 0.80))
        case (_, "speculative", _):
            return ModalSyntaxProfile(score=0.35, bounds=(0.10, 0.50))

        # 3. Default fallback
        case _:
            return ModalSyntaxProfile(score=self.default_base_score, bounds=(0.30, 0.85))

fingerprint()

Return deterministic structuralist modal resolver configuration.

Returns

dict of str to Any Dictionary containing class identifier and default base score.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
60
61
62
63
64
65
66
67
68
69
70
71
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic structuralist modal resolver configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier and default base score.
    """
    return {
        "class": self.__class__.__name__,
        "default_base_score": self.default_base_score,
    }

get_syntax_bounds(atom)

Compute admissible modal certainty interval [M_min, M_max] for guardrail clipping.

Parameters

atom : TheoryAtom Target theoretical atom.

Returns

tuple of (float, float) Lower and upper bounds for authorial propositional certainty in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def get_syntax_bounds(self, atom: TheoryAtom) -> tuple[float, float]:
    """Compute admissible modal certainty interval [M_min, M_max] for guardrail clipping.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.

    Returns
    -------
    tuple of (float, float)
        Lower and upper bounds for authorial propositional certainty in [0.0, 1.0].
    """
    return self.evaluate_syntax_profile(atom).bounds

resolve_modality(atom, context=None) async

Asynchronously derive deterministic modal certainty (delegates to sync).

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Ignored for symbolic evaluation.

Returns

float Propositional modal strength M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
async def resolve_modality(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Asynchronously derive deterministic modal certainty (delegates to sync).

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Ignored for symbolic evaluation.

    Returns
    -------
    float
        Propositional modal strength M(phi) in [0.0, 1.0].
    """
    return self.resolve_modality_sync(atom, context)

resolve_modality_sync(atom, context=None)

Synchronously derive deterministic modal certainty from structuralist syntax.

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Ignored for purely symbolic syntactic evaluation.

Returns

float Propositional modal strength M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
def resolve_modality_sync(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Synchronously derive deterministic modal certainty from structuralist syntax.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Ignored for purely symbolic syntactic evaluation.

    Returns
    -------
    float
        Propositional modal strength M(phi) in [0.0, 1.0].
    """
    return self.evaluate_syntax_profile(atom).score

DecisionEngineModalResolver

Empirical modal strength resolver backed by a System 1 DecisionEngine.

Evaluates linguistic hedging, modal auxiliaries, and assertiveness directly on the claim and surrounding sentence context.

Parameters

decision_engine : DecisionEngine System 1 calibrated decision engine. question_template : str, default "Assess the author's propositional certainty / modal qualification for this claim." Evaluative prompt question for the decision engine. levels : list of float, optional Ordinal certainty levels in [0.0, 1.0]. Defaults to [0.2, 0.4, 0.6, 0.8, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
class DecisionEngineModalResolver:
    """Empirical modal strength resolver backed by a System 1 DecisionEngine.

    Evaluates linguistic hedging, modal auxiliaries, and assertiveness directly
    on the claim and surrounding sentence context.

    Parameters
    ----------
    decision_engine : DecisionEngine
        System 1 calibrated decision engine.
    question_template : str, default "Assess the author's propositional certainty / modal qualification for this claim."
        Evaluative prompt question for the decision engine.
    levels : list of float, optional
        Ordinal certainty levels in [0.0, 1.0]. Defaults to [0.2, 0.4, 0.6, 0.8, 1.0].
    """

    def __init__(
        self,
        decision_engine: DecisionEngine,
        question_template: str = "Assess the author's propositional certainty / modal qualification for this claim.",
        levels: list[float] | None = None,
    ) -> None:
        self.decision_engine = decision_engine
        self.question_template = question_template
        self.levels = levels or [0.2, 0.4, 0.6, 0.8, 1.0]
        self._fallback_resolver = StructuralistModalResolver()

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic decision engine modal resolver configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing class identifier, question template, levels,
            and underlying decision engine fingerprint.
        """
        eng_fp = (
            self.decision_engine.fingerprint()
            if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
            else {"class": self.decision_engine.__class__.__name__}
        )
        return {
            "class": self.__class__.__name__,
            "question_template": self.question_template,
            "levels": list(self.levels),
            "decision_engine": eng_fp,
        }

    async def resolve_modality(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Evaluate linguistic hedging via System 1 DecisionEngine.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Surrounding context text.

        Returns
        -------
        float
            Calibrated expected propositional modal strength M(phi) in [0.0, 1.0].
        """
        claim_text = atom.text or ""
        state_str = f"Claim: {claim_text}\nContext:\n{context or claim_text}"

        level_options = {f"Level_{i}": f"Certainty {lvl:.2f}" for i, lvl in enumerate(self.levels)}
        try:
            score: DecisionScore = await self.decision_engine.evaluate_choice(
                state=state_str,
                question=self.question_template,
                options=level_options,
            )

            # Compute expected value over probability distribution if available
            probs = score.probabilities or {}
            if probs:
                expected_m = 0.0
                total_p = 0.0
                for i, lvl in enumerate(self.levels):
                    opt_key = f"Level_{i}"
                    p = probs.get(opt_key, 0.0)
                    expected_m += lvl * p
                    total_p += p
                if total_p > 0:
                    return float(max(0.0, min(1.0, expected_m / total_p)))

            # Fall back to selected option index
            sel = str(score.selected_option)
            for i, lvl in enumerate(self.levels):
                if f"Level_{i}" in sel:
                    return lvl

            return float(score.class_probability) if score.class_probability is not None else 0.60
        except Exception as e:
            logger.warning("DecisionEngineModalResolver failed (%s); falling back to syntax", e)
            return self._fallback_resolver.resolve_modality_sync(atom, context)

    def resolve_modality_sync(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Synchronous fallback delegating to structuralist syntax.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Textual context.

        Returns
        -------
        float
            Fallback modal strength M(phi) in [0.0, 1.0].
        """
        return self._fallback_resolver.resolve_modality_sync(atom, context)

fingerprint()

Return deterministic decision engine modal resolver configuration.

Returns

dict of str to Any Dictionary containing class identifier, question template, levels, and underlying decision engine fingerprint.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic decision engine modal resolver configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing class identifier, question template, levels,
        and underlying decision engine fingerprint.
    """
    eng_fp = (
        self.decision_engine.fingerprint()
        if hasattr(self.decision_engine, "fingerprint") and callable(self.decision_engine.fingerprint)
        else {"class": self.decision_engine.__class__.__name__}
    )
    return {
        "class": self.__class__.__name__,
        "question_template": self.question_template,
        "levels": list(self.levels),
        "decision_engine": eng_fp,
    }

resolve_modality(atom, context=None) async

Evaluate linguistic hedging via System 1 DecisionEngine.

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Surrounding context text.

Returns

float Calibrated expected propositional modal strength M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
async def resolve_modality(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Evaluate linguistic hedging via System 1 DecisionEngine.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Surrounding context text.

    Returns
    -------
    float
        Calibrated expected propositional modal strength M(phi) in [0.0, 1.0].
    """
    claim_text = atom.text or ""
    state_str = f"Claim: {claim_text}\nContext:\n{context or claim_text}"

    level_options = {f"Level_{i}": f"Certainty {lvl:.2f}" for i, lvl in enumerate(self.levels)}
    try:
        score: DecisionScore = await self.decision_engine.evaluate_choice(
            state=state_str,
            question=self.question_template,
            options=level_options,
        )

        # Compute expected value over probability distribution if available
        probs = score.probabilities or {}
        if probs:
            expected_m = 0.0
            total_p = 0.0
            for i, lvl in enumerate(self.levels):
                opt_key = f"Level_{i}"
                p = probs.get(opt_key, 0.0)
                expected_m += lvl * p
                total_p += p
            if total_p > 0:
                return float(max(0.0, min(1.0, expected_m / total_p)))

        # Fall back to selected option index
        sel = str(score.selected_option)
        for i, lvl in enumerate(self.levels):
            if f"Level_{i}" in sel:
                return lvl

        return float(score.class_probability) if score.class_probability is not None else 0.60
    except Exception as e:
        logger.warning("DecisionEngineModalResolver failed (%s); falling back to syntax", e)
        return self._fallback_resolver.resolve_modality_sync(atom, context)

resolve_modality_sync(atom, context=None)

Synchronous fallback delegating to structuralist syntax.

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Textual context.

Returns

float Fallback modal strength M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def resolve_modality_sync(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Synchronous fallback delegating to structuralist syntax.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Textual context.

    Returns
    -------
    float
        Fallback modal strength M(phi) in [0.0, 1.0].
    """
    return self._fallback_resolver.resolve_modality_sync(atom, context)

HybridModalResolver

Neuro-symbolic hybrid modal strength resolver.

Harmonizes symbolic structuralist properties (ScopeType, EpistemicStatus) with calibrated linguistic assertiveness scoring from the System 1 DecisionEngine.

Parameters

structural_resolver : StructuralistModalResolver or None, optional Symbolic resolver instance. If None, initialized with default settings. decision_resolver : DecisionEngineModalResolver or None, optional Empirical decision engine resolver. If None, runs in pure structuralist mode. mode : Literal["guardrail", "convex", "structural_only", "engine_only"], default "guardrail" Integration mode: - "guardrail": Clips decision engine score into structuralist syntax bounds. - "convex": Computes weighted average between structural prior and engine score. - "structural_only": Strictly evaluates structuralist syntax. - "engine_only": Strictly evaluates decision engine score. fusion_alpha : float, default 0.50 Relative weight of structuralist syntax in convex fusion mode (in [0.0, 1.0]).

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
class HybridModalResolver:
    """Neuro-symbolic hybrid modal strength resolver.

    Harmonizes symbolic structuralist properties (ScopeType, EpistemicStatus) with
    calibrated linguistic assertiveness scoring from the System 1 DecisionEngine.

    Parameters
    ----------
    structural_resolver : StructuralistModalResolver or None, optional
        Symbolic resolver instance. If None, initialized with default settings.
    decision_resolver : DecisionEngineModalResolver or None, optional
        Empirical decision engine resolver. If None, runs in pure structuralist mode.
    mode : Literal["guardrail", "convex", "structural_only", "engine_only"], default "guardrail"
        Integration mode:
        - "guardrail": Clips decision engine score into structuralist syntax bounds.
        - "convex": Computes weighted average between structural prior and engine score.
        - "structural_only": Strictly evaluates structuralist syntax.
        - "engine_only": Strictly evaluates decision engine score.
    fusion_alpha : float, default 0.50
        Relative weight of structuralist syntax in convex fusion mode (in [0.0, 1.0]).
    """

    def __init__(
        self,
        structural_resolver: StructuralistModalResolver | None = None,
        decision_resolver: DecisionEngineModalResolver | None = None,
        mode: Literal["guardrail", "convex", "structural_only", "engine_only"] = "guardrail",
        fusion_alpha: float = 0.50,
    ) -> None:
        self.structural_resolver = structural_resolver or StructuralistModalResolver()
        self.decision_resolver = decision_resolver
        self.mode = mode
        self.fusion_alpha = max(0.0, min(1.0, fusion_alpha))

    def fingerprint(self) -> dict[str, Any]:
        """Return deterministic hybrid modal resolver configuration.

        Returns
        -------
        dict of str to Any
            Dictionary containing mode, fusion alpha, and component resolver fingerprints.
        """
        return {
            "class": self.__class__.__name__,
            "mode": self.mode,
            "fusion_alpha": self.fusion_alpha,
            "structural_resolver": (
                self.structural_resolver.fingerprint()
                if hasattr(self.structural_resolver, "fingerprint") and callable(self.structural_resolver.fingerprint)
                else {"class": self.structural_resolver.__class__.__name__}
            ),
            "decision_resolver": (
                self.decision_resolver.fingerprint()
                if self.decision_resolver and hasattr(self.decision_resolver, "fingerprint") and callable(self.decision_resolver.fingerprint)
                else None
            ),
        }

    @classmethod
    def create(
        cls,
        config: ModalResolverConfig | dict[str, Any] | None = None,
        decision_engine: DecisionEngine | None = None,
        structural_resolver: StructuralistModalResolver | None = None,
        decision_resolver: DecisionEngineModalResolver | None = None,
    ) -> HybridModalResolver:
        """Construct a fully configured HybridModalResolver from config and dependencies.

        Parameters
        ----------
        config : ModalResolverConfig or dict or None, optional
            Modal resolver configuration. If None or empty, default settings are used.
        decision_engine : DecisionEngine or None, optional
            Calibrated System 1 decision engine. If provided and decision_resolver is None,
            constructs DecisionEngineModalResolver automatically.
        structural_resolver : StructuralistModalResolver or None, optional
            Custom structuralist resolver. If None, initialized using config.default_base_score.
        decision_resolver : DecisionEngineModalResolver or None, optional
            Custom decision resolver. If None and decision_engine is provided, constructed automatically.

        Returns
        -------
        HybridModalResolver
            Configured neuro-symbolic hybrid modal strength resolver.
        """
        from episteme_pipeline.config import ModalResolverConfig

        if isinstance(config, dict):
            cfg_dict = config.get("modal_resolver", config)
            cfg = ModalResolverConfig.model_validate(cfg_dict) if isinstance(cfg_dict, dict) else ModalResolverConfig()
        elif isinstance(config, ModalResolverConfig):
            cfg = config
        else:
            cfg = ModalResolverConfig()

        structural = structural_resolver or StructuralistModalResolver(
            default_base_score=cfg.default_base_score
        )
        dec_res = decision_resolver or (
            DecisionEngineModalResolver(decision_engine) if decision_engine is not None else None
        )
        mode = cfg.mode if dec_res is not None else "structural_only"

        return cls(
            structural_resolver=structural,
            decision_resolver=dec_res,
            mode=mode,
            fusion_alpha=cfg.fusion_alpha,
        )

    async def resolve_modality(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Resolve propositional modal strength with event emission and observability.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Surrounding context text.

        Returns
        -------
        float
            Resolved modal certainty M(phi) in [0.0, 1.0].
        """
        syntax_profile = self.structural_resolver.evaluate_syntax_profile(atom)
        syntax_score = syntax_profile.score
        raw_engine_score: float | None = None
        clamped = False

        if self.mode == "structural_only" or self.decision_resolver is None:
            final_score = syntax_score
            resolver_type = "structural"
        elif self.mode == "engine_only":
            raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
            final_score = raw_engine_score
            resolver_type = "decision_engine"
        elif self.mode == "convex":
            raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
            final_score = (self.fusion_alpha * syntax_score) + ((1.0 - self.fusion_alpha) * raw_engine_score)
            resolver_type = "hybrid_convex"
        else:
            # Mode "guardrail": evaluate engine score and clamp within structural bounds
            raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
            bounds = syntax_profile.bounds
            clamped_score = max(bounds[0], min(bounds[1], raw_engine_score))
            clamped = clamped_score != raw_engine_score
            final_score = clamped_score
            resolver_type = "hybrid_guardrail"

        final_score = float(max(0.0, min(1.0, final_score)))

        # Emit observability domain event
        try:
            emitter = get_event_emitter()
            emitter.emit(
                ModalStrengthResolved(
                    atom_id=atom.id,
                    modal_strength=final_score,
                    resolver_type=resolver_type,
                    scope_type=atom.scope_type,
                    epistemic_status=atom.epistemic_status,
                    raw_engine_score=raw_engine_score,
                    clamped=clamped,
                )
            )
        except Exception as e:
            logger.debug("Failed to emit ModalStrengthResolved event: %s", e)

        logger.debug(
            "Resolved modality for atom %s (%s, %s): %.3f [mode=%s, raw=%.3f, clamped=%s]",
            atom.id,
            atom.scope_type,
            atom.epistemic_status,
            final_score,
            self.mode,
            raw_engine_score or 0.0,
            clamped,
        )
        return final_score

    def resolve_modality_sync(
        self,
        atom: TheoryAtom,
        context: str | None = None,
    ) -> float:
        """Synchronously resolve propositional modal strength via structuralist fallback.

        Parameters
        ----------
        atom : TheoryAtom
            Target theoretical atom.
        context : str or None, optional
            Surrounding context text.

        Returns
        -------
        float
            Resolved modal certainty M(phi) in [0.0, 1.0].
        """
        return self.structural_resolver.resolve_modality_sync(atom, context)

create(config=None, decision_engine=None, structural_resolver=None, decision_resolver=None) classmethod

Construct a fully configured HybridModalResolver from config and dependencies.

Parameters

config : ModalResolverConfig or dict or None, optional Modal resolver configuration. If None or empty, default settings are used. decision_engine : DecisionEngine or None, optional Calibrated System 1 decision engine. If provided and decision_resolver is None, constructs DecisionEngineModalResolver automatically. structural_resolver : StructuralistModalResolver or None, optional Custom structuralist resolver. If None, initialized using config.default_base_score. decision_resolver : DecisionEngineModalResolver or None, optional Custom decision resolver. If None and decision_engine is provided, constructed automatically.

Returns

HybridModalResolver Configured neuro-symbolic hybrid modal strength resolver.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
@classmethod
def create(
    cls,
    config: ModalResolverConfig | dict[str, Any] | None = None,
    decision_engine: DecisionEngine | None = None,
    structural_resolver: StructuralistModalResolver | None = None,
    decision_resolver: DecisionEngineModalResolver | None = None,
) -> HybridModalResolver:
    """Construct a fully configured HybridModalResolver from config and dependencies.

    Parameters
    ----------
    config : ModalResolverConfig or dict or None, optional
        Modal resolver configuration. If None or empty, default settings are used.
    decision_engine : DecisionEngine or None, optional
        Calibrated System 1 decision engine. If provided and decision_resolver is None,
        constructs DecisionEngineModalResolver automatically.
    structural_resolver : StructuralistModalResolver or None, optional
        Custom structuralist resolver. If None, initialized using config.default_base_score.
    decision_resolver : DecisionEngineModalResolver or None, optional
        Custom decision resolver. If None and decision_engine is provided, constructed automatically.

    Returns
    -------
    HybridModalResolver
        Configured neuro-symbolic hybrid modal strength resolver.
    """
    from episteme_pipeline.config import ModalResolverConfig

    if isinstance(config, dict):
        cfg_dict = config.get("modal_resolver", config)
        cfg = ModalResolverConfig.model_validate(cfg_dict) if isinstance(cfg_dict, dict) else ModalResolverConfig()
    elif isinstance(config, ModalResolverConfig):
        cfg = config
    else:
        cfg = ModalResolverConfig()

    structural = structural_resolver or StructuralistModalResolver(
        default_base_score=cfg.default_base_score
    )
    dec_res = decision_resolver or (
        DecisionEngineModalResolver(decision_engine) if decision_engine is not None else None
    )
    mode = cfg.mode if dec_res is not None else "structural_only"

    return cls(
        structural_resolver=structural,
        decision_resolver=dec_res,
        mode=mode,
        fusion_alpha=cfg.fusion_alpha,
    )

fingerprint()

Return deterministic hybrid modal resolver configuration.

Returns

dict of str to Any Dictionary containing mode, fusion alpha, and component resolver fingerprints.

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def fingerprint(self) -> dict[str, Any]:
    """Return deterministic hybrid modal resolver configuration.

    Returns
    -------
    dict of str to Any
        Dictionary containing mode, fusion alpha, and component resolver fingerprints.
    """
    return {
        "class": self.__class__.__name__,
        "mode": self.mode,
        "fusion_alpha": self.fusion_alpha,
        "structural_resolver": (
            self.structural_resolver.fingerprint()
            if hasattr(self.structural_resolver, "fingerprint") and callable(self.structural_resolver.fingerprint)
            else {"class": self.structural_resolver.__class__.__name__}
        ),
        "decision_resolver": (
            self.decision_resolver.fingerprint()
            if self.decision_resolver and hasattr(self.decision_resolver, "fingerprint") and callable(self.decision_resolver.fingerprint)
            else None
        ),
    }

resolve_modality(atom, context=None) async

Resolve propositional modal strength with event emission and observability.

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Surrounding context text.

Returns

float Resolved modal certainty M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
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
async def resolve_modality(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Resolve propositional modal strength with event emission and observability.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Surrounding context text.

    Returns
    -------
    float
        Resolved modal certainty M(phi) in [0.0, 1.0].
    """
    syntax_profile = self.structural_resolver.evaluate_syntax_profile(atom)
    syntax_score = syntax_profile.score
    raw_engine_score: float | None = None
    clamped = False

    if self.mode == "structural_only" or self.decision_resolver is None:
        final_score = syntax_score
        resolver_type = "structural"
    elif self.mode == "engine_only":
        raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
        final_score = raw_engine_score
        resolver_type = "decision_engine"
    elif self.mode == "convex":
        raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
        final_score = (self.fusion_alpha * syntax_score) + ((1.0 - self.fusion_alpha) * raw_engine_score)
        resolver_type = "hybrid_convex"
    else:
        # Mode "guardrail": evaluate engine score and clamp within structural bounds
        raw_engine_score = await self.decision_resolver.resolve_modality(atom, context)
        bounds = syntax_profile.bounds
        clamped_score = max(bounds[0], min(bounds[1], raw_engine_score))
        clamped = clamped_score != raw_engine_score
        final_score = clamped_score
        resolver_type = "hybrid_guardrail"

    final_score = float(max(0.0, min(1.0, final_score)))

    # Emit observability domain event
    try:
        emitter = get_event_emitter()
        emitter.emit(
            ModalStrengthResolved(
                atom_id=atom.id,
                modal_strength=final_score,
                resolver_type=resolver_type,
                scope_type=atom.scope_type,
                epistemic_status=atom.epistemic_status,
                raw_engine_score=raw_engine_score,
                clamped=clamped,
            )
        )
    except Exception as e:
        logger.debug("Failed to emit ModalStrengthResolved event: %s", e)

    logger.debug(
        "Resolved modality for atom %s (%s, %s): %.3f [mode=%s, raw=%.3f, clamped=%s]",
        atom.id,
        atom.scope_type,
        atom.epistemic_status,
        final_score,
        self.mode,
        raw_engine_score or 0.0,
        clamped,
    )
    return final_score

resolve_modality_sync(atom, context=None)

Synchronously resolve propositional modal strength via structuralist fallback.

Parameters

atom : TheoryAtom Target theoretical atom. context : str or None, optional Surrounding context text.

Returns

float Resolved modal certainty M(phi) in [0.0, 1.0].

Source code in packages/episteme-pipeline/episteme_pipeline/decision/modal_resolver.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
def resolve_modality_sync(
    self,
    atom: TheoryAtom,
    context: str | None = None,
) -> float:
    """Synchronously resolve propositional modal strength via structuralist fallback.

    Parameters
    ----------
    atom : TheoryAtom
        Target theoretical atom.
    context : str or None, optional
        Surrounding context text.

    Returns
    -------
    float
        Resolved modal certainty M(phi) in [0.0, 1.0].
    """
    return self.structural_resolver.resolve_modality_sync(atom, context)