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.
- second_source/__init__.py +3 -0
- second_source/action/__init__.py +4 -0
- second_source/action/commands.py +88 -0
- second_source/action/event.py +89 -0
- second_source/action/inputs.py +118 -0
- second_source/action/main.py +203 -0
- second_source/action/publish.py +184 -0
- second_source/action/setup.py +143 -0
- second_source/action/sweep.py +85 -0
- second_source/action/wait.py +49 -0
- second_source/benchmark/__init__.py +1 -0
- second_source/benchmark/aidev.py +248 -0
- second_source/benchmark/aidev_local.py +85 -0
- second_source/benchmark/golden.py +314 -0
- second_source/benchmark/redact.py +45 -0
- second_source/benchmark/rescore.py +388 -0
- second_source/benchmark/runner.py +159 -0
- second_source/benchmark/sample.py +243 -0
- second_source/benchmark/stats.py +363 -0
- second_source/cli/__init__.py +1 -0
- second_source/cli/bench.py +427 -0
- second_source/cli/main.py +182 -0
- second_source/core/__init__.py +4 -0
- second_source/core/aggregate.py +102 -0
- second_source/core/checks.py +470 -0
- second_source/core/engine.py +98 -0
- second_source/core/evidence.py +29 -0
- second_source/core/expr.py +206 -0
- second_source/core/hashing.py +41 -0
- second_source/core/model.py +112 -0
- second_source/core/pack.py +156 -0
- second_source/packs/__init__.py +1 -0
- second_source/packs/coding/__init__.py +16 -0
- second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
- second_source/packs/coding/checks/ci_result.yaml +133 -0
- second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
- second_source/packs/coding/checks/deployed.yaml +36 -0
- second_source/packs/coding/checks/docs_updated.yaml +22 -0
- second_source/packs/coding/checks/fixes_issue.yaml +58 -0
- second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
- second_source/packs/coding/checks/integrity_guard.yaml +34 -0
- second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
- second_source/packs/coding/checks/lint_caution.yaml +22 -0
- second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
- second_source/packs/coding/checks/not_reverted.yaml +38 -0
- second_source/packs/coding/checks/tests_added.yaml +25 -0
- second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
- second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
- second_source/packs/coding/detection.py +94 -0
- second_source/packs/coding/diff_facts.py +665 -0
- second_source/packs/coding/extract.py +911 -0
- second_source/packs/coding/functions.py +241 -0
- second_source/packs/coding/pack.yaml +33 -0
- second_source/packs/coding/trusted_rules.yaml +50 -0
- second_source/pipeline.py +112 -0
- second_source/report/__init__.py +1 -0
- second_source/report/render.py +503 -0
- second_source/sources/__init__.py +1 -0
- second_source/sources/github/__init__.py +4 -0
- second_source/sources/github/auth.py +48 -0
- second_source/sources/github/cache.py +67 -0
- second_source/sources/github/client.py +261 -0
- second_source/sources/github/mappers.py +454 -0
- second_source/sources/github/source.py +385 -0
- second_source/sources/github/urls.py +51 -0
- second_source-0.5.0.dist-info/METADATA +311 -0
- second_source-0.5.0.dist-info/RECORD +71 -0
- second_source-0.5.0.dist-info/WHEEL +4 -0
- second_source-0.5.0.dist-info/entry_points.txt +2 -0
- second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
- second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Evidence helpers that every pack relies on."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
|
|
7
|
+
from second_source.core.hashing import canonical_json
|
|
8
|
+
from second_source.core.model import Evidence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _rank(record: Evidence) -> tuple[int, object, str]:
|
|
12
|
+
# The contents break exact ties, so the result never depends on the order records arrive in.
|
|
13
|
+
return (record.version, record.observed_at, canonical_json(dict(record.attributes)))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def dedupe_evidence(records: Iterable[Evidence]) -> list[Evidence]:
|
|
17
|
+
"""Keep one record per (record_type, external_ref): the latest version, then latest observation,
|
|
18
|
+
then (for an exact tie) the record whose contents sort last, so the order is irrelevant.
|
|
19
|
+
|
|
20
|
+
Re-observing the same record (for example a re-uploaded file or a repeated API read) must never
|
|
21
|
+
count it twice.
|
|
22
|
+
"""
|
|
23
|
+
latest: dict[tuple[str, str], Evidence] = {}
|
|
24
|
+
for record in records:
|
|
25
|
+
key = (record.record_type, record.external_ref)
|
|
26
|
+
current = latest.get(key)
|
|
27
|
+
if current is None or _rank(record) > _rank(current):
|
|
28
|
+
latest[key] = record
|
|
29
|
+
return sorted(latest.values(), key=lambda e: (e.record_type, e.external_ref))
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Expression layer: a thin, safe wrapper around CEL (Common Expression Language).
|
|
2
|
+
|
|
3
|
+
Checks are written as small CEL expressions in YAML (for example
|
|
4
|
+
``"checks.exists(c, c.conclusion == 'failure')"``). This module is the only place that
|
|
5
|
+
talks to the CEL library, so the rest of the engine works with plain Python values.
|
|
6
|
+
|
|
7
|
+
It provides four things:
|
|
8
|
+
|
|
9
|
+
1. ``to_cel`` / ``from_cel`` convert between Python values and CEL values.
|
|
10
|
+
2. ``FunctionRegistry`` holds the pure functions that packs make available to expressions.
|
|
11
|
+
3. ``Evaluator`` compiles each expression once (cached) and evaluates it.
|
|
12
|
+
4. ``ExpressionError`` is the single error type callers need to handle.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Callable, Mapping
|
|
18
|
+
from datetime import UTC, datetime, timedelta
|
|
19
|
+
from enum import Enum
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
import celpy
|
|
23
|
+
from celpy import celtypes
|
|
24
|
+
from celpy.celparser import CELParseError
|
|
25
|
+
from celpy.evaluation import CELEvalError, CELSyntaxError, CELUnsupportedError
|
|
26
|
+
|
|
27
|
+
# Errors raised by the CEL library that mean "this expression could not be compiled or
|
|
28
|
+
# evaluated". We translate all of them into ExpressionError.
|
|
29
|
+
_CEL_ERRORS = (CELParseError, CELEvalError, CELSyntaxError, CELUnsupportedError)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ExpressionError(Exception):
|
|
33
|
+
"""An expression failed to compile or evaluate. Carries the expression text for debugging."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, expression: str, message: str) -> None:
|
|
36
|
+
super().__init__(f"{message} (expression: {expression!r})")
|
|
37
|
+
self.expression = expression
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --------------------------------------------------------------------------------------------
|
|
41
|
+
# Value conversion
|
|
42
|
+
# --------------------------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def to_cel(value: Any) -> Any:
|
|
46
|
+
"""Convert a plain Python value (recursively) into the matching CEL value.
|
|
47
|
+
|
|
48
|
+
Datetimes must be timezone-aware; naive datetimes are rejected because comparing them
|
|
49
|
+
with aware ones would silently give wrong answers.
|
|
50
|
+
"""
|
|
51
|
+
# Order matters: bool is a subclass of int in Python, so test it first.
|
|
52
|
+
if value is None:
|
|
53
|
+
return celtypes.NullType()
|
|
54
|
+
if isinstance(value, bool):
|
|
55
|
+
return celtypes.BoolType(value)
|
|
56
|
+
if isinstance(value, Enum):
|
|
57
|
+
return to_cel(value.value)
|
|
58
|
+
if isinstance(value, int):
|
|
59
|
+
return celtypes.IntType(value)
|
|
60
|
+
if isinstance(value, float):
|
|
61
|
+
return celtypes.DoubleType(value)
|
|
62
|
+
if isinstance(value, str):
|
|
63
|
+
return celtypes.StringType(value)
|
|
64
|
+
if isinstance(value, datetime):
|
|
65
|
+
if value.tzinfo is None:
|
|
66
|
+
raise ValueError("naive datetime passed to an expression; use timezone-aware UTC")
|
|
67
|
+
return celtypes.TimestampType(value.astimezone(UTC))
|
|
68
|
+
if isinstance(value, timedelta):
|
|
69
|
+
# CEL durations take whole seconds plus nanoseconds.
|
|
70
|
+
whole_seconds = int(value.total_seconds())
|
|
71
|
+
nanos = value.microseconds * 1000 if value.total_seconds() >= 0 else 0
|
|
72
|
+
return celtypes.DurationType(seconds=whole_seconds, nanos=nanos)
|
|
73
|
+
if isinstance(value, Mapping):
|
|
74
|
+
# Keys whose value is None are left out. cel-python does not compare null reliably
|
|
75
|
+
# (e.g. `x == null` can be false for a null x), so "no value" is expressed as a missing
|
|
76
|
+
# key and checks test for it with `has(x.field)`.
|
|
77
|
+
return celtypes.MapType(
|
|
78
|
+
{celtypes.StringType(str(k)): to_cel(v) for k, v in value.items() if v is not None}
|
|
79
|
+
)
|
|
80
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
81
|
+
items = sorted(value) if isinstance(value, (set, frozenset)) else value
|
|
82
|
+
return celtypes.ListType([to_cel(v) for v in items])
|
|
83
|
+
raise TypeError(f"cannot convert {type(value).__name__} to a CEL value")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def from_cel(value: Any) -> Any:
|
|
87
|
+
"""Convert a CEL value (recursively) back into a plain Python value."""
|
|
88
|
+
# Order matters: CEL's BoolType subclasses int, and TimestampType subclasses datetime.
|
|
89
|
+
if isinstance(value, celtypes.NullType):
|
|
90
|
+
return None
|
|
91
|
+
if isinstance(value, celtypes.BoolType):
|
|
92
|
+
return bool(value)
|
|
93
|
+
if isinstance(value, (celtypes.IntType, celtypes.UintType)):
|
|
94
|
+
return int(value)
|
|
95
|
+
if isinstance(value, celtypes.DoubleType):
|
|
96
|
+
return float(value)
|
|
97
|
+
if isinstance(value, celtypes.StringType):
|
|
98
|
+
return str(value)
|
|
99
|
+
if isinstance(value, celtypes.TimestampType):
|
|
100
|
+
return datetime.fromtimestamp(value.timestamp(), tz=UTC)
|
|
101
|
+
if isinstance(value, celtypes.DurationType):
|
|
102
|
+
return timedelta(seconds=value.total_seconds())
|
|
103
|
+
if isinstance(value, celtypes.MapType):
|
|
104
|
+
return {str(k): from_cel(v) for k, v in value.items()}
|
|
105
|
+
if isinstance(value, celtypes.ListType):
|
|
106
|
+
return [from_cel(v) for v in value]
|
|
107
|
+
return value
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# --------------------------------------------------------------------------------------------
|
|
111
|
+
# Functions available inside expressions
|
|
112
|
+
# --------------------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
CelFunction = Callable[..., Any]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _cel_sum(values: Any) -> Any:
|
|
118
|
+
"""``sum(list)``: total of a list of numbers. Returns a double if any element is a double."""
|
|
119
|
+
numbers = [from_cel(v) for v in values]
|
|
120
|
+
total = sum(numbers)
|
|
121
|
+
return celtypes.DoubleType(total) if isinstance(total, float) else celtypes.IntType(total)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# Functions every pack can rely on. Packs add their own through FunctionRegistry.register.
|
|
125
|
+
_BUILTINS: dict[str, CelFunction] = {"sum": _cel_sum}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class FunctionRegistry:
|
|
129
|
+
"""Named, pure functions that expressions may call.
|
|
130
|
+
|
|
131
|
+
Packs register helpers such as ``is_test_check(name)``. Functions must be deterministic
|
|
132
|
+
and must not perform I/O, so that every verdict can be replayed.
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
def __init__(self) -> None:
|
|
136
|
+
self._functions: dict[str, CelFunction] = dict(_BUILTINS)
|
|
137
|
+
|
|
138
|
+
def register(self, name: str, function: CelFunction) -> None:
|
|
139
|
+
"""Add a function. Re-using an existing name is an error, so packs cannot clash."""
|
|
140
|
+
if name in self._functions:
|
|
141
|
+
raise ValueError(f"expression function {name!r} is already registered")
|
|
142
|
+
self._functions[name] = function
|
|
143
|
+
|
|
144
|
+
def as_dict(self) -> dict[str, CelFunction]:
|
|
145
|
+
return dict(self._functions)
|
|
146
|
+
|
|
147
|
+
def __contains__(self, name: str) -> bool:
|
|
148
|
+
return name in self._functions
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# --------------------------------------------------------------------------------------------
|
|
152
|
+
# Compilation and evaluation
|
|
153
|
+
# --------------------------------------------------------------------------------------------
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class Evaluator:
|
|
157
|
+
"""Compiles expressions once and evaluates them against an activation (variables).
|
|
158
|
+
|
|
159
|
+
One Evaluator is created per Engine. The compile cache is keyed by expression text,
|
|
160
|
+
so a check evaluated thousands of times is only parsed once.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, functions: FunctionRegistry | None = None) -> None:
|
|
164
|
+
self._env = celpy.Environment()
|
|
165
|
+
self._functions = (functions or FunctionRegistry()).as_dict()
|
|
166
|
+
self._programs: dict[str, Any] = {}
|
|
167
|
+
|
|
168
|
+
def compile(self, expression: str) -> None:
|
|
169
|
+
"""Compile and cache an expression. Raises ExpressionError on syntax errors.
|
|
170
|
+
|
|
171
|
+
Called when checks are loaded, so broken expressions fail early, not mid-run.
|
|
172
|
+
"""
|
|
173
|
+
self._program(expression)
|
|
174
|
+
|
|
175
|
+
def evaluate(self, expression: str, activation: Mapping[str, Any]) -> Any:
|
|
176
|
+
"""Evaluate a compiled expression. ``activation`` must already hold CEL values.
|
|
177
|
+
|
|
178
|
+
Returns a CEL value; use ``from_cel`` to turn it into plain Python.
|
|
179
|
+
"""
|
|
180
|
+
program = self._program(expression)
|
|
181
|
+
try:
|
|
182
|
+
return program.evaluate(dict(activation))
|
|
183
|
+
except _CEL_ERRORS as error:
|
|
184
|
+
raise ExpressionError(expression, f"evaluation failed: {error}") from error
|
|
185
|
+
except (TypeError, ValueError, KeyError, ZeroDivisionError) as error:
|
|
186
|
+
# Errors raised inside registered functions surface here.
|
|
187
|
+
raise ExpressionError(expression, f"evaluation failed: {error}") from error
|
|
188
|
+
|
|
189
|
+
def evaluate_bool(self, expression: str, activation: Mapping[str, Any]) -> bool:
|
|
190
|
+
"""Evaluate an expression that must produce a boolean (used for conditions)."""
|
|
191
|
+
result = self.evaluate(expression, activation)
|
|
192
|
+
if not isinstance(result, celtypes.BoolType):
|
|
193
|
+
raise ExpressionError(expression, f"expected a boolean, got {type(result).__name__}")
|
|
194
|
+
return bool(result)
|
|
195
|
+
|
|
196
|
+
def _program(self, expression: str) -> Any:
|
|
197
|
+
"""Return the cached compiled program for an expression, compiling it if needed."""
|
|
198
|
+
program = self._programs.get(expression)
|
|
199
|
+
if program is None:
|
|
200
|
+
try:
|
|
201
|
+
ast = self._env.compile(expression)
|
|
202
|
+
program = self._env.program(ast, functions=self._functions)
|
|
203
|
+
except _CEL_ERRORS as error:
|
|
204
|
+
raise ExpressionError(expression, f"invalid expression: {error}") from error
|
|
205
|
+
self._programs[expression] = program
|
|
206
|
+
return program
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Canonical hashing so identical inputs always produce identical hashes (replayability)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from datetime import datetime, timedelta
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _normalise(value: Any) -> Any:
|
|
15
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
16
|
+
return {f.name: _normalise(getattr(value, f.name)) for f in dataclasses.fields(value)}
|
|
17
|
+
if isinstance(value, Enum):
|
|
18
|
+
return value.value
|
|
19
|
+
if isinstance(value, datetime):
|
|
20
|
+
if value.tzinfo is None:
|
|
21
|
+
raise ValueError("naive datetimes are not allowed; use timezone-aware UTC times")
|
|
22
|
+
return {"$ts": value.isoformat()}
|
|
23
|
+
if isinstance(value, timedelta):
|
|
24
|
+
# Normalise the number too, so 120 s and 120.0 s hash identically.
|
|
25
|
+
return {"$dur": _normalise(value.total_seconds())}
|
|
26
|
+
if isinstance(value, Mapping):
|
|
27
|
+
return {str(k): _normalise(v) for k, v in value.items()}
|
|
28
|
+
if isinstance(value, (list, tuple)):
|
|
29
|
+
return [_normalise(v) for v in value]
|
|
30
|
+
if isinstance(value, float) and value.is_integer():
|
|
31
|
+
return int(value)
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def canonical_json(value: Any) -> str:
|
|
36
|
+
"""Serialise with sorted keys and no insignificant whitespace."""
|
|
37
|
+
return json.dumps(_normalise(value), sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def sha256_hex(value: Any) -> str:
|
|
41
|
+
return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Domain-neutral data model.
|
|
2
|
+
|
|
3
|
+
Every agent type (coding, customer-facing, tool-using, ...) is described with the same
|
|
4
|
+
objects: an Episode (one unit of agent work), Claims the agent made, Evidence observed in
|
|
5
|
+
the systems the agent acted on, and Verdicts produced by Checks.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
from enum import StrEnum
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Result(StrEnum):
|
|
18
|
+
"""Outcome of a check or a verdict."""
|
|
19
|
+
|
|
20
|
+
VERIFIED = "VERIFIED"
|
|
21
|
+
CONTRADICTED = "CONTRADICTED"
|
|
22
|
+
PENDING = "PENDING"
|
|
23
|
+
UNVERIFIABLE = "UNVERIFIABLE"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CheckKind(StrEnum):
|
|
27
|
+
RULE = "rule"
|
|
28
|
+
STATE = "state"
|
|
29
|
+
TEMPORAL = "temporal"
|
|
30
|
+
JUDGE = "judge"
|
|
31
|
+
HUMAN = "human"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# Kinds whose results may decide a verdict on their own. Judge checks are shadow-only in v1.
|
|
35
|
+
DETERMINISTIC_KINDS = frozenset(
|
|
36
|
+
{CheckKind.RULE, CheckKind.STATE, CheckKind.TEMPORAL, CheckKind.HUMAN}
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Level(StrEnum):
|
|
41
|
+
L1 = "L1" # output quality
|
|
42
|
+
L2 = "L2" # instruction / policy adherence
|
|
43
|
+
L3 = "L3" # action correctness
|
|
44
|
+
L4 = "L4" # effect happened in the system of record
|
|
45
|
+
L5 = "L5" # effect stayed true over time
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Episode:
|
|
50
|
+
"""One unit of agent work (a pull request, a conversation, a task run)."""
|
|
51
|
+
|
|
52
|
+
id: str
|
|
53
|
+
kind: str
|
|
54
|
+
agent: str
|
|
55
|
+
opened_at: datetime
|
|
56
|
+
closed_at: datetime | None = None
|
|
57
|
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class Claim:
|
|
62
|
+
"""Something the agent asserted about its work."""
|
|
63
|
+
|
|
64
|
+
id: str
|
|
65
|
+
episode_id: str
|
|
66
|
+
type: str
|
|
67
|
+
made_at: datetime
|
|
68
|
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
|
69
|
+
origin: str = "unknown" # where the claim came from (e.g. title, body, transcript)
|
|
70
|
+
span: str | None = None # the exact text supporting the claim
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Evidence:
|
|
75
|
+
"""An observation from a system of record, at a point in time."""
|
|
76
|
+
|
|
77
|
+
record_type: str
|
|
78
|
+
external_ref: str
|
|
79
|
+
observed_at: datetime
|
|
80
|
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
|
81
|
+
occurred_at: datetime | None = None
|
|
82
|
+
version: int = 1 # higher version = later observation of the same record
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class CheckRun:
|
|
87
|
+
"""One evaluation of one check against one claim, with frozen, hashed inputs."""
|
|
88
|
+
|
|
89
|
+
check_id: str
|
|
90
|
+
check_version: str
|
|
91
|
+
kind: CheckKind
|
|
92
|
+
level: Level
|
|
93
|
+
claim_id: str
|
|
94
|
+
result: Result
|
|
95
|
+
reason: str
|
|
96
|
+
inputs_hash: str
|
|
97
|
+
derived: Mapping[str, Any] = field(default_factory=dict)
|
|
98
|
+
explanation: str | None = None
|
|
99
|
+
role: str = "check" # "check" decides a claim; "guard" may only withdraw a VERIFIED
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class Verdict:
|
|
104
|
+
"""The aggregate result for a claim."""
|
|
105
|
+
|
|
106
|
+
claim_id: str
|
|
107
|
+
result: Result
|
|
108
|
+
reasons: tuple[str, ...]
|
|
109
|
+
check_runs: tuple[CheckRun, ...]
|
|
110
|
+
# Reasons of optional guards that found something: shown next to the result as a caution,
|
|
111
|
+
# never changing it (for example "this PR changed CI configuration").
|
|
112
|
+
caveats: tuple[str, ...] = ()
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Pack loading: how domain logic plugs into the domain-neutral core.
|
|
2
|
+
|
|
3
|
+
A pack is a directory with a ``pack.yaml`` manifest, for example::
|
|
4
|
+
|
|
5
|
+
id: customer_support_demo
|
|
6
|
+
version: 0.1.0
|
|
7
|
+
kind: agent_type # or: overlay
|
|
8
|
+
description: Refund claims made by support agents.
|
|
9
|
+
claim_types: [REFUND_ISSUED]
|
|
10
|
+
checks:
|
|
11
|
+
- checks/refund_issued.yaml
|
|
12
|
+
functions: my_package.my_pack:register # optional: adds CEL helper functions
|
|
13
|
+
|
|
14
|
+
Each check file holds one check definition or a list of them. Check ids must start with the
|
|
15
|
+
pack id (``customer_support_demo.refund_issued``) so packs can never clash, and every check
|
|
16
|
+
must apply only to claim types the pack declares.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import importlib
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Callable, Iterable
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import yaml
|
|
29
|
+
|
|
30
|
+
from second_source.core.checks import CheckDefinition, CheckDefinitionError
|
|
31
|
+
from second_source.core.expr import FunctionRegistry
|
|
32
|
+
|
|
33
|
+
PACK_KINDS = frozenset({"agent_type", "overlay"})
|
|
34
|
+
_PACK_ID = re.compile(r"^[a-z][a-z0-9_]*$")
|
|
35
|
+
_VERSION = re.compile(r"^\d+\.\d+\.\d+$")
|
|
36
|
+
_FUNCTION_REF = re.compile(r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$") # "module.path:callable"
|
|
37
|
+
|
|
38
|
+
RegisterFunctions = Callable[[FunctionRegistry], None]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PackError(ValueError):
|
|
42
|
+
"""A pack manifest or one of its files is invalid."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Pack:
|
|
47
|
+
id: str
|
|
48
|
+
version: str
|
|
49
|
+
kind: str
|
|
50
|
+
claim_types: tuple[str, ...]
|
|
51
|
+
checks: tuple[CheckDefinition, ...]
|
|
52
|
+
description: str = ""
|
|
53
|
+
register_functions: RegisterFunctions | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_pack(directory: str | Path) -> Pack:
|
|
57
|
+
"""Load and validate a pack from a directory. Raises PackError with a clear message."""
|
|
58
|
+
root = Path(directory).resolve()
|
|
59
|
+
manifest = _read_yaml(root / "pack.yaml")
|
|
60
|
+
if not isinstance(manifest, dict):
|
|
61
|
+
raise PackError(f"{root / 'pack.yaml'}: expected a mapping")
|
|
62
|
+
|
|
63
|
+
pack_id = str(manifest.get("id", ""))
|
|
64
|
+
|
|
65
|
+
def fail(problem: str) -> PackError:
|
|
66
|
+
return PackError(f"pack {pack_id or root.name}: {problem}")
|
|
67
|
+
|
|
68
|
+
# Manifest fields.
|
|
69
|
+
if not _PACK_ID.match(pack_id):
|
|
70
|
+
raise fail("id must be lower_snake_case")
|
|
71
|
+
version = str(manifest.get("version", ""))
|
|
72
|
+
if not _VERSION.match(version):
|
|
73
|
+
raise fail("version must be semantic, e.g. '0.1.0'")
|
|
74
|
+
kind = manifest.get("kind")
|
|
75
|
+
if kind not in PACK_KINDS:
|
|
76
|
+
raise fail(f"kind must be one of {sorted(PACK_KINDS)}")
|
|
77
|
+
claim_types = manifest.get("claim_types") or []
|
|
78
|
+
if not claim_types or not all(isinstance(t, str) and t for t in claim_types):
|
|
79
|
+
raise fail("claim_types must be a non-empty list")
|
|
80
|
+
|
|
81
|
+
# Check files: resolved inside the pack directory only (no path traversal).
|
|
82
|
+
checks: list[CheckDefinition] = []
|
|
83
|
+
for relative in manifest.get("checks") or []:
|
|
84
|
+
path = (root / str(relative)).resolve()
|
|
85
|
+
if root not in path.parents:
|
|
86
|
+
raise fail(f"check file {relative!r} is outside the pack directory")
|
|
87
|
+
for raw in _as_list(_read_yaml(path)):
|
|
88
|
+
try:
|
|
89
|
+
check = CheckDefinition.from_dict(raw)
|
|
90
|
+
except CheckDefinitionError as error:
|
|
91
|
+
raise fail(f"{relative}: {error}") from error
|
|
92
|
+
if not check.id.startswith(f"{pack_id}."):
|
|
93
|
+
raise fail(f"check {check.id} must be named '{pack_id}.<name>'")
|
|
94
|
+
unknown = set(check.applies_to) - set(claim_types)
|
|
95
|
+
if unknown:
|
|
96
|
+
raise fail(f"check {check.id} applies to undeclared claim types {sorted(unknown)}")
|
|
97
|
+
checks.append(check)
|
|
98
|
+
|
|
99
|
+
# Optional Python hook that registers CEL helper functions.
|
|
100
|
+
register = None
|
|
101
|
+
reference = manifest.get("functions")
|
|
102
|
+
if reference:
|
|
103
|
+
register = _import_callable(str(reference), fail)
|
|
104
|
+
|
|
105
|
+
return Pack(
|
|
106
|
+
id=pack_id,
|
|
107
|
+
version=version,
|
|
108
|
+
kind=kind,
|
|
109
|
+
claim_types=tuple(claim_types),
|
|
110
|
+
checks=tuple(checks),
|
|
111
|
+
description=str(manifest.get("description", "")),
|
|
112
|
+
register_functions=register,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def build_function_registry(packs: Iterable[Pack]) -> FunctionRegistry:
|
|
117
|
+
"""Collect every pack's helper functions into one registry (name clashes are errors)."""
|
|
118
|
+
registry = FunctionRegistry()
|
|
119
|
+
for pack in packs:
|
|
120
|
+
if pack.register_functions is not None:
|
|
121
|
+
pack.register_functions(registry)
|
|
122
|
+
return registry
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_yaml(path: Path) -> Any:
|
|
126
|
+
"""Read a YAML file with the safe loader (never executes tags)."""
|
|
127
|
+
try:
|
|
128
|
+
with path.open(encoding="utf-8") as handle:
|
|
129
|
+
return yaml.safe_load(handle)
|
|
130
|
+
except FileNotFoundError as error:
|
|
131
|
+
raise PackError(f"{path}: file not found") from error
|
|
132
|
+
except yaml.YAMLError as error:
|
|
133
|
+
raise PackError(f"{path}: invalid YAML: {error}") from error
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _as_list(value: Any) -> list[dict[str, Any]]:
|
|
137
|
+
"""A check file may contain one definition (a mapping) or several (a list)."""
|
|
138
|
+
if isinstance(value, dict):
|
|
139
|
+
return [value]
|
|
140
|
+
if isinstance(value, list) and all(isinstance(item, dict) for item in value):
|
|
141
|
+
return value
|
|
142
|
+
raise PackError("a check file must contain a mapping or a list of mappings")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _import_callable(reference: str, fail: Callable[[str], PackError]) -> RegisterFunctions:
|
|
146
|
+
"""Import ``module.path:callable``. Packs are trusted code shipped with the package."""
|
|
147
|
+
if not _FUNCTION_REF.match(reference):
|
|
148
|
+
raise fail(f"functions must look like 'module.path:callable', got {reference!r}")
|
|
149
|
+
module_name, attribute = reference.split(":")
|
|
150
|
+
try:
|
|
151
|
+
function = getattr(importlib.import_module(module_name), attribute)
|
|
152
|
+
except (ImportError, AttributeError) as error:
|
|
153
|
+
raise fail(f"cannot import {reference!r}: {error}") from error
|
|
154
|
+
if not callable(function):
|
|
155
|
+
raise fail(f"{reference!r} is not callable")
|
|
156
|
+
return function
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Agent-type packs and industry overlays (domain logic lives here, not in core)."""
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Coding pack: verify claims made by coding agents in pull requests.
|
|
2
|
+
|
|
3
|
+
See docs/packs/coding.md for the design and the evidence contract.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from second_source.core.pack import Pack, load_pack
|
|
9
|
+
|
|
10
|
+
# The pack's manifest and check files live next to this module.
|
|
11
|
+
PACK_DIR = Path(__file__).parent
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load() -> Pack:
|
|
15
|
+
"""Load the coding pack shipped with Second Source."""
|
|
16
|
+
return load_pack(PACK_DIR)
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Optional guards: integrity cautions shown next to a result, never changing it.
|
|
2
|
+
#
|
|
3
|
+
# These signals are real but too common or not yet measured to withdraw a verification
|
|
4
|
+
# (CI or test configuration changes in about 6-17% of agent PRs). Each is its own optional
|
|
5
|
+
# guard so a claim can carry several cautions. A signal moves to a required guard only after
|
|
6
|
+
# audited precision of at least 0.90 on at least 30 flagged PRs (docs/packs/coding.md).
|
|
7
|
+
id: coding.ci_config_caution
|
|
8
|
+
version: 1.1.0
|
|
9
|
+
kind: state
|
|
10
|
+
role: guard
|
|
11
|
+
required: false
|
|
12
|
+
level: L4
|
|
13
|
+
applies_to: [TESTS_PASS, BUILD_OK, LINT_OK]
|
|
14
|
+
evidence:
|
|
15
|
+
summary:
|
|
16
|
+
record_type: changed_files_summary
|
|
17
|
+
derive:
|
|
18
|
+
# Field reads are guarded by has(): an older or newer summary must not error.
|
|
19
|
+
s: "size(summary) > 0 ? summary[0] : {}"
|
|
20
|
+
changed: "size(summary) > 0 && (has(s.ci_config_changed) ? s.ci_config_changed : false)"
|
|
21
|
+
outcomes:
|
|
22
|
+
- {when: "changed", result: UNVERIFIABLE, reason: PR_CHANGES_CI_CONFIG}
|
|
23
|
+
- {otherwise: true, result: VERIFIED, reason: CI_CONFIG_UNCHANGED}
|