-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidation.py
More file actions
1234 lines (1135 loc) · 59.6 KB
/
Copy pathvalidation.py
File metadata and controls
1234 lines (1135 loc) · 59.6 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
from __future__ import annotations
import csv
import json
import re
from collections import Counter
from pathlib import Path
from typing import Any
from jsonschema import Draft202012Validator
from referencing import Registry, Resource
from .ingestion import file_sha256
from .repository import KnowledgeRepository
SEED_COLUMNS = {
"request_id",
"source",
"input_mode",
"hr_utterance",
"system_context",
"intents",
"domains",
"workflow_ids",
"slots_json",
"missing_slots",
"ambiguities",
"sensitivity",
"next_action",
"expected_output",
"review_status",
}
NEXT_ACTIONS = {
"REQUEST_CLARIFICATION",
"REQUEST_CLASSIFICATION_CONFIRMATION",
"CREATE_DRAFT_TASK",
"REQUIRE_HR_REVIEW",
"SPLIT_AND_CONFIRM",
"OUT_OF_SCOPE",
}
PROCESSED_DATASET_COLUMNS = {
"required_documents_manufacturing.csv": {
"requirement_id",
"application_name",
"document_name",
"applicable_scope",
"requirement_marker",
"sample_form_available",
"source_industry_text",
"source_id",
"source_version",
},
"manufacturing_industries.csv": {
"industry_id",
"major_category",
"middle_category",
"business_content_ko",
"business_content_en",
"source_id",
"source_version",
},
}
INTENT_DATA_PII_PATTERNS = {
"resident_or_alien_registration_number": re.compile(r"(?<!\d)\d{6}-?[1-8]\d{6}(?!\d)"),
"mobile_phone_number": re.compile(r"(?<!\d)01[016789]-?\d{3,4}-?\d{4}(?!\d)"),
"passport_number": re.compile(r"(?<![A-Z0-9])[A-Z]{1,2}\d{7,8}(?![A-Z0-9])"),
}
GIT_LFS_POINTER_PATTERN = re.compile(
r"\Aversion https://git-lfs\.github\.com/spec/v1\n"
r"oid sha256:([a-f0-9]{64})\n"
r"size ([1-9][0-9]*)\n?\Z"
)
def find_internal_keys(text: str, internal_keys: set[str]) -> list[str]:
"""Return machine-facing identifiers exposed in user-facing text."""
found: list[str] = []
for key in sorted(internal_keys):
pattern = rf"(?<![A-Za-z0-9_]){re.escape(key)}(?![A-Za-z0-9_])"
if re.search(pattern, text, flags=re.IGNORECASE):
found.append(key)
return found
def split_codes(raw: str | None) -> list[str]:
return [item.strip() for item in (raw or "").split("|") if item.strip()]
def read_git_lfs_pointer(path: Path) -> tuple[str, int] | None:
"""Read an LFS pointer without loading a potentially large model into memory."""
if path.stat().st_size > 256:
return None
try:
content = path.read_text(encoding="ascii")
except UnicodeDecodeError:
return None
match = GIT_LFS_POINTER_PATTERN.fullmatch(content)
if not match:
return None
return match.group(1), int(match.group(2))
class KnowledgeValidator:
def __init__(self, repository: KnowledgeRepository) -> None:
self.repository = repository
self.errors: list[str] = []
def validate_all(self) -> list[str]:
self.errors = []
self._validate_manifest_files()
self._validate_processed_datasets()
self._validate_workflow_schema()
self._validate_workflow_runtime()
self._validate_document_contracts()
self._validate_required_slot_contracts()
self._validate_cross_references()
self._validate_seed_data()
self._validate_evaluation_data()
self._validate_catalog_e2e_data()
self._validate_intent_data()
self._validate_intent_split()
self._validate_model_artifacts()
return self.errors
def _validate_manifest_files(self) -> None:
manifest = self.repository.manifest
for key, relative_path in manifest.get("files", {}).items():
if not (self.repository.root / relative_path).is_file():
self.errors.append(f"manifest file missing: {key} -> {relative_path}")
for key, relative_path in manifest.get("datasets", {}).items():
if not (self.repository.root / relative_path).is_file():
self.errors.append(f"manifest dataset missing: {key} -> {relative_path}")
for key, relative_path in manifest.get("artifacts", {}).items():
if not (self.repository.root / relative_path).is_file():
self.errors.append(f"manifest artifact missing: {key} -> {relative_path}")
def _validate_model_artifacts(self) -> None:
relative_path = self.repository.manifest.get("artifacts", {}).get("intent_models")
schema_path = self.repository.manifest.get("artifacts", {}).get("intent_model_schema")
if not relative_path or not schema_path:
return
manifest = self.repository.load_yaml(relative_path)
schema = self.repository.load_json(schema_path)
schema_errors = list(Draft202012Validator(schema).iter_errors(manifest))
for error in schema_errors:
path = ".".join(str(item) for item in error.path)
self.errors.append(f"model artifact schema [{path}]: {error.message}")
if schema_errors:
return
intent_manifest = self.repository.load_yaml("data/intent/manifest.yaml")
known_snapshot = intent_manifest["known_model_training_snapshot"]
training_dataset = manifest["training_dataset"]
if training_dataset["version"] != known_snapshot["dataset_version"]:
self.errors.append("model artifact: training dataset version mismatch")
if training_dataset["sha256"] != known_snapshot["sha256"]:
self.errors.append("model artifact: training dataset checksum mismatch")
if training_dataset["current_dataset_version"] != intent_manifest["version"]:
self.errors.append("model artifact: current dataset version mismatch")
if training_dataset["matches_current_dataset"] != known_snapshot["matches_current_dataset"]:
self.errors.append("model artifact: current dataset match flag mismatch")
seen_model_ids: set[str] = set()
seen_paths: set[str] = set()
for model in manifest["models"]:
if model["id"] in seen_model_ids:
self.errors.append(f"model artifact: duplicate model id {model['id']}")
seen_model_ids.add(model["id"])
for artifact in model["snapshot_files"]:
artifact_path = artifact["path"]
if artifact_path in seen_paths:
self.errors.append(f"model artifact: duplicate file {artifact_path}")
seen_paths.add(artifact_path)
path = self.repository.root / artifact_path
if not path.is_file():
self.errors.append(f"model artifact: missing file {artifact_path}")
continue
lfs_pointer = read_git_lfs_pointer(path)
if lfs_pointer:
pointer_sha256, pointer_bytes = lfs_pointer
if pointer_bytes != artifact["bytes"]:
self.errors.append(f"model artifact: LFS size mismatch {artifact_path}")
if pointer_sha256 != artifact["sha256"]:
self.errors.append(f"model artifact: LFS checksum mismatch {artifact_path}")
continue
if path.stat().st_size != artifact["bytes"]:
self.errors.append(f"model artifact: size mismatch {artifact_path}")
if file_sha256(path) != artifact["sha256"]:
self.errors.append(f"model artifact: checksum mismatch {artifact_path}")
def _validate_processed_datasets(self) -> None:
processed_manifest_path = self.repository.root / "data/processed/manifest.yaml"
if not processed_manifest_path.is_file():
return
processed_manifest = self.repository.load_yaml("data/processed/manifest.yaml")
source_manifest = self.repository.load_yaml("data/external/source_manifest.yaml")
known_sources = {item["id"] for item in source_manifest["sources"]}
for dataset in processed_manifest.get("datasets", []):
filename = dataset["path"]
path = self.repository.root / "data/processed" / filename
if not path.is_file():
self.errors.append(f"processed dataset missing: {filename}")
continue
if dataset["source_id"] not in known_sources:
self.errors.append(
f"processed dataset {filename}: unknown source {dataset['source_id']}"
)
if file_sha256(path) != dataset["sha256"]:
self.errors.append(f"processed dataset {filename}: checksum mismatch")
with path.open("r", encoding="utf-8", newline="") as handle:
reader = csv.DictReader(handle)
rows = list(reader)
if len(rows) != dataset["row_count"]:
self.errors.append(f"processed dataset {filename}: row count mismatch")
expected_columns = PROCESSED_DATASET_COLUMNS.get(filename)
if expected_columns and set(reader.fieldnames or []) != expected_columns:
self.errors.append(f"processed dataset {filename}: column mismatch")
if filename == "manufacturing_industries.csv" and any(
row["major_category"] != "제조업" for row in rows
):
self.errors.append(f"processed dataset {filename}: non-manufacturing row")
critical_fields = {
"required_documents_manufacturing.csv": [
"requirement_id",
"application_name",
"document_name",
],
"manufacturing_industries.csv": [
"industry_id",
"middle_category",
"business_content_ko",
],
}.get(filename, [])
for line_number, row in enumerate(rows, start=2):
if any(not row.get(field, "").strip() for field in critical_fields):
self.errors.append(
f"processed dataset {filename} line {line_number}: blank critical field"
)
def _validate_workflow_schema(self) -> None:
schema = self.repository.load_json("schemas/workflow-catalog.schema.json")
catalog = self.repository.load_yaml("knowledge/workflow_catalog.yaml")
validator = Draft202012Validator(schema)
for error in validator.iter_errors(catalog):
path = ".".join(str(item) for item in error.path)
self.errors.append(f"workflow schema [{path}]: {error.message}")
def _validate_workflow_runtime(self) -> None:
runtime = self.repository.load_yaml("knowledge/workflow_runtime.yaml")
schema = self.repository.load_json("schemas/workflow-runtime.schema.json")
schema_errors = list(Draft202012Validator(schema).iter_errors(runtime))
for error in schema_errors:
path = ".".join(str(item) for item in error.path)
self.errors.append(f"workflow runtime schema [{path}]: {error.message}")
if schema_errors:
return
catalog = self.repository.load_yaml("knowledge/workflow_catalog.yaml")
workflows = {workflow["id"]: workflow for workflow in catalog["workflows"]}
slot_requirements = self.repository.load_yaml("knowledge/required_slots.yaml")[
"workflow_requirements"
]
profiles = {profile["id"]: profile for profile in runtime["profiles"]}
if len(profiles) != len(runtime["profiles"]):
self.errors.append("workflow runtime: duplicate profile id")
expected_intents = {
"EXPIRY_RENEWAL",
"WORKER_ONBOARDING",
"EMPLOYMENT_CHANGE",
"DOCUMENT_REQUEST",
"PAYROLL_EXPLANATION",
"WORK_INSTRUCTION",
}
if {profile["intent"] for profile in profiles.values()} != expected_intents:
self.errors.append("workflow runtime: six MVP intents must have one profile each")
for profile_id, profile in profiles.items():
included_workflow_ids = set(profile["included_workflow_ids"])
if profile["master_workflow_id"] not in included_workflow_ids:
self.errors.append(f"workflow runtime {profile_id}: master must be included")
for workflow_id in included_workflow_ids | set(profile["reusable_subflow_ids"]):
if workflow_id not in workflows:
self.errors.append(
f"workflow runtime {profile_id}: unknown workflow {workflow_id}"
)
master = workflows.get(profile["master_workflow_id"])
if master and master["intent"] != profile["intent"]:
self.errors.append(f"workflow runtime {profile_id}: master intent mismatch")
if profile["required_slots_ref"] not in slot_requirements:
self.errors.append(f"workflow runtime {profile_id}: unknown required slots ref")
stages = {stage["id"]: stage for stage in profile["stages"]}
if len(stages) != len(profile["stages"]):
self.errors.append(f"workflow runtime {profile_id}: duplicate stage id")
stage_order = {stage["id"]: index for index, stage in enumerate(profile["stages"])}
referenced_steps: set[str] = set()
for stage in profile["stages"]:
for dependency in stage["depends_on"]:
if dependency not in stages:
self.errors.append(
f"workflow runtime {profile_id}.{stage['id']}: "
f"unknown dependency {dependency}"
)
elif stage_order[dependency] >= stage_order[stage["id"]]:
self.errors.append(
f"workflow runtime {profile_id}.{stage['id']}: "
f"dependency {dependency} must be earlier"
)
for step_reference in stage["catalog_steps"]:
workflow_id, step_id = step_reference.split(".", maxsplit=1)
if workflow_id not in included_workflow_ids:
self.errors.append(
f"workflow runtime {profile_id}: step outside included workflow "
f"{step_reference}"
)
continue
known_steps = {step["id"]: step for step in workflows[workflow_id]["steps"]}
if step_id not in known_steps:
self.errors.append(
f"workflow runtime {profile_id}: unknown step {step_reference}"
)
continue
if step_reference in referenced_steps:
self.errors.append(
f"workflow runtime {profile_id}: duplicate step {step_reference}"
)
referenced_steps.add(step_reference)
catalog_step = known_steps[step_id]
if (catalog_step["actor"] == "HR" or catalog_step.get("gate")) and stage[
"human_gate"
] == "NONE":
self.errors.append(
f"workflow runtime {profile_id}.{stage['id']}: "
"human-controlled step requires a human gate"
)
if (
step_id in {"manual_external_process", "manual_report"}
and stage["human_gate"] != "MANUAL_EXTERNAL_ACTION"
):
self.errors.append(
f"workflow runtime {profile_id}.{stage['id']}: "
"external action must remain manual"
)
expected_steps = {
f"{workflow_id}.{step['id']}"
for workflow_id in included_workflow_ids
for step in workflows[workflow_id]["steps"]
}
if referenced_steps != expected_steps:
self.errors.append(
f"workflow runtime {profile_id}: all included catalog steps must be mapped"
)
fixture_manifest = self.repository.load_yaml(
"data/evaluation/workflow_runtime_manifest.yaml"
)
fixture_schema = self.repository.load_json(fixture_manifest["schema"])
fixture_path = self.repository.root / fixture_manifest["path"]
if file_sha256(fixture_path) != fixture_manifest["sha256"]:
self.errors.append("workflow runtime fixtures: checksum mismatch")
cases: list[dict[str, Any]] = []
seen_case_ids: set[str] = set()
for line_number, raw_line in enumerate(
fixture_path.read_text(encoding="utf-8").splitlines(), start=1
):
if not raw_line.strip():
continue
try:
case = json.loads(raw_line)
except json.JSONDecodeError as exc:
self.errors.append(f"workflow runtime fixture line {line_number}: {exc}")
continue
cases.append(case)
for error in Draft202012Validator(fixture_schema).iter_errors(case):
path = ".".join(str(item) for item in error.path)
self.errors.append(
f"workflow runtime fixture line {line_number} [{path}]: {error.message}"
)
case_id = case.get("case_id")
if case_id in seen_case_ids:
self.errors.append(f"workflow runtime fixture: duplicate {case_id}")
seen_case_ids.add(case_id)
profile = profiles.get(case.get("profile_id"))
if not profile:
self.errors.append(f"workflow runtime fixture line {line_number}: unknown profile")
continue
stage_ids = {stage["id"] for stage in profile["stages"]}
if not set(case.get("expected_ready_stage_ids", [])) <= stage_ids:
self.errors.append(
f"workflow runtime fixture line {line_number}: unknown ready stage"
)
if set(case.get("provided_slots", [])) & set(case.get("missing_slots", [])):
self.errors.append(
f"workflow runtime fixture line {line_number}: "
"slot cannot be provided and missing"
)
if case.get("path") == "MISSING_INPUT" and not case.get("missing_slots"):
self.errors.append(
f"workflow runtime fixture line {line_number}: missing path needs missing slots"
)
if len(cases) != fixture_manifest["record_count"]:
self.errors.append("workflow runtime fixtures: record count mismatch")
cases_by_profile = Counter(case.get("profile_id") for case in cases)
required_paths = set(fixture_manifest["required_paths"])
for profile_id in profiles:
if cases_by_profile[profile_id] != fixture_manifest["cases_per_profile"]:
self.errors.append(f"workflow runtime fixtures: {profile_id} must have three cases")
profile_paths = {
case.get("path") for case in cases if case.get("profile_id") == profile_id
}
if profile_paths != required_paths:
self.errors.append(f"workflow runtime fixtures: {profile_id} paths are incomplete")
def _validate_document_contracts(self) -> None:
roles = self.repository.load_yaml("knowledge/document_roles.yaml")
expected_roles = {
"EVIDENCE",
"FORM_TEMPLATE",
"REFERENCE",
"GENERATED_OUTPUT",
"COMMUNICATION_ATTACHMENT",
"UNKNOWN",
}
expected_states = {
"UPLOADED",
"SCANNING",
"PARSING",
"CLASSIFYING",
"REVIEW_REQUIRED",
"VERIFIED",
"FAILED",
}
if set(roles["roles"]) != expected_roles:
self.errors.append("document contract: role catalog mismatch")
if set(roles["processing_states"]) != expected_states:
self.errors.append("document contract: processing state catalog mismatch")
if any(route["automatic_persistence_allowed"] for route in roles["parser_routes"].values()):
self.errors.append("document contract: parser route cannot auto-persist")
type_catalog = self.repository.load_yaml("knowledge/document_type_catalog.yaml")
document_types = {item["id"]: item for item in type_catalog["document_types"]}
if len(document_types) != len(type_catalog["document_types"]):
self.errors.append("document contract: duplicate document type")
for document_type, definition in document_types.items():
if not set(definition["allowed_roles"]) <= expected_roles:
self.errors.append(f"document contract {document_type}: unknown allowed role")
template_policy = self.repository.load_yaml("knowledge/company_template_policy.yaml")
if template_policy["scopes"]["TENANT"]["visibility"] != "OWNER_COMPANY_ONLY":
self.errors.append("document contract: tenant template must be company-only")
if not template_policy["tenant_isolation"]["cross_company_search_forbidden"]:
self.errors.append("document contract: cross-company template search must be blocked")
spreadsheet_policy = self.repository.load_yaml("knowledge/spreadsheet_normalization.yaml")
if spreadsheet_policy["formula"]["recalculate"]:
self.errors.append("document contract: parser must not recalculate formulas")
if not spreadsheet_policy["row_error_policy"]["valid_rows_survive_other_row_errors"]:
self.errors.append("document contract: valid spreadsheet rows must be preserved")
manifest = self.repository.load_yaml("data/evaluation/document_ir_manifest.yaml")
fixture_path = self.repository.root / manifest["path"]
if file_sha256(fixture_path) != manifest["sha256"]:
self.errors.append("document IR fixtures: checksum mismatch")
field_schema = self.repository.load_json(manifest["field_schema"])
ir_schema = self.repository.load_json(manifest["schema"])
registry = Registry().with_resource(
field_schema["$id"], Resource.from_contents(field_schema)
)
validator = Draft202012Validator(ir_schema, registry=registry)
fixtures: list[dict[str, Any]] = []
seen_ids: set[str] = set()
for line_number, raw_line in enumerate(
fixture_path.read_text(encoding="utf-8").splitlines(), start=1
):
if not raw_line.strip():
continue
try:
document = json.loads(raw_line)
except json.JSONDecodeError as exc:
self.errors.append(f"document IR line {line_number}: invalid JSON ({exc})")
continue
fixtures.append(document)
for error in validator.iter_errors(document):
path = ".".join(str(item) for item in error.path)
self.errors.append(f"document IR line {line_number} [{path}]: {error.message}")
document_ref = document.get("document_ref")
if document_ref in seen_ids:
self.errors.append(f"document IR line {line_number}: duplicate {document_ref}")
seen_ids.add(document_ref)
definition = document_types.get(document.get("document_type"))
if not definition:
self.errors.append(f"document IR line {line_number}: unknown document type")
else:
if document.get("role") not in definition["allowed_roles"]:
self.errors.append(
f"document IR line {line_number}: role not allowed for document type"
)
if document.get("source_file", {}).get("format") not in definition["formats"]:
self.errors.append(
f"document IR line {line_number}: format not allowed for document type"
)
template = document.get("template", {})
if template.get("scope") == "TENANT":
if template.get("owner_company_ref") != document.get("company_ref"):
self.errors.append(
f"document IR line {line_number}: tenant template owner mismatch"
)
if template.get("visible_to_other_companies"):
self.errors.append(
f"document IR line {line_number}: tenant template visibility leak"
)
if document.get("parser_route") in {"UNCLASSIFIED", "UNSUPPORTED"} and document.get(
"automatic_persistence_allowed"
):
self.errors.append(
f"document IR line {line_number}: unclassified document cannot auto-persist"
)
if len(fixtures) != manifest["record_count"]:
self.errors.append("document IR fixtures: record count mismatch")
formats = {fixture["source_file"]["format"] for fixture in fixtures}
if formats != set(manifest["required_formats"]):
self.errors.append("document IR fixtures: required format coverage missing")
xlsx_fixture = next(
(fixture for fixture in fixtures if fixture["source_file"]["format"] == "XLSX"),
None,
)
expected_row_statuses = {"VALID", "REVIEW_REQUIRED"}
actual_row_statuses = (
{row["status"] for row in xlsx_fixture["spreadsheet"]["row_results"]}
if xlsx_fixture
else set()
)
if actual_row_statuses != expected_row_statuses:
self.errors.append("document IR fixtures: XLSX partial row handling missing")
def _validate_required_slot_contracts(self) -> None:
config = self.repository.load_yaml("knowledge/required_slots.yaml")
schema = self.repository.load_json("schemas/required-slots.schema.json")
schema_errors = list(Draft202012Validator(schema).iter_errors(config))
for error in schema_errors:
path = ".".join(str(item) for item in error.path)
self.errors.append(f"required slots schema [{path}]: {error.message}")
if schema_errors:
return
known_slots = set(config["slot_definitions"])
known_sources = set(config["source_priority_definitions"])
known_rules = set(config["validation_rule_definitions"])
workflows = {
item["id"]: item
for item in self.repository.load_yaml("knowledge/workflow_catalog.yaml")["workflows"]
}
internal_keys = self._user_facing_internal_keys()
for workflow_id, requirement in config["workflow_requirements"].items():
if workflow_id not in workflows:
self.errors.append(f"slot contract: unknown workflow {workflow_id}")
continue
if workflows[workflow_id]["required_slots_ref"] != workflow_id:
self.errors.append(f"slot contract: workflow ref mismatch {workflow_id}")
required = set(requirement["required"])
optional = set(requirement.get("optional", []))
contracts = requirement["slot_contracts"]
contract_names = set(contracts)
if required & optional:
self.errors.append(f"slot contract {workflow_id}: required and optional overlap")
if contract_names != required | optional:
self.errors.append(
f"slot contract {workflow_id}: contracts must match required and optional slots"
)
if not set(requirement["resolvable_from_context"]) <= contract_names:
self.errors.append(
f"slot contract {workflow_id}: unknown resolvable_from_context slot"
)
for slot_name, contract in contracts.items():
if slot_name not in known_slots:
self.errors.append(f"slot contract {workflow_id}: unknown slot {slot_name}")
if contract["required"] != (slot_name in required):
self.errors.append(
f"slot contract {workflow_id}.{slot_name}: required flag mismatch"
)
for source in contract["source_priority"]:
if source not in known_sources:
self.errors.append(
f"slot contract {workflow_id}.{slot_name}: unknown source {source}"
)
for rule in contract["validation_rules"]:
if rule not in known_rules:
self.errors.append(
f"slot contract {workflow_id}.{slot_name}: unknown rule {rule}"
)
for field in ("display_name_ko", "worker_prompt_easy_ko"):
leaked = find_internal_keys(contract[field], internal_keys)
if leaked:
self.errors.append(
f"slot contract {workflow_id}.{slot_name}: internal key exposed "
f"in {field} ({', '.join(leaked)})"
)
def _validate_cross_references(self) -> None:
context = self.repository.load_context_files()
intents = self._index_unique(context["intents"]["intents"], "intent")
domains = self._index_unique(context["domains"]["domains"], "domain")
sources = self._index_unique(context["sources"]["sources"], "source")
workflows = self._index_unique(context["workflows"]["workflows"], "workflow")
case_templates = self._index_unique(context["workflows"]["case_templates"], "case template")
checklists = self._index_unique(context["checklists"]["checklists"], "checklist")
procedures = self._index_unique(context["procedures"]["procedures"], "procedure")
slot_refs = context["slots"]["workflow_requirements"]
for workflow_id, workflow in workflows.items():
if workflow["intent"] not in intents:
self.errors.append(f"{workflow_id}: unknown intent {workflow['intent']}")
for domain in workflow["domains"]:
if domain not in domains:
self.errors.append(f"{workflow_id}: unknown domain {domain}")
for source_id in workflow["source_ids"]:
if source_id not in sources:
self.errors.append(f"{workflow_id}: unknown source {source_id}")
if workflow["required_slots_ref"] not in slot_refs:
self.errors.append(
f"{workflow_id}: unknown slot policy {workflow['required_slots_ref']}"
)
checklist_id = workflow.get("checklist_id")
if checklist_id and checklist_id not in checklists:
self.errors.append(f"{workflow_id}: unknown checklist {checklist_id}")
for template_id, template in case_templates.items():
if template["intent"] not in intents:
self.errors.append(f"{template_id}: unknown intent {template['intent']}")
for workflow_id in template["workflow_ids"]:
if workflow_id not in workflows:
self.errors.append(f"{template_id}: unknown workflow {workflow_id}")
task_keys = {task["key"] for task in template["tasks"]}
tasks_by_key = {task["key"]: task for task in template["tasks"]}
if len(task_keys) != len(template["tasks"]):
self.errors.append(f"{template_id}: duplicate task key")
task_orders = {task["order"] for task in template["tasks"]}
if len(task_orders) != len(template["tasks"]):
self.errors.append(f"{template_id}: duplicate task order")
for task in template["tasks"]:
if task["workflow_id"] not in template["workflow_ids"]:
self.errors.append(
f"{template_id}.{task['key']}: workflow not declared by template"
)
dependencies = task["depends_on"] + task["depends_on_if_present"]
for dependency in dependencies:
if dependency not in task_keys:
self.errors.append(
f"{template_id}.{task['key']}: unknown dependency {dependency}"
)
if dependency == task["key"]:
self.errors.append(
f"{template_id}.{task['key']}: task cannot depend on itself"
)
elif dependency in tasks_by_key and (
tasks_by_key[dependency]["order"] >= task["order"]
):
self.errors.append(
f"{template_id}.{task['key']}: dependency {dependency} "
"must have a lower order"
)
document_types = set(context["checklists"]["document_types"])
for checklist_id, checklist in checklists.items():
if checklist["workflow_id"] not in workflows:
self.errors.append(f"{checklist_id}: unknown workflow {checklist['workflow_id']}")
for item in checklist["items"]:
if item["document_type"] not in document_types:
self.errors.append(
f"{checklist_id}: unknown document type {item['document_type']}"
)
for source_id in checklist.get("official_sources", []):
if source_id not in sources:
self.errors.append(f"{checklist_id}: unknown source {source_id}")
for template in context["multilingual_templates"]["templates"]:
if template["workflow_id"] not in workflows:
self.errors.append(f"{template['id']}: unknown workflow {template['workflow_id']}")
required_documents = self.repository.load_csv(
"data/processed/required_documents_manufacturing.csv"
)
application_names = {row["application_name"] for row in required_documents}
for procedure_id, procedure in procedures.items():
if procedure["workflow_id"] not in workflows:
self.errors.append(f"{procedure_id}: unknown workflow {procedure['workflow_id']}")
for source_id in procedure["source_ids"]:
if source_id not in sources:
self.errors.append(f"{procedure_id}: unknown source {source_id}")
for key in ("next_workflow_ids", "possible_prerequisite_workflow_ids"):
for workflow_id in procedure.get(key, []):
if workflow_id not in workflows:
self.errors.append(f"{procedure_id}: unknown workflow {workflow_id}")
application_name = procedure.get("dataset_application_name")
if application_name and application_name not in application_names:
self.errors.append(
f"{procedure_id}: unknown dataset application {application_name}"
)
valid_guardrail_targets = set(intents) | {"ALL"}
for rule in context["guardrails"]["rules"]:
for target in rule["applies_to"]:
if target not in valid_guardrail_targets:
self.errors.append(f"{rule['id']}: unknown applies_to {target}")
def _validate_seed_data(self) -> None:
context = self.repository.load_context_files()
known_intents = {item["id"] for item in context["intents"]["intents"]} | {
context["intents"]["out_of_scope_label"]
}
known_domains = {item["id"] for item in context["domains"]["domains"]}
known_workflows = {item["id"] for item in context["workflows"]["workflows"]}
known_sources = set(self.repository.load_yaml("data/provenance.yaml")["sources"])
review_statuses = set(self.repository.load_yaml("data/provenance.yaml")["review_statuses"])
input_modes = set(self.repository.manifest["input_modes"])
path = self.repository.root / "data/seed/gold_seed.csv"
seen: set[str] = set()
with path.open("r", encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
if set(reader.fieldnames or []) != SEED_COLUMNS:
self.errors.append("seed CSV columns do not match the documented schema")
return
for line_number, row in enumerate(reader, start=2):
request_id = row["request_id"]
if request_id in seen:
self.errors.append(f"seed line {line_number}: duplicate {request_id}")
seen.add(request_id)
self._check_codes(line_number, "intent", split_codes(row["intents"]), known_intents)
self._check_codes(line_number, "domain", split_codes(row["domains"]), known_domains)
self._check_codes(
line_number, "workflow", split_codes(row["workflow_ids"]), known_workflows
)
if row["source"] not in known_sources:
self.errors.append(f"seed line {line_number}: unknown source {row['source']}")
if row["input_mode"] not in input_modes:
self.errors.append(
f"seed line {line_number}: invalid input_mode {row['input_mode']}"
)
if row["next_action"] not in NEXT_ACTIONS:
self.errors.append(
f"seed line {line_number}: invalid next_action {row['next_action']}"
)
if row["review_status"] not in review_statuses:
self.errors.append(
f"seed line {line_number}: invalid review_status {row['review_status']}"
)
try:
parsed_slots = json.loads(row["slots_json"])
if not isinstance(parsed_slots, dict):
raise TypeError("slots_json must be an object")
except (json.JSONDecodeError, TypeError) as exc:
self.errors.append(f"seed line {line_number}: invalid slots_json ({exc})")
def _validate_evaluation_data(self) -> None:
schema = self.repository.load_json("schemas/golden-case.schema.json")
validator = Draft202012Validator(schema)
context = self.repository.load_context_files()
known_intents = {item["id"] for item in context["intents"]["intents"]} | {
context["intents"]["out_of_scope_label"]
}
known_domains = {item["id"] for item in context["domains"]["domains"]}
known_workflows = {item["id"] for item in context["workflows"]["workflows"]}
seen: set[str] = set()
path = self.repository.root / "data/evaluation/golden_cases.jsonl"
for line_number, raw_line in enumerate(
path.read_text(encoding="utf-8").splitlines(), start=1
):
if not raw_line.strip():
continue
try:
case = json.loads(raw_line)
except json.JSONDecodeError as exc:
self.errors.append(f"evaluation line {line_number}: invalid JSON ({exc})")
continue
for error in validator.iter_errors(case):
self.errors.append(f"evaluation line {line_number}: {error.message}")
case_id = case.get("case_id")
if case_id in seen:
self.errors.append(f"evaluation line {line_number}: duplicate {case_id}")
seen.add(case_id)
self._check_codes(
line_number, "intent", case.get("expected_intents", []), known_intents
)
self._check_codes(
line_number, "domain", case.get("expected_domains", []), known_domains
)
self._check_codes(
line_number,
"workflow",
case.get("expected_workflow_ids", []),
known_workflows,
)
def _validate_catalog_e2e_data(self) -> None:
manifest = self.repository.load_yaml("data/evaluation/e2e_catalog_manifest.yaml")
path = self.repository.root / manifest["path"]
schema = self.repository.load_json(manifest["schema"])
validator = Draft202012Validator(schema)
context = self.repository.load_context_files()
known_intents = {item["id"] for item in context["intents"]["intents"]} | {
context["intents"]["out_of_scope_label"]
}
known_workflows = {item["id"] for item in context["workflows"]["workflows"]}
known_slots = set(context["slots"]["slot_definitions"])
supported_locales = set(self.repository.manifest["supported_worker_locales"]) | {
self.repository.manifest["default_locale"]
}
internal_keys = self._user_facing_internal_keys()
if file_sha256(path) != manifest["sha256"]:
self.errors.append("catalog e2e data: checksum mismatch")
cases: list[dict[str, Any]] = []
seen_ids: set[str] = set()
for line_number, raw_line in enumerate(
path.read_text(encoding="utf-8").splitlines(), start=1
):
if not raw_line.strip():
continue
try:
case = json.loads(raw_line)
except json.JSONDecodeError as exc:
self.errors.append(f"catalog e2e line {line_number}: invalid JSON ({exc})")
continue
cases.append(case)
for error in validator.iter_errors(case):
error_path = ".".join(str(item) for item in error.path)
location = f" [{error_path}]" if error_path else ""
self.errors.append(f"catalog e2e line {line_number}{location}: {error.message}")
case_id = case.get("case_id")
if case_id in seen_ids:
self.errors.append(f"catalog e2e line {line_number}: duplicate {case_id}")
seen_ids.add(case_id)
self._check_codes(
line_number, "intent", case.get("expected_intents", []), known_intents
)
self._check_codes(
line_number,
"workflow",
case.get("expected_workflow_ids", []),
known_workflows,
)
self._check_codes(
line_number,
"slot",
list(case.get("expected_slots", {})),
known_slots,
)
intents = case.get("expected_intents", [])
workflows = case.get("expected_workflow_ids", [])
if "OUT_OF_SCOPE" in intents and (len(intents) != 1 or workflows):
self.errors.append(
f"catalog e2e line {line_number}: OUT_OF_SCOPE must not have workflows"
)
workers = {
worker["worker_id"]: worker
for worker in case.get("directory_context", {}).get("workers", [])
}
lookup = case.get("expected_subject_lookup", {})
worker_id = lookup.get("worker_id")
candidates = set(lookup.get("candidate_worker_ids", []))
if worker_id is not None and worker_id not in workers:
self.errors.append(
f"catalog e2e line {line_number}: matched worker missing from directory"
)
if not candidates <= set(workers):
self.errors.append(
f"catalog e2e line {line_number}: candidate worker missing from directory"
)
if lookup.get("status") == "AMBIGUOUS" and not lookup.get("requires_confirmation"):
self.errors.append(
f"catalog e2e line {line_number}: ambiguous name must require confirmation"
)
if lookup.get("match_basis") == "PHONETIC_ALIAS" and not lookup.get(
"requires_confirmation"
):
self.errors.append(
f"catalog e2e line {line_number}: phonetic alias must require confirmation"
)
for notice in case.get("worker_notices", []):
if notice["locale"] not in supported_locales:
self.errors.append(f"catalog e2e line {line_number}: unsupported notice locale")
missing_values = [
value for value in notice["critical_values"] if value not in notice["text"]
]
if missing_values:
self.errors.append(
f"catalog e2e line {line_number}: notice loses critical values "
f"({', '.join(missing_values)})"
)
leaked = find_internal_keys(notice["text"], internal_keys)
if leaked:
self.errors.append(
f"catalog e2e line {line_number}: notice exposes internal keys "
f"({', '.join(leaked)})"
)
for text in [
case.get("hr_input", ""),
*[n["text"] for n in case.get("worker_notices", [])],
]:
for pii_kind, pattern in INTENT_DATA_PII_PATTERNS.items():
if pattern.search(text):
self.errors.append(
f"catalog e2e line {line_number}: possible PII ({pii_kind})"
)
if len(cases) != manifest["record_count"]:
self.errors.append("catalog e2e data: record count mismatch")
tags = {tag for case in cases for tag in case.get("scenario_tags", [])}
required_tags = {
"SPACING_VARIANT",
"ROMANIZED_ALIAS",
"CASE_VARIANT",
"PHONETIC_ALIAS",
"AMBIGUOUS_NAME",
"COMPOSITE_REQUEST",
"BOUNDARY_INTENT",
"OUT_OF_SCOPE",
"VIETNAMESE_NOTICE",
"EXTERNAL_EXECUTION",
}
if not required_tags <= tags:
self.errors.append("catalog e2e data: required scenario coverage is missing")
if manifest["status"] == "pending_independent_review" and any(
case.get("review", {}).get("adjudication") != "PENDING" for case in cases
):
self.errors.append("catalog e2e data: review status conflicts with manifest")
def _user_facing_internal_keys(self) -> set[str]:
context = self.repository.load_context_files()
keys = set(context["slots"]["slot_definitions"])
keys.update(item["id"] for item in context["intents"]["intents"])
keys.add(context["intents"]["out_of_scope_label"])
for workflow in context["workflows"]["workflows"]:
keys.add(workflow["id"])
keys.update(step["id"] for step in workflow["steps"])
keys.update(step["output"] for step in workflow["steps"])
keys.update(item["id"] for item in context["sources"]["sources"])
return keys
def _validate_intent_data(self) -> None:
intent_manifest = self.repository.load_yaml("data/intent/manifest.yaml")
schema = self.repository.load_json(intent_manifest["schema"])
validator = Draft202012Validator(schema)
context = self.repository.load_context_files()
known_intents = {item["id"] for item in context["intents"]["intents"]} | {
context["intents"]["out_of_scope_label"]
}
out_of_scope_label = context["intents"]["out_of_scope_label"]
seen_ids: set[int] = set()
seen_inputs: set[str] = set()
path = self.repository.root / intent_manifest["path"]
record_count = 0
for line_number, raw_line in enumerate(
path.read_text(encoding="utf-8").splitlines(), start=1
):
if not raw_line.strip():
continue
record_count += 1
try:
case = json.loads(raw_line)
except json.JSONDecodeError as exc:
self.errors.append(f"intent data line {line_number}: invalid JSON ({exc})")
continue
if not isinstance(case, dict):
self.errors.append(f"intent data line {line_number}: record must be an object")
continue
for error in validator.iter_errors(case):
error_path = ".".join(str(item) for item in error.path)
location = f" [{error_path}]" if error_path else ""
self.errors.append(f"intent data line {line_number}{location}: {error.message}")
case_id = case.get("id")