second-source 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. second_source/__init__.py +3 -0
  2. second_source/action/__init__.py +4 -0
  3. second_source/action/commands.py +88 -0
  4. second_source/action/event.py +89 -0
  5. second_source/action/inputs.py +118 -0
  6. second_source/action/main.py +203 -0
  7. second_source/action/publish.py +184 -0
  8. second_source/action/setup.py +143 -0
  9. second_source/action/sweep.py +85 -0
  10. second_source/action/wait.py +49 -0
  11. second_source/benchmark/__init__.py +1 -0
  12. second_source/benchmark/aidev.py +248 -0
  13. second_source/benchmark/aidev_local.py +85 -0
  14. second_source/benchmark/golden.py +314 -0
  15. second_source/benchmark/redact.py +45 -0
  16. second_source/benchmark/rescore.py +388 -0
  17. second_source/benchmark/runner.py +159 -0
  18. second_source/benchmark/sample.py +243 -0
  19. second_source/benchmark/stats.py +363 -0
  20. second_source/cli/__init__.py +1 -0
  21. second_source/cli/bench.py +427 -0
  22. second_source/cli/main.py +182 -0
  23. second_source/core/__init__.py +4 -0
  24. second_source/core/aggregate.py +102 -0
  25. second_source/core/checks.py +470 -0
  26. second_source/core/engine.py +98 -0
  27. second_source/core/evidence.py +29 -0
  28. second_source/core/expr.py +206 -0
  29. second_source/core/hashing.py +41 -0
  30. second_source/core/model.py +112 -0
  31. second_source/core/pack.py +156 -0
  32. second_source/packs/__init__.py +1 -0
  33. second_source/packs/coding/__init__.py +16 -0
  34. second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
  35. second_source/packs/coding/checks/ci_result.yaml +133 -0
  36. second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
  37. second_source/packs/coding/checks/deployed.yaml +36 -0
  38. second_source/packs/coding/checks/docs_updated.yaml +22 -0
  39. second_source/packs/coding/checks/fixes_issue.yaml +58 -0
  40. second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
  41. second_source/packs/coding/checks/integrity_guard.yaml +34 -0
  42. second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
  43. second_source/packs/coding/checks/lint_caution.yaml +22 -0
  44. second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
  45. second_source/packs/coding/checks/not_reverted.yaml +38 -0
  46. second_source/packs/coding/checks/tests_added.yaml +25 -0
  47. second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
  48. second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
  49. second_source/packs/coding/detection.py +94 -0
  50. second_source/packs/coding/diff_facts.py +665 -0
  51. second_source/packs/coding/extract.py +911 -0
  52. second_source/packs/coding/functions.py +241 -0
  53. second_source/packs/coding/pack.yaml +33 -0
  54. second_source/packs/coding/trusted_rules.yaml +50 -0
  55. second_source/pipeline.py +112 -0
  56. second_source/report/__init__.py +1 -0
  57. second_source/report/render.py +503 -0
  58. second_source/sources/__init__.py +1 -0
  59. second_source/sources/github/__init__.py +4 -0
  60. second_source/sources/github/auth.py +48 -0
  61. second_source/sources/github/cache.py +67 -0
  62. second_source/sources/github/client.py +261 -0
  63. second_source/sources/github/mappers.py +454 -0
  64. second_source/sources/github/source.py +385 -0
  65. second_source/sources/github/urls.py +51 -0
  66. second_source-0.5.0.dist-info/METADATA +311 -0
  67. second_source-0.5.0.dist-info/RECORD +71 -0
  68. second_source-0.5.0.dist-info/WHEEL +4 -0
  69. second_source-0.5.0.dist-info/entry_points.txt +2 -0
  70. second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
  71. second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
