endomorphosis commited on
Commit
ea1b53b
·
verified ·
1 Parent(s): 9248879

DE-SN amending acts densify: +1,376 laws / +3,630 articles (append-only at 92488791; live rows byte-identical); added/not-added/known-gap manifests

Browse files
README.md CHANGED
@@ -37,12 +37,12 @@ Bremen (DE-HB) was collected but is **held back** pending a licence review (see
37
 
38
  | Field | Value |
39
  | --- | --- |
40
- | Snapshot date | 2026-09-05 (federal); Landesrecht 2026-10-02; DE-SN densify 2026-10-15; DE-SN heading/HTML fix 2026-10-15; contents/titles fix 2026-10-15; SN law-text line breaks 2026-10-15 |
41
  | Coverage | full Bundesrecht via gesetze-im-internet.de TOC |
42
  | Source | Bundesministerium der Justiz / gesetze-im-internet.de |
43
  | Collector | `scrapers/collect_gii.py` |
44
- | Laws / instruments | 10953 (federal 6127 + Landesrecht 4826) |
45
- | Articles | 209481 (federal 129124 + Landesrecht 80357) |
46
  | Language | de |
47
  | Jurisdiction | Germany (`DE` federal; `DE-<Land>` Landesrecht) |
48
  | License | `urhg-5-amtliche-werke` |
@@ -61,6 +61,7 @@ Bremen (DE-HB) was collected but is **held back** pending a licence review (see
61
  - `manifests/fix_sn_headings_ids.jsonl` — every DE-SN law/article id changed by the 2026-10-15 heading/HTML fix, with the action taken; `manifests/fix_sn_headings_REPORT.json` — invariants and gate results.
62
  - `manifests/fix_contents_titles_ids.jsonl` — every article row dropped and every title restored by the 2026-10-15 contents/titles fix, plus each law whose article_count changed; `manifests/fix_contents_titles_REPORT.json` — invariants and gate results.
63
  - `manifests/fix_sn_lawtext_br_ids.jsonl` — the DE-SN law texts whose line breaks were restored on 2026-10-15, with offsets and before/after snippets; `manifests/fix_sn_lawtext_br_REPORT.json` — invariants and gate results.
 
64
  - `MANIFEST.md`, `PACK_META.json` — records of the 2026-10-02 Landesrecht append (not updated for later densify batches).
65
 
66
  ## License / reuse
@@ -215,3 +216,33 @@ Totals after the contents/titles fix: 10,953 laws / 209,481 articles.
215
  - In 24 DE-SN law texts the 2026-10-15 heading/HTML fix had removed 34 line breaks (`<br>`) that sat directly between two words, joining them (e.g. `elektronischenInformations-`). Each is a line break again, at the exact position taken from the raw text before that fix; offsets and before/after snippets are in `manifests/fix_sn_lawtext_br_ids.jsonl`.
216
  - No other field or row changed; law and article counts are unchanged.
217
  - Note: the bundled `scrapers/de_lib.py` still has default `HUB_TIP` f9384361 (an earlier tip). Set `DE_HUB_TIP` to the current tip before building a new pack, as the scrapers README says.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  | Field | Value |
39
  | --- | --- |
40
+ | Snapshot date | 2026-09-05 (federal); Landesrecht 2026-10-02; DE-SN densify 2026-10-15; DE-SN heading/HTML fix 2026-10-15; contents/titles fix 2026-10-15; SN law-text line breaks 2026-10-15; DE-SN amending acts 2026-10-17 |
41
  | Coverage | full Bundesrecht via gesetze-im-internet.de TOC |
42
  | Source | Bundesministerium der Justiz / gesetze-im-internet.de |
43
  | Collector | `scrapers/collect_gii.py` |
44
+ | Laws / instruments | 12329 (federal 6127 + Landesrecht 6202) |
45
+ | Articles | 213111 (federal 129124 + Landesrecht 83987) |
46
  | Language | de |
47
  | Jurisdiction | Germany (`DE` federal; `DE-<Land>` Landesrecht) |
48
  | License | `urhg-5-amtliche-werke` |
 
61
  - `manifests/fix_sn_headings_ids.jsonl` — every DE-SN law/article id changed by the 2026-10-15 heading/HTML fix, with the action taken; `manifests/fix_sn_headings_REPORT.json` — invariants and gate results.
62
  - `manifests/fix_contents_titles_ids.jsonl` — every article row dropped and every title restored by the 2026-10-15 contents/titles fix, plus each law whose article_count changed; `manifests/fix_contents_titles_REPORT.json` — invariants and gate results.
63
  - `manifests/fix_sn_lawtext_br_ids.jsonl` — the DE-SN law texts whose line breaks were restored on 2026-10-15, with offsets and before/after snippets; `manifests/fix_sn_lawtext_br_REPORT.json` — invariants and gate results.
64
+ - `manifests/densify_sn_amending_added_ids.jsonl` — every law and article id added by the DE-SN amending-acts densify (2026-10-17); `manifests/densify_sn_amending_known_gaps.jsonl` — rows of those laws dropped by the clean-up (with reason) and the repeal placeholders kept; `manifests/densify_sn_amending_not_added.jsonl` — collected records not added (duplicates of live rows; pages with no norm text).
65
  - `MANIFEST.md`, `PACK_META.json` — records of the 2026-10-02 Landesrecht append (not updated for later densify batches).
66
 
67
  ## License / reuse
 
216
  - In 24 DE-SN law texts the 2026-10-15 heading/HTML fix had removed 34 line breaks (`<br>`) that sat directly between two words, joining them (e.g. `elektronischenInformations-`). Each is a line break again, at the exact position taken from the raw text before that fix; offsets and before/after snippets are in `manifests/fix_sn_lawtext_br_ids.jsonl`.
217
  - No other field or row changed; law and article counts are unchanged.
218
  - Note: the bundled `scrapers/de_lib.py` still has default `HUB_TIP` f9384361 (an earlier tip). Set `DE_HUB_TIP` to the current tip before building a new pack, as the scrapers README says.
219
+
220
+ ## DE-SN amending acts densify — 2026-10-17 (1,376 laws / 3,630 articles, append-only at 92488791)
221
+
222
+ - Source: www.revosax.sachsen.de (revosax); licence: Public domain (gemeinfrei): amtliche Werke i.S.d. § 5 Abs. 1 UrhG; Sächsische Staatskanzlei / revosax.sachsen.de (REVOSax)
223
+ - Kinds: {"amending": 1376} — Änderungs-/Aufhebungsgesetze and -verordnungen (`metadata_json.metadata.kind` = `amending`), which the 2026-10-02 append and the 2026-10-15 densify excluded.
224
+ - Every live row is byte-identical and comes first; only rows are appended (no live row changed or removed). New law and article ids are unique and disjoint from the tip; `article_count` = article rows for every added law.
225
+ - Not added: 2,041 collected records are **duplicates of live rows** (1,666 id_on_tip, 375 same_title_same_land_on_tip); listed in `manifests/densify_sn_amending_not_added.jsonl`. (Earlier build logs called these 'dropped'; they are not bounds rejections.)
226
+ - Not added: 2,003 REVOSax pages carry no norm text of their own (text under 80 characters; stub pages that only point to a parent act, e.g. `Gesetz zum Zehnten Rundfunkänderungsstaatsvertrag`); listed in the same manifest.
227
+ - Clean-up (pipeline, added rows only): revosax footnotes are `[n]` markers plus a plain-text `Fußnoten:` block (16 article rows, 0 law texts converted at pack time); 18 structural heading rows (Teil/Abschnitt/Zustimmungsgesetz, or an `Artikel N` heading over the § rows of the act it contains) folded into the next row; 0 titles cleaned; 0 metadata fields cleaned of HTML. An empty `Artikel N` heading is never merged into Artikel N+1: each Artikel keeps its own text.
228
+ - Repeal placeholders kept: 5 rows such as `Artikel 7 (außer Kraft)` / `(aufgehoben)` stay as rows, with stray footnote digits removed and `metadata_json.body_status` = `repealed_placeholder` (no new column; the dataset schema is unchanged): `de-sn-19408:Artikel#2`, `de-sn-5041:Artikel#7`, `de-sn-5041:Artikel#8`, `de-sn-5041:Artikel#9`, `de-sn-5041:Artikel#10`.
229
+ - Personal data: only personal data of private individuals is redacted (`[REDACTED-<kind>]`); official accounts (Bundesbank / public cash offices), functional and authority mailboxes (e.g. `@sachsen.de`) and table numbers stay verbatim. Redaction markers in the added rows: 0.
230
+ - Pages re-fetched for this rebuild (robots-checked, gated, polite delay) and cached so later parser fixes re-parse offline: 50.
231
+
232
+ ### Known gaps (DE-SN amending acts)
233
+
234
+ Rows of the added laws that are not in the data (every id with its reason is in `manifests/densify_sn_amending_known_gaps.jsonl`):
235
+
236
+ - 26 empty `Artikel` headings with no body on the REVOSax page (mostly an Artikel that enacts a separate act, whose text REVOSax keeps under that act's own page): `de-sn-11376:Artikel`, `de-sn-11615:Artikel`, `de-sn-11615:Artikel#2`, `de-sn-11696:Artikel#2`, `de-sn-12339:Artikel#13`, `de-sn-12800:Artikel`, `de-sn-12867:Artikel`, `de-sn-1540:Artikel`, `de-sn-18048:Artikel`, `de-sn-18270:Artikel#3`, `de-sn-18816:Artikel`, `de-sn-1915:Artikel`, `de-sn-19985:Artikel`, `de-sn-20002:Artikel`, `de-sn-20785:Artikel#2`, `de-sn-20785:Artikel#3`, `de-sn-20980:Artikel`, `de-sn-21005:Artikel`, `de-sn-21009:Artikel`, `de-sn-21195:Artikel`, `de-sn-21417:Artikel`, `de-sn-21520:Artikel`, `de-sn-3982:Artikel`, `de-sn-4371:Artikel`, `de-sn-4371:Artikel#2`, `de-sn-5119:Artikel#2`.
237
+ - 2 heading rows with only a footnote number: `de-sn-16702:Artikel#2`, `de-sn-17593:Artikel#2`.
238
+ - 2 attachment stubs (the map / Anhang itself is not on the page): `de-sn-21304:Anlagen`, `de-sn-4976:Anlagen`.
239
+ - 37 trailing heading-only rows (`Anlage`, `Anhang`, `Übersichtskarte` … with no content after them): listed in the manifest.
240
+
241
+ ### source_terms_note
242
+
243
+ User decision relayed by Chief of Staff on 2026-10-13: 'I want the entire law, the government laws are not copyrighted' (official statute text, § 5 UrhG). Applies to DE-SN (incl. amending acts, VwV), DE-BB VwV, the DE-NW change set, DE-NI (NI-VORIS) and DE-HB (transparenz.bremen.de). Collected robots fail-closed, no WAF/challenge bypass, polite throttling.
244
+
245
+ Every added row also carries `source_terms_note` inside `metadata_json.metadata`.
246
+
247
+ DE-SN totals after this batch: 3,976 laws (2,600 + 1,376) / 37,181 articles (33,551 + 3,630). Dataset totals: 12,329 laws / 213,111 articles.
248
+ - The bundled `scrapers/de_lib.py` has default `HUB_TIP` 92488791 (the parent of this batch); set `DE_HUB_TIP` to the current tip before building a new pack.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ca5e29490f1a2c335767df6125281a991903a55fbe909cefeb010c0a168bc82d
3
- size 73325075
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02731418eb76b6016ba9a04e94c9f7381798b121a521728a4e511ed42f7e8520
3
+ size 76292125
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f7e428a2a2d853935cf4e8bb1f6ae6d91ae212ea4e157d2a53d4b670ed4cca69
3
- size 69196884
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4f907029496f4f85788ca893e0df4537ab34366563d430cc1948e050c4fb984
3
+ size 72370665
manifests/densify_sn_amending_CARD_SECTION.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## DE-SN densify (1376 laws / 3630 articles, append-only at 92488791)
2
+
3
+ - Source: www.revosax.sachsen.de (revosax); licence: Public domain (gemeinfrei): amtliche Werke i.S.d. § 5 Abs. 1 UrhG; Sächsische Staatskanzlei / revosax.sachsen.de (REVOSax)
4
+ - Kinds: {"amending": 1376}
5
+ - Not added: 2041 records that are duplicates of live rows (1666 id_on_tip, 375 same_title_same_land_on_tip); 2003 stub pages with no norm text of their own (they only point to a parent act)
6
+ - Clean-up (pipeline, added rows only): 0 contents-list rows dropped; revosax footnote HTML converted to plain-text 'Fußnoten:' blocks in 16 article rows and 0 law texts; 18 heading-only rows folded into the next article, 37 trailing ones dropped; 0 titles cleaned; known gaps (dropped, listed in manifests/): 26 empty Artikel headings, 2 footnote-number-only rows, 2 attachment stubs; 5 repeal placeholders kept (metadata_json.body_status)
7
+
8
+ ### source_terms_note
9
+
10
+ User decision relayed by Chief of Staff on 2026-10-13: 'I want the entire law, the government laws are not copyrighted' (official statute text, § 5 UrhG). Applies to DE-SN (incl. amending acts, VwV), DE-BB VwV, the DE-NW change set, DE-NI (NI-VORIS) and DE-HB (transparenz.bremen.de). Collected robots fail-closed, no WAF/challenge bypass, polite throttling.
11
+
12
+ Every added row also carries `source_terms_note` inside `metadata_json.metadata`.
manifests/densify_sn_amending_DENSIFY_REPORT.json ADDED
The diff for this file is too large to render. See raw diff
 
manifests/densify_sn_amending_SHA256SUMS ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 9cd03ea60fb0e7bb7c12457a51b2fc1742145e520ce85a9025a25004d06ef528 CARD_SECTION.md
2
+ 56ee3c6a557c478e2161cbd541a65214a65544093b7b455438d61664322d105b DENSIFY_REPORT.json
3
+ 5e2e81b2a0c7b9567e3ff2b22f6f7b859aa2b77908ae177473815be698f909af README.md
4
+ 02731418eb76b6016ba9a04e94c9f7381798b121a521728a4e511ed42f7e8520 data/articles.parquet
5
+ c4f907029496f4f85788ca893e0df4537ab34366563d430cc1948e050c4fb984 data/laws.parquet
6
+ 623d874fab2d706e01bfe63205a135287ec0bf85d03e381d82466e7a0f0533f1 manifests/densify_sn_amending_added_ids.jsonl
7
+ b9958d06ba879b470ff52f66207dc0d7ee19d6f2cf1526f731c0408dbd4edae8 manifests/densify_sn_amending_known_gaps.jsonl
8
+ eace101b0bc0ed653203b91a45c52ab73befa3a71beddb9c633ee9e1b95da7b5 manifests/densify_sn_amending_not_added.jsonl
9
+ f6f075d3b88033ee06e69ea4bf9c553c64ec24ea3f41175cf4ecbb243bec279d scrapers/README.md
10
+ 03b2ced6ba93f8d387bca7b53e86fb9f8c32619706ec4612a592a44db5682548 scrapers/code.json
11
+ 507acbc9b48b84277688ef9f72f2b6f1f79380838bf9baeab923d52a7fb6a3d1 scrapers/collect_de_laender.py
12
+ 963ef4d135458eb8e11de9048ac5b1b81249585dbb8c172be9e52941c9958567 scrapers/de_lib.py
13
+ 4587e8d9e0b7ce55dffef23d874dae7a03b1093fdead26fd8313d5597c86a31f scrapers/de_queue.example.txt
14
+ 026850a3461008942beb7f5299b3ee58daecf4e7e7e005dcf8baa4e47666a79d scrapers/de_waiter.sh
15
+ af4465eb44fc84a744176116094436fc01a04d689886cf57da66e5d6347b16ec scrapers/finalize_gate.py
16
+ 315a8fe0768c6d33bb8d3b388508461187959cef48bd4f5aa3630104e95b2f8b scrapers/fix_contents_titles.py
17
+ 2dcc695bebf6ea306c045b13e483097353be8f402e90a8fd3984fa21b3260d1c scrapers/fix_lawtext_br.py
18
+ 048fdd4e5f999ebb49db7491fe9f98c2792a5236cf57f5c7798c260ee927b117 scrapers/fix_sn.py
19
+ fbfbe563bf0b7ceebb8478f8600654dd0f9014c0f3f1a6d467a16230b24a883d scrapers/gate_profile.sh
20
+ b2f838db772d33a17e51abaedde6adb4e8ac96e4b067761d1a4dc2e0b7db6092 scrapers/pack_de.py
21
+ 582f60ecb86fedce8c78fb4cb1b814e8d1ca9b84d72349b4aa9cea7c051dd40f scrapers/refetch_de.py
22
+ 7ec8cb4ff762e625dcf70bb8be15f166ef93cf602ffb234c6c8192a86f5762af scrapers/refetch_de.sh
23
+ 7420dd98db2604b7f2ef9ccbf8679d5aceb9bdd8f769bfca587ae19e15e5be00 scrapers/requirements.txt
24
+ 87915efb8db8d5863f7a2d209b27ae4c64bfde7126dd5bf388242b5ed8c3c96b scrapers/resume_loop_de.sh
25
+ fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542 scrapers/robots_guard.py
26
+ 9b7e5d48f8803a9e6f83e630f03e7110b96f5ea8971adaec771b4c7db50d9798 scrapers/run_de_short.sh
27
+ 129c7f34bcacb6ba9bfdd856c68d9b5e33e547107689bde17afa9f61de9e8e09 scrapers/short_turn.sh
28
+ 788bd4924861d35f5317b48682712d582190bcfcff3fe9410033b9f8ef5b7418 scrapers/tests/test_de_laender.py
29
+ f63e7554e32afe1e734fe0043271764aaca6899ae4f24f933ed0fe0f6734f49b scrapers/tests/test_finalize_gate.py
30
+ 9811842a3c165c0671d8e150359bba808931088fdf880b43b93adb6b25fb67f6 scrapers/tests/test_fix_contents_titles.py
31
+ 994e6a99b74f47d3dc283977cc7021a37c6ff0153da61623d61dd9a96d0817ea scrapers/tests/test_fix_lawtext_br.py
32
+ 6870695e1c3c224c82b1110bb36bcdb0f52be134b98da726456b5e2b483a5264 scrapers/tests/test_fix_sn.py
33
+ 6f6681d63f90858cf01924133e07a26d9c56e1f783b7ed35017e513ceb5ce7b7 scrapers/tests/test_short_turn.py
34
+ 69fc225e9bdfd05af3c52b5448fe80fae1b91cb98c6bbf409787d47ff4500d79 scrapers/tests/test_sn_rework.py
manifests/densify_sn_amending_added_ids.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
manifests/densify_sn_amending_code.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "de_lib.py": "963ef4d135458eb8e11de9048ac5b1b81249585dbb8c172be9e52941c9958567",
3
+ "collect_de_laender.py": "507acbc9b48b84277688ef9f72f2b6f1f79380838bf9baeab923d52a7fb6a3d1",
4
+ "pack_de.py": "b2f838db772d33a17e51abaedde6adb4e8ac96e4b067761d1a4dc2e0b7db6092",
5
+ "robots_guard.py": "fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542",
6
+ "run_de_short.sh": "9b7e5d48f8803a9e6f83e630f03e7110b96f5ea8971adaec771b4c7db50d9798",
7
+ "resume_loop_de.sh": "87915efb8db8d5863f7a2d209b27ae4c64bfde7126dd5bf388242b5ed8c3c96b",
8
+ "de_waiter.sh": "026850a3461008942beb7f5299b3ee58daecf4e7e7e005dcf8baa4e47666a79d",
9
+ "gate_profile.sh": "fbfbe563bf0b7ceebb8478f8600654dd0f9014c0f3f1a6d467a16230b24a883d",
10
+ "de_queue.example.txt": "4587e8d9e0b7ce55dffef23d874dae7a03b1093fdead26fd8313d5597c86a31f",
11
+ "requirements.txt": "7420dd98db2604b7f2ef9ccbf8679d5aceb9bdd8f769bfca587ae19e15e5be00",
12
+ "README.md": "f6f075d3b88033ee06e69ea4bf9c553c64ec24ea3f41175cf4ecbb243bec279d",
13
+ "tests/test_de_laender.py": "788bd4924861d35f5317b48682712d582190bcfcff3fe9410033b9f8ef5b7418",
14
+ "short_turn.sh": "129c7f34bcacb6ba9bfdd856c68d9b5e33e547107689bde17afa9f61de9e8e09",
15
+ "tests/test_short_turn.py": "6f6681d63f90858cf01924133e07a26d9c56e1f783b7ed35017e513ceb5ce7b7",
16
+ "finalize_gate.py": "af4465eb44fc84a744176116094436fc01a04d689886cf57da66e5d6347b16ec",
17
+ "tests/test_finalize_gate.py": "f63e7554e32afe1e734fe0043271764aaca6899ae4f24f933ed0fe0f6734f49b",
18
+ "fix_sn.py": "048fdd4e5f999ebb49db7491fe9f98c2792a5236cf57f5c7798c260ee927b117",
19
+ "tests/test_fix_sn.py": "6870695e1c3c224c82b1110bb36bcdb0f52be134b98da726456b5e2b483a5264",
20
+ "fix_contents_titles.py": "315a8fe0768c6d33bb8d3b388508461187959cef48bd4f5aa3630104e95b2f8b",
21
+ "tests/test_fix_contents_titles.py": "9811842a3c165c0671d8e150359bba808931088fdf880b43b93adb6b25fb67f6",
22
+ "fix_lawtext_br.py": "2dcc695bebf6ea306c045b13e483097353be8f402e90a8fd3984fa21b3260d1c",
23
+ "tests/test_fix_lawtext_br.py": "994e6a99b74f47d3dc283977cc7021a37c6ff0153da61623d61dd9a96d0817ea",
24
+ "refetch_de.py": "582f60ecb86fedce8c78fb4cb1b814e8d1ca9b84d72349b4aa9cea7c051dd40f",
25
+ "refetch_de.sh": "7ec8cb4ff762e625dcf70bb8be15f166ef93cf602ffb234c6c8192a86f5762af",
26
+ "tests/test_sn_rework.py": "69fc225e9bdfd05af3c52b5448fe80fae1b91cb98c6bbf409787d47ff4500d79",
27
+ "_notes": {
28
+ "robots_guard.py": "robots_guard fa882316 (CoS 2026-10-17): adds 'rejected request|support id' to _CHALLENGE and a VERIFY_X509_STRICT-only TLS relax for 4 Taiwan hosts; no German host affected. Earlier DE packs were fetched with 1c9f28bc (one-hop, 2026-10-14)."
29
+ }
30
+ }
manifests/densify_sn_amending_known_gaps.jsonl ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "de-sn-10852:Anlagen", "law_id": "de-sn-10852", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
2
+ {"id": "de-sn-11376:Artikel", "law_id": "de-sn-11376", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
3
+ {"id": "de-sn-11615:Artikel", "law_id": "de-sn-11615", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
4
+ {"id": "de-sn-11615:Artikel#2", "law_id": "de-sn-11615", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
5
+ {"id": "de-sn-11696:Artikel#2", "law_id": "de-sn-11696", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
6
+ {"id": "de-sn-12046:Anlagen", "law_id": "de-sn-12046", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
7
+ {"id": "de-sn-12339:Artikel#13", "law_id": "de-sn-12339", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
8
+ {"id": "de-sn-12800:Artikel", "law_id": "de-sn-12800", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
9
+ {"id": "de-sn-12829:Anhang", "law_id": "de-sn-12829", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
10
+ {"id": "de-sn-12834:Anhang", "law_id": "de-sn-12834", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
11
+ {"id": "de-sn-12867:Artikel", "law_id": "de-sn-12867", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
12
+ {"id": "de-sn-12897:Anlagen", "law_id": "de-sn-12897", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
13
+ {"id": "de-sn-13995:Anhang", "law_id": "de-sn-13995", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
14
+ {"id": "de-sn-1540:Artikel", "law_id": "de-sn-1540", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
15
+ {"id": "de-sn-16702:Artikel#2", "law_id": "de-sn-16702", "action": "dropped", "reason": "footnote_digit_rows_dropped", "why": "heading plus only a footnote number/marker, no body"}
16
+ {"id": "de-sn-16864:Anhang", "law_id": "de-sn-16864", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
17
+ {"id": "de-sn-17410:Anlage", "law_id": "de-sn-17410", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
18
+ {"id": "de-sn-17573:Anhang", "law_id": "de-sn-17573", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
19
+ {"id": "de-sn-17593:Artikel#2", "law_id": "de-sn-17593", "action": "dropped", "reason": "footnote_digit_rows_dropped", "why": "heading plus only a footnote number/marker, no body"}
20
+ {"id": "de-sn-17845:Anhang", "law_id": "de-sn-17845", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
21
+ {"id": "de-sn-17849:Anlage", "law_id": "de-sn-17849", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
22
+ {"id": "de-sn-17892:Anhang", "law_id": "de-sn-17892", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
23
+ {"id": "de-sn-17924:Anlagen", "law_id": "de-sn-17924", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
24
+ {"id": "de-sn-17985:Anhänge", "law_id": "de-sn-17985", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
25
+ {"id": "de-sn-18048:Artikel", "law_id": "de-sn-18048", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
26
+ {"id": "de-sn-18270:Artikel#3", "law_id": "de-sn-18270", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
27
+ {"id": "de-sn-18704:Anhang", "law_id": "de-sn-18704", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
28
+ {"id": "de-sn-18740:Anlage", "law_id": "de-sn-18740", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
29
+ {"id": "de-sn-18816:Artikel", "law_id": "de-sn-18816", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
30
+ {"id": "de-sn-18905:Anhänge", "law_id": "de-sn-18905", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
31
+ {"id": "de-sn-18922:Anhang", "law_id": "de-sn-18922", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
32
+ {"id": "de-sn-19087:Anhang zu Artikel 1 Nummer 3", "law_id": "de-sn-19087", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
33
+ {"id": "de-sn-1915:Artikel", "law_id": "de-sn-1915", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
34
+ {"id": "de-sn-19261:Anhang zu Artikel 1 Nummer 7", "law_id": "de-sn-19261", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
35
+ {"id": "de-sn-19408:Artikel#2", "law_id": "de-sn-19408", "action": "kept", "reason": "repealed_placeholder", "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"}
36
+ {"id": "de-sn-19843:Anlage", "law_id": "de-sn-19843", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
37
+ {"id": "de-sn-19895:Anlage", "law_id": "de-sn-19895", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
38
+ {"id": "de-sn-19985:Artikel", "law_id": "de-sn-19985", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
39
+ {"id": "de-sn-20002:Artikel", "law_id": "de-sn-20002", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
40
+ {"id": "de-sn-20350:Anhang", "law_id": "de-sn-20350", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
41
+ {"id": "de-sn-20357:Anhang", "law_id": "de-sn-20357", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
42
+ {"id": "de-sn-20769:Anlagen", "law_id": "de-sn-20769", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
43
+ {"id": "de-sn-20785:Artikel#2", "law_id": "de-sn-20785", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
44
+ {"id": "de-sn-20785:Artikel#3", "law_id": "de-sn-20785", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
45
+ {"id": "de-sn-20980:Artikel", "law_id": "de-sn-20980", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
46
+ {"id": "de-sn-21005:Artikel", "law_id": "de-sn-21005", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
47
+ {"id": "de-sn-21009:Artikel", "law_id": "de-sn-21009", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/�� with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
48
+ {"id": "de-sn-21083:Anhang zu Nummer 60 und 63", "law_id": "de-sn-21083", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
49
+ {"id": "de-sn-21119:Anhang", "law_id": "de-sn-21119", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
50
+ {"id": "de-sn-21195:Artikel", "law_id": "de-sn-21195", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
51
+ {"id": "de-sn-21304:Anlagen", "law_id": "de-sn-21304", "action": "dropped", "reason": "attachment_stubs_dropped", "why": "attachment stub (e.g. 'Anlagen' -> 'Karte'): the attachment itself is not on the page"}
52
+ {"id": "de-sn-21417:Artikel", "law_id": "de-sn-21417", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
53
+ {"id": "de-sn-21520:Artikel", "law_id": "de-sn-21520", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
54
+ {"id": "de-sn-3982:Artikel", "law_id": "de-sn-3982", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
55
+ {"id": "de-sn-4371:Artikel", "law_id": "de-sn-4371", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
56
+ {"id": "de-sn-4371:Artikel#2", "law_id": "de-sn-4371", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
57
+ {"id": "de-sn-4976:Anlagen", "law_id": "de-sn-4976", "action": "dropped", "reason": "attachment_stubs_dropped", "why": "attachment stub (e.g. 'Anlagen' -> 'Karte'): the attachment itself is not on the page"}
58
+ {"id": "de-sn-5010:Übersichtskarte", "law_id": "de-sn-5010", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
59
+ {"id": "de-sn-5010:Flurkarte 1", "law_id": "de-sn-5010", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
60
+ {"id": "de-sn-5010:Flurkarte 2", "law_id": "de-sn-5010", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
61
+ {"id": "de-sn-5010:Flurkarte 3", "law_id": "de-sn-5010", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
62
+ {"id": "de-sn-5010:Flurkarte 4", "law_id": "de-sn-5010", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
63
+ {"id": "de-sn-5041:Artikel#7", "law_id": "de-sn-5041", "action": "kept", "reason": "repealed_placeholder", "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"}
64
+ {"id": "de-sn-5041:Artikel#8", "law_id": "de-sn-5041", "action": "kept", "reason": "repealed_placeholder", "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"}
65
+ {"id": "de-sn-5041:Artikel#9", "law_id": "de-sn-5041", "action": "kept", "reason": "repealed_placeholder", "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"}
66
+ {"id": "de-sn-5041:Artikel#10", "law_id": "de-sn-5041", "action": "kept", "reason": "repealed_placeholder", "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"}
67
+ {"id": "de-sn-5119:Artikel#2", "law_id": "de-sn-5119", "action": "dropped", "reason": "norm_headings_dropped", "why": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel"}
68
+ {"id": "de-sn-5490:Übersichtskarten  1 bis 5", "law_id": "de-sn-5490", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
69
+ {"id": "de-sn-5623:Übersichtskarte", "law_id": "de-sn-5623", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
70
+ {"id": "de-sn-5624:Übersichtskarte", "law_id": "de-sn-5624", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
71
+ {"id": "de-sn-9571:Anlage", "law_id": "de-sn-9571", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
72
+ {"id": "de-sn-9757:Übersichtskarte", "law_id": "de-sn-9757", "action": "dropped", "reason": "headings_dropped", "why": "trailing heading-only row (no following article to fold into)"}
manifests/densify_sn_amending_not_added.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
scrapers/README.md CHANGED
@@ -48,7 +48,7 @@ export DE_WORK=/workspace/de_laender/work
48
  .venv/bin/python pack_de.py ids --out $DE_WORK/hub_tip_ids.txt # public Hub read, no token
49
  nohup ./de_waiter.sh >/dev/null 2>&1 & # ONE waiter; walks de_queue.txt behind GI, v2 gate, 300 s stagger
50
  # one slice by hand: .venv/bin/python collect_de_laender.py --land SN --tag amending --kinds amending --existing-ids $DE_WORK/hub_tip_ids.txt
51
- .venv/bin/python pack_de.py build --land SN --tags -,amending --live-laws tip_laws.parquet --live-articles tip_articles.parquet
52
  .venv/bin/python pack_de.py build --land NW --tags delta [--include-updates] ...
53
  DE_HUB_TIP=<current tip> .venv/bin/python pack_de.py stage --land SN # tip unchanged -> READY_germany_laws_densify_sn
54
  ```
@@ -100,3 +100,30 @@ leaked into a title after the `Vom <date>` line is cut, and article_count is rec
100
  - 2026-10-15 23:20 PT: `fix_lawtext_br.py` restores, as line breaks, the `<br>` spots the headings fix had glued in DE-SN law texts
101
  (exact positions from the pre-fix raw text; re-runs the legacy cleaning and requires a byte-exact match). Its `stage` refuses READY
102
  until `<out>/HUB_PARENT` holds the live commit of the base pack and the live data shas equal the staged base. Tests `tests/test_fix_lawtext_br.py`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  .venv/bin/python pack_de.py ids --out $DE_WORK/hub_tip_ids.txt # public Hub read, no token
49
  nohup ./de_waiter.sh >/dev/null 2>&1 & # ONE waiter; walks de_queue.txt behind GI, v2 gate, 300 s stagger
50
  # one slice by hand: .venv/bin/python collect_de_laender.py --land SN --tag amending --kinds amending --existing-ids $DE_WORK/hub_tip_ids.txt
51
+ .venv/bin/python pack_de.py build --land SN --tags=-,amending --live-laws tip_laws.parquet --live-articles tip_articles.parquet
52
  .venv/bin/python pack_de.py build --land NW --tags delta [--include-updates] ...
53
  DE_HUB_TIP=<current tip> .venv/bin/python pack_de.py stage --land SN # tip unchanged -> READY_germany_laws_densify_sn
54
  ```
 
100
  - 2026-10-15 23:20 PT: `fix_lawtext_br.py` restores, as line breaks, the `<br>` spots the headings fix had glued in DE-SN law texts
101
  (exact positions from the pre-fix raw text; re-runs the legacy cleaning and requires a byte-exact match). Its `stage` refuses READY
102
  until `<out>/HUB_PARENT` holds the live commit of the base pack and the live data shas equal the staged base. Tests `tests/test_fix_lawtext_br.py`.
103
+
104
+ ## DE-SN amending rework (CoS rejection 2026-10-17)
105
+
106
+ - **PII scan** (`de_lib.pii_scan`) redacts only personal data of private individuals. Kept verbatim: official accounts printed in
107
+ law (Bundesbank BLZ `xxx00000`, a public payee such as Landeshauptkasse/Staatskasse within 160 chars before, or BIC MARKDEF1),
108
+ official / functional mailboxes (government domains incl. sub-domains such as `justiz.`, `@sachsen.de`, local parts such as
109
+ poststelle/datenschutz/spammeldung). The tax-id rule needs a Steuer-ID label within 40 chars on the same line, so table numbers
110
+ never match. Tests: `tests/test_sn_rework.py`.
111
+ - **SN parser**: tags are removed across lines (attribute-aware), a `>` inside a quoted attribute no longer ends `<section …>`,
112
+ a section without a title attribute takes its own heading line (never the internal anchor such as `a2`), footnote anchors
113
+ become `[n]` + `Fußnoten:`. Word breaks lost in one rendering of a heading (title attribute / Eingangsformel h3) are restored
114
+ from the h4 / h1 / Vollzitat rendering of the same words (`_respace`). Other Länder still use `_text`.
115
+ - **finalize_gate**: raw HTML is any tag-shaped string (generic regex, not a tag list), also escaped `&lt;tag`, comments,
116
+ attribute residue `">` and footnote attributes, in titles, texts AND every metadata_json string. `heading_only_ids` lists
117
+ rows with no body beyond their heading; repeal placeholders (`(aufgehoben)`, `weggefallen`, …) are kept and tagged
118
+ `metadata_json.body_status = "repealed_placeholder"` (metadata, no new column).
119
+ - **clean_record**: an empty `Artikel N` heading is never merged into Artikel N+1 (dropped, listed as a known gap; revosax prints
120
+ the body of a Mantelgesetz's Artikel as its own /vorschrift page); footnote-digit rows and attachment stubs (`Karte`,
121
+ `Anhang` with no text) are dropped; other heading-only rows still fold into the next row.
122
+ - **Page cache + re-fetch**: SN/BB/NW/HB pages are cached gzip under `$DE_PAGE_CACHE` (default `/workspace/de_laender/page_cache/<lane>`,
123
+ outside `$DE_WORK`, so not counted in the tree cap). `refetch_de.sh <LAND> <tag> <ids>` re-fetches only uncached pages under
124
+ the light gate, the short-lane flock (`flock -n`, never waits holding it), the 300 s stagger and the robots guard; it does not
125
+ touch the GI/DE turn files. `refetch_de.py reparse` rebuilds records offline from the cache (old record kept once in `records_prev/`).
126
+ A connection dropped mid-body is `Transient` (one retry, then the id is skipped and reported).
127
+ - **pack_de build** writes `manifests/<prefix>_added_ids.jsonl` (every added law and article id), `_known_gaps.jsonl` and
128
+ `_not_added.jsonl`, and with `--readme <live README>` a cumulative README (live README + new section); the gate checks the
129
+ README counts and the manifest against the parquet.
scrapers/code.json CHANGED
@@ -1,24 +1,30 @@
1
  {
2
- "de_lib.py": "410a63b8b89f9cd870711ba76b3bf814e1a3e6d94236939344ef508a17610c90",
3
- "collect_de_laender.py": "6d3295170bf67bf187bbf361e9e5c9a77fbe5d2fb5c7149bd4b9966e7e479faf",
4
- "pack_de.py": "a386a7b235b3bf4f1eb0e3df86ef73ef9e3c8688ff7182015df9d730cee79b99",
5
- "robots_guard.py": "1c9f28bcf6851eaff85180c90bdf8054a3500edca773c5c5a84701e6053f0990",
6
  "run_de_short.sh": "9b7e5d48f8803a9e6f83e630f03e7110b96f5ea8971adaec771b4c7db50d9798",
7
  "resume_loop_de.sh": "87915efb8db8d5863f7a2d209b27ae4c64bfde7126dd5bf388242b5ed8c3c96b",
8
  "de_waiter.sh": "026850a3461008942beb7f5299b3ee58daecf4e7e7e005dcf8baa4e47666a79d",
9
  "gate_profile.sh": "fbfbe563bf0b7ceebb8478f8600654dd0f9014c0f3f1a6d467a16230b24a883d",
10
  "de_queue.example.txt": "4587e8d9e0b7ce55dffef23d874dae7a03b1093fdead26fd8313d5597c86a31f",
11
  "requirements.txt": "7420dd98db2604b7f2ef9ccbf8679d5aceb9bdd8f769bfca587ae19e15e5be00",
12
- "README.md": "792bd097762ac6419bda46b832c8aa7846168c42732e7a45191666fd629eb7c3",
13
  "tests/test_de_laender.py": "788bd4924861d35f5317b48682712d582190bcfcff3fe9410033b9f8ef5b7418",
14
  "short_turn.sh": "129c7f34bcacb6ba9bfdd856c68d9b5e33e547107689bde17afa9f61de9e8e09",
15
  "tests/test_short_turn.py": "6f6681d63f90858cf01924133e07a26d9c56e1f783b7ed35017e513ceb5ce7b7",
16
- "finalize_gate.py": "09a00eec60380b50e94ef57ec069add4835104bc34082c3981482054af1d12ad",
17
- "tests/test_finalize_gate.py": "9aec8bddfd4f9f65250e3def710f63097e9e5a2e85fcb4ca1304d0f2e10f8401",
18
  "fix_sn.py": "048fdd4e5f999ebb49db7491fe9f98c2792a5236cf57f5c7798c260ee927b117",
19
  "tests/test_fix_sn.py": "6870695e1c3c224c82b1110bb36bcdb0f52be134b98da726456b5e2b483a5264",
20
  "fix_contents_titles.py": "315a8fe0768c6d33bb8d3b388508461187959cef48bd4f5aa3630104e95b2f8b",
21
  "tests/test_fix_contents_titles.py": "9811842a3c165c0671d8e150359bba808931088fdf880b43b93adb6b25fb67f6",
22
  "fix_lawtext_br.py": "2dcc695bebf6ea306c045b13e483097353be8f402e90a8fd3984fa21b3260d1c",
23
- "tests/test_fix_lawtext_br.py": "994e6a99b74f47d3dc283977cc7021a37c6ff0153da61623d61dd9a96d0817ea"
 
 
 
 
 
 
24
  }
 
1
  {
2
+ "de_lib.py": "963ef4d135458eb8e11de9048ac5b1b81249585dbb8c172be9e52941c9958567",
3
+ "collect_de_laender.py": "507acbc9b48b84277688ef9f72f2b6f1f79380838bf9baeab923d52a7fb6a3d1",
4
+ "pack_de.py": "b2f838db772d33a17e51abaedde6adb4e8ac96e4b067761d1a4dc2e0b7db6092",
5
+ "robots_guard.py": "fa8823164631f53174a67a4b100f5278758b151c3e6a522d8c9987bb57753542",
6
  "run_de_short.sh": "9b7e5d48f8803a9e6f83e630f03e7110b96f5ea8971adaec771b4c7db50d9798",
7
  "resume_loop_de.sh": "87915efb8db8d5863f7a2d209b27ae4c64bfde7126dd5bf388242b5ed8c3c96b",
8
  "de_waiter.sh": "026850a3461008942beb7f5299b3ee58daecf4e7e7e005dcf8baa4e47666a79d",
9
  "gate_profile.sh": "fbfbe563bf0b7ceebb8478f8600654dd0f9014c0f3f1a6d467a16230b24a883d",
10
  "de_queue.example.txt": "4587e8d9e0b7ce55dffef23d874dae7a03b1093fdead26fd8313d5597c86a31f",
11
  "requirements.txt": "7420dd98db2604b7f2ef9ccbf8679d5aceb9bdd8f769bfca587ae19e15e5be00",
12
+ "README.md": "f6f075d3b88033ee06e69ea4bf9c553c64ec24ea3f41175cf4ecbb243bec279d",
13
  "tests/test_de_laender.py": "788bd4924861d35f5317b48682712d582190bcfcff3fe9410033b9f8ef5b7418",
14
  "short_turn.sh": "129c7f34bcacb6ba9bfdd856c68d9b5e33e547107689bde17afa9f61de9e8e09",
15
  "tests/test_short_turn.py": "6f6681d63f90858cf01924133e07a26d9c56e1f783b7ed35017e513ceb5ce7b7",
16
+ "finalize_gate.py": "af4465eb44fc84a744176116094436fc01a04d689886cf57da66e5d6347b16ec",
17
+ "tests/test_finalize_gate.py": "f63e7554e32afe1e734fe0043271764aaca6899ae4f24f933ed0fe0f6734f49b",
18
  "fix_sn.py": "048fdd4e5f999ebb49db7491fe9f98c2792a5236cf57f5c7798c260ee927b117",
19
  "tests/test_fix_sn.py": "6870695e1c3c224c82b1110bb36bcdb0f52be134b98da726456b5e2b483a5264",
20
  "fix_contents_titles.py": "315a8fe0768c6d33bb8d3b388508461187959cef48bd4f5aa3630104e95b2f8b",
21
  "tests/test_fix_contents_titles.py": "9811842a3c165c0671d8e150359bba808931088fdf880b43b93adb6b25fb67f6",
22
  "fix_lawtext_br.py": "2dcc695bebf6ea306c045b13e483097353be8f402e90a8fd3984fa21b3260d1c",
23
+ "tests/test_fix_lawtext_br.py": "994e6a99b74f47d3dc283977cc7021a37c6ff0153da61623d61dd9a96d0817ea",
24
+ "refetch_de.py": "582f60ecb86fedce8c78fb4cb1b814e8d1ca9b84d72349b4aa9cea7c051dd40f",
25
+ "refetch_de.sh": "7ec8cb4ff762e625dcf70bb8be15f166ef93cf602ffb234c6c8192a86f5762af",
26
+ "tests/test_sn_rework.py": "69fc225e9bdfd05af3c52b5448fe80fae1b91cb98c6bbf409787d47ff4500d79",
27
+ "_notes": {
28
+ "robots_guard.py": "robots_guard fa882316 (CoS 2026-10-17): adds 'rejected request|support id' to _CHALLENGE and a VERIFY_X509_STRICT-only TLS relax for 4 Taiwan hosts; no German host affected. Earlier DE packs were fetched with 1c9f28bc (one-hop, 2026-10-14)."
29
+ }
30
  }
scrapers/collect_de_laender.py CHANGED
@@ -14,12 +14,13 @@ Every request (and every redirect hop, via robots_guard.GuardedSession) is robot
14
  stops the run. Spacing per host = max(land min_delay, robots Crawl-delay) (BB: 20 s).
15
  Exit: 0 slice/done, 5 licence flag missing (NI/HB), 2 robots (disallow, or 3rd consecutive robots.txt network failure), 3 land disabled,
16
  4 memory (<3 GiB for 15 s) / RSS > 1 GiB, 6 host park (401/403/429/challenge -> work/PARKED_host), 143 SIGTERM.
17
- Output: work/<land>/records/<id>.json ({"law": row, "articles": [...], "pii_hits": n, "bounds": [...]})
18
  """
19
  import argparse, json, os, re, signal, sys, threading, time
20
  from pathlib import Path
21
 
22
  import requests
 
23
 
24
  BASE_WORK = Path(os.environ.get("DE_WORK", "/workspace/de_laender/work"))
25
  os.environ["LEGAL_CORPORA_ROOT"] = os.environ.get("DE_GUARD_ROOT", str(BASE_WORK.parent / "guard_root"))
@@ -28,6 +29,7 @@ sys.path.insert(0, str(HERE))
28
  import de_lib as L # noqa: E402
29
  import robots_guard as RG # noqa: E402
30
 
 
31
  SLICE_S = int(os.environ.get("DE_SLICE_SECONDS", "1680"))
32
  RSS_CAP_MB = 1024
33
  MAX_ROBOTS_TLS = 3
@@ -123,6 +125,9 @@ class Lane:
123
  self.state_path = self.work / "state.json"
124
  self.parked = self.work / "PARKED_host"
125
  self.req_log = self.work / "requests.jsonl"
 
 
 
126
  self.st = {"queue": {}, "done_ids": [], "ok": 0, "skipped_existing": 0, "bounds_rejects": 0, "pii_hits": 0, "errors": 0,
127
  "text_bytes": 0, "requests": 0, "seeded": False, "done": False, "stop_reason": "", "robots_tls_run": 0,
128
  "frontier": [], "seen_lists": [], "tip_updates": 0, "kind_filtered": 0}
@@ -156,7 +161,10 @@ class Lane:
156
  last = exc; time.sleep(15)
157
  if r is None:
158
  raise Transient(str(last))
159
- body = r.raw.read(L.BOUNDS["max_page_bytes"] + 1, decode_content=True) or b""
 
 
 
160
  head = body[:6000].decode("utf-8", "replace")
161
  challenge = bool(CHAL.search(head) and not any(m in head for m in SITE_MARK.get(self.land, ())))
162
  with self.req_log.open("a") as f:
@@ -173,6 +181,20 @@ class Lane:
173
  self.st["requests"] += 1; self.st["robots_tls_run"] = 0
174
  return body.decode(r.encoding or "utf-8", "replace")
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  # ------------------------------------------------------------ seeding (resumable frontier of listing pages)
177
  def _q(self, key, url, kind, **extra):
178
  if kind not in self.kinds:
@@ -256,13 +278,13 @@ class Lane:
256
  def item(self, s, rid, v, t0):
257
  land = self.land
258
  if land == "SN":
259
- info = L.parse_sn_page(self.fetch(s, v["url"], "law"), v["url"])
260
  elif land == "BB":
261
- info = L.parse_bb_page(self.fetch(s, v["url"], "law"), v["url"])
262
  elif land == "NW":
263
- info = L.parse_nw_page(self.fetch(s, v["url"], "law"), v["url"]); info["lastmod"] = v.get("lastmod")
264
  elif land == "HB":
265
- info = L.parse_hb_page(self.fetch(s, v["url"], "law"), v["url"], rid)
266
  elif land == "NI":
267
  part = self.work / "partial" / f"{rid}.json"; part.parent.mkdir(parents=True, exist_ok=True)
268
  pc = json.loads(part.read_text()) if part.exists() else {"docs": None, "got": {}}
 
14
  stops the run. Spacing per host = max(land min_delay, robots Crawl-delay) (BB: 20 s).
15
  Exit: 0 slice/done, 5 licence flag missing (NI/HB), 2 robots (disallow, or 3rd consecutive robots.txt network failure), 3 land disabled,
16
  4 memory (<3 GiB for 15 s) / RSS > 1 GiB, 6 host park (401/403/429/challenge -> work/PARKED_host), 143 SIGTERM.
17
+ Output: work/<land>/records/<id>.json ({"law": row, "articles": [...], "pii_hits": n, "bounds": [...]}); raw pages: $DE_PAGE_CACHE/<land>[_<tag>]/<rid>.html.gz
18
  """
19
  import argparse, json, os, re, signal, sys, threading, time
20
  from pathlib import Path
21
 
22
  import requests
23
+ import urllib3
24
 
25
  BASE_WORK = Path(os.environ.get("DE_WORK", "/workspace/de_laender/work"))
26
  os.environ["LEGAL_CORPORA_ROOT"] = os.environ.get("DE_GUARD_ROOT", str(BASE_WORK.parent / "guard_root"))
 
29
  import de_lib as L # noqa: E402
30
  import robots_guard as RG # noqa: E402
31
 
32
+ PAGE_CACHE = Path(os.environ.get("DE_PAGE_CACHE", str(BASE_WORK.parent / "page_cache")))
33
  SLICE_S = int(os.environ.get("DE_SLICE_SECONDS", "1680"))
34
  RSS_CAP_MB = 1024
35
  MAX_ROBOTS_TLS = 3
 
125
  self.state_path = self.work / "state.json"
126
  self.parked = self.work / "PARKED_host"
127
  self.req_log = self.work / "requests.jsonl"
128
+ # gz page cache (added 2026-10-17): re-parse offline after a parser fix instead of re-fetching. Kept OUTSIDE $DE_WORK so
129
+ # it never counts toward the lane-tree gate cap (300 MB). Default /workspace/de_laender/page_cache/<land>[_<tag>].
130
+ self.pages = PAGE_CACHE / self.work.name
131
  self.st = {"queue": {}, "done_ids": [], "ok": 0, "skipped_existing": 0, "bounds_rejects": 0, "pii_hits": 0, "errors": 0,
132
  "text_bytes": 0, "requests": 0, "seeded": False, "done": False, "stop_reason": "", "robots_tls_run": 0,
133
  "frontier": [], "seen_lists": [], "tip_updates": 0, "kind_filtered": 0}
 
161
  last = exc; time.sleep(15)
162
  if r is None:
163
  raise Transient(str(last))
164
+ try: # a connection dropped mid-body is transient, not a crash (urllib3 ProtocolError is not a RequestException)
165
+ body = r.raw.read(L.BOUNDS["max_page_bytes"] + 1, decode_content=True) or b""
166
+ except (requests.RequestException, urllib3.exceptions.HTTPError, OSError) as exc:
167
+ r.close(); raise Transient(f"body read failed {url}: {exc}")
168
  head = body[:6000].decode("utf-8", "replace")
169
  challenge = bool(CHAL.search(head) and not any(m in head for m in SITE_MARK.get(self.land, ())))
170
  with self.req_log.open("a") as f:
 
181
  self.st["requests"] += 1; self.st["robots_tls_run"] = 0
182
  return body.decode(r.encoding or "utf-8", "replace")
183
 
184
+ def cache_page(self, rid, page):
185
+ """Keep the raw fetched page (gzip) so a later parser fix re-parses it offline instead of re-fetching."""
186
+ import gzip
187
+ self.pages.mkdir(parents=True, exist_ok=True)
188
+ tmp = self.pages / f".{rid}.html.gz.tmp"
189
+ with gzip.open(tmp, "wt", encoding="utf-8") as f:
190
+ f.write(page)
191
+ tmp.replace(self.pages / f"{rid}.html.gz")
192
+
193
+ def fetch_page(self, s, rid, url, kind="law"):
194
+ page = self.fetch(s, url, kind)
195
+ self.cache_page(rid, page)
196
+ return page
197
+
198
  # ------------------------------------------------------------ seeding (resumable frontier of listing pages)
199
  def _q(self, key, url, kind, **extra):
200
  if kind not in self.kinds:
 
278
  def item(self, s, rid, v, t0):
279
  land = self.land
280
  if land == "SN":
281
+ info = L.parse_sn_page(self.fetch_page(s, rid, v["url"]), v["url"])
282
  elif land == "BB":
283
+ info = L.parse_bb_page(self.fetch_page(s, rid, v["url"]), v["url"])
284
  elif land == "NW":
285
+ info = L.parse_nw_page(self.fetch_page(s, rid, v["url"]), v["url"]); info["lastmod"] = v.get("lastmod")
286
  elif land == "HB":
287
+ info = L.parse_hb_page(self.fetch_page(s, rid, v["url"]), v["url"], rid)
288
  elif land == "NI":
289
  part = self.work / "partial" / f"{rid}.json"; part.parent.mkdir(parents=True, exist_ok=True)
290
  pc = json.loads(part.read_text()) if part.exists() else {"docs": None, "got": {}}
scrapers/de_lib.py CHANGED
@@ -9,7 +9,7 @@ from urllib.parse import urlsplit
9
 
10
  COUNTRY, LANG = "Germany", "de"
11
  HUB_REPO = "endomorphosis/ipfs_germany_laws"
12
- HUB_TIP = os.environ.get("DE_HUB_TIP", "f9384361294208adf8ce7f0a7fc2f3eb66cd8434") # DE-SN headings fix live 2026-10-15 23:05 PT (parent e5474984); set after each upload
13
 
14
  # Per-Land adapters. enabled=False lands are refused by the collector (no request is ever made).
15
  LANDS = {
@@ -99,60 +99,254 @@ def de_date(s):
99
  return f"{int(m.group(3)):04d}-{MONTHS[m.group(2).lower()]:02d}-{int(m.group(1)):02d}"
100
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def parse_sn_page(page, url):
103
  """REVOSax /vorschrift/<id> page -> title, date, vollzitat, sections."""
104
  page = page or ""
105
  m = RE_SN_LAW.match(urlsplit(url).path)
106
  rid = m.group(1) if m else ""
107
  h1 = re.search(r"<h1[^>]*>(.*?)</h1>", page, re.S)
108
- short = _text(h1.group(1)) if h1 else ""
109
  vz = re.search(r"<p>\s*Vollzitat:(.*?)</p>", page, re.S)
110
- vollzitat = _text(vz.group(1)) if vz else ""
111
- head = re.search(r'<header[^>]*title="Eingangsformel"[^>]*>(.*?)</header>', page, re.S)
112
- long_title = _text(re.sub(r"(?s)<p.*", "", head.group(1))).replace("\n", " ") if head else ""
 
 
 
 
 
 
 
 
113
  vom = re.search(r"<b>\s*Vom\s+([^<]+)</b>", head.group(1)) if head else None
114
  date = de_date(vom.group(1)) if vom else de_date(vollzitat)
115
  art = re.search(r'<article[^>]*id="lesetext"[^>]*>(.*?)</article>', page, re.S)
116
  body = art.group(1) if art else ""
117
  secs = []
118
- opens = list(re.finditer(r'<section\b([^>]*)>', body))
119
  for k, sm in enumerate(opens): # nested sections: each section's own text runs to the next <section> opening
120
  attrs = sm.group(1)
121
  inner = body[sm.end(): opens[k + 1].start() if k + 1 < len(opens) else len(body)]
122
- t = re.search(r'title="([^"]*)"', attrs)
123
- a = re.search(r'id="([^"]*)"', attrs)
124
- txt = _text(inner)
125
  if txt:
126
- secs.append({"anchor": a.group(1) if a else str(len(secs) + 1), "title": html.unescape(t.group(1)) if t else "", "text": txt})
127
- full = _text(body)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  return {"revosax_id": rid, "short_title": short, "title": long_title or short, "vollzitat": vollzitat, "date": date,
129
  "sections": secs, "text": full}
130
 
131
 
132
  # ---------------------------------------------------------------- PII scan (gazette texts normally carry none)
133
- RE_EMAIL = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
134
- RE_IBAN = re.compile(r"\bDE\d{2}(?:\s?\d{4}){4}\s?\d{2}\b")
135
- RE_STEUER = re.compile(r"\b\d{2}\s?\d{3}\s?\d{3}\s?\d{3}\b") # 11-digit Steuer-IdNr shape
136
- OFFICIAL_MAIL = re.compile(r"@(?:[a-z0-9-]+\.)*(?:sachsen|brandenburg|nrw|niedersachsen|bremen|bund|de\.eu)\.de$|@[a-z0-9.-]*\.(?:gov|europa\.eu)$", re.I)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
 
139
  def pii_scan(text):
140
- """Return (redacted_text, hits). Official authority mailboxes are kept; private mails, IBANs, phone-like
141
- numbers outside citation context and Steuer-IdNr shapes are redacted to [REDACTED-<kind>]."""
142
  hits = []
 
143
 
144
  def mail(m):
145
- if OFFICIAL_MAIL.search(m.group(0)):
146
  return m.group(0)
147
  hits.append(("email", m.group(0))); return "[REDACTED-email]"
148
- t = RE_EMAIL.sub(mail, text or "")
149
 
150
  def iban(m):
 
 
151
  hits.append(("iban", m.group(0))); return "[REDACTED-iban]"
152
  t = RE_IBAN.sub(iban, t)
153
 
154
  def steuer(m):
155
- hits.append(("taxid", m.group(0))); return "[REDACTED-taxid]"
156
  t = RE_STEUER.sub(steuer, t)
157
  return t, hits
158
 
@@ -480,9 +674,14 @@ def ni_assemble(node_label, docs):
480
 
481
  # ---- record clean-up (2026-10-15, after CoS rejected the DE-SN densify): applied to every collected record at pack time,
482
  # so it holds for every future Land pack. Live tip rows are never touched (append-only).
483
- from finalize_gate import strip_html_footnotes, strip_html_title, is_contents_row, fold_heading_rows # noqa: E402
 
484
 
485
  _TITLE_BODY = re.compile(r"(\sVom \d{1,2}\.\s*\S+\s+\d{4})\s+(\S.{20,})$", re.S)
 
 
 
 
486
 
487
 
488
  def clean_title(t):
@@ -492,11 +691,72 @@ def clean_title(t):
492
  return t[:m.end(1)].strip() if m else t
493
 
494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495
  def clean_record(rec):
496
- """Returns (rec, stats). Strips raw footnote HTML (-> '[n]' + plain 'Fußnoten:' block), drops contents-list rows,
497
- folds heading-only rows into the next article, trims body text out of titles, recomputes article_count."""
 
 
 
 
 
 
 
498
  st = {"footnote_rows": 0, "footnote_law_texts": 0, "contents_dropped": [], "headings_folded": 0, "headings_dropped": [],
499
- "titles_trimmed": []}
 
500
  law = dict(rec["law"])
501
  t, n = strip_html_footnotes(law.get("text") or "")
502
  if n or t != (law.get("text") or ""):
@@ -504,6 +764,8 @@ def clean_record(rec):
504
  nt = clean_title(law.get("title"))
505
  if nt != law.get("title"):
506
  st["titles_trimmed"].append(law["id"]); law["title"] = nt
 
 
507
  arts = []
508
  for a in rec.get("articles", []):
509
  a = dict(a)
@@ -512,10 +774,45 @@ def clean_record(rec):
512
  if tx != (a.get("text") or "") or ti != (a.get("title") or ""):
513
  st["footnote_rows"] += 1
514
  a["text"], a["title"] = tx, ti
 
 
515
  if is_contents_row(ti):
516
  st["contents_dropped"].append(a["id"]); continue
517
  arts.append(a)
518
- arts, folded, dropped = fold_heading_rows(arts)
519
- st["headings_folded"], st["headings_dropped"] = len(folded), dropped
520
- law["article_count"] = len(arts)
521
- return dict(rec, law=law, articles=arts), st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  COUNTRY, LANG = "Germany", "de"
11
  HUB_REPO = "endomorphosis/ipfs_germany_laws"
12
+ HUB_TIP = os.environ.get("DE_HUB_TIP", "92488791e93016b06d0c26e7dd158ab401c69522") # SN law-text <br> fix live 2026-10-15 23:22 PT (parent 9c40c341); set after each upload
13
 
14
  # Per-Land adapters. enabled=False lands are refused by the collector (no request is ever made).
15
  LANDS = {
 
99
  return f"{int(m.group(3)):04d}-{MONTHS[m.group(2).lower()]:02d}-{int(m.group(1)):02d}"
100
 
101
 
102
+ # ---- SN (REVOSax) parser, revised 2026-10-17 after CoS rejected the DE-SN amending densify. Root causes fixed here:
103
+ # * tags were stripped line by line, so a tag whose attribute value wraps (title="...\n...") survived as raw text
104
+ # (`<section data-anchor=...>`, `<a href=... title=...>`) -> tags are now removed across lines with an attribute-aware regex;
105
+ # * `<section\b([^>]*)>` stopped at a '>' inside a quoted attribute (title="...<br>..."), so the section lost its title (title fell
106
+ # back to the internal anchor, e.g. 'a2') and the rest of the attribute leaked into the text -> attribute-aware open-tag regex;
107
+ # * title attributes carrying markup (<br>, &lt;br&gt;, soft hyphen) lost the word break -> a line break / tag inside a title is
108
+ # a space, soft hyphens are dropped;
109
+ # * revosax itself drops a word break in ONE rendering of a heading: the section title attribute ('Artikel 1
110
+ # SächsischesWassergesetz (SächsWG)', de-sn-12867) or the Eingangsformel h3 ('zur Änderung derInfektionsschutzgesetz-...',
111
+ # de-sn-19479), while the h4 / h1 / Vollzitat print the same words with the break -> _respace() unites the word breaks of
112
+ # renderings that are identical ignoring whitespace; h1/Vollzitat compounds wrapped after a hyphen are re-joined;
113
+ # * footnote anchors on one line became bare digits ('... Fachschule 1'), split ones raw HTML -> every revosax footnote anchor is
114
+ # now a '[n]' marker plus a plain-text 'Fußnoten:' block (the format the pipeline already used).
115
+ _TAG_ANY = re.compile(r"""<[A-Za-z!/?](?:[^<>"']|"[^"]*"|'[^']*')*>""")
116
+ _SEC_OPEN = re.compile(r"""<section\b((?:[^>"']|"[^"]*"|'[^']*')*)>""")
117
+ _SN_FN = re.compile(r"""(?is)<a\b((?:[^>"']|"[^"]*"|'[^']*')*)>\s*([^<]{0,12}?)\s*</a\s*>""")
118
+ _NBSP_SHY = re.compile("[\xad\u200b]")
119
+
120
+
121
+ def _attr_val(attrs, name):
122
+ m = re.search(r"""(?is)(?:^|\s)%s\s*=\s*(?:"([^"]*)"|'([^']*)')""" % re.escape(name), attrs or "")
123
+ return (m.group(1) if m.group(1) is not None else m.group(2)) if m else None
124
+
125
+
126
+ def _plain_attr(v):
127
+ """Attribute text -> one line: entities decoded, markup (<br>, tags) and line breaks become spaces, soft hyphens dropped."""
128
+ v = html.unescape(v or "")
129
+ v = re.sub(r"(?i)<br\s*/?>", " ", v)
130
+ v = _TAG_ANY.sub(" ", v)
131
+ v = _NBSP_SHY.sub("", v)
132
+ return re.sub(r"[ \t\r\n]+", " ", v).strip()
133
+
134
+
135
+ def _sn_footnotes(fr, notes):
136
+ """revosax footnote anchors -> ' [n]'; their title attribute is collected into notes {n: text} (document order)."""
137
+ def rep(m):
138
+ attrs, label = m.group(1), (m.group(2) or "").strip()
139
+ href = _attr_val(attrs, "href") or ""; cls = _attr_val(attrs, "class") or ""
140
+ if "FNID_" not in href and "fussnote" not in cls:
141
+ return m.group(0)
142
+ n = (re.search(r"FNID_(\d+)", href) or re.search(r"(\d+)", label) or [None, str(len(notes) + 1)])[1]
143
+ note = _plain_attr(_attr_val(attrs, "title") or "")
144
+ if note and n not in notes:
145
+ notes[n] = note
146
+ return f" [{n}]"
147
+ return _SN_FN.sub(rep, fr or "")
148
+
149
+
150
+ def _sn_text(fr, notes=None):
151
+ """HTML fragment -> text lines. Same line-break rules as _text, but tags (incl. ones whose attributes wrap lines) are removed
152
+ across lines before the split; footnote anchors -> [n] (+ notes)."""
153
+ own = {} if notes is None else notes
154
+ fr = _sn_footnotes(fr, own)
155
+ fr = re.sub(r"""(?is)<(script|style)\b(?:[^>"']|"[^"]*"|'[^']*')*>.*?</\1\s*>""", " ", fr)
156
+ fr = re.sub(r"(?i)<br\s*/?>|</p\s*>|</dd\s*>|</dt\s*>|</h\d\s*>|</li\s*>|</tr\s*>", "\n", fr)
157
+ fr = _TAG_ANY.sub(" ", fr)
158
+ lines = [re.sub(r"[ \t\xa0]+", " ", html.unescape(ln)).strip() for ln in fr.split("\n")]
159
+ return "\n".join(l for l in lines if l)
160
+
161
+
162
+ _WS = re.compile(r"[\s\xa0]")
163
+
164
+
165
+ def _hyph_join(t):
166
+ """'Infektionsschutzgesetz-\nZuständigkeitsverordnung' (a compound wrapped after its hyphen) -> one word."""
167
+ return re.sub(r"(?<=\w)-[ \t]*\n[ \t]*(?=\w)", "-", t or "")
168
+
169
+
170
+ def _respace(primary, *alts):
171
+ """revosax sometimes drops a word break in one rendering of a heading only (title attribute 'SächsischesWassergesetz', the
172
+ Eingangsformel h3 'derInfektionsschutzgesetz-...') while another rendering of the SAME words keeps it (the h4 / h1 text).
173
+ If an alternative has the same characters ignoring whitespace, the word breaks of both are united; the primary's own
174
+ whitespace characters (e.g. NBSP in 'Artikel\xa01') are kept. Different wording -> primary unchanged."""
175
+ if not primary:
176
+ return primary
177
+ key = _WS.sub("", primary)
178
+ for alt in alts:
179
+ if not alt or _WS.sub("", alt) != key or alt == primary:
180
+ continue
181
+ out, j = [], 0
182
+ for ch in primary:
183
+ if _WS.match(ch):
184
+ out.append(ch)
185
+ while j < len(alt) and _WS.match(alt[j]):
186
+ j += 1
187
+ continue
188
+ if j < len(alt) and _WS.match(alt[j]) and out and not _WS.match(out[-1]):
189
+ out.append(" ")
190
+ while j < len(alt) and _WS.match(alt[j]):
191
+ j += 1
192
+ out.append(ch); j += 1
193
+ primary = "".join(out)
194
+ return primary
195
+
196
+
197
+ def _respace_map(before, after, fixes):
198
+ """Collect the glued words _respace split ('derInfektionsschutzgesetz-...' -> 'der Infektionsschutzgesetz-...')."""
199
+ if before and after and before != after:
200
+ for w in before.split():
201
+ if len(w) > 6:
202
+ f = _respace(w, _find_span(after, w))
203
+ if f != w:
204
+ fixes[w] = f
205
+
206
+
207
+ def _find_span(text, w):
208
+ """The span of text that equals w ignoring whitespace (None if absent)."""
209
+ key = _WS.sub("", w)
210
+ if not key:
211
+ return None
212
+ pat = r"[\s\xa0]*".join(re.escape(c) for c in key)
213
+ m = re.search(pat, text)
214
+ return m.group(0) if m else None
215
+
216
+
217
+ def _apply_fixes(text, fixes):
218
+ for w, f in fixes.items():
219
+ text = re.sub(r"(?<!\S)%s(?!\S)" % re.escape(w), f, text)
220
+ return text
221
+
222
+
223
+ def _with_notes(text, notes):
224
+ return text + ("\n\nFußnoten:\n" + "\n".join(f"[{n}] {t}" for n, t in notes.items()) if notes else "")
225
+
226
+
227
  def parse_sn_page(page, url):
228
  """REVOSax /vorschrift/<id> page -> title, date, vollzitat, sections."""
229
  page = page or ""
230
  m = RE_SN_LAW.match(urlsplit(url).path)
231
  rid = m.group(1) if m else ""
232
  h1 = re.search(r"<h1[^>]*>(.*?)</h1>", page, re.S)
233
+ short = _plain_attr(_hyph_join(_sn_text(h1.group(1))).replace("\n", " ")) if h1 else ""
234
  vz = re.search(r"<p>\s*Vollzitat:(.*?)</p>", page, re.S)
235
+ vollzitat = _hyph_join(_sn_text(vz.group(1))) if vz else ""
236
+ head = re.search(r"""<header\b(?:[^>"']|"[^"]*"|'[^']*')*title="Eingangsformel"(?:[^>"']|"[^"]*"|'[^']*')*>(.*?)</header>""", page, re.S)
237
+ long_title, fixes = "", {}
238
+ if head:
239
+ ht = re.sub(r"(?s)<p\b.*", "", head.group(1))
240
+ ht = re.sub(r"""(?is)<a\b(?:[^>"']|"[^"]*"|'[^']*')*(?:fussnote|FNID_)(?:[^>"']|"[^"]*"|'[^']*')*>.*?</a\s*>""", " ", ht) # no footnotes in titles
241
+ long_title = _NBSP_SHY.sub("", _sn_text(ht)).replace("\n", " ")
242
+ long_title = re.sub(r" {2,}", " ", long_title).strip()
243
+ raw_long = long_title
244
+ long_title = _respace(long_title, short, re.sub(r"\s+vom\s.*$", "", vollzitat.replace("\n", " ")))
245
+ _respace_map(raw_long, long_title, fixes)
246
  vom = re.search(r"<b>\s*Vom\s+([^<]+)</b>", head.group(1)) if head else None
247
  date = de_date(vom.group(1)) if vom else de_date(vollzitat)
248
  art = re.search(r'<article[^>]*id="lesetext"[^>]*>(.*?)</article>', page, re.S)
249
  body = art.group(1) if art else ""
250
  secs = []
251
+ opens = list(_SEC_OPEN.finditer(body))
252
  for k, sm in enumerate(opens): # nested sections: each section's own text runs to the next <section> opening
253
  attrs = sm.group(1)
254
  inner = body[sm.end(): opens[k + 1].start() if k + 1 < len(opens) else len(body)]
255
+ t = _attr_val(attrs, "title"); a = _attr_val(attrs, "id")
256
+ notes = {}
257
+ txt = _sn_text(inner, notes)
258
  if txt:
259
+ title = _plain_attr(t) if t is not None else ""
260
+ h = re.search(r"(?is)<h\d\b[^>]*>(.*?)</h\d\s*>", inner)
261
+ if title and h: # the section heading as printed keeps word breaks the title attribute can lose
262
+ raw_t = title
263
+ title = _respace(title, _plain_attr(_sn_text(h.group(1)).replace("\n", " ")))
264
+ _respace_map(raw_t, title, fixes)
265
+ if not title: # no title attribute: the section's own heading line, never the internal anchor
266
+ first = txt.split("\n", 1)[0]
267
+ title = first if RE_ENBEZ.match(first) and len(first) <= 120 else ""
268
+ secs.append({"anchor": a if a else str(len(secs) + 1), "title": title, "text": _with_notes(txt, notes)})
269
+ allnotes = {}
270
+ full = _with_notes(_sn_text(body, allnotes), allnotes)
271
+ if fixes: # the same glued words in the printed text (Eingangsformel, Inhaltsübersicht)
272
+ full = _apply_fixes(full, fixes)
273
+ for sec in secs:
274
+ sec["text"] = _apply_fixes(sec["text"], fixes)
275
  return {"revosax_id": rid, "short_title": short, "title": long_title or short, "vollzitat": vollzitat, "date": date,
276
  "sections": secs, "text": full}
277
 
278
 
279
  # ---------------------------------------------------------------- PII scan (gazette texts normally carry none)
280
+ # Revised 2026-10-17 after CoS rejected the DE-SN amending densify (76 over-redactions: 60 table numbers taken for tax ids,
281
+ # 12 official treasury IBANs printed in the law, 4 official mailboxes). Only personal data of PRIVATE individuals is redacted:
282
+ # - e-mail: kept when the domain is an authority / public-body domain (soft hyphens and line-wrap tolerated) or the local part is a
283
+ # functional mailbox (poststelle@, datenschutz@, info@ ...); otherwise redacted.
284
+ # - IBAN: kept when it is an official account: Deutsche Bundesbank bank code (BLZ xxx000 00 / BIC MARKDEF1xxx) or a public payee
285
+ # (Bundes-/Landes-/Staats-/Gerichtskasse, Finanzamt, Fonds, Freistaat ...) within 160 chars before it; otherwise redacted.
286
+ # - Steuer-IdNr: only an 11-digit number on ONE line, introduced by a tax-id label (Steuer-ID, Steuer-Identifikationsnummer,
287
+ # IdNr ...) within 40 chars; bare digit runs (tables, amounts, Aktenzeichen) never fire.
288
+ _SHY = "\xad\u200b"
289
+ RE_EMAIL = re.compile(r"(?<![\w.%+-])[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+[" + _SHY + r"]*\.[" + _SHY + r"]*)+[A-Za-z]{2,}\b")
290
+ RE_IBAN = re.compile(r"\bDE ?\d{2}(?:[ \xa0]?\d{4}){4}[ \xa0]?\d{2}\b")
291
+ RE_STEUER = re.compile(r"(?i)(?:steuer[- ]?(?:id|identifikations)(?:[- ]?(?:nr|nummer))?\.?|\bidnr\.?|identifikationsnummer(?: nach § 139b AO)?)"
292
+ r"[ \t:.\xa0-]{0,40}?(\d{2}[ \xa0]?\d{3}[ \xa0]?\d{3}[ \xa0]?\d{3})(?![\d])")
293
+ OFFICIAL_MAIL = re.compile(r"@(?:[a-z0-9-]+\.)*(?:sachsen|brandenburg|nrw|niedersachsen|bremen|bund|berlin|hamburg|hessen|bayern|saarland|"
294
+ r"thueringen|sachsen-anhalt|schleswig-holstein|rlp|mv-regierung|landtag[a-z-]*|bundesbank|bsi|bfdi)\.de$|"
295
+ r"@[a-z0-9.-]*\.(?:gov|europa\.eu|gv\.at|admin\.ch)$|@(?:[a-z0-9-]+\.)*(?:landkreis|kreis|stadt|gemeinde)[a-z0-9-]*\.de$", re.I)
296
+ FUNCTIONAL_LOCAL = re.compile(r"^(?:poststelle|post|info|kontakt|datenschutz|datenschutzbeauftragte[rn]?|dsb|presse|service|buergerservice|"
297
+ r"verwaltung|sekretariat|zentrale|vergabe|beschwerde[n]?|phishing|spam|[a-z]*meldung(?:en)?|abuse|cert|security|sicherheit|it-sicherheit|"
298
+ r"poststelle\.[a-z0-9-]+|[a-z]+stelle|office|mail|webmaster|redaktion|kanzlei|geschaeftsstelle|einreichung|antrag|"
299
+ r"[a-z0-9-]*(?:referat|abteilung|amt|stelle|behoerde|ministerium|portal|team|service|support)[a-z0-9.-]*)$", re.I)
300
+ OFFICIAL_PAYEE = re.compile(r"(?i)bundeskasse|landeskasse|landeshauptkasse|staatskasse|gerichtskasse|justizkasse|amtskasse|zahlstelle|"
301
+ r"finanzamt|bundesbank|freistaat|landesamt|bundesamt|staatsministerium|ministerium|fonds|sondervermögen|"
302
+ r"anstalt des öffentlichen rechts|körperschaft|landesdirektion|regierungspräsidium|kommunal|stadtkasse|kreiskasse")
303
+ RE_BIC_BBK = re.compile(r"(?i)\bMARK\s?DE\s?F\s?1")
304
+
305
+
306
+ # a public body's own sub-domain anywhere in the host (also when the printed TLD part has a typo, e.g. the official
307
+ # 'spammeldung@lit.justiz.sachsden.de' in de-sn-20360)
308
+ OFFICIAL_HOST_LABEL = re.compile(r"(?i)@(?:[a-z0-9-]+\.)*(?:justiz|polizei|landtag|bundestag|gericht|[a-z-]*gericht|staatsanwaltschaft|"
309
+ r"finanzamt|finanzverwaltung|landesamt|bundesamt|ministerium|[a-z]*ministerium|staatskanzlei|"
310
+ r"landesdirektion|regierungspraesidium|bezirksregierung|kreis|landkreis|stadt|gemeinde)\.")
311
+
312
+
313
+ def _mail_plain(m):
314
+ return re.sub("[" + _SHY + "]", "", m)
315
+
316
+
317
+ def mail_is_official(addr):
318
+ a = _mail_plain(addr)
319
+ return bool(OFFICIAL_MAIL.search(a) or OFFICIAL_HOST_LABEL.search(a)) or bool(FUNCTIONAL_LOCAL.match(a.split("@", 1)[0]))
320
+
321
+
322
+ def iban_is_official(iban, before, after=""):
323
+ digits = re.sub(r"\D", "", iban) # kk + BLZ(8) + account(10)
324
+ blz = digits[2:10]
325
+ if len(blz) == 8 and blz[3:] == "00000": # Deutsche Bundesbank branch (BLZ xxx000 00): accounts of public bodies only
326
+ return True
327
+ return bool(OFFICIAL_PAYEE.search(before[-160:])) or bool(RE_BIC_BBK.search(after[:40]))
328
 
329
 
330
  def pii_scan(text):
331
+ """Return (redacted_text, hits). Redacts only personal data of private individuals (see the rules above); official
332
+ accounts and functional / authority mailboxes stay verbatim. hits = [(kind, value)] of the redactions made."""
333
  hits = []
334
+ src = text or ""
335
 
336
  def mail(m):
337
+ if mail_is_official(m.group(0)):
338
  return m.group(0)
339
  hits.append(("email", m.group(0))); return "[REDACTED-email]"
340
+ t = RE_EMAIL.sub(mail, src)
341
 
342
  def iban(m):
343
+ if iban_is_official(m.group(0), m.string[:m.start()], m.string[m.end():]):
344
+ return m.group(0)
345
  hits.append(("iban", m.group(0))); return "[REDACTED-iban]"
346
  t = RE_IBAN.sub(iban, t)
347
 
348
  def steuer(m):
349
+ hits.append(("taxid", m.group(1))); return m.group(0)[:m.start(1) - m.start(0)] + "[REDACTED-taxid]"
350
  t = RE_STEUER.sub(steuer, t)
351
  return t, hits
352
 
 
674
 
675
  # ---- record clean-up (2026-10-15, after CoS rejected the DE-SN densify): applied to every collected record at pack time,
676
  # so it holds for every future Land pack. Live tip rows are never touched (append-only).
677
+ from finalize_gate import (strip_html_footnotes, strip_html_title, is_contents_row, fold_heading_rows, is_heading_only, # noqa: E402
678
+ is_bodyless, is_repeal_placeholder, has_raw_html, RAW_HTML)
679
 
680
  _TITLE_BODY = re.compile(r"(\sVom \d{1,2}\.\s*\S+\s+\d{4})\s+(\S.{20,})$", re.S)
681
+ # norm headings (2026-10-17): an empty 'Artikel N' / '§ N' row is never merged into the next Artikel (CoS); see clean_record.
682
+ NORM_HEAD = re.compile(r"^\s*(?:Artikel|Art\.|§§?)\s*\d", re.I)
683
+ ATTACH_TITLE = re.compile(r"^\s*(?:Anlagen?|Anh[aä]nge?|Anlage\s*\d+[a-z]?|Anhang\s*\d+[a-z]?)\s*$", re.I)
684
+ ATTACH_STUB = re.compile(r"^\s*(?:Karten?|Übersichtskarten?|Anhang|Anh[aä]nge|Anlagen?|Plan|Pläne|Lageplan|Flurkarte|Abbildung(?:en)?|Tabelle(?:n)?|Muster|Formular)\s*\d*\s*$", re.I)
685
 
686
 
687
  def clean_title(t):
 
691
  return t[:m.end(1)].strip() if m else t
692
 
693
 
694
+ def _clean_meta(mj):
695
+ """Strip HTML out of every string in a metadata_json document (e.g. a revosax <a ... data-name=...> left in `titel`)."""
696
+ if not mj or ("<" not in mj and "&lt;" not in mj):
697
+ return mj, False
698
+ try:
699
+ d = json.loads(mj)
700
+ except ValueError:
701
+ return mj, False
702
+ hit = [False]
703
+
704
+ def walk(v):
705
+ if isinstance(v, str):
706
+ if RAW_HTML.search(v):
707
+ hit[0] = True
708
+ return strip_html_title(v)
709
+ return v
710
+ if isinstance(v, dict):
711
+ return {k: walk(x) for k, x in v.items()}
712
+ if isinstance(v, list):
713
+ return [walk(x) for x in v]
714
+ return v
715
+ d = walk(d)
716
+ return (json.dumps(d, ensure_ascii=False), True) if hit[0] else (mj, False)
717
+
718
+
719
+ def repeal_placeholder_row(a):
720
+ """'Artikel 7\n1\n(außer Kraft)' / 'Artikel 2\n(aufgehoben) 1' / '... [1] ... Fußnoten:' -> stray footnote digits and markers
721
+ stripped from the text; the footnote note (if any) is kept in metadata_json.footnotes; metadata_json.body_status =
722
+ 'repealed_placeholder' (the live schema has no body_status column)."""
723
+ text = a.get("text") or ""
724
+ notes = ""
725
+ m = re.search(r"\n\s*Fußnoten:\s*\n(.*)\Z", text, re.S)
726
+ if m:
727
+ notes, text = m.group(1).strip(), text[:m.start()]
728
+ text = re.sub(r"\s*\[\d{1,3}\]", "", text)
729
+ lines = [ln.strip() for ln in text.split("\n") if ln.strip()]
730
+ out = []
731
+ for k, ln in enumerate(lines):
732
+ if k and re.fullmatch(r"\d{1,3}", ln):
733
+ continue # superscript footnote number on its own line
734
+ if k:
735
+ ln = re.sub(r"(\))\s+\d{1,3}$", r"\1", ln) # '(aufgehoben) 1'
736
+ out.append(ln)
737
+ try:
738
+ md = json.loads(a.get("metadata_json") or "{}")
739
+ except ValueError:
740
+ md = {}
741
+ md["body_status"] = "repealed_placeholder"
742
+ if notes:
743
+ md["footnotes"] = notes
744
+ return dict(a, text="\n".join(out), metadata_json=json.dumps(md, ensure_ascii=False))
745
+
746
+
747
  def clean_record(rec):
748
+ """Returns (rec, stats). Strips raw HTML (footnote anchors -> '[n]' + plain 'Fußnoten:' block; any other tag; HTML inside
749
+ metadata_json strings), drops contents-list rows, trims body text out of titles, recomputes article_count, and (2026-10-17):
750
+ * repeal placeholders ('Artikel 7 (aufgehoben)') are KEPT, tagged metadata_json.body_status='repealed_placeholder', stray
751
+ footnote digits stripped;
752
+ * an empty norm heading ('Artikel N' / '§ N' with no body, incl. heading + footnote digits only) is never merged into the next
753
+ Artikel: it is folded only when the next row is not itself a norm heading row (Artikel -> its § rows), otherwise dropped
754
+ (known gap, listed);
755
+ * rows with a heading plus only footnote markers/digits are dropped; attachment stubs ('Anlagen' -> 'Karte') are dropped;
756
+ * other heading-only rows (Teil/Abschnitt/Zustimmungsgesetz ...) fold into the next article as before; trailing ones drop."""
757
  st = {"footnote_rows": 0, "footnote_law_texts": 0, "contents_dropped": [], "headings_folded": 0, "headings_dropped": [],
758
+ "titles_trimmed": [], "norm_headings_dropped": [], "footnote_digit_rows_dropped": [], "attachment_stubs_dropped": [],
759
+ "repealed_placeholders": [], "metadata_html_cleaned": 0, "folded_ids": []}
760
  law = dict(rec["law"])
761
  t, n = strip_html_footnotes(law.get("text") or "")
762
  if n or t != (law.get("text") or ""):
 
764
  nt = clean_title(law.get("title"))
765
  if nt != law.get("title"):
766
  st["titles_trimmed"].append(law["id"]); law["title"] = nt
767
+ law["metadata_json"], hit = _clean_meta(law.get("metadata_json"))
768
+ st["metadata_html_cleaned"] += int(hit)
769
  arts = []
770
  for a in rec.get("articles", []):
771
  a = dict(a)
 
774
  if tx != (a.get("text") or "") or ti != (a.get("title") or ""):
775
  st["footnote_rows"] += 1
776
  a["text"], a["title"] = tx, ti
777
+ a["metadata_json"], hit = _clean_meta(a.get("metadata_json"))
778
+ st["metadata_html_cleaned"] += int(hit)
779
  if is_contents_row(ti):
780
  st["contents_dropped"].append(a["id"]); continue
781
  arts.append(a)
782
+ # classify and fold (one pass)
783
+ out, carry = [], []
784
+ for k, a in enumerate(arts):
785
+ ti, tx = a["title"], a["text"]
786
+ if is_repeal_placeholder(ti, tx):
787
+ a = repeal_placeholder_row(a); st["repealed_placeholders"].append(a["id"])
788
+ elif is_bodyless(ti, tx):
789
+ if NORM_HEAD.match(ti):
790
+ nxt = arts[k + 1] if k + 1 < len(arts) else None
791
+ if nxt is not None and not (NORM_HEAD.match(nxt["title"]) and _norm_kind(nxt["title"]) == _norm_kind(ti)):
792
+ carry.append(a); continue # 'Artikel 3' heading over the § rows of the act it contains
793
+ (st["footnote_digit_rows_dropped"] if _fn_residue(ti, tx) else st["norm_headings_dropped"]).append(a["id"]); continue
794
+ if _fn_residue(ti, tx) and not is_heading_only(ti, tx):
795
+ st["footnote_digit_rows_dropped"].append(a["id"]); continue
796
+ carry.append(a); continue
797
+ elif ATTACH_TITLE.match(ti) and ATTACH_STUB.match(tx or ""):
798
+ st["attachment_stubs_dropped"].append(a["id"]); continue
799
+ if carry:
800
+ a = dict(a, text="\n".join(c["title"].strip() for c in carry) + "\n" + (a.get("text") or ""))
801
+ st["folded_ids"] += [c["id"] for c in carry]; carry = []
802
+ out.append(a)
803
+ st["headings_dropped"] = [c["id"] for c in carry]
804
+ st["headings_folded"] = len(st["folded_ids"])
805
+ law["article_count"] = len(out)
806
+ return dict(rec, law=law, articles=out), st
807
+
808
+
809
+ def _fn_residue(ti, tx):
810
+ """The text carries footnote markers / a footnote block / standalone digits that are not in the heading."""
811
+ if re.search(r"\[\d{1,3}\]|\nFußnoten:", tx or ""):
812
+ return True
813
+ d = lambda x: sorted(re.findall(r"(?<![\w.])\d{1,3}(?![\w.])", re.sub(r"\s+", " ", x or ""))) # noqa: E731
814
+ return d(tx) != d(ti)
815
+
816
+
817
+ def _norm_kind(t):
818
+ return "art" if re.match(r"^\s*(?:Artikel|Art\.)", t or "", re.I) else "par"
scrapers/finalize_gate.py CHANGED
@@ -3,7 +3,8 @@
3
  Added 2026-10-15 after CoS rejected the DE-SN densify HUB-READY (contents-list rows, raw revosax footnote HTML, card kind
4
  counts taken before drops). Four checks (4th added 2026-10-15 22:50 PT), each must be 0 / True before a pack may be staged:
5
  1. contents_rows article rows that are a table of contents (title is a contents heading)
6
- 2. raw_html_rows law/article texts or titles still carrying HTML markup (tags, href/class attributes, FNID anchors)
 
7
  3. card_matches_data every count printed on the card equals the count recomputed from the written parquet
8
  4. heading_only_ok heading-only rows (text == title, whitespace collapsed: 'Teil 1\nX' == 'Teil 1 X') == the number the
9
  card discloses as kept (0 for DE, where they are folded into the next article)
@@ -15,11 +16,28 @@ CONTENTS_TITLE = re.compile(
15
  r"^\s*(?:inhaltsverzeichnis|inhaltsübersicht|inhaltsuebersicht|table of contents|contents|arrangement of (?:sections|regulations|rules|clauses)|"
16
  r"indholdsfortegnelse|innehållsförteckning|innihaldsyvirlit)\s*(?:\[\d+\]|\d+)?\s*[:.]?\s*$", re.I)
17
  HTML_TAGS = r"(?:a|abbr|b|br|dd|div|dl|dt|em|font|h[1-6]|i|img|li|ol|p|span|strong|sub|sup|table|tbody|td|th|thead|tr|u|ul)"
18
- RAW_HTML = re.compile(r"(?is)</?%s\b[^>]*>|<a\s+(?:title|class|href)=|\bclass=\"fussnote_link\"|href=\"#FNID_\d+\"|\bfussnote_link\b" % HTML_TAGS)
 
 
 
 
 
 
 
 
 
 
 
 
19
  _FN_ANCHOR = re.compile(r"(?is)<a\b([^>]*)>[ \t]*(\d{1,3}(?:[ \t]+\d{1,3})*(?=\s*(?:<|$))|\d{1,3}|[^<\d]{0,12}?(?=\s*</a))?(?:\s*</a\s*>)?")
20
  _FN_TRUNC = re.compile(r"(?is)<a\b[^>]*$") # anchor cut off at the end of a split article
21
  _BR = re.compile(r"(?i)<br\s*/?>")
22
- _TAG = re.compile(r"(?is)</?%s\b[^>]*>" % HTML_TAGS)
 
 
 
 
 
23
 
24
 
25
  def ws(s):
@@ -27,11 +45,45 @@ def ws(s):
27
  return re.sub(r"\s+", " ", s or "").strip()
28
 
29
 
 
 
 
 
 
30
  def is_heading_only(title, text):
31
  t = ws(text)
32
  return bool(t) and t == ws(title)
33
 
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def _attr(attrs, name):
36
  m = re.search(r'(?is)\b%s\s*=\s*"([^"]*)"' % name, attrs)
37
  return m.group(1) if m else ""
@@ -40,7 +92,7 @@ def _attr(attrs, name):
40
  def strip_html_footnotes(text):
41
  """revosax-style '<a title="NOTE" class="fussnote_link" href="#FNID_n"> n</a>' -> inline '[n]' plus a plain-text
42
  'Fußnoten:' block at the end; any other known HTML tag is removed. Returns (clean_text, n_footnotes_converted)."""
43
- if not text or "<" not in text:
44
  return text, 0
45
  notes, order = {}, []
46
 
@@ -60,7 +112,9 @@ def strip_html_footnotes(text):
60
  if note:
61
  mm = re.search(r"FNID_(\d+)", m.group(0)); n = mm.group(1) if mm else str(len(order) + 1); notes[n] = note; order.append(n); out += f" [{n}]"
62
  out = _BR.sub("\n", out) # a line break separates words: never glue them (fixed 2026-10-15 after 'elektronischenInformations-')
63
- out = _TAG.sub("", out)
 
 
64
  out = re.sub(r"[ \t]+\n", "\n", re.sub(r"[ \t]{2,}", " ", out)).strip()
65
  if order:
66
  out += "\n\nFußnoten:\n" + "\n".join(f"[{n}] {notes[n]}" for n in order)
@@ -95,21 +149,64 @@ def fold_heading_rows(articles):
95
  return out, folded, dropped
96
 
97
 
98
- def gate(law_rows, article_rows, card_counts, data_counts, heading_only_allowed=0):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  """law_rows / article_rows: iterables of dicts (only the rows this pack adds). card_counts / data_counts: dicts of
100
  the numbers printed on the card vs recomputed from the parquet. heading_only_allowed: heading-only rows (whitespace-
101
- collapsed text == title) the card discloses as kept (GI/territory one-line sections); 0 for DE (folded). Returns a dict; 'ok' is True only if all three pass."""
 
 
 
102
  law_rows, article_rows = list(law_rows), list(article_rows)
103
  contents = [a.get("id") for a in article_rows if is_contents_row(a.get("title"))]
104
- html_a = [a.get("id") for a in article_rows if RAW_HTML.search((a.get("text") or "") + "\n" + (a.get("title") or ""))]
105
- html_l = [x.get("id") for x in law_rows if RAW_HTML.search((x.get("text") or "") + "\n" + (x.get("title") or ""))]
106
  diff = {k: {"card": card_counts.get(k), "data": data_counts.get(k)} for k in set(card_counts) | set(data_counts)
107
  if card_counts.get(k) != data_counts.get(k)}
108
- heading_only = sum(1 for a in article_rows if is_heading_only(a.get("title"), a.get("text")))
 
 
 
109
  res = {"contents_rows": len(contents), "contents_row_ids": contents[:20],
110
  "raw_html_article_rows": len(html_a), "raw_html_law_rows": len(html_l), "raw_html_ids": (html_a + html_l)[:20],
111
  "card_matches_data": not diff, "card_vs_data_diff": diff,
112
- "heading_only_rows": heading_only, "heading_only_allowed": heading_only_allowed, "heading_only_ok": heading_only == heading_only_allowed}
 
113
  res["ok"] = res["contents_rows"] == 0 and res["raw_html_article_rows"] == 0 and res["raw_html_law_rows"] == 0 and res["card_matches_data"] and res["heading_only_ok"]
114
  return res
115
 
@@ -128,8 +225,11 @@ def pack_gate(pack, laws_f, arts_f, card_text, extra_card=None, extra_data=None,
128
  import pyarrow.parquet as pq
129
  from pathlib import Path
130
  pack = Path(pack)
131
- lt = pq.read_table(pack / laws_f, columns=["id", "title", "text"]).to_pylist()
132
- at = pq.read_table(pack / arts_f, columns=["id", "title", "text"]).to_pylist()
 
 
 
133
  rows = card_file_rows(card_text)
134
  card = {f"rows:{laws_f}": rows.get(laws_f), f"rows:{arts_f}": rows.get(arts_f), **(extra_card or {})}
135
  data = {f"rows:{laws_f}": len(lt), f"rows:{arts_f}": len(at), **(extra_data or {})}
 
3
  Added 2026-10-15 after CoS rejected the DE-SN densify HUB-READY (contents-list rows, raw revosax footnote HTML, card kind
4
  counts taken before drops). Four checks (4th added 2026-10-15 22:50 PT), each must be 0 / True before a pack may be staged:
5
  1. contents_rows article rows that are a table of contents (title is a contents heading)
6
+ 2. raw_html_rows law/article titles, texts or metadata_json strings still carrying HTML markup: ANY tag (generic regex,
7
+ 2026-10-17), escaped tags, attribute residue, FNID anchors
8
  3. card_matches_data every count printed on the card equals the count recomputed from the written parquet
9
  4. heading_only_ok heading-only rows (text == title, whitespace collapsed: 'Teil 1\nX' == 'Teil 1 X') == the number the
10
  card discloses as kept (0 for DE, where they are folded into the next article)
 
16
  r"^\s*(?:inhaltsverzeichnis|inhaltsübersicht|inhaltsuebersicht|table of contents|contents|arrangement of (?:sections|regulations|rules|clauses)|"
17
  r"indholdsfortegnelse|innehållsförteckning|innihaldsyvirlit)\s*(?:\[\d+\]|\d+)?\s*[:.]?\s*$", re.I)
18
  HTML_TAGS = r"(?:a|abbr|b|br|dd|div|dl|dt|em|font|h[1-6]|i|img|li|ol|p|span|strong|sub|sup|table|tbody|td|th|thead|tr|u|ul)"
19
+ # Generic raw-HTML detector (2026-10-17, after `<section data-anchor=...>` tags passed the old tag list): ANY tag name, not a list.
20
+ # - a tag with attribute syntax, any case, closed or cut off: <section data-anchor="1" ...> <a href="/x" title="..." <A HREF=x>
21
+ # - a bare open/close/void tag whose name is all-lowercase or all-uppercase: <p> </div> <br/> <BR> <wbr> <o:p>
22
+ # - escaped markup (&lt;section ...&gt;), comments/doctype, and attribute residue of a broken tag ('...)">').
23
+ # Statute placeholders such as <ER/SIE>, <Name>, <Ort> and comparisons like "a < b > c" are not markup and do not match.
24
+ _ATTR = r"""[A-Za-z_:][-\w:.]*\s*=\s*(?:"[^"]*"?|'[^']*'?|[^\s"'<>=`]+)"""
25
+ RAW_HTML = re.compile(
26
+ r"<[A-Za-z][-\w:]*\s+" + _ATTR + # tag with attributes (closed or not)
27
+ r"|</?(?:[a-z][a-z0-9]*(?:[:-][a-z0-9]+)*|[A-Z][A-Z0-9]*)\s*/?>" # bare tag, one-case name
28
+ r"|&lt;/?[A-Za-z][-\w:]*(?:\s|/?&gt;)" # escaped tag
29
+ r"|<!--|<!DOCTYPE|<!\[CDATA\[" # comment / doctype / cdata
30
+ r'|"\s*/?>' # residue of a cut-off attribute value
31
+ r"|\bclass=\"fussnote_link\"|href=\"#FNID_\d+\"|\bfussnote_link\b|\bdata-(?:anchor|level|link|name|id)=")
32
  _FN_ANCHOR = re.compile(r"(?is)<a\b([^>]*)>[ \t]*(\d{1,3}(?:[ \t]+\d{1,3})*(?=\s*(?:<|$))|\d{1,3}|[^<\d]{0,12}?(?=\s*</a))?(?:\s*</a\s*>)?")
33
  _FN_TRUNC = re.compile(r"(?is)<a\b[^>]*$") # anchor cut off at the end of a split article
34
  _BR = re.compile(r"(?i)<br\s*/?>")
35
+ _TAG_LIST = re.compile(r"(?is)</?%s\b[^>]*>" % HTML_TAGS)
36
+ # any real tag (2026-10-17): a tag with attribute syntax (any name, attribute values may wrap lines), or a bare tag with a one-case
37
+ # name. '<ER/SIE>', '<Name>', 'a < b > c' are statute text and stay.
38
+ _ATTR_STRICT = r"""[A-Za-z_:][-\w:.]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>=`]+))?"""
39
+ _ATTR_EQ = r"""[A-Za-z_:][-\w:.]*\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>=`]+)"""
40
+ _TAG = re.compile(r"<[A-Za-z][-\w:]*(?:\s+" + _ATTR_STRICT + r")*?\s+" + _ATTR_EQ + r"(?:\s+" + _ATTR_STRICT + r")*\s*/?>|</?(?:[a-z][a-z0-9]*(?:[:-][a-z0-9]+)*|[A-Z][A-Z0-9]*)\s*/?>")
41
 
42
 
43
  def ws(s):
 
45
  return re.sub(r"\s+", " ", s or "").strip()
46
 
47
 
48
+ _FN_BLOCK = re.compile(r"\n\s*Fußnoten:\s*\n.*\Z", re.S)
49
+ _FN_MARK = re.compile(r"\s*\[\d{1,3}\]")
50
+ REPEAL = re.compile(r"^\(?\s*(?:aufgehoben|weggefallen|außer\s+kraft|ausser\s+kraft|gestrichen|entfallen|nicht\s+mehr\s+belegt)\s*\)?\.?$", re.I)
51
+
52
+
53
  def is_heading_only(title, text):
54
  t = ws(text)
55
  return bool(t) and t == ws(title)
56
 
57
 
58
+ def body_text(title, text):
59
+ """What the row says beyond its own heading: the footnote block and [n] markers are removed, standalone 1-3 digit words
60
+ (superscript footnote numbers such as 'Artikel 7\n1\n(außer Kraft)' or '... Fachschule 1') are ignored on both sides, and the
61
+ heading (title) words are removed from the start. '' = the row carries no body of its own."""
62
+ def toks(x):
63
+ return [w for w in ws(_FN_MARK.sub(" ", x or "")).split(" ") if w and not re.fullmatch(r"\d{1,3}", w)]
64
+ tt = toks(_FN_BLOCK.sub("", text or "")); hh = toks(title)
65
+ if hh and tt[:len(hh)] == hh:
66
+ return " ".join(tt[len(hh):])
67
+ j = lambda x: re.sub(r"[\W_]+", "", "".join(x)) # noqa: E731 letters/digits only: wrap, spacing, line-end hyphen, '( X )' vs '(X'
68
+ if hh and j(tt) and j(tt) == j(hh): # same heading as the title, only punctuation/spacing differs
69
+ return ""
70
+ return " ".join(tt)
71
+
72
+
73
+ def is_bodyless(title, text):
74
+ """Heading-only in the wider sense: nothing but the heading, footnote markers/digits and a footnote block."""
75
+ return bool(ws(text)) and body_text(title, text) == ""
76
+
77
+
78
+ def is_repeal_placeholder(title, text):
79
+ """'Artikel 7 (aufgehoben)' / '(außer Kraft)' / '(weggefallen)' rows: the heading itself says the norm is repealed."""
80
+ h = ws(_FN_MARK.sub("", title or ""))
81
+ m = re.search(r"\(([^()]*)\)\s*$", h)
82
+ tail = m.group(0) if m else ""
83
+ b = body_text(title, text)
84
+ return bool(tail and REPEAL.match(tail)) and (b == "" or bool(REPEAL.match(b)))
85
+
86
+
87
  def _attr(attrs, name):
88
  m = re.search(r'(?is)\b%s\s*=\s*"([^"]*)"' % name, attrs)
89
  return m.group(1) if m else ""
 
92
  def strip_html_footnotes(text):
93
  """revosax-style '<a title="NOTE" class="fussnote_link" href="#FNID_n"> n</a>' -> inline '[n]' plus a plain-text
94
  'Fußnoten:' block at the end; any other known HTML tag is removed. Returns (clean_text, n_footnotes_converted)."""
95
+ if not text or ("<" not in text and "&lt;" not in text):
96
  return text, 0
97
  notes, order = {}, []
98
 
 
112
  if note:
113
  mm = re.search(r"FNID_(\d+)", m.group(0)); n = mm.group(1) if mm else str(len(order) + 1); notes[n] = note; order.append(n); out += f" [{n}]"
114
  out = _BR.sub("\n", out) # a line break separates words: never glue them (fixed 2026-10-15 after 'elektronischenInformations-')
115
+ out = _TAG_LIST.sub("", out)
116
+ out = _TAG.sub("\x00", out) # any other tag (e.g. <section data-anchor=...>): a space, never glue words;
117
+ out = re.sub(r"(?m)^[ \t\x00]*\x00[ \t\x00]*\n", "", out).replace("\x00", " ") # a line that held only a tag goes away
118
  out = re.sub(r"[ \t]+\n", "\n", re.sub(r"[ \t]{2,}", " ", out)).strip()
119
  if order:
120
  out += "\n\nFußnoten:\n" + "\n".join(f"[{n}] {notes[n]}" for n in order)
 
149
  return out, folded, dropped
150
 
151
 
152
+ def _strings(v):
153
+ if isinstance(v, str):
154
+ yield v
155
+ elif isinstance(v, dict):
156
+ for x in v.values():
157
+ yield from _strings(x)
158
+ elif isinstance(v, list):
159
+ for x in v:
160
+ yield from _strings(x)
161
+
162
+
163
+ def row_strings(row):
164
+ """Every text-bearing field of a row: title, text and each string inside metadata_json (decoded; raw string if not JSON)."""
165
+ import json
166
+ out = [row.get("title") or "", row.get("text") or ""]
167
+ m = row.get("metadata_json")
168
+ if m:
169
+ try:
170
+ out += list(_strings(json.loads(m)))
171
+ except (ValueError, TypeError):
172
+ out.append(str(m))
173
+ return out
174
+
175
+
176
+ def has_raw_html(row):
177
+ return any(RAW_HTML.search(s) for s in row_strings(row))
178
+
179
+
180
+ def body_status(row):
181
+ import json
182
+ try:
183
+ return (json.loads(row.get("metadata_json") or "{}") or {}).get("body_status")
184
+ except (ValueError, TypeError, AttributeError):
185
+ return None
186
+
187
+
188
+ def gate(law_rows, article_rows, card_counts, data_counts, heading_only_allowed=0, bodyless_check=False):
189
  """law_rows / article_rows: iterables of dicts (only the rows this pack adds). card_counts / data_counts: dicts of
190
  the numbers printed on the card vs recomputed from the parquet. heading_only_allowed: heading-only rows (whitespace-
191
+ collapsed text == title) the card discloses as kept (GI/territory one-line sections); 0 for DE (folded). Raw HTML = generic tag
192
+ regex over title, text and every metadata_json string. Rows tagged metadata_json.body_status='repealed_placeholder' are counted
193
+ apart, not as heading-only. bodyless_check (DE): heading + footnote markers/digits only also counts as heading-only.
194
+ Returns a dict; 'ok' is True only if every check passes."""
195
  law_rows, article_rows = list(law_rows), list(article_rows)
196
  contents = [a.get("id") for a in article_rows if is_contents_row(a.get("title"))]
197
+ html_a = [a.get("id") for a in article_rows if has_raw_html(a)]
198
+ html_l = [x.get("id") for x in law_rows if has_raw_html(x)]
199
  diff = {k: {"card": card_counts.get(k), "data": data_counts.get(k)} for k in set(card_counts) | set(data_counts)
200
  if card_counts.get(k) != data_counts.get(k)}
201
+ repealed = [a.get("id") for a in article_rows if body_status(a) == "repealed_placeholder"]
202
+ heading_only_ids = [a.get("id") for a in article_rows if body_status(a) != "repealed_placeholder"
203
+ and (is_heading_only(a.get("title"), a.get("text")) or (bodyless_check and is_bodyless(a.get("title"), a.get("text"))))]
204
+ heading_only = len(heading_only_ids)
205
  res = {"contents_rows": len(contents), "contents_row_ids": contents[:20],
206
  "raw_html_article_rows": len(html_a), "raw_html_law_rows": len(html_l), "raw_html_ids": (html_a + html_l)[:20],
207
  "card_matches_data": not diff, "card_vs_data_diff": diff,
208
+ "heading_only_rows": heading_only, "heading_only_ids": heading_only_ids[:20], "heading_only_allowed": heading_only_allowed,
209
+ "heading_only_ok": heading_only == heading_only_allowed, "repealed_placeholder_rows": len(repealed)}
210
  res["ok"] = res["contents_rows"] == 0 and res["raw_html_article_rows"] == 0 and res["raw_html_law_rows"] == 0 and res["card_matches_data"] and res["heading_only_ok"]
211
  return res
212
 
 
225
  import pyarrow.parquet as pq
226
  from pathlib import Path
227
  pack = Path(pack)
228
+ def cols(f):
229
+ names = pq.read_schema(pack / f).names
230
+ return [c for c in ("id", "title", "text", "metadata_json") if c in names]
231
+ lt = pq.read_table(pack / laws_f, columns=cols(laws_f)).to_pylist()
232
+ at = pq.read_table(pack / arts_f, columns=cols(arts_f)).to_pylist()
233
  rows = card_file_rows(card_text)
234
  card = {f"rows:{laws_f}": rows.get(laws_f), f"rows:{arts_f}": rows.get(arts_f), **(extra_card or {})}
235
  data = {f"rows:{laws_f}": len(lt), f"rows:{arts_f}": len(at), **(extra_data or {})}
scrapers/pack_de.py CHANGED
@@ -22,7 +22,8 @@ API = f"https://huggingface.co/api/datasets/{L.HUB_REPO}"
22
  RESOLVE = f"https://huggingface.co/datasets/{L.HUB_REPO}/resolve/{L.HUB_TIP}"
23
  BUNDLE = ["de_lib.py", "collect_de_laender.py", "pack_de.py", "robots_guard.py", "run_de_short.sh", "resume_loop_de.sh",
24
  "de_waiter.sh", "gate_profile.sh", "de_queue.example.txt", "requirements.txt", "README.md", "tests/test_de_laender.py",
25
- "short_turn.sh", "tests/test_short_turn.py", "finalize_gate.py", "tests/test_finalize_gate.py", "fix_sn.py", "tests/test_fix_sn.py", "fix_contents_titles.py", "tests/test_fix_contents_titles.py", "fix_lawtext_br.py", "tests/test_fix_lawtext_br.py"]
 
26
  SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY|xox[abps]-[A-Za-z0-9-]{10,}")
27
 
28
 
@@ -66,7 +67,14 @@ def as_version(r):
66
  return r
67
 
68
 
69
- CLEAN_KEYS = ("footnote_rows", "footnote_law_texts", "contents_dropped", "headings_folded", "headings_dropped", "titles_trimmed")
 
 
 
 
 
 
 
70
 
71
 
72
  def load_records(land, tags=("-",), include_updates=False, clean_stats=None):
@@ -83,7 +91,7 @@ def load_records(land, tags=("-",), include_updates=False, clean_stats=None):
83
  r = as_version(r)
84
  r, st = L.clean_record(r); r["_clean"] = st
85
  for k in CLEAN_KEYS:
86
- cs[k] = cs.get(k, [] if isinstance(st[k], list) else 0) + st[k]
87
  (rejected if r.get("bounds") else out).append(r)
88
  return out, rejected, updates
89
 
@@ -161,12 +169,36 @@ def finalize_gate(pack, n_old_laws, n_old_arts):
161
  cnt = {}
162
  for a in na:
163
  cnt[a["law_id"]] = cnt.get(a["law_id"], 0) + 1
164
- res = G.gate(nl, na, card_counts((pack / "CARD_SECTION.md").read_text()), data)
 
 
 
 
 
 
 
 
 
165
  res["article_count_mismatch"] = sum(1 for x in nl if x["article_count"] != cnt.get(x["id"], 0))
166
- res["ok"] = res["ok"] and res["article_count_mismatch"] == 0
 
 
 
 
 
 
 
 
167
  return res
168
 
169
 
 
 
 
 
 
 
 
170
  def scan_tree(root):
171
  hits = []
172
  for p in Path(root).rglob("*"):
@@ -205,7 +237,7 @@ def cmd_build(a):
205
  out = stage_dir(a.land); pack = out / "pack"
206
  if pack.exists():
207
  shutil.rmtree(pack)
208
- (pack / "data").mkdir(parents=True); (pack / "scrapers" / "tests").mkdir(parents=True)
209
  pq.write_table(laws, pack / "data" / "laws.parquet", compression="zstd")
210
  pq.write_table(arts, pack / "data" / "articles.parquet", compression="zstd")
211
  for f in BUNDLE:
@@ -213,20 +245,42 @@ def cmd_build(a):
213
  print("bundle file missing", f); return 8
214
  shutil.copy2(HERE / f, pack / "scrapers" / f)
215
  rep["bounds_rejected"] = [r["law"]["id"] for r in rejected]
216
- rep["pii_redactions"] = sum(r.get("pii_hits", 0) for r in recs)
 
 
 
 
217
  rep["tip_updates_seen"] = updates; rep["tip_updates_included"] = bool(a.include_updates)
218
  added = set(laws.column("id").to_pylist()[rep["laws_old"]:]); ca = {}
219
  for r in recs:
220
  if r["law"]["id"] in added:
221
  for k in CLEAN_KEYS:
222
- ca[k] = ca.get(k, [] if isinstance(r["_clean"][k], list) else 0) + r["_clean"][k]
223
  rep["clean_up"] = {k: (len(v) if isinstance(v, list) else v) for k, v in ca.items()} # rows this pack adds
224
  rep["clean_up_ids"] = {k: v for k, v in ca.items() if isinstance(v, list)}
225
  rep["clean_up_all_records"] = {k: (len(v) if isinstance(v, list) else v) for k, v in cs.items()}
226
  rep["source_terms_note"] = L.SOURCE_TERMS_NOTE
227
  rep["built_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
 
 
 
 
 
 
 
 
 
 
 
 
228
  (pack / "DENSIFY_REPORT.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1))
229
  (pack / "CARD_SECTION.md").write_text(card_section(a.land, rep))
 
 
 
 
 
 
230
  g = finalize_gate(pack, rep["laws_old"], rep["articles_old"])
231
  rep["finalize_gate"] = g
232
  (pack / "DENSIFY_REPORT.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1))
@@ -237,21 +291,134 @@ def cmd_build(a):
237
  if hits:
238
  print("secret scan hits", hits[:5]); return 7
239
  code = {f: sha256(pack / "scrapers" / f) for f in BUNDLE}
 
240
  (pack / "scrapers" / "code.json").write_text(json.dumps(code, indent=1))
241
  sums = [f"{sha256(p)} {p.relative_to(pack)}" for p in sorted(pack.rglob("*")) if p.is_file()]
242
  (pack / "SHA256SUMS").write_text("\n".join(sums) + "\n")
243
  print(json.dumps({k: v for k, v in rep.items() if k != "dropped"}), "dropped", len(rep["dropped"])); return 0
244
 
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  def card_section(land, rep):
247
  cfg = L.LANDS[land]
248
  return (f"## {cfg['jurisdiction']} densify ({rep['laws_added']} laws / {rep['articles_added']} articles, append-only at {L.HUB_TIP[:8]})\n\n"
249
  f"- Source: {cfg['host']} ({cfg['source_type']}); licence: {cfg['license']}\n"
250
  f"- Kinds: {json.dumps(rep.get('kinds', {}), ensure_ascii=False)}\n"
 
 
 
 
251
  + (f"- Clean-up (pipeline, added rows only): {cu.get('contents_dropped', 0)} contents-list rows dropped; revosax footnote HTML converted "
252
  f"to plain-text 'Fußnoten:' blocks in {cu.get('footnote_rows', 0)} article rows and {cu.get('footnote_law_texts', 0)} law texts; "
253
  f"{cu.get('headings_folded', 0)} heading-only rows folded into the next article, {cu.get('headings_dropped', 0)} trailing ones dropped; "
254
- f"{cu.get('titles_trimmed', 0)} titles cleaned\n" if (cu := rep.get("clean_up")) else "") + "\n"
 
 
255
  f"### source_terms_note\n\n{L.SOURCE_TERMS_NOTE}\n\n"
256
  "Every added row also carries `source_terms_note` inside `metadata_json.metadata`.\n")
257
 
@@ -289,6 +456,7 @@ def main(argv=None):
289
  ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
290
  p = sp.add_parser("ids"); p.add_argument("--out", default=str(WORK / "hub_tip_ids.txt")); p.add_argument("--laws", default="")
291
  p = sp.add_parser("build"); p.add_argument("--land", required=True); p.add_argument("--live-laws", required=True); p.add_argument("--live-articles", required=True)
 
292
  p.add_argument("--tags", default=None, help="comma list of sub-lanes, '-' = main (e.g. SN: '-,amending'; BB: vwv; NW: delta)")
293
  p.add_argument("--include-updates", action="store_true", help="NW: add tip_update records as separate '<id>@<valid_from>' version rows")
294
  p = sp.add_parser("stage"); p.add_argument("--land", required=True)
 
22
  RESOLVE = f"https://huggingface.co/datasets/{L.HUB_REPO}/resolve/{L.HUB_TIP}"
23
  BUNDLE = ["de_lib.py", "collect_de_laender.py", "pack_de.py", "robots_guard.py", "run_de_short.sh", "resume_loop_de.sh",
24
  "de_waiter.sh", "gate_profile.sh", "de_queue.example.txt", "requirements.txt", "README.md", "tests/test_de_laender.py",
25
+ "short_turn.sh", "tests/test_short_turn.py", "finalize_gate.py", "tests/test_finalize_gate.py", "fix_sn.py", "tests/test_fix_sn.py", "fix_contents_titles.py", "tests/test_fix_contents_titles.py", "fix_lawtext_br.py", "tests/test_fix_lawtext_br.py",
26
+ "refetch_de.py", "refetch_de.sh", "tests/test_sn_rework.py"]
27
  SECRET = re.compile(r"hf_[A-Za-z0-9]{30,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY|xox[abps]-[A-Za-z0-9-]{10,}")
28
 
29
 
 
67
  return r
68
 
69
 
70
+ CLEAN_KEYS = ("footnote_rows", "footnote_law_texts", "contents_dropped", "headings_folded", "headings_dropped", "titles_trimmed",
71
+ "norm_headings_dropped", "footnote_digit_rows_dropped", "attachment_stubs_dropped", "repealed_placeholders",
72
+ "metadata_html_cleaned", "folded_ids")
73
+ GAP_KEYS = {"norm_headings_dropped": "empty norm heading (Artikel/§ with no body of its own on the revosax page, e.g. an Artikel that enacts a separate act); not merged into the next Artikel",
74
+ "footnote_digit_rows_dropped": "heading plus only a footnote number/marker, no body",
75
+ "attachment_stubs_dropped": "attachment stub (e.g. 'Anlagen' -> 'Karte'): the attachment itself is not on the page",
76
+ "headings_dropped": "trailing heading-only row (no following article to fold into)",
77
+ "contents_dropped": "contents-list row"}
78
 
79
 
80
  def load_records(land, tags=("-",), include_updates=False, clean_stats=None):
 
91
  r = as_version(r)
92
  r, st = L.clean_record(r); r["_clean"] = st
93
  for k in CLEAN_KEYS:
94
+ cs[k] = cs.get(k, [] if isinstance(st.get(k, 0), list) else 0) + st.get(k, 0)
95
  (rejected if r.get("bounds") else out).append(r)
96
  return out, rejected, updates
97
 
 
169
  cnt = {}
170
  for a in na:
171
  cnt[a["law_id"]] = cnt.get(a["law_id"], 0) + 1
172
+ card = card_counts((pack / "CARD_SECTION.md").read_text())
173
+ rd = pack / "README.md"
174
+ if rd.exists(): # cumulative README: its totals table must equal the written parquet
175
+ rc = readme_counts(rd.read_text(encoding="utf-8"))
176
+ card.update({f"readme:{k}": v for k, v in rc.items()})
177
+ jur = {x: j for x, j in zip(laws.column("id").to_pylist(), laws.column("jurisdiction").to_pylist())}
178
+ data.update({"readme:laws_total": laws.num_rows, "readme:laws_federal": sum(1 for j in jur.values() if j == "DE"),
179
+ "readme:articles_total": arts.num_rows,
180
+ "readme:articles_federal": sum(1 for x in arts.column("law_id").to_pylist() if jur.get(x) == "DE")})
181
+ res = G.gate(nl, na, card, data, bodyless_check=True)
182
  res["article_count_mismatch"] = sum(1 for x in nl if x["article_count"] != cnt.get(x["id"], 0))
183
+ mfs = sorted((pack / "manifests").glob("*_added_ids.jsonl")) if (pack / "manifests").exists() else []
184
+ mf = mfs[0] if len(mfs) == 1 else None
185
+ if mf is not None: # manifest lists exactly the added law + article ids
186
+ man = [json.loads(x) for x in mf.read_text(encoding="utf-8").splitlines() if x.strip()]
187
+ res["manifest_matches_data"] = (sorted(m["id"] for m in man if m["table"] == "laws") == sorted(x["id"] for x in nl)
188
+ and sorted(m["id"] for m in man if m["table"] == "articles") == sorted(a["id"] for a in na))
189
+ else:
190
+ res["manifest_matches_data"] = False
191
+ res["ok"] = res["ok"] and res["article_count_mismatch"] == 0 and res["manifest_matches_data"]
192
  return res
193
 
194
 
195
+ def readme_counts(text):
196
+ m1 = re.search(r"\| Laws / instruments \| (\d+) \(federal (\d+) \+ Landesrecht (\d+)\)", text or "")
197
+ m2 = re.search(r"\| Articles \| (\d+) \(federal (\d+) \+ Landesrecht (\d+)\)", text or "")
198
+ return {"laws_total": int(m1.group(1)) if m1 else None, "laws_federal": int(m1.group(2)) if m1 else None,
199
+ "articles_total": int(m2.group(1)) if m2 else None, "articles_federal": int(m2.group(2)) if m2 else None}
200
+
201
+
202
  def scan_tree(root):
203
  hits = []
204
  for p in Path(root).rglob("*"):
 
237
  out = stage_dir(a.land); pack = out / "pack"
238
  if pack.exists():
239
  shutil.rmtree(pack)
240
+ (pack / "data").mkdir(parents=True); (pack / "scrapers" / "tests").mkdir(parents=True); (pack / "manifests").mkdir()
241
  pq.write_table(laws, pack / "data" / "laws.parquet", compression="zstd")
242
  pq.write_table(arts, pack / "data" / "articles.parquet", compression="zstd")
243
  for f in BUNDLE:
 
245
  print("bundle file missing", f); return 8
246
  shutil.copy2(HERE / f, pack / "scrapers" / f)
247
  rep["bounds_rejected"] = [r["law"]["id"] for r in rejected]
248
+ rep["pii_redactions_all_records"] = sum(r.get("pii_hits", 0) for r in recs) # every collected record, incl. ones not added
249
+ _mark = re.compile(r"\[REDACTED-[a-z_]+\]")
250
+ rep["pii_redactions"] = sum(len(_mark.findall(v or "")) for t, n0 in ((laws, rep["laws_old"]), (arts, rep["articles_old"]))
251
+ for c in ("title", "text", "metadata_json") if c in t.column_names
252
+ for v in t.column(c).to_pylist()[n0:]) # markers in the rows this pack adds
253
  rep["tip_updates_seen"] = updates; rep["tip_updates_included"] = bool(a.include_updates)
254
  added = set(laws.column("id").to_pylist()[rep["laws_old"]:]); ca = {}
255
  for r in recs:
256
  if r["law"]["id"] in added:
257
  for k in CLEAN_KEYS:
258
+ ca[k] = ca.get(k, [] if isinstance(r["_clean"].get(k, 0), list) else 0) + r["_clean"].get(k, 0)
259
  rep["clean_up"] = {k: (len(v) if isinstance(v, list) else v) for k, v in ca.items()} # rows this pack adds
260
  rep["clean_up_ids"] = {k: v for k, v in ca.items() if isinstance(v, list)}
261
  rep["clean_up_all_records"] = {k: (len(v) if isinstance(v, list) else v) for k, v in cs.items()}
262
  rep["source_terms_note"] = L.SOURCE_TERMS_NOTE
263
  rep["built_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
264
+ # 'dropped' = records NOT added because the row is already live (same id, or same title in the same Land): duplicates of live
265
+ # rows, not bounds rejections. bounds_rejected = pages with no norm text of their own (text < min_text_chars).
266
+ rep["not_added_duplicates_of_live_rows"] = {"total": len(rep["dropped"]),
267
+ "by_reason": {w: sum(1 for d in rep["dropped"] if d["why"] == w) for w in sorted({d["why"] for d in rep["dropped"]})}}
268
+ rep["bounds_rejected_reasons"] = {}
269
+ for r in rejected:
270
+ for b in r.get("bounds") or []:
271
+ rep["bounds_rejected_reasons"][b] = rep["bounds_rejected_reasons"].get(b, 0) + 1
272
+ rep["refetched_pages"] = sum(1 for r in recs if r["law"]["id"] in set(laws.column("id").to_pylist()[rep["laws_old"]:]) and refetched(a.land, r["law"]["id"]))
273
+ prefix = os.environ.get("DE_MANIFEST_PREFIX") or ("densify_" + a.land.lower() + "".join(f"_{t}" for t in tags if t and t != "-"))
274
+ rep["manifest_prefix"] = prefix
275
+ write_manifests(pack, prefix, laws, arts, rep, recs, rejected)
276
  (pack / "DENSIFY_REPORT.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1))
277
  (pack / "CARD_SECTION.md").write_text(card_section(a.land, rep))
278
+ if getattr(a, "readme", None):
279
+ rep["_pack"] = str(pack) # read by cumulative_readme only; never written to DENSIFY_REPORT.json
280
+ try:
281
+ (pack / "README.md").write_text(cumulative_readme(Path(a.readme).read_text(encoding="utf-8"), a.land, rep, laws, arts), encoding="utf-8")
282
+ finally:
283
+ rep.pop("_pack", None)
284
  g = finalize_gate(pack, rep["laws_old"], rep["articles_old"])
285
  rep["finalize_gate"] = g
286
  (pack / "DENSIFY_REPORT.json").write_text(json.dumps(rep, ensure_ascii=False, indent=1))
 
291
  if hits:
292
  print("secret scan hits", hits[:5]); return 7
293
  code = {f: sha256(pack / "scrapers" / f) for f in BUNDLE}
294
+ code["_notes"] = {"robots_guard.py": "robots_guard fa882316 (CoS 2026-10-17): adds 'rejected request|support id' to _CHALLENGE and a VERIFY_X509_STRICT-only TLS relax for 4 Taiwan hosts; no German host affected. Earlier DE packs were fetched with 1c9f28bc (one-hop, 2026-10-14)."}
295
  (pack / "scrapers" / "code.json").write_text(json.dumps(code, indent=1))
296
  sums = [f"{sha256(p)} {p.relative_to(pack)}" for p in sorted(pack.rglob("*")) if p.is_file()]
297
  (pack / "SHA256SUMS").write_text("\n".join(sums) + "\n")
298
  print(json.dumps({k: v for k, v in rep.items() if k != "dropped"}), "dropped", len(rep["dropped"])); return 0
299
 
300
 
301
+ def refetched(land, lid):
302
+ """True when the record was rebuilt from a page re-fetched by refetch_de.py (a records_prev/ copy exists)."""
303
+ rid = lid.split("-", 2)[2]
304
+ return any((d / "records_prev" / f"{lid}.json").exists() for d in WORK.glob(land.lower() + "*")) and bool(rid)
305
+
306
+
307
+ def write_manifests(pack, prefix, laws, arts, rep, recs, rejected):
308
+ """manifests/<prefix>_added_ids.jsonl every added law and article id (table, id[, law_id]);
309
+ <prefix>_known_gaps.jsonl rows of the added laws that were dropped by the clean-up (id, law_id, reason) and the repeal
310
+ placeholders kept with metadata_json.body_status; <prefix>_not_added.jsonl collected records not added: duplicates of live
311
+ rows (same id / same title in the same Land) and bounds rejections (no norm text of their own)."""
312
+ md = pack / "manifests"; md.mkdir(exist_ok=True)
313
+ nl, na = rep["laws_old"], rep["articles_old"]
314
+ with open(md / f"{prefix}_added_ids.jsonl", "w", encoding="utf-8") as f:
315
+ for i in laws.column("id").to_pylist()[nl:]:
316
+ f.write(json.dumps({"table": "laws", "id": i}, ensure_ascii=False) + "\n")
317
+ for i, l in zip(arts.column("id").to_pylist()[na:], arts.column("law_id").to_pylist()[na:]):
318
+ f.write(json.dumps({"table": "articles", "id": i, "law_id": l}, ensure_ascii=False) + "\n")
319
+ added = set(laws.column("id").to_pylist()[nl:])
320
+ gaps = []
321
+ for r in recs:
322
+ if r["law"]["id"] not in added:
323
+ continue
324
+ c = r["_clean"]
325
+ for k, why in GAP_KEYS.items():
326
+ for i in c.get(k) or []:
327
+ gaps.append({"id": i, "law_id": r["law"]["id"], "action": "dropped", "reason": k, "why": why})
328
+ for i in c.get("repealed_placeholders") or []:
329
+ gaps.append({"id": i, "law_id": r["law"]["id"], "action": "kept", "reason": "repealed_placeholder",
330
+ "why": "repeal placeholder kept; metadata_json.body_status='repealed_placeholder'; stray footnote digits stripped"})
331
+ with open(md / f"{prefix}_known_gaps.jsonl", "w", encoding="utf-8") as f:
332
+ for g in gaps:
333
+ f.write(json.dumps(g, ensure_ascii=False) + "\n")
334
+ with open(md / f"{prefix}_not_added.jsonl", "w", encoding="utf-8") as f:
335
+ for d in rep["dropped"]:
336
+ f.write(json.dumps({"id": d["id"], "reason": "duplicate_of_live_row", "detail": d["why"]}, ensure_ascii=False) + "\n")
337
+ for r in rejected:
338
+ f.write(json.dumps({"id": r["law"]["id"], "reason": "no_norm_text", "detail": ",".join(r.get("bounds") or []),
339
+ "title": (r["law"].get("title") or "")[:200], "text_chars": len(r["law"].get("text") or "")}, ensure_ascii=False) + "\n")
340
+ rep["known_gaps"] = {k: sum(1 for g in gaps if g["reason"] == k) for k in list(GAP_KEYS) + ["repealed_placeholder"]}
341
+ return gaps
342
+
343
+
344
+ def _fmt(n):
345
+ return f"{n:,}"
346
+
347
+
348
+ def cumulative_readme(live, land, rep, laws, arts):
349
+ """Full live README (as at the tip) + this batch: snapshot/totals rows updated, contents bullet, new section at the end."""
350
+ cfg = L.LANDS[land]; jur = cfg["jurisdiction"]; prefix = rep["manifest_prefix"]; day = rep["built_at"][:10]
351
+ ids = laws.column("id").to_pylist(); js = laws.column("jurisdiction").to_pylist()
352
+ jmap = dict(zip(ids, js)); fed_l = sum(1 for j in js if j == "DE")
353
+ fed_a = sum(1 for x in arts.column("law_id").to_pylist() if jmap.get(x) == "DE")
354
+ s = live
355
+ s = re.sub(r"(\| Snapshot date \| [^|\n]*?)( \|)", lambda m: m.group(1) + (f"; {jur} amending acts {day}" if f"{jur} amending acts" not in m.group(1) else "") + m.group(2), s, count=1)
356
+ s = re.sub(r"\| Laws / instruments \| \d+ \(federal \d+ \+ Landesrecht \d+\)", f"| Laws / instruments | {laws.num_rows} (federal {fed_l} + Landesrecht {laws.num_rows - fed_l})", s, count=1)
357
+ s = re.sub(r"\| Articles \| \d+ \(federal \d+ \+ Landesrecht \d+\)", f"| Articles | {arts.num_rows} (federal {fed_a} + Landesrecht {arts.num_rows - fed_a})", s, count=1)
358
+ bullet = (f"- `manifests/{prefix}_added_ids.jsonl` — every law and article id added by the {jur} amending-acts densify ({day}); "
359
+ f"`manifests/{prefix}_known_gaps.jsonl` — rows of those laws dropped by the clean-up (with reason) and the repeal placeholders kept; "
360
+ f"`manifests/{prefix}_not_added.jsonl` — collected records not added (duplicates of live rows; pages with no norm text).")
361
+ anchor = None
362
+ for anchor in re.finditer(r"^- `manifests/[^\n]*$", s, re.M):
363
+ pass
364
+ s = s[:anchor.end()] + "\n" + bullet + s[anchor.end():] if anchor else s.rstrip("\n") + "\n\n" + bullet + "\n"
365
+ k = rep.get("kinds", {}); cu = rep.get("clean_up", {}); kg = rep.get("known_gaps", {}); nd = rep["not_added_duplicates_of_live_rows"]
366
+ jl_old = sum(1 for j in js[:rep["laws_old"]] if j == jur)
367
+ ja_old = sum(1 for x in arts.column("law_id").to_pylist()[:rep["articles_old"]] if jmap.get(x) == jur)
368
+ gap_ids = {}
369
+ for g in (json.loads(x) for x in (Path(rep["_pack"]) / "manifests" / f"{prefix}_known_gaps.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()):
370
+ gap_ids.setdefault(g["reason"], []).append(g["id"])
371
+ def ids_line(key):
372
+ v = gap_ids.get(key, [])
373
+ return ", ".join(f"`{i}`" for i in v)
374
+ sec = (f"\n## {jur} amending acts densify — {day} ({_fmt(rep['laws_added'])} laws / {_fmt(rep['articles_added'])} articles, append-only at {L.HUB_TIP[:8]})\n\n"
375
+ f"- Source: {cfg['host']} ({cfg['source_type']}); licence: {cfg['license']}\n"
376
+ f"- Kinds: {json.dumps(k, ensure_ascii=False)} — Änderungs-/Aufhebungsgesetze and -verordnungen (`metadata_json.metadata.kind` = `amending`), which the 2026-10-02 append and the 2026-10-15 densify excluded.\n"
377
+ f"- Every live row is byte-identical and comes first; only rows are appended (no live row changed or removed). New law and article ids are unique and disjoint from the tip; `article_count` = article rows for every added law.\n"
378
+ f"- Not added: {_fmt(nd['total'])} collected records are **duplicates of live rows** "
379
+ f"({', '.join(f'{_fmt(v)} {w}' for w, v in nd['by_reason'].items())}); listed in `manifests/{prefix}_not_added.jsonl`. "
380
+ f"(Earlier build logs called these 'dropped'; they are not bounds rejections.)\n"
381
+ f"- Not added: {_fmt(len(rep['bounds_rejected']))} REVOSax pages carry no norm text of their own (text under {L.BOUNDS['min_text_chars']} characters; "
382
+ f"stub pages that only point to a parent act, e.g. `Gesetz zum Zehnten Rundfunkänderungsstaatsvertrag`); listed in the same manifest.\n"
383
+ f"- Clean-up (pipeline, added rows only): revosax footnotes are `[n]` markers plus a plain-text `Fußnoten:` block ({cu.get('footnote_rows', 0)} article rows, "
384
+ f"{cu.get('footnote_law_texts', 0)} law texts converted at pack time); {cu.get('headings_folded', 0)} structural heading rows (Teil/Abschnitt/Zustimmungsgesetz, or an "
385
+ f"`Artikel N` heading over the § rows of the act it contains) folded into the next row; {cu.get('titles_trimmed', 0)} titles cleaned; "
386
+ f"{cu.get('metadata_html_cleaned', 0)} metadata fields cleaned of HTML. An empty `Artikel N` heading is never merged into Artikel N+1: each Artikel keeps its own text.\n"
387
+ f"- Repeal placeholders kept: {kg.get('repealed_placeholder', 0)} rows such as `Artikel 7 (außer Kraft)` / `(aufgehoben)` stay as rows, with stray footnote digits removed "
388
+ f"and `metadata_json.body_status` = `repealed_placeholder` (no new column; the dataset schema is unchanged): {ids_line('repealed_placeholder')}.\n"
389
+ f"- Personal data: only personal data of private individuals is redacted (`[REDACTED-<kind>]`); official accounts (Bundesbank / public cash offices), "
390
+ f"functional and authority mailboxes (e.g. `@sachsen.de`) and table numbers stay verbatim. Redaction markers in the added rows: {rep.get('pii_redactions', 0)}.\n"
391
+ f"- Pages re-fetched for this rebuild (robots-checked, gated, polite delay) and cached so later parser fixes re-parse offline: {rep.get('refetched_pages', 0)}.\n\n"
392
+ f"### Known gaps ({jur} amending acts)\n\n"
393
+ f"Rows of the added laws that are not in the data (every id with its reason is in `manifests/{prefix}_known_gaps.jsonl`):\n\n"
394
+ f"- {kg.get('norm_headings_dropped', 0)} empty `Artikel` headings with no body on the REVOSax page (mostly an Artikel that enacts a separate act, whose text "
395
+ f"REVOSax keeps under that act's own page): {ids_line('norm_headings_dropped')}.\n"
396
+ f"- {kg.get('footnote_digit_rows_dropped', 0)} heading rows with only a footnote number: {ids_line('footnote_digit_rows_dropped')}.\n"
397
+ f"- {kg.get('attachment_stubs_dropped', 0)} attachment stubs (the map / Anhang itself is not on the page): {ids_line('attachment_stubs_dropped')}.\n"
398
+ f"- {kg.get('headings_dropped', 0)} trailing heading-only rows (`Anlage`, `Anhang`, `Übersichtskarte` … with no content after them): listed in the manifest.\n\n"
399
+ f"### source_terms_note\n\n{L.SOURCE_TERMS_NOTE}\n\nEvery added row also carries `source_terms_note` inside `metadata_json.metadata`.\n\n"
400
+ f"{jur} totals after this batch: {_fmt(jl_old + rep['laws_added'])} laws ({_fmt(jl_old)} + {_fmt(rep['laws_added'])}) / "
401
+ f"{_fmt(ja_old + rep['articles_added'])} articles ({_fmt(ja_old)} + {_fmt(rep['articles_added'])}). "
402
+ f"Dataset totals: {_fmt(laws.num_rows)} laws / {_fmt(arts.num_rows)} articles.\n"
403
+ f"- The bundled `scrapers/de_lib.py` has default `HUB_TIP` {L.HUB_TIP[:8]} (the parent of this batch); set `DE_HUB_TIP` to the current tip before building a new pack.\n")
404
+ return s.rstrip("\n") + "\n" + sec
405
+
406
+
407
  def card_section(land, rep):
408
  cfg = L.LANDS[land]
409
  return (f"## {cfg['jurisdiction']} densify ({rep['laws_added']} laws / {rep['articles_added']} articles, append-only at {L.HUB_TIP[:8]})\n\n"
410
  f"- Source: {cfg['host']} ({cfg['source_type']}); licence: {cfg['license']}\n"
411
  f"- Kinds: {json.dumps(rep.get('kinds', {}), ensure_ascii=False)}\n"
412
+ + (f"- Not added: {rep['not_added_duplicates_of_live_rows']['total']} records that are duplicates of live rows "
413
+ f"({', '.join(f'{v} {w}' for w, v in rep['not_added_duplicates_of_live_rows']['by_reason'].items())}); "
414
+ f"{len(rep.get('bounds_rejected', []))} stub pages with no norm text of their own (they only point to a parent act)\n"
415
+ if "not_added_duplicates_of_live_rows" in rep else "")
416
  + (f"- Clean-up (pipeline, added rows only): {cu.get('contents_dropped', 0)} contents-list rows dropped; revosax footnote HTML converted "
417
  f"to plain-text 'Fußnoten:' blocks in {cu.get('footnote_rows', 0)} article rows and {cu.get('footnote_law_texts', 0)} law texts; "
418
  f"{cu.get('headings_folded', 0)} heading-only rows folded into the next article, {cu.get('headings_dropped', 0)} trailing ones dropped; "
419
+ f"{cu.get('titles_trimmed', 0)} titles cleaned; known gaps (dropped, listed in manifests/): {cu.get('norm_headings_dropped', 0)} empty Artikel headings, "
420
+ f"{cu.get('footnote_digit_rows_dropped', 0)} footnote-number-only rows, {cu.get('attachment_stubs_dropped', 0)} attachment stubs; "
421
+ f"{cu.get('repealed_placeholders', 0)} repeal placeholders kept (metadata_json.body_status)\n" if (cu := rep.get("clean_up")) else "") + "\n"
422
  f"### source_terms_note\n\n{L.SOURCE_TERMS_NOTE}\n\n"
423
  "Every added row also carries `source_terms_note` inside `metadata_json.metadata`.\n")
424
 
 
456
  ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
457
  p = sp.add_parser("ids"); p.add_argument("--out", default=str(WORK / "hub_tip_ids.txt")); p.add_argument("--laws", default="")
458
  p = sp.add_parser("build"); p.add_argument("--land", required=True); p.add_argument("--live-laws", required=True); p.add_argument("--live-articles", required=True)
459
+ p.add_argument("--readme", default="", help="live README.md at the tip (read-only copy); the pack README = it + this batch's section")
460
  p.add_argument("--tags", default=None, help="comma list of sub-lanes, '-' = main (e.g. SN: '-,amending'; BB: vwv; NW: delta)")
461
  p.add_argument("--include-updates", action="store_true", help="NW: add tip_update records as separate '<id>@<valid_from>' version rows")
462
  p = sp.add_parser("stage"); p.add_argument("--land", required=True)
scrapers/refetch_de.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Targeted re-fetch / offline re-parse of already-collected DE Landesrecht records (added 2026-10-17 after CoS rejected the
3
+ DE-SN amending densify: records had been redacted/parsed at fetch time and no raw page was kept).
4
+
5
+ refetch_de.py fetch --land SN --tag amending --ids 4371,3982 # only ids with no cached page are fetched (run via refetch_de.sh:
6
+ # light gate + short-lane flock + 300 s stagger; robots_guard
7
+ # GuardedSession, scope check, per-host delay, challenge -> park)
8
+ refetch_de.py reparse --land SN --tag amending [--ids ...] # offline: rebuild records from $DE_PAGE_CACHE with the current parser
9
+
10
+ A rebuilt record keeps the law id, kind and tip_update flag; the previous record is kept once under records_prev/.
11
+ Exit: 0 ok, 2 robots, 6 host park, 9 id has no record / no cached page (reparse).
12
+ """
13
+ import argparse, gzip, json, sys, time
14
+ from pathlib import Path
15
+
16
+ HERE = Path(__file__).resolve().parent
17
+ sys.path.insert(0, str(HERE))
18
+ import collect_de_laender as C # noqa: E402 (sets LEGAL_CORPORA_ROOT for the guard)
19
+ import de_lib as L # noqa: E402
20
+ import robots_guard as RG # noqa: E402
21
+
22
+ PARSE = {"SN": L.parse_sn_page, "BB": L.parse_bb_page, "NW": L.parse_nw_page}
23
+
24
+
25
+ def lane(land, tag):
26
+ return C.Lane(land, set(), set(), tag)
27
+
28
+
29
+ def rebuild(ln, rid, page, retrieved_at=None):
30
+ lid = L.law_id(ln.land, rid)
31
+ p = ln.rec / f"{lid}.json"
32
+ old = json.loads(p.read_text())
33
+ url = old["law"]["source_url"]
34
+ info = PARSE[ln.land](page, url)
35
+ info["kind"] = old.get("kind") or info.get("kind", "")
36
+ ts = retrieved_at or old["law"]["retrieved_at"]
37
+ law, arts, hits = L.make_rows(ln.land, info, url, ts)
38
+ out = dict(old, law=law, articles=arts, pii_hits=len(hits), bounds=L.check_bounds(info))
39
+ prev = ln.work / "records_prev" / p.name
40
+ if not prev.exists():
41
+ prev.parent.mkdir(parents=True, exist_ok=True); prev.write_text(p.read_text())
42
+ tmp = p.with_suffix(".tmp"); tmp.write_text(json.dumps(out, ensure_ascii=False)); tmp.replace(p)
43
+ return out
44
+
45
+
46
+ def read_cache(ln, rid):
47
+ f = ln.pages / f"{rid}.html.gz"
48
+ return gzip.open(f, "rt", encoding="utf-8").read() if f.exists() else None
49
+
50
+
51
+ def cmd_fetch(a):
52
+ ln = lane(a.land, a.tag)
53
+ ids = [x.strip() for x in a.ids.split(",") if x.strip()]
54
+ for rid in ids:
55
+ if not (ln.rec / f"{L.law_id(a.land, rid)}.json").exists():
56
+ print("no record", rid); return 9
57
+ if ln.parked.exists():
58
+ print("PARKED_host present; not fetching"); return C.RC_HOST_PARK
59
+ C.start_guard() # collector hard floor (GATE_HARD_MIB from gate_profile.sh) + RSS cap
60
+ RG.set_country("de")
61
+ s = RG.GuardedSession()
62
+ s.headers.update({"User-Agent": RG.ROBOTS_UA, "Accept": "text/html,application/xml;q=0.9,*/*;q=0.5"})
63
+ log = []
64
+ try:
65
+ for rid in ids:
66
+ page = read_cache(ln, rid)
67
+ if page is not None:
68
+ log.append({"rid": rid, "cached": True}); continue
69
+ url = json.loads((ln.rec / f"{L.law_id(a.land, rid)}.json").read_text())["law"]["source_url"]
70
+ try:
71
+ page = ln.fetch_page(s, rid, url, "refetch")
72
+ except C.Transient as e: # one retry after a pause, then skip the id (reported; a rerun picks it up, cached ids are not refetched)
73
+ print("transient", rid, str(e)[:200], flush=True); time.sleep(30)
74
+ try:
75
+ page = ln.fetch_page(s, rid, url, "refetch")
76
+ except C.Transient as e2:
77
+ log.append({"rid": rid, "failed": str(e2)[:200]}); print("failed", rid, flush=True); continue
78
+ rebuild(ln, rid, page, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
79
+ log.append({"rid": rid, "fetched": True})
80
+ print("fetched", rid, flush=True)
81
+ except (RG.RobotsBlocked, C.RobotsTLS) as e:
82
+ print("robots", e); return C.RC_ROBOTS
83
+ except C.HostStop as e:
84
+ ln.parked.write_text(f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} {str(e)[:300]}\n"); print("host stop", e); return C.RC_HOST_PARK
85
+ except C.Transient as e:
86
+ print("transient", e); return 9
87
+ finally:
88
+ print(json.dumps({"fetched": sum(1 for x in log if x.get("fetched")), "cached": sum(1 for x in log if x.get("cached")),
89
+ "failed": [x["rid"] for x in log if x.get("failed")]}))
90
+ return 9 if any(x.get("failed") for x in log) else 0
91
+
92
+
93
+ def cmd_reparse(a):
94
+ ln = lane(a.land, a.tag)
95
+ ids = [x.strip() for x in a.ids.split(",") if x.strip()] if a.ids else sorted(f.name.split(".")[0] for f in ln.pages.glob("*.html.gz"))
96
+ n = 0
97
+ for rid in ids:
98
+ page = read_cache(ln, rid)
99
+ if page is None or not (ln.rec / f"{L.law_id(a.land, rid)}.json").exists():
100
+ print("no cached page / record", rid); return 9
101
+ rebuild(ln, rid, page); n += 1
102
+ print("reparsed", n); return 0
103
+
104
+
105
+ def main(argv=None):
106
+ ap = argparse.ArgumentParser(); sp = ap.add_subparsers(dest="cmd", required=True)
107
+ for c in ("fetch", "reparse"):
108
+ p = sp.add_parser(c); p.add_argument("--land", required=True, choices=sorted(PARSE)); p.add_argument("--tag", default="")
109
+ p.add_argument("--ids", required=(c == "fetch"), default="")
110
+ a = ap.parse_args(argv)
111
+ return {"fetch": cmd_fetch, "reparse": cmd_reparse}[a.cmd](a)
112
+
113
+
114
+ if __name__ == "__main__":
115
+ sys.exit(main())
scrapers/refetch_de.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Gated wrapper for refetch_de.py fetch (2026-10-17). Same gate as a DE short-lane slice: gate_profile.sh light/v2 start
3
+ # MemAvailable + disk >= 12600 MiB held 120 s, then the shared short-lane flock with flock -n (never steals it; busy -> retry
4
+ # from the gate), monotonic deadline REFETCH_WAIT_S (exit 74/75); honours and stamps the 300 s stagger; 30 min TERM timeout. The DE/GI turn files are NOT touched (no turn consumed).
5
+ # refetch_de.sh SN amending 4371,3982,...
6
+ set -u
7
+ CODE=$(cd "$(dirname "$0")" && pwd); . "$CODE/gate_profile.sh"
8
+ PY=${DE_PYTHON:-/workspace/legal-corpora/.venv/bin/python}; WORK=${DE_WORK:-/workspace/de_laender/work}
9
+ LOCK=${DE_LANE_LOCK:-/dev/shm/muni_runner.short.lock}; STAMP=${DE_LANE_STAMP:-/dev/shm/muni_last_start}
10
+ WAIT=${REFETCH_WAIT_S:-7200}
11
+ unset HF_TOKEN HUGGINGFACE_HUB_TOKEN HUGGING_FACE_HUB_TOKEN HF_HUB_TOKEN
12
+ export DE_WORK=$WORK MALLOC_ARENA_MAX=2
13
+ mono() { cut -d. -f1 /proc/uptime; }
14
+ gate_profile "$WORK"; echo "[$(date -Is)] refetch gate profile $GATE_PROFILE (start $GATE_START_MIB MiB)"
15
+ end_all=$(( $(mono) + WAIT ))
16
+ while :; do
17
+ # gate first (nothing held), then the flock (-n, never steal), then a quick re-check of the start threshold
18
+ good=0
19
+ while :; do
20
+ m=$(awk '/MemAvailable/{print int($2/1024)}' /proc/meminfo); d=$(df -BM --output=avail /workspace | tail -1 | tr -dc 0-9)
21
+ if [ "$m" -ge "$GATE_START_MIB" ] && [ "$d" -ge 12600 ]; then good=$((good+5)); else good=0; fi
22
+ [ $good -ge 120 ] && break
23
+ [ "$(mono)" -ge $end_all ] && { echo "[$(date -Is)] gate/lock not obtained within ${WAIT} s (mem $m)"; exit 74; }
24
+ sleep 5
25
+ done
26
+ exec 9>"$LOCK"
27
+ if flock -n 9; then
28
+ m=$(awk '/MemAvailable/{print int($2/1024)}' /proc/meminfo)
29
+ [ "$m" -ge "$GATE_START_MIB" ] && { echo "[$(date -Is)] gate ok 120 s + short-lane flock held (mem $m MiB)"; break; }
30
+ flock -u 9
31
+ fi
32
+ exec 9>&-
33
+ [ "$(mono)" -ge $end_all ] && { echo "[$(date -Is)] short lane busy / gate lost until deadline"; exit 75; }
34
+ sleep 20
35
+ done
36
+ while :; do
37
+ last=$(stat -c %Y "$STAMP" 2>/dev/null || echo 0); now=$(date +%s)
38
+ [ $((now - last)) -ge 300 ] && break
39
+ sleep 15
40
+ done
41
+ ( flock 8; date -Is > "$STAMP" ) 8>"$STAMP.lock"
42
+ echo "[$(date -Is)] stagger ok; refetch_de.py fetch --land $1 --tag $2"
43
+ timeout -s TERM 30m "$PY" "$CODE/refetch_de.py" fetch --land "$1" --tag "$2" --ids "$3"
44
+ rc=$?; echo "[$(date -Is)] refetch rc=$rc"; exit $rc
scrapers/robots_guard.py CHANGED
@@ -422,6 +422,132 @@ def ca_verify_for(url_or_host: str) -> object:
422
  return _default_ca()
423
 
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  # --- robots.txt redirect policy (CoS GO 2026-10-14 21:39 PT, "one-hop" fix) ---------------------------------------
426
  # Redirects on a robots.txt fetch are followed manually, one hop at a time:
427
  # * same-host hop (scheme change allowed): followed, at most ROBOTS_MAX_HOPS hops in total;
@@ -482,6 +608,7 @@ def _default_fetch(robots_url: str):
482
  try:
483
  url, r, hops, seen = robots_url, None, 0, {robots_url}
484
  with requests.Session() as sess:
 
485
  while True:
486
  _robots_hop_clock(url, paced=hops > 0)
487
  r = sess.get(url, timeout=ROBOTS_TIMEOUT, allow_redirects=False, verify=ca_verify_for(url),
@@ -520,7 +647,8 @@ def _default_fetch(robots_url: str):
520
 
521
 
522
  _CHALLENGE = re.compile(r"just a moment|cf-browser-verification|challenge-platform|captcha|awswaf|"
523
- r"checking your browser|enable javascript|request rejected|access denied", re.I)
 
524
 
525
 
526
  def _load_host(origin: str, host: str) -> HostState:
@@ -872,6 +1000,10 @@ try:
872
 
873
  min_interval: float = 0.0
874
 
 
 
 
 
875
  def send(self, request, **kwargs):
876
  guard_send(request.url, min_interval=self.min_interval, caller="GuardedSession")
877
  return super().send(request, **kwargs)
 
422
  return _default_ca()
423
 
424
 
425
+ # --- per-host TLS: clear ONLY ssl.VERIFY_X509_STRICT (CoS GO 2026-10-16, Taiwan municipal law hosts) ------------
426
+ # Python 3.13 / urllib3 2.3+ turn on VERIFY_X509_STRICT, which rejects some TW government certificates
427
+ # ("Missing Subject Key Identifier") that OpenSSL otherwise verifies fine. For the EXACT hosts below (no subdomains,
428
+ # no wildcards) the SSL context is the normal urllib3/certifi one with that single flag cleared:
429
+ # * verify_mode stays ssl.CERT_REQUIRED, check_hostname stays True, the full chain is still verified against
430
+ # certifi (or the host's registered CA bundle), all other verify_flags (e.g. VERIFY_X509_PARTIAL_CHAIN) unchanged;
431
+ # * verify=False is refused for these hosts (never used anywhere);
432
+ # * every use (context build and every request) is appended to <logdir>/tls/tls_relaxed_strict.jsonl.
433
+ # Applied to the robots.txt fetch (_default_fetch) and to GuardedSession (and guarded_get/... wrappers). Not applied
434
+ # to guarded_urlopen / guarded_curl_run (curl uses system OpenSSL, which does not enable X509_STRICT).
435
+ import ssl as _ssl # noqa: E402
436
+
437
+ TLS_RELAX_STRICT_HOSTS = frozenset({
438
+ "laws.gov.taipei", # Taipei City law system (臺北市法規查詢系統)
439
+ "www.laws.taipei.gov.tw", # Taipei legacy host (301 -> laws.gov.taipei)
440
+ "web.law.ntpc.gov.tw", # New Taipei City (新北市法規查詢系統)
441
+ "outlaw.kcg.gov.tw", # Kaohsiung City (高雄市法規查詢系統)
442
+ })
443
+
444
+
445
+ class TLSPolicyError(ValueError):
446
+ """Refused TLS configuration (e.g. verify=False on a relaxed-strict host, or a host not on the allowlist)."""
447
+
448
+
449
+ def tls_relax_strict_allowed(url_or_host: str) -> bool:
450
+ host = (urlsplit(url_or_host).hostname if "://" in url_or_host else url_or_host) or ""
451
+ return host.lower().strip(".") in TLS_RELAX_STRICT_HOSTS
452
+
453
+
454
+ def _log_tls_relax(row: dict) -> None:
455
+ _append_jsonl(_logdir() / "tls" / "tls_relaxed_strict.jsonl", {"ts": _utc_iso(), "country": country(), **row})
456
+
457
+
458
+ def relaxed_strict_ssl_context(host: str, cafile=None, caller: str = ""):
459
+ """SSL context for an allowlisted host: default verified context minus VERIFY_X509_STRICT only."""
460
+ host = (host or "").lower().strip(".")
461
+ if host not in TLS_RELAX_STRICT_HOSTS:
462
+ raise TLSPolicyError(f"host not on TLS_RELAX_STRICT_HOSTS: {host!r}")
463
+ try:
464
+ from urllib3.util.ssl_ import create_urllib3_context
465
+ ctx = create_urllib3_context(cert_reqs=_ssl.CERT_REQUIRED)
466
+ except Exception: # pragma: no cover - urllib3 missing
467
+ ctx = _ssl.create_default_context()
468
+ if cafile is None:
469
+ cafile = ca_verify_for(host)
470
+ if isinstance(cafile, str) and os.path.isdir(cafile):
471
+ ctx.load_verify_locations(capath=cafile)
472
+ elif isinstance(cafile, str):
473
+ ctx.load_verify_locations(cafile=cafile)
474
+ else:
475
+ ctx.load_default_certs()
476
+ before = int(ctx.verify_flags)
477
+ ctx.verify_flags &= ~_ssl.VERIFY_X509_STRICT
478
+ ctx.verify_mode = _ssl.CERT_REQUIRED
479
+ ctx.check_hostname = True
480
+ assert ctx.verify_mode == _ssl.CERT_REQUIRED and ctx.check_hostname
481
+ assert not (ctx.verify_flags & _ssl.VERIFY_X509_STRICT)
482
+ _log_tls_relax({"event": "context", "host": host, "caller": caller, "cafile": str(cafile),
483
+ "verify_flags_before": before, "verify_flags_after": int(ctx.verify_flags),
484
+ "verify_mode": "CERT_REQUIRED", "check_hostname": True})
485
+ return ctx
486
+
487
+
488
+ try:
489
+ from requests.adapters import HTTPAdapter as _HTTPAdapter
490
+
491
+ class _RelaxedStrictAdapter(_HTTPAdapter):
492
+ """HTTPS adapter bound to ONE allowlisted host; pools use relaxed_strict_ssl_context(host)."""
493
+
494
+ def __init__(self, host: str, caller: str = "", **kw):
495
+ self._rs_host = host.lower().strip(".")
496
+ if self._rs_host not in TLS_RELAX_STRICT_HOSTS:
497
+ raise TLSPolicyError(f"host not on TLS_RELAX_STRICT_HOSTS: {host!r}")
498
+ self._rs_caller = caller
499
+ super().__init__(**kw)
500
+
501
+ def init_poolmanager(self, *a, **kw):
502
+ kw["ssl_context"] = relaxed_strict_ssl_context(self._rs_host, caller=self._rs_caller)
503
+ return super().init_poolmanager(*a, **kw)
504
+
505
+ def proxy_manager_for(self, proxy, **kw):
506
+ kw["ssl_context"] = relaxed_strict_ssl_context(self._rs_host, caller=self._rs_caller + ":proxy")
507
+ return super().proxy_manager_for(proxy, **kw)
508
+
509
+ def send(self, request, **kw):
510
+ host = (urlsplit(request.url).hostname or "").lower()
511
+ if host != self._rs_host:
512
+ raise TLSPolicyError(f"relaxed adapter for {self._rs_host} got {host}")
513
+ if kw.get("verify") is False:
514
+ _log_tls_relax({"event": "refused_verify_false", "host": host, "url": request.url, "caller": self._rs_caller})
515
+ raise TLSPolicyError(f"verify=False refused for {host}")
516
+ _log_tls_relax({"event": "request", "host": host, "method": request.method, "url": request.url,
517
+ "caller": self._rs_caller})
518
+ return super().send(request, **kw)
519
+
520
+ class TLSPolicyAdapter(_HTTPAdapter):
521
+ """Mounted on https:// : allowlisted hosts go through their _RelaxedStrictAdapter, all others unchanged."""
522
+
523
+ def __init__(self, caller: str = "", **kw):
524
+ self._caller, self._relaxed = caller, {}
525
+ super().__init__(**kw)
526
+
527
+ def send(self, request, **kw):
528
+ host = (urlsplit(request.url).hostname or "").lower().strip(".")
529
+ if urlsplit(request.url).scheme == "https" and host in TLS_RELAX_STRICT_HOSTS:
530
+ ad = self._relaxed.get(host)
531
+ if ad is None:
532
+ ad = self._relaxed[host] = _RelaxedStrictAdapter(host, caller=self._caller)
533
+ return ad.send(request, **kw)
534
+ return super().send(request, **kw)
535
+
536
+ def close(self):
537
+ for ad in self._relaxed.values():
538
+ ad.close()
539
+ super().close()
540
+ except Exception: # pragma: no cover - requests missing
541
+ TLSPolicyAdapter = None # type: ignore
542
+
543
+
544
+ def mount_tls_policy(sess, caller: str = ""):
545
+ """Mount TLSPolicyAdapter on a requests.Session (no-op for objects without .mount, e.g. test fakes)."""
546
+ if TLSPolicyAdapter is not None and hasattr(sess, "mount"):
547
+ sess.mount("https://", TLSPolicyAdapter(caller=caller))
548
+ return sess
549
+
550
+
551
  # --- robots.txt redirect policy (CoS GO 2026-10-14 21:39 PT, "one-hop" fix) ---------------------------------------
552
  # Redirects on a robots.txt fetch are followed manually, one hop at a time:
553
  # * same-host hop (scheme change allowed): followed, at most ROBOTS_MAX_HOPS hops in total;
 
608
  try:
609
  url, r, hops, seen = robots_url, None, 0, {robots_url}
610
  with requests.Session() as sess:
611
+ mount_tls_policy(sess, caller="robots_fetch")
612
  while True:
613
  _robots_hop_clock(url, paced=hops > 0)
614
  r = sess.get(url, timeout=ROBOTS_TIMEOUT, allow_redirects=False, verify=ca_verify_for(url),
 
647
 
648
 
649
  _CHALLENGE = re.compile(r"just a moment|cf-browser-verification|challenge-platform|captcha|awswaf|"
650
+ r"checking your browser|enable javascript|request rejected|access denied|"
651
+ r"rejected request|support id", re.I) # + F5 BIG-IP ASM page (CoS 2026-10-16; OCM/Senate KH)
652
 
653
 
654
  def _load_host(origin: str, host: str) -> HostState:
 
1000
 
1001
  min_interval: float = 0.0
1002
 
1003
+ def __init__(self, *a, **kw):
1004
+ super().__init__(*a, **kw)
1005
+ mount_tls_policy(self, caller="GuardedSession") # per-host VERIFY_X509_STRICT relax (allowlist only)
1006
+
1007
  def send(self, request, **kwargs):
1008
  guard_send(request.url, min_interval=self.min_interval, caller="GuardedSession")
1009
  return super().send(request, **kwargs)
scrapers/tests/test_finalize_gate.py CHANGED
@@ -100,6 +100,33 @@ class Gate(unittest.TestCase):
100
  self.assertTrue(g["ok"], g)
101
 
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  class PackGate(unittest.TestCase):
104
  def test_pack_gate_card_rows_vs_parquet(self):
105
  import tempfile, pyarrow as pa, pyarrow.parquet as pq
 
100
  self.assertTrue(g["ok"], g)
101
 
102
 
103
+ class GenericHtml(unittest.TestCase): # 2026-10-17: any tag, not a list; metadata strings too
104
+ def test_any_tag_name(self):
105
+ for t in ('<section data-anchor="1" data-level="1" title="Artikel 1" id="x1" >', "<wbr>", "</article>", "<o:p>", "<BR>",
106
+ '<a href="/vorschrift/17134" title="A\nB">', 'Forstvermehrungsgutverordnung)">', "&lt;section id=\"x\"&gt;"):
107
+ self.assertTrue(G.RAW_HTML.search(t), t)
108
+ for t in ("– y <ER/SIE>", "§ 1 a < b > c", "<Name, Vorname>", "Wert <5 mg", "Text [1]"):
109
+ self.assertFalse(G.RAW_HTML.search(t), t)
110
+
111
+ def test_strip_removes_unlisted_tags_without_gluing(self):
112
+ t, _ = G.strip_html_footnotes('Präambel:\n<section data-anchor="1" title="Artikel 1 A\nB" id="x1" >\nArtikel 1')
113
+ self.assertEqual(t, "Präambel:\nArtikel 1"); self.assertIsNone(G.RAW_HTML.search(t))
114
+
115
+ def test_gate_scans_metadata_json(self):
116
+ row = {"id": "a:1", "title": "Artikel 2", "text": "Body", "metadata_json": '{"titel": "2 <a data-name=\'FAG\'>FAG</a>"}'}
117
+ g = G.gate([], [row], {}, {})
118
+ self.assertFalse(g["ok"]); self.assertEqual(g["raw_html_ids"], ["a:1"])
119
+ self.assertTrue(G.gate([], [dict(row, metadata_json='{"titel": "2 FAG"}')], {}, {})["ok"])
120
+
121
+ def test_body_status_repealed_placeholder_counted_apart(self):
122
+ row = {"id": "a:7", "title": "Artikel 7 (aufgehoben)", "text": "Artikel 7\n(aufgehoben)", "metadata_json": '{"body_status": "repealed_placeholder"}'}
123
+ g = G.gate([], [row], {}, {})
124
+ self.assertTrue(g["ok"], g); self.assertEqual((g["heading_only_rows"], g["repealed_placeholder_rows"]), (0, 1))
125
+ self.assertTrue(G.is_repeal_placeholder("Artikel 7 (außer Kraft)", "Artikel 7\n1\n(außer Kraft)"))
126
+ self.assertTrue(G.is_bodyless("Artikel 2 Änderung der X", "Artikel 2\nÄnderung der X 1"))
127
+ self.assertFalse(G.is_bodyless("Artikel 2 Änderung der X", "Artikel 2\nÄnderung der X\nIn § 1 wird ..."))
128
+
129
+
130
  class PackGate(unittest.TestCase):
131
  def test_pack_gate_card_rows_vs_parquet(self):
132
  import tempfile, pyarrow as pa, pyarrow.parquet as pq
scrapers/tests/test_sn_rework.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Offline tests for the 2026-10-17 DE-SN amending rework (CoS rejection): PII policy, revosax parser root causes, generic raw-HTML
3
+ gate incl. metadata, norm-heading / repeal-placeholder clean-up, page cache + offline re-parse, pack manifests and cumulative README."""
4
+ import gzip, json, os, sys, tempfile, unittest
5
+ from pathlib import Path
6
+
7
+ HERE = Path(__file__).resolve().parent; CODE = HERE.parent
8
+ TMP = Path(tempfile.mkdtemp(prefix="de_rework_"))
9
+ os.environ["DE_WORK"] = str(TMP / "work"); os.environ["DE_GUARD_ROOT"] = str(TMP / "guard")
10
+ sys.path.insert(0, str(CODE))
11
+ import de_lib as L # noqa: E402
12
+ import finalize_gate as G # noqa: E402
13
+
14
+ URL = "https://www.revosax.sachsen.de/vorschrift/99-Aend-X"
15
+
16
+
17
+ class Pii(unittest.TestCase):
18
+ def test_table_numbers_are_not_tax_ids(self):
19
+ t = "152\n40 000\n160\n55 000\n165\n32 500 000\n200 und 12 345 678 901 Euro"
20
+ self.assertEqual(L.pii_scan(t), (t, []))
21
+
22
+ def test_tax_id_needs_label_and_one_line(self):
23
+ t, h = L.pii_scan("Steuer-Identifikationsnummer: 12 345 678 901 des Herrn X")
24
+ self.assertIn("[REDACTED-taxid]", t); self.assertEqual(h, [("taxid", "12 345 678 901")])
25
+ self.assertEqual(L.pii_scan("Steuer-ID\n\n\n\n" + "x" * 50 + " 12345678901")[1], [])
26
+
27
+ def test_official_ibans_stay(self):
28
+ for t in ("Bundeskasse Trier – Dienstsitz Kiel, IBAN:\nDE81 2100 0000 0021 0010 20, BIC: MARK DE F1 200 unter Angabe",
29
+ "„IBAN: DE38 8600 0000 0086 0010 40, BIC: MARK DE F1 860“", "Landeshauptkasse Sachsen, IBAN DE22 8505 0300 3120 0001 23"):
30
+ self.assertEqual(L.pii_scan(t), (t, []), t)
31
+
32
+ def test_private_iban_redacted(self):
33
+ t, h = L.pii_scan("Herr Max Muster, IBAN DE89 3704 0044 0532 0130 00")
34
+ self.assertIn("[REDACTED-iban]", t); self.assertEqual(h[0][0], "iban")
35
+
36
+ def test_official_and_functional_mailboxes_stay(self):
37
+ for t in ("E-Mail-Adresse: datenschutzbeauftragter@smk.\xadsachsen.de.", "an phishing@lsf.sachsen.de zu senden",
38
+ "poststelle@smi.sachsen.de", "datenschutz@example-verband.de"):
39
+ self.assertEqual(L.pii_scan(t), (t, []), t)
40
+ t, h = L.pii_scan("privat: max.muster@gmail.com")
41
+ self.assertEqual(t, "privat: [REDACTED-email]"); self.assertEqual(h, [("email", "max.muster@gmail.com")])
42
+
43
+
44
+ PAGE = ('<html><h1>AendVO</h1><header class="x" title="Eingangsformel"><b>Verordnung</b><br/>der Staatsregierung zur Änderung der<br>'
45
+ 'Infektionsschutzgesetz-Zuständigkeitsverordnung<p><b>Vom 5. Januar 2022</b></p></header>'
46
+ '<article id="lesetext">'
47
+ '<section data-anchor="1" data-level="1" title="Artikel&nbsp;1 Sächsisches<br>Wassergesetz (SächsWG)" id="a1"><h4>Artikel 1</h4>'
48
+ '<p>Sächsisches Wassergesetz<br>(SächsWG)</p></section>'
49
+ '<section data-anchor="1" data-level="1" title="Artikel 2 Verordnung<br/>der Staatsregierung\nzur Durchführung" data-link="a2" id="a2">'
50
+ '<p>Artikel 2</p><p>Verordnung</p><p>Text<a title="Artikel 2 tritt am\n1. Januar 2002 in Kraft" class="fussnote_link" href="#FNID_1"> 1</a>'
51
+ ' gilt. Siehe <a href="/vorschrift/17134" title="Sächsische\nOrdnung">SächsO</a>.</p></section>'
52
+ '<section data-anchor="1" data-level="1" id="a3"><p>Artikel 3</p><p>Inkrafttreten</p><p>Tritt in Kraft.</p></section>'
53
+ '</article></html>')
54
+
55
+
56
+ class PiiTypo(unittest.TestCase):
57
+ def test_official_mailbox_with_printed_typo_kept(self): # de-sn-20360
58
+ t = "Betreff an spammeldung@lit.justiz.sachsden.de zu senden."
59
+ self.assertEqual(L.pii_scan(t)[0] if isinstance(L.pii_scan(t), tuple) else t, t)
60
+ self.assertTrue(L.mail_is_official("spammeldung@lit.justiz.sachsden.de"))
61
+ self.assertFalse(L.mail_is_official("max.mustermann@gmx.de"))
62
+
63
+
64
+ class Parser(unittest.TestCase):
65
+ def setUp(self):
66
+ self.i = L.parse_sn_page(PAGE, URL)
67
+
68
+ def test_title_br_is_a_space(self):
69
+ self.assertEqual(self.i["sections"][0]["title"], "Artikel\xa01 Sächsisches Wassergesetz (SächsWG)")
70
+ self.assertIn("der Infektionsschutzgesetz-Zuständigkeitsverordnung", self.i["title"])
71
+ self.assertNotIn("derInfektions", self.i["title"])
72
+
73
+ def test_gt_inside_attribute_keeps_title_and_text_clean(self):
74
+ s = self.i["sections"][1]
75
+ self.assertEqual(s["title"], "Artikel 2 Verordnung der Staatsregierung zur Durchführung"); self.assertEqual(s["anchor"], "a2")
76
+ self.assertNotIn('">', s["text"]); self.assertFalse(G.RAW_HTML.search(s["text"]))
77
+
78
+ def test_wrapped_anchor_and_footnote(self):
79
+ s = self.i["sections"][1]["text"]
80
+ self.assertIn("Text [1] gilt.", s); self.assertIn("SächsO", s)
81
+ self.assertTrue(s.endswith("Fußnoten:\n[1] Artikel 2 tritt am 1. Januar 2002 in Kraft"))
82
+ self.assertNotIn("<a", self.i["text"])
83
+
84
+ def test_no_title_attribute_falls_back_to_heading_not_anchor(self):
85
+ self.assertEqual(self.i["sections"][2]["title"], "Artikel 3")
86
+
87
+ def test_rows_have_no_html_anywhere(self):
88
+ law, arts, hits = L.make_rows("SN", dict(self.i, kind="amending"), URL, "t")
89
+ self.assertEqual(hits, [])
90
+ for r in [law] + arts:
91
+ self.assertFalse(G.has_raw_html(r), r["id"])
92
+
93
+
94
+ class GenericGate(unittest.TestCase):
95
+ def test_any_tag_is_caught(self):
96
+ for t in ('x <section data-anchor="1" data-level="1" title="A" id="x1" > y', "<wbr>", "</div>", "<o:p>",
97
+ 'Verordnung)">\nArtikel 2', "&lt;section id=\"x\"&gt;", '<a href="/v/1" title="A\nB">T'):
98
+ self.assertTrue(G.RAW_HTML.search(t), t)
99
+ for t in ("– y <ER/SIE>", "§ 1 a < b > c", "<Name, Vorname>", "Wert <5 mg", "Text [1]"):
100
+ self.assertFalse(G.RAW_HTML.search(t), t)
101
+
102
+ def test_metadata_is_scanned(self):
103
+ row = {"id": "a", "title": "Artikel 2", "text": "T", "metadata_json": json.dumps(
104
+ {"titel": "2 Änderung des <a href='x' data-name='FAG'>Finanzausgleichsgesetzes</a> 1994"})}
105
+ g = G.gate([], [row], {}, {})
106
+ self.assertFalse(g["ok"]); self.assertEqual(g["raw_html_article_rows"], 1)
107
+
108
+ def test_repeal_placeholders_are_not_heading_only(self):
109
+ row = {"id": "a", "title": "Artikel 7 (außer Kraft)", "text": "Artikel 7\n(außer Kraft)",
110
+ "metadata_json": json.dumps({"body_status": "repealed_placeholder"})}
111
+ g = G.gate([], [row], {}, {}, bodyless_check=True)
112
+ self.assertTrue(g["ok"], g); self.assertEqual(g["repealed_placeholder_rows"], 1)
113
+
114
+ def test_bodyless_check(self):
115
+ row = {"id": "a", "title": "Artikel 2 Änderung der X", "text": "Artikel 2\nÄnderung der X 1"}
116
+ self.assertTrue(G.gate([], [row], {}, {})["ok"])
117
+ self.assertFalse(G.gate([], [row], {}, {}, bodyless_check=True)["ok"])
118
+
119
+
120
+ def art(i, title, text):
121
+ return {"id": f"de-sn-9:{i}", "law_id": "de-sn-9", "title": title, "text": text,
122
+ "metadata_json": json.dumps({"doknr": i, "enbez": "Artikel", "titel": title})}
123
+
124
+
125
+ class Clean(unittest.TestCase):
126
+ def rec(self, arts):
127
+ return {"kind": "amending", "law": {"id": "de-sn-9", "title": "G", "text": "x" * 100, "article_count": len(arts),
128
+ "metadata_json": json.dumps({"metadata": {"kind": "amending"}})}, "articles": arts}
129
+
130
+ def test_empty_artikel_is_not_merged_into_next_artikel(self):
131
+ r, st = L.clean_record(self.rec([art("a1", "Artikel\xa01 Gesetz über X (XG)", "Artikel 1\nGesetz über X\n(XG)"),
132
+ art("a2", "Artikel\xa02 Änderung", "Artikel 2\nÄnderung\nIn § 1 wird ...")]))
133
+ self.assertEqual([a["id"] for a in r["articles"]], ["de-sn-9:a2"])
134
+ self.assertEqual(r["articles"][0]["text"], "Artikel 2\nÄnderung\nIn § 1 wird ...") # own text only
135
+ self.assertEqual(st["norm_headings_dropped"], ["de-sn-9:a1"]); self.assertEqual(st["headings_folded"], 0)
136
+
137
+ def test_artikel_heading_over_paragraphs_still_folds(self):
138
+ r, st = L.clean_record(self.rec([art("a1", "Artikel 1 Gesetz über X", "Artikel 1\nGesetz über X"),
139
+ art("p1", "§ 1 Zweck", "§ 1\nZweck\nDieses Gesetz ...")]))
140
+ self.assertEqual(st["folded_ids"], ["de-sn-9:a1"]); self.assertTrue(r["articles"][0]["text"].startswith("Artikel 1 Gesetz über X\n§ 1"))
141
+
142
+ def test_footnote_digit_row_and_attachment_stub_dropped(self):
143
+ r, st = L.clean_record(self.rec([art("a1", "Artikel 1 Änderung", "Artikel 1\nÄnderung\nText."),
144
+ art("a2", "Artikel\xa02 Änderung der OWi-ZuVO", "Artikel 2\nÄnderung der OWi-ZuVO 1"),
145
+ art("a3", "Artikel 3 Inkrafttreten", "Artikel 3\nInkrafttreten\nTritt in Kraft."),
146
+ art("x", "Anlagen", "Karte")]))
147
+ self.assertEqual(st["footnote_digit_rows_dropped"], ["de-sn-9:a2"]); self.assertEqual(st["attachment_stubs_dropped"], ["de-sn-9:x"])
148
+ self.assertEqual(r["law"]["article_count"], 2)
149
+
150
+ def test_repeal_placeholder_kept_tagged_digits_stripped(self):
151
+ r, st = L.clean_record(self.rec([art("a7", "Artikel\xa07 (außer Kraft)", "Artikel 7\n1\n(außer Kraft)"),
152
+ art("a8", "Artikel\xa02 (aufgehoben)", "Artikel 2\n(aufgehoben) 1"),
153
+ art("a9", "Artikel 9 Inkrafttreten", "Artikel 9\nInkrafttreten\nTritt in Kraft.")]))
154
+ a7, a8 = r["articles"][0], r["articles"][1]
155
+ self.assertEqual(a7["text"], "Artikel 7\n(außer Kraft)"); self.assertEqual(a8["text"], "Artikel 2\n(aufgehoben)")
156
+ self.assertEqual(json.loads(a7["metadata_json"])["body_status"], "repealed_placeholder")
157
+ self.assertEqual(st["repealed_placeholders"], ["de-sn-9:a7", "de-sn-9:a8"])
158
+ self.assertTrue(G.gate([r["law"]], r["articles"], {}, {}, bodyless_check=True)["ok"])
159
+
160
+ def test_metadata_html_cleaned(self):
161
+ a = art("a2", "Artikel 2 Änderung", "Artikel 2\nÄnderung\nText.")
162
+ a["metadata_json"] = json.dumps({"titel": "2 Änderung des <a href='x' data-name='FAG' data-id='162'>Finanzausgleichsgesetzes</a> 1994"})
163
+ r, st = L.clean_record(self.rec([a]))
164
+ self.assertEqual(json.loads(r["articles"][0]["metadata_json"])["titel"], "2 Änderung des Finanzausgleichsgesetzes 1994")
165
+ self.assertEqual(st["metadata_html_cleaned"], 1); self.assertFalse(G.has_raw_html(r["articles"][0]))
166
+
167
+
168
+ class CacheReparse(unittest.TestCase):
169
+ def test_page_cached_and_reparsed_offline(self):
170
+ import collect_de_laender as C, refetch_de as R
171
+ lane = C.Lane("SN", {"amending"}, {"x"}, "rw")
172
+ lane.rec.mkdir(parents=True, exist_ok=True)
173
+ old = {"law": {"id": "de-sn-99", "source_url": URL, "retrieved_at": "2026-10-16T00:00:00Z"}, "articles": [], "kind": "amending",
174
+ "pii_hits": 3, "bounds": [], "tip_update": False}
175
+ (lane.rec / "de-sn-99.json").write_text(json.dumps(old))
176
+ lane.fetch = lambda s, url, kind: PAGE
177
+ page = lane.fetch_page(None, "99", URL)
178
+ self.assertTrue((C.PAGE_CACHE / "sn_rw" / "99.html.gz").exists())
179
+ self.assertEqual(gzip.open(C.PAGE_CACHE / "sn_rw" / "99.html.gz", "rt").read(), page)
180
+ self.assertFalse(str(C.PAGE_CACHE).startswith(str(C.BASE_WORK))) # outside the lane tree (gate cap)
181
+ self.assertEqual(R.main(["reparse", "--land", "SN", "--tag", "rw", "--ids", "99"]), 0)
182
+ r = json.loads((lane.rec / "de-sn-99.json").read_text())
183
+ self.assertEqual(r["pii_hits"], 0); self.assertEqual(r["kind"], "amending"); self.assertEqual(len(r["articles"]), 3)
184
+ self.assertTrue((lane.work / "records_prev" / "de-sn-99.json").exists())
185
+ self.assertEqual(R.main(["reparse", "--land", "SN", "--tag", "rw", "--ids", "100"]), 9)
186
+
187
+
188
+ @unittest.skipUnless((CODE / "pack_de.py").exists(), "DE bundle only")
189
+ class PackOutputs(unittest.TestCase):
190
+ def test_readme_counts_and_manifests(self):
191
+ import pyarrow as pa, pack_de as P
192
+ live = ("# X\n\n## Snapshot\n\n| Field | Value |\n| --- | --- |\n| Snapshot date | 2026-09-05 (federal) |\n"
193
+ "| Laws / instruments | 2 (federal 1 + Landesrecht 1) |\n| Articles | 2 (federal 1 + Landesrecht 1) |\n\n## Contents\n\n"
194
+ "- `manifests/fix_x_ids.jsonl` — old.\n\n## Old section\n\nkeep me\n")
195
+ laws = pa.Table.from_pylist([{"id": "f", "jurisdiction": "DE"}, {"id": "de-sn-1", "jurisdiction": "DE-SN"}, {"id": "de-sn-9", "jurisdiction": "DE-SN"}])
196
+ arts = pa.Table.from_pylist([{"id": "f:1", "law_id": "f"}, {"id": "de-sn-1:1", "law_id": "de-sn-1"}, {"id": "de-sn-9:a2", "law_id": "de-sn-9"}])
197
+ pack = TMP / "pk"; (pack / "manifests").mkdir(parents=True, exist_ok=True)
198
+ rec = {"law": {"id": "de-sn-9"}, "_clean": {"norm_headings_dropped": ["de-sn-9:a1"], "repealed_placeholders": []}}
199
+ rep = {"laws_old": 2, "articles_old": 2, "laws_added": 1, "articles_added": 1, "dropped": [{"id": "de-sn-1", "why": "id_on_tip"}],
200
+ "bounds_rejected": ["de-sn-5"], "not_added_duplicates_of_live_rows": {"total": 1, "by_reason": {"id_on_tip": 1}},
201
+ "manifest_prefix": "densify_sn_amending", "built_at": "2026-10-17T05:00:00-0700", "_pack": str(pack), "kinds": {"amending": 1}}
202
+ P.write_manifests(pack, "densify_sn_amending", laws, arts, rep, [rec], [{"law": {"id": "de-sn-5", "title": "Stub", "text": ""}, "bounds": ["text_too_short"]}])
203
+ man = [json.loads(x) for x in (pack / "manifests" / "densify_sn_amending_added_ids.jsonl").read_text().splitlines()]
204
+ self.assertEqual(man, [{"table": "laws", "id": "de-sn-9"}, {"table": "articles", "id": "de-sn-9:a2", "law_id": "de-sn-9"}])
205
+ gaps = [json.loads(x) for x in (pack / "manifests" / "densify_sn_amending_known_gaps.jsonl").read_text().splitlines()]
206
+ self.assertEqual(gaps[0]["id"], "de-sn-9:a1")
207
+ na = [json.loads(x) for x in (pack / "manifests" / "densify_sn_amending_not_added.jsonl").read_text().splitlines()]
208
+ self.assertEqual([x["reason"] for x in na], ["duplicate_of_live_row", "no_norm_text"])
209
+ rd = P.cumulative_readme(live, "SN", rep, laws, arts)
210
+ self.assertTrue(rd.startswith(live.split("| Snapshot")[0])); self.assertIn("keep me", rd)
211
+ self.assertEqual(P.readme_counts(rd), {"laws_total": 3, "laws_federal": 1, "articles_total": 3, "articles_federal": 1})
212
+ self.assertIn("duplicates of live rows", rd); self.assertIn("`de-sn-9:a1`", rd); self.assertIn("densify_sn_amending_added_ids.jsonl", rd)
213
+ self.assertIn("DE-SN amending acts 2026-10-17", rd)
214
+
215
+
216
+ class Respace(unittest.TestCase):
217
+ """de-sn-12867 / de-sn-19479: revosax drops a word break in one rendering of a heading only."""
218
+
219
+ def test_section_title_attribute_glue(self):
220
+ pg = ('<h1>Gesetz zur Änderung wasserrechtlicher Vorschriften</h1><article id="lesetext">'
221
+ '<section data-anchor="2" id="a1" title="Artikel 1 SächsischesWassergesetz (SächsWG)"><h4>Artikel 1\n<br>'
222
+ '<a href="/Text.link?stid=1" title="SächsWG">Sächsisches Wassergesetz\n<br>(SächsWG)</a></h4></section>'
223
+ '<section data-anchor="3" id="a2" title="Artikel 2 Inkrafttreten"><h4>Artikel 2<br>Inkrafttreten</h4>'
224
+ '<p>Dieses Gesetz tritt am Tag nach seiner Verkündung in Kraft.</p></section></article>')
225
+ r = L.parse_sn_page(pg, "https://www.revosax.sachsen.de/vorschrift/12867")
226
+ self.assertEqual(r["sections"][0]["title"], "Artikel 1 Sächsisches Wassergesetz (SächsWG)")
227
+
228
+ def test_eingangsformel_glue_and_hyphen_wrap(self):
229
+ pg = ('<h1 class="x">Sechste Verordnung zur Änderung der Infektionsschutzgesetz-\nZuständigkeitsverordnung</h1>'
230
+ '<p>Vollzitat: Sechste Verordnung zur Änderung der Infektionsschutzgesetz-\nZuständigkeitsverordnung vom 5. Januar 2022</p>'
231
+ '<article id="lesetext"><header data-anchor="1000" id="ef" title="Eingangsformel"><h3>Sechste Verordnung<br>'
232
+ 'zur Änderung derInfektionsschutzgesetz-Zuständigkeitsverordnung</h3><p><b>Vom 5. Januar 2022</b></p></header>'
233
+ '<section id="a1" title="Artikel 1 Inkrafttreten"><h4>Artikel 1<br>Inkrafttreten</h4><p>Diese Verordnung tritt in Kraft.</p>'
234
+ '</section></article>')
235
+ r = L.parse_sn_page(pg, "https://www.revosax.sachsen.de/vorschrift/19479")
236
+ self.assertEqual(r["title"], "Sechste Verordnung zur Änderung der Infektionsschutzgesetz-Zuständigkeitsverordnung")
237
+ self.assertEqual(r["short_title"], r["title"])
238
+ self.assertNotIn("derInfektion", r["text"])
239
+
240
+ def test_different_wording_untouched(self):
241
+ self.assertEqual(L._respace("Artikel\xa01 Foo", "Artikel 1 Bar"), "Artikel\xa01 Foo")
242
+ self.assertEqual(L._respace("Artikel\xa01 FooBar", "Artikel 1 Foo Bar"), "Artikel\xa01 Foo Bar")
243
+
244
+
245
+ class BodyReadTransient(unittest.TestCase):
246
+ def test_dropped_body_is_transient(self):
247
+ import collect_de_laender as C
248
+ import urllib3
249
+ src = Path(C.__file__).read_text()
250
+ self.assertIn("urllib3.exceptions.HTTPError", src)
251
+ self.assertTrue(issubclass(urllib3.exceptions.ProtocolError, urllib3.exceptions.HTTPError))
252
+
253
+
254
+ if __name__ == "__main__":
255
+ unittest.main()