endomorphosis commited on
Commit
83f042b
·
verified ·
1 Parent(s): 1736136

Wave3A OH/state admin+EO additive +851 rows

Browse files
data/ARE-US-COUNTY-MUNICIPAL.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a9a53d6815993f434ab160d9f506a880444d168caf7e6a3b2e804e17d4a743b9
3
+ size 24986
data/oh_ARE-US-OH_resume_20261106T055344Z.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7b2e7b47660e47df0b74c79e8ae3b3661d12e51085e7816bea3e0e96f2578a2
3
+ size 40202
data/oh_OH_official_normalized_existing.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f68575a77bda56590c6dce77cb5099fcb056ef3ba6490e51e9919e17d71c11b1
3
+ size 644485
data/oh_OH_official_resume_20261106T054123Z.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f36a52bc9b5fadc8ff37dea9324f1f77e68fb7c7ca100fa9d2682ead963478e5
3
+ size 41218
scrapers_and_normalizers/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # US Admin Rules & EO (seed-driven, pause-capable)
2
+
3
+ - Seeds: `/workspace/coverage/world_admin_eo_seeds_20261105.jsonl`
4
+ - Live official URLs primary for IN/NH/TN/WY; Wayback only on failure (`archive_source`)
5
+ - Deep frontier crawl per state (multi-record), Governor EOs → `us_executive_orders_20261105`
6
+ - Memguard: pause/hibernate below 4.2 GiB, resume at 4.35 GiB; disk exit; RSS re-exec at 500 MiB
scrapers_and_normalizers/__pycache__/federal_collector.cpython-313.pyc ADDED
Binary file (15.2 kB). View file
 
scrapers_and_normalizers/__pycache__/gap_queue.cpython-313.pyc ADDED
Binary file (2.03 kB). View file
 
scrapers_and_normalizers/__pycache__/io_zst.cpython-313.pyc ADDED
Binary file (12.4 kB). View file
 
scrapers_and_normalizers/__pycache__/municipal_collector.cpython-313.pyc ADDED
Binary file (7.87 kB). View file
 
scrapers_and_normalizers/__pycache__/normalizer.cpython-313.pyc ADDED
Binary file (10.8 kB). View file
 
scrapers_and_normalizers/__pycache__/seeds.cpython-313.pyc ADDED
Binary file (4.77 kB). View file
 
scrapers_and_normalizers/__pycache__/state_admin_collector.cpython-313.pyc ADDED
Binary file (27.1 kB). View file
 
