itself 0.2.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.
- itself/__init__.py +282 -0
- itself/_endpoints.py +255 -0
- itself/_filesystem.py +187 -0
- itself/_formats.py +104 -0
- itself/_json.py +223 -0
- itself/_version.py +8 -0
- itself/bundle.py +723 -0
- itself/cli.py +719 -0
- itself/decision_model.py +1283 -0
- itself/evidence_bundle.py +981 -0
- itself/inference.py +1571 -0
- itself/ledger.py +373 -0
- itself/py.typed +0 -0
- itself/receipts.py +621 -0
- itself/records.py +743 -0
- itself/reporting.py +125 -0
- itself/schema_export.py +178 -0
- itself/schemas/v0alpha/evidence-bundle.schema.json +144 -0
- itself/schemas/v0alpha/protocol.schema.json +466 -0
- itself/schemas/v0alpha/reasoning-receipt.schema.json +366 -0
- itself/schemas/v0alpha2/evidence-bundle.schema.json +145 -0
- itself/schemas/v0alpha2/protocol.schema.json +503 -0
- itself/schemas/v0alpha2/reasoning-receipt.schema.json +406 -0
- itself/state.py +178 -0
- itself/types.py +21 -0
- itself/validation.py +185 -0
- itself-0.2.0.dist-info/METADATA +508 -0
- itself-0.2.0.dist-info/RECORD +32 -0
- itself-0.2.0.dist-info/WHEEL +5 -0
- itself-0.2.0.dist-info/entry_points.txt +2 -0
- itself-0.2.0.dist-info/licenses/LICENSE +373 -0
- itself-0.2.0.dist-info/top_level.txt +1 -0
itself/bundle.py
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
# Copyright (C) 2026 Greater Expanse LLC
|
|
3
|
+
|
|
4
|
+
"""Cross-record integrity validation and deterministic epistemic-state replay."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections.abc import Collection, Iterable, Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from enum import StrEnum
|
|
11
|
+
from types import MappingProxyType
|
|
12
|
+
from typing import Final, cast
|
|
13
|
+
|
|
14
|
+
import rfc8785
|
|
15
|
+
|
|
16
|
+
from .state import (
|
|
17
|
+
EVIDENCE_BACKED_STATUSES,
|
|
18
|
+
ActorRole,
|
|
19
|
+
ActorType,
|
|
20
|
+
ClaimStatus,
|
|
21
|
+
TransitionError,
|
|
22
|
+
TransitionRequest,
|
|
23
|
+
validate_transition,
|
|
24
|
+
)
|
|
25
|
+
from .types import JsonObject
|
|
26
|
+
from .validation import ProtocolValidator
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class IntegrityCode(StrEnum):
|
|
30
|
+
"""Stable identifiers for deterministic bundle-integrity failures."""
|
|
31
|
+
|
|
32
|
+
SCHEMA_INVALID = "schema_invalid"
|
|
33
|
+
DUPLICATE_ID = "duplicate_id"
|
|
34
|
+
UNRESOLVED_REFERENCE = "unresolved_reference"
|
|
35
|
+
REFERENCE_KIND_MISMATCH = "reference_kind_mismatch"
|
|
36
|
+
REFERENCE_NOT_AVAILABLE = "reference_not_available"
|
|
37
|
+
SUBJECT_NOT_AVAILABLE = "subject_not_available"
|
|
38
|
+
STATE_MISMATCH = "state_mismatch"
|
|
39
|
+
INVALID_TRANSITION = "invalid_transition"
|
|
40
|
+
EVIDENCE_RELATION_MISSING = "evidence_relation_missing"
|
|
41
|
+
TRANSITION_SUBJECT_MISMATCH = "transition_subject_mismatch"
|
|
42
|
+
VERDICT_MISMATCH = "verdict_mismatch"
|
|
43
|
+
SCOPE_MISMATCH = "scope_mismatch"
|
|
44
|
+
UNTRUSTED_AUTHORIZER = "untrusted_authorizer"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class IntegrityIssue:
|
|
49
|
+
"""One deterministic integrity violation in a protocol-record bundle."""
|
|
50
|
+
|
|
51
|
+
code: IntegrityCode
|
|
52
|
+
record_id: str
|
|
53
|
+
message: str
|
|
54
|
+
reference: str | None = None
|
|
55
|
+
|
|
56
|
+
def __str__(self) -> str:
|
|
57
|
+
reference = f" [{self.reference}]" if self.reference is not None else ""
|
|
58
|
+
return f"{self.code.value}: {self.record_id}{reference}: {self.message}"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True, slots=True)
|
|
62
|
+
class BundleSnapshot:
|
|
63
|
+
"""Deterministic state derived by replaying an ordered valid bundle."""
|
|
64
|
+
|
|
65
|
+
record_ids: tuple[str, ...]
|
|
66
|
+
current_states: Mapping[str, ClaimStatus]
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def record_count(self) -> int:
|
|
70
|
+
"""Return the number of records in the replayed bundle."""
|
|
71
|
+
|
|
72
|
+
return len(self.record_ids)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class BundleIntegrityError(ValueError):
|
|
76
|
+
"""Raised when records are valid individually but incoherent as a bundle."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, issues: Sequence[IntegrityIssue]) -> None:
|
|
79
|
+
self.issues: tuple[IntegrityIssue, ...] = tuple(issues)
|
|
80
|
+
super().__init__("\n".join(str(issue) for issue in self.issues))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True, slots=True)
|
|
84
|
+
class _ReferenceField:
|
|
85
|
+
name: str
|
|
86
|
+
allowed_kinds: frozenset[str]
|
|
87
|
+
allow_external: bool = True
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_ARTIFACT: Final = frozenset({"artifact_reference"})
|
|
91
|
+
_CLAIM_OR_HYPOTHESIS: Final = frozenset({"claim", "hypothesis"})
|
|
92
|
+
_EVIDENCE: Final = frozenset({"evidence"})
|
|
93
|
+
_PREDICTION: Final = frozenset({"prediction"})
|
|
94
|
+
_TEST: Final = frozenset({"test"})
|
|
95
|
+
_TRANSITION: Final = frozenset({"status_transition"})
|
|
96
|
+
_VERDICT: Final = frozenset({"verdict"})
|
|
97
|
+
_ANY_RECORD: Final = frozenset(
|
|
98
|
+
{
|
|
99
|
+
"artifact_reference",
|
|
100
|
+
"claim",
|
|
101
|
+
"hypothesis",
|
|
102
|
+
"prediction",
|
|
103
|
+
"test",
|
|
104
|
+
"evidence",
|
|
105
|
+
"verdict",
|
|
106
|
+
"decision",
|
|
107
|
+
"status_transition",
|
|
108
|
+
}
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
_REFERENCE_FIELDS: Final[dict[str, tuple[_ReferenceField, ...]]] = {
|
|
112
|
+
"artifact_reference": (_ReferenceField("derived_from_refs", _ARTIFACT),),
|
|
113
|
+
"claim": (
|
|
114
|
+
_ReferenceField("evidence_refs", _EVIDENCE),
|
|
115
|
+
_ReferenceField("contradicting_evidence_refs", _EVIDENCE),
|
|
116
|
+
_ReferenceField("dependency_refs", _ANY_RECORD),
|
|
117
|
+
_ReferenceField("transition_refs", _TRANSITION),
|
|
118
|
+
),
|
|
119
|
+
"hypothesis": (
|
|
120
|
+
_ReferenceField("explains_evidence_refs", _EVIDENCE),
|
|
121
|
+
_ReferenceField("alternative_hypothesis_refs", frozenset({"hypothesis"})),
|
|
122
|
+
_ReferenceField("prediction_refs", _PREDICTION),
|
|
123
|
+
_ReferenceField("dependency_refs", _ANY_RECORD),
|
|
124
|
+
),
|
|
125
|
+
"prediction": (
|
|
126
|
+
_ReferenceField("hypothesis_ref", frozenset({"hypothesis"})),
|
|
127
|
+
_ReferenceField("test_ref", _TEST),
|
|
128
|
+
),
|
|
129
|
+
"test": (
|
|
130
|
+
_ReferenceField("subject_refs", _CLAIM_OR_HYPOTHESIS),
|
|
131
|
+
_ReferenceField("prediction_refs", _PREDICTION),
|
|
132
|
+
_ReferenceField("plan_ref", _TEST),
|
|
133
|
+
_ReferenceField("evidence_refs", _EVIDENCE),
|
|
134
|
+
),
|
|
135
|
+
"evidence": (
|
|
136
|
+
_ReferenceField("artifact_refs", _ARTIFACT),
|
|
137
|
+
_ReferenceField("test_ref", _TEST),
|
|
138
|
+
),
|
|
139
|
+
"verdict": (
|
|
140
|
+
_ReferenceField("subject_ref", _CLAIM_OR_HYPOTHESIS),
|
|
141
|
+
_ReferenceField("evidence_refs", _EVIDENCE),
|
|
142
|
+
_ReferenceField("policy_ref", _ARTIFACT),
|
|
143
|
+
),
|
|
144
|
+
"decision": (
|
|
145
|
+
_ReferenceField("policy_ref", _ARTIFACT),
|
|
146
|
+
_ReferenceField("relied_on_claim_refs", frozenset({"claim"})),
|
|
147
|
+
_ReferenceField("unresolved_claim_refs", frozenset({"claim"})),
|
|
148
|
+
),
|
|
149
|
+
"status_transition": (
|
|
150
|
+
_ReferenceField("subject_ref", _CLAIM_OR_HYPOTHESIS, allow_external=False),
|
|
151
|
+
_ReferenceField("evidence_refs", _EVIDENCE, allow_external=False),
|
|
152
|
+
_ReferenceField("verdict_ref", _VERDICT, allow_external=False),
|
|
153
|
+
_ReferenceField("policy_ref", _ARTIFACT, allow_external=False),
|
|
154
|
+
),
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _record_id(record: JsonObject, position: int) -> str:
|
|
159
|
+
value = record.get("id")
|
|
160
|
+
return value if isinstance(value, str) else f"@record[{position}]"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _required_string(record: JsonObject, field: str) -> str:
|
|
164
|
+
value = record[field]
|
|
165
|
+
if not isinstance(value, str):
|
|
166
|
+
raise TypeError(f"schema-valid field {field!r} was not a string")
|
|
167
|
+
return value
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _optional_string(record: JsonObject, field: str) -> str | None:
|
|
171
|
+
value = record.get(field)
|
|
172
|
+
if value is None:
|
|
173
|
+
return None
|
|
174
|
+
if not isinstance(value, str):
|
|
175
|
+
raise TypeError(f"schema-valid field {field!r} was not a string")
|
|
176
|
+
return value
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _object(record: JsonObject, field: str) -> JsonObject:
|
|
180
|
+
value = record[field]
|
|
181
|
+
if not isinstance(value, dict):
|
|
182
|
+
raise TypeError(f"schema-valid field {field!r} was not an object")
|
|
183
|
+
return value
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _objects(record: JsonObject, field: str) -> tuple[JsonObject, ...]:
|
|
187
|
+
value = record[field]
|
|
188
|
+
if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
|
|
189
|
+
raise TypeError(f"schema-valid field {field!r} was not an object array")
|
|
190
|
+
return tuple(cast(JsonObject, item) for item in value)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _references(record: JsonObject, field: str) -> tuple[str, ...]:
|
|
194
|
+
value = record.get(field)
|
|
195
|
+
if value is None:
|
|
196
|
+
return ()
|
|
197
|
+
if isinstance(value, str):
|
|
198
|
+
return (value,)
|
|
199
|
+
if isinstance(value, list) and all(isinstance(item, str) for item in value):
|
|
200
|
+
return tuple(cast(str, item) for item in value)
|
|
201
|
+
raise TypeError(
|
|
202
|
+
f"schema-valid field {field!r} was not a reference or reference array"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _checked_prefix(value: int, record_count: int) -> int:
|
|
207
|
+
runtime_value = cast(object, value)
|
|
208
|
+
if (
|
|
209
|
+
isinstance(runtime_value, bool)
|
|
210
|
+
or not isinstance(runtime_value, int)
|
|
211
|
+
or not 0 <= runtime_value <= record_count
|
|
212
|
+
):
|
|
213
|
+
raise ValueError(
|
|
214
|
+
f"a schema-checked prefix must be an integer from 0 to {record_count}"
|
|
215
|
+
)
|
|
216
|
+
return runtime_value
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _trusted_authorizers(value: object) -> frozenset[str]:
|
|
220
|
+
if isinstance(value, str) or not isinstance(value, Collection):
|
|
221
|
+
raise ValueError("trusted_authorizers must be a collection of actor ids")
|
|
222
|
+
authorizers = frozenset(cast(Collection[object], value))
|
|
223
|
+
if not all(
|
|
224
|
+
isinstance(actor_id, str) and actor_id.strip() for actor_id in authorizers
|
|
225
|
+
):
|
|
226
|
+
raise ValueError("trusted_authorizers must contain non-empty actor ids")
|
|
227
|
+
return cast(frozenset[str], authorizers)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
class BundleValidator:
|
|
231
|
+
"""Validate references and replay state across ordered protocol records.
|
|
232
|
+
|
|
233
|
+
Records declare their own actors, so by default any identifier may
|
|
234
|
+
authorize an evidence-backed transition if its declared type and role
|
|
235
|
+
allow it. ``trusted_authorizers`` lists the only actor ids that may:
|
|
236
|
+
identity is established outside the protocol, and the validator then
|
|
237
|
+
rejects every other authorizer with ``untrusted_authorizer``.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
def __init__(
|
|
241
|
+
self,
|
|
242
|
+
protocol_validator: ProtocolValidator | None = None,
|
|
243
|
+
*,
|
|
244
|
+
trusted_authorizers: Collection[str] | None = None,
|
|
245
|
+
) -> None:
|
|
246
|
+
self._protocol_validator = protocol_validator or ProtocolValidator()
|
|
247
|
+
self._trusted_authorizers = (
|
|
248
|
+
None
|
|
249
|
+
if trusted_authorizers is None
|
|
250
|
+
else _trusted_authorizers(trusted_authorizers)
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def trusted_authorizers(self) -> frozenset[str] | None:
|
|
255
|
+
"""The only actor ids allowed to authorize evidence-backed transitions."""
|
|
256
|
+
|
|
257
|
+
return self._trusted_authorizers
|
|
258
|
+
|
|
259
|
+
def errors(
|
|
260
|
+
self,
|
|
261
|
+
records: Iterable[JsonObject],
|
|
262
|
+
*,
|
|
263
|
+
external_refs: Collection[str] = (),
|
|
264
|
+
) -> list[IntegrityIssue]:
|
|
265
|
+
"""Return every deterministic integrity issue found in an ordered bundle."""
|
|
266
|
+
|
|
267
|
+
_, issues = self._analyze(tuple(records), frozenset(external_refs), 0)
|
|
268
|
+
return issues
|
|
269
|
+
|
|
270
|
+
def validate(
|
|
271
|
+
self,
|
|
272
|
+
records: Iterable[JsonObject],
|
|
273
|
+
*,
|
|
274
|
+
external_refs: Collection[str] = (),
|
|
275
|
+
) -> BundleSnapshot:
|
|
276
|
+
"""Return replayed state or raise BundleIntegrityError for an invalid bundle."""
|
|
277
|
+
|
|
278
|
+
return self._validated(tuple(records), frozenset(external_refs), 0)
|
|
279
|
+
|
|
280
|
+
def _validated(
|
|
281
|
+
self,
|
|
282
|
+
records: tuple[JsonObject, ...],
|
|
283
|
+
external_refs: frozenset[str],
|
|
284
|
+
schema_checked: int,
|
|
285
|
+
) -> BundleSnapshot:
|
|
286
|
+
# Only Ledger passes a nonzero ``schema_checked``: its held records are
|
|
287
|
+
# private copies this validator already accepted, so they skip only
|
|
288
|
+
# the per-record schema check, and every cross-record check still
|
|
289
|
+
# covers the whole sequence.
|
|
290
|
+
snapshot, issues = self._analyze(
|
|
291
|
+
records,
|
|
292
|
+
external_refs,
|
|
293
|
+
_checked_prefix(schema_checked, len(records)),
|
|
294
|
+
)
|
|
295
|
+
if issues:
|
|
296
|
+
raise BundleIntegrityError(issues)
|
|
297
|
+
if snapshot is None:
|
|
298
|
+
raise RuntimeError("bundle analysis produced neither a snapshot nor issues")
|
|
299
|
+
return snapshot
|
|
300
|
+
|
|
301
|
+
def _analyze(
|
|
302
|
+
self,
|
|
303
|
+
records: tuple[JsonObject, ...],
|
|
304
|
+
external_refs: frozenset[str],
|
|
305
|
+
schema_checked_prefix: int,
|
|
306
|
+
) -> tuple[BundleSnapshot | None, list[IntegrityIssue]]:
|
|
307
|
+
issues = self._schema_issues(records, schema_checked_prefix)
|
|
308
|
+
if issues:
|
|
309
|
+
return None, issues
|
|
310
|
+
|
|
311
|
+
duplicate_issues = self._duplicate_issues(records)
|
|
312
|
+
if duplicate_issues:
|
|
313
|
+
return None, duplicate_issues
|
|
314
|
+
|
|
315
|
+
index = {_required_string(record, "id"): record for record in records}
|
|
316
|
+
positions = {
|
|
317
|
+
_required_string(record, "id"): position
|
|
318
|
+
for position, record in enumerate(records)
|
|
319
|
+
}
|
|
320
|
+
issues.extend(self._reference_issues(records, index, external_refs))
|
|
321
|
+
issues.extend(self._verdict_issues(records, index, positions))
|
|
322
|
+
states, replay_issues = self._replay(records, index, positions)
|
|
323
|
+
issues.extend(replay_issues)
|
|
324
|
+
|
|
325
|
+
snapshot = BundleSnapshot(
|
|
326
|
+
record_ids=tuple(_required_string(record, "id") for record in records),
|
|
327
|
+
current_states=MappingProxyType(states),
|
|
328
|
+
)
|
|
329
|
+
return snapshot, issues
|
|
330
|
+
|
|
331
|
+
def _schema_issues(
|
|
332
|
+
self,
|
|
333
|
+
records: tuple[JsonObject, ...],
|
|
334
|
+
start: int,
|
|
335
|
+
) -> list[IntegrityIssue]:
|
|
336
|
+
issues: list[IntegrityIssue] = []
|
|
337
|
+
for position, record in enumerate(records[start:], start):
|
|
338
|
+
for message in self._protocol_validator.errors(record):
|
|
339
|
+
issues.append(
|
|
340
|
+
IntegrityIssue(
|
|
341
|
+
code=IntegrityCode.SCHEMA_INVALID,
|
|
342
|
+
record_id=_record_id(record, position),
|
|
343
|
+
message=message,
|
|
344
|
+
)
|
|
345
|
+
)
|
|
346
|
+
return issues
|
|
347
|
+
|
|
348
|
+
@staticmethod
|
|
349
|
+
def _duplicate_issues(records: tuple[JsonObject, ...]) -> list[IntegrityIssue]:
|
|
350
|
+
first_positions: dict[str, int] = {}
|
|
351
|
+
issues: list[IntegrityIssue] = []
|
|
352
|
+
for position, record in enumerate(records):
|
|
353
|
+
record_id = _required_string(record, "id")
|
|
354
|
+
first_position = first_positions.setdefault(record_id, position)
|
|
355
|
+
if first_position != position:
|
|
356
|
+
issues.append(
|
|
357
|
+
IntegrityIssue(
|
|
358
|
+
code=IntegrityCode.DUPLICATE_ID,
|
|
359
|
+
record_id=record_id,
|
|
360
|
+
message=(
|
|
361
|
+
f"duplicates the record at position {first_position}; "
|
|
362
|
+
f"encountered again at position {position}"
|
|
363
|
+
),
|
|
364
|
+
)
|
|
365
|
+
)
|
|
366
|
+
return issues
|
|
367
|
+
|
|
368
|
+
def _reference_issues(
|
|
369
|
+
self,
|
|
370
|
+
records: tuple[JsonObject, ...],
|
|
371
|
+
index: Mapping[str, JsonObject],
|
|
372
|
+
external_refs: frozenset[str],
|
|
373
|
+
) -> list[IntegrityIssue]:
|
|
374
|
+
issues: list[IntegrityIssue] = []
|
|
375
|
+
for record in records:
|
|
376
|
+
record_id = _required_string(record, "id")
|
|
377
|
+
kind = _required_string(record, "kind")
|
|
378
|
+
for spec in _REFERENCE_FIELDS[kind]:
|
|
379
|
+
for reference in _references(record, spec.name):
|
|
380
|
+
issues.extend(
|
|
381
|
+
self._check_reference(
|
|
382
|
+
record_id,
|
|
383
|
+
reference,
|
|
384
|
+
spec,
|
|
385
|
+
index,
|
|
386
|
+
external_refs,
|
|
387
|
+
)
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
if kind == "evidence":
|
|
391
|
+
for relation in _objects(record, "relations"):
|
|
392
|
+
reference = _required_string(relation, "subject_ref")
|
|
393
|
+
issues.extend(
|
|
394
|
+
self._check_reference(
|
|
395
|
+
record_id,
|
|
396
|
+
reference,
|
|
397
|
+
_ReferenceField(
|
|
398
|
+
"relations.subject_ref", _CLAIM_OR_HYPOTHESIS
|
|
399
|
+
),
|
|
400
|
+
index,
|
|
401
|
+
external_refs,
|
|
402
|
+
)
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
if kind in {"claim", "hypothesis"}:
|
|
406
|
+
for transition_ref in _references(record, "transition_refs"):
|
|
407
|
+
transition = index.get(transition_ref)
|
|
408
|
+
if (
|
|
409
|
+
transition is not None
|
|
410
|
+
and _required_string(transition, "kind") == "status_transition"
|
|
411
|
+
and _required_string(transition, "subject_ref") != record_id
|
|
412
|
+
):
|
|
413
|
+
issues.append(
|
|
414
|
+
IntegrityIssue(
|
|
415
|
+
code=IntegrityCode.TRANSITION_SUBJECT_MISMATCH,
|
|
416
|
+
record_id=record_id,
|
|
417
|
+
reference=transition_ref,
|
|
418
|
+
message="referenced transition targets a different subject",
|
|
419
|
+
)
|
|
420
|
+
)
|
|
421
|
+
return issues
|
|
422
|
+
|
|
423
|
+
@staticmethod
|
|
424
|
+
def _check_reference(
|
|
425
|
+
record_id: str,
|
|
426
|
+
reference: str,
|
|
427
|
+
spec: _ReferenceField,
|
|
428
|
+
index: Mapping[str, JsonObject],
|
|
429
|
+
external_refs: frozenset[str],
|
|
430
|
+
) -> list[IntegrityIssue]:
|
|
431
|
+
target = index.get(reference)
|
|
432
|
+
if target is None:
|
|
433
|
+
if reference in external_refs and spec.allow_external:
|
|
434
|
+
return []
|
|
435
|
+
return [
|
|
436
|
+
IntegrityIssue(
|
|
437
|
+
code=IntegrityCode.UNRESOLVED_REFERENCE,
|
|
438
|
+
record_id=record_id,
|
|
439
|
+
reference=reference,
|
|
440
|
+
message=f"{spec.name} does not resolve within the bundle",
|
|
441
|
+
)
|
|
442
|
+
]
|
|
443
|
+
target_kind = _required_string(target, "kind")
|
|
444
|
+
if target_kind not in spec.allowed_kinds:
|
|
445
|
+
allowed = ", ".join(sorted(spec.allowed_kinds))
|
|
446
|
+
return [
|
|
447
|
+
IntegrityIssue(
|
|
448
|
+
code=IntegrityCode.REFERENCE_KIND_MISMATCH,
|
|
449
|
+
record_id=record_id,
|
|
450
|
+
reference=reference,
|
|
451
|
+
message=(
|
|
452
|
+
f"{spec.name} targets {target_kind}; expected one of: {allowed}"
|
|
453
|
+
),
|
|
454
|
+
)
|
|
455
|
+
]
|
|
456
|
+
return []
|
|
457
|
+
|
|
458
|
+
@staticmethod
|
|
459
|
+
def _scope(record: JsonObject) -> JsonObject:
|
|
460
|
+
return _object(record, "scope")
|
|
461
|
+
|
|
462
|
+
@staticmethod
|
|
463
|
+
def _same_json(left: JsonObject, right: JsonObject) -> bool:
|
|
464
|
+
return rfc8785.dumps(left) == rfc8785.dumps(right)
|
|
465
|
+
|
|
466
|
+
def _verdict_issues(
|
|
467
|
+
self,
|
|
468
|
+
records: tuple[JsonObject, ...],
|
|
469
|
+
index: Mapping[str, JsonObject],
|
|
470
|
+
positions: Mapping[str, int],
|
|
471
|
+
) -> list[IntegrityIssue]:
|
|
472
|
+
issues: list[IntegrityIssue] = []
|
|
473
|
+
for position, verdict in enumerate(records):
|
|
474
|
+
if _required_string(verdict, "kind") != "verdict":
|
|
475
|
+
continue
|
|
476
|
+
|
|
477
|
+
verdict_id = _required_string(verdict, "id")
|
|
478
|
+
subject_ref = _required_string(verdict, "subject_ref")
|
|
479
|
+
evidence_refs = _references(verdict, "evidence_refs")
|
|
480
|
+
policy_ref = _optional_string(verdict, "policy_ref")
|
|
481
|
+
material_refs = (subject_ref,) + evidence_refs
|
|
482
|
+
if policy_ref is not None:
|
|
483
|
+
material_refs += (policy_ref,)
|
|
484
|
+
for reference in material_refs:
|
|
485
|
+
reference_position = positions.get(reference)
|
|
486
|
+
if reference_position is not None and reference_position >= position:
|
|
487
|
+
issues.append(
|
|
488
|
+
IntegrityIssue(
|
|
489
|
+
code=IntegrityCode.REFERENCE_NOT_AVAILABLE,
|
|
490
|
+
record_id=verdict_id,
|
|
491
|
+
reference=reference,
|
|
492
|
+
message="verdict material must appear before the verdict",
|
|
493
|
+
)
|
|
494
|
+
)
|
|
495
|
+
|
|
496
|
+
subject = index.get(subject_ref)
|
|
497
|
+
if (
|
|
498
|
+
subject is None
|
|
499
|
+
or _required_string(subject, "kind") not in _CLAIM_OR_HYPOTHESIS
|
|
500
|
+
):
|
|
501
|
+
continue
|
|
502
|
+
verdict_scope = self._scope(verdict)
|
|
503
|
+
if not self._same_json(verdict_scope, self._scope(subject)):
|
|
504
|
+
issues.append(
|
|
505
|
+
IntegrityIssue(
|
|
506
|
+
code=IntegrityCode.SCOPE_MISMATCH,
|
|
507
|
+
record_id=verdict_id,
|
|
508
|
+
reference=subject_ref,
|
|
509
|
+
message="verdict scope must exactly match its subject scope",
|
|
510
|
+
)
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
outcome = ClaimStatus(_required_string(verdict, "outcome"))
|
|
514
|
+
observed_relations: set[str] = set()
|
|
515
|
+
for evidence_ref in evidence_refs:
|
|
516
|
+
evidence = index.get(evidence_ref)
|
|
517
|
+
if evidence is None or _required_string(evidence, "kind") != "evidence":
|
|
518
|
+
continue
|
|
519
|
+
if not self._same_json(self._scope(evidence), verdict_scope):
|
|
520
|
+
issues.append(
|
|
521
|
+
IntegrityIssue(
|
|
522
|
+
code=IntegrityCode.SCOPE_MISMATCH,
|
|
523
|
+
record_id=verdict_id,
|
|
524
|
+
reference=evidence_ref,
|
|
525
|
+
message=(
|
|
526
|
+
"verdict evidence scope must exactly match "
|
|
527
|
+
"the verdict scope"
|
|
528
|
+
),
|
|
529
|
+
)
|
|
530
|
+
)
|
|
531
|
+
relations = {
|
|
532
|
+
_required_string(relation, "relation")
|
|
533
|
+
for relation in _objects(evidence, "relations")
|
|
534
|
+
if _required_string(relation, "subject_ref") == subject_ref
|
|
535
|
+
}
|
|
536
|
+
if not relations:
|
|
537
|
+
issues.append(
|
|
538
|
+
IntegrityIssue(
|
|
539
|
+
code=IntegrityCode.EVIDENCE_RELATION_MISSING,
|
|
540
|
+
record_id=verdict_id,
|
|
541
|
+
reference=evidence_ref,
|
|
542
|
+
message=f"verdict evidence does not relate to {subject_ref}",
|
|
543
|
+
)
|
|
544
|
+
)
|
|
545
|
+
continue
|
|
546
|
+
observed_relations.update(relations)
|
|
547
|
+
expected_relation = {
|
|
548
|
+
ClaimStatus.SUPPORTED: "supports",
|
|
549
|
+
ClaimStatus.CORROBORATED_WITHIN_SCOPE: "supports",
|
|
550
|
+
ClaimStatus.REFUTED: "contradicts",
|
|
551
|
+
}.get(outcome)
|
|
552
|
+
if expected_relation is not None and expected_relation not in relations:
|
|
553
|
+
issues.append(
|
|
554
|
+
IntegrityIssue(
|
|
555
|
+
code=IntegrityCode.EVIDENCE_RELATION_MISSING,
|
|
556
|
+
record_id=verdict_id,
|
|
557
|
+
reference=evidence_ref,
|
|
558
|
+
message=(
|
|
559
|
+
f"{outcome.value} verdict requires evidence "
|
|
560
|
+
f"that {expected_relation} the subject"
|
|
561
|
+
),
|
|
562
|
+
)
|
|
563
|
+
)
|
|
564
|
+
|
|
565
|
+
if outcome is ClaimStatus.MIXED_EVIDENCE and not {
|
|
566
|
+
"supports",
|
|
567
|
+
"contradicts",
|
|
568
|
+
}.issubset(observed_relations):
|
|
569
|
+
issues.append(
|
|
570
|
+
IntegrityIssue(
|
|
571
|
+
code=IntegrityCode.EVIDENCE_RELATION_MISSING,
|
|
572
|
+
record_id=verdict_id,
|
|
573
|
+
reference=subject_ref,
|
|
574
|
+
message=(
|
|
575
|
+
"mixed_evidence verdict requires both supporting "
|
|
576
|
+
"and contradicting evidence relations"
|
|
577
|
+
),
|
|
578
|
+
)
|
|
579
|
+
)
|
|
580
|
+
return issues
|
|
581
|
+
|
|
582
|
+
def _replay(
|
|
583
|
+
self,
|
|
584
|
+
records: tuple[JsonObject, ...],
|
|
585
|
+
index: Mapping[str, JsonObject],
|
|
586
|
+
positions: Mapping[str, int],
|
|
587
|
+
) -> tuple[dict[str, ClaimStatus], list[IntegrityIssue]]:
|
|
588
|
+
states: dict[str, ClaimStatus] = {}
|
|
589
|
+
issues: list[IntegrityIssue] = []
|
|
590
|
+
|
|
591
|
+
for position, record in enumerate(records):
|
|
592
|
+
kind = _required_string(record, "kind")
|
|
593
|
+
record_id = _required_string(record, "id")
|
|
594
|
+
if kind in {"claim", "hypothesis"}:
|
|
595
|
+
states[record_id] = ClaimStatus(_required_string(record, "status"))
|
|
596
|
+
continue
|
|
597
|
+
if kind != "status_transition":
|
|
598
|
+
continue
|
|
599
|
+
|
|
600
|
+
subject_ref = _required_string(record, "subject_ref")
|
|
601
|
+
current_status = states.get(subject_ref)
|
|
602
|
+
can_apply = True
|
|
603
|
+
if current_status is None:
|
|
604
|
+
issues.append(
|
|
605
|
+
IntegrityIssue(
|
|
606
|
+
code=IntegrityCode.SUBJECT_NOT_AVAILABLE,
|
|
607
|
+
record_id=record_id,
|
|
608
|
+
reference=subject_ref,
|
|
609
|
+
message="transition subject has not appeared earlier in the bundle",
|
|
610
|
+
)
|
|
611
|
+
)
|
|
612
|
+
can_apply = False
|
|
613
|
+
|
|
614
|
+
from_status = ClaimStatus(_required_string(record, "from_status"))
|
|
615
|
+
to_status = ClaimStatus(_required_string(record, "to_status"))
|
|
616
|
+
if current_status is not None and from_status is not current_status:
|
|
617
|
+
issues.append(
|
|
618
|
+
IntegrityIssue(
|
|
619
|
+
code=IntegrityCode.STATE_MISMATCH,
|
|
620
|
+
record_id=record_id,
|
|
621
|
+
reference=subject_ref,
|
|
622
|
+
message=(
|
|
623
|
+
f"declares from_status={from_status.value}, but replayed state "
|
|
624
|
+
f"is {current_status.value}"
|
|
625
|
+
),
|
|
626
|
+
)
|
|
627
|
+
)
|
|
628
|
+
can_apply = False
|
|
629
|
+
|
|
630
|
+
evidence_refs = _references(record, "evidence_refs")
|
|
631
|
+
verdict_ref = _optional_string(record, "verdict_ref")
|
|
632
|
+
policy_ref = _optional_string(record, "policy_ref")
|
|
633
|
+
available_refs = evidence_refs
|
|
634
|
+
if verdict_ref is not None:
|
|
635
|
+
available_refs += (verdict_ref,)
|
|
636
|
+
if policy_ref is not None:
|
|
637
|
+
available_refs += (policy_ref,)
|
|
638
|
+
for reference in available_refs:
|
|
639
|
+
reference_position = positions.get(reference)
|
|
640
|
+
if reference_position is not None and reference_position >= position:
|
|
641
|
+
issues.append(
|
|
642
|
+
IntegrityIssue(
|
|
643
|
+
code=IntegrityCode.REFERENCE_NOT_AVAILABLE,
|
|
644
|
+
record_id=record_id,
|
|
645
|
+
reference=reference,
|
|
646
|
+
message="authorizing material must appear before the transition",
|
|
647
|
+
)
|
|
648
|
+
)
|
|
649
|
+
can_apply = False
|
|
650
|
+
|
|
651
|
+
authorized_by = _object(record, "authorized_by")
|
|
652
|
+
request = TransitionRequest(
|
|
653
|
+
subject_ref=subject_ref,
|
|
654
|
+
from_status=from_status,
|
|
655
|
+
to_status=to_status,
|
|
656
|
+
authorized_by=_required_string(authorized_by, "id"),
|
|
657
|
+
actor_type=ActorType(_required_string(authorized_by, "actor_type")),
|
|
658
|
+
actor_role=ActorRole(_required_string(authorized_by, "role")),
|
|
659
|
+
evidence_refs=evidence_refs,
|
|
660
|
+
verdict_ref=verdict_ref,
|
|
661
|
+
policy_ref=policy_ref,
|
|
662
|
+
)
|
|
663
|
+
try:
|
|
664
|
+
validate_transition(request)
|
|
665
|
+
except TransitionError as error:
|
|
666
|
+
issues.append(
|
|
667
|
+
IntegrityIssue(
|
|
668
|
+
code=IntegrityCode.INVALID_TRANSITION,
|
|
669
|
+
record_id=record_id,
|
|
670
|
+
reference=subject_ref,
|
|
671
|
+
message=str(error),
|
|
672
|
+
)
|
|
673
|
+
)
|
|
674
|
+
can_apply = False
|
|
675
|
+
if (
|
|
676
|
+
self._trusted_authorizers is not None
|
|
677
|
+
and to_status in EVIDENCE_BACKED_STATUSES
|
|
678
|
+
and request.authorized_by not in self._trusted_authorizers
|
|
679
|
+
):
|
|
680
|
+
issues.append(
|
|
681
|
+
IntegrityIssue(
|
|
682
|
+
code=IntegrityCode.UNTRUSTED_AUTHORIZER,
|
|
683
|
+
record_id=record_id,
|
|
684
|
+
reference=request.authorized_by,
|
|
685
|
+
message="evidence-backed transition is authorized by an actor "
|
|
686
|
+
"that is not trusted to authorize it",
|
|
687
|
+
)
|
|
688
|
+
)
|
|
689
|
+
can_apply = False
|
|
690
|
+
|
|
691
|
+
if verdict_ref is not None:
|
|
692
|
+
verdict = index.get(verdict_ref)
|
|
693
|
+
if verdict is None or _required_string(verdict, "kind") != "verdict":
|
|
694
|
+
can_apply = False
|
|
695
|
+
else:
|
|
696
|
+
verdict_evidence = frozenset(_references(verdict, "evidence_refs"))
|
|
697
|
+
mismatches: list[str] = []
|
|
698
|
+
if _required_string(verdict, "subject_ref") != subject_ref:
|
|
699
|
+
mismatches.append("subject")
|
|
700
|
+
if _required_string(verdict, "outcome") != to_status.value:
|
|
701
|
+
mismatches.append("outcome")
|
|
702
|
+
if verdict_evidence != frozenset(evidence_refs):
|
|
703
|
+
mismatches.append("evidence")
|
|
704
|
+
if _optional_string(verdict, "policy_ref") != policy_ref:
|
|
705
|
+
mismatches.append("policy")
|
|
706
|
+
if mismatches:
|
|
707
|
+
issues.append(
|
|
708
|
+
IntegrityIssue(
|
|
709
|
+
code=IntegrityCode.VERDICT_MISMATCH,
|
|
710
|
+
record_id=record_id,
|
|
711
|
+
reference=verdict_ref,
|
|
712
|
+
message=(
|
|
713
|
+
"transition does not match verdict fields: "
|
|
714
|
+
+ ", ".join(mismatches)
|
|
715
|
+
),
|
|
716
|
+
)
|
|
717
|
+
)
|
|
718
|
+
can_apply = False
|
|
719
|
+
|
|
720
|
+
if can_apply:
|
|
721
|
+
states[subject_ref] = to_status
|
|
722
|
+
|
|
723
|
+
return states, issues
|