casekit 0.9.1__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.
- casekit/__init__.py +8 -0
- casekit/caps.py +60 -0
- casekit/decision_log.py +237 -0
- casekit/evidence.py +29 -0
- casekit/export.py +146 -0
- casekit/fetch.py +229 -0
- casekit/jsonschema/case-1.0.json +274 -0
- casekit/narrative.py +76 -0
- casekit/py.typed +0 -0
- casekit/schema.py +187 -0
- casekit/scoring.py +60 -0
- casekit/text.py +161 -0
- casekit-0.9.1.dist-info/METADATA +49 -0
- casekit-0.9.1.dist-info/RECORD +16 -0
- casekit-0.9.1.dist-info/WHEEL +4 -0
- casekit-0.9.1.dist-info/licenses/LICENSE +21 -0
casekit/fetch.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
"""Bounded HTTP fetching: the one module in casekit that touches the network.
|
|
2
|
+
|
|
3
|
+
Every request is checked against a scheme + host allowlist before it is sent. Responses are
|
|
4
|
+
read in chunks under a size cap and one total deadline (shared by all redirect hops), on top
|
|
5
|
+
of the per-operation socket timeout. Redirects are refused unless `max_redirects` > 0; then
|
|
6
|
+
every hop is checked against the allowlist, https -> http is refused, and on any origin
|
|
7
|
+
change (scheme, host or port) only SAFE_HEADERS survive and a request body is never resent.
|
|
8
|
+
URLs with userinfo, whitespace or control characters are refused. The default transport
|
|
9
|
+
ignores proxy environment variables, so traffic can't leave through a proxy the allowlist
|
|
10
|
+
never saw.
|
|
11
|
+
|
|
12
|
+
Not covered (caller's job): DNS rebinding / internal addresses behind an allowed name. Only
|
|
13
|
+
allowlist names you control or trust.
|
|
14
|
+
|
|
15
|
+
The transport is injectable (stdlib by default, no HTTP client dependency): a callable
|
|
16
|
+
`transport(request, timeout=...)` returning a context-managed response with `.status`,
|
|
17
|
+
`.headers` and `.read(n)`, raising urllib.error.HTTPError/URLError like `urlopen`.
|
|
18
|
+
Error messages carry the method, host and path only: never the query string or headers.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import http.client
|
|
24
|
+
import json
|
|
25
|
+
import re
|
|
26
|
+
import time
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.parse
|
|
29
|
+
import urllib.request
|
|
30
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
31
|
+
from dataclasses import dataclass, field
|
|
32
|
+
from typing import Any
|
|
33
|
+
|
|
34
|
+
DEFAULT_MAX_BYTES = 10 * 1024 * 1024
|
|
35
|
+
DEFAULT_TIMEOUT_S = 30.0 # per socket operation
|
|
36
|
+
DEFAULT_TOTAL_TIMEOUT_S = 120.0 # whole call, all hops
|
|
37
|
+
CHUNK_BYTES = 64 * 1024
|
|
38
|
+
REDIRECT_CODES = frozenset({301, 302, 303, 307, 308})
|
|
39
|
+
SAFE_HEADERS = frozenset({"accept", "accept-language", "user-agent", "content-type"})
|
|
40
|
+
_HOSTNAME = re.compile(
|
|
41
|
+
r"^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$"
|
|
42
|
+
)
|
|
43
|
+
_UNSAFE_URL = re.compile(r"[\x00-\x20\x7f]")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class FetchError(RuntimeError):
|
|
47
|
+
"""A fetch failed or was refused. `status` is the HTTP status when there was one."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, message: str, status: int | None = None) -> None:
|
|
50
|
+
super().__init__(message)
|
|
51
|
+
self.status = status
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class Response:
|
|
56
|
+
status: int
|
|
57
|
+
url: str
|
|
58
|
+
body: bytes
|
|
59
|
+
headers: Mapping[str, str] = field(default_factory=dict) # lower-cased names
|
|
60
|
+
|
|
61
|
+
def text(self, encoding: str = "utf-8") -> str:
|
|
62
|
+
return self.body.decode(encoding, errors="replace")
|
|
63
|
+
|
|
64
|
+
def json(self) -> Any:
|
|
65
|
+
try:
|
|
66
|
+
return json.loads(self.body)
|
|
67
|
+
except (ValueError, RecursionError):
|
|
68
|
+
raise FetchError(f"{_redact(self.url)} returned invalid JSON") from None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
72
|
+
"""Never follow a redirect inside urllib: it would copy credentials to the new host."""
|
|
73
|
+
|
|
74
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# ProxyHandler({}) = ignore HTTP(S)_PROXY from the environment.
|
|
79
|
+
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect)
|
|
80
|
+
_DEFAULT_TRANSPORT: Callable[..., Any] = _OPENER.open
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _redact(url: str) -> str:
|
|
84
|
+
parts = urllib.parse.urlsplit(url)
|
|
85
|
+
return f"{parts.scheme}://{parts.hostname or ''}{parts.path}"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _names(value: Iterable[str], what: str) -> frozenset[str]:
|
|
89
|
+
if isinstance(value, (str, bytes)):
|
|
90
|
+
raise TypeError(f"{what} must be a collection of names, not a single string")
|
|
91
|
+
return frozenset(str(v).lower().rstrip(".") for v in value)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _allowlist(hosts: Iterable[str]) -> frozenset[str]:
|
|
95
|
+
names = _names(hosts, "allowed_hosts")
|
|
96
|
+
if not names:
|
|
97
|
+
raise ValueError("allowed_hosts must name at least one host")
|
|
98
|
+
bad = sorted(n for n in names if not _HOSTNAME.match(n))
|
|
99
|
+
if bad:
|
|
100
|
+
raise ValueError(f"allowed_hosts entries must be bare hostnames: {bad[:3]}")
|
|
101
|
+
return names
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
Origin = tuple[str, str, int]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _checked(url: str, schemes: frozenset[str], hosts: frozenset[str]) -> Origin:
|
|
108
|
+
if _UNSAFE_URL.search(url):
|
|
109
|
+
raise FetchError("URL contains whitespace or control characters")
|
|
110
|
+
try:
|
|
111
|
+
parts = urllib.parse.urlsplit(url)
|
|
112
|
+
host = (parts.hostname or "").lower().rstrip(".")
|
|
113
|
+
port = parts.port
|
|
114
|
+
except ValueError:
|
|
115
|
+
raise FetchError("malformed URL") from None
|
|
116
|
+
scheme = parts.scheme.lower()
|
|
117
|
+
if scheme not in schemes:
|
|
118
|
+
raise FetchError(f"scheme {parts.scheme!r} is not allowed")
|
|
119
|
+
if parts.username is not None or parts.password is not None:
|
|
120
|
+
raise FetchError("credentials in the URL are not allowed; send them as a header")
|
|
121
|
+
if host not in hosts:
|
|
122
|
+
raise FetchError(f"host {host!r} is not allowed")
|
|
123
|
+
return scheme, host, port or (443 if scheme == "https" else 80)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _headers_of(obj: Any) -> dict[str, str]:
|
|
127
|
+
return {k.lower(): v for k, v in (obj.items() if obj is not None else [])}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _read_body(resp: Any, where: str, max_bytes: int, deadline: float) -> bytes:
|
|
131
|
+
chunks: list[bytes] = []
|
|
132
|
+
total = 0
|
|
133
|
+
while True:
|
|
134
|
+
if time.monotonic() > deadline:
|
|
135
|
+
raise FetchError(f"{where}: total deadline exceeded")
|
|
136
|
+
chunk = resp.read(min(CHUNK_BYTES, max_bytes + 1 - total))
|
|
137
|
+
if not chunk:
|
|
138
|
+
return b"".join(chunks)
|
|
139
|
+
total += len(chunk)
|
|
140
|
+
if total > max_bytes:
|
|
141
|
+
raise FetchError(f"{where}: response too large (limit {max_bytes} bytes)")
|
|
142
|
+
chunks.append(chunk)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _send(
|
|
146
|
+
transport: Callable[..., Any],
|
|
147
|
+
request: urllib.request.Request,
|
|
148
|
+
timeout: float,
|
|
149
|
+
max_bytes: int,
|
|
150
|
+
deadline: float,
|
|
151
|
+
) -> tuple[int, dict[str, str], bytes]:
|
|
152
|
+
where = f"{request.get_method()} {_redact(request.full_url)}"
|
|
153
|
+
try:
|
|
154
|
+
with transport(request, timeout=timeout) as resp:
|
|
155
|
+
headers = _headers_of(resp.headers)
|
|
156
|
+
status = int(getattr(resp, "status", 200))
|
|
157
|
+
if status in REDIRECT_CODES:
|
|
158
|
+
return status, headers, b""
|
|
159
|
+
length = headers.get("content-length", "")
|
|
160
|
+
if length.isdigit() and int(length) > max_bytes:
|
|
161
|
+
raise FetchError(f"{where}: response too large (limit {max_bytes} bytes)")
|
|
162
|
+
return status, headers, _read_body(resp, where, max_bytes, deadline)
|
|
163
|
+
except urllib.error.HTTPError as exc:
|
|
164
|
+
headers = _headers_of(exc.headers)
|
|
165
|
+
exc.close()
|
|
166
|
+
if exc.code in REDIRECT_CODES:
|
|
167
|
+
return exc.code, headers, b""
|
|
168
|
+
raise FetchError(f"{where}: HTTP {exc.code}", status=exc.code) from None
|
|
169
|
+
except urllib.error.URLError as exc:
|
|
170
|
+
raise FetchError(f"{where}: {exc.reason}") from None
|
|
171
|
+
except (OSError, http.client.HTTPException, ValueError) as exc:
|
|
172
|
+
raise FetchError(f"{where}: {type(exc).__name__}") from None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _next_hop(
|
|
176
|
+
status: int, url: str, location: str | None, method: str, body: bytes | None
|
|
177
|
+
) -> tuple[str, str, bytes | None]:
|
|
178
|
+
if not location:
|
|
179
|
+
raise FetchError(f"{method} {_redact(url)}: redirect without a Location")
|
|
180
|
+
if status == 303 or (status in (301, 302) and method == "POST"):
|
|
181
|
+
method, body = "GET", None
|
|
182
|
+
return urllib.parse.urljoin(url, location), method, body
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def fetch(
|
|
186
|
+
url: str,
|
|
187
|
+
*,
|
|
188
|
+
allowed_hosts: Iterable[str],
|
|
189
|
+
method: str = "GET",
|
|
190
|
+
headers: Mapping[str, str] | None = None,
|
|
191
|
+
body: bytes | None = None,
|
|
192
|
+
max_bytes: int = DEFAULT_MAX_BYTES,
|
|
193
|
+
timeout: float = DEFAULT_TIMEOUT_S,
|
|
194
|
+
total_timeout: float = DEFAULT_TOTAL_TIMEOUT_S,
|
|
195
|
+
max_redirects: int = 0,
|
|
196
|
+
schemes: Iterable[str] = ("https",),
|
|
197
|
+
transport: Callable[..., Any] | None = None,
|
|
198
|
+
) -> Response:
|
|
199
|
+
"""One bounded request (plus at most `max_redirects` checked hops)."""
|
|
200
|
+
hosts = _allowlist(allowed_hosts)
|
|
201
|
+
allowed_schemes = _names(schemes, "schemes")
|
|
202
|
+
if max_bytes <= 0 or timeout <= 0 or total_timeout <= 0 or max_redirects < 0:
|
|
203
|
+
raise ValueError("max_bytes and timeouts must be positive; max_redirects >= 0")
|
|
204
|
+
deadline = time.monotonic() + total_timeout
|
|
205
|
+
send = transport or _DEFAULT_TRANSPORT
|
|
206
|
+
current_headers = dict(headers or {})
|
|
207
|
+
origin = _checked(url, allowed_schemes, hosts)
|
|
208
|
+
for hop in range(max_redirects + 1):
|
|
209
|
+
# S310: the scheme and host of this hop were checked by _checked.
|
|
210
|
+
request = urllib.request.Request(url, data=body, headers=current_headers, method=method) # noqa: S310
|
|
211
|
+
status, response_headers, data = _send(send, request, timeout, max_bytes, deadline)
|
|
212
|
+
if status not in REDIRECT_CODES:
|
|
213
|
+
return Response(status=status, url=url, body=data, headers=response_headers)
|
|
214
|
+
if max_redirects == 0:
|
|
215
|
+
raise FetchError(f"{method} {_redact(url)}: got a redirect; redirects are disabled")
|
|
216
|
+
if hop == max_redirects:
|
|
217
|
+
break
|
|
218
|
+
url, method, body = _next_hop(status, url, response_headers.get("location"), method, body)
|
|
219
|
+
new_origin = _checked(url, allowed_schemes, hosts)
|
|
220
|
+
if origin[0] == "https" and new_origin[0] != "https":
|
|
221
|
+
raise FetchError(f"{method} {_redact(url)}: refusing an https -> http downgrade")
|
|
222
|
+
if new_origin != origin:
|
|
223
|
+
if body is not None:
|
|
224
|
+
raise FetchError(f"{method} {_redact(url)}: refusing to resend a body cross-origin")
|
|
225
|
+
current_headers = {
|
|
226
|
+
k: v for k, v in current_headers.items() if k.lower() in SAFE_HEADERS
|
|
227
|
+
}
|
|
228
|
+
origin = new_origin
|
|
229
|
+
raise FetchError(f"{method} {_redact(url)}: too many redirects (limit {max_redirects})")
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$defs": {
|
|
3
|
+
"Claim": {
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"description": "One statement in a narrative. Evidence-backed claims must cite evidence IDs.",
|
|
6
|
+
"properties": {
|
|
7
|
+
"evidence_backed": {
|
|
8
|
+
"default": true,
|
|
9
|
+
"title": "Evidence Backed",
|
|
10
|
+
"type": "boolean"
|
|
11
|
+
},
|
|
12
|
+
"evidence_ids": {
|
|
13
|
+
"default": [],
|
|
14
|
+
"items": {
|
|
15
|
+
"maxLength": 500,
|
|
16
|
+
"minLength": 1,
|
|
17
|
+
"type": "string"
|
|
18
|
+
},
|
|
19
|
+
"maxItems": 10000,
|
|
20
|
+
"title": "Evidence Ids",
|
|
21
|
+
"type": "array"
|
|
22
|
+
},
|
|
23
|
+
"text": {
|
|
24
|
+
"maxLength": 2000,
|
|
25
|
+
"title": "Text",
|
|
26
|
+
"type": "string"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"required": [
|
|
30
|
+
"text"
|
|
31
|
+
],
|
|
32
|
+
"title": "Claim",
|
|
33
|
+
"type": "object"
|
|
34
|
+
},
|
|
35
|
+
"Decision": {
|
|
36
|
+
"additionalProperties": false,
|
|
37
|
+
"description": "A human judgement about an item, as recorded in a decision log.",
|
|
38
|
+
"properties": {
|
|
39
|
+
"actor": {
|
|
40
|
+
"maxLength": 80,
|
|
41
|
+
"minLength": 1,
|
|
42
|
+
"title": "Actor",
|
|
43
|
+
"type": "string"
|
|
44
|
+
},
|
|
45
|
+
"data_as_of": {
|
|
46
|
+
"anyOf": [
|
|
47
|
+
{
|
|
48
|
+
"format": "date-time",
|
|
49
|
+
"type": "string"
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"type": "null"
|
|
53
|
+
}
|
|
54
|
+
],
|
|
55
|
+
"default": null,
|
|
56
|
+
"title": "Data As Of"
|
|
57
|
+
},
|
|
58
|
+
"decision": {
|
|
59
|
+
"maxLength": 500,
|
|
60
|
+
"minLength": 1,
|
|
61
|
+
"title": "Decision",
|
|
62
|
+
"type": "string"
|
|
63
|
+
},
|
|
64
|
+
"item_id": {
|
|
65
|
+
"maxLength": 500,
|
|
66
|
+
"minLength": 1,
|
|
67
|
+
"title": "Item Id",
|
|
68
|
+
"type": "string"
|
|
69
|
+
},
|
|
70
|
+
"kind": {
|
|
71
|
+
"maxLength": 500,
|
|
72
|
+
"minLength": 1,
|
|
73
|
+
"title": "Kind",
|
|
74
|
+
"type": "string"
|
|
75
|
+
},
|
|
76
|
+
"note": {
|
|
77
|
+
"default": "",
|
|
78
|
+
"maxLength": 2000,
|
|
79
|
+
"title": "Note",
|
|
80
|
+
"type": "string"
|
|
81
|
+
},
|
|
82
|
+
"recorded_at": {
|
|
83
|
+
"format": "date-time",
|
|
84
|
+
"title": "Recorded At",
|
|
85
|
+
"type": "string"
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
"required": [
|
|
89
|
+
"item_id",
|
|
90
|
+
"kind",
|
|
91
|
+
"decision",
|
|
92
|
+
"actor",
|
|
93
|
+
"recorded_at"
|
|
94
|
+
],
|
|
95
|
+
"title": "Decision",
|
|
96
|
+
"type": "object"
|
|
97
|
+
},
|
|
98
|
+
"Evidence": {
|
|
99
|
+
"additionalProperties": false,
|
|
100
|
+
"description": "A pointer to one source record that supports a case.",
|
|
101
|
+
"properties": {
|
|
102
|
+
"record_id": {
|
|
103
|
+
"maxLength": 500,
|
|
104
|
+
"minLength": 1,
|
|
105
|
+
"title": "Record Id",
|
|
106
|
+
"type": "string"
|
|
107
|
+
},
|
|
108
|
+
"sha256": {
|
|
109
|
+
"anyOf": [
|
|
110
|
+
{
|
|
111
|
+
"pattern": "^[0-9a-f]{64}$",
|
|
112
|
+
"type": "string"
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
"type": "null"
|
|
116
|
+
}
|
|
117
|
+
],
|
|
118
|
+
"default": null,
|
|
119
|
+
"title": "Sha256"
|
|
120
|
+
},
|
|
121
|
+
"source": {
|
|
122
|
+
"maxLength": 500,
|
|
123
|
+
"minLength": 1,
|
|
124
|
+
"title": "Source",
|
|
125
|
+
"type": "string"
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
"required": [
|
|
129
|
+
"source",
|
|
130
|
+
"record_id"
|
|
131
|
+
],
|
|
132
|
+
"title": "Evidence",
|
|
133
|
+
"type": "object"
|
|
134
|
+
},
|
|
135
|
+
"Narrative": {
|
|
136
|
+
"additionalProperties": false,
|
|
137
|
+
"properties": {
|
|
138
|
+
"claims": {
|
|
139
|
+
"items": {
|
|
140
|
+
"$ref": "#/$defs/Claim"
|
|
141
|
+
},
|
|
142
|
+
"maxItems": 10000,
|
|
143
|
+
"title": "Claims",
|
|
144
|
+
"type": "array"
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
"required": [
|
|
148
|
+
"claims"
|
|
149
|
+
],
|
|
150
|
+
"title": "Narrative",
|
|
151
|
+
"type": "object"
|
|
152
|
+
},
|
|
153
|
+
"ScoreBreakdown": {
|
|
154
|
+
"additionalProperties": false,
|
|
155
|
+
"description": "A total that always travels with the components that produced it.",
|
|
156
|
+
"properties": {
|
|
157
|
+
"components": {
|
|
158
|
+
"items": {
|
|
159
|
+
"$ref": "#/$defs/ScoreComponent"
|
|
160
|
+
},
|
|
161
|
+
"maxItems": 10000,
|
|
162
|
+
"title": "Components",
|
|
163
|
+
"type": "array"
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
"required": [
|
|
167
|
+
"components"
|
|
168
|
+
],
|
|
169
|
+
"title": "ScoreBreakdown",
|
|
170
|
+
"type": "object"
|
|
171
|
+
},
|
|
172
|
+
"ScoreComponent": {
|
|
173
|
+
"additionalProperties": false,
|
|
174
|
+
"description": "One scored factor: a 0..1 value times its weight.",
|
|
175
|
+
"properties": {
|
|
176
|
+
"detail": {
|
|
177
|
+
"maxLength": 2000,
|
|
178
|
+
"title": "Detail",
|
|
179
|
+
"type": "string"
|
|
180
|
+
},
|
|
181
|
+
"name": {
|
|
182
|
+
"maxLength": 500,
|
|
183
|
+
"minLength": 1,
|
|
184
|
+
"title": "Name",
|
|
185
|
+
"type": "string"
|
|
186
|
+
},
|
|
187
|
+
"raw": {
|
|
188
|
+
"maximum": 1.0,
|
|
189
|
+
"minimum": 0.0,
|
|
190
|
+
"title": "Raw",
|
|
191
|
+
"type": "number"
|
|
192
|
+
},
|
|
193
|
+
"weight": {
|
|
194
|
+
"maximum": 1000,
|
|
195
|
+
"minimum": 0,
|
|
196
|
+
"title": "Weight",
|
|
197
|
+
"type": "integer"
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
"required": [
|
|
201
|
+
"name",
|
|
202
|
+
"weight",
|
|
203
|
+
"raw",
|
|
204
|
+
"detail"
|
|
205
|
+
],
|
|
206
|
+
"title": "ScoreComponent",
|
|
207
|
+
"type": "object"
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
"$id": "urn:casekit:case:1.0",
|
|
211
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
212
|
+
"additionalProperties": false,
|
|
213
|
+
"description": "A ranked, evidence-backed case.",
|
|
214
|
+
"properties": {
|
|
215
|
+
"case_id": {
|
|
216
|
+
"maxLength": 500,
|
|
217
|
+
"minLength": 1,
|
|
218
|
+
"title": "Case Id",
|
|
219
|
+
"type": "string"
|
|
220
|
+
},
|
|
221
|
+
"decisions": {
|
|
222
|
+
"default": [],
|
|
223
|
+
"items": {
|
|
224
|
+
"$ref": "#/$defs/Decision"
|
|
225
|
+
},
|
|
226
|
+
"maxItems": 10000,
|
|
227
|
+
"title": "Decisions",
|
|
228
|
+
"type": "array"
|
|
229
|
+
},
|
|
230
|
+
"evidence": {
|
|
231
|
+
"items": {
|
|
232
|
+
"$ref": "#/$defs/Evidence"
|
|
233
|
+
},
|
|
234
|
+
"maxItems": 10000,
|
|
235
|
+
"minItems": 1,
|
|
236
|
+
"title": "Evidence",
|
|
237
|
+
"type": "array"
|
|
238
|
+
},
|
|
239
|
+
"narrative": {
|
|
240
|
+
"anyOf": [
|
|
241
|
+
{
|
|
242
|
+
"$ref": "#/$defs/Narrative"
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
"type": "null"
|
|
246
|
+
}
|
|
247
|
+
],
|
|
248
|
+
"default": null
|
|
249
|
+
},
|
|
250
|
+
"schema_version": {
|
|
251
|
+
"const": "1.0",
|
|
252
|
+
"default": "1.0",
|
|
253
|
+
"title": "Schema Version",
|
|
254
|
+
"type": "string"
|
|
255
|
+
},
|
|
256
|
+
"score": {
|
|
257
|
+
"$ref": "#/$defs/ScoreBreakdown"
|
|
258
|
+
},
|
|
259
|
+
"title": {
|
|
260
|
+
"maxLength": 500,
|
|
261
|
+
"minLength": 1,
|
|
262
|
+
"title": "Title",
|
|
263
|
+
"type": "string"
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
"required": [
|
|
267
|
+
"case_id",
|
|
268
|
+
"title",
|
|
269
|
+
"score",
|
|
270
|
+
"evidence"
|
|
271
|
+
],
|
|
272
|
+
"title": "Case",
|
|
273
|
+
"type": "object"
|
|
274
|
+
}
|
casekit/narrative.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Citation checks for model-written narratives.
|
|
2
|
+
|
|
3
|
+
A narrative passes when every cited ID exists in the evidence (no invented IDs) and at least
|
|
4
|
+
`min_coverage` of the evidence-backed claims cite one. The report says which IDs and claims
|
|
5
|
+
failed, so an eval can show why.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Iterable
|
|
11
|
+
from dataclasses import asdict, dataclass
|
|
12
|
+
|
|
13
|
+
from .schema import Claim, Narrative
|
|
14
|
+
|
|
15
|
+
DEFAULT_MIN_COVERAGE = 0.9
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class CitationReport:
|
|
20
|
+
citations: int
|
|
21
|
+
valid_citations: int
|
|
22
|
+
invented_ids: tuple[str, ...]
|
|
23
|
+
backed_claims: int
|
|
24
|
+
cited_backed_claims: int
|
|
25
|
+
uncited_claims: tuple[int, ...] # indexes into narrative.claims
|
|
26
|
+
min_coverage: float
|
|
27
|
+
claims: int
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def valid_ratio(self) -> float:
|
|
31
|
+
return self.valid_citations / self.citations if self.citations else 1.0
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def coverage(self) -> float:
|
|
35
|
+
return self.cited_backed_claims / self.backed_claims if self.backed_claims else 1.0
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def passed(self) -> bool:
|
|
39
|
+
return self.claims > 0 and not self.invented_ids and self.coverage >= self.min_coverage
|
|
40
|
+
|
|
41
|
+
def to_dict(self) -> dict:
|
|
42
|
+
return {
|
|
43
|
+
**asdict(self),
|
|
44
|
+
"valid_ratio": self.valid_ratio,
|
|
45
|
+
"coverage": self.coverage,
|
|
46
|
+
"passed": self.passed,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def validate_citations(
|
|
51
|
+
narrative: Narrative,
|
|
52
|
+
evidence_ids: Iterable[str],
|
|
53
|
+
min_coverage: float = DEFAULT_MIN_COVERAGE,
|
|
54
|
+
is_backed: Callable[[Claim], bool] | None = None,
|
|
55
|
+
) -> CitationReport:
|
|
56
|
+
"""`is_backed` decides which claims must cite evidence. By default it trusts each claim's
|
|
57
|
+
own `evidence_backed` flag, which the narrative's author sets: for model-written text pass
|
|
58
|
+
a policy (e.g. `lambda c: True`) so the model can't opt its claims out. An empty
|
|
59
|
+
narrative fails. Citing an ID proves it exists, not that it supports the claim."""
|
|
60
|
+
if not 0.0 <= min_coverage <= 1.0:
|
|
61
|
+
raise ValueError("min_coverage must be between 0 and 1")
|
|
62
|
+
backed_rule = is_backed or (lambda c: c.evidence_backed)
|
|
63
|
+
known = set(evidence_ids)
|
|
64
|
+
cited = [i for claim in narrative.claims for i in claim.evidence_ids]
|
|
65
|
+
backed = [(n, c) for n, c in enumerate(narrative.claims) if backed_rule(c)]
|
|
66
|
+
uncited = tuple(n for n, c in backed if not c.evidence_ids)
|
|
67
|
+
return CitationReport(
|
|
68
|
+
citations=len(cited),
|
|
69
|
+
valid_citations=sum(i in known for i in cited),
|
|
70
|
+
invented_ids=tuple(sorted({i for i in cited if i not in known})),
|
|
71
|
+
backed_claims=len(backed),
|
|
72
|
+
cited_backed_claims=len(backed) - len(uncited),
|
|
73
|
+
uncited_claims=uncited,
|
|
74
|
+
min_coverage=min_coverage,
|
|
75
|
+
claims=len(narrative.claims),
|
|
76
|
+
)
|
casekit/py.typed
ADDED
|
File without changes
|