forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_static_demo.py
More file actions
1826 lines (1676 loc) · 66.9 KB
/
Copy pathtest_static_demo.py
File metadata and controls
1826 lines (1676 loc) · 66.9 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
import json
import re
import shutil
import subprocess
from datetime import date
from io import BytesIO
import pytest
from demo.app import (
MAX_BODY_BYTES,
ROOT,
Handler,
result_page,
static_path,
)
from demo.app import (
STRINGS as DEMO_STRINGS,
)
from scripts.build_demo_bundle import (
COVERAGE_INDEX_OUTPUT,
OUTPUT,
build_bundle,
build_coverage_index_payload,
build_journey_payload,
build_readiness_payload,
encoded_coverage_index,
)
def run_node_module(script: str) -> None:
"""Run generated JavaScript over stdin to stay below OS argument limits."""
subprocess.run(
["node", "--input-type=module"],
input=script,
check=True,
capture_output=True,
text=True,
)
def test_committed_demo_bundle_matches_canonical_json():
bundle = build_bundle()
assert OUTPUT.read_text(encoding="utf-8") == bundle
assert '"format_version":6' in bundle
assert '"coverage_index":' in bundle
assert '"source_state":' in bundle
assert '"program_availability":' in bundle
assert '"rule_verification":' in bundle
def test_generated_coverage_index_matches_canonical_records():
index = build_coverage_index_payload()
assert COVERAGE_INDEX_OUTPUT.read_text(encoding="utf-8") == (
encoded_coverage_index()
)
assert index["schema_version"] == 1
assert len(index["statewide_rule_ids"]) == 17
assert len(index["profiles"]) == 541
assert index["profiles"]["davis"]["local_rule_ids"] == ["davis-local-adu-process"]
assert index["profiles"]["alameda"]["local_rule_ids"] == []
def test_generated_woodland_journey_binds_one_route_and_packet_envelope():
readiness, _ = build_readiness_payload()
journey, digests = build_journey_payload()
assert journey["journey_id"] == ("woodland-preapproved-detached-adu-synthetic")
assert journey["version"] == "1.0.0"
assert journey["synthetic"] is True
assert journey["screening_case_id"] == ("woodland-new-detached-adu-local-layer")
assert journey["candidate_route_rule_ids"] == ["adu-ministerial-review"]
assert journey["readiness_workflow_id"] == ("woodland-preapproved-detached-adu")
assert journey["readiness_packet_id"] == (
"woodland-preapproved-adu-hypothetical-001"
)
assert journey["applicability_status"] == "applies"
assert [route["rule_id"] for route in journey["candidate_routes"]] == [
"adu-ministerial-review"
]
assert journey["route_source_status"] == "current"
assert journey["route_source_status_as_of"] == "2026-07-30"
assert journey["route_source_review_due_on"] == "2027-01-23"
assert journey["screening_intake"] == {
"project_type": "adu",
"primary_dwelling_status": "existing_single_family",
"adu_project_form": "new_detached",
"unpermitted_existing": "no",
"jurisdiction": "woodland",
}
assert [fact["fact_id"] for fact in journey["applicability_facts"]] == [
"uses_city_preapproved_plan",
"parcel_city_matches_woodland",
"parcel_land_use_is_residential",
]
assert [
fact["fact_id"] for fact in journey["applicability_facts"] if fact["editable"]
] == ["uses_city_preapproved_plan"]
assert all(
fact["value"] == fact["expected_value"] == "yes"
for fact in journey["applicability_facts"]
)
assert journey["screening_case_fingerprint"].startswith("sha256:")
assert (
journey["readiness_workflow_fingerprint"]
== (readiness["result"]["workflow_fingerprint"])
)
assert (
journey["readiness_packet_fingerprint"]
== (readiness["result"]["packet_fingerprint"])
)
assert journey["readiness_evidence_manifest"] == readiness["evidence_manifest"]
assert journey["fact_envelope"]["synthetic"] is True
assert journey["fact_envelope_fingerprint"].startswith("sha256:")
assert journey["journey_fingerprint"].startswith("sha256:")
assert set(digests) == {"data/journeys/woodland-preapproved-detached-adu.json"}
def test_python_trust_rehearsal_uses_human_readable_source_label():
html = (ROOT / "demo" / "app.py").read_text(encoding="utf-8")
assert '"Gov. Code § 66321"' in html
assert "Gov. Code § {html.escape(changed[0])}" not in html
def test_static_pages_load_only_the_assets_they_need():
landing = (ROOT / "index.html").read_text(encoding="utf-8")
assert 'src="data/demo-data.js?' not in landing
assert 'src="assets/demo.js?' not in landing
style_versions = {}
for page_name in (
"index.html",
"check.html",
"prepare.html",
"review.html",
"evidence.html",
):
html = (ROOT / page_name).read_text(encoding="utf-8")
style_match = re.search(
r'<link rel="stylesheet" href="assets/site\.css\?v=([a-zA-Z0-9]+)">',
html,
)
assert style_match, page_name
style_versions[page_name] = style_match.group(1)
assert len(set(style_versions.values())) == 1
for page_name, page_id in {
"check.html": "project",
"prepare.html": "readiness",
"review.html": "review",
"evidence.html": "evidence",
}.items():
html = (ROOT / page_name).read_text(encoding="utf-8")
assert f'<body data-page="{page_id}">' in html
bundle_match = re.search(
r'<script src="data/demo-data\.js\?v=([a-zA-Z0-9]+)" defer></script>',
html,
)
application_match = re.search(
r'<script src="assets/demo\.js\?v=([a-zA-Z0-9]+)" defer></script>',
html,
)
assert bundle_match, page_name
assert application_match, page_name
assert bundle_match.group(1) == application_match.group(1), page_name
assert application_match.group(1) == style_versions[page_name], page_name
assert bundle_match.start() < application_match.start(), page_name
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert "globalThis.PERMIT_PATHWAYS_DEMO_DATA" in application
assert "data?._meta?.format_version !== 6" in application
assert "normalizeCoverageIndex" in application
def test_check_page_has_a_hidden_until_recognized_coverage_profile_region():
check = (ROOT / "check.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert '<details class="jurisdiction-profile ca-box"' in check
assert 'id="jurisdictionProfile"' in check
assert 'aria-labelledby="jurisdictionProfileHeading"' in check
profile_start = check.index('<details class="jurisdiction-profile ca-box"')
profile_tag = check[profile_start : check.index(">", profile_start) + 1]
assert " hidden" in profile_tag
assert " open" not in profile_tag
assert "renderJurisdictionProfile" in application
assert (
'output.innerHTML = `<summary id="jurisdictionProfileHeading">' in application
)
assert "output.open = false" in application
assert "No linked records in this dataset" in application
assert "This is not evidence of compliance" in application
def test_check_page_uses_collapsed_native_support_disclosures_and_route_first_order():
check = (ROOT / "check.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
clock_start = check.index('<details class="optional-tool" id="clocks"')
clock_tag = check[clock_start : check.index(">", clock_start) + 1]
clock_end = check.index("</details>", clock_start)
clock_markup = check[clock_start:clock_end]
assert " open" not in clock_tag
assert "<summary>" in clock_markup
assert 'id="recvDate"' in clock_markup
assert 'id="clockBtn"' in clock_markup
assert '<details class="result-cover-sheet result-support ca-box"' in application
assert (
'<summary class="result-support-summary" id="projectFactsHeading">'
in application
)
assert '<details class="statewide-orientation result-support ca-box"' in application
sample_result_start = check.index('id="sampleResult"')
sample_result_tag = check[
check.rfind("<a", 0, sample_result_start) : check.index(
">", sample_result_start
)
+ 1
]
assert " hidden" in sample_result_tag
assert (
'<details class="result-cover-sheet result-support ca-box" open'
not in application
)
assert (
'<details class="statewide-orientation result-support ca-box" open'
not in application
)
facts_summary_start = application.index(
'<summary class="result-support-summary" id="projectFactsHeading">'
)
facts_summary_end = application.index("</summary>", facts_summary_start)
facts_summary = application[facts_summary_start:facts_summary_end]
assert "result-support-meta" not in facts_summary
assert "${esc(s.editAnswers)}" not in facts_summary
render_results = application[
application.index("function renderResults(list)") : application.index(
"function questionLabel", application.index("function renderResults(list)")
)
]
assert render_results.index("${sections}") < render_results.rindex(
"${renderProjectFacts()}"
)
assert render_results.rindex("${renderProjectFacts()}") < render_results.rindex(
"${statewideOrientationMarkup(list)}"
)
def test_static_pages_have_consistent_navigation_and_resolvable_links():
pages = {
ROOT / "index.html": 1,
ROOT / "check.html": 2,
ROOT / "prepare.html": 0,
ROOT / "review.html": 2,
ROOT / "evidence.html": 2,
}
expected_nav = [
("check.html", "Start"),
("evidence.html", "Sources & limits"),
("review.html", "For staff"),
]
for path, expected_current_count in pages.items():
html = path.read_text(encoding="utf-8")
site_header = html[
html.index('<header class="site-header">') : html.index("</header>")
]
assert html.count("<main ") == 1
assert html.count("<h1") == 1
assert 'href="#mainContent"' in html
assert html.count('aria-current="page"') == expected_current_count
assert html.count('class="mobile-menu"') == 1
assert html.count('aria-label="Mobile primary"') == 1
assert "<summary>Sections</summary>" in html
assert (
'<link rel="icon" href="assets/favicon.svg" type="image/svg+xml">' in html
)
assert 'http-equiv="Content-Security-Policy"' in html
for target, label in expected_nav:
assert site_header.count(f'<a href="{target}"') == 2
assert site_header.count(f">{label}</a>") == 2
for target in re.findall(r'(?:href|src)="([^"]+)"', html):
if target.startswith(("https://", "http://", "#", "data:")):
continue
assert not target.startswith("/")
local_target = target.split("?", 1)[0].split("#", 1)[0]
assert (ROOT / local_target).is_file(), (path.name, target)
def _webp_dimensions(asset):
data = asset.read_bytes()
assert data[:4] == b"RIFF"
assert data[8:12] == b"WEBP"
assert int.from_bytes(data[4:8], "little") == len(data) - 8
dimensions = None
offset = 12
while offset < len(data):
assert offset + 8 <= len(data)
chunk_type = data[offset : offset + 4]
chunk_size = int.from_bytes(data[offset + 4 : offset + 8], "little")
payload_start = offset + 8
payload_end = payload_start + chunk_size
assert payload_end <= len(data)
payload = data[payload_start:payload_end]
if chunk_type == b"VP8 ":
assert len(payload) >= 10
assert payload[3:6] == b"\x9d\x01\x2a"
dimensions = (
int.from_bytes(payload[6:8], "little") & 0x3FFF,
int.from_bytes(payload[8:10], "little") & 0x3FFF,
)
elif chunk_type == b"VP8L":
assert len(payload) >= 5 and payload[0] == 0x2F
bits = int.from_bytes(payload[1:5], "little")
dimensions = ((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)
elif chunk_type == b"VP8X":
assert len(payload) >= 10
dimensions = (
int.from_bytes(payload[4:7], "little") + 1,
int.from_bytes(payload[7:10], "little") + 1,
)
offset = payload_end + (chunk_size % 2)
assert offset == len(data)
assert dimensions is not None
return dimensions
def test_site_illustrations_are_local_bounded_and_decorative():
expected_assets = {
"assets/illustrations/permit-pathway-hero-768.webp": (768, 512),
"assets/illustrations/permit-pathway-hero.webp": (1152, 768),
"assets/illustrations/project-check-path.webp": (1152, 768),
}
for asset_path, dimensions in expected_assets.items():
asset = ROOT / asset_path
assert asset.is_file()
assert asset.stat().st_size < 96 * 1024
assert _webp_dimensions(asset) == dimensions
expected_pages = {
"index.html": (
"assets/illustrations/permit-pathway-hero.webp",
"home-hero-visual",
),
"check.html": (
"assets/illustrations/project-check-path.webp",
"project-hero-visual",
),
}
for page_name, (asset_path, figure_class) in expected_pages.items():
page = (ROOT / page_name).read_text(encoding="utf-8")
assert f'<figure class="{figure_class}" aria-hidden="true">' in page
assert f'src="{asset_path}" alt=""' in page
assert 'width="1152" height="768"' in page
landing = (ROOT / "index.html").read_text(encoding="utf-8")
assert "permit-pathway-hero-768.webp 768w" in landing
assert "permit-pathway-hero.webp 1152w" in landing
assert 'sizes="(max-width: 58rem) calc(100vw - 2rem), 42vw"' in landing
styles = (ROOT / "assets" / "site.css").read_text(encoding="utf-8")
assert ".home-hero-visual" in styles
assert ".project-hero-visual" in styles
assert 'body[data-page="project"] .tool-hero-grid' in styles
def test_landing_scope_matches_the_current_bounded_davis_record():
landing = (ROOT / "index.html").read_text(encoding="utf-8")
assert "Davis source record is explicitly unverified" not in landing
assert (
"Davis record reports only the City\u2019s published processing categories"
in landing
)
assert "HCD\u2019s unresolved ordinance-status warning" in landing
def test_public_brand_name_and_tagline_are_consistent():
public_files = {
ROOT / "index.html",
ROOT / "check.html",
ROOT / "prepare.html",
ROOT / "review.html",
ROOT / "evidence.html",
ROOT / "assets" / "demo.js",
ROOT / "demo" / "app.py",
ROOT / "README.md",
ROOT / "docs" / "PRODUCT-CONTEXT.md",
ROOT / "AGENTS.md",
ROOT / "LICENSE",
ROOT / "THIRD_PARTY_NOTICES.md",
ROOT / "src" / "permit_pathways" / "__init__.py",
}
legacy_human_name = "Permit " + "Pathways"
for path in public_files:
assert legacy_human_name not in path.read_text(encoding="utf-8")
landing = (ROOT / "index.html").read_text(encoding="utf-8")
project = (ROOT / "check.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
tagline = (
"Find a candidate route. See the sources behind it. "
"Take open questions to staff."
)
assert (
"<title>Permit Bearings | Get your bearings before you file</title>" in landing
)
assert (
'<meta property="og:title" content="Permit Bearings | Get your bearings '
'before you file">' in landing
)
assert (
'<meta property="og:url" '
'content="https://chelseakr.github.io/permit-bearings/">' in landing
)
assert (
'<meta property="og:image" content="https://chelseakr.github.io/'
'permit-bearings/assets/social-card.png">' in landing
)
assert '<meta name="twitter:card" content="summary_large_image">' in landing
assert "Get your bearings before you file." in landing
assert "Know the path in. Test the path out." in landing
assert "Open the made-up Woodland example" in landing
assert "Check a different project" in landing
assert 'href="check.html?sample=adu"' in landing
social_card = (ROOT / "assets" / "social-card.png").read_bytes()
assert social_card[:8] == b"\x89PNG\r\n\x1a\n"
assert int.from_bytes(social_card[16:20], "big") == 1200
assert int.from_bytes(social_card[20:24], "big") == 630
assert 'id="t-tagline"' in project
assert tagline in application
assert DEMO_STRINGS["en"]["title"] == "Permit Bearings | demo"
assert DEMO_STRINGS["en"]["tagline"] == tagline
assert DEMO_STRINGS["es"]["title"] == "Permit Bearings | demostración"
assert DEMO_STRINGS["es"]["tagline"] == (
"Encuentre una posible ruta. Vea las fuentes que la respaldan. "
"Consulte las preguntas pendientes con el personal de la agencia."
)
rendered_page = result_page(
{
"jurisdiction": "Davis",
"project_type": "adu",
"primary_dwelling_status": "existing_single_family",
"adu_project_form": "new_detached",
},
"en",
)
assert '<a class="brand" href="/?lang=en">Permit Bearings</a>' in rendered_page
pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
assert 'name = "permit-pathways"' in pyproject
assert "globalThis.PERMIT_PATHWAYS_DEMO_DATA" in application
assert (ROOT / "src" / "permit_pathways").is_dir()
def test_public_interface_copy_uses_no_em_dashes():
public_sources = [
ROOT / "index.html",
ROOT / "check.html",
ROOT / "prepare.html",
ROOT / "review.html",
ROOT / "evidence.html",
ROOT / "assets" / "demo.js",
ROOT / "demo" / "app.py",
]
em_dash = chr(0x2014)
for path in public_sources:
assert em_dash not in path.read_text(encoding="utf-8"), path
rendered = result_page(
{
"jurisdiction": ["davis"],
"project_type": ["adu"],
"primary_dwelling_status": ["existing_single_family"],
"adu_project_form": ["new_detached"],
"unpermitted_existing": ["no"],
},
"en",
)
assert em_dash not in rendered
def test_static_site_uses_published_california_design_tokens():
css = (ROOT / "assets" / "site.css").read_text(encoding="utf-8")
for token, value in {
"--primary-900": "#003688",
"--cagov-primary": "#004abc",
"--cagov-highlight": "#fec02f",
"--accent2-300": "#ecb32d",
"--success-900": "#154425",
"--danger-900": "#721923",
"--w-lg": "73.5rem",
"--w-page-content": "54.75rem",
}.items():
assert f"{token}: {value}" in css
assert '--site-font: "Public Sans", "Noto Sans", Arial, sans-serif' in css
assert "--paper: var(--gray-50)" in css
assert "--blue: var(--primary-900)" in css
assert "--yellow: var(--cagov-highlight)" in css
assert "outline: 3px solid var(--accent2-300)" in css
assert "Avenir" not in css
def test_mobile_navigation_and_evidence_records_have_responsive_hooks():
css = (ROOT / "assets" / "site.css").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert ".mobile-menu" in css
assert '.mobile-nav a[aria-current="page"]' in css
assert ".table-scroll td::before" in css
for label in (
"Rule",
"Scope",
"Source status",
"Interpretation review",
"Source",
"Monitoring",
"Recorded",
"SHA-256",
):
assert f'data-label="{label}"' in application
def test_section_headings_use_interface_type_instead_of_utility_mono():
css = (ROOT / "assets" / "site.css").read_text(encoding="utf-8")
for selector in (
".result-group > h3",
".result-card h5",
".scanner-notes h3",
):
match = re.search(rf"{re.escape(selector)}\s*\{{(?P<body>[^}}]+)\}}", css)
assert match, selector
declarations = match.group("body")
assert "font-family: var(--display);" in declarations
assert "font-family: var(--utility);" not in declarations
assert "text-transform: uppercase;" not in declarations
def test_static_result_cards_keep_explanations_separate_from_matching():
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
project = (ROOT / "check.html").read_text(encoding="utf-8")
review = (ROOT / "review.html").read_text(encoding="utf-8")
evidence = (ROOT / "evidence.html").read_text(encoding="utf-8")
assert "function screen(intake)" in application
assert "function renderResultCard(rule, explanation" in application
assert "async function normalizeExplanations(payload, rules)" in application
assert "Array.isArray(payload.entries)" in application
assert "async function citationFingerprint(rule)" in application
assert "async function ruleFingerprint(rule)" in application
assert "async function localizedContentFingerprint" in application
assert "source_dependencies: rule.source_dependencies" in application
assert "function validHighlights(value)" in application
assert "record.citation_fingerprint !== expectedFingerprint" in application
assert "record.rule_fingerprint !== expectedRuleFingerprint" in application
assert (
"if (!globalThis.crypto || !globalThis.crypto.subtle) return new Map()"
in application
)
assert "EXPLANATIONS.get(rule.rule_id)" in application
assert "EXPLANATIONS = await normalizeExplanations" in application
assert "data-rule-id=" in application
assert '<details class="rule-details"' in application
assert 'source: "Source"' in application
assert "Draft explanation · made with AI · not reviewed by a person" in application
assert "no revisado para comprobar su exactitud" in application
assert "We are not showing next steps" in application
assert "limited rules in this prototype" in application
assert '"primary_dwelling_status"' in application
assert '"adu_project_form"' in application
assert '["yes","Yes"],["no","No"],["unknown","I\'m not sure"]' in application
assert 'id="resultsHeading" tabindex="-1"' in application
assert 'class="edit-answers" href="#screenHeading"' in application
assert 'id="screenHeading" tabindex="-1"' in project
assert "heading.focus()" in application
assert "aria-invalid" in application
assert 'name="has_primary_dwelling"' not in application
assert (
'"jadu")\n return ["primary_dwelling_status", "unpermitted_existing"]'
in application
)
assert "two_unit_contributing_historic_location" in application
assert "lot_split_alters_historic_district_resource" in application
assert "Supporting local information is shown below" in application
assert 'fieldset data-question="${esc(name)}"${describedBy}' in application
assert "Check candidate pathways" in project
assert 'href="check.html?sample=adu"' in project
assert 'id="projectSampleNotice"' in project
assert 'id="resultStatus"' in project
assert 'id="clockBtn"' in project
assert 'id="loadSample"' in review
assert 'id="scanStatus"' in review
assert 'id="simBtn"' in evidence
assert 'id="sourceTable"' in evidence
def test_packet_sample_renders_only_the_generated_python_result():
readiness, _ = build_readiness_payload()
page = (ROOT / "prepare.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert readiness["packet"]["synthetic"] is True
assert readiness["result"]["applicability_status"] == "applies"
assert readiness["evidence_manifest"]["applicability_status"] == ("applies")
assert readiness["result"]["overall_status"] == "known_gaps"
assert readiness["counts"] == {
"present": 14,
"missing": 3,
"not_applicable": 3,
"conflicting": 0,
"needs_staff_review": 5,
"not_evaluated": 0,
}
assert readiness["remedies"]["review"]["status"] == ("prototype_review_pending")
assert readiness["remedies"]["content_fingerprint"].startswith("sha256:")
assert readiness["ai_trace"]["runtime_model_call"] is False
assert readiness["ai_trace"]["applicant_data_sent_to_model"] is False
assert readiness["ai_trace"]["mapping_version"] == "1.1.0"
assert readiness["ai_trace"]["mapping_review_status"] == (
"prototype_review_pending"
)
assert readiness["ai_trace"]["mapping_provider"] == "unknown"
assert readiness["ai_trace"]["mapping_model"] == "unknown"
assert readiness["ai_trace"]["mapping_run_record_status"] == ("not_recorded")
assert readiness["ai_trace"]["remedy_review_status"] == ("prototype_review_pending")
assert readiness["ai_trace"]["remedy_reviewer"] is None
assert (
readiness["ai_trace"]["output_remedy_content_fingerprint"]
== readiness["remedies"]["content_fingerprint"]
)
assert readiness["source_review_due_on"] == "2027-01-25"
parcel_facts = [
fact
for fact in readiness["packet"]["facts"]
if fact["provenance"] == "synthetic_public_record_fixture"
]
assert [fact["source_field"] for fact in parcel_facts] == [
"CITY",
"LU_Descr",
]
assert {fact["source_id"] for fact in parcel_facts} == {"yolo-public-parcels-layer"}
assert '<body data-page="readiness">' in page
assert "This is a synthetic future-state" in page
assert re.search(r"certify\s+completeness", page)
assert 'id="readinessOutput"' in page
assert re.search(r"No model\s+runs in the public browser\.", page)
assert "function renderReadiness(data)" in application
assert "data.result.findings.filter" in application
assert "function evaluateReadiness" not in application
assert "function readinessSourceIsCurrent(" in application
assert "function readinessParcelEvidenceMarkup(data, current)" in application
assert "no address, APN, or live parcel was" in application
assert "Action copy is" in application
assert "withheld." in application
assert "data.readiness" in application
def test_journey_handoff_uses_public_ids_without_browser_storage():
project = (ROOT / "check.html").read_text(encoding="utf-8")
packet = (ROOT / "prepare.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert 'href="check.html?sample=adu"' in project
assert 'id="journeyEntrySummary"' in packet
assert 'id="packetCover"' in packet
assert 'id="readinessMethod"' in packet
assert "function journeyHandoffState(" in application
assert "function journeyQueryState(" in application
assert "function normalizeProgramAvailability(" in application
assert 'status: "simulation_ready"' in application
assert 'status: "program_status_review_required"' in application
assert "Preapproved ADU List: Coming soon!" in application
assert "Future-state simulation" in packet
assert (
"href: `prepare.html?journey=${encodeURIComponent(journey.journey_id)}`"
in application
)
assert "`&version=${encodeURIComponent(journey.version)}`" in application
assert '["journey", "version"]' in application
for storage_api in (
"localStorage",
"sessionStorage",
"indexedDB",
"document.cookie",
):
assert storage_api not in application
def test_rule_verification_ledger_is_exposed_without_inflating_review_claims():
page = (ROOT / "evidence.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
assert "async function normalizeRuleVerifications(payload, rules)" in application
assert "function effectiveRuleVerification(rule)" in application
assert "reviewed_citation_fingerprint" in application
assert "reviewed_rule_fingerprint" in application
assert "Verification ledger is missing or invalid" in application
assert 'id="verificationScore"' in page
assert 'id="verificationLine"' in page
assert "Machine-linked means" in page
assert "it is not named human or jurisdiction review" in page
assert "data/validation/rule-verification.json" in page
@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js unavailable")
def test_rule_verification_browser_contract_fails_closed():
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
def source_between(start: str, end: str) -> str:
start_index = application.index(start)
return application[start_index : application.index(end, start_index)]
matching = source_between("function isJsonNumber", "function uiText")
validation = source_between("function safeExternalUrl", "function validTextList")
verification = source_between("function stableJson", "const JOURNEY_KEYS")
script = "\n".join(
[
'import {readFileSync} from "node:fs";',
'import {webcrypto} from "node:crypto";',
'Object.defineProperty(globalThis, "crypto", {',
" value: webcrypto, configurable: true,",
"});",
"let RULES = [];",
"let RULE_VERIFICATIONS = null;",
"let SOURCE_STATE = null;",
"let simulating = false;",
matching,
validation,
verification,
r"""
const bundleSource = readFileSync("data/demo-data.js", "utf8");
const assignment = "globalThis.PERMIT_PATHWAYS_DEMO_DATA=";
const bundle = JSON.parse(
bundleSource.slice(bundleSource.indexOf(assignment) + assignment.length)
.trim().replace(/;$/, "")
);
const NativeDate = Date;
class FixedDate extends NativeDate {
constructor(...args) {
super(...(args.length ? args : ["2026-08-09T12:00:00Z"]));
}
static now() { return NativeDate.parse("2026-08-09T12:00:00Z"); }
static parse(value) { return NativeDate.parse(value); }
static UTC(...args) { return NativeDate.UTC(...args); }
}
globalThis.Date = FixedDate;
RULES = bundle.rules;
SOURCE_STATE = bundle.source_state;
function check(condition, message) {
if (!condition) throw new Error(message);
}
const canonical = await normalizeRuleVerifications(
structuredClone(bundle.rule_verification),
RULES,
);
check(canonical !== null, "canonical verification ledger rejected");
check(canonical.size === RULES.length, "canonical ledger coverage changed");
check(
[...canonical.values()].every(entry => entry.level === "machine_linked"),
"canonical ledger invented named review",
);
async function reject(label, mutate, rules = RULES) {
const candidate = structuredClone(bundle.rule_verification);
await mutate(candidate);
check(
await normalizeRuleVerifications(candidate, rules) === null,
`${label}: invalid ledger accepted`,
);
}
await reject("unknown entry field", candidate => {
candidate.entries[0].unexpected = true;
});
await reject("incomplete coverage", candidate => {
candidate.entries.pop();
});
await reject("duplicate coverage", candidate => {
candidate.entries[1].rule_id = candidate.entries[0].rule_id;
});
await reject("machine-linked reviewer metadata", candidate => {
candidate.entries[0].reviewer = "Named reviewer";
});
await reject("future review date", candidate => {
const entry = candidate.entries[0];
entry.level = "human_reviewed";
entry.reviewer = "Named reviewer";
entry.method = "Compared the full rule with its cited source.";
entry.reviewed_on = "2026-08-10";
entry.reviewed_citation_fingerprint = `sha256:${"0".repeat(64)}`;
entry.reviewed_rule_fingerprint = `sha256:${"0".repeat(64)}`;
});
const reviewedPayload = structuredClone(bundle.rule_verification);
const reviewedRule = RULES[0];
const reviewedEntry = reviewedPayload.entries.find(
entry => entry.rule_id === reviewedRule.rule_id,
);
reviewedEntry.level = "human_reviewed";
reviewedEntry.reviewer = "Named reviewer";
reviewedEntry.method = "Compared the full rule with its cited source.";
reviewedEntry.reviewed_on = "2026-08-09";
reviewedEntry.reviewed_citation_fingerprint = await citationFingerprint(
reviewedRule,
);
reviewedEntry.reviewed_rule_fingerprint = await ruleFingerprint(reviewedRule);
const reviewedLedger = await normalizeRuleVerifications(reviewedPayload, RULES);
check(reviewedLedger !== null, "valid named review rejected");
RULE_VERIFICATIONS = reviewedLedger;
check(
effectiveRuleVerification(reviewedRule).level === "human_reviewed",
"current named review did not take effect",
);
const changedRules = structuredClone(RULES);
changedRules[0].notes += " semantic drift";
check(
await normalizeRuleVerifications(reviewedPayload, changedRules) === null,
"full-rule drift retained a named review",
);
SOURCE_STATE = {changed_source_ids: [reviewedRule.source_dependencies[0]]};
const changedEffective = effectiveRuleVerification(reviewedRule);
check(
changedEffective.level === "machine_linked" && changedEffective.stale,
"changed source did not demote named review",
);
SOURCE_STATE = bundle.source_state;
const undatedRule = structuredClone(reviewedRule);
undatedRule.citation.verified_on = null;
const undatedEffective = effectiveRuleVerification(undatedRule);
check(
undatedEffective.level === "machine_linked" && undatedEffective.stale,
"undated source did not demote named review",
);
globalThis.Date = NativeDate;
""",
]
)
run_node_module(script)
def test_printable_journey_summary_is_semantic_gated_and_print_scoped():
page = (ROOT / "prepare.html").read_text(encoding="utf-8")
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
styles = (ROOT / "assets" / "site.css").read_text(encoding="utf-8")
assert re.search(
r'<section class="journey-evidence-summary"\s+'
r'id="journeyEvidenceSummary"[^>]*\shidden>',
page,
re.DOTALL,
)
assert 'aria-labelledby="journeyEvidenceHeading"' in page
assert 'aria-describedby="journeyEvidenceBoundary"' in page
assert '<dl class="journey-evidence-meta" id="journeyEvidenceMeta">' in page
assert '<dl id="journeyEvidenceFactsList"></dl>' in page
assert '<ol id="journeyEvidenceActionsList"></ol>' in page
assert '<ul id="journeyEvidenceQuestionsList"></ul>' in page
assert 'id="journeyEvidenceSourcesList"></dl>' in page
assert 'id="journeyEvidenceBoundaryText"></p>' in page
print_button = re.search(
r'<button class="(?P<classes>[^"]+)" '
r'id="printJourneySummary" type="button">',
page,
)
assert print_button
assert {"button", "ca-button"} <= set(print_button.group("classes").split())
assert "function renderJourneyEvidenceSummary(" in application
assert "journeyEvidenceSummary" in application
assert "journeyEvidenceActionsReview" in application
assert "journeyEvidenceSourcesList" in application
assert "window.print()" in application
assert "@media print" in styles
assert (
'body[data-page="readiness"] .readiness-main '
"> :not(#journeyEvidenceSummary)" in styles
)
assert 'body[data-page="readiness"] #journeyEvidenceSummary' in styles
assert 'body[data-page="readiness"] #printJourneySummary' in styles
assert "overflow-wrap: anywhere" in styles
def test_packet_build_explicitly_replays_canonical_evaluation_date(
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setattr(
"permit_pathways.dates.utc_today",
lambda: date(2027, 1, 26),
)
readiness, _ = build_readiness_payload()
assert readiness["packet"]["evaluated_on"] == "2026-07-30"
assert readiness["result"]["evaluated_on"] == "2026-07-30"
assert readiness["result"]["source_status"] == "current"
assert readiness["result"]["source_status_as_of"] == "2026-07-30"
assert readiness["result"]["source_review_due_on"] == "2027-01-25"
assert readiness["evidence_manifest"]["source_status_as_of"] == ("2026-07-30")
assert readiness["evidence_manifest"]["source_review_due_on"] == ("2027-01-25")
@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js unavailable")
def test_packet_renderer_honors_trust_states_and_conflicts():
readiness, _ = build_readiness_payload()
application = (ROOT / "assets" / "demo.js").read_text(encoding="utf-8")
renderer_source = application[
application.index("const READINESS_FINDING_STATUSES") : application.index(
"function fetchJson"
)
]
script = f"""
function nonBlank(value) {{
return typeof value === "string" && value.trim().length > 0;
}}
function validStableId(value) {{
return /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(value || "");
}}
function validIsoDate(value) {{
if (!/^\\d{{4}}-\\d{{2}}-\\d{{2}}$/.test(value || "")) return false;
const parsed = new Date(`${{value}}T00:00:00Z`);
return !Number.isNaN(parsed.getTime())
&& parsed.toISOString().slice(0, 10) === value;
}}
function dateIsNotFuture(value) {{
return validIsoDate(value) && value <= "2026-08-02";
}}
function validHttpsUrl(value) {{
try {{
return new URL(value).protocol === "https:";
}} catch {{
return false;
}}
}}
function safeExternalUrl(value) {{
return validHttpsUrl(value) ? value : null;
}}
function formatSourceDate(value) {{
return value;
}}
function esc(value) {{
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}}
function readinessEvidenceHref() {{
return "data/readiness/generated/woodland-preapproved-adu-evidence.json";
}}
let READINESS = null;
const NORMALIZED_READINESS_DATA = new WeakSet();
const nodes = {{
readinessOutput: {{
innerHTML: "",
attributes: {{}},
setAttribute(name, value) {{ this.attributes[name] = value; }},
}},
readinessPacketId: {{textContent: ""}},
readinessDate: {{textContent: ""}},
}};
const document = {{
getElementById(id) {{ return nodes[id] || null; }},
}};
{renderer_source}
const canonical = {json.dumps(readiness)};
function check(condition, message) {{
if (!condition) throw new Error(message);
}}
function render(payload) {{
nodes.readinessOutput.innerHTML = "";
deepFreezeGeneratedData(payload);
NORMALIZED_READINESS_DATA.add(payload);
renderReadiness(payload);
return nodes.readinessOutput.innerHTML;
}}
function setDueDate(payload, value) {{
payload.source_review_due_on = value;
payload.result.source_review_due_on = value;
payload.evidence_manifest.source_review_due_on = value;
}}
function setAllFindings(payload, status) {{
for (const finding of payload.result.findings) finding.status = status;
for (const key of Object.keys(payload.counts)) payload.counts[key] = 0;