@@ -0,0 +1,102 @@
1
+ """Aggregation: turn the check runs for one claim into a single verdict.
2
+
3
+ The rules are conservative on purpose. A claim is only CONTRADICTED when a deterministic
4
+ check proves it false; missing or unclear evidence never counts against the agent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+
11
+ from second_source.core.checks import ENGINE_ERROR
12
+ from second_source.core.model import DETERMINISTIC_KINDS, CheckRun, Result, Verdict
13
+
14
+ # Reason used when no check applies to a claim type.
15
+ NO_APPLICABLE_CHECKS = "NO_APPLICABLE_CHECKS"
16
+ # Caveat shown when a guard could not be evaluated (it then withdraws nothing).
17
+ GUARD_ERROR = "GUARD_ERROR"
18
+
19
+
20
+ def aggregate(
21
+ claim_id: str,
22
+ runs: Sequence[CheckRun],
23
+ *,
24
+ required: frozenset[str] | None = None,
25
+ ) -> Verdict:
26
+ """Combine check runs into a verdict. The first matching rule wins:
27
+
28
+ 1. Any CONTRADICTED from a deterministic check -> CONTRADICTED
29
+ 2. Otherwise any PENDING -> PENDING
30
+ 3. Otherwise any UNVERIFIABLE -> UNVERIFIABLE
31
+ 4. Otherwise all VERIFIED (at least one check) -> VERIFIED
32
+ 5. No deciding checks at all -> UNVERIFIABLE (NO_APPLICABLE_CHECKS)
33
+
34
+ Only *deciding* runs count: runs from deterministic kinds whose check is required.
35
+ Judge (model) runs and optional checks are kept in the verdict for transparency but never
36
+ change the result. ``required`` holds the ids of required checks; None means all of them.
37
+
38
+ Guards (role "guard") can only return VERIFIED or UNVERIFIABLE, so a required guard can turn
39
+ an all-VERIFIED claim into UNVERIFIABLE and nothing else (rules 1 and 2 still win). A guard
40
+ that found nothing adds no reason, so a clean claim keeps its deciding checks' reasons.
41
+ Optional guards that found something become ``caveats``: shown, never deciding.
42
+
43
+ A guard that could not be evaluated (ENGINE_ERROR) never decides, required or not: a guard
44
+ that cannot look must not withdraw a verification, just as stale data withdraws nothing.
45
+ It is shown once as the caveat GUARD_ERROR.
46
+ """
47
+
48
+ def guard_failed(run: CheckRun) -> bool:
49
+ return run.role == "guard" and run.reason == ENGINE_ERROR
50
+
51
+ deciding = [
52
+ run
53
+ for run in runs
54
+ if run.kind in DETERMINISTIC_KINDS
55
+ and (required is None or run.check_id in required)
56
+ and not guard_failed(run)
57
+ ]
58
+
59
+ found: list[str] = []
60
+ for run in sorted(runs, key=lambda r: r.check_id):
61
+ if guard_failed(run):
62
+ reason = GUARD_ERROR
63
+ elif (
64
+ run.role == "guard"
65
+ and run.result is Result.UNVERIFIABLE
66
+ and required is not None
67
+ and run.check_id not in required
68
+ ):
69
+ reason = run.reason
70
+ else:
71
+ continue
72
+ if reason not in found:
73
+ found.append(reason)
74
+ caveats = tuple(found)
75
+
76
+ def with_reasons(result: Result, chosen: Sequence[CheckRun]) -> Verdict:
77
+ # Keep reasons in a stable order (by check id) so outputs are reproducible.
78
+ reasons = tuple(run.reason for run in sorted(chosen, key=lambda r: r.check_id))
79
+ return Verdict(
80
+ claim_id=claim_id,
81
+ result=result,
82
+ reasons=reasons,
83
+ check_runs=tuple(runs),
84
+ caveats=caveats,
85
+ )
86
+
87
+ if not deciding:
88
+ return Verdict(
89
+ claim_id=claim_id,
90
+ result=Result.UNVERIFIABLE,
91
+ reasons=(NO_APPLICABLE_CHECKS,),
92
+ check_runs=tuple(runs),
93
+ caveats=caveats,
94
+ )
95
+
96
+ for result in (Result.CONTRADICTED, Result.PENDING, Result.UNVERIFIABLE):
97
+ matching = [run for run in deciding if run.result is result]
98
+ if matching:
99
+ return with_reasons(result, matching)
100
+
101
+ # Every deciding run is VERIFIED; guards that found nothing say nothing.
102
+ return with_reasons(Result.VERIFIED, [run for run in deciding if run.role != "guard"])
@@ -0,0 +1,470 @@
1
+ """Check definitions: how a claim type is verified.
2
+
3
+ A check is declarative data (normally written in YAML) made of:
4
+
5
+ - ``params``: tunable values with defaults and bounds (e.g. a time window);
6
+ - ``evidence``: named sets of evidence records, selected by type and an optional filter;
7
+ - ``derive``: named intermediate values, computed in order;
8
+ - ``outcomes``: ordered conditions; the first one that is true decides the result.
9
+
10
+ This module validates definitions when they are loaded (so mistakes fail early) and
11
+ evaluates them into ``CheckRun`` objects. Evaluation is pure: no I/O, no clock. The current
12
+ time and all evidence are passed in, so the same inputs always give the same result.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ import string
19
+ from collections.abc import Iterable, Iterator, Mapping
20
+ from dataclasses import dataclass, field
21
+ from datetime import datetime
22
+ from typing import Any
23
+
24
+ from celpy import celtypes
25
+
26
+ from second_source.core.evidence import dedupe_evidence
27
+ from second_source.core.expr import Evaluator, ExpressionError, from_cel, to_cel
28
+ from second_source.core.hashing import sha256_hex
29
+ from second_source.core.model import (
30
+ CheckKind,
31
+ CheckRun,
32
+ Claim,
33
+ Episode,
34
+ Evidence,
35
+ Level,
36
+ Result,
37
+ )
38
+
39
+ # Names the engine itself provides to expressions; evidence sets and derived values may not
40
+ # reuse them.
41
+ ROLES = frozenset({"check", "guard"})
42
+ RESERVED_NAMES = frozenset({"claim", "episode", "params", "now", "stale", "e"})
43
+
44
+ # Kinds that can be expressed as YAML checks in v1. Judge checks (model-assessed) and human
45
+ # checks (review decisions) are handled elsewhere and are not loaded from definitions.
46
+ SUPPORTED_KINDS = frozenset({CheckKind.RULE, CheckKind.STATE, CheckKind.TEMPORAL})
47
+
48
+ _IDENTIFIER = re.compile(r"^[a-z_][a-z0-9_]*$")
49
+ _CHECK_ID = re.compile(r"^[a-z0-9_]+(\.[a-z0-9_]+)+$") # e.g. "coding.tests_pass"
50
+ _VERSION = re.compile(r"^\d+\.\d+\.\d+$")
51
+ _REASON = re.compile(r"^[A-Z][A-Z0-9_]*$") # e.g. "TEST_CHECK_FAILED"
52
+ _PARAM_TYPES = {"int": int, "double": float, "string": str, "bool": bool}
53
+
54
+ # Reason used whenever a check cannot be evaluated because of a definition or data problem.
55
+ ENGINE_ERROR = "ENGINE_ERROR"
56
+
57
+
58
+ class CheckDefinitionError(ValueError):
59
+ """A check definition is malformed. The message names the check and the problem."""
60
+
61
+
62
+ # --------------------------------------------------------------------------------------------
63
+ # Definition model
64
+ # --------------------------------------------------------------------------------------------
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ParamSpec:
69
+ """A tunable parameter with a type, a default and optional bounds."""
70
+
71
+ name: str
72
+ type: str
73
+ default: Any
74
+ min: float | None = None
75
+ max: float | None = None
76
+
77
+ def resolve(self, value: Any = None) -> Any:
78
+ """Return the effective value (the override if given, else the default), validated."""
79
+ chosen = self.default if value is None else value
80
+ expected = _PARAM_TYPES[self.type]
81
+ # bool is a subclass of int: do not let True pass as an int (or vice versa).
82
+ is_bool_mismatch = (expected is bool) != isinstance(chosen, bool)
83
+ if expected is float and isinstance(chosen, int) and not isinstance(chosen, bool):
84
+ chosen = float(chosen)
85
+ if not isinstance(chosen, expected) or is_bool_mismatch:
86
+ raise CheckDefinitionError(
87
+ f"param {self.name!r} must be {self.type}, got {type(chosen).__name__}"
88
+ )
89
+ if self.min is not None and chosen < self.min:
90
+ raise CheckDefinitionError(f"param {self.name!r}={chosen} is below min {self.min}")
91
+ if self.max is not None and chosen > self.max:
92
+ raise CheckDefinitionError(f"param {self.name!r}={chosen} is above max {self.max}")
93
+ return chosen
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class EvidenceSelector:
98
+ """A named set of evidence: all records of one type, optionally filtered by ``where``.
99
+
100
+ Inside ``where`` the current record is available as ``e``.
101
+ """
102
+
103
+ name: str
104
+ record_type: str
105
+ where: str | None = None
106
+
107
+
108
+ @dataclass(frozen=True)
109
+ class Outcome:
110
+ """One branch of the decision: if ``when`` is true, return ``result`` with ``reason``.
111
+
112
+ ``when`` is None for the final ``otherwise`` branch.
113
+ """
114
+
115
+ when: str | None
116
+ result: Result
117
+ reason: str
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class CheckDefinition:
122
+ id: str
123
+ version: str
124
+ kind: CheckKind
125
+ level: Level
126
+ applies_to: tuple[str, ...]
127
+ outcomes: tuple[Outcome, ...]
128
+ params: tuple[ParamSpec, ...] = ()
129
+ evidence: tuple[EvidenceSelector, ...] = ()
130
+ derive: tuple[tuple[str, str], ...] = () # ordered (name, expression) pairs
131
+ explain: str | None = None
132
+ required: bool = True
133
+ # "guard": a check on top of the deciding checks that can only withdraw a VERIFIED (its
134
+ # outcomes are limited to VERIFIED = "nothing found" and UNVERIFIABLE). It enforces the
135
+ # cardinal rule in the schema: a guard can never accuse. See docs/ARCHITECTURE.md.
136
+ role: str = "check"
137
+
138
+ @classmethod
139
+ def from_dict(cls, data: Mapping[str, Any]) -> CheckDefinition:
140
+ """Build and validate a definition from parsed YAML/JSON data."""
141
+ return _parse_definition(data)
142
+
143
+ def expressions(self) -> Iterator[str]:
144
+ """Every expression in this definition (used to pre-compile and fail early)."""
145
+ for selector in self.evidence:
146
+ if selector.where:
147
+ yield selector.where
148
+ for _, expression in self.derive:
149
+ yield expression
150
+ for outcome in self.outcomes:
151
+ if outcome.when:
152
+ yield outcome.when
153
+
154
+
155
+ # --------------------------------------------------------------------------------------------
156
+ # Parsing and validation
157
+ # --------------------------------------------------------------------------------------------
158
+
159
+
160
+ def _parse_definition(data: Mapping[str, Any]) -> CheckDefinition:
161
+ check_id = str(data.get("id", "")).strip()
162
+
163
+ def fail(problem: str) -> CheckDefinitionError:
164
+ return CheckDefinitionError(f"check {check_id or '<missing id>'}: {problem}")
165
+
166
+ # Identity and classification.
167
+ if not _CHECK_ID.match(check_id):
168
+ raise fail("id must look like 'pack.check_name'")
169
+ version = str(data.get("version", ""))
170
+ if not _VERSION.match(version):
171
+ raise fail("version must be semantic, e.g. '1.0.0'")
172
+ try:
173
+ kind = CheckKind(data.get("kind"))
174
+ level = Level(data.get("level"))
175
+ except ValueError as error:
176
+ raise fail(str(error)) from error
177
+ if kind not in SUPPORTED_KINDS:
178
+ raise fail(f"kind {kind.value!r} cannot be defined in YAML in this version")
179
+
180
+ # Which claim types this check verifies.
181
+ applies_to = data.get("applies_to")
182
+ if not applies_to or not all(isinstance(t, str) and t for t in applies_to):
183
+ raise fail("applies_to must be a non-empty list of claim types")
184
+
185
+ # Parameters.
186
+ params = []
187
+ for name, spec in (data.get("params") or {}).items():
188
+ if not _IDENTIFIER.match(name):
189
+ raise fail(f"invalid param name {name!r}")
190
+ if not isinstance(spec, Mapping) or spec.get("type") not in _PARAM_TYPES:
191
+ raise fail(f"param {name!r} needs a type in {sorted(_PARAM_TYPES)}")
192
+ param = ParamSpec(name, spec["type"], spec.get("default"), spec.get("min"), spec.get("max"))
193
+ try:
194
+ param.resolve() # the default itself must satisfy the type and bounds
195
+ except CheckDefinitionError as error:
196
+ raise fail(str(error)) from error
197
+ params.append(param)
198
+
199
+ # Names introduced by evidence sets and derived values must be unique and not reserved.
200
+ seen_names: set[str] = set()
201
+
202
+ def claim_name(name: str) -> None:
203
+ if not _IDENTIFIER.match(name) or name in RESERVED_NAMES or name in seen_names:
204
+ raise fail(f"name {name!r} is invalid, reserved or duplicated")
205
+ seen_names.add(name)
206
+
207
+ evidence = []
208
+ for name, spec in (data.get("evidence") or {}).items():
209
+ claim_name(name)
210
+ if not isinstance(spec, Mapping) or not spec.get("record_type"):
211
+ raise fail(f"evidence {name!r} needs a record_type")
212
+ evidence.append(EvidenceSelector(name, str(spec["record_type"]), spec.get("where")))
213
+
214
+ derive = []
215
+ for name, expression in (data.get("derive") or {}).items():
216
+ claim_name(name)
217
+ if not isinstance(expression, str) or not expression.strip():
218
+ raise fail(f"derive {name!r} must be an expression string")
219
+ derive.append((name, expression))
220
+
221
+ # Outcomes: at least one, exactly one `otherwise`, and it must be last.
222
+ raw_outcomes = data.get("outcomes") or []
223
+ if not raw_outcomes:
224
+ raise fail("outcomes must not be empty")
225
+ outcomes = []
226
+ for index, raw in enumerate(raw_outcomes):
227
+ is_last = index == len(raw_outcomes) - 1
228
+ is_otherwise = bool(raw.get("otherwise"))
229
+ if is_otherwise != is_last:
230
+ raise fail("exactly one 'otherwise' outcome is required, and it must be last")
231
+ when = None if is_otherwise else raw.get("when")
232
+ if not is_otherwise and (not isinstance(when, str) or not when.strip()):
233
+ raise fail(f"outcome {index} needs a 'when' expression")
234
+ try:
235
+ result = Result(raw.get("result"))
236
+ except ValueError as error:
237
+ raise fail(f"outcome {index}: {error}") from error
238
+ reason = str(raw.get("reason", ""))
239
+ if not _REASON.match(reason):
240
+ raise fail(f"outcome {index}: reason must be UPPER_SNAKE_CASE")
241
+ outcomes.append(Outcome(when, result, reason))
242
+
243
+ role = str(data.get("role", "check"))
244
+ if role not in ROLES:
245
+ raise fail(f"role must be one of {sorted(ROLES)}")
246
+ if role == "guard":
247
+ allowed = {Result.VERIFIED, Result.UNVERIFIABLE}
248
+ if any(outcome.result not in allowed for outcome in outcomes):
249
+ raise fail("a guard's outcomes may only be VERIFIED or UNVERIFIABLE")
250
+
251
+ return CheckDefinition(
252
+ id=check_id,
253
+ version=version,
254
+ kind=kind,
255
+ level=level,
256
+ applies_to=tuple(applies_to),
257
+ outcomes=tuple(outcomes),
258
+ params=tuple(params),
259
+ evidence=tuple(evidence),
260
+ derive=tuple(derive),
261
+ explain=data.get("explain"),
262
+ required=bool(data.get("required", True)),
263
+ role=role,
264
+ )
265
+
266
+
267
+ # --------------------------------------------------------------------------------------------
268
+ # Evaluation
269
+ # --------------------------------------------------------------------------------------------
270
+
271
+
272
+ def claim_view(claim: Claim) -> dict[str, Any]:
273
+ """How a claim looks inside expressions (``claim.type``, ``claim.attributes.x``, ...)."""
274
+ return {
275
+ "id": claim.id,
276
+ "type": claim.type,
277
+ "made_at": claim.made_at,
278
+ "origin": claim.origin,
279
+ "span": claim.span,
280
+ "attributes": dict(claim.attributes),
281
+ }
282
+
283
+
284
+ def episode_view(episode: Episode) -> dict[str, Any]:
285
+ """How an episode looks inside expressions."""
286
+ return {
287
+ "id": episode.id,
288
+ "kind": episode.kind,
289
+ "agent": episode.agent,
290
+ "opened_at": episode.opened_at,
291
+ "closed_at": episode.closed_at,
292
+ "attributes": dict(episode.attributes),
293
+ }
294
+
295
+
296
+ def evidence_view(record: Evidence) -> dict[str, Any]:
297
+ """How an evidence record looks inside expressions.
298
+
299
+ Attributes are flattened for convenience (``c.conclusion`` rather than
300
+ ``c.attributes.conclusion``). The standard fields are written last, so an attribute can
301
+ never overwrite them.
302
+ """
303
+ return {
304
+ **dict(record.attributes),
305
+ "record_type": record.record_type,
306
+ "external_ref": record.external_ref,
307
+ "observed_at": record.observed_at,
308
+ "occurred_at": record.occurred_at,
309
+ "version": record.version,
310
+ }
311
+
312
+
313
+ def evaluate_check(
314
+ definition: CheckDefinition,
315
+ claim: Claim,
316
+ episode: Episode,
317
+ evidence: Iterable[Evidence],
318
+ *,
319
+ now: datetime,
320
+ evaluator: Evaluator,
321
+ stale: frozenset[str] = frozenset(),
322
+ params: Mapping[str, Any] | None = None,
323
+ ) -> CheckRun:
324
+ """Evaluate one check for one claim and return the frozen, hashed result.
325
+
326
+ Never raises for data or expression problems: those produce an UNVERIFIABLE result with
327
+ reason ENGINE_ERROR, so one broken check cannot crash a run or accuse an agent.
328
+ """
329
+ overrides = dict(params or {})
330
+ records = dedupe_evidence(evidence)
331
+ relevant_types = {selector.record_type for selector in definition.evidence}
332
+ relevant = [r for r in records if r.record_type in relevant_types]
333
+
334
+ # Resolve parameters first; a bad override is a configuration error, not agent failure.
335
+ try:
336
+ resolved_params = {p.name: p.resolve(overrides.get(p.name)) for p in definition.params}
337
+ except CheckDefinitionError as error:
338
+ return _error_run(definition, claim, str(error), inputs_hash="")
339
+
340
+ # Hash every input that can influence the outcome, so results can be replayed and audited.
341
+ inputs_hash = sha256_hex(
342
+ {
343
+ "check": [definition.id, definition.version],
344
+ "claim": claim_view(claim),
345
+ "episode": episode_view(episode),
346
+ "evidence": [evidence_view(r) for r in relevant],
347
+ "params": resolved_params,
348
+ "now": now,
349
+ "stale": sorted(stale),
350
+ }
351
+ )
352
+
353
+ try:
354
+ # Base variables every expression can use.
355
+ activation: dict[str, Any] = {
356
+ "claim": to_cel(claim_view(claim)),
357
+ "episode": to_cel(episode_view(episode)),
358
+ "params": to_cel(resolved_params),
359
+ "now": to_cel(now),
360
+ "stale": to_cel(sorted(stale)),
361
+ }
362
+
363
+ # Named evidence sets: records of the right type that pass the optional filter.
364
+ for selector in definition.evidence:
365
+ selected = []
366
+ for record in relevant:
367
+ if record.record_type != selector.record_type:
368
+ continue
369
+ view = to_cel(evidence_view(record))
370
+ if selector.where is None or evaluator.evaluate_bool(
371
+ selector.where, {**activation, "e": view}
372
+ ):
373
+ selected.append(view)
374
+ activation[selector.name] = celtypes.ListType(selected)
375
+
376
+ # Derived values, in order; each may use the ones before it.
377
+ derived: dict[str, Any] = {}
378
+ for name, expression in definition.derive:
379
+ value = evaluator.evaluate(expression, activation)
380
+ activation[name] = value
381
+ derived[name] = from_cel(value)
382
+
383
+ # First matching outcome wins; the last one is always `otherwise`.
384
+ for outcome in definition.outcomes:
385
+ if outcome.when is None or evaluator.evaluate_bool(outcome.when, activation):
386
+ return CheckRun(
387
+ check_id=definition.id,
388
+ check_version=definition.version,
389
+ kind=definition.kind,
390
+ level=definition.level,
391
+ claim_id=claim.id,
392
+ result=outcome.result,
393
+ reason=outcome.reason,
394
+ inputs_hash=inputs_hash,
395
+ derived=derived,
396
+ explanation=_render_explanation(definition.explain, derived, resolved_params),
397
+ role=definition.role,
398
+ )
399
+ except (ExpressionError, ValueError, TypeError) as error:
400
+ return _error_run(definition, claim, str(error), inputs_hash)
401
+
402
+ # Unreachable: validation guarantees a final `otherwise` outcome.
403
+ raise AssertionError(f"check {definition.id} produced no outcome")
404
+
405
+
406
+ def _error_run(
407
+ definition: CheckDefinition, claim: Claim, message: str, inputs_hash: str
408
+ ) -> CheckRun:
409
+ """A CheckRun recording that the check could not be evaluated."""
410
+ return CheckRun(
411
+ check_id=definition.id,
412
+ check_version=definition.version,
413
+ kind=definition.kind,
414
+ level=definition.level,
415
+ claim_id=claim.id,
416
+ result=Result.UNVERIFIABLE,
417
+ reason=ENGINE_ERROR,
418
+ inputs_hash=inputs_hash,
419
+ explanation=message,
420
+ role=definition.role,
421
+ )
422
+
423
+
424
+ class _KeepMissing(dict):
425
+ """Format helper: leaves unknown ``{placeholders}`` in place instead of failing."""
426
+
427
+ def __missing__(self, key: str) -> str:
428
+ return "{" + key + "}"
429
+
430
+
431
+ def _render_explanation(
432
+ template: str | None, derived: Mapping[str, Any], params: Mapping[str, Any]
433
+ ) -> str | None:
434
+ """Fill ``{name}`` placeholders in the explanation with derived values and params."""
435
+ if not template:
436
+ return None
437
+ values = _KeepMissing({**params, **derived})
438
+ return string.Formatter().vformat(template, (), values)
439
+
440
+
441
+ @dataclass
442
+ class CompiledChecks:
443
+ """Checks grouped by the claim type they apply to, with expressions pre-compiled."""
444
+
445
+ by_claim_type: dict[str, list[CheckDefinition]] = field(default_factory=dict)
446
+
447
+ @classmethod
448
+ def build(cls, definitions: Iterable[CheckDefinition], evaluator: Evaluator) -> CompiledChecks:
449
+ """Index checks by claim type and compile every expression, failing early on errors."""
450
+ compiled = cls()
451
+ seen: set[str] = set()
452
+ for definition in definitions:
453
+ if definition.id in seen:
454
+ raise CheckDefinitionError(f"check {definition.id}: defined more than once")
455
+ seen.add(definition.id)
456
+ for expression in definition.expressions():
457
+ try:
458
+ evaluator.compile(expression)
459
+ except ExpressionError as error:
460
+ raise CheckDefinitionError(f"check {definition.id}: {error}") from error
461
+ for claim_type in definition.applies_to:
462
+ compiled.by_claim_type.setdefault(claim_type, []).append(definition)
463
+ for claim_type, checks in compiled.by_claim_type.items():
464
+ # A guard can withdraw a verification but never create one.
465
+ if all(check.role == "guard" for check in checks):
466
+ raise CheckDefinitionError(f"claim type {claim_type}: only guards apply to it")
467
+ return compiled
468
+
469
+ def for_claim_type(self, claim_type: str) -> list[CheckDefinition]:
470
+ return list(self.by_claim_type.get(claim_type, []))
@@ -0,0 +1,98 @@
1
+ """The engine: verify every claim of an episode against the available evidence.
2
+
3
+ This is the single entry point the rest of the system uses. It is pure: callers pass in the
4
+ episode, its claims, the evidence and the current time, and get verdicts back.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Iterable, Mapping, Sequence
10
+ from datetime import datetime
11
+ from typing import Any
12
+
13
+ from second_source.core.aggregate import aggregate
14
+ from second_source.core.checks import CheckDefinition, CompiledChecks, evaluate_check
15
+ from second_source.core.expr import Evaluator, FunctionRegistry
16
+ from second_source.core.model import Claim, Episode, Evidence, Verdict
17
+ from second_source.core.pack import Pack, build_function_registry
18
+
19
+
20
+ class Engine:
21
+ """Holds compiled checks and verifies claims.
22
+
23
+ Create one engine per set of checks and reuse it: expressions are compiled once when the
24
+ engine is built, so invalid checks fail immediately rather than in the middle of a run.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ definitions: Iterable[CheckDefinition],
30
+ functions: FunctionRegistry | None = None,
31
+ ) -> None:
32
+ self._evaluator = Evaluator(functions)
33
+ self._checks = CompiledChecks.build(definitions, self._evaluator)
34
+
35
+ @classmethod
36
+ def from_packs(cls, packs: Sequence[Pack]) -> Engine:
37
+ """Build an engine from loaded packs: all their checks and helper functions."""
38
+ definitions = [check for pack in packs for check in pack.checks]
39
+ return cls(definitions, build_function_registry(packs))
40
+
41
+ def checks_for(self, claim_type: str) -> list[CheckDefinition]:
42
+ """The checks that apply to a claim type (useful for deciding what evidence to fetch)."""
43
+ return self._checks.for_claim_type(claim_type)
44
+
45
+ def evidence_types_for(self, claims: Iterable[Claim]) -> frozenset[str]:
46
+ """Evidence record types needed to verify these claims.
47
+
48
+ Sources use this to fetch only what is necessary, which keeps API usage low.
49
+ """
50
+ return frozenset(
51
+ selector.record_type
52
+ for claim in claims
53
+ for check in self.checks_for(claim.type)
54
+ for selector in check.evidence
55
+ )
56
+
57
+ def verify(
58
+ self,
59
+ episode: Episode,
60
+ claims: Sequence[Claim],
61
+ evidence: Iterable[Evidence],
62
+ *,
63
+ now: datetime,
64
+ stale: frozenset[str] = frozenset(),
65
+ params: Mapping[str, Mapping[str, Any]] | None = None,
66
+ ) -> list[Verdict]:
67
+ """Return one verdict per claim, in the order the claims were given.
68
+
69
+ ``stale`` lists evidence record types the source could not refresh; checks can turn
70
+ those into UNVERIFIABLE results. ``params`` maps a check id to parameter overrides.
71
+ """
72
+ if now.tzinfo is None:
73
+ raise ValueError("now must be timezone-aware")
74
+ for claim in claims:
75
+ if claim.episode_id != episode.id:
76
+ raise ValueError(f"claim {claim.id} does not belong to episode {episode.id}")
77
+
78
+ evidence_list = list(evidence) # may be iterated once per check
79
+ overrides = params or {}
80
+ verdicts = []
81
+ for claim in claims:
82
+ checks = self.checks_for(claim.type)
83
+ runs = [
84
+ evaluate_check(
85
+ check,
86
+ claim,
87
+ episode,
88
+ evidence_list,
89
+ now=now,
90
+ evaluator=self._evaluator,
91
+ stale=stale,
92
+ params=overrides.get(check.id),
93
+ )
94
+ for check in checks
95
+ ]
96
+ required = frozenset(check.id for check in checks if check.required)
97
+ verdicts.append(aggregate(claim.id, runs, required=required))
98
+ return verdicts