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/cli.py ADDED
@@ -0,0 +1,719 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ # Copyright (C) 2026 Greater Expanse LLC
3
+
4
+ """Command-line utilities for protocol records and local ledgers."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+ from collections.abc import Collection, Sequence
13
+ from datetime import UTC, datetime
14
+ from pathlib import Path
15
+ from types import MappingProxyType
16
+ from typing import Final, cast
17
+
18
+ from ._json import strict_json_loads
19
+ from ._version import __version__
20
+ from .bundle import BundleIntegrityError, BundleValidator
21
+ from .evidence_bundle import (
22
+ DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS,
23
+ DEFAULT_EVIDENCE_BUNDLE_LIMITS,
24
+ EvidenceBundleBuilder,
25
+ EvidenceBundleBuildError,
26
+ EvidenceBundleFile,
27
+ EvidenceBundleFileRole,
28
+ EvidenceBundleValidationError,
29
+ EvidenceBundleValidator,
30
+ )
31
+ from .ledger import JsonlLedgerStore, Ledger, LedgerFormatError
32
+ from .receipts import (
33
+ JsonReceiptStore,
34
+ ReasoningReceiptFormatError,
35
+ ReasoningReceiptValidationError,
36
+ ReasoningReceiptValidator,
37
+ build_reasoning_receipt,
38
+ )
39
+ from .reporting import replay_subjects, summarize_ledger
40
+ from .schema_export import SchemaExportError, export_schemas
41
+ from .types import JsonObject, JsonValue
42
+ from .validation import ProtocolValidator
43
+
44
+
45
+ class _RecordFileError(ValueError):
46
+ pass
47
+
48
+
49
+ # Ledgers and receipts loaded here use the documented evidence-bundle ceilings,
50
+ # the bounds a default closed bundle enforces. `ledger append` loads through
51
+ # JsonlLedgerStore.extend, which takes no limits.
52
+ _CLI_LIMITS: Final = DEFAULT_EVIDENCE_BUNDLE_LIMITS
53
+
54
+ # Media types for --input and --supplemental files by lowercase suffix. The
55
+ # mimetypes module reads host files such as /etc/mime.types and changes across
56
+ # Python releases, which would make --created-at regeneration host-dependent.
57
+ _MEDIA_TYPES: Final = MappingProxyType(
58
+ {
59
+ ".csv": "text/csv",
60
+ ".gif": "image/gif",
61
+ ".htm": "text/html",
62
+ ".html": "text/html",
63
+ ".jpeg": "image/jpeg",
64
+ ".jpg": "image/jpeg",
65
+ ".json": "application/json",
66
+ ".jsonl": "application/x-ndjson",
67
+ ".log": "text/plain",
68
+ ".md": "text/markdown",
69
+ ".ndjson": "application/x-ndjson",
70
+ ".pdf": "application/pdf",
71
+ ".png": "image/png",
72
+ ".svg": "image/svg+xml",
73
+ ".tsv": "text/tab-separated-values",
74
+ ".txt": "text/plain",
75
+ ".webp": "image/webp",
76
+ ".xml": "application/xml",
77
+ ".yaml": "application/yaml",
78
+ ".yml": "application/yaml",
79
+ ".zip": "application/zip",
80
+ }
81
+ )
82
+
83
+
84
+ def _timestamp_argument(value: str) -> datetime:
85
+ try:
86
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
87
+ except ValueError as error:
88
+ raise argparse.ArgumentTypeError(
89
+ f"{value!r} is not an ISO 8601 date-time"
90
+ ) from error
91
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
92
+ raise argparse.ArgumentTypeError("date-time must include a UTC offset")
93
+ return parsed.astimezone(UTC)
94
+
95
+
96
+ def _add_external_refs(parser: argparse.ArgumentParser) -> None:
97
+ parser.add_argument(
98
+ "--external-ref",
99
+ action="append",
100
+ default=[],
101
+ metavar="ID",
102
+ help="declare an unresolved identifier external; may be repeated",
103
+ )
104
+
105
+
106
+ def _add_trusted_authorizers(parser: argparse.ArgumentParser) -> None:
107
+ parser.add_argument(
108
+ "--trusted-authorizer",
109
+ action="append",
110
+ metavar="ID",
111
+ help=(
112
+ "refuse evidence-backed transitions authorized by any other declared "
113
+ "actor id; may be repeated"
114
+ ),
115
+ )
116
+
117
+
118
+ def _parser() -> argparse.ArgumentParser:
119
+ parser = argparse.ArgumentParser(
120
+ description="Validate and inspect Claim and Evidence Protocol records."
121
+ )
122
+ parser.add_argument(
123
+ "--version",
124
+ action="version",
125
+ version=f"%(prog)s {__version__}",
126
+ )
127
+ subcommands = parser.add_subparsers(dest="command", required=True)
128
+
129
+ validate = subcommands.add_parser(
130
+ "validate",
131
+ help="validate individual JSON protocol records",
132
+ )
133
+ validate.add_argument("files", nargs="+", type=Path)
134
+
135
+ bundle = subcommands.add_parser(
136
+ "bundle",
137
+ help="create or validate a closed, digest-inventoried evidence bundle",
138
+ )
139
+ bundle_commands = bundle.add_subparsers(dest="bundle_command", required=True)
140
+ bundle_create = bundle_commands.add_parser(
141
+ "create",
142
+ help="materialize a validated ledger, receipt, and referenced artifacts",
143
+ )
144
+ bundle_create.add_argument("ledger", type=Path)
145
+ bundle_create.add_argument("destination", type=Path)
146
+ bundle_create.add_argument("--title", required=True)
147
+ bundle_create.add_argument(
148
+ "--created-at",
149
+ type=_timestamp_argument,
150
+ help="bundle date-time with UTC offset; defaults to the current time",
151
+ )
152
+ bundle_create.add_argument(
153
+ "--artifact",
154
+ action="append",
155
+ default=[],
156
+ metavar="RECORD_REF=FILE",
157
+ help="map an artifact_reference record to its source file; may be repeated",
158
+ )
159
+ bundle_create.add_argument(
160
+ "--input",
161
+ action="append",
162
+ default=[],
163
+ type=Path,
164
+ metavar="FILE",
165
+ help="include a file under inputs/; may be repeated",
166
+ )
167
+ bundle_create.add_argument(
168
+ "--supplemental",
169
+ action="append",
170
+ default=[],
171
+ type=Path,
172
+ metavar="FILE",
173
+ help="include a file under supplemental/; may be repeated",
174
+ )
175
+ bundle_create.add_argument(
176
+ "--limitation",
177
+ action="append",
178
+ default=[],
179
+ metavar="TEXT",
180
+ help="add a bundle-specific limitation; may be repeated",
181
+ )
182
+ _add_trusted_authorizers(bundle_create)
183
+ bundle_validate = bundle_commands.add_parser(
184
+ "validate",
185
+ help="verify bundle bytes, ledger, receipt, and artifact bindings",
186
+ )
187
+ bundle_validate.add_argument("bundle", type=Path)
188
+ _add_trusted_authorizers(bundle_validate)
189
+
190
+ ledger = subcommands.add_parser(
191
+ "ledger",
192
+ help="write and inspect a local JSON Lines ledger",
193
+ )
194
+ ledger_commands = ledger.add_subparsers(dest="ledger_command", required=True)
195
+
196
+ ledger_validate = ledger_commands.add_parser(
197
+ "validate",
198
+ help="validate and replay a complete ledger",
199
+ )
200
+ ledger_validate.add_argument("ledger", type=Path)
201
+ _add_external_refs(ledger_validate)
202
+ _add_trusted_authorizers(ledger_validate)
203
+
204
+ append = ledger_commands.add_parser(
205
+ "append",
206
+ help="atomically append one or more JSON record files",
207
+ )
208
+ append.add_argument("ledger", type=Path)
209
+ append.add_argument("records", nargs="+", type=Path)
210
+ _add_external_refs(append)
211
+ _add_trusted_authorizers(append)
212
+
213
+ replay = ledger_commands.add_parser(
214
+ "replay",
215
+ help="show initial and current state for every claim and hypothesis",
216
+ )
217
+ replay.add_argument("ledger", type=Path)
218
+ replay.add_argument("--format", choices=("text", "json"), default="text")
219
+ _add_external_refs(replay)
220
+ _add_trusted_authorizers(replay)
221
+
222
+ summary = ledger_commands.add_parser(
223
+ "summary",
224
+ help="summarize record kinds and current epistemic states",
225
+ )
226
+ summary.add_argument("ledger", type=Path)
227
+ summary.add_argument("--format", choices=("text", "json"), default="text")
228
+ _add_external_refs(summary)
229
+ _add_trusted_authorizers(summary)
230
+
231
+ receipt = subcommands.add_parser(
232
+ "receipt",
233
+ help="generate and validate deterministic reasoning receipts",
234
+ )
235
+ receipt_commands = receipt.add_subparsers(dest="receipt_command", required=True)
236
+
237
+ receipt_generate = receipt_commands.add_parser(
238
+ "generate",
239
+ help="generate a receipt from a validated ledger",
240
+ )
241
+ receipt_generate.add_argument("ledger", type=Path)
242
+ receipt_generate.add_argument("--output", "-o", type=Path)
243
+ _add_external_refs(receipt_generate)
244
+ _add_trusted_authorizers(receipt_generate)
245
+
246
+ receipt_validate = receipt_commands.add_parser(
247
+ "validate",
248
+ help="validate receipt shape and optionally bind it to a ledger",
249
+ )
250
+ receipt_validate.add_argument("receipt", type=Path)
251
+ receipt_validate.add_argument("--ledger", type=Path)
252
+ _add_external_refs(receipt_validate)
253
+ _add_trusted_authorizers(receipt_validate)
254
+
255
+ schema = subcommands.add_parser(
256
+ "schema",
257
+ help="inspect or export the canonical packaged JSON Schemas",
258
+ )
259
+ schema_commands = schema.add_subparsers(dest="schema_command", required=True)
260
+ schema_export = schema_commands.add_parser(
261
+ "export",
262
+ help="export canonical schemas, catalogs, and checksums",
263
+ )
264
+ schema_export.add_argument("destination", type=Path)
265
+ return parser
266
+
267
+
268
+ def _load_record(path: Path) -> JsonObject:
269
+ try:
270
+ source = path.read_text(encoding="utf-8")
271
+ except (OSError, UnicodeError) as error:
272
+ raise _RecordFileError(f"{path}: cannot read record: {error}") from error
273
+ try:
274
+ value = strict_json_loads(source)
275
+ except (json.JSONDecodeError, ValueError) as error:
276
+ raise _RecordFileError(f"{path}: invalid JSON: {error}") from error
277
+ if not isinstance(value, dict):
278
+ raise _RecordFileError(f"{path}: protocol record must be a JSON object")
279
+ return value
280
+
281
+
282
+ def _validate_records(paths: Sequence[Path]) -> int:
283
+ validator = ProtocolValidator()
284
+ failed = False
285
+ for path in paths:
286
+ try:
287
+ record = _load_record(path)
288
+ except _RecordFileError as error:
289
+ print(f"FAIL {error}", file=sys.stderr)
290
+ failed = True
291
+ continue
292
+
293
+ issues = validator.errors(record)
294
+ if issues:
295
+ print(f"FAIL {path}", file=sys.stderr)
296
+ for issue in issues:
297
+ print(f" {issue}", file=sys.stderr)
298
+ failed = True
299
+ else:
300
+ print(f"PASS {path}")
301
+ return 1 if failed else 0
302
+
303
+
304
+ def _ledger_store(
305
+ path: Path,
306
+ trusted_authorizers: Collection[str] | None,
307
+ ) -> JsonlLedgerStore:
308
+ return JsonlLedgerStore(
309
+ path,
310
+ validator=BundleValidator(trusted_authorizers=trusted_authorizers),
311
+ )
312
+
313
+
314
+ def _load_existing_ledger(
315
+ path: Path,
316
+ external_refs: Collection[str],
317
+ trusted_authorizers: Collection[str] | None,
318
+ ) -> Ledger:
319
+ if not path.is_file():
320
+ raise _RecordFileError(f"{path}: ledger file does not exist")
321
+ return _ledger_store(path, trusted_authorizers).load(
322
+ external_refs=external_refs,
323
+ max_records=_CLI_LIMITS.max_ledger_records,
324
+ max_bytes=_CLI_LIMITS.max_ledger_bytes,
325
+ )
326
+
327
+
328
+ def _record_string(record: JsonObject, field: str) -> str:
329
+ value = record[field]
330
+ if not isinstance(value, str):
331
+ raise TypeError(f"validated record field {field!r} was not a string")
332
+ return value
333
+
334
+
335
+ def _artifact_source_map(specifications: Sequence[str]) -> dict[str, Path]:
336
+ sources: dict[str, Path] = {}
337
+ for specification in specifications:
338
+ record_ref, separator, source = specification.partition("=")
339
+ if not separator or not record_ref.strip() or not source:
340
+ raise _RecordFileError(
341
+ "artifact mapping must use non-empty RECORD_REF=FILE syntax"
342
+ )
343
+ if record_ref in sources:
344
+ raise _RecordFileError(
345
+ f"duplicate artifact mapping for record {record_ref!r}"
346
+ )
347
+ sources[record_ref] = Path(source)
348
+ return sources
349
+
350
+
351
+ def _media_type(path: Path) -> str:
352
+ return _MEDIA_TYPES.get(path.suffix.lower(), "application/octet-stream")
353
+
354
+
355
+ def _named_bundle_file(
356
+ source: Path,
357
+ *,
358
+ directory: str,
359
+ role: EvidenceBundleFileRole,
360
+ ) -> EvidenceBundleFile:
361
+ return EvidenceBundleFile.from_path(
362
+ source,
363
+ path=f"{directory}/{source.name}",
364
+ media_type=_media_type(source),
365
+ role=role,
366
+ )
367
+
368
+
369
+ def _bundle_create(
370
+ ledger_path: Path,
371
+ destination: Path,
372
+ *,
373
+ title: str,
374
+ created_at: datetime | None,
375
+ artifact_specs: Sequence[str],
376
+ input_paths: Sequence[Path],
377
+ supplemental_paths: Sequence[Path],
378
+ additional_limitations: Sequence[str],
379
+ trusted_authorizers: Collection[str] | None,
380
+ ) -> int:
381
+ ledger = _load_existing_ledger(ledger_path, (), trusted_authorizers)
382
+ artifact_records = {
383
+ _record_string(record, "id"): record
384
+ for record in ledger.records
385
+ if _record_string(record, "kind") == "artifact_reference"
386
+ }
387
+ artifact_sources = _artifact_source_map(artifact_specs)
388
+ unknown = sorted(set(artifact_sources).difference(artifact_records))
389
+ missing = sorted(set(artifact_records).difference(artifact_sources))
390
+ if unknown or missing:
391
+ raise _RecordFileError(
392
+ "artifact mappings must exactly match ledger artifact_reference records; "
393
+ f"missing={missing}, unknown={unknown}"
394
+ )
395
+
396
+ bundle_files = [
397
+ *(
398
+ _named_bundle_file(
399
+ source,
400
+ directory="inputs",
401
+ role=EvidenceBundleFileRole.INPUT,
402
+ )
403
+ for source in input_paths
404
+ ),
405
+ *(
406
+ EvidenceBundleFile.from_path(
407
+ artifact_sources[record_ref],
408
+ path=_record_string(record, "uri"),
409
+ media_type=_record_string(record, "media_type"),
410
+ role=EvidenceBundleFileRole.ARTIFACT,
411
+ record_ref=record_ref,
412
+ )
413
+ for record_ref, record in artifact_records.items()
414
+ ),
415
+ *(
416
+ _named_bundle_file(
417
+ source,
418
+ directory="supplemental",
419
+ role=EvidenceBundleFileRole.SUPPLEMENTAL,
420
+ )
421
+ for source in supplemental_paths
422
+ ),
423
+ ]
424
+ limitations = (
425
+ *DEFAULT_EVIDENCE_BUNDLE_LIMITATIONS,
426
+ *additional_limitations,
427
+ )
428
+ verified = EvidenceBundleBuilder(
429
+ validator=EvidenceBundleValidator(trusted_authorizers=trusted_authorizers)
430
+ ).build(
431
+ destination,
432
+ ledger=ledger,
433
+ title=title,
434
+ created_at=created_at,
435
+ files=bundle_files,
436
+ limitations=limitations,
437
+ )
438
+ file_count = len(cast(list[JsonValue], verified.manifest["files"]))
439
+ print(
440
+ f"PASS {destination}: {verified.ledger.snapshot.record_count} records, "
441
+ f"{file_count} files, {verified.manifest['bundle_id']}"
442
+ )
443
+ return 0
444
+
445
+
446
+ def _bundle_validate(
447
+ path: Path,
448
+ trusted_authorizers: Collection[str] | None,
449
+ ) -> int:
450
+ verified = EvidenceBundleValidator(
451
+ trusted_authorizers=trusted_authorizers
452
+ ).validate(path)
453
+ file_count = len(cast(list[JsonValue], verified.manifest["files"]))
454
+ print(
455
+ f"PASS {path}: {verified.ledger.snapshot.record_count} records, "
456
+ f"{file_count} files, {verified.manifest['bundle_id']}"
457
+ )
458
+ return 0
459
+
460
+
461
+ def _ledger_validate(
462
+ path: Path,
463
+ external_refs: Collection[str],
464
+ trusted_authorizers: Collection[str] | None,
465
+ ) -> int:
466
+ ledger = _load_existing_ledger(path, external_refs, trusted_authorizers)
467
+ summary = summarize_ledger(ledger)
468
+ print(
469
+ f"PASS {path}: {summary.record_count} records, {summary.subject_count} subjects"
470
+ )
471
+ return 0
472
+
473
+
474
+ def _ledger_append(
475
+ path: Path,
476
+ record_paths: Sequence[Path],
477
+ external_refs: Collection[str],
478
+ trusted_authorizers: Collection[str] | None,
479
+ ) -> int:
480
+ records = tuple(_load_record(record_path) for record_path in record_paths)
481
+ snapshot = _ledger_store(path, trusted_authorizers).extend(
482
+ records,
483
+ external_refs=external_refs,
484
+ )
485
+ print(
486
+ f"PASS {path}: appended {len(records)} records; "
487
+ f"ledger now contains {snapshot.record_count} records"
488
+ )
489
+ return 0
490
+
491
+
492
+ def _ledger_replay(
493
+ path: Path,
494
+ external_refs: Collection[str],
495
+ trusted_authorizers: Collection[str] | None,
496
+ output_format: str,
497
+ ) -> int:
498
+ ledger = _load_existing_ledger(path, external_refs, trusted_authorizers)
499
+ subjects = replay_subjects(ledger)
500
+ if output_format == "json":
501
+ print(
502
+ json.dumps(
503
+ [subject.to_json_object() for subject in subjects],
504
+ ensure_ascii=False,
505
+ indent=2,
506
+ sort_keys=True,
507
+ )
508
+ )
509
+ return 0
510
+
511
+ if not subjects:
512
+ print("No claims or hypotheses.")
513
+ return 0
514
+ for subject in subjects:
515
+ transition_label = (
516
+ "transition" if subject.transition_count == 1 else "transitions"
517
+ )
518
+ print(
519
+ f"{subject.subject_id}\t{subject.kind.value}\t"
520
+ f"{subject.initial_status.value} -> {subject.current_status.value}\t"
521
+ f"{subject.transition_count} {transition_label}"
522
+ )
523
+ return 0
524
+
525
+
526
+ def _ledger_summary(
527
+ path: Path,
528
+ external_refs: Collection[str],
529
+ trusted_authorizers: Collection[str] | None,
530
+ output_format: str,
531
+ ) -> int:
532
+ summary = summarize_ledger(
533
+ _load_existing_ledger(path, external_refs, trusted_authorizers)
534
+ )
535
+ if output_format == "json":
536
+ print(
537
+ json.dumps(
538
+ summary.to_json_object(),
539
+ ensure_ascii=False,
540
+ indent=2,
541
+ sort_keys=True,
542
+ )
543
+ )
544
+ return 0
545
+
546
+ print(f"records: {summary.record_count}")
547
+ print(f"subjects: {summary.subject_count}")
548
+ print("records_by_kind:")
549
+ for kind, count in summary.record_counts.items():
550
+ print(f" {kind}: {count}")
551
+ print("current_states:")
552
+ for status, count in summary.state_counts.items():
553
+ print(f" {status.value}: {count}")
554
+ return 0
555
+
556
+
557
+ def _receipt_generate(
558
+ ledger_path: Path,
559
+ output_path: Path | None,
560
+ external_refs: Collection[str],
561
+ trusted_authorizers: Collection[str] | None,
562
+ ) -> int:
563
+ ledger = _load_existing_ledger(ledger_path, external_refs, trusted_authorizers)
564
+ if (
565
+ output_path is not None
566
+ and output_path.exists()
567
+ and os.path.samefile(output_path, ledger_path)
568
+ ):
569
+ raise _RecordFileError(
570
+ f"{output_path}: receipt output would replace the source ledger"
571
+ )
572
+ receipt = build_reasoning_receipt(ledger)
573
+ if output_path is None:
574
+ print(
575
+ json.dumps(
576
+ receipt,
577
+ ensure_ascii=False,
578
+ indent=2,
579
+ sort_keys=True,
580
+ )
581
+ )
582
+ return 0
583
+
584
+ # The receipt must stay readable by `receipt validate` and `bundle create`.
585
+ JsonReceiptStore(output_path).write(
586
+ receipt,
587
+ max_bytes=_CLI_LIMITS.max_receipt_bytes,
588
+ )
589
+ print(f"PASS {output_path}: receipt generated from {ledger_path}")
590
+ return 0
591
+
592
+
593
+ def _receipt_validate(
594
+ receipt_path: Path,
595
+ ledger_path: Path | None,
596
+ external_refs: Collection[str],
597
+ trusted_authorizers: Collection[str] | None,
598
+ ) -> int:
599
+ if ledger_path is None and trusted_authorizers is not None:
600
+ # The authorizers are checked while the ledger replays, so a trust list
601
+ # without the ledger would otherwise pass unchecked.
602
+ raise _RecordFileError(
603
+ f"{receipt_path}: --trusted-authorizer requires --ledger"
604
+ )
605
+ receipt = JsonReceiptStore(receipt_path).load(
606
+ max_bytes=_CLI_LIMITS.max_receipt_bytes
607
+ )
608
+ if ledger_path is None:
609
+ print(f"PASS {receipt_path}: schema-valid receipt")
610
+ return 0
611
+
612
+ ledger = _load_existing_ledger(ledger_path, external_refs, trusted_authorizers)
613
+ ReasoningReceiptValidator().validate_against_ledger(receipt, ledger)
614
+ print(f"PASS {receipt_path}: bound to {ledger_path}")
615
+ return 0
616
+
617
+
618
+ def main(argv: Sequence[str] | None = None) -> int:
619
+ """Run the command-line interface and return a process exit status."""
620
+
621
+ args = _parser().parse_args(argv)
622
+ trusted_authorizers = cast(
623
+ list[str] | None,
624
+ getattr(args, "trusted_authorizer", None),
625
+ )
626
+ try:
627
+ if args.command == "validate":
628
+ return _validate_records(cast(list[Path], args.files))
629
+
630
+ if args.command == "bundle" and args.bundle_command == "create":
631
+ return _bundle_create(
632
+ cast(Path, args.ledger),
633
+ cast(Path, args.destination),
634
+ title=cast(str, args.title),
635
+ created_at=cast(datetime | None, args.created_at),
636
+ artifact_specs=cast(list[str], args.artifact),
637
+ input_paths=cast(list[Path], args.input),
638
+ supplemental_paths=cast(list[Path], args.supplemental),
639
+ additional_limitations=cast(list[str], args.limitation),
640
+ trusted_authorizers=trusted_authorizers,
641
+ )
642
+
643
+ if args.command == "bundle" and args.bundle_command == "validate":
644
+ return _bundle_validate(cast(Path, args.bundle), trusted_authorizers)
645
+
646
+ if args.command == "ledger":
647
+ ledger_path = cast(Path, args.ledger)
648
+ external_refs = cast(list[str], args.external_ref)
649
+ if args.ledger_command == "validate":
650
+ return _ledger_validate(
651
+ ledger_path,
652
+ external_refs,
653
+ trusted_authorizers,
654
+ )
655
+ if args.ledger_command == "append":
656
+ return _ledger_append(
657
+ ledger_path,
658
+ cast(list[Path], args.records),
659
+ external_refs,
660
+ trusted_authorizers,
661
+ )
662
+ if args.ledger_command == "replay":
663
+ return _ledger_replay(
664
+ ledger_path,
665
+ external_refs,
666
+ trusted_authorizers,
667
+ cast(str, args.format),
668
+ )
669
+ if args.ledger_command == "summary":
670
+ return _ledger_summary(
671
+ ledger_path,
672
+ external_refs,
673
+ trusted_authorizers,
674
+ cast(str, args.format),
675
+ )
676
+
677
+ if args.command == "receipt":
678
+ external_refs = cast(list[str], args.external_ref)
679
+ if args.receipt_command == "generate":
680
+ return _receipt_generate(
681
+ cast(Path, args.ledger),
682
+ cast(Path | None, args.output),
683
+ external_refs,
684
+ trusted_authorizers,
685
+ )
686
+ if args.receipt_command == "validate":
687
+ return _receipt_validate(
688
+ cast(Path, args.receipt),
689
+ cast(Path | None, args.ledger),
690
+ external_refs,
691
+ trusted_authorizers,
692
+ )
693
+
694
+ if args.command == "schema" and args.schema_command == "export":
695
+ snapshot = export_schemas(cast(Path, args.destination))
696
+ print(
697
+ f"PASS {snapshot.destination}: "
698
+ f"exported {len(snapshot.schemas)} canonical schemas"
699
+ )
700
+ return 0
701
+ except (
702
+ BundleIntegrityError,
703
+ EvidenceBundleBuildError,
704
+ EvidenceBundleValidationError,
705
+ LedgerFormatError,
706
+ ReasoningReceiptFormatError,
707
+ ReasoningReceiptValidationError,
708
+ SchemaExportError,
709
+ _RecordFileError,
710
+ OSError,
711
+ ) as error:
712
+ print(f"FAIL {error}", file=sys.stderr)
713
+ return 1
714
+
715
+ raise RuntimeError("unreachable command dispatch")
716
+
717
+
718
+ if __name__ == "__main__":
719
+ raise SystemExit(main())