forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1727 lines (1658 loc) · 81.5 KB
/
Copy pathindex.html
File metadata and controls
1727 lines (1658 loc) · 81.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'">
<title>Permit Bearings — cited housing-permit guidance for California jurisdictions</title>
<meta name="description" content="Prototype source-grounded ADU, JADU, and SB 9 candidate-route guidance for California jurisdictions, with visible source status and a source-drift review harness.">
<meta property="og:title" content="Permit Bearings">
<meta property="og:description" content="Find a candidate route, see its cited source, and identify what still needs confirmation. Prototype ADU, JADU, and SB 9 guidance for California jurisdictions.">
<meta property="og:type" content="website">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%F0%9F%A7%AD%3C/text%3E%3C/svg%3E">
<style>
/* Color tokens from the California Design System (open-source "cagov"
theme, @cagov/ds-base-css). Steps are chosen to meet WCAG 2.2 AAA 7:1
text contrast on these surfaces; the dark theme derives from the same
hues (CDS ships light-only). No state branding is used. */
:root {
color-scheme: light;
--primary-100: #e7eef9; --primary-300: #a3bee7; --primary-500: #5a8ad4;
--primary-700: #165ac2; --primary-900: #003688;
--accent2-100: #ffecc4; --accent2-900: #4a3918;
--surface: #fcfcfb; --page: #f9f9f7;
--ink: #0b0b0b; --ink-2: #52514e; --muted: #565550;
--grid: #e1e0d9; --border: rgba(11,11,11,0.10);
--control-border: #706f69;
--accent: var(--primary-900);
--good: #0ca30c; --warning: #fab219; --critical: #d03b3b;
--good-text: #005700; --bad-text: #8b1a1a; --warn-text: var(--accent2-900);
--good-bg: #e9f6e9; --warn-bg: var(--accent2-100); --crit-bg: #fbe7e7;
}
@media (prefers-color-scheme: dark) {
:root:where(:not([data-theme="light"])) {
color-scheme: dark;
--surface: #1a1a19; --page: #0d0d0d;
--ink: #ffffff; --ink-2: #c3c2b7; --muted: #aaa8a0;
--grid: #2c2c2a; --border: rgba(255,255,255,0.10);
--control-border: #a3a198;
--accent: var(--primary-300);
--good-text: #4ade80; --bad-text: #fca5a5; --warn-text: var(--warning);
--good-bg: #12310f; --warn-bg: #33270a; --crit-bg: #351212;
}
}
:root[data-theme="dark"] {
color-scheme: dark;
--surface: #1a1a19; --page: #0d0d0d;
--ink: #ffffff; --ink-2: #c3c2b7; --muted: #aaa8a0;
--grid: #2c2c2a; --border: rgba(255,255,255,0.10);
--control-border: #a3a198;
--accent: var(--primary-300);
--good-text: #4ade80; --bad-text: #fca5a5; --warn-text: var(--warning);
--good-bg: #12310f; --warn-bg: #33270a; --crit-bg: #351212;
}
* { box-sizing: border-box; }
body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
margin: 0; background: var(--page); color: var(--ink); line-height: 1.55; }
:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
* { scroll-behavior: auto !important; }
}
main { max-width: 46rem; margin: 0 auto; padding: 1.5rem 1rem 3rem; }
h1 { font-size: 1.45rem; margin: .4rem 0 .2rem; }
h2 { font-size: 1.15rem; margin-top: 2rem; }
.tag { color: var(--ink-2); margin-top: 0; }
nav { display: flex; flex-wrap: wrap; align-items: center; gap: .2rem .55rem;
font-size: .85rem; }
nav a, nav .nav-button { color: var(--accent); text-decoration: none;
display: inline-flex; align-items: center; min-height: 44px; padding: 0 .25rem; }
nav .nav-button { display: inline-flex; align-items: center; min-height: 44px;
padding: 0 .2rem; border: 0; background: transparent; font: inherit;
font-weight: 400; vertical-align: middle; }
.skip-link { position: absolute; left: .75rem; top: .5rem; z-index: 10;
transform: translateY(-180%); padding: .65rem .8rem; border-radius: 4px;
background: var(--surface); color: var(--accent); }
.skip-link:focus { transform: translateY(0); }
fieldset { border: 1px solid var(--grid); border-radius: 10px;
margin: 1rem 0; padding: .9rem 1rem; background: var(--surface);
min-width: 0; }
legend { font-weight: 600; font-size: .92rem; padding: 0 .35rem; }
label { display: flex; align-items: flex-start; gap: .6rem;
min-height: 44px; padding: .3rem 0; }
label > input[type="radio"], label > input[type="checkbox"] {
flex: none; width: 1.25rem; height: 1.25rem; margin-top: .15rem; }
select { font-size: 1rem; padding: .5rem; min-height: 44px; border-radius: 4px;
border: 2px solid var(--control-border); background: var(--surface); color: var(--ink);
width: 100%; max-width: 100%; }
input[type="text"], input[type="date"], input[list], textarea {
min-height: 44px; border: 2px solid var(--control-border);
border-radius: 6px; background: var(--surface); color: var(--ink); }
input[aria-invalid="true"], select[aria-invalid="true"] {
border-color: var(--bad-text); }
button { background: var(--accent); color: var(--page); border: 0;
border-radius: 4px; min-height: 44px; padding: .6rem 1.3rem;
font-size: 1rem; font-weight: 600; cursor: pointer; }
button:hover { text-decoration: underline; box-shadow: 0 0 0 2px var(--primary-500); }
button:disabled { cursor: wait; opacity: .58; text-decoration: none;
box-shadow: none; }
button.ghost { background: transparent; color: var(--accent);
border: 1px solid var(--accent); }
button.link-button { display: inline; min-height: 0; padding: 0;
border: 0; border-radius: 0; background: transparent; color: var(--accent);
font: inherit; font-weight: 400; text-decoration: underline; }
button.link-button:hover { box-shadow: none; }
.question-help { margin: -.25rem 0 .7rem; }
.choice-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr));
gap: .25rem .8rem; }
.choice-grid label { align-items: center; }
.conditional-intake[hidden] { display: none; }
.translation-scope { margin: .15rem 0 1rem; }
.card { background: var(--surface); border: 1px solid var(--border);
border-left: 5px solid var(--good); border-radius: 10px;
padding: 1rem 1.1rem; margin: 1rem 0; }
.card.unverified { border-left-color: var(--warning); }
.card h3 { margin: 0 0 .3rem; font-size: 1.02rem; }
.result-group { margin-top: 1.6rem; }
.result-group > h3 { font-size: 1.03rem; margin: 1.2rem 0 .45rem; }
.result-card { overflow-wrap: anywhere; border-left-color: var(--grid); }
.result-card.unverified { border-left-color: var(--warning); }
.result-card .result-head { display: flex; align-items: flex-start;
justify-content: space-between; gap: .65rem; flex-wrap: wrap; }
.result-card .result-title { flex: 1 1 18rem; margin: 0;
font-size: 1.02rem; }
.result-card h5 { font-size: .9rem; margin: 1rem 0 .25rem; }
.result-card ol, .result-card ul { margin-top: .3rem; padding-left: 1.35rem; }
.result-card .badge { max-width: 100%; white-space: normal; }
.result-heading:focus { outline: 3px solid var(--accent); outline-offset: 4px; }
.review-note { color: var(--ink-2); font-size: .82rem; font-weight: 650;
margin: .45rem 0 .8rem; }
.confirmation { border: 1px solid var(--grid); border-radius: 8px;
padding: 0 .75rem .2rem; margin-top: .9rem; }
.key-points { border-left: 4px solid var(--grid); padding: .05rem .75rem .15rem;
margin: .8rem 0; }
.source-basis { font-size: .88rem; margin-top: 1rem; }
.result-card details { border-top: 1px solid var(--grid); margin-top: 1rem;
padding-top: .25rem; }
.result-card summary { color: var(--accent); cursor: pointer; font-weight: 650;
min-height: 44px; display: list-item; padding: .55rem 0; }
.badge { display: inline-block; font-size: .78rem; font-weight: 600;
padding: .12rem .55rem; border-radius: 999px; white-space: nowrap; }
.badge.ok { background: var(--good-bg); color: var(--good-text); }
.badge.info { background: var(--surface); color: var(--ink-2);
border: 1px solid var(--grid); }
.badge.warn { background: var(--warn-bg); color: var(--warn-text); }
.badge.bad { background: var(--crit-bg); color: var(--bad-text); }
blockquote { font-size: .86rem; color: var(--ink-2);
border-left: 3px solid var(--grid); margin: .6rem 0; padding-left: .8rem; }
.small { font-size: .85rem; color: var(--ink-2); }
.mutedtxt { color: var(--muted); }
a { color: var(--accent); }
.notice { background: var(--surface); border: 1px solid var(--grid);
border-radius: 10px; padding: .8rem 1rem; font-size: .9rem; }
.hero { font-size: 2.4rem; font-weight: 700; margin: 0; }
.meter { display: flex; height: 14px; border-radius: 7px; overflow: hidden;
background: var(--grid); margin: .5rem 0 .3rem; }
.meter > div { height: 100%; }
.meter > div + div { border-left: 2px solid var(--ink); }
.meter .m-good { background: var(--good); }
.meter .m-bad { background: var(--critical); }
.meter .m-warn { background: var(--warning); }
table { border-collapse: collapse; width: 100%; background: var(--surface);
border-radius: 10px; font-size: .88rem; }
.table-scroll { max-width: 100%; overflow-x: auto; }
.table-scroll table { min-width: 36rem; }
td, th { border-bottom: 1px solid var(--grid); padding: .45rem .6rem;
text-align: left; vertical-align: top; }
th { color: var(--ink-2); font-weight: 600; }
tr:last-child td { border-bottom: 0; }
.status-ico { font-weight: 700; margin-right: .25rem; }
footer { margin-top: 2.5rem; font-size: .8rem; color: var(--muted); }
.hidden { display: none; }
.visually-hidden { position: absolute !important; width: 1px; height: 1px;
padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0; }
@media (max-width: 30rem) {
.choice-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<a class="skip-link" href="#mainContent">Skip to main content</a>
<main id="mainContent">
<nav aria-label="Primary">
<a href="#screen">Find a pathway</a>
<a href="#conformance">Scan an ordinance</a>
<a href="#clocks">Review clocks</a>
<a href="#trust">Trust dashboard</a>
<a href="#sources">Source monitoring</a>
<button class="nav-button" id="langToggle" type="button">Español: formulario y resultados</button>
</nav>
<h1 id="t-title">Permit Bearings</h1>
<p class="tag" id="t-tagline">Find a candidate route. See the sources behind it. Take open questions to staff.</p>
<p class="small translation-scope" id="translationScope">The language choice applies to the applicant form and pathway results. The ordinance, clock, and trust tools below remain in English.</p>
<section id="screen" aria-labelledby="screenHeading">
<h2 id="screenHeading">Find a possible permit path</h2>
<form id="intake" novalidate>
<fieldset>
<legend id="t-juris">Where is the property?</legend>
<input id="jurisInput" name="jurisdiction_name" list="jurisList"
autocomplete="off" aria-labelledby="t-juris"
aria-describedby="jurisHelp jurisStatus"
required
placeholder="Type any California city or county…"
style="width:100%;font-size:1rem;padding:.45rem">
<datalist id="jurisList"></datalist>
<p class="small" id="jurisHelp">Choose a suggestion, or enter the exact city or county name.</p>
<p class="small" id="jurisStatus" role="status" aria-live="polite"
aria-atomic="true"></p>
</fieldset>
<fieldset>
<legend id="t-project">What are you proposing?</legend>
<div id="typeRadios"></div>
</fieldset>
<div id="projectQuestions" class="conditional-intake" hidden></div>
<button type="submit" id="t-submit" disabled>Check candidate pathways</button>
</form>
<p id="resultStatus" class="visually-hidden" role="status"
aria-live="polite" aria-atomic="true"></p>
<div id="results"></div>
</section>
<section id="conformance">
<h2>Scan an ordinance for potential state-law issues</h2>
<p class="small">Paste local ADU/SB 9 ordinance or handout text. It is screened
against the failure modes HCD documents in its enforcement letters — stale
SB 477 citations, height caps below state allowances, unit undercounts,
subjective standards, and more. <b>Text never leaves your browser.</b>
Presence-based screening for staff/counsel review — not a certification of
compliance, and silence is not a clean bill of health.</p>
<p class="small">Named regression fixture: six provisions quoted in HCD's
June 2025 Santa Clara County findings letter reproduce the six expected
review flags. This is not a statewide accuracy evaluation.
<button class="link-button" type="button" id="loadSample">Load two of those provisions as a sample</button>.</p>
<textarea id="ordText" rows="8" aria-label="Ordinance text to scan"
style="width:100%;font-size:.9rem;
padding:.6rem" placeholder="Paste ordinance text here…"></textarea>
<p><button id="scanBtn" disabled>Scan</button></p>
<p id="scanStatus" class="visually-hidden" role="status"
aria-live="polite" aria-atomic="true"></p>
<div id="scanResults"></div>
</section>
<section id="clocks">
<h2>ADU review-clock illustration</h2>
<p class="small" id="clockHelp">This tool illustrates current ADU clocks
only. Enter the date the agency received the ADU application. An exact
15-business-day date requires the agency's own closure calendar, which this
prototype does not have. The separate 60-day illustration is shown only
when you confirm both conditions below.</p>
<p><input type="date" id="recvDate"
aria-label="Date the ADU application was received" aria-describedby="clockHelp"
style="font-size:1rem;padding:.35rem;
"> <button class="ghost" id="clockBtn">Show clock information</button></p>
<fieldset>
<legend>Conditions for the ADU 60-day illustration</legend>
<label><input type="checkbox" id="clockComplete">
The agency confirmed this ADU application was complete on the receipt date.</label>
<label><input type="checkbox" id="clockExisting">
For this ADU application, a single-family or multifamily dwelling already
existed on the lot.</label>
</fieldset>
<p id="clockStatus" class="visually-hidden" role="status"
aria-live="polite" aria-atomic="true"></p>
<div id="clockResults"></div>
</section>
<section id="trust">
<h2 id="t-dash">Trust dashboard</h2>
<p class="small" id="t-dashsub">What a jurisdiction sees before deciding to rely on this guidance.</p>
<p class="hero"><span id="pct">–</span><span style="font-size:1.2rem">%</span></p>
<p class="small" id="t-pctlabel">of rule records have dated source evidence within the 180-day review window</p>
<div class="meter" id="meter" role="img" aria-label="share of rule records inside the review window, stale, or without a dated source record"></div>
<p class="small" id="meterLegend"></p>
<p class="small"><span id="goldenLine"></span></p>
<p class="small mutedtxt" id="covLine"></p>
<p>
<button class="ghost" id="simBtn" disabled>Rehearse a legislative amendment to Gov. Code § 66321</button>
<button class="ghost hidden" id="resetBtn" disabled>Reset</button>
</p>
<div class="notice hidden" id="simNote">
Simulating: Gov. Code § 66321 (ADU size, setback, and height standards) has been
amended. Every rule linked to that source by its exact stable dependency ID
is <b>stale</b> until staff re-check it against the new text. A durable,
persisted review queue remains planned.
</div>
<p id="simulationStatus" class="visually-hidden" aria-live="polite"></p>
<div class="table-scroll" role="region" aria-label="Rule source status table"
tabindex="0">
<table id="ruleTable" aria-describedby="t-dash"><thead>
<tr><th>Rule</th><th>Scope</th><th>Status</th></tr>
</thead><tbody></tbody></table>
</div>
</section>
<section id="sources">
<h2 id="t-sources">Source monitoring</h2>
<p class="small" id="t-sourcesub">Selected official state and local source
hashes are recorded and re-fetched so revisions or fetch failures become
visible. Rules link to sources through exact stable dependency IDs. Sources
that cannot be watched are labeled reference only; a durable, persisted
review queue remains planned.</p>
<div class="table-scroll" role="region" aria-label="Source monitoring table"
tabindex="0">
<table id="sourceTable"><thead>
<tr><th>Source</th><th>Monitoring</th><th>Recorded</th><th>SHA-256</th></tr>
</thead><tbody></tbody></table>
</div>
</section>
<footer>
<p id="t-disclaimer">Decision support only — not legal advice and not a substitute for your
jurisdiction's review. Prototype for the California AI Permitting Innovation
Showcase (2026).</p>
</footer>
</main>
<script src="data/demo-data.js"></script>
<script>
const STRINGS = {
en: {
tagline: "Find a candidate route. See the sources behind it. Take open questions to staff.",
screenHeading: "Find a possible permit path",
translationScope: "The language choice applies to the applicant form and pathway results. The ordinance, clock, and trust tools below remain in English.",
juris: "Where is the property?",
jurisPlaceholder: "Type any California city or county…",
jurisHelp: "Choose a suggestion, or enter the exact city or county name.",
statusLocal: "A jurisdiction-scoped metadata record exists; inspect its source status below.",
statusBaseline: "The statewide candidate-rule set is available. No local requirements layer is encoded",
statusUnknown: "Choose a recognized California city or county; screening will not run until it resolves.",
jurisRequired: "Select a recognized California city or county before screening.",
localCoverage: (count, total) => `${count} of ${total} have a jurisdiction-scoped record.`,
hcdHistory: "Known HCD accountability letter",
localMetadata: "local metadata",
scanned: "screened",
scanRecord: (date, count) => `Ordinance screened ${date}: ${count} provision${count === 1 ? "" : "s"} flagged for review`,
viewScan: "view scan findings (JSON)",
letterCount: count => `${count} letter${count === 1 ? "" : "s"} on record.`,
moreLetters: count => `and ${count} more`,
project: "What are you proposing?",
types: [["adu","Accessory dwelling unit (backyard cottage, garage conversion)"],
["jadu","Junior ADU (small unit inside my house)"],
["two_unit","Two homes on my single-family lot (SB 9)"],
["lot_split","Split my lot into two parcels (SB 9)"]],
tri: [["yes","Yes"],["no","No"],["unknown","I'm not sure"]],
primaryQuestion: "What dwelling exists on the lot now—or is proposed?",
primaryHelp: "Choose what exists now separately from what is only proposed. Some review clocks depend on that difference.",
questionIntro: "Choose “I'm not sure” when you do not know. The prototype will send uncertain material facts to staff instead of assuming they favor a path.",
primaryOptions: [
["existing_single_family","An existing single-family home"],
["existing_multifamily","An existing multifamily building"],
["proposed_single_family","A single-family home is proposed; none exists now"],
["proposed_multifamily","A multifamily building is proposed; none exists now"],
["none","No primary dwelling exists or is proposed"],
["unknown","I'm not sure"],
],
aduFormQuestion: "What kind of ADU work are you planning?",
aduFormOptions: [
["new_detached","Build a new detached ADU"],
["new_attached","Build a new attached ADU"],
["conversion","Convert space in an existing structure"],
["same_footprint_rebuild","Replace a structure in the same location and dimensions"],
["unknown","I'm not sure"],
],
unpermittedQuestions: {
adu: "Are you trying to legalize an ADU built without permits before January 1, 2020?",
jadu: "Are you trying to legalize a junior ADU built without permits before January 1, 2020?",
},
questions: {
in_urbanized_area: "Is the property inside an incorporated city or another SB 9-qualifying urban area?",
sf_zone: "Is the property zoned for single-family residential use?",
demolishes_protected_housing: "Would the project demolish or alter rent-restricted, price-controlled, or deed-restricted affordable housing?",
tenant_occupied_last_3_years: "Has a tenant lived in housing the project would demolish or alter during the last three years?",
ellis_withdrawal_last_15_years: "Was housing on the property withdrawn from rental use under the Ellis Act during the last 15 years?",
two_unit_contributing_historic_location: "Would the two-home project be located in a contributing structure in a state-listed historic district, or in a historic property or district protected by a city or county ordinance?",
two_unit_individually_listed_historic_property: "Is the parcel individually listed in the State Historic Resources Inventory, or is the property individually designated or listed as a city or county landmark?",
lot_split_on_historic_landmark_site: "Is the parcel within a historical landmark property in the State Historic Resources Inventory, or on a site designated or listed as a city or county landmark?",
lot_split_alters_historic_district_resource: "Would the lot split require demolition or alteration of a contributing structure or an existing exterior structural wall in a historic district listed by California or designated by a city or county?",
on_protected_site: "Does the property have a wetland, hazardous-land, conservation, habitat, or other protected-site condition named in SB 9?",
parcel_created_by_sb9_split: "Was this parcel already created by an SB 9 lot split?",
adjacent_sb9_split_same_actor: "Has the same owner—or someone working with that owner—used SB 9 to split an adjacent parcel?",
proposed_lot_ratio_compliant: "Would each proposed parcel contain at least 40% of the original lot area?",
proposed_lot_size_compliant: "Would both new lots be at least 1,200 square feet, or meet a smaller minimum verified in a current local ordinance?",
},
submit: "Check candidate pathways",
results: "Possible permit paths and rules",
resultIntro: "We compared your answers with the limited set of rules in this prototype. We did not verify the property facts, decide eligibility, or approve the project.",
resultCount: count => count === 1 ? "1 result found." : `${count} results found.`,
none: "The included rules do not identify a possible path from these answers. This does not mean the project is impossible. Ask the local planning counter to review it.",
supportingOnly: "Supporting local information is shown below, but it is not a candidate permit path.",
unknownHeading: "Staff review is needed before showing a possible path",
unknownIntro: "You chose “I'm not sure” for a fact that can change the result. Confirm these items with the local planning counter:",
explanationBanner: "About these explanations: the text shown is an AI-assisted draft and has not been reviewed by a person. The cited source stays separate in each card.",
dataLoadError: "The demo data did not load. Keep data/demo-data.js beside index.html, or serve the repository over HTTP. Pathway and ordinance controls stay disabled until the data is available.",
groups: {
route: "Possible permit paths",
standard: "Rules that may apply",
local_process: "Local process information",
other: "Other matching rules",
},
means: "What this result means",
next: "What you can do next",
confirm: "Questions to ask staff",
docs: "Typical document hints",
source: "Source",
evidence: "Why we're saying this",
evidenceUnavailable: "No supporting excerpt is recorded for this non-current source record.",
copyRecord: "Explanation details",
aiDraft: "Draft explanation · made with AI · not reviewed by a person",
translationDraft: "Spanish draft · made with AI · not reviewed for accuracy",
unavailable: "This explanation is not available. The matching rule and source are still shown.",
withheldUnverified: "We are not showing next steps because this source has no date on file. Ask staff to confirm the source before you rely on it.",
withheldStale: "We are not showing next steps because the source needs a new check. Confirm it before you rely on it.",
nextScope: "These are starting points, not a complete checklist. Ask local staff what your project needs.",
englishOnly: "English explanation shown because no valid Spanish draft is available.",
simulationApplied: count => `${count} matching guidance record${count === 1 ? " was" : "s were"} marked stale and withheld by the amendment rehearsal.`,
simulationReset: count => `The amendment rehearsal was reset. ${count} matching guidance record${count === 1 ? " is" : "s are"} available again.`,
verifiedOn: "source date on file", stale: "SOURCE NEEDS A NEW CHECK",
unverified: "NO SOURCE DATE ON FILE",
langBtn: "Español: formulario y resultados",
},
es: {
tagline: "Encuentre una posible ruta. Vea las fuentes que la respaldan. Consulte las preguntas pendientes con el personal de la agencia.",
screenHeading: "Encuentre una posible vía de permiso",
translationScope: "El idioma elegido se aplica al formulario y a los resultados para solicitantes. Las herramientas de ordenanzas, plazos y confianza que aparecen abajo permanecen en inglés.",
juris: "¿Dónde está la propiedad?",
jurisPlaceholder: "Escriba cualquier ciudad o condado de California…",
jurisHelp: "Elija una sugerencia o escriba el nombre exacto de la ciudad o el condado.",
statusLocal: "Existe un registro de metadatos de la jurisdicción; revise el estado de sus fuentes abajo.",
statusBaseline: "El conjunto estatal de reglas posibles está disponible. Aún no se codifican los requisitos locales",
statusUnknown: "Elija una ciudad o condado reconocido de California; no se ejecutará la evaluación hasta resolverlo.",
jurisRequired: "Seleccione una ciudad o condado reconocido de California antes de continuar.",
localCoverage: (count, total) => `${count} de ${total} tienen un registro específico de la jurisdicción.`,
hcdHistory: "Carta de responsabilidad de HCD conocida",
localMetadata: "metadatos locales",
scanned: "evaluada",
scanRecord: (date, count) => `Ordenanza evaluada el ${date}: ${count} disposición${count === 1 ? "" : "es"} señalada${count === 1 ? "" : "s"} para revisión`,
viewScan: "ver los resultados de la evaluación (JSON)",
letterCount: count => `${count} carta${count === 1 ? "" : "s"} registrada${count === 1 ? "" : "s"}.`,
moreLetters: count => `y ${count} más`,
project: "¿Qué propone construir?",
types: [["adu","Vivienda accesoria (casita de patio, conversión de garaje)"],
["jadu","ADU júnior (unidad pequeña dentro de mi casa)"],
["two_unit","Dos viviendas en mi lote unifamiliar (SB 9)"],
["lot_split","Dividir mi lote en dos parcelas (SB 9)"]],
tri: [["yes","Sí"],["no","No"],["unknown","No lo sé"]],
primaryQuestion: "¿Qué vivienda existe ahora en el lote o está propuesta?",
primaryHelp: "Distinga lo que ya existe de lo que solo está propuesto. Algunos plazos dependen de esa diferencia.",
questionIntro: "Elija “No lo sé” si no conoce la respuesta. El prototipo enviará los datos materiales inciertos al personal en lugar de suponer que favorecen una vía.",
primaryOptions: [
["existing_single_family","Ya existe una vivienda unifamiliar"],
["existing_multifamily","Ya existe un edificio multifamiliar"],
["proposed_single_family","Se propone una vivienda unifamiliar; aún no existe"],
["proposed_multifamily","Se propone un edificio multifamiliar; aún no existe"],
["none","No existe ni se propone una vivienda principal"],
["unknown","No lo sé"],
],
aduFormQuestion: "¿Qué tipo de trabajo de ADU propone?",
aduFormOptions: [
["new_detached","Construir una ADU nueva y separada"],
["new_attached","Construir una ADU nueva y adosada"],
["conversion","Convertir espacio dentro de una estructura existente"],
["same_footprint_rebuild","Reemplazar una estructura en el mismo lugar y con las mismas dimensiones"],
["unknown","No lo sé"],
],
unpermittedQuestions: {
adu: "¿Quiere legalizar una ADU construida sin permisos antes del 1 de enero de 2020?",
jadu: "¿Quiere legalizar una ADU júnior construida sin permisos antes del 1 de enero de 2020?",
},
questions: {
in_urbanized_area: "¿Está la propiedad dentro de una ciudad incorporada u otra área urbana que califique para la SB 9?",
sf_zone: "¿Tiene la propiedad zonificación residencial unifamiliar?",
demolishes_protected_housing: "¿El proyecto demolería o alteraría vivienda con renta o precio controlado, o vivienda asequible restringida por escritura?",
tenant_occupied_last_3_years: "¿Un inquilino vivió durante los últimos tres años en una vivienda que el proyecto demolería o alteraría?",
ellis_withdrawal_last_15_years: "¿Se retiró del mercado de alquiler alguna vivienda de la propiedad conforme a la Ley Ellis durante los últimos 15 años?",
two_unit_contributing_historic_location: "¿Estaría el proyecto de dos viviendas en una estructura que contribuye al valor de un distrito histórico incluido por el estado, o en una propiedad o distrito histórico protegido por una ordenanza local?",
two_unit_individually_listed_historic_property: "¿Está la parcela incluida individualmente en el inventario estatal de recursos históricos, o está la propiedad designada individualmente como monumento histórico por la ciudad o el condado?",
lot_split_on_historic_landmark_site: "¿Está la parcela dentro de una propiedad incluida en el inventario estatal de recursos históricos, o en un sitio designado como monumento histórico por la ciudad o el condado?",
lot_split_alters_historic_district_resource: "¿La división del lote exigiría demoler o alterar una estructura que contribuye a un distrito histórico, o un muro estructural exterior existente, dentro de un distrito histórico incluido por el estado o designado localmente?",
on_protected_site: "¿Tiene la propiedad humedales, suelo peligroso, terreno de conservación, hábitat u otra condición de sitio protegido indicada en la SB 9?",
parcel_created_by_sb9_split: "¿Esta parcela ya fue creada mediante una división de lote SB 9?",
adjacent_sb9_split_same_actor: "¿El mismo propietario, o alguien que actúe con ese propietario, usó la SB 9 para dividir una parcela adyacente?",
proposed_lot_ratio_compliant: "¿Cada parcela propuesta tendría al menos el 40% del área del lote original?",
proposed_lot_size_compliant: "¿Tendrían ambos lotes nuevos al menos 1,200 pies cuadrados, o cumplirían un mínimo menor verificado en una ordenanza local vigente?",
},
submit: "Revisar posibles vías",
results: "Posibles vías de permiso y reglas",
resultIntro: "Comparamos sus respuestas con el conjunto limitado de reglas de este prototipo. No verificamos los datos de la propiedad, decidimos la elegibilidad ni aprobamos el proyecto.",
resultCount: count => count === 1 ? "Se encontró 1 resultado." : `Se encontraron ${count} resultados.`,
none: "Las reglas incluidas no identifican una posible vía con estas respuestas. Esto no significa que el proyecto sea imposible. Pida una revisión en el departamento local de planificación.",
supportingOnly: "Abajo se muestra información local de apoyo, pero no es una posible vía de permiso.",
unknownHeading: "Se necesita revisión del personal antes de mostrar una posible vía",
unknownIntro: "Eligió “No lo sé” para un dato que puede cambiar el resultado. Confirme estos puntos con el departamento local de planificación:",
explanationBanner: "Sobre estas explicaciones: el texto mostrado es un borrador creado con ayuda de IA y no ha sido revisado por una persona. El texto en español es una traducción automática sin revisión de exactitud. La fuente citada se mantiene separada en cada tarjeta.",
dataLoadError: "No se pudieron cargar los datos de la demostración. Mantenga data/demo-data.js junto a index.html o sirva el repositorio por HTTP. Los controles de vías y ordenanzas permanecerán desactivados hasta que los datos estén disponibles.",
groups: {
route: "Posibles vías de permiso",
standard: "Reglas que podrían aplicarse",
local_process: "Información del proceso local",
other: "Otras reglas coincidentes",
},
means: "Qué significa este resultado",
next: "Qué puede hacer ahora",
confirm: "Preguntas para el personal",
docs: "Sugerencias de documentos típicos",
source: "Fuente",
evidence: "Por qué decimos esto",
evidenceUnavailable: "No hay un extracto de respaldo registrado para este registro de fuente no vigente.",
copyRecord: "Detalles de la explicación",
aiDraft: "Borrador de explicación · creado con IA · no revisado por una persona",
translationDraft: "Borrador en español · creado con IA · no revisado para comprobar su exactitud",
unavailable: "Esta explicación no está disponible. Aun así se muestran la regla coincidente y la fuente.",
withheldUnverified: "No mostramos los próximos pasos porque esta fuente no tiene una fecha registrada. Pida al personal que confirme la fuente antes de usarla.",
withheldStale: "No mostramos los próximos pasos porque la fuente necesita una nueva comprobación. Confírmela antes de usarla.",
nextScope: "Estos son puntos de partida, no una lista completa. Pregunte al personal local qué necesita su proyecto.",
englishOnly: "Se muestra la explicación en inglés porque no hay un borrador válido en español.",
simulationApplied: count => `El ensayo de la enmienda marcó como desactualizado${count === 1 ? "" : "s"} y ocultó ${count} registro${count === 1 ? "" : "s"} coincidente${count === 1 ? "" : "s"} de orientación.`,
simulationReset: count => `Se restableció el ensayo de la enmienda. ${count} registro${count === 1 ? "" : "s"} coincidente${count === 1 ? " está" : " están"} disponible${count === 1 ? "" : "s"} de nuevo.`,
verifiedOn: "fecha de la fuente registrada", stale: "LA FUENTE NECESITA UNA NUEVA COMPROBACIÓN",
unverified: "SIN FECHA DE LA FUENTE",
langBtn: "English: form and results",
},
};
let lang = "en";
let RULES = [], GOLDEN = [], SOURCES = {}, CHECKS = [], JURIS = [], LETTERS = {}, SCANS = {};
let EXPLANATIONS = new Map();
let jurisByName = new Map();
let intakeDraft = {};
const SAMPLE_ORDINANCE =
"Accessory dwelling units shall not exceed sixteen (16) feet in height if " +
"the dwelling unit does not comply with the setback limitations for a " +
"single-family residence, prescribed by the applicable zoning district. " +
"Detached accessory dwelling units exceeding sixteen (16) feet in height " +
"shall incorporate a hip, gable, or other similar styled roof design.";
function isJsonNumber(value) {
return typeof value === "number" && Number.isFinite(value);
}
function isRuleInteger(value) {
return typeof value === "number" && Number.isSafeInteger(value);
}
function isJsonScalar(value) {
return typeof value === "string"
|| typeof value === "boolean"
|| isRuleInteger(value);
}
const RULE_KEYS = [
"rule_id", "pathway", "route_class", "jurisdiction_scope", "criteria",
"citation", "source_dependencies", "display_group", "required_documents",
"notes",
];
const CITATION_KEYS = [
"source", "url", "excerpt", "excerpt_sha256", "verified_on",
];
const CITATION_REQUIRED_KEYS = ["source", "url", "excerpt", "verified_on"];
const CRITERION_KEYS = ["field", "op", "value"];
function hasExactKeys(value, allowed, required) {
if (!value || typeof value !== "object" || Array.isArray(value))
return false;
const keys = Object.keys(value);
return keys.every(key => allowed.includes(key))
&& required.every(key =>
Object.prototype.hasOwnProperty.call(value, key)
);
}
function sameScalar(left, right) {
if (isJsonNumber(left) && isJsonNumber(right)) return left === right;
return typeof left === typeof right && left === right;
}
const OPS = {
eq: (actual, expected) =>
actual != null && sameScalar(actual, expected),
lte: (actual, expected) =>
isJsonNumber(actual) && isJsonNumber(expected) && actual <= expected,
gte: (actual, expected) =>
isJsonNumber(actual) && isJsonNumber(expected) && actual >= expected,
in: (actual, expected) =>
actual != null && Array.isArray(expected)
&& expected.some(candidate => sameScalar(actual, candidate)),
};
const MAX_AGE_DAYS = 180;
function validCriterion(criterion) {
if (!hasExactKeys(criterion, CRITERION_KEYS, CRITERION_KEYS)
|| !nonBlank(criterion.field)
|| !/^[a-z][a-z0-9_]*$/.test(criterion.field)
|| !Object.prototype.hasOwnProperty.call(OPS, criterion.op)) return false;
const expected = criterion.value;
if (criterion.op === "eq")
return isJsonScalar(expected)
&& !(typeof expected === "string" && !expected.trim());
if (criterion.op === "in") {
if (!Array.isArray(expected) || !expected.length
|| !expected.every(isJsonScalar)
|| expected.some(value =>
typeof value === "string" && !value.trim()
)) return false;
const firstType = typeof expected[0];
return expected.every(value => typeof value === firstType)
&& expected.every((value, index) =>
!expected.slice(0, index).some(prior =>
sameScalar(value, prior)
)
);
}
return isRuleInteger(expected);
}
function matches(rule, intake) {
return Array.isArray(rule.criteria)
&& rule.criteria.length > 0
&& rule.criteria.every(criterion =>
validCriterion(criterion)
&& OPS[criterion.op](intake[criterion.field], criterion.value)
);
}
function screen(intake) {
return RULES.filter(r =>
(r.jurisdiction_scope === "statewide" || r.jurisdiction_scope === intake.jurisdiction)
&& matches(r, intake));
}
function ruleStatus(rule, changedSourceIds) {
const c = rule.citation;
const dependencies = Array.isArray(rule.source_dependencies)
? rule.source_dependencies : [];
if (changedSourceIds.some(sourceId => dependencies.includes(sourceId)))
return "stale";
if (!validIsoDate(c.verified_on)) return "unverified";
const now = new Date();
const todayUtc = Date.UTC(
now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()
);
const verifiedUtc = Date.parse(`${c.verified_on}T00:00:00Z`);
const age = Math.floor((todayUtc - verifiedUtc) / 86400000);
return age < 0 || age > MAX_AGE_DAYS ? "stale" : "verified";
}
function esc(s) { const d = document.createElement("span"); d.textContent = s ?? ""; return d.innerHTML; }
function safeExternalUrl(value) {
try {
const parsed = new URL(String(value));
return ["https:", "http:"].includes(parsed.protocol) ? parsed.href : null;
} catch {
return null;
}
}
function safeLocalJsonPath(slug) {
return /^[a-z0-9-]+$/.test(slug || "")
? `data/conformance/results/${slug}.json` : null;
}
function nonBlank(value) {
return typeof value === "string" && value.trim().length > 0;
}
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) {
if (!validIsoDate(value)) return false;
const now = new Date();
const todayUtc = Date.UTC(
now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()
);
return Date.parse(`${value}T00:00:00Z`) <= todayUtc;
}
function validStableId(value) {
return typeof value === "string"
&& /^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(value);
}
function validHttpsUrl(value) {
try {
const parsed = new URL(String(value));
return parsed.protocol === "https:"
&& Boolean(parsed.hostname)
&& !parsed.username
&& !parsed.password;
} catch {
return false;
}
}
function validRuleRecord(rule) {
if (!hasExactKeys(rule, RULE_KEYS, RULE_KEYS)
|| !validStableId(rule.rule_id)
|| !nonBlank(rule.pathway)
|| !["ministerial", "discretionary", "mixed"].includes(rule.route_class)
|| !validStableId(rule.jurisdiction_scope)
|| !["route", "standard", "local_process"].includes(rule.display_group)
|| !Array.isArray(rule.criteria) || !rule.criteria.length
|| !rule.criteria.every(validCriterion)
|| !Array.isArray(rule.source_dependencies)
|| !rule.source_dependencies.length
|| !rule.source_dependencies.every(validStableId)
|| new Set(rule.source_dependencies).size
!== rule.source_dependencies.length
|| !Array.isArray(rule.required_documents)
|| !rule.required_documents.every(nonBlank)
|| new Set(rule.required_documents).size
!== rule.required_documents.length
|| !nonBlank(rule.notes)) return false;
const citation = rule.citation;
return hasExactKeys(
citation, CITATION_KEYS, CITATION_REQUIRED_KEYS
)
&& nonBlank(citation.source)
&& nonBlank(citation.url)
&& validHttpsUrl(citation.url)
&& (citation.excerpt == null || nonBlank(citation.excerpt))
&& (
citation.excerpt_sha256 == null
|| /^(?:sha256:)?[0-9a-f]{64}$/.test(citation.excerpt_sha256)
)
&& (
citation.verified_on == null
|| dateIsNotFuture(citation.verified_on)
)
&& !(citation.verified_on && !citation.excerpt);
}
function normalizeRules(records) {
if (!Array.isArray(records) || !records.length
|| !records.every(validRuleRecord)) {
throw new Error("rule data failed validation");
}
const ids = records.map(rule => rule.rule_id);
if (new Set(ids).size !== ids.length)
throw new Error("rule data contains duplicate IDs");
return records;
}
function validTextList(value) {
return Array.isArray(value) && value.length > 0 && value.every(nonBlank);
}
function validHighlights(value) {
return value == null || (
typeof value === "object"
&& nonBlank(value.title)
&& Array.isArray(value.items)
&& value.items.length > 0
&& value.items.every(item => item && typeof item === "object"
&& nonBlank(item.label) && nonBlank(item.text))
);
}
async function validReview(review, version, updatedOn, englishCopy) {
if (!review || typeof review !== "object") return false;
const allowed = ["prototype_review_pending", "human_reviewed",
"jurisdiction_approved"];
if (!allowed.includes(review.status)) return false;
const metadata = [review.reviewer, review.reviewed_on, review.method,
review.reviewed_version, review.content_fingerprint];
if (review.status === "prototype_review_pending")
return metadata.every(value => value == null);
if (!(metadata.every(nonBlank)
&& dateIsNotFuture(review.reviewed_on)
&& review.reviewed_on >= updatedOn
&& review.reviewed_version === version)) return false;
try {
const expected = await localizedContentFingerprint(
version, "en", englishCopy
);
return nonBlank(expected) && review.content_fingerprint === expected;
} catch {
return false;
}
}
function validLocalizedCopy(copy, language) {
if (!copy || typeof copy !== "object"
|| !nonBlank(copy.title)
|| !nonBlank(copy.summary)
|| !validTextList(copy.next_steps)
|| !validTextList(copy.confirm_with_staff)
|| !validHighlights(copy.highlights)) return false;
if (language !== "es") return true;
const allowed = ["machine_draft", "human_reviewed", "jurisdiction_approved"];
if (!allowed.includes(copy.translation_status)) return false;
const metadata = [copy.reviewer, copy.reviewed_on, copy.method,
copy.reviewed_version, copy.content_fingerprint];
if (copy.translation_status === "machine_draft")
return metadata.every(value => value == null);
return metadata.every(nonBlank);
}
function stableJson(value) {
if (Array.isArray(value))
return `[${value.map(stableJson).join(",")}]`;
if (value && typeof value === "object")
return `{${Object.keys(value).sort().map(key =>
`${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
return JSON.stringify(value);
}
async function sha256Fingerprint(value) {
if (!globalThis.crypto || !globalThis.crypto.subtle) return null;
const normalized = stableJson(value);
const digest = await globalThis.crypto.subtle.digest(
"SHA-256", new TextEncoder().encode(normalized)
);
return "sha256:" + Array.from(new Uint8Array(digest))
.map(byte => byte.toString(16).padStart(2, "0")).join("");
}
async function localizedContentFingerprint(version, language, copy) {
return sha256Fingerprint({
confirm_with_staff: copy.confirm_with_staff,
highlights: copy.highlights ?? null,
language,
next_steps: copy.next_steps,
summary: copy.summary,
title: copy.title,
version,
});
}
async function validTranslationReview(copy, version, updatedOn) {
if (!validLocalizedCopy(copy, "es")) return false;
if (copy.translation_status === "machine_draft") return true;
if (!dateIsNotFuture(copy.reviewed_on)
|| copy.reviewed_on < updatedOn
|| copy.reviewed_version !== version) return false;
try {
const expected = await localizedContentFingerprint(version, "es", copy);
return nonBlank(expected) && copy.content_fingerprint === expected;
} catch {
return false;
}
}
function normalizedCitation(rule) {
const citation = rule.citation || {};
return {
excerpt: citation.excerpt ?? null,
excerpt_sha256: citation.excerpt_sha256 ?? null,
source: citation.source,
url: citation.url,
verified_on: citation.verified_on ?? null,
};
}
async function citationFingerprint(rule) {
return sha256Fingerprint(normalizedCitation(rule));
}
async function ruleFingerprint(rule) {
return sha256Fingerprint({
citation: normalizedCitation(rule),
criteria: rule.criteria,
display_group: rule.display_group,
jurisdiction_scope: rule.jurisdiction_scope,
notes: rule.notes,
pathway: rule.pathway,
required_documents: rule.required_documents,
route_class: rule.route_class,
rule_id: rule.rule_id,
source_dependencies: rule.source_dependencies,
});
}
async function normalizeExplanations(payload, rules) {
if (!payload || payload.schema_version !== 1
|| !Array.isArray(payload.entries)) return new Map();
if (!globalThis.crypto || !globalThis.crypto.subtle) return new Map();
const rulesById = new Map(rules.map(rule => [rule.rule_id, rule]));
if (rulesById.size !== rules.length) return new Map();
const normalized = new Map();
const seen = new Set();
const blocked = new Set();
for (const record of payload.entries) {
const ruleId = record && record.source_rule_id;
if (!nonBlank(ruleId)) continue;
if (seen.has(ruleId)) {
normalized.delete(ruleId);
blocked.add(ruleId);
continue;
}
seen.add(ruleId);
if (blocked.has(ruleId)) continue;
const rule = rulesById.get(ruleId);
const version = record.version;
const updatedOn = record.updated_on;
if (!rule || !/^\d+\.\d+\.\d+$/.test(version || "")
|| !dateIsNotFuture(updatedOn)
|| record.display_group !== rule.display_group
|| record.drafted_by !== "ai_assisted"
|| (record.source_verified_on ?? null)
!== (rule.citation.verified_on ?? null)
|| (record.source_verified_on
&& !dateIsNotFuture(record.source_verified_on))
|| (record.source_verified_on
&& updatedOn < record.source_verified_on)
|| !validLocalizedCopy(record.en, "en")
|| !(await validReview(
record.review, version, updatedOn, record.en
))) continue;
let expectedFingerprint;
let expectedRuleFingerprint;
try {
expectedFingerprint = await citationFingerprint(rule);
expectedRuleFingerprint = await ruleFingerprint(rule);
} catch {
return new Map();
}
if (!nonBlank(record.citation_fingerprint)
|| !nonBlank(record.rule_fingerprint)
|| !expectedFingerprint
|| !expectedRuleFingerprint
|| record.citation_fingerprint !== expectedFingerprint
|| record.rule_fingerprint !== expectedRuleFingerprint) continue;
normalized.set(ruleId, {
...record,
es: await validTranslationReview(record.es, version, updatedOn)
? record.es : null,
});
}
return normalized;
}
const SB9_BASE_FIELDS = [
"in_urbanized_area",
"sf_zone",
"demolishes_protected_housing",
"tenant_occupied_last_3_years",
"ellis_withdrawal_last_15_years",
"on_protected_site",
];
const SB9_TWO_UNIT_FIELDS = [
"two_unit_contributing_historic_location",
"two_unit_individually_listed_historic_property",
];
const SB9_LOT_SPLIT_FIELDS = [
"lot_split_on_historic_landmark_site",
"lot_split_alters_historic_district_resource",
"parcel_created_by_sb9_split",
"adjacent_sb9_split_same_actor",
"proposed_lot_ratio_compliant",
"proposed_lot_size_compliant",
];
function radioQuestion(name, legend, options, help = "") {
const helpId = `${name}-help`;
const describedBy = help ? ` aria-describedby="${helpId}"` : "";
return `<fieldset data-question="${esc(name)}"${describedBy}>
<legend>${esc(legend)}</legend>
${help ? `<p class="small question-help" id="${helpId}">${esc(help)}</p>` : ""}
<div class="choice-grid">
${options.map(([value, label]) =>
`<label><input type="radio" name="${esc(name)}"
value="${esc(value)}" required> ${esc(label)}</label>`
).join("")}
</div>
</fieldset>`;
}
function fieldsForProject(projectType) {
if (projectType === "adu")
return ["primary_dwelling_status", "adu_project_form",
"unpermitted_existing"];
if (projectType === "jadu")
return ["primary_dwelling_status", "unpermitted_existing"];
if (projectType === "two_unit")
return [...SB9_BASE_FIELDS, ...SB9_TWO_UNIT_FIELDS];
if (projectType === "lot_split")
return [...SB9_BASE_FIELDS, ...SB9_LOT_SPLIT_FIELDS];
return [];
}
function renderProjectQuestions() {
const s = STRINGS[lang];
const projectType = intakeDraft.project_type || null;
const container = document.getElementById("projectQuestions");
if (!projectType) {
container.hidden = true;
container.innerHTML = "";
return;
}
const fields = fieldsForProject(projectType);
const questions = fields.map(name => {
if (name === "primary_dwelling_status")
return radioQuestion(name, s.primaryQuestion, s.primaryOptions, s.primaryHelp);
if (name === "adu_project_form")
return radioQuestion(name, s.aduFormQuestion, s.aduFormOptions);
if (name === "unpermitted_existing")
return radioQuestion(