-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_v3_divergence_pipeline.py
More file actions
4878 lines (4459 loc) · 190 KB
/
Copy pathtest_v3_divergence_pipeline.py
File metadata and controls
4878 lines (4459 loc) · 190 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
#!/usr/bin/env python3
"""
Validate the active v3.0 Governance Promise-Delivery Divergence Engine.
This test validates the current divergence reconstruction artifact contract.
It does not validate the legacy semantic pipeline.
"""
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from docx import Document
from analysis.target_search import run_divergence_engine
from evidence.evidence_ingestion import (
load_or_build_evidence_index,
load_transcript_artifact,
upgrade_evidence_status,
)
from evidence.transcript_acquisition import (
acquire_transcripts,
extract_youtube_video_id,
failure_artifact,
transcript_found_artifact,
upgrade_evidence_from_transcript_artifact,
validate_transcript_artifact,
)
from evidence.timestamp_verification import (
DEFAULT_TIMESTAMP_OUTPUT,
TimestampCandidate,
validate_timestamp_candidate,
verify_timestamps_fixture_only,
)
from evidence.quote_verification import (
DEFAULT_QUOTE_OUTPUT,
QuoteCandidate,
validate_quote_candidate,
verify_quotes_fixture_only,
)
from evidence.case_evidence_linking import (
DEFAULT_CASE_LINK_OUTPUT,
CaseEvidenceLink,
link_case_evidence_fixture_only,
validate_case_evidence_link,
validate_report_sections_resolve,
)
from evidence.report_section_assembly import (
DEFAULT_REPORT_SECTION_OUTPUT,
AssembledReportSection,
assemble_report_sections_fixture_only,
validate_assembled_report_section,
validate_assembled_section_resolves,
)
from evidence.final_report_v1 import (
DEFAULT_FINAL_REPORT_DOCX,
DEFAULT_FINAL_REPORT_PAYLOAD,
FinalReportPayload,
generate_final_report_fixture_only,
validate_final_report_payload,
)
from evidence.final_report_hardening import (
DEFAULT_FINAL_REPORT_HARDENING_RECORD,
DEFAULT_FINAL_REPORT_HARDENING_SUMMARY,
FinalReportHardeningRecord,
build_final_report_hardening_record_dry_run,
harden_final_report_dry_run,
validate_final_report_hardening_record,
)
from evidence.release_readiness import (
DEFAULT_RELEASE_READINESS_RECORD,
DEFAULT_RELEASE_READINESS_SUMMARY,
DRY_RUN_BLOCKER_REASONS,
DRY_RUN_RELEASE_NOTES,
ReleaseReadinessRecord,
check_release_readiness_dry_run,
validate_release_readiness_record,
)
from evidence.release_policy import (
DEFAULT_RELEASE_POLICY_RECORD,
DEFAULT_RELEASE_POLICY_SUMMARY,
PROHIBITED_CONDITIONS,
REQUIRED_CONDITIONS,
ReleasePolicyRecord,
check_release_policy_dry_run,
validate_release_policy_record,
)
from evidence.real_evidence_approval import (
DEFAULT_REAL_EVIDENCE_APPROVAL_RECORDS_OUTPUT,
DEFAULT_REAL_EVIDENCE_APPROVAL_SUMMARY_OUTPUT,
DRY_RUN_BLOCKER_REASONS as APPROVAL_DRY_RUN_BLOCKER_REASONS,
RealEvidenceApprovalRecord,
approve_real_evidence_dry_run,
validate_real_evidence_approval_record,
)
from evidence.real_evidence_inputs import (
DEFAULT_REAL_EVIDENCE_INPUT_STATUS_OUTPUT,
DEFAULT_REAL_EVIDENCE_INPUT_SUMMARY_OUTPUT,
RealEvidenceInputRecord,
load_real_evidence_input_records,
validate_real_evidence_input_record,
validate_real_evidence_inputs_dry_run,
)
from evidence.evidence_location_model import (
missing_location_required_fields,
validate_evidence_location_for_promotion,
)
from scripts.auto_collect_real_evidence import (
AUTO_CONTEXT_SUMMARY,
AUTO_REVIEWER_NOTES,
AUTO_SPEAKER,
auto_collect_real_evidence,
build_candidate_fields,
collect_candidate_for_record,
parse_webvtt,
)
from evidence.source_recovery import (
DEFAULT_SOURCE_RECOVERY_PATH,
SourceRecoveryCandidateRecord,
load_source_recovery_candidates,
summarize_source_recovery_candidates,
validate_source_recovery_candidate_record,
)
from evidence.recovery_candidate_verification import (
RecoveryCandidateVerificationRecord,
validate_recovery_candidate_verification_record,
verify_candidate_reachability,
verify_recovery_candidates,
)
from evidence.selected_recovery_source import (
DEFAULT_SELECTED_RECOVERY_SOURCE_PATH,
load_selected_recovery_sources,
summarize_selected_recovery_sources,
validate_selected_recovery_source_record,
)
from evidence.source_content_extraction import (
SourceContentExtractionRecord,
extract_candidate_text,
extract_content_for_selected_source,
extract_selected_source_content,
validate_source_content_extraction_record,
)
from evidence.source_content_verification import (
build_missing_artifact_records,
validate_source_content_verification_record,
verify_extraction_record,
verify_source_content,
)
from evidence.health_fallback_source import (
BLOCKED_HEALTH_SELECTED_CANDIDATE_ID,
NEXT_HEALTH_FALLBACK_CANDIDATE_ID,
PRIMARY_HEALTH_FALLBACK_CANDIDATE_ID,
HealthFallbackSourceRecord,
build_health_fallback_record,
extract_health_fallback_candidate_text,
handle_health_fallback_candidate,
handle_health_fallback_source,
select_health_fallback_candidate,
validate_health_fallback_source_record,
)
from evidence.canonical_case_model import (
CanonicalCaseModel,
ContradictionAnalysis,
CurrentGovernmentPosition,
EvidenceCollection,
EvidenceReference,
OriginalPromise,
SourceDetails,
SourceOwnership,
SpeakerPoliticalLeader,
build_canonical_case_models,
has_six_blocks,
validate_canonical_case_model,
)
from evidence.template_update_from_content_review import (
HEALTH_EVIDENCE_ID,
JOBS_EVIDENCE_ID,
REVIEWER as TEMPLATE_UPDATE_REVIEWER,
build_template_update,
update_templates_from_content_review,
validate_template_update_record,
)
from evidence.manual_review_promotion import (
APPROVAL_REVIEW_STATUS,
CURRENT_REVIEW_STATUS,
PROMOTION_REVIEWER,
build_manual_review_promotion_record,
promote_manual_review,
validate_manual_review_promotion_record,
)
from scripts.complete_exact_evidence_fields import (
complete_exact_evidence_fields,
build_completion_record,
validate_completion_record,
)
from evidence.exact_quote_manual_entry import (
apply_exact_quote_manual_entry,
build_exact_quote_manual_entry_record,
load_manual_entry,
validate_exact_quote_manual_entry_record,
)
from evidence.final_approved_packet import (
DEFAULT_FINAL_APPROVED_PACKET_RECORD,
DEFAULT_FINAL_APPROVED_PACKET_SUMMARY,
DRY_RUN_BLOCKER_REASONS as PACKET_DRY_RUN_BLOCKER_REASONS,
FinalApprovedEvidencePacketRecord,
generate_final_approved_packet_dry_run,
validate_final_approved_packet_record,
)
from evidence.real_evidence_replacement import (
DEFAULT_REAL_EVIDENCE_OUTPUT_DIR,
DEFAULT_REAL_QUOTE_OUTPUT,
DEFAULT_REAL_STATUS_OUTPUT,
DEFAULT_REAL_TIMESTAMP_OUTPUT,
RealEvidenceReplacementStatus,
phrase_matches_real_text,
replace_real_evidence,
validate_real_evidence_replacement_status,
)
from evidence.manual_review import (
DEFAULT_MANUAL_REVIEW_RECORDS_OUTPUT,
DEFAULT_MANUAL_REVIEW_SUMMARY_OUTPUT,
DRY_RUN_REVIEW_NOTES,
ManualReviewRecord,
manual_review_dry_run,
validate_manual_review_record,
)
from evidence.evidence_loader import DEFAULT_INDEX_PATH, build_evidence_index, load_seed_evidence
from evidence.evidence_gate import validate_case_evidence_links
from evidence.evidence_schema import (
CaseObject,
ClaimObject,
EvidenceObject,
ReportSection,
TranscriptObject,
validate_case_object,
validate_claim_object,
validate_evidence_object,
validate_transcript_object,
)
from evidence.word_exporter import WordExporter
def placeholder_url_parts():
token = "example"
return (
".".join((token, "com")),
token + str(1),
token + str(2),
"youtube.com/watch?v=" + token,
)
def is_placeholder_url(url: str) -> bool:
return any(part in url.lower() for part in placeholder_url_parts())
def run_command(command: str) -> tuple[int, str]:
result = subprocess.run(
command,
shell=True,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
print(result.stdout)
return result.returncode, result.stdout
def assert_nonempty_file(path: str) -> Path:
p = Path(path)
if not p.exists():
raise AssertionError(f"Missing expected file: {path}")
if p.stat().st_size <= 0:
raise AssertionError(f"Expected non-empty file: {path}")
return p
def extract_docx_text(path: Path) -> str:
document = Document(path)
parts = [paragraph.text for paragraph in document.paragraphs]
for table in document.tables:
for row in table.rows:
for cell in row.cells:
parts.append(cell.text)
return "\n".join(parts)
def text_without_allowed_negated_readiness(text: str) -> str:
return text.lower().replace("not institution-ready", "")
def assert_value_error(func, expected_text: str) -> None:
try:
func()
except ValueError as exc:
message = str(exc)
if expected_text not in message:
raise AssertionError(
f"Expected ValueError containing {expected_text!r}, got {message!r}"
)
print(f"✓ expected evidence gate failure: {message}")
return
raise AssertionError("Expected ValueError was not raised")
def make_reportable_case(url: str, verification_status: str = "source_linked"):
evidence_id = "CASE_TEST-PROMISE-001"
evidence = {
"evidence_id": evidence_id,
"case_id": "CASE_TEST",
"source_type": "video",
"platform": "youtube",
"title": "Known Source",
"url": url,
"evidence_role": "promise",
"verification_status": verification_status,
"evidence_strength": "medium",
"timestamp_start": None,
"timestamp_end": None,
}
return {
"case_id": "CASE_TEST",
"evidence_objects": [evidence],
"claim_evidence_links": {
"promise": [evidence_id],
"outcome_or_position": [evidence_id],
"analysis": [evidence_id],
},
}
def validate_divergence_cases(path: Path) -> None:
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
if not isinstance(data, dict):
raise AssertionError("divergence_cases.json must contain a JSON object")
if "metadata" not in data:
raise AssertionError("divergence_cases.json missing root key: metadata")
cases = data.get("cases")
if not isinstance(cases, list) or not cases:
raise AssertionError("divergence_cases.json must contain a non-empty cases list")
required_case_keys = {
"case_id",
"topic",
"promise",
"outcome_or_position",
"divergence_type",
"analysis",
"evidence_strength",
"verification_status",
"description",
"raw_urls",
"evidence_objects",
"claim_evidence_links",
"created_at",
"pipeline_version",
}
required_source_keys = {
"quote",
"source",
"url",
"date",
"evidence_type",
"platform",
"confidence",
}
required_evidence_keys = {
"evidence_id",
"case_id",
"source_type",
"platform",
"title",
"url",
"evidence_role",
"verification_status",
"evidence_strength",
}
required_claim_links = {
"promise",
"outcome_or_position",
"analysis",
}
for idx, case in enumerate(cases):
if not isinstance(case, dict):
raise AssertionError(f"Case {idx} must be an object")
missing = required_case_keys - set(case.keys())
if missing:
raise AssertionError(f"Case {idx} missing keys: {sorted(missing)}")
if case["pipeline_version"] != "divergence_engine_v3.0":
raise AssertionError(
f"Case {idx} has wrong pipeline_version: {case['pipeline_version']}"
)
for nested_key in ("promise", "outcome_or_position"):
nested = case[nested_key]
if not isinstance(nested, dict):
raise AssertionError(f"Case {idx}.{nested_key} must be an object")
missing_nested = required_source_keys - set(nested.keys())
if missing_nested:
raise AssertionError(
f"Case {idx}.{nested_key} missing keys: {sorted(missing_nested)}"
)
nested_url = nested.get("url", "")
if not isinstance(nested_url, str):
raise AssertionError(f"Case {idx}.{nested_key}.url must be a string")
if is_placeholder_url(nested_url):
raise AssertionError(
f"Case {idx}.{nested_key}.url must not be a placeholder"
)
if not isinstance(case["raw_urls"], list):
raise AssertionError(f"Case {idx}.raw_urls must be a list")
for raw_url in case["raw_urls"]:
if not isinstance(raw_url, str):
raise AssertionError(f"Case {idx}.raw_urls entries must be strings")
if is_placeholder_url(raw_url):
raise AssertionError(f"Case {idx}.raw_urls contains a placeholder")
evidence_objects = case["evidence_objects"]
if not isinstance(evidence_objects, list) or not evidence_objects:
raise AssertionError(f"Case {idx}.evidence_objects must be non-empty")
evidence_ids = set()
for evidence_idx, evidence in enumerate(evidence_objects):
if not isinstance(evidence, dict):
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}] must be an object"
)
missing_evidence = required_evidence_keys - set(evidence.keys())
if missing_evidence:
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}] missing keys: "
f"{sorted(missing_evidence)}"
)
for evidence_key in required_evidence_keys:
value = evidence[evidence_key]
if evidence_key == "url":
if not isinstance(value, str):
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}]."
f"{evidence_key} must be a string"
)
if is_placeholder_url(value):
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}]."
f"{evidence_key} must not be a placeholder"
)
continue
if not isinstance(value, str) or not value.strip():
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}]."
f"{evidence_key} must be a non-empty string"
)
verification_status = evidence["verification_status"]
has_timestamp = bool(
evidence.get("timestamp_start") or evidence.get("timestamp_end")
)
if verification_status == "timestamp_verified" and not has_timestamp:
raise AssertionError(
f"Case {idx}.evidence_objects[{evidence_idx}] "
"cannot be timestamp_verified without timestamp fields"
)
evidence_id = evidence["evidence_id"]
if evidence_id in evidence_ids:
raise AssertionError(f"Case {idx} duplicate evidence_id: {evidence_id}")
evidence_ids.add(evidence_id)
claim_links = case["claim_evidence_links"]
if not isinstance(claim_links, dict):
raise AssertionError(f"Case {idx}.claim_evidence_links must be an object")
for claim_key in required_claim_links:
linked_ids = claim_links.get(claim_key)
if not isinstance(linked_ids, list) or not linked_ids:
raise AssertionError(
f"Case {idx}.claim_evidence_links.{claim_key} must be non-empty"
)
for evidence_id in linked_ids:
if evidence_id not in evidence_ids:
raise AssertionError(
f"Case {idx}.claim_evidence_links.{claim_key} references "
f"unknown evidence_id: {evidence_id}"
)
print(f"✓ divergence_cases.json OK: {len(cases)} cases")
def validate_gate_rejections() -> None:
assert_value_error(
lambda: validate_case_evidence_links(make_reportable_case("")),
"EvidenceObject.url must be a non-empty string",
)
token = "example"
placeholder_url = "https://www.youtube.com/watch?v=" + token + str(1)
assert_value_error(
lambda: validate_case_evidence_links(make_reportable_case(placeholder_url)),
"EvidenceObject.url appears to be a placeholder",
)
assert_value_error(
lambda: validate_case_evidence_links(
make_reportable_case(
"https://sources.local/evidence",
verification_status="timestamp_verified",
)
),
"requires timestamp_start and timestamp_end",
)
def validate_schema_objects() -> None:
evidence = EvidenceObject(
evidence_id="VID_TEST_001",
case_id="CASE_TEST",
source_type="video",
platform="youtube",
title="Known Source",
url="https://www.youtube.com/watch?v=abc123",
evidence_role="promise_video",
verification_status="source_found",
evidence_strength="medium",
)
validate_evidence_object(evidence)
assert_value_error(
lambda: validate_evidence_object({**evidence.to_dict(), "url": ""}),
"EvidenceObject.url must be a non-empty string",
)
token = "example"
placeholder_url = "https://www.youtube.com/watch?v=" + token + str(1)
assert_value_error(
lambda: validate_evidence_object({**evidence.to_dict(), "url": placeholder_url}),
"EvidenceObject.url appears to be a placeholder",
)
assert_value_error(
lambda: validate_evidence_object(
{**evidence.to_dict(), "verification_status": "timestamp_verified"}
),
"requires timestamp_start and timestamp_end",
)
assert_value_error(
lambda: validate_evidence_object(
{
**evidence.to_dict(),
"verification_status": "quote_verified",
"timestamp_start": "00:01",
"timestamp_end": "00:10",
"raw_quote": None,
}
),
"requires raw_quote",
)
claim = ClaimObject(
claim_id="CLAIM_TEST_001",
case_id="CASE_TEST",
claim_type="promise",
text="A sourced claim.",
evidence_ids=[evidence.evidence_id],
verification_status="source_found",
)
validate_claim_object(claim)
assert_value_error(
lambda: validate_claim_object({**claim.to_dict(), "evidence_ids": []}),
"ClaimObject.evidence_ids must be a non-empty list",
)
case = CaseObject(
case_id="CASE_TEST",
title="Test Case",
domain="governance",
divergence_type="promise_vs_outcome",
claims=[claim],
evidence=[evidence],
evidence_strength="medium",
verification_status="source_found",
)
validate_case_object(case)
unresolved_claim = ClaimObject(
claim_id="CLAIM_TEST_002",
case_id="CASE_TEST",
claim_type="promise",
text="An unresolved claim.",
evidence_ids=["MISSING_EVIDENCE"],
verification_status="source_found",
)
assert_value_error(
lambda: validate_case_object({**case.to_dict(), "claims": [unresolved_claim]}),
"references unknown evidence_id",
)
print("✓ EvidenceObject v1 schema validation OK")
def validate_ingestion_lane() -> None:
index = load_or_build_evidence_index()
if index["metadata"]["total_evidence_records"] != 2:
raise AssertionError("Evidence ingestion index must contain 2 records")
seed_evidence = load_seed_evidence()[0]
validate_evidence_object(seed_evidence)
pending_transcript = load_transcript_artifact(seed_evidence.evidence_id)
if pending_transcript is None:
raise AssertionError(f"Missing transcript artifact: {seed_evidence.evidence_id}")
validate_transcript_object(pending_transcript)
if pending_transcript.transcript_status != "pending":
raise AssertionError("Seed transcript artifact must remain pending")
assert_value_error(
lambda: upgrade_evidence_status(seed_evidence, "timestamp_verified"),
"Invalid evidence status transition",
)
assert_value_error(
lambda: upgrade_evidence_status(seed_evidence, "transcript_found"),
"requires a transcript artifact",
)
assert_value_error(
lambda: upgrade_evidence_status(
seed_evidence,
"transcript_found",
pending_transcript,
),
"transcript_status=transcribed",
)
transcribed = TranscriptObject(
evidence_id=seed_evidence.evidence_id,
transcript_status="transcribed",
transcript_text="Unit test transcript text.",
source="unit-test",
generated_by="unit-test",
verification_notes="Unit test transcript fixture only.",
)
validate_transcript_object(transcribed)
transcript_found = upgrade_evidence_status(
seed_evidence,
"transcript_found",
transcribed,
)
if transcript_found.verification_status != "transcript_found":
raise AssertionError("Evidence did not move to transcript_found")
for immutable_field in ("evidence_id", "case_id", "url", "title"):
if getattr(seed_evidence, immutable_field) != getattr(transcript_found, immutable_field):
raise AssertionError(f"Evidence ingestion changed {immutable_field}")
assert_value_error(
lambda: upgrade_evidence_status(transcript_found, "timestamp_verified"),
"requires timestamp_start and timestamp_end",
)
timestamped = upgrade_evidence_status(
transcript_found,
"timestamp_verified",
timestamp_start="00:01",
timestamp_end="00:05",
)
validate_evidence_object(timestamped)
assert_value_error(
lambda: upgrade_evidence_status(timestamped, "quote_verified"),
"requires raw_quote",
)
quoted = upgrade_evidence_status(
timestamped,
"quote_verified",
raw_quote="Unit test quote.",
)
validate_evidence_object(quoted)
report_ready = upgrade_evidence_status(quoted, "report_ready")
validate_evidence_object(report_ready)
print("✓ Evidence Ingestion v1 lane validation OK")
def validate_transcript_acquisition_lane() -> None:
seed_evidence = load_seed_evidence()[0]
if extract_youtube_video_id(seed_evidence.url) != "e0MLzB5nGDc":
raise AssertionError("YouTube watch URL video_id extraction failed")
if extract_youtube_video_id("https://youtu.be/e0MLzB5nGDc") != "e0MLzB5nGDc":
raise AssertionError("youtu.be URL video_id extraction failed")
success_artifact = transcript_found_artifact(
seed_evidence,
[{"text": "Fixture transcript text for validation only."}],
"fixture-test",
"en",
)
validate_transcript_artifact(success_artifact)
assert_value_error(
lambda: validate_transcript_artifact(
{**success_artifact.to_dict(), "transcript_text": ""}
),
"transcript_text must be non-empty",
)
unavailable_artifact = failure_artifact(
seed_evidence,
"transcript_unavailable",
"fixture-test",
"No transcript available in fixture.",
)
validate_transcript_artifact(unavailable_artifact)
failed_artifact = failure_artifact(
seed_evidence,
"acquisition_failed",
"fixture-test",
"Fixture provider failure.",
)
validate_transcript_artifact(failed_artifact)
assert_value_error(
lambda: validate_transcript_artifact(
{**unavailable_artifact.to_dict(), "error": ""}
),
"error must be non-empty",
)
assert_value_error(
lambda: validate_transcript_artifact(
{**failed_artifact.to_dict(), "transcript_text": "not allowed"}
),
"transcript_text must be empty",
)
assert_value_error(
lambda: validate_transcript_artifact(
{**success_artifact.to_dict(), "verification_status": "timestamp_verified"}
),
"cannot mark evidence as timestamp_verified",
)
upgraded = upgrade_evidence_from_transcript_artifact(seed_evidence, success_artifact)
if upgraded.verification_status != "transcript_found":
raise AssertionError("Transcript acquisition must only upgrade to transcript_found")
if upgraded.timestamp_start or upgraded.timestamp_end or upgraded.raw_quote:
raise AssertionError("Transcript acquisition must not set timestamps or raw_quote")
assert_value_error(
lambda: upgrade_evidence_from_transcript_artifact(
seed_evidence,
unavailable_artifact,
),
"transcript_found is required",
)
summary = acquire_transcripts(fixtures_only=True)
if summary["processed"] != 2:
raise AssertionError("Fixture transcript acquisition must process 2 records")
if summary["transcript_found"] != 0:
raise AssertionError("Fixture acquisition must not invent transcript text")
if summary["transcript_unavailable"] != 1 or summary["acquisition_failed"] != 1:
raise AssertionError("Fixture acquisition counts are not deterministic")
print("✓ Transcript Acquisition v1 lane validation OK")
def validate_timestamp_verification_lane() -> None:
candidate = TimestampCandidate(
evidence_id="VID_JOBS_001",
case_id="CASE_002",
phrase="500 000 new jobs",
timestamp_start="00:00:10",
timestamp_end="00:00:18",
matched_text="We promised to create 500 000 new jobs in five years.",
match_confidence=1.0,
verification_status="timestamp_verified",
verification_notes="Unit test timestamp fixture only.",
)
validate_timestamp_candidate(candidate)
assert_value_error(
lambda: validate_timestamp_candidate(
{**candidate.to_dict(), "timestamp_start": ""}
),
"timestamp_start must be a non-empty string",
)
assert_value_error(
lambda: validate_timestamp_candidate(
{**candidate.to_dict(), "timestamp_end": ""}
),
"timestamp_end must be a non-empty string",
)
assert_value_error(
lambda: validate_timestamp_candidate(
{
**candidate.to_dict(),
"timestamp_start": "00:00:20",
"timestamp_end": "00:00:10",
}
),
"timestamp_end must not be before start",
)
assert_value_error(
lambda: validate_timestamp_candidate(
{**candidate.to_dict(), "matched_text": ""}
),
"matched_text must be a non-empty string",
)
assert_value_error(
lambda: validate_timestamp_candidate(
{
**candidate.to_dict(),
"phrase": "not in transcript",
}
),
"phrase must appear in matched_text",
)
assert_value_error(
lambda: validate_timestamp_candidate(
{
**candidate.to_dict(),
"evidence_verification_status": "quote_verified",
}
),
"cannot mark evidence as quote_verified",
)
summary = verify_timestamps_fixture_only()
if summary["processed"] != 2:
raise AssertionError("Timestamp fixture verification must process 2 records")
if summary["candidates_found"] != 4:
raise AssertionError("Timestamp fixture verification must produce 4 candidates")
if summary["timestamp_verified"] != 4:
raise AssertionError("Timestamp fixtures must verify 4 timestamp candidates")
if summary["timestamp_rejected"] != 0 or summary["timestamp_unavailable"] != 0:
raise AssertionError("Timestamp fixtures should not reject or miss candidates")
for produced in summary["candidates"]:
if produced.verification_status != "timestamp_verified":
raise AssertionError("Fixture candidates must be timestamp_verified only")
produced_data = produced.to_dict()
if produced_data.get("raw_quote"):
raise AssertionError("Timestamp verification must not set raw_quote")
if produced_data.get("evidence_verification_status") == "quote_verified":
raise AssertionError("Timestamp verification must not imply quote_verified")
assert_nonempty_file(str(DEFAULT_TIMESTAMP_OUTPUT))
print("✓ Timestamp Verification v1 lane validation OK")
def validate_quote_verification_lane() -> None:
candidate = QuoteCandidate(
evidence_id="VID_JOBS_001",
case_id="CASE_002",
phrase="500 000 new jobs",
timestamp_start="00:00:10",
timestamp_end="00:00:18",
matched_text="We promised to create 500 000 new jobs in five years.",
raw_quote="500 000 new jobs",
quote_confidence=1.0,
verification_status="quote_verified",
verification_notes="Unit test quote fixture only. Report readiness pending.",
)
validate_quote_candidate(candidate)
assert_value_error(
lambda: validate_quote_candidate({**candidate.to_dict(), "raw_quote": ""}),
"raw_quote must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate(
{**candidate.to_dict(), "timestamp_start": ""}
),
"timestamp_start must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate(
{**candidate.to_dict(), "timestamp_end": ""}
),
"timestamp_end must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate({**candidate.to_dict(), "matched_text": ""}),
"matched_text must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate(
{**candidate.to_dict(), "raw_quote": "not in transcript"}
),
"raw_quote must be contained in matched_text",
)
assert_value_error(
lambda: validate_quote_candidate(
{
**candidate.to_dict(),
"verification_status": "quote_unavailable",
"raw_quote": "",
"verification_notes": "",
}
),
"verification_notes must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate(
{
**candidate.to_dict(),
"verification_status": "quote_rejected",
"raw_quote": "",
"verification_notes": "",
}
),
"verification_notes must be a non-empty string",
)
assert_value_error(
lambda: validate_quote_candidate(
{**candidate.to_dict(), "evidence_verification_status": "report_ready"}
),
"cannot mark evidence as report_ready",
)
summary = verify_quotes_fixture_only()
if summary["processed"] != 4:
raise AssertionError("Quote fixture verification must process 4 timestamps")
if summary["quote_verified"] != 4:
raise AssertionError("Quote fixtures must verify 4 quote candidates")
if (
summary["quote_candidate_found"] != 0
or summary["quote_rejected"] != 0
or summary["quote_unavailable"] != 0
):
raise AssertionError("Quote fixtures should not be pending, rejected, or missed")
for produced in summary["candidates"]:
if produced.verification_status != "quote_verified":
raise AssertionError("Fixture quote candidates must be quote_verified only")
produced_data = produced.to_dict()
if produced_data.get("evidence_verification_status") == "report_ready":
raise AssertionError("Quote verification must not imply report_ready")
if "TEST FIXTURE ONLY" not in produced.verification_notes:
raise AssertionError("Fixture quote candidates must be clearly labeled")
assert_nonempty_file(str(DEFAULT_QUOTE_OUTPUT))
print("✓ Quote Verification v1 lane validation OK")
def validate_case_evidence_linking_lane() -> None:
link = CaseEvidenceLink(
case_id="CASE_002",
claim_id="CLAIM_JOBS_001",
evidence_id="VID_JOBS_001",
quote_id="QUOTE_VID_JOBS_001_500_000_NEW_JOBS",
phrase="500 000 new jobs",
timestamp_start="00:00:10",
timestamp_end="00:00:18",
raw_quote="500 000 new jobs",
link_status="link_verified",
link_notes="Unit test link fixture only. Report readiness pending.",