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/receipts.py ADDED
@@ -0,0 +1,621 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Deterministic reasoning receipts derived from validated protocol ledgers."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import stat
12
+ import tempfile
13
+ from collections import defaultdict
14
+ from collections.abc import Iterator, Sequence
15
+ from importlib.resources import files
16
+ from pathlib import Path
17
+ from typing import Final, Protocol, cast
18
+
19
+ import rfc8785
20
+ from jsonschema import Draft202012Validator
21
+ from jsonschema.exceptions import ValidationError
22
+
23
+ from ._formats import schema_format_checker
24
+ from ._json import format_json_path as _format_path
25
+ from ._json import strict_json_loads
26
+ from .ledger import Ledger
27
+ from .reporting import summarize_ledger
28
+ from .types import JsonObject, JsonValue, StrPath
29
+
30
+ RECEIPT_VERSION: Final = "0.1.0-alpha.2"
31
+ LEDGER_CANONICALIZATION: Final = "rfc8785-jsonl-v1"
32
+
33
+ _ASSURANCE_BASIS: Final = (
34
+ "protocol_schema_conformance",
35
+ "bundle_reference_integrity",
36
+ "deterministic_state_replay",
37
+ "canonical_ledger_digest",
38
+ )
39
+ _LIMITATIONS: Final = (
40
+ "Structural integrity does not establish factual truth.",
41
+ "The receipt does not independently verify artifact contents or digests.",
42
+ "The receipt does not establish that an oracle or authority is correct.",
43
+ )
44
+
45
+
46
+ class _ReceiptSchemaValidator(Protocol):
47
+ """Typed surface used from the partially typed jsonschema dependency."""
48
+
49
+ def iter_errors(self, instance: JsonValue) -> Iterator[ValidationError]: ...
50
+
51
+
52
+ def _string(record: JsonObject, field: str) -> str:
53
+ value = record[field]
54
+ if not isinstance(value, str):
55
+ raise TypeError(f"validated field {field!r} was not a string")
56
+ return value
57
+
58
+
59
+ def _optional_string(record: JsonObject, field: str) -> str | None:
60
+ value = record.get(field)
61
+ if value is None:
62
+ return None
63
+ if not isinstance(value, str):
64
+ raise TypeError(f"validated field {field!r} was not a string")
65
+ return value
66
+
67
+
68
+ def _strings(record: JsonObject, field: str) -> list[JsonValue]:
69
+ value = record.get(field)
70
+ if value is None:
71
+ return []
72
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
73
+ raise TypeError(f"validated field {field!r} was not a string array")
74
+ return [cast(str, item) for item in value]
75
+
76
+
77
+ def _object(record: JsonObject, field: str) -> JsonObject:
78
+ value = record[field]
79
+ if not isinstance(value, dict):
80
+ raise TypeError(f"validated field {field!r} was not an object")
81
+ return value
82
+
83
+
84
+ def _optional_object(record: JsonObject, field: str) -> JsonObject | None:
85
+ value = record.get(field)
86
+ if value is None:
87
+ return None
88
+ if not isinstance(value, dict):
89
+ raise TypeError(f"validated field {field!r} was not an object")
90
+ return value
91
+
92
+
93
+ def _objects(record: JsonObject, field: str) -> tuple[JsonObject, ...]:
94
+ value = record[field]
95
+ if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):
96
+ raise TypeError(f"validated field {field!r} was not an object array")
97
+ return tuple(cast(JsonObject, item) for item in value)
98
+
99
+
100
+ def _json_objects(values: Sequence[JsonObject]) -> list[JsonValue]:
101
+ return [value for value in values]
102
+
103
+
104
+ def _json_strings(values: Sequence[str]) -> list[JsonValue]:
105
+ return [value for value in values]
106
+
107
+
108
+ def _actor_summary(actor: JsonObject) -> JsonObject:
109
+ value: JsonObject = {
110
+ "id": _string(actor, "id"),
111
+ "actor_type": _string(actor, "actor_type"),
112
+ "role": _string(actor, "role"),
113
+ }
114
+ implementation_ref = _optional_string(actor, "implementation_ref")
115
+ if implementation_ref is not None:
116
+ value["implementation_ref"] = implementation_ref
117
+ return value
118
+
119
+
120
+ def _authority_summary(authority: JsonObject) -> JsonObject:
121
+ value: JsonObject = {
122
+ "authority_type": _string(authority, "authority_type"),
123
+ "actor_ref": _string(authority, "actor_ref"),
124
+ "basis": _string(authority, "basis"),
125
+ }
126
+ independent = authority.get("independent_of_subject")
127
+ if isinstance(independent, bool):
128
+ value["independent_of_subject"] = independent
129
+ return value
130
+
131
+
132
+ def _digest_summary(digest: JsonObject) -> JsonObject:
133
+ return {
134
+ "algorithm": _string(digest, "algorithm"),
135
+ "value": _string(digest, "value"),
136
+ }
137
+
138
+
139
+ def _oracle_summary(oracle: JsonObject) -> JsonObject:
140
+ value: JsonObject = {
141
+ "adapter": _string(oracle, "adapter"),
142
+ "version": _string(oracle, "version"),
143
+ "authority_type": _string(oracle, "authority_type"),
144
+ }
145
+ declared_scope = _optional_string(oracle, "declared_scope")
146
+ if declared_scope is not None:
147
+ value["declared_scope"] = declared_scope
148
+ return value
149
+
150
+
151
+ def canonical_ledger_bytes(ledger: Ledger) -> bytes:
152
+ """Return RFC 8785 records in authoritative order, each followed by LF."""
153
+
154
+ return b"".join(rfc8785.dumps(record) + b"\n" for record in ledger.records)
155
+
156
+
157
+ def _canonical_records(ledger: Ledger) -> tuple[JsonObject, ...]:
158
+ records: list[JsonObject] = []
159
+ for record in ledger.records:
160
+ value = strict_json_loads(rfc8785.dumps(record))
161
+ if not isinstance(value, dict):
162
+ raise RuntimeError("canonical protocol record was not a JSON object")
163
+ records.append(value)
164
+ return tuple(records)
165
+
166
+
167
+ def ledger_sha256(ledger: Ledger) -> str:
168
+ """Return the SHA-256 digest of the canonical ledger representation."""
169
+
170
+ return hashlib.sha256(canonical_ledger_bytes(ledger)).hexdigest()
171
+
172
+
173
+ def _subject_summaries(
174
+ records: Sequence[JsonObject],
175
+ ledger: Ledger,
176
+ ) -> tuple[JsonObject, ...]:
177
+ transition_ids: dict[str, list[str]] = defaultdict(list)
178
+ for record in records:
179
+ if _string(record, "kind") == "status_transition":
180
+ transition_ids[_string(record, "subject_ref")].append(_string(record, "id"))
181
+
182
+ subjects: list[JsonObject] = []
183
+ for record in records:
184
+ kind = _string(record, "kind")
185
+ if kind not in {"claim", "hypothesis"}:
186
+ continue
187
+ subject_id = _string(record, "id")
188
+ scope = _object(record, "scope")
189
+ subject: JsonObject = {
190
+ "subject_id": subject_id,
191
+ "kind": kind,
192
+ "text": _string(
193
+ record,
194
+ "proposition" if kind == "claim" else "statement",
195
+ ),
196
+ "scope_description": _string(scope, "description"),
197
+ "initial_status": _string(record, "status"),
198
+ "current_status": ledger.snapshot.current_states[subject_id].value,
199
+ "transition_ids": _json_strings(transition_ids[subject_id]),
200
+ }
201
+ subjects.append(subject)
202
+ return tuple(subjects)
203
+
204
+
205
+ def _artifact_summary(record: JsonObject) -> JsonObject:
206
+ value: JsonObject = {
207
+ "id": _string(record, "id"),
208
+ "uri": _string(record, "uri"),
209
+ "media_type": _string(record, "media_type"),
210
+ }
211
+ title = _optional_string(record, "title")
212
+ if title is not None:
213
+ value["title"] = title
214
+ digest = _optional_object(record, "digest")
215
+ if digest is not None:
216
+ value["digest"] = _digest_summary(digest)
217
+ return value
218
+
219
+
220
+ def _test_summary(record: JsonObject) -> JsonObject:
221
+ value: JsonObject = {
222
+ "id": _string(record, "id"),
223
+ "status": _string(record, "status"),
224
+ "design": _string(record, "design"),
225
+ "subject_refs": _strings(record, "subject_refs"),
226
+ "prediction_refs": _strings(record, "prediction_refs"),
227
+ "evidence_refs": _strings(record, "evidence_refs"),
228
+ "oracle": _oracle_summary(_object(record, "oracle")),
229
+ }
230
+ plan_ref = _optional_string(record, "plan_ref")
231
+ if plan_ref is not None:
232
+ value["plan_ref"] = plan_ref
233
+ cost = _optional_object(record, "cost")
234
+ if cost is not None:
235
+ value["cost"] = dict(cost)
236
+ return value
237
+
238
+
239
+ def _relation_summary(relation: JsonObject) -> JsonObject:
240
+ value: JsonObject = {
241
+ "subject_ref": _string(relation, "subject_ref"),
242
+ "relation": _string(relation, "relation"),
243
+ }
244
+ public_note = _optional_string(relation, "public_note")
245
+ if public_note is not None:
246
+ value["public_note"] = public_note
247
+ return value
248
+
249
+
250
+ def _evidence_summary(record: JsonObject) -> JsonObject:
251
+ value: JsonObject = {
252
+ "id": _string(record, "id"),
253
+ "evidence_type": _string(record, "evidence_type"),
254
+ "relations": _json_objects(
255
+ tuple(
256
+ _relation_summary(relation)
257
+ for relation in _objects(record, "relations")
258
+ )
259
+ ),
260
+ "authority": _authority_summary(_object(record, "authority")),
261
+ "artifact_refs": _strings(record, "artifact_refs"),
262
+ }
263
+ for field in ("test_ref", "expires_at"):
264
+ field_value = _optional_string(record, field)
265
+ if field_value is not None:
266
+ value[field] = field_value
267
+ return value
268
+
269
+
270
+ def _verdict_summary(record: JsonObject) -> JsonObject:
271
+ value: JsonObject = {
272
+ "id": _string(record, "id"),
273
+ "subject_ref": _string(record, "subject_ref"),
274
+ "outcome": _string(record, "outcome"),
275
+ "evidence_refs": _strings(record, "evidence_refs"),
276
+ "authority": _authority_summary(_object(record, "authority")),
277
+ "public_rationale": _string(record, "public_rationale"),
278
+ }
279
+ policy_ref = _optional_string(record, "policy_ref")
280
+ if policy_ref is not None:
281
+ value["policy_ref"] = policy_ref
282
+ return value
283
+
284
+
285
+ def _transition_summary(record: JsonObject) -> JsonObject:
286
+ value: JsonObject = {
287
+ "id": _string(record, "id"),
288
+ "subject_ref": _string(record, "subject_ref"),
289
+ "from_status": _string(record, "from_status"),
290
+ "to_status": _string(record, "to_status"),
291
+ "evidence_refs": _strings(record, "evidence_refs"),
292
+ "authorized_by": _actor_summary(_object(record, "authorized_by")),
293
+ "reason": _string(record, "reason"),
294
+ }
295
+ policy_ref = _optional_string(record, "policy_ref")
296
+ if policy_ref is not None:
297
+ value["policy_ref"] = policy_ref
298
+ verdict_ref = _optional_string(record, "verdict_ref")
299
+ if verdict_ref is not None:
300
+ value["verdict_ref"] = verdict_ref
301
+ return value
302
+
303
+
304
+ def _decision_summary(record: JsonObject) -> JsonObject:
305
+ value: JsonObject = {
306
+ "id": _string(record, "id"),
307
+ "question": _string(record, "question"),
308
+ "disposition": _string(record, "disposition"),
309
+ "authorized_by": _actor_summary(_object(record, "authorized_by")),
310
+ "relied_on_claim_refs": _strings(record, "relied_on_claim_refs"),
311
+ "unresolved_claim_refs": _strings(record, "unresolved_claim_refs"),
312
+ }
313
+ policy_ref = _optional_string(record, "policy_ref")
314
+ if policy_ref is not None:
315
+ value["policy_ref"] = policy_ref
316
+ return value
317
+
318
+
319
+ class ReasoningReceiptValidationError(ValueError):
320
+ """Raised when a generated or external reasoning receipt is invalid."""
321
+
322
+
323
+ class ReasoningReceiptFormatError(ValueError):
324
+ """Raised when a receipt file cannot be decoded as a JSON object."""
325
+
326
+ def __init__(self, path: Path, detail: str) -> None:
327
+ self.path: Path = path
328
+ self.detail: str = detail
329
+ super().__init__(f"{path}: {detail}")
330
+
331
+
332
+ def decode_receipt_document(content: bytes, *, path: StrPath) -> JsonObject:
333
+ """Decode receipt bytes into one strict JSON object without schema checks.
334
+
335
+ ``path`` names the source in diagnostics only; nothing is read from it.
336
+ """
337
+
338
+ source = Path(path)
339
+ try:
340
+ text = content.decode("utf-8")
341
+ except UnicodeDecodeError as error:
342
+ raise ReasoningReceiptFormatError(
343
+ source,
344
+ f"receipt is not valid UTF-8: {error}",
345
+ ) from error
346
+ try:
347
+ value = strict_json_loads(text)
348
+ except (json.JSONDecodeError, ValueError) as error:
349
+ raise ReasoningReceiptFormatError(
350
+ source,
351
+ f"invalid JSON: {error}",
352
+ ) from error
353
+ if not isinstance(value, dict):
354
+ raise ReasoningReceiptFormatError(
355
+ source,
356
+ "receipt must contain one JSON object",
357
+ )
358
+ return value
359
+
360
+
361
+ class ReasoningReceiptValidator:
362
+ """Validate reasoning receipts against the canonical packaged schema."""
363
+
364
+ def __init__(self) -> None:
365
+ schema_resource = files("itself").joinpath(
366
+ "schemas",
367
+ "v0alpha2",
368
+ "reasoning-receipt.schema.json",
369
+ )
370
+ schema = cast(
371
+ JsonObject,
372
+ strict_json_loads(schema_resource.read_text(encoding="utf-8")),
373
+ )
374
+ Draft202012Validator.check_schema(schema)
375
+ self._validator = cast(
376
+ _ReceiptSchemaValidator,
377
+ Draft202012Validator(schema, format_checker=schema_format_checker()),
378
+ )
379
+
380
+ def errors(self, receipt: JsonValue) -> list[str]:
381
+ """Return stable, human-readable receipt validation errors."""
382
+
383
+ issues = sorted(
384
+ self._validator.iter_errors(receipt),
385
+ key=lambda error: tuple(str(item) for item in error.absolute_path),
386
+ )
387
+ return [
388
+ f"{_format_path(tuple(issue.absolute_path))}: {issue.message}"
389
+ for issue in issues
390
+ ]
391
+
392
+ def validate(self, receipt: JsonValue) -> None:
393
+ """Validate a receipt or raise ReasoningReceiptValidationError."""
394
+
395
+ issues = self.errors(receipt)
396
+ if issues:
397
+ raise ReasoningReceiptValidationError("\n".join(issues))
398
+
399
+ def is_valid(self, receipt: JsonValue) -> bool:
400
+ """Return whether a receipt conforms to the canonical format."""
401
+
402
+ return not self.errors(receipt)
403
+
404
+ def validate_against_ledger(
405
+ self,
406
+ receipt: JsonValue,
407
+ ledger: Ledger,
408
+ ) -> None:
409
+ """Validate shape and require the exact deterministic ledger projection."""
410
+
411
+ self.validate(receipt)
412
+ if receipt != build_reasoning_receipt(ledger):
413
+ raise ReasoningReceiptValidationError(
414
+ "receipt does not match the canonical projection of the supplied ledger"
415
+ )
416
+
417
+
418
+ class JsonReceiptStore:
419
+ """Load and atomically persist schema-valid reasoning receipt documents."""
420
+
421
+ def __init__(
422
+ self,
423
+ path: StrPath,
424
+ validator: ReasoningReceiptValidator | None = None,
425
+ ) -> None:
426
+ self.path: Path = Path(path)
427
+ self._validator = validator or ReasoningReceiptValidator()
428
+
429
+ def load(self, *, max_bytes: int | None = None) -> JsonObject:
430
+ """Decode and validate a receipt document from disk."""
431
+
432
+ if max_bytes is not None and max_bytes < 0:
433
+ raise ValueError("max_bytes must not be negative")
434
+ metadata = self.path.lstat()
435
+ if stat.S_ISLNK(metadata.st_mode):
436
+ raise OSError(f"receipt path must not be a symbolic link: {self.path}")
437
+ if not stat.S_ISREG(metadata.st_mode):
438
+ raise OSError(f"receipt path must be a regular file: {self.path}")
439
+
440
+ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
441
+ flags |= getattr(os, "O_CLOEXEC", 0) | getattr(os, "O_NOFOLLOW", 0)
442
+ descriptor = os.open(self.path, flags)
443
+ try:
444
+ opened_metadata = os.fstat(descriptor)
445
+ if not stat.S_ISREG(opened_metadata.st_mode) or (
446
+ opened_metadata.st_dev,
447
+ opened_metadata.st_ino,
448
+ ) != (metadata.st_dev, metadata.st_ino):
449
+ raise OSError(f"receipt path changed while opening: {self.path}")
450
+ if max_bytes is not None and opened_metadata.st_size > max_bytes:
451
+ raise ReasoningReceiptFormatError(
452
+ self.path,
453
+ f"receipt size exceeds limit {max_bytes} bytes",
454
+ )
455
+ except BaseException:
456
+ os.close(descriptor)
457
+ raise
458
+
459
+ with os.fdopen(descriptor, "rb") as handle:
460
+ source_bytes = handle.read(-1 if max_bytes is None else max_bytes + 1)
461
+ final_size = os.fstat(handle.fileno()).st_size
462
+ if max_bytes is not None and len(source_bytes) > max_bytes:
463
+ raise ReasoningReceiptFormatError(
464
+ self.path,
465
+ f"receipt size exceeds limit {max_bytes} bytes",
466
+ )
467
+ if (
468
+ len(source_bytes) != opened_metadata.st_size
469
+ or final_size != opened_metadata.st_size
470
+ ):
471
+ raise OSError(f"receipt path changed while reading: {self.path}")
472
+ value = decode_receipt_document(source_bytes, path=self.path)
473
+ self._validator.validate(value)
474
+ return value
475
+
476
+ def write(self, receipt: JsonObject, *, max_bytes: int | None = None) -> None:
477
+ """Validate and atomically replace the stored receipt document.
478
+
479
+ With ``max_bytes``, a receipt that serializes to more bytes is refused
480
+ before anything is written, so ``load`` with the same limit can read
481
+ every receipt this method stores.
482
+ """
483
+
484
+ if max_bytes is not None and max_bytes < 0:
485
+ raise ValueError("max_bytes must not be negative")
486
+ self._validator.validate(receipt)
487
+ content = (
488
+ json.dumps(
489
+ receipt,
490
+ allow_nan=False,
491
+ ensure_ascii=False,
492
+ indent=2,
493
+ sort_keys=True,
494
+ )
495
+ + "\n"
496
+ ).encode("utf-8")
497
+ if max_bytes is not None and len(content) > max_bytes:
498
+ raise ReasoningReceiptFormatError(
499
+ self.path,
500
+ f"receipt size {len(content)} bytes exceeds limit {max_bytes} bytes",
501
+ )
502
+ parent = self.path.parent
503
+ parent.mkdir(parents=True, exist_ok=True)
504
+ try:
505
+ original_metadata = self.path.lstat()
506
+ except FileNotFoundError:
507
+ original_metadata = None
508
+ if original_metadata is not None:
509
+ if stat.S_ISLNK(original_metadata.st_mode):
510
+ raise OSError(f"receipt path must not be a symbolic link: {self.path}")
511
+ if not stat.S_ISREG(original_metadata.st_mode):
512
+ raise OSError(f"receipt path must be a regular file: {self.path}")
513
+
514
+ descriptor, temporary_name = tempfile.mkstemp(
515
+ dir=parent,
516
+ prefix=f".{self.path.name}.",
517
+ suffix=".tmp",
518
+ )
519
+ temporary_path = Path(temporary_name)
520
+ try:
521
+ with os.fdopen(descriptor, "wb") as handle:
522
+ handle.write(content)
523
+ handle.flush()
524
+ os.fsync(handle.fileno())
525
+
526
+ try:
527
+ current_metadata = self.path.lstat()
528
+ except FileNotFoundError:
529
+ current_metadata = None
530
+ if original_metadata is None:
531
+ if current_metadata is not None:
532
+ raise OSError(f"receipt path appeared while writing: {self.path}")
533
+ elif current_metadata is None or (
534
+ current_metadata.st_dev,
535
+ current_metadata.st_ino,
536
+ ) != (
537
+ original_metadata.st_dev,
538
+ original_metadata.st_ino,
539
+ ):
540
+ raise OSError(f"receipt path changed while writing: {self.path}")
541
+ else:
542
+ temporary_path.chmod(stat.S_IMODE(original_metadata.st_mode))
543
+ os.replace(temporary_path, self.path)
544
+ finally:
545
+ temporary_path.unlink(missing_ok=True)
546
+
547
+
548
+ def build_reasoning_receipt(ledger: Ledger) -> JsonObject:
549
+ """Build and validate a deterministic public receipt for one valid ledger."""
550
+
551
+ records = _canonical_records(ledger)
552
+ summary = summarize_ledger(ledger)
553
+ digest = ledger_sha256(ledger)
554
+ protocol_versions = sorted(
555
+ {_string(record, "protocol_version") for record in records}
556
+ )
557
+ source_ledger: JsonObject = {
558
+ "canonicalization": LEDGER_CANONICALIZATION,
559
+ "record_count": len(records),
560
+ "protocol_versions": _json_strings(protocol_versions),
561
+ "digest": {
562
+ "algorithm": "sha256",
563
+ "value": digest,
564
+ },
565
+ }
566
+ record_counts: JsonObject = {
567
+ kind: count for kind, count in summary.record_counts.items()
568
+ }
569
+ receipt: JsonObject = {
570
+ "receipt_version": RECEIPT_VERSION,
571
+ "receipt_id": f"urn:sha256:{digest}",
572
+ "source_ledger": source_ledger,
573
+ "assurance_basis": _json_strings(_ASSURANCE_BASIS),
574
+ "limitations": _json_strings(_LIMITATIONS),
575
+ "record_counts": record_counts,
576
+ "subjects": _json_objects(_subject_summaries(records, ledger)),
577
+ "artifacts": _json_objects(
578
+ tuple(
579
+ _artifact_summary(record)
580
+ for record in records
581
+ if _string(record, "kind") == "artifact_reference"
582
+ )
583
+ ),
584
+ "tests": _json_objects(
585
+ tuple(
586
+ _test_summary(record)
587
+ for record in records
588
+ if _string(record, "kind") == "test"
589
+ )
590
+ ),
591
+ "evidence": _json_objects(
592
+ tuple(
593
+ _evidence_summary(record)
594
+ for record in records
595
+ if _string(record, "kind") == "evidence"
596
+ )
597
+ ),
598
+ "verdicts": _json_objects(
599
+ tuple(
600
+ _verdict_summary(record)
601
+ for record in records
602
+ if _string(record, "kind") == "verdict"
603
+ )
604
+ ),
605
+ "transitions": _json_objects(
606
+ tuple(
607
+ _transition_summary(record)
608
+ for record in records
609
+ if _string(record, "kind") == "status_transition"
610
+ )
611
+ ),
612
+ "decisions": _json_objects(
613
+ tuple(
614
+ _decision_summary(record)
615
+ for record in records
616
+ if _string(record, "kind") == "decision"
617
+ )
618
+ ),
619
+ }
620
+ ReasoningReceiptValidator().validate(receipt)
621
+ return receipt