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
1170 lines (1126 loc) · 56.7 KB
/
Copy pathindex.html
File metadata and controls
1170 lines (1126 loc) · 56.7 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 Pathways — cited housing-permit guidance for California jurisdictions</title>
<meta name="description" content="Citation-grounded ADU, JADU, and SB 9 candidate pathway guidance for California jurisdictions, with a prototype source-drift review harness.">
<meta property="og:title" content="Permit Pathways">
<meta property="og:description" content="Every candidate answer cites a source. Selected statewide sources are watched for change. ADU, JADU, and SB 9 guidance with a public trust dashboard.">
<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);
--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);
--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);
--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 { font-size: .85rem; }
nav a, nav .nav-button { color: var(--accent); text-decoration: none;
margin-right: .9rem; }
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; }
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: 1px solid var(--grid); background: var(--surface); color: var(--ink);
width: 100%; max-width: 100%; }
input[type="text"], input[type="date"], input[list], textarea { min-height: 44px; }
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); }
.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; }
.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 .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; }
</style>
</head>
<body>
<main>
<nav>
<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">Watched sources</a>
<button class="nav-button" id="langToggle" type="button">Español</button>
</nav>
<h1 id="t-title">Permit Pathways</h1>
<p class="tag" id="t-tagline">Every candidate answer cites a source. Selected statewide sources are watched for change.</p>
<section id="screen">
<form id="intake">
<fieldset>
<legend id="t-juris">Where is the property?</legend>
<input id="jurisInput" name="jurisdiction_name" list="jurisList"
autocomplete="off" aria-label="California city or county"
required
placeholder="Type any California city or county…"
style="width:100%;font-size:1rem;padding:.45rem;border:1px solid var(--grid);
border-radius:6px;background:var(--surface);color:var(--ink)">
<datalist id="jurisList"></datalist>
<p class="small" id="jurisStatus" aria-live="polite"></p>
</fieldset>
<fieldset>
<legend id="t-project">What are you proposing?</legend>
<div id="typeRadios"></div>
</fieldset>
<fieldset>
<legend id="t-dwelling">What kind of home is on the lot?</legend>
<select name="dwelling_type" id="dwellingSel"></select>
</fieldset>
<fieldset id="factBoxes"></fieldset>
<button type="submit" id="t-submit" disabled>Check candidate pathways</button>
</form>
<p id="resultStatus" class="visually-hidden" aria-live="polite"></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.
<a href="#" id="loadSample">Load two of those provisions as a sample</a>.</p>
<textarea id="ordText" rows="8" aria-label="Ordinance text to scan"
style="width:100%;font-size:.9rem;
border:1px solid var(--grid);border-radius:8px;background:var(--surface);
color:var(--ink);padding:.6rem" placeholder="Paste ordinance text here…"></textarea>
<p><button id="scanBtn" disabled>Scan</button></p>
<div id="scanResults" aria-live="polite"></div>
</section>
<section id="clocks">
<h2>Statutory review clocks</h2>
<p class="small">State law puts the permitting agency on a clock. Enter the
initial receipt date. This bounded prototype assumes the application was
complete on receipt for the illustrative 60-day decision row; it does not
model a correction/resubmittal cycle:</p>
<p><input type="date" id="recvDate" aria-label="Date the application was received"
style="font-size:1rem;padding:.35rem;
border:1px solid var(--grid);border-radius:6px;background:var(--surface);
color:var(--ink)"> <button class="ghost" id="clockBtn">Compute deadlines</button></p>
<div id="clockResults" aria-live="polite"></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. Citation-matched rules are <b>stale</b> until staff re-check them
against the new text. This rehearsal uses citation text matching; stable
dependency IDs and persisted watcher state are the next step.
</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">Watched sources</h2>
<p class="small" id="t-sourcesub">Selected statewide source hashes are
recorded and re-fetched so revisions or fetch failures become visible.
Local-source coverage, explicit dependencies, and a persisted impact queue
are planned.</p>
<div class="table-scroll" role="region" aria-label="Watched source table"
tabindex="0">
<table id="sourceTable"><thead>
<tr><th>Source</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: "Every candidate answer cites a source. Selected statewide sources are watched for change.",
juris: "Where is the property?",
jurisPlaceholder: "Type any California city or county…",
jurisAria: "California city or county",
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",
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)"]],
dwelling: "What kind of home is on the lot?",
dwellings: [["single_family","Single-family house"],
["multifamily","Multifamily building (apartments, attached units)"],
["other","Other / no home yet"]],
facts: [["has_primary_dwelling","There is (or will be) a home on the lot",true],
["in_urbanized_area","The property is in a city / urbanized area",true],
["sf_zone","The property is zoned single-family residential",true],
["unpermitted_existing","The unit already exists but was built without permits (before 2020)",false],
["no_exclusions","None of these apply: demolishing rent-restricted or affordable housing · a tenant lived there in the last 3 years · historic district · wetlands or other protected site · parcel already created by an SB 9 lot split",true]],
submit: "Check candidate pathways",
results: "Possible permit paths and rules",
resultIntro: "This prototype deterministically matched your answers against its bounded encoded rule set. It did not verify parcel facts, eligibility, or approval. Plain-language explanations are AI-assisted drafts; cited source records remain separate below.",
resultCount: count => count === 1 ? "1 matched rule record." : `${count} matched rule records.`,
none: "No pathway in this prototype's encoded state rule set matched your answers. This does not mean your project is impossible — it means it needs staff review. Contact your jurisdiction's planning counter.",
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",
},
es: {
tagline: "Cada respuesta posible cita una fuente. Se monitorean fuentes estatales seleccionadas.",
juris: "¿Dónde está la propiedad?",
jurisPlaceholder: "Escriba cualquier ciudad o condado de California…",
jurisAria: "Ciudad o condado de California",
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",
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)"]],
dwelling: "¿Qué tipo de vivienda hay en el lote?",
dwellings: [["single_family","Casa unifamiliar"],
["multifamily","Edificio multifamiliar (apartamentos, unidades adosadas)"],
["other","Otro / aún no hay vivienda"]],
facts: [["has_primary_dwelling","Hay (o habrá) una vivienda en el lote",true],
["in_urbanized_area","La propiedad está en una ciudad / área urbanizada",true],
["sf_zone","La propiedad tiene zonificación residencial unifamiliar",true],
["unpermitted_existing","La unidad ya existe pero se construyó sin permisos (antes de 2020)",false],
["no_exclusions","Ninguno de estos aplica: demoler vivienda de renta restringida o asequible · un inquilino vivió allí en los últimos 3 años · distrito histórico · humedales u otro sitio protegido · parcela ya creada por una división SB 9",true]],
submit: "Revisar posibles vías",
results: "Posibles vías de permiso y reglas",
resultIntro: "Este prototipo comparó sus respuestas de forma determinista con su conjunto limitado de reglas codificadas. No verificó los datos de la parcela, la elegibilidad ni la aprobación. Las explicaciones en lenguaje sencillo son borradores asistidos por IA; los registros de las fuentes citadas se muestran por separado.",
resultCount: count => count === 1 ? "1 registro de regla coincidente." : `${count} registros de reglas coincidentes.`,
none: "Ninguna vía del conjunto de reglas estatales codificadas de este prototipo coincidió con sus respuestas. Esto no significa que su proyecto sea imposible — significa que necesita revisión del personal. Contacte a su departamento de planificación.",
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",
},
};
let lang = "en";
let RULES = [], GOLDEN = [], SOURCES = {}, CHECKS = [], JURIS = [], LETTERS = {}, SCANS = {};
let EXPLANATIONS = new Map();
let jurisByName = new Map();
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.";
const OPS = {
eq: (a,b) => a === b,
lte: (a,b) => a != null && a <= b,
gte: (a,b) => a != null && a >= b,
in: (a,b) => b.includes(a),
};
const MAX_AGE_DAYS = 180;
function matches(rule, intake) {
return rule.criteria.every(c => OPS[c.op](intake[c.field], c.value));
}
function screen(intake) {
return RULES.filter(r =>
(r.jurisdiction_scope === "statewide" || r.jurisdiction_scope === intake.jurisdiction)
&& matches(r, intake));
}
function ruleStatus(rule, changedMarkers) {
const c = rule.citation;
if (changedMarkers.some(m => (c.source||"").includes(m) || (c.url||"").includes(m)))
return "stale";
if (!c.verified_on) return "unverified";
const age = (Date.now() - new Date(c.verified_on)) / 86400000;
return age > MAX_AGE_DAYS ? "stale" : "verified";
}
function esc(s) { const d = document.createElement("span"); d.textContent = s ?? ""; return d.innerHTML; }
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 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))
);
}
function validReview(review, version, updatedOn) {
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];
if (review.status === "prototype_review_pending")
return metadata.every(value => value == null);
return metadata.every(nonBlank)
&& validIsoDate(review.reviewed_on)
&& review.reviewed_on >= updatedOn
&& review.reviewed_version === version;
}
function validLocalizedCopy(copy, language, version, updatedOn) {
if (!copy || typeof copy !== "object"
|| !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];
if (copy.translation_status === "machine_draft")
return metadata.every(value => value == null);
return metadata.every(nonBlank)
&& validIsoDate(copy.reviewed_on)
&& copy.reviewed_on >= updatedOn
&& copy.reviewed_version === version;
}
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("");
}
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,
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,
});
}
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 || "")
|| !validIsoDate(updatedOn)
|| !["route", "standard", "local_process"].includes(record.display_group)
|| record.drafted_by !== "ai_assisted"
|| (record.source_verified_on ?? null)
!== (rule.citation.verified_on ?? null)
|| (record.source_verified_on
&& updatedOn < record.source_verified_on)
|| !validReview(record.review, version, updatedOn)
|| !validLocalizedCopy(record.en, "en", version, updatedOn)) 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: validLocalizedCopy(record.es, "es", version, updatedOn)
? record.es : null,
});
}
return normalized;
}
function renderForm() {
const s = STRINGS[lang];
const translatedIds = ["t-tagline", "t-juris", "t-project", "t-submit",
"t-dwelling", "typeRadios", "dwellingSel", "factBoxes",
"jurisStatus", "resultStatus"];
translatedIds.forEach(id => { document.getElementById(id).lang = lang; });
document.getElementById("t-tagline").textContent = s.tagline;
document.getElementById("t-juris").textContent = s.juris;
document.getElementById("t-project").textContent = s.project;
document.getElementById("t-submit").textContent = s.submit;
document.getElementById("langToggle").textContent = s.langBtn;
document.getElementById("langToggle").lang = lang === "en" ? "es" : "en";
document.getElementById("jurisInput").placeholder = s.jurisPlaceholder;
document.getElementById("jurisInput").lang = lang;
document.getElementById("jurisInput").setAttribute("aria-label", s.jurisAria);
renderJurisStatus();
document.getElementById("typeRadios").innerHTML =
s.types.map(([v,t],i) => `<label><input type="radio" name="project_type" value="${v}" ${i===0?"checked":""}> ${esc(t)}</label>`).join("");
document.getElementById("t-dwelling").textContent = s.dwelling;
document.getElementById("dwellingSel").innerHTML =
s.dwellings.map(([v,t]) => `<option value="${v}">${esc(t)}</option>`).join("");
document.getElementById("factBoxes").innerHTML =
s.facts.map(([v,t,on]) => `<label><input type="checkbox" name="${v}" ${on?"checked":""}> ${esc(t)}</label>`).join("");
}
function usableLocalizedExplanation(explanation) {
if (!explanation || typeof explanation !== "object") return null;
const preferred = lang === "es" ? explanation.es : explanation.en;
const fallback = lang === "es" ? explanation.en : null;
const localized = preferred || fallback;
if (!localized || typeof localized.summary !== "string"
|| !Array.isArray(localized.next_steps)
|| !localized.next_steps.every(item => typeof item === "string")
|| !Array.isArray(localized.confirm_with_staff)
|| !localized.confirm_with_staff.every(item => typeof item === "string")
|| !validHighlights(localized.highlights)
|| typeof explanation.source_rule_id !== "string"
|| typeof explanation.version !== "string"
|| typeof explanation.updated_on !== "string") return null;
return {localized, copyLang: preferred ? lang : "en"};
}
function baseExplanationReviewLabel(explanation) {
const s = STRINGS[lang];
const review = explanation.review || {};
if (review.status === "jurisdiction_approved") {
return lang === "es"
? `Explicación aprobada por la jurisdicción · ${review.reviewer} · ${review.reviewed_on} · v${review.reviewed_version}`
: `Jurisdiction-approved explanation · ${review.reviewer} · ${review.reviewed_on} · v${review.reviewed_version}`;
}
if (review.status === "human_reviewed") {
return lang === "es"
? `Explicación revisada por una persona · ${review.reviewer} · ${review.reviewed_on} · v${review.reviewed_version}`
: `Human-reviewed explanation · ${review.reviewer} · ${review.reviewed_on} · v${review.reviewed_version}`;
}
return s.aiDraft;
}
function explanationReviewLabels(explanation, localized, copyLang) {
const s = STRINGS[lang];
const labels = [baseExplanationReviewLabel(explanation)];
if (lang !== "es") return labels;
if (copyLang !== "es") return [...labels, s.englishOnly];
if (localized.translation_status === "machine_draft")
return [...labels, s.translationDraft];
if (localized.translation_status === "jurisdiction_approved")
return [...labels,
`Traducción aprobada por la jurisdicción · ${localized.reviewer} · ${localized.reviewed_on} · v${localized.reviewed_version}`];
return [...labels,
`Traducción revisada por una persona · ${localized.reviewer} · ${localized.reviewed_on} · v${localized.reviewed_version}`];
}
function renderResultCard(rule, explanation) {
const s = STRINGS[lang];
const c = rule.citation;
const status = ruleStatus(rule, simulating ? ["66321"] : []);
const ok = status === "verified";
const badge = ok
? `<span class="badge info" lang="${lang}"><span class="status-ico" aria-hidden="true">◷</span>${esc(s.verifiedOn)} ${esc(c.verified_on)}</span>`
: status === "stale"
? `<span class="badge bad" lang="${lang}"><span class="status-ico" aria-hidden="true">✕</span>${esc(s.stale)}</span>`
: `<span class="badge warn" lang="${lang}"><span class="status-ico" aria-hidden="true">⚠</span>${esc(s.unverified)}</span>`;
const localizedRecord = ok ? usableLocalizedExplanation(explanation) : null;
let plainLanguage = status === "unverified"
? `<div class="notice small" lang="${lang}">${esc(s.withheldUnverified)}</div>`
: status === "stale"
? `<div class="notice small" lang="${lang}">${esc(s.withheldStale)}</div>`
: `<div class="notice small" lang="${lang}">${esc(s.unavailable)}</div>`;
let reviewNote = "";
let copyRecord = "";
if (localizedRecord) {
const {localized, copyLang} = localizedRecord;
const steps = localized.next_steps.map(step => `<li>${esc(step)}</li>`).join("");
const confirmations = localized.confirm_with_staff.map(item => `<li>${esc(item)}</li>`).join("");
const highlights = localized.highlights
? `<div class="key-points">
<h5 lang="${copyLang}">${esc(localized.highlights.title)}</h5>
<ul lang="${copyLang}">${localized.highlights.items.map(item =>
`<li><strong>${esc(item.label)}:</strong> ${esc(item.text)}</li>`
).join("")}</ul>
</div>`
: "";
plainLanguage = `<div class="plain-layer">
<h5 lang="${lang}">${esc(s.means)}</h5>
<p lang="${copyLang}">${esc(localized.summary)}</p>
${highlights}
<h5 lang="${lang}">${esc(s.next)}</h5>
<p class="small" lang="${lang}">${esc(s.nextScope)}</p>
<ol lang="${copyLang}">${steps}</ol>
<div class="confirmation">
<h5 lang="${lang}">${esc(s.confirm)}</h5>
<ul lang="${copyLang}">${confirmations}</ul>
</div>
</div>`;
reviewNote = explanationReviewLabels(explanation, localized, copyLang)
.map(label => `<p class="review-note" lang="${lang}">${esc(label)}</p>`)
.join("");
copyRecord = `<p class="small"><span lang="${lang}">${esc(s.copyRecord)}:</span>
<span lang="en">${esc(explanation.source_rule_id)} v${esc(explanation.version)}, ${esc(explanation.updated_on)}</span></p>`;
}
const docs = (rule.required_documents || []).map(d => `<li>${esc(d)}</li>`).join("");
const evidence = `<details>
<summary lang="${lang}">${esc(s.evidence)}</summary>
${ok && rule.notes ? `<p class="small" lang="en">${esc(rule.notes)}</p>` : ""}
${c.excerpt ? `<blockquote lang="en">${esc(c.excerpt)}</blockquote>` : ""}
${!ok && !c.excerpt ? `<p class="small" lang="${lang}">${esc(s.evidenceUnavailable)}</p>` : ""}
${ok && docs ? `<h5 lang="${lang}">${esc(s.docs)}</h5><ul class="small" lang="en">${docs}</ul>` : ""}
${copyRecord}
</details>`;
const safeId = String(rule.rule_id).replace(/[^A-Za-z0-9_-]/g, "-");
return `<article class="card result-card ${ok ? "" : "unverified"}"
data-rule-id="${esc(rule.rule_id)}" aria-labelledby="result-title-${safeId}">
<div class="result-head">
<h4 class="result-title" id="result-title-${safeId}" lang="en">${esc(rule.pathway)}</h4>
${badge}
</div>
${reviewNote}
${plainLanguage}
<p class="source-basis"><b lang="${lang}">${esc(s.source)}:</b>
<a lang="en" href="${esc(c.url)}" rel="noopener">${esc(c.source)}</a></p>
${evidence}
</article>`;
}
function renderResults(list) {
const s = STRINGS[lang];
const el = document.getElementById("results");
LAST_RESULTS = list;
const status = document.getElementById("resultStatus");
status.lang = lang;
status.textContent = list.length
? s.resultCount(list.length)
: `${s.resultCount(0)} ${s.none}`;
if (!list.length) {
el.innerHTML = `<div lang="${lang}"><h2>${esc(s.results)}</h2>
<div class="notice">${esc(s.none)}</div></div>`;
return;
}
const groupOrder = ["route", "standard", "local_process", "other"];
const grouped = new Map(groupOrder.map(group => [group, []]));
list.forEach(rule => {
const explanation = EXPLANATIONS.get(rule.rule_id);
const group = explanation && ["route", "standard", "local_process"].includes(explanation.display_group)
? explanation.display_group : "other";
grouped.get(group).push(renderResultCard(rule, explanation));
});
const sections = groupOrder.map(group => {
const cards = grouped.get(group);
return cards.length
? `<section class="result-group" aria-labelledby="result-group-${group}">
<h3 id="result-group-${group}" lang="${lang}">${esc(s.groups[group])}</h3>
${cards.join("")}
</section>` : "";
}).join("");
el.innerHTML = `<h2 lang="${lang}">${esc(s.results)}</h2>
<p class="small" lang="${lang}">${esc(s.resultIntro)}</p>${sections}`;
}
let simulating = false;
let LAST_RESULTS = null;
function renderDashboard() {
const changed = simulating ? ["66321"] : [];
const statuses = RULES.map(r => ({ rule: r, st: ruleStatus(r, changed) }));
const n = { verified: 0, stale: 0, unverified: 0 };
statuses.forEach(x => n[x.st]++);
const total = RULES.length;
const pct = total ? Math.round(100 * n.verified / total) : 0;
document.getElementById("pct").textContent = pct;
const meter = document.getElementById("meter");
meter.innerHTML =
`<div class="m-good" style="width:${100*n.verified/total}%"></div>` +
`<div class="m-bad" style="width:${100*n.stale/total}%"></div>` +
`<div class="m-warn" style="width:${100*n.unverified/total}%"></div>`;
document.getElementById("meterLegend").innerHTML =
`<span class="badge ok"><span class="status-ico" aria-hidden="true">✓</span>within review window ${n.verified}</span> ` +
`<span class="badge bad"><span class="status-ico" aria-hidden="true">✕</span>stale/simulated change ${n.stale}</span> ` +
`<span class="badge warn"><span class="status-ico" aria-hidden="true">⚠</span>no dated source record ${n.unverified}</span>`;
// Golden replay runs live in the page: same matcher, same data.
let pass = 0;
GOLDEN.forEach(g => {
const got = screen(g.intake).map(r => r.rule_id).sort().join(",");
if (got === [...g.expected_rule_ids].sort().join(",")) pass++;
});
document.getElementById("goldenLine").textContent =
`${pass}/${GOLDEN.length} structured golden scenarios replayed and passing in this browser`;
if (JURIS.length) {
const nCities = JURIS.filter(j => j.kind === "city").length;
const nLocal = JURIS.filter(j => j.has_local_layer).length;
const nHcd = Object.keys(LETTERS).length;
document.getElementById("covLine").textContent =
`Registry: ${JURIS.length} California jurisdictions (${nCities} cities, ` +
`${JURIS.length - nCities} counties) can screen the same statewide ` +
`candidate-rule set; ${nLocal} have jurisdiction-scoped metadata records; ` +
`${nHcd} have known HCD letter history.`;
}
document.querySelector("#ruleTable tbody").innerHTML = statuses.map(({rule, st}) => {
const b = st === "verified"
? `<span class="badge ok"><span class="status-ico" aria-hidden="true">✓</span>within review window</span>`
: st === "stale"
? `<span class="badge bad"><span class="status-ico" aria-hidden="true">✕</span>STALE — re-verify</span>`
: `<span class="badge warn"><span class="status-ico" aria-hidden="true">⚠</span>no dated source record</span>`;
return `<tr><td>${esc(rule.pathway)}</td><td class="mutedtxt">${esc(rule.jurisdiction_scope)}</td><td>${b}</td></tr>`;
}).join("");
document.getElementById("simNote").classList.toggle("hidden", !simulating);
document.getElementById("simBtn").classList.toggle("hidden", simulating);
document.getElementById("resetBtn").classList.toggle("hidden", !simulating);
}
function renderSources() {
document.querySelector("#sourceTable tbody").innerHTML =
Object.entries(SOURCES).map(([url, m]) =>
`<tr><td><a href="${esc(url)}" rel="noopener">${esc(m.label)}</a></td>
<td class="mutedtxt">${esc(m.fetched_on)}</td>
<td class="mutedtxt" style="font-family:ui-monospace,monospace;font-size:.75rem">${esc(m.sha256.slice(0,16))}…</td></tr>`
).join("");
}
document.getElementById("intake").addEventListener("submit", e => {
e.preventDefault();
const f = new FormData(e.target);
const jurisdiction = resolveJurisdiction();
if (!jurisdiction) {
const s = STRINGS[lang];
LAST_RESULTS = null;
document.getElementById("results").innerHTML =
`<div lang="${lang}"><h2>${esc(s.results)}</h2>
<div class="notice">${esc(s.jurisRequired)}</div></div>`;
document.getElementById("resultStatus").textContent = s.jurisRequired;
document.getElementById("jurisInput").focus();
return;
}
const noExcl = f.has("no_exclusions");
renderResults(screen({
project_type: f.get("project_type"),
has_primary_dwelling: f.has("has_primary_dwelling"),
dwelling_type: f.get("dwelling_type"),
unpermitted_existing: f.has("unpermitted_existing"),
in_urbanized_area: f.has("in_urbanized_area"),
zone_class: f.has("sf_zone") ? "single_family_residential" : "other",
demolishes_protected_housing: !noExcl,
tenant_occupied_last_3_years: !noExcl,
in_historic_district: !noExcl,
on_protected_site: !noExcl,
parcel_created_by_sb9_split: !noExcl,
jurisdiction: jurisdiction.slug,
}));
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
document.getElementById("results").scrollIntoView({
behavior: reduceMotion ? "auto" : "smooth",
});
});
function jurisDisplay(j) {
return j.kind === "county" ? j.name : `${j.name} (${j.county.replace(" County","")} Co.)`;
}
function resolveJurisdiction() {
const raw = document.getElementById("jurisInput").value.trim();
return jurisByName.get(raw.toLowerCase()) || null;
}
function renderJurisStatus() {
const s = STRINGS[lang];
const el = document.getElementById("jurisStatus");
const raw = document.getElementById("jurisInput").value.trim();
if (!raw) { el.textContent = ""; return; }
const j = resolveJurisdiction();
if (!j) { el.textContent = s.statusUnknown; return; }
const localCount = JURIS.filter(x => x.has_local_layer).length;
let html = j.has_local_layer
? `<span class="badge ok"><span class="status-ico" aria-hidden="true">✓</span>local metadata</span> ${esc(s.statusLocal)}`
: `${esc(s.statusBaseline)} (${esc(s.localCoverage(localCount, JURIS.length))})`;
const scanRec = SCANS[j.slug];
if (scanRec) {
html += `<br><span class="badge ok"><span class="status-ico" aria-hidden="true">✓</span>scanned</span> ` +
`Ordinance screened ${esc(scanRec.scanned_on)}: ${scanRec.findings} provision(s) ` +
`flagged for review — <a href="data/conformance/results/${esc(j.slug)}.json" rel="noopener">view scan findings (JSON)</a>.`;
}
const history = LETTERS[j.slug] || [];
if (history.length) {
html += `<br><span class="badge warn"><span class="status-ico" aria-hidden="true">⚠</span>HCD</span> ` +
`${esc(s.hcdHistory)}: ${history.length} letter(s) on record.`;
for (const letter of history.slice(0, 3)) {
const label = `${esc(letter.kind)}, ${esc(letter.date)}` +
(letter.authority ? ` — ${esc(letter.authority)}` : "");
html += `<br> · ` +
(letter.url ? `<a href="${esc(letter.url)}" rel="noopener">${label}</a>` : label);
}
if (history.length > 3) html += `<br> · …and ${history.length - 3} more`;
}
el.innerHTML = html;
}
function scanOrdinance(text) {
const findings = [];
for (const check of CHECKS) {
const seen = [];
for (const pattern of check.patterns) {
const re = new RegExp(pattern, "gi");
let m;
while ((m = re.exec(text)) !== null) {
const excluded = (check.exclude_patterns || []).some(ex => {
const exRe = new RegExp(ex, "gi");
let e;
while ((e = exRe.exec(text)) !== null)
if (e.index <= m.index && m.index + m[0].length <= e.index + e[0].length) return true;
return false;
});
if (excluded || seen.some(([s, e]) => s <= m.index && m.index < e)) continue;
if (check.context_patterns) {
const ws = Math.max(0, m.index - 300);
const win = text.slice(ws, m.index + m[0].length + 300);
if (!check.context_patterns.some(p => new RegExp(p, "i").test(win))) continue;
}
seen.push([m.index, m.index + m[0].length]);
const start = Math.max(0, m.index - 120);
const end = Math.min(text.length, m.index + m[0].length + 120);
findings.push({ check, excerpt: text.slice(start, end).replace(/\s+/g, " "), offset: m.index });
}
}
}
return findings.sort((a, b) => a.offset - b.offset);
}
document.getElementById("scanBtn").addEventListener("click", () => {
const text = document.getElementById("ordText").value;
const el = document.getElementById("scanResults");
if (!text.trim()) { el.innerHTML = ""; return; }
const findings = scanOrdinance(text);
if (!findings.length) {
el.innerHTML = `<div class="notice">No candidate provisions flagged.
Presence-based screen only — this is <b>not</b> a certification of compliance.</div>`;
return;
}
el.innerHTML = findings.map(f => {
const definite = f.check.severity === "definite";
return `<div class="card ${definite ? "" : "unverified"}"
style="border-left-color:${definite ? "var(--critical)" : "var(--warning)"}">
<h3>${esc(f.check.title)}
<span class="badge ${definite ? "bad" : "warn"}">
<span class="status-ico" aria-hidden="true">${definite ? "✕" : "⚠"}</span>${definite ? "finding" : "review"}</span></h3>
<blockquote>…${esc(f.excerpt)}…</blockquote>
<p class="small"><b>State law:</b> ${esc(f.check.state_law)}</p>
<p class="small"><b>Explanation:</b> ${esc(f.check.explanation)}</p>
<p class="small mutedtxt"><b>HCD precedent:</b> ${esc(f.check.hcd_precedent)}</p>
</div>`;
}).join("");
});
document.getElementById("loadSample").addEventListener("click", e => {
e.preventDefault();
document.getElementById("ordText").value = SAMPLE_ORDINANCE;
document.getElementById("scanBtn").click();
});
document.getElementById("clockBtn").addEventListener("click", () => {
const v = document.getElementById("recvDate").value;
const el = document.getElementById("clockResults");
if (!v) { el.innerHTML = ""; return; }
const received = new Date(v + "T12:00:00");
const nthWeekday = (y, m, wd, n) => {
const d = new Date(y, m, 1);
return new Date(y, m, 1 + ((wd - d.getDay() + 7) % 7) + 7 * (n - 1));
};
const lastWeekday = (y, m, wd) => {
const d = new Date(y, m + 1, 0);
return new Date(y, m, d.getDate() - ((d.getDay() - wd + 7) % 7));
};
const observed = d => {
const out = new Date(d);
if (d.getDay() === 6) out.setDate(d.getDate() - 1);
if (d.getDay() === 0) out.setDate(d.getDate() + 1);
return out;
};
const caHolidays = y => {
const tg = nthWeekday(y, 10, 4, 4);
const dayAfterTg = new Date(tg); dayAfterTg.setDate(tg.getDate() + 1);
return new Set([
observed(new Date(y, 0, 1)), observed(new Date(y, 2, 31)),
observed(new Date(y, 6, 4)), observed(new Date(y, 10, 11)),
observed(new Date(y, 11, 25)),
nthWeekday(y, 0, 1, 3), nthWeekday(y, 1, 1, 3), lastWeekday(y, 4, 1),
nthWeekday(y, 8, 1, 1), tg, dayAfterTg,
].map(d => d.toDateString()));
};
const hols = new Set([...caHolidays(received.getFullYear()),
...caHolidays(received.getFullYear() + 1)]);
const addBiz = (d, n) => {
const out = new Date(d);
while (n > 0) {
out.setDate(out.getDate() + 1);