forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadiness.py
More file actions
1533 lines (1371 loc) · 49.5 KB
/
Copy pathreadiness.py
File metadata and controls
1533 lines (1371 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Deterministic packet-presence evaluation for bounded local workflows.
This module does not decide legal sufficiency, code compliance, eligibility,
or approval. It compares an explicit packet inventory and explicit project
facts with a source-bound requirement manifest. Unknown conditions remain
questions for staff. A stale or changed source prevents a readiness summary
from being published.
"""
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import asdict, dataclass
from datetime import date, timedelta
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
from .dates import SOURCE_REVIEW_WINDOW_DAYS, resolve_today
from .harness.watch import load_sources
SCHEMA_VERSION = 1
SOURCE_MAX_AGE_DAYS = SOURCE_REVIEW_WINDOW_DAYS
TRI_VALUES = ("yes", "no", "unknown")
INVENTORY_STATUSES = ("present", "missing", "unknown", "conflicting")
FINDING_STATUSES = (
"present",
"missing",
"not_applicable",
"conflicting",
"needs_staff_review",
"not_evaluated",
)
OVERALL_STATUSES = (
"known_gaps",
"needs_review",
"no_known_gaps_in_bounded_manifest",
"outside_bounded_workflow",
"source_review_required",
)
APPLICABILITY_STATUSES = ("applies", "unknown", "does_not_apply")
ITEM_TYPES = ("document", "document_content", "action")
PROVENANCE_VALUES = (
"synthetic_applicant_assertion",
"applicant_assertion",
"synthetic_public_record_fixture",
)
_IDENTIFIER = re.compile(r"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$")
_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
_SOURCE_FIELD = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
def _required_text(value: Any, field: str) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{field}: expected non-blank text")
return value.strip()
def _optional_text(value: Any, field: str) -> str | None:
if value is None:
return None
return _required_text(value, field)
def _identifier(value: Any, field: str) -> str:
identifier = _required_text(value, field)
if not _IDENTIFIER.fullmatch(identifier):
raise ValueError(f"{field}: invalid stable identifier")
return identifier
def _exact_keys(
record: dict[str, Any],
allowed: set[str],
required: set[str],
field: str,
) -> None:
unknown = sorted(set(record) - allowed)
missing = sorted(required - set(record))
if unknown:
raise ValueError(f"{field}: unknown fields: {', '.join(unknown)}")
if missing:
raise ValueError(f"{field}: missing fields: {', '.join(missing)}")
def _iso_date(value: Any, field: str, *, today: date) -> str:
text = _required_text(value, field)
if not _DATE.fullmatch(text):
raise ValueError(f"{field}: expected YYYY-MM-DD")
try:
parsed = date.fromisoformat(text)
except ValueError as error:
raise ValueError(f"{field}: invalid date {text!r}") from error
if parsed > today:
raise ValueError(f"{field}: future dates are not allowed")
return text
def _read_json(path: Path, field: str) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as error:
raise ValueError(f"{field}: could not load JSON") from error
def _fingerprint(payload: Any) -> str:
encoded = json.dumps(
payload,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
)
return "sha256:" + hashlib.sha256(encoded.encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class SourceBinding:
source_id: str
url: str
sha256: str
source_checked_on: str
@dataclass(frozen=True)
class Condition:
fact_id: str
equals: str
@dataclass(frozen=True)
class FactDefinition:
fact_id: str
label: str
question: str
allowed_values: tuple[str, ...]
source_id: str | None
source_field: str | None
@dataclass(frozen=True)
class Requirement:
requirement_id: str
label: str
category: str
item_type: str
parent_requirement_id: str | None
applies_when: tuple[Condition, ...]
source_id: str
source_locator: str
source_excerpt: str
def fingerprint(self) -> str:
return _fingerprint(asdict(self))
@dataclass(frozen=True)
class MappingInputSource:
source_id: str
sha256: str
@dataclass(frozen=True)
class MappingProvenance:
version: str
updated_on: str
drafted_by: str
input_source_fingerprints: tuple[MappingInputSource, ...]
review_status: str
review_scope: str
provider: str
model: str
run_record_status: str
@dataclass(frozen=True)
class ReadinessWorkflow:
workflow_id: str
jurisdiction: str
project_type: str
status: str
title: str
scope: str
source_bindings: tuple[SourceBinding, ...]
mapping_provenance: MappingProvenance
applicability: tuple[Condition, ...]
facts: tuple[FactDefinition, ...]
requirements: tuple[Requirement, ...]
def fingerprint(self) -> str:
return _fingerprint(asdict(self))
def fact_map(self) -> dict[str, FactDefinition]:
return {fact.fact_id: fact for fact in self.facts}
def requirement_map(self) -> dict[str, Requirement]:
return {
requirement.requirement_id: requirement for requirement in self.requirements
}
@dataclass(frozen=True)
class PacketFact:
fact_id: str
value: str
provenance: str
source_id: str | None
source_field: str | None
source_checked_on: str | None
@dataclass(frozen=True)
class InventoryItem:
requirement_id: str
status: str
@dataclass(frozen=True)
class ReadinessPacket:
packet_id: str
workflow_id: str
label: str
synthetic: bool
evaluated_on: str
jurisdiction: str
project_type: str
facts: tuple[PacketFact, ...]
inventory: tuple[InventoryItem, ...]
def fingerprint(self) -> str:
return _fingerprint(asdict(self))
def fact_values(self) -> dict[str, str]:
return {fact.fact_id: fact.value for fact in self.facts}
def inventory_map(self) -> dict[str, str]:
return {item.requirement_id: item.status for item in self.inventory}
@dataclass(frozen=True)
class ReadinessFinding:
requirement_id: str
label: str
category: str
status: str
reason: str
source_id: str
source_locator: str
source_excerpt: str
requirement_fingerprint: str
@dataclass(frozen=True)
class ReadinessResult:
packet_id: str
workflow_id: str
applicability_status: str
overall_status: str
evaluated_on: str
workflow_fingerprint: str
packet_fingerprint: str
source_status: str
source_status_as_of: str
source_review_due_on: str
findings: tuple[ReadinessFinding, ...]
staff_questions: tuple[str, ...]
boundary: str
def counts(self) -> dict[str, int]:
return {
status: sum(finding.status == status for finding in self.findings)
for status in FINDING_STATUSES
}
def to_manifest(
self,
workflow: ReadinessWorkflow,
packet: ReadinessPacket,
) -> dict[str, Any]:
return {
"schema_version": 1,
"manifest_type": "prototype_packet_presence",
"packet_id": self.packet_id,
"workflow_id": self.workflow_id,
"applicability_status": self.applicability_status,
"synthetic": packet.synthetic,
"overall_status": self.overall_status,
"evaluated_on": self.evaluated_on,
"workflow_fingerprint": self.workflow_fingerprint,
"packet_fingerprint": self.packet_fingerprint,
"source_status": self.source_status,
"source_status_as_of": self.source_status_as_of,
"source_review_due_on": self.source_review_due_on,
"source_bindings": [
asdict(binding) for binding in workflow.source_bindings
],
"facts": [asdict(fact) for fact in packet.facts],
"inventory": [asdict(item) for item in packet.inventory],
"counts": self.counts(),
"findings": [asdict(finding) for finding in self.findings],
"staff_questions": list(self.staff_questions),
"boundary": self.boundary,
}
@dataclass(frozen=True)
class RemedyReview:
status: str
reviewer: str | None
method: str | None
reviewed_on: str | None
reviewed_version: str | None
content_fingerprint: str | None
@dataclass(frozen=True)
class ReadinessRemedy:
requirement_id: str
requirement_fingerprint: str
action: str
@dataclass(frozen=True)
class ReadinessRemedies:
workflow_id: str
workflow_fingerprint: str
version: str
content_fingerprint: str
updated_on: str
drafted_by: str
review: RemedyReview
entries: tuple[ReadinessRemedy, ...]
def entry_map(self) -> dict[str, ReadinessRemedy]:
return {entry.requirement_id: entry for entry in self.entries}
def _load_condition(
value: Any,
field: str,
facts: dict[str, FactDefinition],
) -> Condition:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
_exact_keys(value, {"fact_id", "equals"}, {"fact_id", "equals"}, field)
fact_id = _identifier(value["fact_id"], f"{field}.fact_id")
if fact_id not in facts:
raise ValueError(f"{field}.fact_id: unknown fact {fact_id!r}")
expected = _required_text(value["equals"], f"{field}.equals")
if expected not in facts[fact_id].allowed_values or expected == "unknown":
raise ValueError(f"{field}.equals: expected a concrete allowed value")
return Condition(fact_id=fact_id, equals=expected)
def _required_literal(value: Any, field: str, expected: str, message: str) -> str:
text = _required_text(value, field)
if text != expected:
raise ValueError(f"{field}: {message}")
return text
def _mapping_input(
value: Any,
field: str,
bindings_by_id: dict[str, SourceBinding],
) -> MappingInputSource:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {"source_id", "sha256"}
_exact_keys(value, keys, keys, field)
source_id = _identifier(value["source_id"], f"{field}.source_id")
binding = bindings_by_id.get(source_id)
if binding is None:
raise ValueError(f"{field}.source_id: source is not bound")
digest = _required_text(value["sha256"], f"{field}.sha256")
if not _SHA256.fullmatch(digest):
raise ValueError(f"{field}.sha256: expected a SHA-256 digest")
if digest != binding.sha256:
raise ValueError(f"{field}.sha256: does not match bound source")
return MappingInputSource(source_id=source_id, sha256=digest)
def _mapping_inputs(
value: Any,
bindings: tuple[SourceBinding, ...],
field: str,
) -> tuple[MappingInputSource, ...]:
if not isinstance(value, list) or not value:
raise ValueError(f"{field}: expected a non-empty list")
bindings_by_id = {binding.source_id: binding for binding in bindings}
inputs: list[MappingInputSource] = []
seen: set[str] = set()
for index, raw_input in enumerate(value):
parsed = _mapping_input(raw_input, f"{field}[{index}]", bindings_by_id)
if parsed.source_id in seen:
raise ValueError(f"{field}[{index}].source_id: duplicate source")
inputs.append(parsed)
seen.add(parsed.source_id)
missing = sorted(set(bindings_by_id) - seen)
if missing:
raise ValueError(f"{field}: missing sources: " + ", ".join(missing))
return tuple(inputs)
def _load_mapping_provenance(
value: Any,
bindings: tuple[SourceBinding, ...],
*,
today: date,
) -> MappingProvenance:
"""Load truthful, review-pending provenance for the AI-assisted mapping."""
field = "workflow.mapping_provenance"
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {
"version",
"updated_on",
"drafted_by",
"input_source_fingerprints",
"review_status",
"review_scope",
"provider",
"model",
"run_record_status",
}
_exact_keys(value, keys, keys, field)
version = _required_text(value["version"], f"{field}.version")
if not _SEMVER.fullmatch(version):
raise ValueError(f"{field}.version: expected semantic version")
updated_on = _iso_date(value["updated_on"], f"{field}.updated_on", today=today)
if date.fromisoformat(updated_on) < max(
date.fromisoformat(binding.source_checked_on) for binding in bindings
):
raise ValueError(
f"{field}.updated_on: cannot predate an input source fingerprint"
)
drafted_by = _required_literal(
value["drafted_by"],
f"{field}.drafted_by",
"ai_assisted",
"current prototype requires ai_assisted",
)
review_status = _required_literal(
value["review_status"],
f"{field}.review_status",
"prototype_review_pending",
"mapping and excerpts remain review-pending",
)
review_scope = _required_literal(
value["review_scope"],
f"{field}.review_scope",
"requirements_excerpts_and_fact_bindings",
"expected requirements_excerpts_and_fact_bindings",
)
provider = _required_literal(
value["provider"],
f"{field}.provider",
"unknown",
"no provider was recorded for this draft",
)
model = _required_literal(
value["model"],
f"{field}.model",
"unknown",
"no model was recorded for this draft",
)
run_record_status = _required_literal(
value["run_record_status"],
f"{field}.run_record_status",
"not_recorded",
"current draft has no run record",
)
inputs = _mapping_inputs(
value["input_source_fingerprints"],
bindings,
f"{field}.input_source_fingerprints",
)
return MappingProvenance(
version=version,
updated_on=updated_on,
drafted_by=drafted_by,
input_source_fingerprints=inputs,
review_status=review_status,
review_scope=review_scope,
provider=provider,
model=model,
run_record_status=run_record_status,
)
def _versioned_record(path: Path, record_name: str) -> dict[str, Any]:
payload = _read_json(path, str(path))
if not isinstance(payload, dict):
raise ValueError(f"{path}: expected an object")
keys = {"schema_version", record_name}
_exact_keys(payload, keys, keys, str(path))
if payload["schema_version"] != SCHEMA_VERSION:
raise ValueError(f"{path}: unsupported schema version")
raw = payload[record_name]
if not isinstance(raw, dict):
raise ValueError(f"{path}.{record_name}: expected an object")
return raw
def _workflow_record(path: Path) -> dict[str, Any]:
raw = _versioned_record(path, "workflow")
keys = {
"workflow_id",
"jurisdiction",
"project_type",
"status",
"title",
"scope",
"source_bindings",
"mapping_provenance",
"applicability",
"facts",
"requirements",
}
_exact_keys(raw, keys, keys, f"{path}.workflow")
return raw
def _source_binding(
value: Any,
field: str,
sources: dict[str, Any],
as_of: date,
) -> SourceBinding:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {"source_id", "url", "sha256", "source_checked_on"}
_exact_keys(value, keys, keys, field)
source_id = _identifier(value["source_id"], f"{field}.source_id")
source = sources.get(source_id)
if source is None:
raise ValueError(f"{field}.source_id: unknown source")
url = _required_text(value["url"], f"{field}.url")
parsed = urlsplit(url)
if (
parsed.scheme != "https"
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
):
raise ValueError(f"{field}.url: expected a public HTTPS URL")
digest = _required_text(value["sha256"], f"{field}.sha256")
if not _SHA256.fullmatch(digest):
raise ValueError(f"{field}.sha256: expected a SHA-256 digest")
checked = _iso_date(
value["source_checked_on"], f"{field}.source_checked_on", today=as_of
)
if source.url != url or source.sha256 != digest or source.fetched_on != checked:
raise ValueError(f"{field}: binding does not match the source registry")
return SourceBinding(source_id, url, digest, checked)
def _source_bindings(
value: Any,
sources: dict[str, Any],
as_of: date,
) -> tuple[SourceBinding, ...]:
if not isinstance(value, list) or not value:
raise ValueError("workflow.source_bindings: expected a non-empty list")
bindings: list[SourceBinding] = []
seen: set[str] = set()
for index, raw_binding in enumerate(value):
field = f"workflow.source_bindings[{index}]"
binding = _source_binding(raw_binding, field, sources, as_of)
if binding.source_id in seen:
raise ValueError(f"{field}.source_id: duplicate source binding")
bindings.append(binding)
seen.add(binding.source_id)
return tuple(bindings)
def _fact_definition(
value: Any,
field: str,
bound_source_ids: set[str],
) -> FactDefinition:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {
"fact_id",
"label",
"question",
"allowed_values",
"source_id",
"source_field",
}
_exact_keys(value, keys, keys, field)
allowed = value["allowed_values"]
if not isinstance(allowed, list) or tuple(allowed) != TRI_VALUES:
raise ValueError(f"{field}.allowed_values: expected yes, no, unknown")
source_id = _optional_text(value["source_id"], f"{field}.source_id")
source_field = _optional_text(value["source_field"], f"{field}.source_field")
if (source_id is None) != (source_field is None):
raise ValueError(f"{field}: source_id and source_field must appear together")
if source_id is not None:
if not _IDENTIFIER.fullmatch(source_id):
raise ValueError(f"{field}.source_id: invalid stable identifier")
if source_id not in bound_source_ids:
raise ValueError(f"{field}.source_id: source is not bound to the workflow")
if source_field is None or not _SOURCE_FIELD.fullmatch(source_field):
raise ValueError(f"{field}.source_field: invalid source field")
return FactDefinition(
fact_id=_identifier(value["fact_id"], f"{field}.fact_id"),
label=_required_text(value["label"], f"{field}.label"),
question=_required_text(value["question"], f"{field}.question"),
allowed_values=tuple(allowed),
source_id=source_id,
source_field=source_field,
)
def _fact_definitions(
value: Any,
bindings: tuple[SourceBinding, ...],
) -> tuple[tuple[FactDefinition, ...], dict[str, FactDefinition]]:
if not isinstance(value, list) or not value:
raise ValueError("workflow.facts: expected a non-empty list")
facts: list[FactDefinition] = []
by_id: dict[str, FactDefinition] = {}
bound_source_ids = {binding.source_id for binding in bindings}
for index, raw_fact in enumerate(value):
field = f"workflow.facts[{index}]"
fact = _fact_definition(raw_fact, field, bound_source_ids)
if fact.fact_id in by_id:
raise ValueError(f"{field}.fact_id: duplicate fact")
facts.append(fact)
by_id[fact.fact_id] = fact
return tuple(facts), by_id
def _conditions(
value: Any,
field: str,
facts: dict[str, FactDefinition],
*,
non_empty: bool = False,
) -> tuple[Condition, ...]:
if not isinstance(value, list) or (non_empty and not value):
expected = "a non-empty list" if non_empty else "a list"
raise ValueError(f"{field}: expected {expected}")
return tuple(
_load_condition(item, f"{field}[{index}]", facts)
for index, item in enumerate(value)
)
def _requirement(
value: Any,
field: str,
facts: dict[str, FactDefinition],
prior_requirements: dict[str, Requirement],
bound_source_ids: set[str],
) -> Requirement:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {
"requirement_id",
"label",
"category",
"item_type",
"parent_requirement_id",
"applies_when",
"source_id",
"source_locator",
"source_excerpt",
}
_exact_keys(value, keys, keys, field)
requirement_id = _identifier(value["requirement_id"], f"{field}.requirement_id")
item_type = _required_text(value["item_type"], f"{field}.item_type")
if item_type not in ITEM_TYPES:
raise ValueError(f"{field}.item_type: unsupported value")
parent_id = _optional_text(
value["parent_requirement_id"], f"{field}.parent_requirement_id"
)
if parent_id is not None and not _IDENTIFIER.fullmatch(parent_id):
raise ValueError(f"{field}.parent_requirement_id: invalid identifier")
if parent_id is not None and parent_id not in prior_requirements:
raise ValueError(f"{field}.parent_requirement_id: parent must appear first")
source_id = _identifier(value["source_id"], f"{field}.source_id")
if source_id not in bound_source_ids:
raise ValueError(f"{field}.source_id: source is not bound to the workflow")
return Requirement(
requirement_id=requirement_id,
label=_required_text(value["label"], f"{field}.label"),
category=_required_text(value["category"], f"{field}.category"),
item_type=item_type,
parent_requirement_id=parent_id,
applies_when=_conditions(value["applies_when"], f"{field}.applies_when", facts),
source_id=source_id,
source_locator=_required_text(
value["source_locator"], f"{field}.source_locator"
),
source_excerpt=_required_text(
value["source_excerpt"], f"{field}.source_excerpt"
),
)
def _requirements(
value: Any,
facts: dict[str, FactDefinition],
bindings: tuple[SourceBinding, ...],
) -> tuple[Requirement, ...]:
if not isinstance(value, list) or not value:
raise ValueError("workflow.requirements: expected a non-empty list")
requirements: list[Requirement] = []
by_id: dict[str, Requirement] = {}
bound_source_ids = {binding.source_id for binding in bindings}
for index, raw_requirement in enumerate(value):
field = f"workflow.requirements[{index}]"
requirement = _requirement(
raw_requirement, field, facts, by_id, bound_source_ids
)
if requirement.requirement_id in by_id:
raise ValueError(f"{field}.requirement_id: duplicate requirement")
requirements.append(requirement)
by_id[requirement.requirement_id] = requirement
return tuple(requirements)
def load_readiness_workflow(
path: Path,
sources_path: Path,
*,
today: date | None = None,
) -> ReadinessWorkflow:
"""Load and strictly validate one source-bound readiness workflow."""
as_of = resolve_today(today)
raw = _workflow_record(path)
status = _required_text(raw["status"], "workflow.status")
if status != "prototype":
raise ValueError("workflow.status: current schema requires 'prototype'")
bindings = _source_bindings(
raw["source_bindings"],
load_sources(sources_path, today=as_of),
as_of,
)
facts, facts_by_id = _fact_definitions(raw["facts"], bindings)
return ReadinessWorkflow(
workflow_id=_identifier(raw["workflow_id"], "workflow.workflow_id"),
jurisdiction=_identifier(raw["jurisdiction"], "workflow.jurisdiction"),
project_type=_identifier(raw["project_type"], "workflow.project_type"),
status=status,
title=_required_text(raw["title"], "workflow.title"),
scope=_required_text(raw["scope"], "workflow.scope"),
source_bindings=bindings,
mapping_provenance=_load_mapping_provenance(
raw["mapping_provenance"], bindings, today=as_of
),
applicability=_conditions(
raw["applicability"],
"workflow.applicability",
facts_by_id,
non_empty=True,
),
facts=facts,
requirements=_requirements(raw["requirements"], facts_by_id, bindings),
)
def _packet_record(path: Path) -> dict[str, Any]:
raw = _versioned_record(path, "packet")
keys = {
"packet_id",
"workflow_id",
"label",
"synthetic",
"evaluated_on",
"jurisdiction",
"project_type",
"facts",
"inventory",
}
_exact_keys(raw, keys, keys, f"{path}.packet")
return raw
def _packet_fact_evidence(
value: dict[str, Any],
field: str,
definition: FactDefinition,
bindings: dict[str, SourceBinding],
provenance: str,
fact_value: str,
) -> tuple[str | None, str | None, str | None]:
source_id = _optional_text(value["source_id"], f"{field}.source_id")
source_field = _optional_text(value["source_field"], f"{field}.source_field")
checked_value = value["source_checked_on"]
source_checked_on = (
None
if checked_value is None
else _required_text(checked_value, f"{field}.source_checked_on")
)
evidence = (source_id, source_field, source_checked_on)
if definition.source_id is None:
if any(item is not None for item in evidence):
raise ValueError(
f"{field}: applicant assertion cannot claim source evidence"
)
if provenance == "synthetic_public_record_fixture":
raise ValueError(f"{field}.provenance: workflow fact has no source binding")
else:
if provenance != "synthetic_public_record_fixture":
raise ValueError(
f"{field}.provenance: source-bound fixture fact requires "
"synthetic_public_record_fixture"
)
binding = bindings[definition.source_id]
if source_id != definition.source_id:
raise ValueError(f"{field}.source_id: does not match workflow fact binding")
if source_field != definition.source_field:
raise ValueError(
f"{field}.source_field: does not match workflow fact binding"
)
if source_checked_on != binding.source_checked_on:
raise ValueError(f"{field}.source_checked_on: does not match bound source")
if fact_value == "unknown":
raise ValueError(f"{field}.value: source fixture must be concrete")
return source_id, source_field, source_checked_on
def _packet_fact(
value: Any,
field: str,
definitions: dict[str, FactDefinition],
bindings: dict[str, SourceBinding],
) -> PacketFact:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {
"fact_id",
"value",
"provenance",
"source_id",
"source_field",
"source_checked_on",
}
_exact_keys(value, keys, keys, field)
fact_id = _identifier(value["fact_id"], f"{field}.fact_id")
definition = definitions.get(fact_id)
if definition is None:
raise ValueError(f"{field}.fact_id: unknown workflow fact")
fact_value = _required_text(value["value"], f"{field}.value")
if fact_value not in definition.allowed_values:
raise ValueError(f"{field}.value: unsupported value")
provenance = _required_text(value["provenance"], f"{field}.provenance")
if provenance not in PROVENANCE_VALUES:
raise ValueError(f"{field}.provenance: unsupported value")
source_id, source_field, source_checked_on = _packet_fact_evidence(
value,
field,
definition,
bindings,
provenance,
fact_value,
)
return PacketFact(
fact_id=fact_id,
value=fact_value,
provenance=provenance,
source_id=source_id,
source_field=source_field,
source_checked_on=source_checked_on,
)
def _packet_facts(
value: Any,
workflow: ReadinessWorkflow,
) -> tuple[PacketFact, ...]:
if not isinstance(value, list):
raise ValueError("packet.facts: expected a list")
definitions = workflow.fact_map()
bindings = {binding.source_id: binding for binding in workflow.source_bindings}
facts: list[PacketFact] = []
seen: set[str] = set()
for index, raw_fact in enumerate(value):
field = f"packet.facts[{index}]"
fact = _packet_fact(raw_fact, field, definitions, bindings)
if fact.fact_id in seen:
raise ValueError(f"{field}.fact_id: duplicate fact")
facts.append(fact)
seen.add(fact.fact_id)
missing = sorted(set(definitions) - seen)
if missing:
raise ValueError("packet.facts: missing facts: " + ", ".join(missing))
return tuple(facts)
def _packet_inventory_item(
value: Any,
field: str,
requirements: dict[str, Requirement],
) -> InventoryItem:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
keys = {"requirement_id", "status"}
_exact_keys(value, keys, keys, field)
requirement_id = _identifier(value["requirement_id"], f"{field}.requirement_id")
if requirement_id not in requirements:
raise ValueError(f"{field}.requirement_id: unknown workflow requirement")
status = _required_text(value["status"], f"{field}.status")
if status not in INVENTORY_STATUSES:
raise ValueError(f"{field}.status: unsupported value")
return InventoryItem(requirement_id=requirement_id, status=status)
def _packet_inventory(
value: Any,
workflow: ReadinessWorkflow,
) -> tuple[InventoryItem, ...]:
if not isinstance(value, list):
raise ValueError("packet.inventory: expected a list")
requirements = workflow.requirement_map()
inventory: list[InventoryItem] = []
seen: set[str] = set()
for index, raw_item in enumerate(value):
field = f"packet.inventory[{index}]"
item = _packet_inventory_item(raw_item, field, requirements)
if item.requirement_id in seen:
raise ValueError(f"{field}.requirement_id: duplicate item")
inventory.append(item)
seen.add(item.requirement_id)
missing = sorted(set(requirements) - seen)
if missing:
raise ValueError(
"packet.inventory: missing requirements: " + ", ".join(missing)
)
return tuple(inventory)
def load_readiness_packet(
path: Path,
workflow: ReadinessWorkflow,
*,
today: date | None = None,
) -> ReadinessPacket:
"""Load an explicit packet inventory for a readiness workflow."""
raw = _packet_record(path)
synthetic = raw["synthetic"]
if not isinstance(synthetic, bool):
raise ValueError("packet.synthetic: expected boolean")
facts = _packet_facts(raw["facts"], workflow)
if not synthetic and any(
fact.provenance.startswith("synthetic_") for fact in facts
):
raise ValueError("packet.facts: non-synthetic packet cannot use fixtures")
return ReadinessPacket(
packet_id=_identifier(raw["packet_id"], "packet.packet_id"),
workflow_id=_identifier(raw["workflow_id"], "packet.workflow_id"),
label=_required_text(raw["label"], "packet.label"),
synthetic=synthetic,
evaluated_on=_iso_date(
raw["evaluated_on"],
"packet.evaluated_on",
today=resolve_today(today),
),
jurisdiction=_identifier(raw["jurisdiction"], "packet.jurisdiction"),
project_type=_identifier(raw["project_type"], "packet.project_type"),
facts=facts,
inventory=_packet_inventory(raw["inventory"], workflow),
)
def _remedies_record(path: Path) -> dict[str, Any]:
payload = _read_json(path, str(path))
if not isinstance(payload, dict):
raise ValueError(f"{path}: expected an object")
keys = {
"schema_version",
"workflow_id",
"workflow_fingerprint",
"version",
"updated_on",
"drafted_by",
"review",
"entries",
}
_exact_keys(payload, keys, keys, str(path))
if payload["schema_version"] != SCHEMA_VERSION:
raise ValueError(f"{path}: unsupported schema version")
return payload
def _remedy_review(