scrapers_and_normalizers/federal_collector.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stream B targets: ARE-US-ECFR, ARE-US-FR, ARE-US-EO — keyless official APIs."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import time
6
+ import xml.etree.ElementTree as ET
7
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple
8
+
9
+ import requests
10
+
11
+ from normalizer import from_ecfr_section, from_federal_register_doc, xml_to_text, strip_html
12
+
13
+ UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
14
+ FR_API = "https://www.federalregister.gov/api/v1/documents.json"
15
+ ECFR_TITLES = "https://www.ecfr.gov/api/versioner/v1/titles.json"
16
+ FR_FIELDS = [
17
+ "document_number", "title", "type", "subtype", "presidential_document_number",
18
+ "executive_order_number", "publication_date", "html_url", "abstract",
19
+ "body_html_url", "full_text_xml_url", "raw_text_url", "agencies", "citation",
20
+ ]
21
+
22
+
23
+ class PoliteSession:
24
+ def __init__(self, delay: float = 0.75):
25
+ self.s = requests.Session()
26
+ self.s.headers["User-Agent"] = UA
27
+ self.s.verify = True
28
+ self.delay = delay
29
+ self._last = 0.0
30
+ self.n = 0
31
+
32
+ def get(self, url: str, **kwargs) -> Optional[requests.Response]:
33
+ wait = self.delay - (time.time() - self._last)
34
+ if wait > 0:
35
+ time.sleep(wait)
36
+ for attempt in range(3):
37
+ try:
38
+ r = self.s.get(url, timeout=90, verify=True, **kwargs)
39
+ self._last = time.time()
40
+ self.n += 1
41
+ if r.status_code == 429:
42
+ ra = float(r.headers.get("Retry-After") or (5 * (attempt + 1)))
43
+ time.sleep(min(ra, 90))
44
+ continue
45
+ return r
46
+ except requests.RequestException:
47
+ time.sleep(5 * (attempt + 1))
48
+ return None
49
+
50
+
51
+ def ecfr_as_of(sess: PoliteSession) -> Tuple[str, List[Dict[str, Any]]]:
52
+ r = sess.get(ECFR_TITLES)
53
+ if not r or r.status_code != 200:
54
+ return "2026-11-04", []
55
+ titles = list((r.json() or {}).get("titles") or [])
56
+ date = titles[0].get("up_to_date_as_of") if titles else "2026-11-04"
57
+ return date, titles
58
+
59
+
60
+ def iter_structure_parts(node: Dict[str, Any]) -> Iterable[str]:
61
+ if not isinstance(node, dict):
62
+ return
63
+ if (node.get("type") or "").lower() == "part":
64
+ ident = str(node.get("identifier") or "")
65
+ if ident:
66
+ yield ident
67
+ for c in node.get("children") or []:
68
+ yield from iter_structure_parts(c)
69
+
70
+
71
+ def list_parts_for_title(sess: PoliteSession, date: str, title_num: int) -> List[str]:
72
+ r = sess.get(f"https://www.ecfr.gov/api/versioner/v1/structure/{date}/title-{title_num}.json")
73
+ if not r or r.status_code != 200:
74
+ return []
75
+ return list(dict.fromkeys(iter_structure_parts(r.json())))
76
+
77
+
78
+ def _section_text_from_elem(elem: ET.Element) -> Tuple[str, str]:
79
+ head = ""
80
+ chunks: List[str] = []
81
+ for el in elem.iter():
82
+ tag = (el.tag or "").split("}")[-1].upper()
83
+ if tag == "HEAD" and el.text and not head:
84
+ head = (el.text or "").strip()
85
+ if el.text and el.text.strip():
86
+ chunks.append(el.text.strip())
87
+ if el.tail and el.tail.strip():
88
+ chunks.append(el.tail.strip())
89
+ text = " ".join(chunks)
90
+ text = " ".join(text.split())
91
+ return head, text
92
+
93
+
94
+ def parse_part_xml_sections(xml_bytes: bytes, title_num: int, part: str, date: str) -> List[Dict[str, Any]]:
95
+ """Parse a single-part eCFR XML payload (small) into section records via iterparse."""
96
+ out: List[Dict[str, Any]] = []
97
+ source_url = f"https://www.ecfr.gov/current/title-{title_num}/part-{part}"
98
+ try:
99
+ # wrap if needed
100
+ raw = xml_bytes
101
+ if b"<ECFR" not in raw[:200] and b"<DIV" in raw[:200]:
102
+ raw = b"<WRAP>" + raw + b"</WRAP>"
103
+ context = ET.iterparse(io.BytesIO(raw), events=("end",))
104
+ for event, elem in context:
105
+ tag = (elem.tag or "").split("}")[-1].upper()
106
+ typ = (elem.attrib.get("TYPE") or "").upper()
107
+ if tag.startswith("DIV") and typ == "SECTION":
108
+ sec = elem.attrib.get("N") or ""
109
+ head, text = _section_text_from_elem(elem)
110
+ if text and len(text) > 20:
111
+ out.append(
112
+ from_ecfr_section(
113
+ title_num=title_num, part=part, section=sec,
114
+ head=head, text=text, source_url=f"{source_url}/section-{sec}", date=date,
115
+ )
116
+ )
117
+ elem.clear()
118
+ elif tag.startswith("DIV") and typ == "PART":
119
+ # if no sections emitted, keep part-level text
120
+ pass
121
+ except ET.ParseError:
122
+ text = xml_to_text(xml_bytes)
123
+ if text:
124
+ out.append(
125
+ from_ecfr_section(
126
+ title_num=title_num, part=part, section="",
127
+ head=f"Part {part}", text=text[:50000], source_url=source_url, date=date,
128
+ )
129
+ )
130
+ if not out:
131
+ text = xml_to_text(xml_bytes)
132
+ if text:
133
+ out.append(
134
+ from_ecfr_section(
135
+ title_num=title_num, part=part, section="",
136
+ head=f"Part {part}", text=text[:50000], source_url=source_url, date=date,
137
+ )
138
+ )
139
+ return out
140
+
141
+
142
+ def collect_ecfr_title_parts(
143
+ sess: PoliteSession,
144
+ title_num: int,
145
+ date: str,
146
+ *,
147
+ seen_add: Callable[[str], bool],
148
+ max_parts: Optional[int] = None,
149
+ max_records: int = 200,
150
+ should_continue: Optional[Callable[[], bool]] = None,
151
+ ) -> List[Dict[str, Any]]:
152
+ parts = list_parts_for_title(sess, date, title_num)
153
+ out: List[Dict[str, Any]] = []
154
+ for i, part in enumerate(parts):
155
+ if max_parts is not None and i >= max_parts:
156
+ break
157
+ if should_continue and not should_continue():
158
+ break
159
+ if len(out) >= max_records:
160
+ break
161
+ r = sess.get(
162
+ f"https://www.ecfr.gov/api/versioner/v1/full/{date}/title-{title_num}.xml",
163
+ params={"part": part},
164
+ )
165
+ if not r or r.status_code != 200 or not r.content:
166
+ # fallback HTML/xml current
167
+ r2 = sess.get(f"https://www.ecfr.gov/current/title-{title_num}/part-{part}.xml")
168
+ if not r2 or r2.status_code != 200:
169
+ continue
170
+ payload = r2.content
171
+ else:
172
+ payload = r.content
173
+ # refuse huge single payloads
174
+ if len(payload) > 8_000_000:
175
+ continue
176
+ for rec in parse_part_xml_sections(payload, title_num, part, date):
177
+ if seen_add(rec["id"]):
178
+ out.append(rec)
179
+ if len(out) >= max_records:
180
+ break
181
+ if should_continue and not should_continue():
182
+ break
183
+ return out
184
+
185
+
186
+ def iter_fr_documents(
187
+ sess: PoliteSession,
188
+ conditions: List[Tuple[str, str]],
189
+ *,
190
+ per_page: int = 100,
191
+ max_pages: int = 10,
192
+ publication_date_gte: Optional[str] = None,
193
+ ) -> Iterable[Dict[str, Any]]:
194
+ for page in range(1, max_pages + 1):
195
+ params: List[Tuple[str, Any]] = [
196
+ ("per_page", per_page), ("page", page), ("order", "newest"),
197
+ ]
198
+ params.extend(conditions)
199
+ if publication_date_gte:
200
+ params.append(("conditions[publication_date][gte]", publication_date_gte))
201
+ for f in FR_FIELDS:
202
+ params.append(("fields[]", f))
203
+ r = sess.get(FR_API, params=params)
204
+ if not r or r.status_code != 200:
205
+ break
206
+ data = r.json() or {}
207
+ results = data.get("results") or []
208
+ if not results:
209
+ break
210
+ for doc in results:
211
+ yield doc
212
+ if page >= int(data.get("total_pages") or page):
213
+ break
214
+
215
+
216
+ def fetch_doc_text(sess: PoliteSession, doc: Dict[str, Any]) -> str:
217
+ xml_url = doc.get("full_text_xml_url")
218
+ if xml_url:
219
+ r = sess.get(xml_url)
220
+ if r and r.status_code == 200 and r.content and len(r.content) < 5_000_000:
221
+ return xml_to_text(r.content)
222
+ raw = doc.get("raw_text_url")
223
+ if raw:
224
+ r = sess.get(raw)
225
+ if r and r.status_code == 200 and r.text and len(r.content) < 5_000_000:
226
+ return r.text.strip()
227
+ body = doc.get("body_html_url")
228
+ if body:
229
+ r = sess.get(body)
230
+ if r and r.status_code == 200 and r.text and len(r.content) < 5_000_000:
231
+ return strip_html(r.text)
232
+ return doc.get("abstract") or ""
233
+
234
+
235
+ def collect_eo(
236
+ sess: PoliteSession,
237
+ seen_add: Callable[[str], bool],
238
+ *,
239
+ max_docs: int = 40,
240
+ kinds: Optional[List[str]] = None,
241
+ ) -> List[Dict[str, Any]]:
242
+ kinds = kinds or ["executive_order", "proclamation", "determination", "memorandum", "notice"]
243
+ out: List[Dict[str, Any]] = []
244
+ for kind in kinds:
245
+ if len(out) >= max_docs:
246
+ break
247
+ for doc in iter_fr_documents(
248
+ sess,
249
+ [("conditions[type][]", "PRESDOCU"), ("conditions[presidential_document_type][]", kind)],
250
+ per_page=min(100, max_docs - len(out)),
251
+ max_pages=3,
252
+ ):
253
+ text = fetch_doc_text(sess, doc)
254
+ rec = from_federal_register_doc(doc, text, gap_target_id="ARE-US-EO",
255
+ target_hf_repo="justicedao/ipfs_us_executive_orders")
256
+ if seen_add(rec["id"]):
257
+ out.append(rec)
258
+ if len(out) >= max_docs:
259
+ break
260
+ return out
261
+
262
+
263
+ def collect_fr_after(
264
+ sess: PoliteSession,
265
+ seen_add: Callable[[str], bool],
266
+ *,
267
+ gte: str = "2026-07-01",
268
+ max_docs: int = 40,
269
+ types: Optional[List[str]] = None,
270
+ ) -> List[Dict[str, Any]]:
271
+ types = types or ["RULE", "PRORULE", "NOTICE"]
272
+ out: List[Dict[str, Any]] = []
273
+ for t in types:
274
+ if len(out) >= max_docs:
275
+ break
276
+ for doc in iter_fr_documents(
277
+ sess,
278
+ [("conditions[type][]", t)],
279
+ per_page=min(100, max_docs - len(out)),
280
+ max_pages=2,
281
+ publication_date_gte=gte,
282
+ ):
283
+ text = fetch_doc_text(sess, doc)
284
+ rec = from_federal_register_doc(doc, text, gap_target_id="ARE-US-FR",
285
+ target_hf_repo="justicedao/ipfs_federal_register")
286
+ if seen_add(rec["id"]):
287
+ out.append(rec)
288
+ if len(out) >= max_docs:
289
+ break
290
+ return out
scrapers_and_normalizers/gap_queue.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load US items from world_complete_gap_matrix bot_work_queues.admin_rules_eo_scraper."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ MATRIX = Path("/workspace/world_complete_gap_matrix_20261105.json")
9
+ US_LANES = {"us_federal_admin_eo", "us_state_admin_and_eo", "us_local_admin_and_eo"}
10
+
11
+
12
+ def load_us_queue() -> List[Dict[str, Any]]:
13
+ data = json.loads(MATRIX.read_text(encoding="utf-8"))
14
+ q = data["bot_work_queues"]["admin_rules_eo_scraper"]
15
+ us = [it for it in q if it.get("lane") in US_LANES or str(it.get("target_id", "")).startswith("ARE-US-")]
16
+ us.sort(key=lambda x: int(x.get("priority_rank") or 9999))
17
+ return us
18
+
19
+
20
+ def state_code_from_target(target_id: str) -> str | None:
21
+ # ARE-US-OH-ADMIN-EO -> OH
22
+ parts = target_id.split("-")
23
+ if len(parts) >= 4 and parts[0] == "ARE" and parts[1] == "US" and parts[-2] == "ADMIN":
24
+ return parts[2]
25
+ return None
scrapers_and_normalizers/io_zst.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Append-only .jsonl.zst writer + SeenIds + pause-capable memguard."""
2
+ from __future__ import annotations
3
+
4
+ import gc
5
+ import json
6
+ import os
7
+ import time
8
+ from pathlib import Path
9
+ from typing import Any, Optional, Set
10
+
11
+ import zstandard as zstd
12
+
13
+ from normalizer import dumps_line
14
+
15
+
16
+ class JsonlZstWriter:
17
+ def __init__(self, path: str | Path, level: int = 3):
18
+ self.path = Path(path)
19
+ self.path.parent.mkdir(parents=True, exist_ok=True)
20
+ self._fh = open(self.path, "ab")
21
+ self._cctx = zstd.ZstdCompressor(level=level)
22
+ self.count = 0
23
+
24
+ def write(self, rec: dict) -> None:
25
+ line = (dumps_line(rec) + "\n").encode("utf-8")
26
+ self._fh.write(self._cctx.compress(line))
27
+ self.count += 1
28
+ if self.count % 20 == 0:
29
+ self._fh.flush()
30
+
31
+ def flush(self) -> None:
32
+ self._fh.flush()
33
+
34
+ def close(self) -> None:
35
+ try:
36
+ self._fh.flush()
37
+ finally:
38
+ self._fh.close()
39
+
40
+ def __enter__(self):
41
+ return self
42
+
43
+ def __exit__(self, *exc):
44
+ self.close()
45
+
46
+
47
+ def write_json(path: str | Path, obj: Any) -> None:
48
+ p = Path(path)
49
+ p.parent.mkdir(parents=True, exist_ok=True)
50
+ tmp = p.with_suffix(p.suffix + ".tmp")
51
+ tmp.write_text(json.dumps(obj, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
52
+ os.replace(tmp, p)
53
+
54
+
55
+ def load_json(path: str | Path, default: Any = None) -> Any:
56
+ p = Path(path)
57
+ if not p.exists():
58
+ return default
59
+ return json.loads(p.read_text(encoding="utf-8"))
60
+
61
+
62
+ def mem_available_bytes() -> int:
63
+ with open("/proc/meminfo") as f:
64
+ for line in f:
65
+ if line.startswith("MemAvailable:"):
66
+ return int(line.split()[1]) * 1024
67
+ return 0
68
+
69
+
70
+ def process_rss_bytes() -> int:
71
+ with open("/proc/self/status") as f:
72
+ for line in f:
73
+ if line.startswith("VmRSS:"):
74
+ return int(line.split()[1]) * 1024
75
+ return 0
76
+
77
+
78
+ def disk_free_bytes(path: str = "/workspace") -> int:
79
+ st = os.statvfs(path)
80
+ return st.f_bavail * st.f_frsize
81
+
82
+
83
+ class MemGuard:
84
+ MEM_FLOOR = 4_509_715_660 # 4.2 GiB — pause below
85
+ MEM_RESUME = 4_670_881_382 # 4.35 GiB — resume at/above
86
+ DISK_FLOOR = 10 * 1024 ** 3
87
+ RSS_REEXEC = 500 * 1024 ** 2 # re-exec above 500 MiB
88
+ RSS_CEILING = 550 * 1024 ** 2
89
+
90
+ def __init__(self, check_every_items: int = 5, check_every_seconds: float = 10.0):
91
+ self.check_every_items = check_every_items
92
+ self.check_every_seconds = check_every_seconds
93
+ self._n = 0
94
+ self._last = 0.0
95
+ self.stop_reason: Optional[str] = None
96
+ self.need_pause = False
97
+ self.need_reexec = False
98
+ self.need_exit = False
99
+
100
+ def evaluate(self) -> str:
101
+ """Return 'ok' | 'pause' | 'reexec' | 'exit_disk'."""
102
+ mem = mem_available_bytes()
103
+ disk = disk_free_bytes()
104
+ rss = process_rss_bytes()
105
+ if disk < self.DISK_FLOOR:
106
+ self.need_exit = True
107
+ self.stop_reason = f"disk_stop free={disk} < {self.DISK_FLOOR}"
108
+ return "exit_disk"
109
+ if rss > self.RSS_REEXEC:
110
+ self.need_reexec = True
111
+ self.stop_reason = f"rss_reexec rss={rss} > {self.RSS_REEXEC}"
112
+ return "reexec"
113
+ if mem < self.MEM_FLOOR:
114
+ self.need_pause = True
115
+ self.stop_reason = f"paused_low_mem MemAvailable={mem} < {self.MEM_FLOOR}"
116
+ return "pause"
117
+ self.need_pause = False
118
+ return "ok"
119
+
120
+ def tick(self, items: int = 1) -> str:
121
+ self._n += items
122
+ now = time.time()
123
+ if self._n < self.check_every_items and (now - self._last) < self.check_every_seconds:
124
+ return "ok"
125
+ self._n = 0
126
+ self._last = now
127
+ return self.evaluate()
128
+
129
+ @classmethod
130
+ def wait_until_resume(cls, log_fn=None, status_fn=None, stop_flag=None) -> bool:
131
+ """Sleep in low-RSS loop until MemAvailable >= MEM_RESUME or stop. Return True if resumed."""
132
+ while True:
133
+ if stop_flag and stop_flag():
134
+ return False
135
+ mem = mem_available_bytes()
136
+ disk = disk_free_bytes()
137
+ if disk < cls.DISK_FLOOR:
138
+ if log_fn:
139
+ log_fn(f"DISK_EXIT during pause free={disk}")
140
+ return False
141
+ if mem >= cls.MEM_RESUME:
142
+ gc.collect()
143
+ if log_fn:
144
+ log_fn(f"RESUME MemAvailable={mem} >= {cls.MEM_RESUME}")
145
+ return True
146
+ if status_fn:
147
+ status_fn(state="paused_low_mem", mem_available_bytes=mem)
148
+ if log_fn:
149
+ log_fn(f"HIBERNATE MemAvailable={mem} < {cls.MEM_RESUME}; sleep 30s")
150
+ gc.collect()
151
+ time.sleep(30)
152
+
153
+
154
+ class SeenIds:
155
+ def __init__(self, path: str | Path, max_keep: int = 500_000):
156
+ self.path = Path(path)
157
+ self.max_keep = max_keep
158
+ self.ids: Set[str] = set()
159
+ self._dirty = 0
160
+ if self.path.exists():
161
+ try:
162
+ data = json.loads(self.path.read_text(encoding="utf-8"))
163
+ self.ids = set(data.get("ids") or [])
164
+ except Exception:
165
+ for line in self.path.read_text(encoding="utf-8", errors="replace").splitlines():
166
+ line = line.strip()
167
+ if line and not line.startswith("{"):
168
+ self.ids.add(line)
169
+
170
+ def __contains__(self, rid: str) -> bool:
171
+ return rid in self.ids
172
+
173
+ def add(self, rid: str) -> bool:
174
+ if rid in self.ids:
175
+ return False
176
+ self.ids.add(rid)
177
+ self._dirty += 1
178
+ if self._dirty >= 40:
179
+ self.flush()
180
+ return True
181
+
182
+ def flush(self) -> None:
183
+ ids = sorted(self.ids)
184
+ if len(ids) > self.max_keep:
185
+ ids = ids[-self.max_keep :]
186
+ self.ids = set(ids)
187
+ write_json(self.path, {"ids": ids, "count": len(ids), "updated_at": time.time()})
188
+ self._dirty = 0
189
+
190
+
191
+ def load_ids_from_zst(path: Path, seen: SeenIds) -> int:
192
+ if not path.exists():
193
+ return 0
194
+ n = 0
195
+ try:
196
+ with zstd.ZstdDecompressor().stream_reader(open(path, "rb")) as r:
197
+ text = r.read().decode("utf-8", errors="replace")
198
+ for line in text.splitlines():
199
+ if not line.strip():
200
+ continue
201
+ try:
202
+ o = json.loads(line)
203
+ except Exception:
204
+ continue
205
+ rid = o.get("id")
206
+ if rid and rid not in seen.ids:
207
+ seen.ids.add(rid)
208
+ n += 1
209
+ except Exception:
210
+ return n
211
+ return n
scrapers_and_normalizers/municipal_collector.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ARE-US-COUNTY-MUNICIPAL-ADMIN-EO — keyless municipal/county admin rules & mayoral EOs."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from typing import Any, Callable, Dict, List, Optional, Tuple
6
+
7
+ import requests
8
+ from bs4 import BeautifulSoup
9
+
10
+ from normalizer import base_record, strip_html
11
+
12
+ UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
13
+ TARGET = "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO"
14
+ HF = "justicedao/ipfs_us_executive_orders"
15
+
16
+ PORTALS = [
17
+ {"locality": "New York City", "state": "NY", "url": "https://rules.cityofnewyork.us/", "kind": "admin_rules"},
18
+ {"locality": "New York City", "state": "NY",
19
+ "url": "https://www.nyc.gov/office-of-the-mayor/news/executive-orders.page", "kind": "mayoral_eo"},
20
+ {"locality": "San Francisco", "state": "CA",
21
+ "url": "https://sf.gov/resource/2022/mayoral-executive-directives", "kind": "mayoral_eo"},
22
+ {"locality": "Chicago", "state": "IL",
23
+ "url": "https://www.chicago.gov/city/en/depts/mayor/press_room/executive-orders.html", "kind": "mayoral_eo"},
24
+ {"locality": "Los Angeles", "state": "CA",
25
+ "url": "https://mayor.lacity.gov/executive-directives", "kind": "mayoral_eo"},
26
+ {"locality": "Philadelphia", "state": "PA",
27
+ "url": "https://www.phila.gov/departments/mayor/executive-orders/", "kind": "mayoral_eo"},
28
+ {"locality": "Washington", "state": "DC",
29
+ "url": "https://mayor.dc.gov/mayor-orders", "kind": "mayoral_eo"},
30
+ {"locality": "King County", "state": "WA",
31
+ "url": "https://kingcounty.gov/en/legacy/council/legislation/kc_code.aspx", "kind": "county_code"},
32
+ {"locality": "Cook County", "state": "IL",
33
+ "url": "https://www.cookcountyil.gov/agency/board-commissioners", "kind": "county"},
34
+ ]
35
+
36
+
37
+ class PoliteSession:
38
+ def __init__(self, delay: float = 1.0):
39
+ self.s = requests.Session()
40
+ self.s.headers["User-Agent"] = UA
41
+ self.s.verify = True
42
+ self.delay = delay
43
+ self._last = 0.0
44
+
45
+ def get(self, url: str) -> Tuple[Optional[requests.Response], Optional[str]]:
46
+ wait = self.delay - (time.time() - self._last)
47
+ if wait > 0:
48
+ time.sleep(wait)
49
+ try:
50
+ r = self.s.get(url, timeout=45, verify=True)
51
+ except requests.RequestException as e:
52
+ self._last = time.time()
53
+ return None, f"net_error:{e.__class__.__name__}"
54
+ self._last = time.time()
55
+ low = (r.text or "")[:4000].lower()
56
+ if r.status_code in (403, 429, 503) or "just a moment" in low or "captcha" in low:
57
+ return r, "blocked_waf"
58
+ if r.status_code != 200:
59
+ return r, f"http_{r.status_code}"
60
+ return r, None
61
+
62
+
63
+ def collect_municipal(
64
+ sess: PoliteSession,
65
+ seen_add: Callable[[str], bool],
66
+ *,
67
+ max_records: int = 30,
68
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
69
+ out: List[Dict[str, Any]] = []
70
+ manifest: List[Dict[str, Any]] = []
71
+ for p in PORTALS:
72
+ if len(out) >= max_records:
73
+ break
74
+ r, flag = sess.get(p["url"])
75
+ entry = {**p, "status": flag or ("ok" if r else "fetch_failed"),
76
+ "http_status": getattr(r, "status_code", None)}
77
+ manifest.append(entry)
78
+ if not r or flag:
79
+ # status stub
80
+ rec = base_record(
81
+ gap_target_id=TARGET, jurisdiction=f"US-{p['state']}-{p['locality'][:12]}",
82
+ subdivision_level="municipal" if "County" not in p["locality"] else "county",
83
+ document_type="portal_status", title=f"{p['locality']} portal {entry['status']}",
84
+ text=f"status={entry['status']} url={p['url']}", source_url=p["url"],
85
+ state_or_province=p["state"], locality=p["locality"],
86
+ target_hf_repo=HF, extra={"portal_kind": p["kind"], "portal_status": entry["status"]},
87
+ )
88
+ if seen_add(rec["id"]):
89
+ out.append(rec)
90
+ continue
91
+ soup = BeautifulSoup(r.text, "html.parser")
92
+ title = soup.title.get_text(" ", strip=True) if soup.title else p["locality"]
93
+ text = soup.get_text("\n", strip=True)[:10000]
94
+ dtype = "mayoral_eo" if p["kind"] == "mayoral_eo" else "municipal_admin_rules"
95
+ rec = base_record(
96
+ gap_target_id=TARGET, jurisdiction=f"US-{p['state']}",
97
+ subdivision_level="municipal" if "County" not in p["locality"] else "county",
98
+ document_type=dtype, title=title, text=text, source_url=p["url"],
99
+ state_or_province=p["state"], locality=p["locality"],
100
+ target_hf_repo=HF, extra={"portal_kind": p["kind"]},
101
+ )
102
+ if seen_add(rec["id"]):
103
+ out.append(rec)
104
+ # follow a few same-host links that look like EO/order docs
105
+ host = p["url"].split("/")[2]
106
+ followed = 0
107
+ for a in soup.select("a[href]"):
108
+ if followed >= 3 or len(out) >= max_records:
109
+ break
110
+ href = a.get("href") or ""
111
+ if href.startswith("/"):
112
+ href = p["url"].rstrip("/") + "/" + href.lstrip("/") if "://" not in href else href
113
+ # fix double
114
+ if href.startswith("/"):
115
+ href = "https://" + host + href
116
+ if host not in href:
117
+ continue
118
+ low = href.lower()
119
+ if not any(k in low for k in ("executive", "order", "eo-", "directive", "rule")):
120
+ continue
121
+ r2, f2 = sess.get(href)
122
+ if not r2 or f2:
123
+ continue
124
+ t2 = strip_html(r2.text)[:12000]
125
+ if len(t2) < 80:
126
+ continue
127
+ rec2 = base_record(
128
+ gap_target_id=TARGET, jurisdiction=f"US-{p['state']}",
129
+ subdivision_level="municipal", document_type=dtype,
130
+ title=(a.get_text(" ", strip=True) or href)[:200], text=t2, source_url=href,
131
+ state_or_province=p["state"], locality=p["locality"], target_hf_repo=HF,
132
+ )
133
+ if seen_add(rec2["id"]):
134
+ out.append(rec2)
135
+ followed += 1
136
+ return out, manifest
scrapers_and_normalizers/normalizer.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalize US admin-rule / EO / FR / eCFR rows into a shared schema with gap_target_id."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Dict, Optional
9
+ from xml.etree import ElementTree as ET
10
+
11
+ SCHEMA_VERSION = "us_admin_rules_eo_normalized_v2"
12
+
13
+
14
+ def utc_now() -> str:
15
+ return datetime.now(timezone.utc).isoformat()
16
+
17
+
18
+ def sha256_text(text: str) -> str:
19
+ return hashlib.sha256((text or "").encode("utf-8", errors="replace")).hexdigest()
20
+
21
+
22
+ def make_id(*parts: str) -> str:
23
+ return sha256_text("|".join(p or "" for p in parts))
24
+
25
+
26
+ def strip_html(html: str) -> str:
27
+ if not html:
28
+ return ""
29
+ text = re.sub(r"(?is)<script[^>]*>.*?</script>", " ", html)
30
+ text = re.sub(r"(?is)<style[^>]*>.*?</style>", " ", text)
31
+ text = re.sub(r"(?s)<[^>]+>", " ", text)
32
+ text = re.sub(r"&nbsp;", " ", text)
33
+ text = re.sub(r"&amp;", "&", text)
34
+ text = re.sub(r"&lt;", "<", text)
35
+ text = re.sub(r"&gt;", ">", text)
36
+ return re.sub(r"\s+", " ", text).strip()
37
+
38
+
39
+ def xml_to_text(xml_bytes: bytes | str) -> str:
40
+ if isinstance(xml_bytes, bytes):
41
+ raw = xml_bytes.decode("utf-8", errors="replace")
42
+ else:
43
+ raw = xml_bytes
44
+ try:
45
+ root = ET.fromstring(raw)
46
+ except ET.ParseError:
47
+ return strip_html(raw)
48
+ chunks: list[str] = []
49
+ for el in root.iter():
50
+ if el.text and el.text.strip():
51
+ chunks.append(el.text.strip())
52
+ if el.tail and el.tail.strip():
53
+ chunks.append(el.tail.strip())
54
+ return re.sub(r"\s+", " ", " ".join(chunks)).strip()
55
+
56
+
57
+ def base_record(
58
+ *,
59
+ gap_target_id: str,
60
+ jurisdiction: str,
61
+ subdivision_level: str,
62
+ document_type: str,
63
+ title: str,
64
+ text: str,
65
+ source_url: str,
66
+ citation: Optional[str] = None,
67
+ agency: Optional[str] = None,
68
+ state_or_province: Optional[str] = None,
69
+ locality: Optional[str] = None,
70
+ effective_date: Optional[str] = None,
71
+ published_date: Optional[str] = None,
72
+ transport: str = "https",
73
+ archive_source: Optional[str] = None,
74
+ scraped_at: Optional[str] = None,
75
+ extra: Optional[Dict[str, Any]] = None,
76
+ target_hf_repo: Optional[str] = None,
77
+ ) -> Dict[str, Any]:
78
+ text = (text or "").strip()
79
+ content_hash = sha256_text(text)
80
+ rid = make_id(gap_target_id, jurisdiction, document_type, citation or "", source_url, content_hash[:16])
81
+ return {
82
+ "id": rid,
83
+ "gap_target_id": gap_target_id,
84
+ "schema_version": SCHEMA_VERSION,
85
+ "jurisdiction": jurisdiction,
86
+ "subdivision_level": subdivision_level,
87
+ "country": "US",
88
+ "state_or_province": state_or_province,
89
+ "locality": locality,
90
+ "document_type": document_type,
91
+ "agency": agency,
92
+ "citation": citation,
93
+ "title": title,
94
+ "text": text,
95
+ "effective_date": effective_date,
96
+ "published_date": published_date,
97
+ "source_url": source_url,
98
+ "transport": transport,
99
+ "archive_source": archive_source,
100
+ "scraped_at": scraped_at or utc_now(),
101
+ "content_hash": content_hash,
102
+ "target_hf_repo": target_hf_repo,
103
+ "extra": extra or {},
104
+ }
105
+
106
+
107
+ def from_oh_official_row(row: Dict[str, Any], gap_target_id: str = "ARE-US-OH-ADMIN-EO",
108
+ target_hf_repo: str = "justicedao/ipfs_state_admin_rules") -> Dict[str, Any]:
109
+ return base_record(
110
+ gap_target_id=gap_target_id,
111
+ jurisdiction=f"US-{row.get('state') or 'OH'}",
112
+ subdivision_level="state",
113
+ document_type="admin_rule",
114
+ title=row.get("title") or "",
115
+ text=row.get("text") or "",
116
+ source_url=row.get("source_url") or "",
117
+ citation=row.get("citation"),
118
+ state_or_province=row.get("state") or "OH",
119
+ transport=row.get("transport") or "https",
120
+ scraped_at=row.get("fetched_at"),
121
+ target_hf_repo=target_hf_repo,
122
+ extra={"legacy_sha256": row.get("sha256")},
123
+ )
124
+
125
+
126
+ def from_federal_register_doc(doc: Dict[str, Any], text: str, gap_target_id: str,
127
+ target_hf_repo: Optional[str] = None) -> Dict[str, Any]:
128
+ subtype = (doc.get("subtype") or "").strip()
129
+ ptype = (doc.get("type") or "").strip()
130
+ if gap_target_id == "ARE-US-EO" or subtype.lower() == "executive order" or doc.get("executive_order_number"):
131
+ if "proclamation" in subtype.lower():
132
+ document_type = "proclamation"
133
+ elif "determination" in subtype.lower():
134
+ document_type = "determination"
135
+ elif "memorandum" in subtype.lower():
136
+ document_type = "memorandum"
137
+ elif "administrative" in subtype.lower():
138
+ document_type = "administrative_order"
139
+ elif gap_target_id == "ARE-US-EO" and subtype:
140
+ document_type = subtype.lower().replace(" ", "_")
141
+ else:
142
+ document_type = "executive_order"
143
+ elif ptype == "Rule":
144
+ document_type = "rule"
145
+ elif ptype == "Proposed Rule":
146
+ document_type = "proposed_rule"
147
+ elif ptype == "Notice":
148
+ document_type = "register_notice"
149
+ else:
150
+ document_type = (ptype or "register_document").lower().replace(" ", "_")
151
+
152
+ agencies = doc.get("agencies") or []
153
+ agency = None
154
+ if agencies and isinstance(agencies[0], dict):
155
+ agency = agencies[0].get("name") or agencies[0].get("raw_name")
156
+ elif agencies and isinstance(agencies[0], str):
157
+ agency = agencies[0]
158
+
159
+ citation = doc.get("citation")
160
+ if document_type == "executive_order" and doc.get("executive_order_number"):
161
+ citation = citation or f"E.O. {doc['executive_order_number']}"
162
+
163
+ if not target_hf_repo:
164
+ target_hf_repo = (
165
+ "justicedao/ipfs_us_executive_orders" if gap_target_id == "ARE-US-EO"
166
+ else "justicedao/ipfs_federal_register"
167
+ )
168
+
169
+ return base_record(
170
+ gap_target_id=gap_target_id,
171
+ jurisdiction="US-FEDERAL",
172
+ subdivision_level="federal",
173
+ document_type=document_type,
174
+ title=doc.get("title") or "",
175
+ text=text or (doc.get("abstract") or ""),
176
+ source_url=doc.get("html_url") or doc.get("body_html_url") or "",
177
+ citation=citation,
178
+ agency=agency,
179
+ published_date=doc.get("publication_date"),
180
+ transport="https",
181
+ target_hf_repo=target_hf_repo,
182
+ extra={
183
+ "document_number": doc.get("document_number"),
184
+ "presidential_document_number": doc.get("presidential_document_number"),
185
+ "executive_order_number": doc.get("executive_order_number"),
186
+ "subtype": subtype,
187
+ "full_text_xml_url": doc.get("full_text_xml_url"),
188
+ "body_html_url": doc.get("body_html_url"),
189
+ "raw_text_url": doc.get("raw_text_url"),
190
+ },
191
+ )
192
+
193
+
194
+ def from_ecfr_section(*, title_num: int, part: str, section: str, head: str, text: str,
195
+ source_url: str, date: str) -> Dict[str, Any]:
196
+ citation = f"{title_num} CFR § {section}" if section else f"{title_num} CFR Part {part}"
197
+ return base_record(
198
+ gap_target_id="ARE-US-ECFR",
199
+ jurisdiction="US-FEDERAL",
200
+ subdivision_level="federal",
201
+ document_type="ecfr_section" if section else "ecfr_part",
202
+ title=head or citation,
203
+ text=text,
204
+ source_url=source_url,
205
+ citation=citation,
206
+ published_date=date,
207
+ transport="https",
208
+ target_hf_repo="justicedao/ipfs_us_cfr",
209
+ extra={"ecfr_title": title_num, "ecfr_part": part, "ecfr_section": section, "as_of": date},
210
+ )
211
+
212
+
213
+ def dumps_line(rec: Dict[str, Any]) -> str:
214
+ return json.dumps(rec, ensure_ascii=False, separators=(",", ":"))
scrapers_and_normalizers/schema.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "us_admin_rules_eo_normalized_v2",
3
+ "required_fields": ["id", "gap_target_id", "jurisdiction", "subdivision_level", "country", "document_type", "title", "text", "source_url", "transport", "scraped_at", "content_hash"],
4
+ "gap_target_ids": ["ARE-US-ECFR", "ARE-US-FR", "ARE-US-EO", "ARE-US-*-ADMIN-EO", "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO"],
5
+ "dedupe": "persistent SeenIds checkpoint; skip emitted id on restart",
6
+ "memguard": {"MemAvailable_floor_bytes": 4509715660, "disk_floor_bytes": 10737418240, "rss_ceiling_bytes": 576716800}
7
+ }
scrapers_and_normalizers/seeds.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Load verified US seeds from world_admin_eo_seeds_20261105.jsonl."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Optional, Tuple
8
+ from urllib.parse import urlparse
9
+
10
+ SEEDS_PATH = Path("/workspace/coverage/world_admin_eo_seeds_20261105.jsonl")
11
+ WAYBACK_RE = re.compile(r"^https?://web\.archive\.org/web/\d+(?:id_)?/(https?://.*)$", re.I)
12
+
13
+
14
+ def unwrap_wayback(url: str) -> Tuple[str, bool]:
15
+ """Return (live_or_original_url, was_wayback)."""
16
+ m = WAYBACK_RE.match(url or "")
17
+ if m:
18
+ return m.group(1), True
19
+ return url, False
20
+
21
+
22
+ def load_us_seeds() -> List[Dict[str, Any]]:
23
+ rows = []
24
+ for line in SEEDS_PATH.read_text(encoding="utf-8").splitlines():
25
+ if not line.strip():
26
+ continue
27
+ o = json.loads(line)
28
+ if str(o.get("target_id", "")).startswith("ARE-US-"):
29
+ rows.append(o)
30
+ # preserve file order (matches gap matrix priority)
31
+ return rows
32
+
33
+
34
+ def seed_urls_by_role(seed: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
35
+ out: Dict[str, List[Dict[str, Any]]] = {}
36
+ for u in seed.get("urls") or []:
37
+ role = u.get("role") or "unknown"
38
+ out.setdefault(role, []).append(u)
39
+ return out
40
+
41
+
42
+ def preferred_fetch_urls(seed: Dict[str, Any], role: str) -> List[Tuple[str, Optional[str]]]:
43
+ """Return ordered (url, archive_source) pairs: live first, then wayback fallbacks.
44
+
45
+ archive_source is None for live official; 'wayback' for archive.org URLs.
46
+ """
47
+ roles = seed_urls_by_role(seed)
48
+ entries = roles.get(role) or []
49
+ live: List[Tuple[str, Optional[str]]] = []
50
+ wb: List[Tuple[str, Optional[str]]] = []
51
+ seen = set()
52
+ for e in entries:
53
+ raw = e.get("url") or ""
54
+ orig, was_wb = unwrap_wayback(raw)
55
+ if orig not in seen:
56
+ live.append((orig, None))
57
+ seen.add(orig)
58
+ if was_wb and raw not in seen:
59
+ wb.append((raw, "wayback"))
60
+ seen.add(raw)
61
+ elif not was_wb:
62
+ # also keep raw if somehow different
63
+ pass
64
+ # Extra live candidates for hard states
65
+ tid = seed.get("target_id") or ""
66
+ extras = {
67
+ "ARE-US-IN-ADMIN-EO": [
68
+ "https://iga.in.gov/laws/iac",
69
+ "https://iar.iga.in.gov/iac/irtoc.htm",
70
+ "https://iar.iga.in.gov/code/current",
71
+ ],
72
+ "ARE-US-NH-ADMIN-EO": [
73
+ "https://gc.nh.gov/rules/",
74
+ "https://gc.nh.gov/rules/about_rules/listagencies.aspx",
75
+ "https://www.gencourt.state.nh.us/rules/",
76
+ ],
77
+ "ARE-US-TN-ADMIN-EO": [
78
+ "https://publications.tnsosfiles.com/rules/",
79
+ "https://sos.tn.gov/publications/services/effective-rules-and-regulations-of-the-state-of-tennessee",
80
+ ],
81
+ "ARE-US-WY-ADMIN-EO": [
82
+ "https://rules.wyo.gov/",
83
+ "https://rules.wyo.gov/Search.aspx",
84
+ "https://rules.wyo.gov/Search.aspx?mode=7",
85
+ ],
86
+ }
87
+ if role == "admin_code":
88
+ pref=[]
89
+ for u in extras.get(tid, []):
90
+ if u not in seen:
91
+ pref.append((u, None))
92
+ seen.add(u)
93
+ live = pref + live
94
+ return live + wb
95
+
96
+
97
+ def state_code_from_target(target_id: str) -> Optional[str]:
98
+ parts = target_id.split("-")
99
+ if len(parts) >= 4 and parts[0] == "ARE" and parts[1] == "US" and parts[-2] == "ADMIN":
100
+ return parts[2]
101
+ return None
scrapers_and_normalizers/state_admin_collector.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deep US state/territory admin-code + governor EO crawler (seed-driven).
2
+
3
+ Uses /workspace/coverage/world_admin_eo_seeds_20261105.jsonl verified portals.
4
+ Live official URLs first; Wayback only if live fails (archive_source=wayback).
5
+ Extracts multiple substantive rule/EO pages per cycle via URL frontier checkpoints.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ import time
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
16
+ from urllib.parse import urljoin, urlparse
17
+
18
+ import requests
19
+ from bs4 import BeautifulSoup
20
+
21
+ from normalizer import base_record, from_oh_official_row, strip_html
22
+ from seeds import preferred_fetch_urls, state_code_from_target, unwrap_wayback
23
+
24
+ UA = "AdminRulesEOScraper/1.0 (+research; keyless; contact via justicedao HF)"
25
+ OH_BASE = "https://codes.ohio.gov"
26
+ OH_ROWS = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/OH.official/rows.jsonl")
27
+ OH_CURSOR = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/_collector/oh_agency_cursor.json")
28
+ FRONTIER_DIR = Path("/workspace/legal-corpora/us_state_admin_rules_20261104/_collector/frontiers")
29
+ STATE_ROOT = Path("/workspace/legal-corpora/us_state_admin_rules_20261104")
30
+ EO_ROOT = Path("/workspace/legal-corpora/us_executive_orders_20261105")
31
+
32
+ RULE_HINTS = re.compile(
33
+ r"(rule|rules|regulation|admin.?code|chapter|title|section|csr|nac|wac|oac|iac|kar|njac|comar|tar)",
34
+ re.I,
35
+ )
36
+ EO_HINTS = re.compile(r"(executive.?order|exec.?order|\beo\b|proclamation|directive|governor)", re.I)
37
+ NAV_NOISE = re.compile(r"(login|signin|cart|facebook|twitter|linkedin|instagram|javascript:|#)$", re.I)
38
+
39
+
40
+ class PoliteSession:
41
+ def __init__(self, delay: float = 0.9):
42
+ self.s = requests.Session()
43
+ self.s.headers["User-Agent"] = UA
44
+ self.s.verify = True
45
+ self.delay = delay
46
+ self._last = 0.0
47
+ self.n = 0
48
+
49
+ def get(self, url: str) -> Tuple[Optional[requests.Response], Optional[str]]:
50
+ wait = self.delay - (time.time() - self._last)
51
+ if wait > 0:
52
+ time.sleep(wait)
53
+ try:
54
+ r = self.s.get(url, timeout=45, verify=True, allow_redirects=True)
55
+ except requests.RequestException as e:
56
+ self._last = time.time()
57
+ return None, f"net_error:{e.__class__.__name__}"
58
+ self._last = time.time()
59
+ self.n += 1
60
+ low = (r.text or "")[:5000].lower()
61
+ if r.status_code in (403, 429, 503) or "cf-challenge" in low or "just a moment" in low or "captcha" in low:
62
+ return r, "blocked_waf"
63
+ if r.status_code != 200:
64
+ return r, f"http_{r.status_code}"
65
+ return r, None
66
+
67
+
68
+ def wayback_closest(sess: PoliteSession, url: str) -> Tuple[Optional[str], Optional[requests.Response]]:
69
+ api = f"https://archive.org/wayback/available?url={url}"
70
+ r, flag = sess.get(api)
71
+ if not r or flag:
72
+ return None, None
73
+ try:
74
+ snap = (((r.json() or {}).get("archived_snapshots") or {}).get("closest") or {})
75
+ wu = snap.get("url")
76
+ except Exception:
77
+ return None, None
78
+ if not wu:
79
+ return None, None
80
+ r2, flag2 = sess.get(wu)
81
+ if not r2 or flag2:
82
+ return wu, None
83
+ return wu, r2
84
+
85
+
86
+ def fetch_with_fallback(
87
+ sess: PoliteSession, candidates: List[Tuple[str, Optional[str]]]
88
+ ) -> Tuple[Optional[requests.Response], str, Optional[str], Optional[str]]:
89
+ """Try live URLs then wayback. Returns (resp, final_url, archive_source, status)."""
90
+ last_status = "no_candidates"
91
+ for url, arch in candidates:
92
+ r, flag = sess.get(url)
93
+ if r and not flag:
94
+ return r, url, arch, "ok"
95
+ last_status = flag or "fetch_failed"
96
+ if flag == "blocked_waf" or (r and r.status_code in (403, 401, 404, 500)):
97
+ # try wayback of the live URL
98
+ live, _ = unwrap_wayback(url)
99
+ wu, wr = wayback_closest(sess, live)
100
+ if wr:
101
+ return wr, wu or url, "wayback", "ok_wayback"
102
+ return None, "", None, last_status
103
+
104
+
105
+ def _same_site(base: str, href: str) -> bool:
106
+ try:
107
+ b = urlparse(base).netloc.lower().lstrip("www.")
108
+ h = urlparse(href).netloc.lower().lstrip("www.")
109
+ return bool(h) and (h == b or h.endswith("." + b) or b.endswith("." + h))
110
+ except Exception:
111
+ return False
112
+
113
+
114
+ def extract_links(base_url: str, html: str, kind: str) -> List[str]:
115
+ soup = BeautifulSoup(html, "html.parser")
116
+ out: List[str] = []
117
+ for a in soup.select("a[href]"):
118
+ href = (a.get("href") or "").strip()
119
+ if not href or href.startswith("mailto:") or NAV_NOISE.search(href):
120
+ continue
121
+ full = urljoin(base_url, href)
122
+ if full.startswith("//"):
123
+ full = "https:" + full
124
+ if not full.startswith("http"):
125
+ continue
126
+ if not _same_site(base_url, full):
127
+ continue
128
+ text = (a.get_text(" ", strip=True) or "") + " " + full
129
+ if kind == "admin" and not RULE_HINTS.search(text) and not RULE_HINTS.search(full):
130
+ # still allow .pdf/.htm rule-ish paths
131
+ if not re.search(r"\.(pdf|html?|aspx?)$", full, re.I):
132
+ continue
133
+ if kind == "eo" and not EO_HINTS.search(text) and not EO_HINTS.search(full):
134
+ if not re.search(r"\.(pdf|html?|aspx?)$", full, re.I):
135
+ continue
136
+ out.append(full.split("#")[0])
137
+ # dedupe preserve order
138
+ return list(dict.fromkeys(out))
139
+
140
+
141
+ def is_substantive(text: str, title: str = "") -> bool:
142
+ t = (text or "").strip()
143
+ if len(t) < 400:
144
+ return False
145
+ # reject thin nav shells
146
+ low = t.lower()
147
+ nav_marks = sum(1 for k in ("home", "contact us", "privacy", "accessibility", "skip to") if k in low[:800])
148
+ if nav_marks >= 3 and len(t) < 1200:
149
+ return False
150
+ return True
151
+
152
+
153
+ def frontier_path(target_id: str) -> Path:
154
+ FRONTIER_DIR.mkdir(parents=True, exist_ok=True)
155
+ safe = re.sub(r"[^A-Za-z0-9_\-]", "_", target_id)
156
+ return FRONTIER_DIR / f"{safe}.json"
157
+
158
+
159
+ def load_frontier(target_id: str) -> Dict[str, Any]:
160
+ p = frontier_path(target_id)
161
+ if p.exists():
162
+ try:
163
+ return json.loads(p.read_text(encoding="utf-8"))
164
+ except Exception:
165
+ pass
166
+ return {"queue": [], "visited": [], "cursor": 0}
167
+
168
+
169
+ def save_frontier(target_id: str, fr: Dict[str, Any]) -> None:
170
+ # cap visited
171
+ visited = list(dict.fromkeys(fr.get("visited") or []))[-4000:]
172
+ queue = list(dict.fromkeys(fr.get("queue") or []))[:2000]
173
+ fr = {"queue": queue, "visited": visited, "cursor": int(fr.get("cursor") or 0),
174
+ "updated_at": datetime.now(timezone.utc).isoformat()}
175
+ p = frontier_path(target_id)
176
+ tmp = p.with_suffix(".tmp")
177
+ tmp.write_text(json.dumps(fr), encoding="utf-8")
178
+ tmp.replace(p)
179
+
180
+
181
+ def make_doc_record(
182
+ *,
183
+ gap_target_id: str,
184
+ state: str,
185
+ title: str,
186
+ text: str,
187
+ source_url: str,
188
+ document_type: str,
189
+ archive_source: Optional[str],
190
+ target_hf_repo: str,
191
+ locality: Optional[str] = None,
192
+ ) -> Dict[str, Any]:
193
+ level = "territorial" if state in ("PR", "GU", "VI", "AS", "MP", "DC") and locality is None else "state"
194
+ if state == "DC":
195
+ level = "state"
196
+ if locality:
197
+ level = "municipal"
198
+ return base_record(
199
+ gap_target_id=gap_target_id,
200
+ jurisdiction=f"US-{state}",
201
+ subdivision_level=level,
202
+ document_type=document_type,
203
+ title=title[:300],
204
+ text=text[:60000],
205
+ source_url=source_url,
206
+ citation=title[:200] if title else None,
207
+ state_or_province=state,
208
+ locality=locality,
209
+ transport="https" if source_url.startswith("https") else "http",
210
+ archive_source=archive_source,
211
+ target_hf_repo=target_hf_repo,
212
+ )
213
+
214
+
215
+ # ---- OH deep resume (unchanged approach) ----
216
+ def load_oh_done_urls() -> Set[str]:
217
+ done: Set[str] = set()
218
+ if OH_ROWS.exists():
219
+ with open(OH_ROWS, encoding="utf-8") as f:
220
+ for line in f:
221
+ try:
222
+ done.add(json.loads(line)["source_url"])
223
+ except Exception:
224
+ continue
225
+ return done
226
+
227
+
228
+ def load_oh_cursor() -> Dict[str, Any]:
229
+ if OH_CURSOR.exists():
230
+ try:
231
+ return json.loads(OH_CURSOR.read_text(encoding="utf-8"))
232
+ except Exception:
233
+ pass
234
+ return {"completed_agencies": [], "skip_until_agency": "/ohio-administrative-code/122"}
235
+
236
+
237
+ def save_oh_cursor(cur: Dict[str, Any]) -> None:
238
+ OH_CURSOR.parent.mkdir(parents=True, exist_ok=True)
239
+ tmp = OH_CURSOR.with_suffix(".tmp")
240
+ tmp.write_text(json.dumps(cur, indent=2) + "\n", encoding="utf-8")
241
+ tmp.replace(OH_CURSOR)
242
+
243
+
244
+ def append_oh_legacy_row(cit: str, title: str, text: str, url: str) -> Dict[str, Any]:
245
+ OH_ROWS.parent.mkdir(parents=True, exist_ok=True)
246
+ row = {
247
+ "state": "OH", "citation": cit, "title": title, "text": text, "source_url": url,
248
+ "fetched_at": datetime.now(timezone.utc).isoformat(),
249
+ "sha256": hashlib.sha256(text.encode()).hexdigest(), "transport": "https",
250
+ }
251
+ with open(OH_ROWS, "a", encoding="utf-8") as f:
252
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
253
+ return row
254
+
255
+
256
+ def resume_ohio(sess: PoliteSession, done: Set[str], seen_add: Callable[[str], bool], *, max_new: int = 25):
257
+ manifest: Dict[str, Any] = {"portal": OH_BASE + "/ohio-administrative-code", "status": "ok"}
258
+ out: List[Dict[str, Any]] = []
259
+ cur = load_oh_cursor()
260
+ completed: Set[str] = set(cur.get("completed_agencies") or [])
261
+ skip_until = cur.get("skip_until_agency")
262
+ r, flag = sess.get(OH_BASE + "/ohio-administrative-code")
263
+ if flag or not r:
264
+ manifest["status"] = flag or "fetch_failed"
265
+ return out, manifest
266
+ top = BeautifulSoup(r.text, "html.parser")
267
+ ags = sorted({
268
+ a["href"] for a in top.select("a[href]")
269
+ if re.fullmatch(r"/ohio-administrative-code/[0-9a-z:\-]+", a.get("href") or "")
270
+ and "chapter" not in a["href"] and "rule" not in a["href"]
271
+ })
272
+ started = not skip_until
273
+ for ag in ags:
274
+ if len(out) >= max_new:
275
+ break
276
+ if not started:
277
+ if ag < skip_until:
278
+ continue
279
+ started = True
280
+ cur["skip_until_agency"] = None
281
+ save_oh_cursor({**cur, "completed_agencies": sorted(completed)})
282
+ if ag in completed:
283
+ continue
284
+ r, flag = sess.get(OH_BASE + ag)
285
+ if flag == "blocked_waf" or not r:
286
+ if flag == "blocked_waf":
287
+ manifest["status"] = "blocked_waf"
288
+ break
289
+ continue
290
+ chs = list(dict.fromkeys(
291
+ a["href"] for a in BeautifulSoup(r.text, "html.parser").select(
292
+ 'a[href^="/ohio-administrative-code/chapter-"]'
293
+ )
294
+ ))
295
+ agency_new = 0
296
+ agency_seen = 0
297
+ all_done = True
298
+ for ch in chs:
299
+ if len(out) >= max_new:
300
+ break
301
+ r, flag = sess.get(OH_BASE + ch)
302
+ if flag == "blocked_waf" or not r:
303
+ if flag == "blocked_waf":
304
+ manifest["status"] = "blocked_waf"
305
+ return out, manifest
306
+ continue
307
+ rules = list(dict.fromkeys(
308
+ a["href"] for a in BeautifulSoup(r.text, "html.parser").select(
309
+ 'a[href^="/ohio-administrative-code/rule-"]'
310
+ )
311
+ ))
312
+ for ru in rules:
313
+ agency_seen += 1
314
+ u = OH_BASE + ru
315
+ if u in done:
316
+ continue
317
+ all_done = False
318
+ if len(out) >= max_new:
319
+ break
320
+ r, flag = sess.get(u)
321
+ if flag or not r:
322
+ if flag == "blocked_waf":
323
+ manifest["status"] = "blocked_waf"
324
+ return out, manifest
325
+ continue
326
+ b = BeautifulSoup(r.text, "html.parser")
327
+ h = b.select_one("section.laws-header h1")
328
+ body = b.select_one("section.laws-body")
329
+ if not h or not body:
330
+ continue
331
+ ht = h.get_text(" ", strip=True)
332
+ cit, _, title = ht.partition("|")
333
+ text = body.get_text("\n", strip=True)
334
+ legacy = append_oh_legacy_row(cit.strip(), title.strip(), text, u)
335
+ rec = from_oh_official_row(legacy)
336
+ if seen_add(rec["id"]):
337
+ out.append(rec)
338
+ done.add(u)
339
+ agency_new += 1
340
+ if agency_seen > 0 and all_done and agency_new == 0 and len(out) < max_new:
341
+ completed.add(ag)
342
+ save_oh_cursor({"completed_agencies": sorted(completed), "last_agency": ag})
343
+ elif agency_new > 0:
344
+ save_oh_cursor({"completed_agencies": sorted(completed), "last_agency": ag})
345
+ manifest["new"] = len(out)
346
+ return out, manifest
347
+
348
+
349
+ def deep_collect_state(
350
+ sess: PoliteSession,
351
+ seed: Dict[str, Any],
352
+ seen_add: Callable[[str], bool],
353
+ *,
354
+ max_admin: int = 12,
355
+ max_eo: int = 8,
356
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], Dict[str, Any]]:
357
+ """Return (admin_records, eo_records, manifest)."""
358
+ tid = seed["target_id"]
359
+ st = state_code_from_target(tid) or "XX"
360
+ hf_admin = seed.get("target_hf_repo") or "justicedao/ipfs_state_admin_rules"
361
+ hf_eo = "justicedao/ipfs_us_executive_orders"
362
+ admin_out: List[Dict[str, Any]] = []
363
+ eo_out: List[Dict[str, Any]] = []
364
+ man: Dict[str, Any] = {"target_id": tid, "state": st, "admin_status": None, "eo_status": None}
365
+
366
+ if st == "OH":
367
+ done = load_oh_done_urls()
368
+ recs, m = resume_ohio(sess, done, seen_add, max_new=max_admin)
369
+ admin_out.extend(recs)
370
+ man["admin_status"] = m
371
+ # also governor EO if present in seeds
372
+ else:
373
+ fr = load_frontier(tid)
374
+ visited = set(fr.get("visited") or [])
375
+ queue = list(fr.get("queue") or [])
376
+
377
+ # seed admin_code
378
+ admin_cands = preferred_fetch_urls(seed, "admin_code")
379
+ if admin_cands and not queue:
380
+ queue.extend([u for u, _ in admin_cands[:5]])
381
+
382
+ # ensure we fetch at least one admin seed page to expand frontier
383
+ if admin_cands:
384
+ r, final_url, arch, status = fetch_with_fallback(sess, admin_cands)
385
+ man["admin_status"] = status
386
+ man["admin_url"] = final_url
387
+ if r:
388
+ visited.add(final_url)
389
+ links = extract_links(final_url, r.text, "admin")
390
+ for L in links[:80]:
391
+ if L not in visited and L not in queue:
392
+ queue.append(L)
393
+ # if seed page itself is substantive, keep it
394
+ title = BeautifulSoup(r.text, "html.parser").title
395
+ title_s = title.get_text(" ", strip=True) if title else f"{st} admin"
396
+ text = BeautifulSoup(r.text, "html.parser").get_text("\n", strip=True)
397
+ if is_substantive(text, title_s):
398
+ rec = make_doc_record(
399
+ gap_target_id=tid, state=st, title=title_s, text=text,
400
+ source_url=final_url, document_type="admin_rule",
401
+ archive_source=arch, target_hf_repo=hf_admin,
402
+ )
403
+ if seen_add(rec["id"]):
404
+ admin_out.append(rec)
405
+
406
+ # crawl frontier for admin docs
407
+ while queue and len(admin_out) < max_admin:
408
+ url = queue.pop(0)
409
+ if url in visited:
410
+ continue
411
+ visited.add(url)
412
+ r, flag = sess.get(url)
413
+ arch = "wayback" if "web.archive.org" in url else None
414
+ if flag or not r:
415
+ if flag == "blocked_waf":
416
+ live, _ = unwrap_wayback(url)
417
+ wu, wr = wayback_closest(sess, live)
418
+ if wr:
419
+ r, url, arch, flag = wr, wu or url, "wayback", None
420
+ else:
421
+ continue
422
+ else:
423
+ continue
424
+ soup = BeautifulSoup(r.text, "html.parser")
425
+ title = soup.title.get_text(" ", strip=True) if soup.title else url
426
+ # prefer PDF binary skip — only text/html
427
+ ctype = (r.headers.get("content-type") or "").lower()
428
+ if "pdf" in ctype:
429
+ # store short PDF meta stub only if substantive headers
430
+ text = f"[PDF content-type] bytes={len(r.content)} url={url}"
431
+ if len(r.content) > 5000:
432
+ rec = make_doc_record(
433
+ gap_target_id=tid, state=st, title=title or Path(urlparse(url).path).name,
434
+ text=text, source_url=url, document_type="admin_rule_pdf_meta",
435
+ archive_source=arch, target_hf_repo=hf_admin,
436
+ )
437
+ if seen_add(rec["id"]):
438
+ admin_out.append(rec)
439
+ continue
440
+ text = soup.get_text("\n", strip=True)
441
+ if is_substantive(text, title):
442
+ rec = make_doc_record(
443
+ gap_target_id=tid, state=st, title=title, text=text,
444
+ source_url=url, document_type="admin_rule",
445
+ archive_source=arch, target_hf_repo=hf_admin,
446
+ )
447
+ if seen_add(rec["id"]):
448
+ admin_out.append(rec)
449
+ # expand a bit
450
+ if len(visited) < 120:
451
+ for L in extract_links(url, r.text, "admin")[:20]:
452
+ if L not in visited and L not in queue:
453
+ queue.append(L)
454
+
455
+ fr["queue"] = queue
456
+ fr["visited"] = list(visited)
457
+ save_frontier(tid, fr)
458
+
459
+ # Governor EO role
460
+ eo_cands = preferred_fetch_urls(seed, "governor_eo")
461
+ if eo_cands:
462
+ r, final_url, arch, status = fetch_with_fallback(sess, eo_cands)
463
+ man["eo_status"] = status
464
+ man["eo_url"] = final_url
465
+ if r:
466
+ links = extract_links(final_url, r.text, "eo")
467
+ # include landing if substantive
468
+ soup = BeautifulSoup(r.text, "html.parser")
469
+ title = soup.title.get_text(" ", strip=True) if soup.title else f"{st} Governor EOs"
470
+ text = soup.get_text("\n", strip=True)
471
+ candidates = [(final_url, r, arch, title)]
472
+ for L in links[: max_eo * 3]:
473
+ if len(candidates) >= max_eo + 1:
474
+ break
475
+ r2, f2 = sess.get(L)
476
+ a2 = "wayback" if "web.archive.org" in L else None
477
+ if f2 or not r2:
478
+ continue
479
+ s2 = BeautifulSoup(r2.text, "html.parser")
480
+ t2 = s2.title.get_text(" ", strip=True) if s2.title else L
481
+ candidates.append((L, r2, a2, t2))
482
+ for url, resp, a, title in candidates:
483
+ if len(eo_out) >= max_eo:
484
+ break
485
+ ctype = (resp.headers.get("content-type") or "").lower()
486
+ if "pdf" in ctype:
487
+ text = f"[PDF] bytes={len(resp.content)} url={url}"
488
+ if len(resp.content) < 3000:
489
+ continue
490
+ else:
491
+ text = BeautifulSoup(resp.text, "html.parser").get_text("\n", strip=True)
492
+ if not is_substantive(text, title) and "pdf" not in ctype:
493
+ continue
494
+ rec = make_doc_record(
495
+ gap_target_id=tid, state=st, title=title, text=text,
496
+ source_url=url, document_type="governor_eo",
497
+ archive_source=a, target_hf_repo=hf_eo,
498
+ )
499
+ if seen_add(rec["id"]):
500
+ eo_out.append(rec)
501
+
502
+ man["admin_written"] = len(admin_out)
503
+ man["eo_written"] = len(eo_out)
504
+ return admin_out, eo_out, man
scrapers_and_normalizers/unified_daemon.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Seed-driven US Admin Rules & EO daemon with pause/hibernate memguard.
3
+
4
+ Queue: /workspace/coverage/world_admin_eo_seeds_20261105.jsonl (US ARE-US-* rows).
5
+ MemAvailable < 4.2 GiB -> flush, gc, status=paused_low_mem, sleep until >= 4.35 GiB.
6
+ Disk < 10 GiB -> exit. RSS > 500 MiB -> flush + os.execv self.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import gc
11
+ import json
12
+ import os
13
+ import signal
14
+ import sys
15
+ import time
16
+ import traceback
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ BUNDLE = Path(__file__).resolve().parent
21
+ sys.path.insert(0, str(BUNDLE))
22
+ IPFS = Path("/workspace/ipfs_datasets_py_latest")
23
+ if IPFS.exists():
24
+ sys.path.insert(0, str(IPFS))
25
+
26
+ from io_zst import (
27
+ JsonlZstWriter, MemGuard, SeenIds, load_ids_from_zst, load_json, write_json,
28
+ mem_available_bytes, disk_free_bytes, process_rss_bytes,
29
+ )
30
+ from seeds import load_us_seeds, state_code_from_target
31
+ from federal_collector import (
32
+ PoliteSession as FedSession, ecfr_as_of, collect_ecfr_title_parts, collect_eo, collect_fr_after,
33
+ )
34
+ from state_admin_collector import PoliteSession as StateSession, deep_collect_state
35
+ from municipal_collector import PoliteSession as MuniSession, collect_municipal
36
+
37
+ FED_ROOT = Path("/workspace/legal-corpora/us_federal_admin_eo_20261105")
38
+ STATE_ROOT = Path("/workspace/legal-corpora/us_state_admin_rules_20261104")
39
+ EO_ROOT = Path("/workspace/legal-corpora/us_executive_orders_20261105")
40
+ STATE_SHARDS = STATE_ROOT / "shards"
41
+ COLLECTOR = STATE_ROOT / "_collector"
42
+ STATUS_STATE = COLLECTOR / "status.json"
43
+ STATUS_FED = FED_ROOT / "status.json"
44
+ STATUS_EO = EO_ROOT / "status.json"
45
+ CKPT = COLLECTOR / "checkpoint_gap.json"
46
+ SEEN_PATH = COLLECTOR / "seen_ids.json"
47
+ LOG = Path("/workspace/logs/us_admin_eo_gap_daemon_20261105.log")
48
+ SEEDS_PATH = "/workspace/coverage/world_admin_eo_seeds_20261105.jsonl"
49
+
50
+ STOP = False
51
+
52
+
53
+ def log(msg: str) -> None:
54
+ LOG.parent.mkdir(parents=True, exist_ok=True)
55
+ line = f"{datetime.now().isoformat(timespec='seconds')} {msg}"
56
+ with open(LOG, "a", encoding="utf-8") as f:
57
+ f.write(line + "\n")
58
+ print(line, flush=True)
59
+
60
+
61
+ def _sig(signum, frame):
62
+ global STOP
63
+ STOP = True
64
+ log(f"SIGNAL {signum} -> graceful stop")
65
+
66
+
67
+ signal.signal(signal.SIGTERM, _sig)
68
+ signal.signal(signal.SIGINT, _sig)
69
+
70
+
71
+ def dual_status(**kwargs):
72
+ payload = dict(kwargs)
73
+ payload.update({
74
+ "updated_at": datetime.now(timezone.utc).isoformat(),
75
+ "pid": os.getpid(),
76
+ "mem_available_bytes": mem_available_bytes(),
77
+ "disk_free_bytes": disk_free_bytes(),
78
+ "rss_bytes": process_rss_bytes(),
79
+ "mem_floor_bytes": MemGuard.MEM_FLOOR,
80
+ "mem_resume_bytes": MemGuard.MEM_RESUME,
81
+ "disk_floor_bytes": MemGuard.DISK_FLOOR,
82
+ "rss_reexec_bytes": MemGuard.RSS_REEXEC,
83
+ "seeds": SEEDS_PATH,
84
+ "log": str(LOG),
85
+ "seen_ids_path": str(SEEN_PATH),
86
+ })
87
+ for path in (STATUS_STATE, STATUS_FED, STATUS_EO):
88
+ prev = load_json(path, default={}) or {}
89
+ prev.update(payload)
90
+ write_json(path, prev)
91
+
92
+
93
+ def shard_path(root: Path, prefix: str) -> Path:
94
+ (root / "shards").mkdir(parents=True, exist_ok=True)
95
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
96
+ return root / "shards" / f"{prefix}_{ts}.jsonl.zst"
97
+
98
+
99
+ def write_batch(path: Path, records: list, seen: SeenIds) -> int:
100
+ if not records:
101
+ return 0
102
+ with JsonlZstWriter(path) as w:
103
+ for rec in records:
104
+ w.write(rec)
105
+ w.flush()
106
+ seen.flush()
107
+ return len(records)
108
+
109
+
110
+ def seed_seen(seen: SeenIds) -> int:
111
+ n = 0
112
+ for root in [FED_ROOT / "shards", STATE_SHARDS, STATE_ROOT / "OH.official" / "shards", EO_ROOT / "shards"]:
113
+ if not root.exists():
114
+ continue
115
+ for p in root.glob("*.jsonl.zst"):
116
+ n += load_ids_from_zst(p, seen)
117
+ for p in root.glob("**/*.jsonl.zst"):
118
+ n += load_ids_from_zst(p, seen)
119
+ # also per-state .gap
120
+ for p in STATE_ROOT.glob("*.gap/shards/*.jsonl.zst"):
121
+ n += load_ids_from_zst(p, seen)
122
+ seen.flush()
123
+ return n
124
+
125
+
126
+ def handle_guard(action: str, guard: MemGuard, seen: SeenIds, ckpt: dict) -> bool:
127
+ """Return False if caller should exit; True to continue (possibly after pause/reexec)."""
128
+ if action == "ok":
129
+ return True
130
+ seen.flush()
131
+ write_json(CKPT, ckpt)
132
+ gc.collect()
133
+ if action == "exit_disk":
134
+ dual_status(state="exited", stop_reason=guard.stop_reason, totals=ckpt.get("totals"))
135
+ log(f"EXIT_DISK {guard.stop_reason}")
136
+ return False
137
+ if action == "reexec":
138
+ dual_status(state="reexec_rss", stop_reason=guard.stop_reason, totals=ckpt.get("totals"))
139
+ log(f"REEXEC {guard.stop_reason}")
140
+ os.execv(sys.executable, [sys.executable, "-u", str(Path(__file__).resolve())] + sys.argv[1:])
141
+ return False # unreachable
142
+ if action == "pause":
143
+ dual_status(state="paused_low_mem", stop_reason=guard.stop_reason, totals=ckpt.get("totals"),
144
+ queue_index=ckpt.get("queue_index"), ecfr_title_index=ckpt.get("ecfr_title_index"),
145
+ current_target="(paused)")
146
+ log(f"PAUSE {guard.stop_reason}")
147
+ ok = MemGuard.wait_until_resume(
148
+ log_fn=log,
149
+ status_fn=lambda **kw: dual_status(totals=ckpt.get("totals"),
150
+ queue_index=ckpt.get("queue_index"),
151
+ ecfr_title_index=ckpt.get("ecfr_title_index"),
152
+ current_target="(paused)", **kw),
153
+ stop_flag=lambda: STOP,
154
+ )
155
+ if not ok:
156
+ dual_status(state="exited", stop_reason="stop_during_pause_or_disk", totals=ckpt.get("totals"))
157
+ return False
158
+ dual_status(state="running", stop_reason=None, totals=ckpt.get("totals"))
159
+ return True
160
+ return True
161
+
162
+
163
+ def main() -> int:
164
+ for d in [FED_ROOT / "shards", STATE_SHARDS, EO_ROOT / "shards", COLLECTOR,
165
+ STATE_ROOT / "OH.official" / "shards"]:
166
+ d.mkdir(parents=True, exist_ok=True)
167
+
168
+ guard = MemGuard()
169
+ seen = SeenIds(SEEN_PATH)
170
+ seeded = seed_seen(seen)
171
+ log(f"START pid={os.getpid()} seeded_seen={seeded} total_seen={len(seen.ids)} mem={mem_available_bytes()}")
172
+
173
+ # Immediate pause if already below floor
174
+ action = guard.evaluate()
175
+ ckpt = load_json(CKPT, default={}) or {}
176
+ if action != "ok":
177
+ if not handle_guard(action, guard, seen, ckpt):
178
+ return 0
179
+
180
+ queue = load_us_seeds()
181
+ queue_index = int(ckpt.get("queue_index") or 0)
182
+ ecfr_title_index = int(ckpt.get("ecfr_title_index") or 0)
183
+ totals = ckpt.get("totals") or {"written": 0, "skipped_dup": 0, "by_target": {}}
184
+
185
+ def seen_add(rid: str) -> bool:
186
+ ok = seen.add(rid)
187
+ if not ok:
188
+ totals["skipped_dup"] = totals.get("skipped_dup", 0) + 1
189
+ return ok
190
+
191
+ fed = FedSession(delay=0.7)
192
+ state = StateSession(delay=0.9)
193
+ muni = MuniSession(delay=1.0)
194
+
195
+ dual_status(state="starting", stream="seeds_us", queue_len=len(queue), queue_index=queue_index, totals=totals)
196
+ date, titles = ecfr_as_of(fed)
197
+ title_nums = [int(t["number"]) for t in titles if not t.get("reserved")] or list(range(1, 51))
198
+ log(f"seeds={len(queue)} eCFR as_of={date} titles={len(title_nums)}")
199
+
200
+ while not STOP:
201
+ action = guard.tick()
202
+ ckpt = {
203
+ "queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
204
+ "totals": totals, "saved_at": datetime.now(timezone.utc).isoformat(),
205
+ }
206
+ if not handle_guard(action, guard, seen, ckpt):
207
+ return 0
208
+
209
+ if queue_index >= len(queue):
210
+ # wrap: continue ECFR titles if needed else restart from FR/EO/state deepen
211
+ if ecfr_title_index < len(title_nums):
212
+ queue_index = 0
213
+ log(f"WRAP to ECFR title_index={ecfr_title_index}")
214
+ else:
215
+ queue_index = 0
216
+ log("FULL WRAP deepen cycle")
217
+
218
+ seed = queue[queue_index]
219
+ tid = seed["target_id"]
220
+ lane = seed.get("lane")
221
+ hf = seed.get("target_hf_repo")
222
+ dual_status(state="running", current_target=tid, queue_index=queue_index, lane=lane,
223
+ target_hf_repo=hf, totals=totals, ecfr_title_index=ecfr_title_index)
224
+ log(f"TARGET {queue_index+1}/{len(queue)} {tid} lane={lane} hf={hf}")
225
+
226
+ try:
227
+ if tid == "ARE-US-ECFR":
228
+ wrote_any = 0
229
+ for _ in range(2):
230
+ if ecfr_title_index >= len(title_nums) or STOP:
231
+ break
232
+ action = guard.tick()
233
+ if action != "ok":
234
+ ckpt = {"queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
235
+ "totals": totals, "saved_at": datetime.now(timezone.utc).isoformat()}
236
+ if not handle_guard(action, guard, seen, ckpt):
237
+ return 0
238
+ break
239
+ tnum = title_nums[ecfr_title_index]
240
+ recs = collect_ecfr_title_parts(
241
+ fed, tnum, date, seen_add=seen_add, max_parts=10, max_records=60,
242
+ should_continue=lambda: (not STOP) and guard.evaluate() == "ok",
243
+ )
244
+ if recs:
245
+ path = shard_path(FED_ROOT, f"ARE-US-ECFR_title{tnum}")
246
+ n = write_batch(path, recs, seen)
247
+ wrote_any += n
248
+ totals["written"] = totals.get("written", 0) + n
249
+ totals.setdefault("by_target", {})
250
+ totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
251
+ log(f"ECFR title {tnum} wrote {n}")
252
+ ecfr_title_index += 1
253
+ queue_index += 1
254
+
255
+ elif tid == "ARE-US-EO":
256
+ recs = collect_eo(fed, seen_add, max_docs=25)
257
+ path = shard_path(EO_ROOT, "ARE-US-EO")
258
+ # also keep federal staging copy for continuity
259
+ n = write_batch(path, recs, seen)
260
+ if recs:
261
+ write_batch(shard_path(FED_ROOT, "ARE-US-EO"), recs, seen)
262
+ totals["written"] = totals.get("written", 0) + n
263
+ totals.setdefault("by_target", {})
264
+ totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
265
+ log(f"EO wrote {n}")
266
+ queue_index += 1
267
+
268
+ elif tid == "ARE-US-FR":
269
+ recs = collect_fr_after(fed, seen_add, gte="2026-07-01", max_docs=30)
270
+ path = shard_path(FED_ROOT, "ARE-US-FR")
271
+ n = write_batch(path, recs, seen)
272
+ totals["written"] = totals.get("written", 0) + n
273
+ totals.setdefault("by_target", {})
274
+ totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
275
+ log(f"FR wrote {n}")
276
+ queue_index += 1
277
+
278
+ elif tid == "ARE-US-COUNTY-MUNICIPAL-ADMIN-EO":
279
+ recs, man = collect_municipal(muni, seen_add, max_records=20)
280
+ path = shard_path(EO_ROOT, "ARE-US-COUNTY-MUNICIPAL")
281
+ n = write_batch(path, recs, seen)
282
+ write_json(COLLECTOR / "municipal_manifest.json", man)
283
+ totals["written"] = totals.get("written", 0) + n
284
+ totals.setdefault("by_target", {})
285
+ totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
286
+ log(f"MUNICIPAL wrote {n}")
287
+ queue_index += 1
288
+
289
+ elif tid.endswith("-ADMIN-EO"):
290
+ admin_recs, eo_recs, man = deep_collect_state(
291
+ state, seed, seen_add, max_admin=12, max_eo=8,
292
+ )
293
+ st = state_code_from_target(tid) or "XX"
294
+ n_admin = n_eo = 0
295
+ if admin_recs:
296
+ # per-state + aggregate state shards
297
+ out_dir = STATE_ROOT / f"{st}.gap" / "shards"
298
+ out_dir.mkdir(parents=True, exist_ok=True)
299
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
300
+ p1 = out_dir / f"{tid}_{ts}.jsonl.zst"
301
+ n_admin = write_batch(p1, admin_recs, seen)
302
+ write_batch(STATE_SHARDS / f"{tid}_{ts}.jsonl.zst", admin_recs, seen)
303
+ if eo_recs:
304
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
305
+ n_eo = write_batch(shard_path(EO_ROOT, f"{tid}_gov_eo"), eo_recs, seen)
306
+ with open(COLLECTOR / "portal_manifest.jsonl", "a", encoding="utf-8") as mf:
307
+ mf.write(json.dumps(man) + "\n")
308
+ n = n_admin + n_eo
309
+ totals["written"] = totals.get("written", 0) + n
310
+ totals.setdefault("by_target", {})
311
+ totals["by_target"][tid] = totals["by_target"].get(tid, 0) + n
312
+ log(f"{tid} wrote admin={n_admin} eo={n_eo} status={man.get('admin_status')}/{man.get('eo_status')}")
313
+ queue_index += 1
314
+ else:
315
+ log(f"SKIP {tid}")
316
+ queue_index += 1
317
+
318
+ except Exception as e:
319
+ log(f"ERR {tid} {e!r}\n{traceback.format_exc()}")
320
+ queue_index += 1
321
+
322
+ ckpt = {
323
+ "queue_index": queue_index, "ecfr_title_index": ecfr_title_index,
324
+ "totals": totals, "saved_at": datetime.now(timezone.utc).isoformat(),
325
+ }
326
+ write_json(CKPT, ckpt)
327
+ seen.flush()
328
+ dual_status(state="running", queue_index=queue_index, ecfr_title_index=ecfr_title_index,
329
+ totals=totals, current_target=tid)
330
+ gc.collect()
331
+
332
+ seen.flush()
333
+ dual_status(state="exited", totals=totals, queue_index=queue_index, stop_reason="signal")
334
+ log(f"EXIT signal totals={totals}")
335
+ return 0
336
+
337
+
338
+ if __name__ == "__main__":
339
+ try:
340
+ sys.exit(main() or 0)
341
+ except Exception as e:
342
+ log(f"FATAL {e!r}\n{traceback.format_exc()}")
343
+ try:
344
+ dual_status(state="fatal", error=repr(e))
345
+ except Exception:
346
+ pass
347
+ sys.exit(1)